Failed Conditions
Pull Request — master (#1846)
by Struan
54:09 queued 22:02
created

Standard::setUserData()   F

Complexity

Conditions 40
Paths 4160

Size

Total Lines 116
Code Lines 88

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
cc 40
eloc 88
nc 4160
nop 0
dl 0
loc 116
rs 0
c 3
b 0
f 1

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
namespace MySociety\TheyWorkForYou\AlertView;
4
5
include_once '../../../www/includes/easyparliament/init.php';
6
include_once INCLUDESPATH . "easyparliament/member.php";
7
include_once INCLUDESPATH . "easyparliament/searchengine.php";
8
include_once INCLUDESPATH . '../../commonlib/phplib/auth.php';
9
include_once INCLUDESPATH . '../../commonlib/phplib/crosssell.php';
10
11
class Standard extends \MySociety\TheyWorkForYou\AlertView {
12
    public $data;
13
14
    public function __construct($THEUSER = null) {
15
        parent::__construct($THEUSER);
16
        $this->data = [];
17
    }
18
19
    public function display() {
20
        global $this_page;
21
        $this_page = "alert";
22
23
        $this->processAction();
24
        $this->getBasicData();
25
        $this->checkInput();
26
        $this->searchForConstituenciesAndMembers();
27
28
        if ($this->data['step'] || $this->data['addword']) {
29
            $this->processStep();
30
        } elseif (!$this->data['results'] == 'changes-abandoned' && !sizeof($this->data['errors']) && $this->data['submitted'] && ($this->data['keyword'] || $this->data['pid'])) {
31
            $this->addAlert();
32
        }
33
34
        $this->formatSearchTerms();
35
        $this->checkForCommonMistakes();
36
        $this->formatSearchMemberData();
37
        $this->setUserData();
38
39
        return $this->data;
40
    }
41
42
    # This only happens if we have an alert and want to do something to it.
43
    private function processAction() {
44
        $token = get_http_var('t');
45
        $alert = $this->alert->check_token($token);
46
47
        $this->data['results'] = false;
48
        if ($action = get_http_var('action')) {
49
            $success = true;
50
            if ($action == 'Confirm') {
51
                $success = $this->confirmAlert($token);
52
                if ($success) {
53
                    $this->data['results'] = 'alert-confirmed';
54
                    $this->data['criteria'] = $this->alert->criteria;
55
                    $this->data['display_criteria'] = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($this->alert->criteria);
56
                }
57
            } elseif ($action == 'Suspend') {
58
                $success = $this->suspendAlert($token);
59
                if ($success) {
60
                    $this->data['results'] = 'alert-suspended';
61
                }
62
            } elseif ($action == 'Resume') {
63
                $success = $this->resumeAlert($token);
64
                if ($success) {
65
                    $this->data['results'] = 'alert-resumed';
66
                }
67
            } elseif ($action == 'Delete') {
68
                $success = $this->deleteAlert($token);
69
                if ($success) {
70
                    $this->data['results'] = 'alert-deleted';
71
                }
72
            } elseif ($action == 'Delete All') {
73
                $success = $this->deleteAllAlerts($token);
74
                if ($success) {
75
                    $this->data['results'] = 'all-alerts-deleted';
76
                }
77
            } elseif ($action == 'Abandon') {
78
                $this->data['results'] = 'changes-abandoned';
79
            }
80
            if (!$success) {
81
                $this->data['results'] = 'alert-fail';
82
            }
83
        }
84
85
        $this->data['alert'] = $alert;
86
    }
87
88
    # Process a screen in the alert creation wizard
89
    private function processStep() {
90
        # fetch a list of suggested terms. Need this for the define screen so we can filter out the suggested terms
91
        # and not show them if the user goes back
92
        if (($this->data['step'] == 'review' || $this->data['step'] == 'define') && !$this->data['shown_related']) {
93
            $suggestions = [];
94
            foreach ($this->data['keywords'] as $word) {
95
                $terms = $this->alert->get_related_terms($word);
96
                $terms = array_diff($terms, $this->data['keywords']);
97
                if ($terms && count($terms)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $terms of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
98
                    $suggestions = array_merge($suggestions, $terms);
99
                }
100
            }
101
102
            if (count($suggestions) > 0) {
103
                $this->data['step'] = 'add_vector_related';
104
                $this->data['suggestions'] = $suggestions;
105
            }
106
        # confirm the alert. Handles both creating and editing alerts
107
        } elseif ($this->data['step'] == 'confirm') {
108
            $success = true;
109
            # if there's already an alert assume we are editing it and user must be logged in
110
            if ($this->data['alert']) {
111
                $success = $this->updateAlert($this->data['alert']['id'], $this->data);
0 ignored issues
show
Unused Code introduced by
The call to MySociety\TheyWorkForYou...Standard::updateAlert() has too many arguments starting with $this->data. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

111
                /** @scrutinizer ignore-call */ 
112
                $success = $this->updateAlert($this->data['alert']['id'], $this->data);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
112
                if ($success) {
113
                    # reset all the data to stop anything getting confused
114
                    $this->data['results'] = 'alert-confirmed';
115
                    $this->data['step'] = '';
116
                    $this->data['pid'] = '';
117
                    $this->data['alertsearch'] = '';
118
                    $this->data['pc'] = '';
119
                    $this->data['members'] = false;
120
                    $this->data['constituencies'] = [];
121
                } else {
122
                    $this->data['results'] = 'alert-fail';
123
                    $this->data['step'] = 'review';
124
                }
125
            } else {
126
                $success = $this->addAlert();
0 ignored issues
show
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
Bug introduced by
Are you sure the assignment to $success is correct as $this->addAlert() targeting MySociety\TheyWorkForYou...ew\Standard::addAlert() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
127
                $this->data['step'] = '';
128
            }
129
        }
130
    }
131
132
133
    private function getBasicData() {
134
        global $this_page;
135
136
        if ($this->user->loggedin()) {
137
            $this->data['email'] = $this->user->email();
138
            $this->data['email_verified'] = true;
139
        } elseif ($this->data['alert']) {
140
            $this->data['email'] = $this->data['alert']['email'];
141
            $this->data['email_verified'] = true;
142
        } else {
143
            $this->data["email"] = trim(get_http_var("email"));
144
            $this->data['email_verified'] = false;
145
        }
146
147
        $this->data['token'] = get_http_var('t');
148
        $this->data['step'] = trim(get_http_var("step"));
149
        $this->data['mp_step'] = trim(get_http_var("mp_step"));
150
        $this->data['addword'] = trim(get_http_var("addword"));
151
        $this->data['this_step'] = trim(get_http_var("this_step"));
152
        $this->data['shown_related'] = get_http_var('shown_related');
153
        $this->data['match_all'] = get_http_var('match_all') == 'on';
154
        $this->data['keyword'] = trim(get_http_var("keyword"));
155
        $this->data['search_section'] = '';
156
        $this->data['alertsearch'] = trim(get_http_var("alertsearch"));
157
        $this->data['mp_search'] = trim(get_http_var("mp_search"));
158
        $this->data['pid'] = trim(get_http_var("pid"));
159
        $this->data['pc'] = get_http_var('pc');
160
        $this->data['submitted'] = get_http_var('submitted') || $this->data['pid'] || $this->data['keyword'] || $this->data['step'];
161
162
        if ($this->data['addword'] || $this->data['step']) {
163
            $alert = $this->alert->check_token($this->data['token']);
164
165
            $criteria = '';
166
            if ($alert) {
167
                $criteria = $alert['criteria'];
168
            }
169
170
            $this->data['alert'] = $alert;
171
172
            $this->data['alert_parts'] = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($criteria, true);
173
174
            $existing_rep = '';
175
            if (isset($this->data['alert_parts']['spokenby'])) {
176
                $existing_rep = $this->data['alert_parts']['spokenby'][0];
177
            }
178
179
            $existing_section = '';
180
            if (count($this->data['alert_parts']['sections'])) {
181
                $existing_section = $this->data['alert_parts']['sections'][0];
182
            }
183
184
            if ($this->data['alert_parts']['match_all']) {
185
                $this->data['match_all'] = true;
186
            }
187
188
            $words = get_http_var('words', $this->data['alert_parts']['words'], true);
189
190
            $this->data['words'] = [];
191
            $this->data['keywords'] = [];
192
            foreach ($words as $word) {
193
                if (trim($word) != '') {
194
                    $this->data['keywords'][] = $word;
195
                    $this->data['words'][] = $this->wrap_phrase_in_quotes($word);
196
                }
197
            }
198
199
            $add_all_related = get_http_var('add_all_related');
200
            $this->data['add_all_related'] = $add_all_related;
201
            $this->data['skip_keyword_terms'] = [];
202
203
            $selected_related_terms = get_http_var('selected_related_terms', [], true);
204
            $this->data['selected_related_terms'] = $selected_related_terms;
205
206
            if ($this->data['step'] !== 'define') {
207
                if ($add_all_related) {
208
                    $this->data['selected_related_terms'] = [];
209
                    $related_terms = get_http_var('related_terms', [], true);
210
                    foreach ($related_terms as $term) {
211
                        $this->data['skip_keyword_terms'][] = $term;
212
                        $this->data['keywords'][] = $term;
213
                        $this->data['words'][] = $this->wrap_phrase_in_quotes($term);
214
                    }
215
                } else {
216
                    $this->data['skip_keyword_terms'] = $selected_related_terms;
217
                    foreach ($selected_related_terms as $term) {
218
                        $this->data['keywords'][] = $term;
219
                        $this->data['words'][] = $this->wrap_phrase_in_quotes($term);
220
                    }
221
                }
222
            }
223
            $this->data['exclusions'] = trim(get_http_var("exclusions", implode('', $this->data['alert_parts']['exclusions'])));
224
            $this->data['representative'] = trim(get_http_var("representative", $existing_rep));
225
226
            $this->data['search_section'] = trim(get_http_var("search_section", $existing_section));
227
228
            $separator = ' OR ';
229
            if ($this->data['match_all']) {
230
                $separator = ' ';
231
            }
232
            $this->data['keyword'] = implode($separator, $this->data['words']);
233
            if ($this->data['exclusions']) {
234
                $this->data['keyword'] = '(' . $this->data['keyword'] . ') -' . $this->data["exclusions"];
235
            }
236
237
            $this->data['results'] = '';
238
239
            $this->getSearchSections();
240
        } # XXX probably should do something here if $alertsearch is set
241
242
        $this->data['sign'] = get_http_var('sign');
243
        $this->data['site'] = get_http_var('site');
244
        $this->data['message'] = '';
245
246
        $ACTIONURL = new \MySociety\TheyWorkForYou\Url($this_page);
247
        $ACTIONURL->reset();
248
        $this->data['actionurl'] = $ACTIONURL->generate();
249
250
    }
251
252
    private function wrap_phrase_in_quotes($phrase) {
253
        if (strpos($phrase, ' ') > 0) {
254
            $phrase = '"' . trim($phrase, '"') . '"';
255
        }
256
257
        return $phrase;
258
    }
259
260
    private function getRecentResults($text) {
261
        global $SEARCHENGINE;
262
        $se = new \SEARCHENGINE($text);
263
        $this->data['search_result_count'] = $se->run_count(0, 10);
264
        $se->run_search(0, 1, 'date');
265
    }
266
267
    private function getSearchSections() {
268
        $this->data['sections'] = [];
269
        if ($this->data['search_section']) {
270
            foreach (explode(' ', $this->data['search_section']) as $section) {
271
                $this->data['sections'][] = \MySociety\TheyWorkForYou\Utility\Alert::sectionToTitle($section);
272
            }
273
        }
274
    }
275
276
    protected function updateAlert($token) {
277
        $success = $this->alert->update($token, $this->data);
278
        return $success;
279
    }
280
281
    protected function checkInput() {
282
        global $SEARCHENGINE;
283
284
        $errors = [];
285
286
        # these are the initial screens and so cannot have any errors as we've not submitted
287
        if (!$this->data['submitted'] || $this->data['step'] == 'define' || $this->data['mp_step'] == 'mp_alert') {
288
            $this->data['errors'] = $errors;
289
            return;
290
        }
291
292
        // Check each of the things the user has input.
293
        // If there is a problem with any of them, set an entry in the $errors array.
294
        // This will then be used to (a) indicate there were errors and (b) display
295
        // error messages when we show the form again.
296
297
        // Check email address is valid and unique.
298
        if (!$this->data['email']) {
299
            $errors["email"] = gettext("Please enter your email address");
300
        } elseif (!validate_email($this->data["email"])) {
301
            // validate_email() is in includes/utilities.php
302
            $errors["email"] = gettext("Please enter a valid email address");
303
        }
304
305
        if ($this->data['pid'] && !ctype_digit($this->data['pid'])) {
306
            $errors['pid'] = 'Invalid person ID passed';
307
        }
308
309
        $text = $this->data['alertsearch'];
310
        if ($this->data['mp_search']) {
311
            $text = $this->data['mp_search'];
312
        }
313
        if (!$text) {
314
            $text = $this->data['keyword'];
315
        }
316
317
        if ($this->data['submitted'] && !$this->data['pid'] && !$text) {
318
            $errors['alertsearch'] = gettext('Please enter what you want to be alerted about');
319
        }
320
321
        if (strpos($text, '..')) {
322
            $errors['alertsearch'] = gettext('You probably don&rsquo;t want a date range as part of your criteria, as you won&rsquo;t be alerted to anything new!');
323
        }
324
325
        $se = new \SEARCHENGINE($text);
326
        if (!$se->valid) {
327
            $errors['alertsearch'] = sprintf(gettext('That search appears to be invalid - %s - please check and try again.'), $se->error);
328
        }
329
330
        if (strlen($text) > 255) {
331
            $errors['alertsearch'] = gettext('That search is too long for our database; please split it up into multiple smaller alerts.');
332
        }
333
334
        $this->data['errors'] = $errors;
335
    }
336
337
    protected function searchForConstituenciesAndMembers() {
338
        if ($this->data['results'] == 'changes-abandoned') {
339
            $this->data['members'] = false;
340
            return;
341
        }
342
343
        $text = $this->data['alertsearch'];
344
        if ($this->data['mp_search']) {
345
            $text = $this->data['mp_search'];
346
        }
347
        $errors = [];
348
        if ($text != '') {
349
            //$members_from_pids = array_values(\MySociety\TheyWorkForYou\Utility\Search::membersForIDs($this->data['alertsearch']));
350
            $members_from_names = [];
351
            $names_from_pids = array_values(\MySociety\TheyWorkForYou\Utility\Search::speakerNamesForIDs($text));
352
            foreach ($names_from_pids as $name) {
353
                $members_from_names = array_merge($members_from_names,\MySociety\TheyWorkForYou\Utility\Search::searchMemberDbLookupWithNames($name));
354
            }
355
            $members_from_words = \MySociety\TheyWorkForYou\Utility\Search::searchMemberDbLookupWithNames($text, true);
356
            $this->data['members'] = array_merge($members_from_words, $members_from_names);
357
            [$this->data['constituencies'], $this->data['valid_postcode']] = \MySociety\TheyWorkForYou\Utility\Search::searchConstituenciesByQuery($text, false);
358
        } elseif ($this->data['pid']) {
359
            $MEMBER = new \MEMBER(['person_id' => $this->data['pid']]);
360
            $this->data['members'] = [[
361
                "person_id" => $MEMBER->person_id,
362
                "given_name" => $MEMBER->given_name,
363
                "family_name" => $MEMBER->family_name,
364
                "house" => $MEMBER->house_disp,
365
                "title" => $MEMBER->title,
366
                "lordofname" => $MEMBER->lordofname,
367
                "constituency" => $MEMBER->constituency,
368
            ]];
369
        } elseif (isset($this->data['representative']) && $this->data['representative'] != '') {
370
            $this->data['members'] = \MySociety\TheyWorkForYou\Utility\Search::searchMemberDbLookupWithNames($this->data['representative'], true);
371
372
            $member_count = count($this->data['members']);
373
            if ($member_count == 0) {
374
                $errors["representative"] = gettext("No matching representative found");
375
            } elseif ($member_count > 1) {
376
                $errors["representative"] = gettext("Multiple matching representatives found, please select one.");
377
            } else {
378
                $this->data['pid'] = $this->data['members'][0]['person_id'];
379
            }
380
        } else {
381
            $this->data['members'] = [];
382
        }
383
384
        # If the above search returned one result for constituency
385
        # search by postcode, use it immediately
386
        if (isset($this->data['constituencies']) && count($this->data['constituencies']) == 1 && $this->data['valid_postcode']) {
387
            $MEMBER = new \MEMBER(['constituency' => array_values($this->data['constituencies'])[0], 'house' => 1]);
388
            $this->data['pid'] = $MEMBER->person_id();
389
            $this->data['pc'] = $text;
390
            unset($this->data['constituencies']);
391
        }
392
393
        if (isset($this->data['constituencies'])) {
394
            $cons = [];
395
            foreach ($this->data['constituencies'] as $constituency) {
396
                try {
397
                    $MEMBER = new \MEMBER(['constituency' => $constituency]);
398
                    $cons[$constituency] = $MEMBER;
399
                } catch (\MySociety\TheyWorkForYou\MemberException $e) {
400
                    // do nothing
401
                }
402
            }
403
            $this->data['constituencies'] = $cons;
404
            if (count($cons) == 1) {
405
                $cons = array_values($cons);
406
                $this->data['pid'] = $cons[0]->person_id();
407
            }
408
        }
409
410
        if ($this->data['alertsearch'] && !$this->data['mp_step'] && ($this->data['pid'] || $this->data['members'] || $this->data['constituencies'])) {
411
            if (count($this->data['members']) == 1) {
412
                $this->data['pid'] = $this->data['members'][0]['person_id'];
413
            }
414
            $this->data['mp_step'] = 'mp_alert';
415
            $this->data['mp_search'] = $this->data['alertsearch'];
416
            $this->data['alertsearch'] = '';
417
        }
418
419
        if (count($this->data["errors"]) > 0) {
420
            $this->data["errors"] = array_merge($this->data["errors"], $errors);
421
        } else {
422
            $this->data["errors"] = $errors;
423
        }
424
    }
425
426
    protected function addAlert() {
427
        $external_auth = auth_verify_with_shared_secret($this->data['email'], OPTION_AUTH_SHARED_SECRET, get_http_var('sign'));
428
        if ($external_auth) {
429
            $confirm = false;
430
        } elseif ($this->data['email_verified']) {
431
            $confirm = false;
432
        } else {
433
            $confirm = true;
434
        }
435
436
        // If this goes well, the alert will be added to the database and a confirmation email
437
        // will be sent to them.
438
        $success = $this->alert->add($this->data, $confirm);
439
440
        if ($success > 0 && !$confirm) {
441
            $this->data['step'] = '';
442
            $this->data['mp_step'] = '';
443
            $result = 'alert-added';
444
        } elseif ($success > 0) {
445
            $this->data['step'] = '';
446
            $this->data['mp_step'] = '';
447
            $result = 'alert-confirmation';
448
        } elseif ($success == -2) {
449
            // we need to make sure we know that the person attempting to sign up
450
            // for the alert has that email address to stop people trying to work
451
            // out what alerts they are signed up to
452
            if ($this->data['email_verified'] || ($this->user->loggedin && $this->user->email() == $this->data['email'])) {
453
                $result = 'alert-exists';
454
            } else {
455
                // don't throw an error message as that implies that they have already signed
456
                // up for the alert but instead pretend all is normal but send an email saying
457
                // that someone tried to sign them up for an existing alert
458
                $result = 'alert-already-signed';
459
                $this->alert->send_already_signedup_email($this->data);
460
            }
461
        } else {
462
            $result = 'alert-fail';
463
        }
464
465
        // don't need these anymore so get rid of them
466
        $this->data['keyword'] = '';
467
        $this->data['pid'] = '';
468
        $this->data['alertsearch'] = '';
469
        $this->data['pc'] = '';
470
471
        $this->data['results'] = $result;
472
        $this->data['criteria'] = $this->alert->criteria;
473
        $this->data['display_criteria'] = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($this->alert->criteria);
474
    }
475
476
477
    protected function formatSearchTerms() {
478
        if ($this->data['alertsearch']) {
479
            $this->data['alertsearch_pretty'] = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($this->data['alertsearch']);
480
            $this->data['search_text'] = $this->data['alertsearch'];
481
        } else {
482
            $this->data['search_text'] = $this->data['keyword'];
483
        }
484
    }
485
486
    protected function checkForCommonMistakes() {
487
        $mistakes = [];
488
        if (strstr($this->data['alertsearch'], ',') > -1) {
489
            $mistakes['multiple'] = 1;
490
        }
491
492
        if (
493
            preg_match('#([A-Z]{1,2}\d+[A-Z]? ?\d[A-Z]{2})#i', $this->data['alertsearch'], $m) &&
494
            strlen($this->data['alertsearch']) > strlen($m[1]) &&
495
            validate_postcode($m[1])
496
        ) {
497
            $this->data['postcode'] = $m[1];
498
            $mistakes['postcode_and'] = 1;
499
        }
500
501
        $this->data['mistakes'] = $mistakes;
502
    }
503
504
    protected function formatSearchMemberData() {
505
        if (isset($this->data['postcode'])) {
506
            try {
507
                $postcode = $this->data['postcode'];
508
509
                $MEMBER = new \MEMBER(['postcode' => $postcode]);
510
                // move the postcode to the front just to be tidy
511
                $tidy_alertsearch = $postcode . " " . trim(str_replace("$postcode", "", $this->data['alertsearch']));
512
                $alertsearch_display = str_replace("$postcode ", "", $tidy_alertsearch);
513
514
                $this->data['member_alertsearch'] = str_replace("$postcode", "speaker:" . $MEMBER->person_id, $tidy_alertsearch);
515
                $this->data['member_displaysearch'] = $alertsearch_display;
516
                $this->data['member'] = $MEMBER;
517
518
                if (isset($this->data['mistakes']['postcode_and'])) {
519
                    $constituencies = \MySociety\TheyWorkForYou\Utility\Postcode::postcodeToConstituencies($postcode);
520
                    if (isset($constituencies['SPC'])) {
521
                        $MEMBER = new \MEMBER(['constituency' => $constituencies['SPC'], 'house' => HOUSE_TYPE_SCOTLAND]);
522
                        $this->data['scottish_alertsearch'] = str_replace("$postcode", "speaker:" . $MEMBER->person_id, $tidy_alertsearch);
523
                        $this->data['scottish_member'] = $MEMBER;
524
                    } elseif (isset($constituencies['WAC'])) {
525
                        $MEMBER = new \MEMBER(['constituency' => $constituencies['WAC'], 'house' => HOUSE_TYPE_WALES]);
526
                        $this->data['welsh_alertsearch'] = str_replace("$postcode", "speaker:" . $MEMBER->person_id, $tidy_alertsearch);
527
                        $this->data['welsh_member'] = $MEMBER;
528
                    }
529
                }
530
            } catch (\MySociety\TheyWorkForYou\MemberException $e) {
531
                $this->data['member_error'] = 1;
532
            }
533
        }
534
535
        if ($this->data['pid']) {
536
            $MEMBER = new \MEMBER(['person_id' => $this->data['pid']]);
537
            $this->data['pid_member'] = $MEMBER;
538
        }
539
540
        if ($this->data['keyword']) {
541
            $this->data['display_keyword'] = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($this->data['keyword']);
542
        }
543
    }
544
545
    protected function setUserData() {
546
        if (!isset($this->data['criteria'])) {
547
            $criteria = $this->data['keyword'];
548
            if (!$this->data['match_all']) {
549
                $has_or = strpos($criteria, ' OR ') !== false;
550
                $missing_braces = strpos($criteria, '(') === false;
551
552
                if ($has_or && $missing_braces) {
553
                    $criteria = "($criteria)";
554
                }
555
            }
556
            if ($this->data['search_section']) {
557
                $criteria .= " section:" . $this->data['search_section'];
558
            }
559
            if ($this->data['pid']) {
560
                $criteria .= " speaker:" . $this->data['pid'];
561
            }
562
            $this->getRecentResults($criteria);
563
564
            $this->data['criteria'] = $criteria;
565
            $this->data['display_criteria'] = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($criteria);
566
        }
567
        if ($this->data['results'] == 'changes-abandoned') {
568
            $this->data['members'] = false;
569
            $this->data['alertsearch'] = '';
570
        }
571
572
        if ($this->data['alertsearch'] && !(isset($this->data['mistakes']['postcode_and']) || $this->data['members'] || $this->data['pid'])) {
573
            $this->data['step'] = 'define';
574
            $this->data['words'] = [$this->data['alertsearch']];
575
            $this->data['keywords'] = [$this->data['alertsearch']];
576
            $this->data['exclusions'] = '';
577
            $this->data['representative'] = '';
578
        } elseif ($this->data['alertsearch'] && ($this->data['members'] || $this->data['pid'])) {
579
            $this->data['mp_step'] = 'mp_alert';
580
            $this->data['mp_search'] = [$this->data['alertsearch']];
581
        } elseif ($this->data['members'] && $this->data['mp_step'] == 'mp_search') {
582
            $this->data['mp_step'] = '';
583
        }
584
585
        $this->data['current_mp'] = false;
586
        $this->data['alerts'] = [];
587
        $this->data['keyword_alerts'] = [];
588
        $this->data['speaker_alerts'] = [];
589
        $this->data['spoken_alerts'] = [];
590
        $this->data['own_member_alerts'] = [];
591
        $this->data['all_keywords'] = [];
592
        $this->data['own_mp_criteria'] = '';
593
        $own_mp_criteria = '';
594
595
        if ($this->data['email_verified']) {
596
            if ($this->user->postcode()) {
597
                $current_mp = new \MEMBER(['postcode' => $this->user->postcode()]);
598
                if ($current_mp_alert = !$this->alert->fetch_by_mp($this->data['email'], $current_mp->person_id())) {
0 ignored issues
show
Unused Code introduced by
The assignment to $current_mp_alert is dead and can be removed.
Loading history...
599
                    $this->data['current_mp'] = $current_mp;
600
                    $own_mp_criteria = sprintf('speaker:%s', $current_mp->person_id());
0 ignored issues
show
Unused Code introduced by
The assignment to $own_mp_criteria is dead and can be removed.
Loading history...
601
                }
602
                $own_mp_criteria = $current_mp->full_name();
603
                $this->data['own_mp_criteria'] = $own_mp_criteria;
604
            }
605
            $this->data['alerts'] = \MySociety\TheyWorkForYou\Utility\Alert::forUser($this->data['email']);
606
            foreach ($this->data['alerts'] as $alert) {
607
                if (array_key_exists('spokenby', $alert) and sizeof($alert['spokenby']) == 1 and $alert['spokenby'][0] == $own_mp_criteria) {
608
                    $this->data['own_member_alerts'][] = $alert;
609
                } elseif (array_key_exists('spokenby', $alert)) {
610
                    if (!array_key_exists($alert['spokenby'][0], $this->data['spoken_alerts'])) {
611
                        $this->data['spoken_alerts'][$alert['spokenby'][0]] = [];
612
                    }
613
                    $this->data['spoken_alerts'][$alert['spokenby'][0]][] = $alert;
614
                }
615
            }
616
            foreach ($this->data['alerts'] as $alert) {
617
                $term = implode(' ', $alert['words']);
618
                $add = true;
619
                if (array_key_exists('spokenby', $alert)) {
620
                    $add = false;
621
                } elseif (array_key_exists($term, $this->data['spoken_alerts'])) {
622
                    $add = false;
623
                    $this->data['all_keywords'][] = $term;
624
                    $this->data['spoken_alerts'][$term][] = $alert;
625
                } elseif ($term == $own_mp_criteria) {
626
                    $add = false;
627
                    $this->data['all_keywords'][] = $term;
628
                    $this->data['own_member_alerts'][] = $alert;
629
                } elseif (\MySociety\TheyWorkForYou\Utility\Search::searchMemberDbLookupWithNames($term, true)) {
630
                    if (!array_key_exists($term, $this->data['spoken_alerts'])) {
631
                        $this->data['spoken_alerts'][$term] = [];
632
                    }
633
                    $add = false;
634
                    # need to add this to make it consistent so the front end know where to get the name
635
                    $alert['spokenby'] = [$term];
636
                    $this->data['all_keywords'][] = $term;
637
                    $this->data['spoken_alerts'][$term][] = $alert;
638
                }
639
                if ($add) {
640
                    $this->data['all_keywords'][] = $term;
641
                    $this->data['keyword_alerts'][] = $alert;
642
                }
643
            }
644
        } else {
645
            if ($this->data['alertsearch'] && $this->data['pc']) {
646
                $this->data['mp_step'] = 'mp_alert';
647
            }
648
        }
649
        if (count($this->data['alerts'])) {
650
            $this->data['delete_token'] = $this->data['alerts'][0]['token'];
651
        }
652
        if ($this->data['addword'] != '' || ($this->data['step'] && count($this->data['errors']) > 0)) {
653
            $this->data["step"] = get_http_var('this_step');
654
        } else {
655
            $this->data['this_step'] = '';
656
        }
657
658
        $this->data["search_term"] = $this->data['alertsearch'];
659
        if ($this->data['mp_search']) {
660
            $this->data["search_term"] = $this->data['mp_search'];
661
        }
662
    }
663
}
664