User::checkUpdateDetails()   F
last analyzed

Complexity

Conditions 29
Paths 1800

Size

Total Lines 116
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 870

Importance

Changes 0
Metric Value
cc 29
eloc 48
nc 1800
nop 1
dl 0
loc 116
ccs 0
cts 43
cp 0
crap 870
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * User Class
4
 *
5
 * @package TheyWorkForYou
6
 */
7
8
namespace MySociety\TheyWorkForYou;
9
10
/**
11
 * User
12
 */
13
14
function calculateOptinValue($optin_service, $optin_stream, $optin_org) {
15
    // combine three booleans into a single integer to store in the database
16
    // +1 = optin_service
17
    // +2 = optin_stream
18
    // +4 = optin_org
19
20
    $value = 0;
21
22
    $value += $optin_service ? 1 : 0;
23
    $value += $optin_stream ? 2 : 0;
24
    $value += $optin_org ? 4 : 0;
25
26
    return $value;
27
}
28
29
function extractOptinValues($value) {
30
    // convert an integer into three seperate optin values ('Yes', 'No')
31
    return [
32
        'optin_service' => ($value & 1) ? "Yes" : "No",
33
        'optin_stream' => ($value & 2) ? "Yes" : "No",
34
        'optin_org' => ($value & 4) ? "Yes" : "No",
35
    ];
36
}
37
38
class User {
39
    public function getUserDetails($user_id = false) {
40
        global $THEUSER;
41
42
        $user = $THEUSER;
43
        if ($user_id && $user_id != $THEUSER->user_id()) {
44
            $user = new \USER();
45
            $valid = $user->init($user_id);
46
47
            if (!$valid || !$user->confirmed || $user->deleted()) {
48
                return ['error' => 'User does not exist'];
49
            }
50
        }
51
52
        $data = [];
53
        $data['firstname'] = $user->firstname();
54
        $data['lastname'] = $user->lastname();
55
        $data['name'] = $user->firstname() . " " . $user->lastname();
56
        $data['url'] = $user->url();
57
        $data['email'] = $user->email();
58
        $optin_values = extractOptinValues($user->optin());
59
        $data['optin_service'] = $optin_values['optin_service'];
60
        $data['optin_stream'] = $optin_values['optin_stream'];
61
        $data['optin_org'] = $optin_values['optin_org'];
62
        $data['postcode']	= $user->postcode();
63
        $data['website']	= $user->url();
64
        $data['registrationtime']	= $user->registrationtime();
65
        $data['status'] = $user->status();
66
        $data["deleted"] = $user->deleted();
67
        $data["confirmed"] = $user->confirmed();
68
        $data["status"] = $user->status();
69
        $data["facebook_id"] = $user->facebook_id();
70
        $data['facebook_user'] = $user->facebook_user();
71
        $data['can_annotate'] = $user->can_annotate();
72
        $data['organisation'] = $user->organisation();
73
        return $data;
74
    }
75
76
    public function getUpdateDetails($this_page, $user) {
77
        $details = [];
78
79
        if ($user->facebook_user) {
80
            $details = $this->getUserDetails();
81
            $details["password"] = '';
82
        } else {
83
            $details["firstname"] = trim(get_http_var("firstname"));
84
            $details["lastname"] = trim(get_http_var("lastname"));
85
86
            $details["password"] = trim(get_http_var("password"));
87
            $details["password2"] = trim(get_http_var("password2"));
88
89
            $details["email"] = trim(get_http_var("em"));
90
91
            $details["url"] = trim(get_http_var("url"));
92
93
            $optin_service = get_http_var("optin_service") == "true" ? true : false;
94
            $optin_stream = get_http_var("optin_stream") == "true" ? true : false;
95
            $optin_org = get_http_var("optin_org") == "true" ? true : false;
96
97
            $details["optin"] = calculateOptinValue($optin_service, $optin_stream, $optin_org);
98
99
            if (get_http_var("remember") != "") {
100
                $remember = get_http_var("remember");
101
                $details["remember"] = $remember[0] == "true" ? true : false;
102
            }
103
104
            if ($details['url'] != '' && !preg_match('/^http/', $details['url'])) {
105
                $details['url'] = 'https://' . $details['url'];
106
            }
107
108
            # these are used when displaying user details
109
            $details['name'] = $details["firstname"] . " " . $details["lastname"];
110
            $details["website"] = $details["url"];
111
            $details['registrationtime'] = $user->registrationtime();
112
            $details['status'] = $user->status();
113
        }
114
115
        $details['mp_alert'] = get_http_var('mp_alert') == 'true' ? true : false;
116
        $details["postcode"] = trim(get_http_var("postcode"));
117
118
        if ($this_page == "otheruseredit") {
119
            $details["user_id"] = trim(get_http_var("u"));
120
            $details["status"] = trim(get_http_var("status"));
121
            $details["can_annotate"] = get_http_var("can_annotate") == "true" ? true : false;
122
            $details["organisation"] = trim(get_http_var("organisation"));
123
124
125
            if (get_http_var("deleted") != "") {
126
                $deleted = get_http_var("deleted");
127
                $details["deleted"] = $deleted[0] == "true" ? true : false;
128
            } else {
129
                $details['deleted'] = false;
130
            }
131
132
            if (get_http_var("confirmed") != "") {
133
                $confirmed = get_http_var("confirmed");
134
                $details["confirmed"] = $confirmed[0] == "true" ? true : false;
135
            } else {
136
                $details['confirmed'] = false;
137
            }
138
        }
139
140
        return $details;
141
    }
142
143
    public function checkUpdateDetails($details) {
144
        global $THEUSER, $this_page;
145
146
        $errors = [];
147
148
        // Check each of the things the user has input.
149
        // If there is a problem with any of them, set an entry in the $errors array.
150
        // This will then be used to (a) indicate there were errors and (b) display
151
        // error messages when we show the form again.
152
153
        // facebook user's can only change their postcode so skip all this
154
        if (!isset($details['facebook_user'])) {
155
            // Check first name.
156
            if ($details["firstname"] == "") {
157
                $errors["firstname"] = "Please enter a first name";
158
            }
159
160
            // They don't need a last name. In case Madonna joins.
161
162
            // Check email address is valid and unique.
163
            if ($this_page == "otheruseredit" || $this_page == 'userjoin' || $this_page == 'useredit') {
164
                if ($details["email"] == "") {
165
                    $errors["email"] = "Please enter an email address";
166
167
                } elseif (!validate_email($details["email"])) {
168
                    // validate_email() is in includes/utilities.php
169
                    $errors["email"] = "Please enter a valid email address";
170
171
                } else {
172
173
                    $USER = new \USER();
174
                    $id_of_user_with_this_addresss = $USER->email_exists($details["email"], true);
175
176
                    if ($this_page == "useredit" &&
177
                        get_http_var("u") == "" &&
178
                        $THEUSER->isloggedin()) {
179
                        // User is updating their own info.
180
                        // Check no one else has this email.
181
182
                        if ($id_of_user_with_this_addresss &&
183
                            $id_of_user_with_this_addresss != $THEUSER->user_id()) {
184
                            $errors["email"] = "Someone else has already joined with this email address";
185
                        }
186
187
                    } else {
188
                        // User is joining. Check no one is already here with this email.
189
                        if ($this_page == "userjoin" && $id_of_user_with_this_addresss) {
190
                            $errors["email"] = "There is already a user with this email address";
191
                        }
192
                    }
193
                }
194
            }
195
196
            // Check passwords.
197
            if ($this_page == "userjoin") {
198
199
                // Only *must* enter a password if they're joining.
200
                if ($details["password"] == "") {
201
                    $errors["password"] = gettext("Please enter a password");
202
203
                } elseif (strlen($details["password"]) < 6) {
204
                    $errors["password"] = gettext("Please enter at least six characters");
205
                }
206
207
                if ($details["password2"] == "") {
208
                    $errors["password2"] = gettext("Please enter a password again");
209
                }
210
211
                if ($details["password"] != "" && $details["password2"] != "" && $details["password"] != $details["password2"]) {
212
                    $errors["password"] = gettext("The passwords did not match. Please try again.");
213
                }
214
215
            } else {
216
217
                // Update details pages.
218
219
                if ($details["password"] != "" && strlen($details["password"]) < 6) {
220
                    $errors["password"] = gettext("Please enter at least six characters");
221
                }
222
223
                if ($details["password"] != $details["password2"]) {
224
                    $errors["password"] = gettext("The passwords did not match. Please try again.");
225
                }
226
            }
227
        }
228
229
        // Check postcode (which is not a compulsory field).
230
        if ($details["postcode"] != "") {
231
            if (!validate_postcode($details["postcode"])) {
232
                $errors["postcode"] = gettext("Sorry, this isn't a valid UK postcode.");
233
            } else {
234
                try {
235
                    new \MySociety\TheyWorkForYou\Member([
236
                        'postcode' => $details['postcode'],
237
                        'house' => HOUSE_TYPE_COMMONS,
238
                    ]);
239
                } catch (MemberException $e) {
240
                    $errors["postcode"] = gettext("Sorry, we could not find an MP for that postcode.");
241
                }
242
            }
243
        }
244
245
        // No checking of URL.
246
247
248
        if ($this_page == "otheruseredit") {
249
250
            // We're editing another user's info.
251
252
            // Could check status here...?
253
254
255
        }
256
257
        // Send the array of any errors back...
258
        return $errors;
259
    }
260
261
    public function update($details) {
262
        global $THEUSER, $this_page, $PAGE;
263
264
        $results = [];
265
        // There were no errors when the edit user form was submitted,
266
        // so make the changes in the DB.
267
268
        // Who are we updating? $THEUSER or someone else?
269
        if ($this_page == "otheruseredit") {
270
            $who = 'the user&rsquo;s';
271
            $success = $THEUSER->update_other_user($details);
272
        } else {
273
            $who = 'your';
274
            $success = $THEUSER->update_self($details);
275
        }
276
277
278
        if ($success) {
279
            // No errors, all updated, show results.
280
281
            if ($this_page == 'otheruseredit') {
282
                $this_page = "userview";
283
            } else {
284
                $this_page = "userviewself";
285
            }
286
287
            if ($details['email'] != $THEUSER->email()) {
288
                $results['email_changed'] = true;
289
            }
290
291
292
        } else {
293
            $results['errors'] = ["db" => "Sorry, we were unable to update $who details. Please <a href=\"mailto:" . str_replace('@', '&#64;', CONTACTEMAIL) . "\">let us know</a> what you were trying to change. Thanks."];
294
        }
295
296
        return $results;
297
    }
298
299
    public function add($details) {
300
        global $THEUSER, $PAGE, $this_page;
301
302
303
        // If this goes well, the user will have their data
304
        // added to the database and a confirmation email
305
        // will be sent to them.
306
        $success = $THEUSER->add($details);
307
308
        $errors = [];
309
310
        if (!$success) {
311
            $errors["db"] = "Sorry, we were unable to create an account for you. Please <a href=\"mailto:" . str_replace('@', '&#64;', CONTACTEMAIL) . "\">let us know</a>. Thanks.";
312 4
        }
313 4
314 4
        return $errors;
315 4
    }
316
317
    public function getRep($cons_type, $mp_house) {
318
        global $THEUSER;
319
        if (!$THEUSER->has_postcode()) {
320
            return [];
321
        }
322
323
        // User is logged in and has a postcode, or not logged in with a cookied postcode.
324
325
        // (We don't allow the user to search for a postcode if they
326
        // already have one set in their prefs.)
327
328
        // this is for people who have e.g. an English postcode looking at the
329
        // Scottish homepage
330
        try {
331
            $constituencies = \MySociety\TheyWorkForYou\Utility\Postcode::postcodeToConstituencies($THEUSER->postcode());
332
            if (isset($constituencies[$cons_type])) {
333
                $constituency = $constituencies[$cons_type];
334
                $MEMBER = new Member(['constituency' => $constituency, 'house' => $mp_house]);
335
            }
336
        } catch (MemberException $e) {
337
            return [];
338
        }
339
340
        if (isset($MEMBER) && $MEMBER->valid) {
341
            return $this->constructMPData($MEMBER, $THEUSER, $mp_house);
342
        }
343
344
        return [];
345
    }
346
347
    private function constructMPData($member, $user, $mp_house) {
348
        $mp_data = [];
349
        $mp_data['name'] = $member->full_name();
350
        $mp_data['party'] = $member->party();
351
        $mp_data['constituency'] = $member->constituency();
352
        $left_house = $member->left_house();
353
        $mp_data['former'] = '';
354
        if ($left_house[$mp_house]['date'] != '9999-12-31') {
355
            $mp_data['former'] = 'former';
356
        }
357
        $mp_data['postcode'] = $user->postcode();
358
        $mp_data['mp_url'] = $member->url();
359
        $mp_data['person_id'] = $member->person_id();
360
        $mp_data['change_url'] = $this->getPostCodeChangeURL();
361
362 2
        $image = $member->image();
363 2
        $mp_data['image'] = $image['url'];
364
365 2
        return $mp_data;
366 2
    }
367
368
    public function getRegionalReps($cons_type, $mp_house) {
369
        global $THEUSER;
370
371
        $mreg = [];
372
        if ($THEUSER->isloggedin() && $THEUSER->postcode() != '' || $THEUSER->postcode_is_set()) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($THEUSER->isloggedin() ...USER->postcode_is_set(), Probably Intended Meaning: $THEUSER->isloggedin() &...SER->postcode_is_set())
Loading history...
373
            $reps = \MySociety\TheyWorkForYou\Member::getRegionalList($THEUSER->postcode, $mp_house, $cons_type);
374 2
            foreach ($reps as $rep) {
375
                $member = new \MySociety\TheyWorkForYou\Member(['person_id' => $rep['person_id']]);
376
                $mreg[$rep['person_id']] = $this->constructMPData($member, $THEUSER, $mp_house);
377
            }
378
        }
379
380
        return $mreg;
381
    }
382
383
    public function getPostCodeChangeURL() {
384
        global $THEUSER;
385
        $CHANGEURL = new Url('userchangepc');
386
        if ($THEUSER->isloggedin()) {
387
            $CHANGEURL = new Url('useredit');
388
        }
389
390
        return $CHANGEURL->generate();
391
    }
392
393
394
}
395