Failed Conditions
Pull Request — master (#1851)
by Struan
35:22
created

Standard::processAction()   C

Complexity

Conditions 14
Paths 25

Size

Total Lines 43
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 32
nc 25
nop 0
dl 0
loc 43
rs 6.2666
c 0
b 0
f 0

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