Passed
Pull Request — master (#1958)
by
unknown
04:52
created

Standard::display()   C

Complexity

Conditions 16
Paths 93

Size

Total Lines 32
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 16
eloc 21
c 1
b 0
f 0
nc 93
nop 0
dl 0
loc 32
rs 5.5666

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
    /**
20
     * This file handles all actions on user alerts.
21
     *
22
     * It splits alerts into two types and they get different screens:
23
     *  * keyword alerts - a person wants an alert when a word or phrase is said
24
     *  * representative alerts - a person wants an alert when a representative speaks or votes
25
     *
26
     * There are several form variables that control what is displayed or what action is taken:
27
     * * action - this is used for things happening to alerts - creation/editing, deletion, suspension etc
28
     * * step - this determines which step of creating a keyword alert to display
29
     * * this_step - stores which step is currently being processed, also used for prev step button
30
     * * mp_step - show the representative alert screen
31
     * * results - stores the results of an action, used to display appropriate message
32
     *
33
     *  The steps in the keyword alert creation/editing process are:
34
     *  * define - Initial options where you can add a keyword, any exclusions plus select which chambers it applies to
35
     *  * add_vector_related - an optional related terms step which suggests extra terms if we find any in the database
36
     *  * review - a confirmation step
37
     *
38
     *  If the user is happy then they will click Confirm which will submit the form with action set to Confirm and the alert
39
     *  will be created or updated.
40
     *
41
     * If mp_step is one of the parameters set then the form to add a representative alert is displayed. This only has a creation
42
     * and a confirm step. As part of this the mp_search param will be submitted which will trigger checking detecting
43
     * which MP the user is trying to add. This will try the following steps:
44
     * * try to match the search text against a name
45
     * * check if the text contains a postcode and if so use that to look up the constituencies
46
     * * if there's not a postcode then try to match against a constituency name
47
     *
48
     * If there is more than one match then these are stored in the constituencies varaible and a choice is
49
     * presented to the user.
50
     *
51
     * The representive alert creation flow will also be entered if an alertsearch or pid parameter is submitted. This
52
     * is used for handling "create an alert when $rep speaks" links from elsewhere in the site (e.g. an MP page)
53
     *
54
     * Other actions such as suspend use a form with only an action value and the alert token if required.
55
     */
56
    public function display() {
57
        global $this_page;
58
        $this_page = "alert";
59
60
        $this->processAction();
61
        $this->getBasicData();
62
        $this->checkInput();
63
        $this->searchForConstituenciesAndMembers();
64
65
        if ($this->data['step'] || $this->data['addword']) {
66
            $this->processStep();
67
        } elseif (!$this->data['results'] == 'changes-abandoned' && !sizeof($this->data['errors']) && $this->data['submitted'] && ($this->data['keyword'] || $this->data['pid'])) {
68
            $this->addAlert();
69
        }
70
71
        $this->formatSearchTerms();
72
        $this->checkForCommonMistakes();
73
        $this->formatSearchMemberData();
74
75
        // Determine if we should fetch alert counts
76
        // We skip counts when in form workflows (step, mp_step, disambiguation)
77
        $in_active_workflow = $this->data['step'] ||           // Alert creation wizard steps
78
                             $this->data['mp_step'] ||         // MP alert creation
79
                             ($this->data['members'] && is_array($this->data['members']) && count($this->data['members']) > 0) || // Member disambiguation
80
                             (isset($this->data['constituencies']) && count($this->data['constituencies']) > 0) ||  // Constituency disambiguation
81
                             ($this->data['alertsearch'] && !$this->data['results']); // Search disambiguation (but not if showing results)
82
83
        $this->data['showing_main_alert_list'] = !$in_active_workflow;
84
85
        $this->setUserData();
86
87
        return $this->data;
88
    }
89
90
    # This only happens if we have an alert and want to do something to it.
91
    private function processAction() {
92
        $token = get_http_var('t');
93
        $alert = $this->alert->check_token($token);
94
95
        $this->data['results'] = false;
96
        if ($action = get_http_var('action')) {
97
            $success = true;
98
            if ($action == 'Confirm') {
99
                $success = $this->confirmAlert($token);
100
                if ($success) {
101
                    $this->data['results'] = 'alert-confirmed';
102
                    $this->data['criteria'] = $this->alert->criteria;
103
                    $this->data['display_criteria'] = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($this->alert->criteria, $this->alert->ignore_speaker_votes);
104
                }
105
            } elseif ($action == 'Suspend') {
106
                $success = $this->suspendAlert($token);
107
                if ($success) {
108
                    $this->data['results'] = 'alert-suspended';
109
                }
110
            } elseif ($action == 'Resume') {
111
                $success = $this->resumeAlert($token);
112
                if ($success) {
113
                    $this->data['results'] = 'alert-resumed';
114
                }
115
            } elseif ($action == 'Delete') {
116
                $success = $this->deleteAlert($token);
117
                if ($success) {
118
                    $this->data['results'] = 'alert-deleted';
119
                }
120
            } elseif ($action == 'Delete All') {
121
                $success = $this->deleteAllAlerts($token);
122
                if ($success) {
123
                    $this->data['results'] = 'all-alerts-deleted';
124
                }
125
            } elseif ($action == 'ignore-votes') {
126
                $success = $this->ignoreVotesAlert($token);
127
                if ($success) {
128
                    $this->data['criteria'] = $this->alert->criteria;
129
                    $display = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($this->alert->criteria, $this->alert->ignore_speaker_votes);
130
                    $this->data['display_criteria'] = str_replace('speaks', 'votes', $display);
131
                    $this->data['results'] = 'alert-ignore-votes';
132
                }
133
            } elseif ($action == 'include-votes') {
134
                $success = $this->includeVotesAlert($token);
135
                if ($success) {
136
                    $this->data['criteria'] = $this->alert->criteria;
137
                    $display = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($this->alert->criteria, $this->alert->ignore_speaker_votes);
138
                    $this->data['display_criteria'] = str_replace('speaks', 'votes', $display);
139
                    $this->data['results'] = 'alert-include-votes';
140
                }
141
            } elseif ($action == 'Abandon') {
142
                $this->data['results'] = 'changes-abandoned';
143
            }
144
            if (!$success) {
145
                $this->data['results'] = 'alert-fail';
146
            }
147
        }
148
149
        $this->data['alert'] = $alert;
150
    }
151
152
    # Process a screen in the alert creation wizard
153
    private function processStep() {
154
        # fetch a list of suggested terms. Need this for the define screen so we can filter out the suggested terms
155
        # and not show them if the user goes back
156
        if (($this->data['step'] == 'review' || $this->data['step'] == 'define') && !$this->data['shown_related']) {
157
            $suggestions = [];
158
            foreach ($this->data['keywords'] as $word) {
159
                $terms = $this->alert->get_related_terms($word);
160
                $terms = array_diff($terms, $this->data['keywords']);
161
                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...
162
                    $suggestions = array_merge($suggestions, $terms);
163
                }
164
            }
165
166
            if (count($suggestions) > 0) {
167
                $this->data['step'] = 'add_vector_related';
168
                $this->data['suggestions'] = $suggestions;
169
            }
170
            # confirm the alert. Handles both creating and editing alerts
171
        } elseif ($this->data['step'] == 'confirm') {
172
            $success = true;
173
            # if there's already an alert assume we are editing it and user must be logged in
174
            if ($this->data['alert']) {
175
                $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

175
                /** @scrutinizer ignore-call */ 
176
                $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...
176
                if ($success) {
177
                    # reset all the data to stop anything getting confused
178
                    $this->data['results'] = 'alert-confirmed';
179
                    $this->data['step'] = '';
180
                    $this->data['pid'] = '';
181
                    $this->data['alertsearch'] = '';
182
                    $this->data['pc'] = '';
183
                    $this->data['members'] = false;
184
                    $this->data['constituencies'] = [];
185
                    $this->data['member_constituencies'] = [];
186
                } else {
187
                    $this->data['results'] = 'alert-fail';
188
                    $this->data['step'] = 'review';
189
                }
190
            } else {
191
                $success = $this->addAlert();
0 ignored issues
show
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...
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
192
                $this->data['step'] = '';
193
            }
194
        }
195
    }
196
197
198
    /*
199
     * set up the data we will be using in processing later steps
200
     */
201
    private function getBasicData() {
202
        global $this_page;
203
204
        if ($this->user->loggedin()) {
205
            $this->data['email'] = $this->user->email();
206
            $this->data['email_verified'] = true;
207
        } elseif ($this->data['alert']) {
208
            $this->data['email'] = $this->data['alert']['email'];
209
            $this->data['email_verified'] = true;
210
        } else {
211
            $this->data["email"] = trim(get_http_var("email"));
212
            $this->data['email_verified'] = false;
213
        }
214
215
        $this->data['token'] = get_http_var('t');
216
        $this->data['step'] = trim(get_http_var("step"));
217
        $this->data['mp_step'] = trim(get_http_var("mp_step"));
218
        $this->data['addword'] = trim(get_http_var("addword"));
219
        $this->data['this_step'] = trim(get_http_var("this_step"));
220
        $this->data['shown_related'] = get_http_var('shown_related');
221
        $this->data['match_all'] = get_http_var('match_all') == 'on';
222
        $this->data['keyword'] = trim(get_http_var("keyword"));
223
        $this->data['search_section'] = '';
224
        $this->data['alertsearch'] = trim(get_http_var("alertsearch"));
225
        $this->data['mp_search'] = trim(get_http_var("mp_search"));
226
        $this->data['pid'] = trim(get_http_var("pid"));
227
        $this->data['pc'] = get_http_var('pc');
228
        $this->data['submitted'] = get_http_var('submitted') || $this->data['pid'] || $this->data['keyword'] || $this->data['step'];
229
        $this->data['ignore_speaker_votes'] = get_http_var('ignore_speaker_votes');
230
231
        if ($this->data['addword'] || $this->data['step']) {
232
            $alert = $this->alert->check_token($this->data['token']);
233
234
            $criteria = '';
235
            $alert_ignore_speaker_votes = 0;
236
            if ($alert) {
237
                $criteria = $alert['criteria'];
238
                $alert_ignore_speaker_votes = $alert['ignore_speaker_votes'];
239
            }
240
241
            $ignore_speaker_votes = get_http_var('ignore_speaker_votes', $alert_ignore_speaker_votes);
242
            $this->data['ignore_speaker_votes'] = ($ignore_speaker_votes == 'on' || $ignore_speaker_votes == 1);
243
244
            $this->data['alert'] = $alert;
245
246
            $this->data['alert_parts'] = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($criteria, $alert_ignore_speaker_votes, true);
247
248
            $existing_rep = '';
249
            if (isset($this->data['alert_parts']['spokenby'])) {
250
                $existing_rep = $this->data['alert_parts']['spokenby'][0];
251
            }
252
253
            $existing_section = '';
254
            if (count($this->data['alert_parts']['sections'])) {
255
                $existing_section = $this->data['alert_parts']['sections'][0];
256
            }
257
258
            # only want to load this the first time, otherwise we want to default to the form
259
            # value
260
            if (!$this->data['this_step'] && $this->data['alert_parts']['match_all']) {
261
                $this->data['match_all'] = false;
262
            }
263
264
            $words = get_http_var('words', $this->data['alert_parts']['words'], true);
265
266
            $this->data['words'] = [];
267
            $this->data['keywords'] = [];
268
            foreach ($words as $word) {
269
                if (trim($word) != '') {
270
                    $this->data['keywords'][] = $word;
271
                    $this->data['words'][] = $this->wrap_phrase_in_quotes($word);
272
                }
273
            }
274
275
            $add_all_related = get_http_var('add_all_related');
276
            $this->data['add_all_related'] = $add_all_related;
277
            $this->data['skip_keyword_terms'] = [];
278
279
            $selected_related_terms = get_http_var('selected_related_terms', [], true);
280
            $this->data['selected_related_terms'] = $selected_related_terms;
281
282
            if ($this->data['step'] !== 'define') {
283
                if ($add_all_related) {
284
                    $this->data['selected_related_terms'] = [];
285
                    $related_terms = get_http_var('related_terms', [], true);
286
                    foreach ($related_terms as $term) {
287
                        $this->data['skip_keyword_terms'][] = $term;
288
                        $this->data['keywords'][] = $term;
289
                        $this->data['words'][] = $this->wrap_phrase_in_quotes($term);
290
                    }
291
                } else {
292
                    $this->data['skip_keyword_terms'] = $selected_related_terms;
293
                    foreach ($selected_related_terms as $term) {
294
                        $this->data['keywords'][] = $term;
295
                        $this->data['words'][] = $this->wrap_phrase_in_quotes($term);
296
                    }
297
                }
298
            }
299
            $this->data['exclusions'] = trim(get_http_var("exclusions", implode(' ', $this->data['alert_parts']['exclusions'])));
300
            $this->data['representative'] = trim(get_http_var("representative", $existing_rep));
301
302
            $this->data['search_section'] = trim(get_http_var("search_section", $existing_section));
303
304
            $separator = ' OR ';
305
            if ($this->data['match_all']) {
306
                $separator = ' ';
307
            }
308
            $this->data['keyword'] = implode($separator, $this->data['words']);
309
            if ($this->data['exclusions']) {
310
                $this->data['keyword'] = '(' . $this->data['keyword'] . ') -' . implode(' -', explode(' ', $this->data["exclusions"]));
311
            }
312
313
            $this->data['results'] = '';
314
315
            $this->getSearchSections();
316
        } elseif ($this->data['mp_step'] == 'mp_alert') {
317
            $alert = $this->alert->check_token($this->data['token']);
318
            if ($alert) {
319
                $ignore_speaker_votes = get_http_var('ignore_speaker_votes', $alert['ignore_speaker_votes']);
320
                $this->data['ignore_speaker_votes'] = ($ignore_speaker_votes == 'on' || $ignore_speaker_votes == 1);
321
322
                $existing_rep = '';
323
                if (isset($alert['criteria'])) {
324
                    $alert_parts = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($alert['criteria'], $alert['ignore_speaker_votes'], true);
325
                    $existing_rep = $alert_parts['spokenby'][0];
326
                    $this->data['pid'] = $alert_parts['pid'];
327
                }
328
                $this->data['keyword'] = get_http_var('mp_search', $existing_rep);
329
            } else {
330
                $this->data['ignore_speaker_votes'] = get_http_var('ignore_speaker_votes');
331
            }
332
        }
333
334
        $this->data['sign'] = get_http_var('sign');
335
        $this->data['site'] = get_http_var('site');
336
        $this->data['message'] = '';
337
338
        $ACTIONURL = new \MySociety\TheyWorkForYou\Url($this_page);
339
        $ACTIONURL->reset();
340
        $this->data['actionurl'] = $ACTIONURL->generate();
341
342
    }
343
344
    private function wrap_phrase_in_quotes($phrase) {
345
        if (strpos($phrase, ' ') > 0) {
346
            $phrase = '"' . trim($phrase, '"') . '"';
347
        }
348
349
        return $phrase;
350
    }
351
352
    /*
353
     * Check if the current alert has returned any results recently
354
     */
355
    private function getRecentResults($text) {
356
        global $SEARCHENGINE;
357
        $today = date_create();
358
        $one_week_ago = date_create('7 days ago');
359
        $restriction = date_format($one_week_ago, 'd/m/Y') . '..' . date_format($today, 'd/m/Y');
360
        // Wrap the original query in parentheses and add the date restriction with AND
361
        $wrapped_query = '(' . $text . ') AND ' . $restriction;
362
        $last_week_count = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $last_week_count is dead and can be removed.
Loading history...
363
        $se = new \SEARCHENGINE($wrapped_query);
364
        $last_week_count = $se->run_count(0, 10);
365
        $se = new \SEARCHENGINE($text);
366
        $count = $se->run_count(0, 10, 'date');
367
        $last_mention = null;
368
        if ($count > 0) {
369
            $se->run_search(0, 1, 'date');
370
            $gid = $se->get_gids()[0];
371
372
            $q = ['gid_to' => $gid];
373
            do {
374
                $gid = $q['gid_to'];
375
                $q = $this->db->query("SELECT gid_to FROM gidredirect WHERE gid_from = :gid", [':gid' => $gid])->first();
376
            } while ($q);
377
378
            $q = $this->db->query("SELECT hansard.gid, hansard.hdate
379
            FROM hansard
380
            WHERE hansard.gid = :gid", [':gid' => $gid])->first();
381
382
            if ($q) {
383
                $last_mention_date = date_create($q['hdate']);
384
                $last_mention = date_format($last_mention_date, 'd M Y'); //$se->get_gids()[0];
385
            }
386
        }
387
        return [
388
            "last_mention" => $last_mention,
389
            "last_week_count" => $last_week_count,
390
            "all_time_count" => $count,
391
        ];
392
    }
393
394
    private function getSearchSections() {
395
        $this->data['sections'] = [];
396
        if ($this->data['search_section']) {
397
            foreach (explode(' ', $this->data['search_section']) as $section) {
398
                $this->data['sections'][] = \MySociety\TheyWorkForYou\Utility\Alert::sectionToTitle($section);
399
            }
400
        }
401
    }
402
403
    private function updateAlert($token) {
404
        $success = $this->alert->update($token, $this->data);
405
        return $success;
406
    }
407
408
    private function checkInput() {
409
        global $SEARCHENGINE;
410
411
        $errors = [];
412
413
        # these are the initial screens and so cannot have any errors as we've not submitted
414
        if (!$this->data['submitted'] || $this->data['step'] == 'define' || $this->data['mp_step'] == 'mp_alert') {
415
            $this->data['errors'] = $errors;
416
            return;
417
        }
418
419
        // Check each of the things the user has input.
420
        // If there is a problem with any of them, set an entry in the $errors array.
421
        // This will then be used to (a) indicate there were errors and (b) display
422
        // error messages when we show the form again.
423
424
        // Check email address is valid and unique.
425
        if (!$this->data['email']) {
426
            $errors["email"] = gettext("Please enter your email address");
427
        } elseif (!validate_email($this->data["email"])) {
428
            // validate_email() is in includes/utilities.php
429
            $errors["email"] = gettext("Please enter a valid email address");
430
        }
431
432
        if ($this->data['pid'] && !ctype_digit($this->data['pid'])) {
433
            $errors['pid'] = 'Invalid person ID passed';
434
        }
435
436
        $text = $this->data['alertsearch'];
437
        if ($this->data['mp_search']) {
438
            $text = $this->data['mp_search'];
439
        }
440
        if (!$text) {
441
            $text = $this->data['keyword'];
442
        }
443
444
        if ($this->data['submitted'] && !$this->data['pid'] && !$text) {
445
            $errors['alertsearch'] = gettext('Please enter what you want to be alerted about');
446
        }
447
448
        if (strpos($text, '..')) {
449
            $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!');
450
        }
451
452
        $se = new \SEARCHENGINE($text);
453
        if (!$se->valid) {
454
            $errors['alertsearch'] = sprintf(gettext('That search appears to be invalid - %s - please check and try again.'), $se->error);
455
        }
456
457
        if (strlen($text) > 255) {
458
            $errors['alertsearch'] = gettext('That search is too long for our database; please split it up into multiple smaller alerts.');
459
        }
460
461
        $this->data['errors'] = $errors;
462
    }
463
464
465
    private function searchForConstituenciesAndMembers() {
466
        if ($this->data['results'] == 'changes-abandoned') {
467
            $this->data['members'] = false;
468
            return;
469
        }
470
471
        $cons_sort = function ($a, $b) {
472
            if ($a['rep_name'] == $b['rep_name']) {
473
                if ($a['constituency'] == $b['constituency']) {
474
                    if ($a['member']->family_name == $b['member']->family_name) {
475
                        return 0;
476
                    }
477
                    return ($a['member']->family_name < $b['member']->family_name) ? -1 : 1;
478
                }
479
                return ($a['constituency'] < $b['constituency']) ? -1 : 1;
480
            }
481
482
            return ($a['rep_name'] < $b['rep_name']) ? -1 : 1;
483
        };
484
485
        $text = $this->data['alertsearch'];
486
        if ($this->data['mp_search']) {
487
            $text = $this->data['mp_search'];
488
        }
489
        $errors = [];
490
        if ($text != '') {
491
            //$members_from_pids = array_values(\MySociety\TheyWorkForYou\Utility\Search::membersForIDs($this->data['alertsearch']));
492
            $members_from_names = [];
493
            $names_from_pids = array_values(\MySociety\TheyWorkForYou\Utility\Search::speakerNamesForIDs($text));
494
            foreach ($names_from_pids as $name) {
495
                $members_from_names = array_merge($members_from_names, \MySociety\TheyWorkForYou\Utility\Search::searchMemberDbLookupWithNames($name));
496
            }
497
            $members_from_words = \MySociety\TheyWorkForYou\Utility\Search::searchMemberDbLookupWithNames($text, true);
498
            $this->data['members'] = array_merge($members_from_words, $members_from_names);
499
            [$this->data['constituencies'], $this->data['valid_postcode']] = \MySociety\TheyWorkForYou\Utility\Search::searchConstituenciesByQuery($text, false);
500
            # if there's no postcode match then constituencies will only have a list of names of westminster constituencies
501
            # so do a lookup using the member table to get members in all constituency types
502
            if (!$this->data['valid_postcode']) {
503
                $this->data['member_constituencies'] = \MySociety\TheyWorkForYou\Utility\Search::searchMembersByConstituency($text);
504
            }
505
            $member_count = count($this->data['members']);
506
            $cons_count = count($this->data['constituencies']);
507
            $mem_cons_count = isset($this->data['member_constituencies']) ? count($this->data['member_constituencies']) : 0;
508
            if (!$this->data['alertsearch'] && $member_count == 0 && $cons_count == 0 && $mem_cons_count == 0) {
509
                $errors["representative"] = gettext("No matching representative found");
510
            }
511
        } elseif ($this->data['pid']) {
512
            $MEMBER = new \MySociety\TheyWorkForYou\Member(['person_id' => $this->data['pid']]);
513
            $this->data['members'] = [[
514
                "person_id" => $MEMBER->person_id,
515
                "given_name" => $MEMBER->given_name,
516
                "family_name" => $MEMBER->family_name,
517
                "house" => $MEMBER->house_disp,
518
                "title" => $MEMBER->title,
519
                "lordofname" => $MEMBER->lordofname,
520
                "constituency" => $MEMBER->constituency,
521
            ]];
522
        } elseif (isset($this->data['representative']) && $this->data['representative'] != '') {
523
            $this->data['members'] = \MySociety\TheyWorkForYou\Utility\Search::searchMemberDbLookupWithNames($this->data['representative'], true);
524
525
            $member_count = count($this->data['members']);
526
            if ($member_count == 0) {
527
                $errors["representative"] = gettext("No matching representative found");
528
            } elseif ($member_count > 1) {
529
                $errors["representative"] = gettext("Multiple matching representatives found, please select one.");
530
            } else {
531
                $this->data['pid'] = $this->data['members'][0]['person_id'];
532
            }
533
        } else {
534
            $this->data['members'] = [];
535
        }
536
537
538
        /*
539
         * If member_constituncies is set then it implies there wasn't a postcode match and hence we will have
540
         * a list of members which we can turn into constituencies, otherwise we have a hash of constituency names
541
         * keyed by mapit type
542
         */
543
        if (isset($this->data['member_constituencies'])) {
544
            $cons = [];
545
            foreach ($this->data['member_constituencies'] as $pid) {
546
                try {
547
                    $MEMBER = new \MySociety\TheyWorkForYou\Member(['person_id' => $pid]);
548
                    $cons[] = [ 'member' => $MEMBER, 'constituency' => $MEMBER->constituency, 'rep_name' => $MEMBER->getMostRecentMembership()['rep_name'] ];
549
                } catch (\MySociety\TheyWorkForYou\MemberException $e) {
550
                    // do nothing
551
                }
552
            }
553
            uasort($cons, $cons_sort);
554
            $this->data['constituencies'] = $cons;
555
        } elseif (isset($this->data['constituencies'])) {
556
            $cons = [];
557
            foreach ($this->data['constituencies'] as $type => $constituency) {
558
                try {
559
                    $house = \MySociety\TheyWorkForYou\Utility\Postcode::mapitTypeToHouse($type);
560
                    // regional list reps for wales and scotland
561
                    if ($type == 'SPE' || $type == 'WAE') {
562
                        $db = new \ParlDB();
563
                        $q = $db->query("SELECT person_id FROM member WHERE constituency = :constituency AND house = :house and left_reason = 'still_in_office'", [':constituency' => $constituency, ':house' => $house]);
564
                        foreach ($q as $row) {
565
                            $MEMBER = new \MySociety\TheyWorkForYou\Member(['person_id' => $row['person_id'], 'house' => $house]);
566
                            $cons[] = [ 'member' => $MEMBER, 'constituency' => $constituency, 'rep_name' => $MEMBER->getMostRecentMembership()['rep_name'] ];
567
                        }
568
569
                    } else {
570
                        $MEMBER = new \MySociety\TheyWorkForYou\Member(['constituency' => $constituency, 'house' => $house]);
571
                        $cons[] = [ 'member' => $MEMBER, 'constituency' => $constituency ];
572
                    }
573
                } catch (\MySociety\TheyWorkForYou\MemberException $e) {
574
                    // do nothing
575
                }
576
            }
577
            uasort($cons, $cons_sort);
578
            $this->data['constituencies'] = $cons;
579
        }
580
581
582
        if ($this->data['alertsearch'] && !$this->data['mp_step'] && ($this->data['pid'] || $this->data['members'] || $this->data['constituencies'])) {
583
            $this->data['mp_step'] = 'mp_alert';
584
            $this->data['mp_search'] = $this->data['alertsearch'];
585
            $this->data['alertsearch'] = '';
586
        }
587
588
        if (count($this->data["errors"]) > 0) {
589
            $this->data["errors"] = array_merge($this->data["errors"], $errors);
590
        } else {
591
            $this->data["errors"] = $errors;
592
        }
593
    }
594
595
    private function addAlert() {
596
        $external_auth = auth_verify_with_shared_secret($this->data['email'], OPTION_AUTH_SHARED_SECRET, get_http_var('sign'));
597
        if ($external_auth) {
598
            $confirm = false;
599
        } elseif ($this->data['email_verified']) {
600
            $confirm = false;
601
        } else {
602
            $confirm = true;
603
        }
604
605
        // If this goes well, the alert will be added to the database and a confirmation email
606
        // will be sent to them.
607
        $success = $this->alert->add($this->data, $confirm);
608
609
        if ($success > 0 && !$confirm) {
610
            $this->data['step'] = '';
611
            $this->data['mp_step'] = '';
612
            $result = 'alert-added';
613
        } elseif ($success > 0) {
614
            $this->data['step'] = '';
615
            $this->data['mp_step'] = '';
616
            $result = 'alert-confirmation';
617
        } elseif ($success == -2) {
618
            // we need to make sure we know that the person attempting to sign up
619
            // for the alert has that email address to stop people trying to work
620
            // out what alerts they are signed up to
621
            if ($this->data['email_verified'] || ($this->user->loggedin && $this->user->email() == $this->data['email'])) {
622
                $result = 'alert-exists';
623
            } else {
624
                // don't throw an error message as that implies that they have already signed
625
                // up for the alert but instead pretend all is normal but send an email saying
626
                // that someone tried to sign them up for an existing alert
627
                $result = 'alert-already-signed';
628
                $this->alert->send_already_signedup_email($this->data);
629
            }
630
        } else {
631
            $result = 'alert-fail';
632
        }
633
634
        // don't need these anymore so get rid of them
635
        $this->data['keyword'] = '';
636
        $this->data['pid'] = '';
637
        $this->data['alertsearch'] = '';
638
        $this->data['pc'] = '';
639
640
        $this->data['results'] = $result;
641
        $this->data['criteria'] = $this->alert->criteria;
642
        $this->data['display_criteria'] = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($this->alert->criteria, $this->alert->ignore_speaker_votes);
643
    }
644
645
646
    private function formatSearchTerms() {
647
        if ($this->data['alertsearch']) {
648
            $this->data['alertsearch_pretty'] = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($this->data['alertsearch']);
649
            $this->data['search_text'] = $this->data['alertsearch'];
650
        } elseif ($this->data['mp_search']) {
651
            $this->data['search_text'] = $this->data['mp_search'];
652
        } else {
653
            $this->data['search_text'] = $this->data['keyword'];
654
        }
655
    }
656
657
    private function checkForCommonMistakes() {
658
        $mistakes = [];
659
        if (strstr($this->data['alertsearch'], ',') > -1) {
660
            $mistakes['multiple'] = 1;
661
        }
662
663
        if (
664
            preg_match('#([A-Z]{1,2}\d+[A-Z]? ?\d[A-Z]{2})#i', $this->data['alertsearch'], $m) &&
665
            strlen($this->data['alertsearch']) > strlen($m[1]) &&
666
            validate_postcode($m[1])
667
        ) {
668
            $this->data['postcode'] = $m[1];
669
            $mistakes['postcode_and'] = 1;
670
        }
671
672
        $this->data['mistakes'] = $mistakes;
673
    }
674
675
    private function formatSearchMemberData() {
676
        if (isset($this->data['postcode'])) {
677
            try {
678
                $postcode = $this->data['postcode'];
679
680
                $MEMBER = new \MySociety\TheyWorkForYou\Member(['postcode' => $postcode]);
681
                // move the postcode to the front just to be tidy
682
                $tidy_alertsearch = $postcode . " " . trim(str_replace("$postcode", "", $this->data['alertsearch']));
683
                $alertsearch_display = str_replace("$postcode ", "", $tidy_alertsearch);
684
685
                $this->data['member_alertsearch'] = str_replace("$postcode", "speaker:" . $MEMBER->person_id, $tidy_alertsearch);
686
                $this->data['member_displaysearch'] = $alertsearch_display;
687
                $this->data['member'] = $MEMBER;
688
689
                if (isset($this->data['mistakes']['postcode_and'])) {
690
                    $constituencies = \MySociety\TheyWorkForYou\Utility\Postcode::postcodeToConstituencies($postcode);
691
                    if (isset($constituencies['SPC'])) {
692
                        $MEMBER = new \MySociety\TheyWorkForYou\Member(['constituency' => $constituencies['SPC'], 'house' => HOUSE_TYPE_SCOTLAND]);
693
                        $this->data['scottish_alertsearch'] = str_replace("$postcode", "speaker:" . $MEMBER->person_id, $tidy_alertsearch);
694
                        $this->data['scottish_member'] = $MEMBER;
695
                    } elseif (isset($constituencies['WAC'])) {
696
                        $MEMBER = new \MySociety\TheyWorkForYou\Member(['constituency' => $constituencies['WAC'], 'house' => HOUSE_TYPE_WALES]);
697
                        $this->data['welsh_alertsearch'] = str_replace("$postcode", "speaker:" . $MEMBER->person_id, $tidy_alertsearch);
698
                        $this->data['welsh_member'] = $MEMBER;
699
                    }
700
                }
701
            } catch (\MySociety\TheyWorkForYou\MemberException $e) {
702
                $this->data['member_error'] = 1;
703
            }
704
        }
705
706
        if ($this->data['pid']) {
707
            $MEMBER = new \MySociety\TheyWorkForYou\Member(['person_id' => $this->data['pid']]);
708
            $this->data['pid_member'] = $MEMBER;
709
        }
710
711
        if ($this->data['keyword']) {
712
            $this->data['display_keyword'] = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($this->data['keyword']);
713
        }
714
    }
715
716
    /*
717
     * This makes sure that the $this->data makes sense once all the other steps have been completed
718
     */
719
    private function setUserData() {
720
        if (!isset($this->data['criteria'])) {
721
            $criteria = $this->data['keyword'];
722
            if ($criteria) {
723
                if (!$this->data['match_all']) {
724
                    $has_or = strpos($criteria, ' OR ') !== false;
725
                    $missing_braces = strpos($criteria, '(') === false;
726
727
                    if ($has_or && $missing_braces) {
728
                        $criteria = "($criteria)";
729
                    }
730
                }
731
                if ($this->data['search_section']) {
732
                    $criteria .= " section:" . $this->data['search_section'];
733
                }
734
                if ($this->data['pid']) {
735
                    $criteria .= " speaker:" . $this->data['pid'];
736
                }
737
                $this->data['search_results']  = $this->getRecentResults($criteria);
738
            }
739
740
            $this->data['criteria'] = $criteria;
741
            $this->data['display_criteria'] = \MySociety\TheyWorkForYou\Utility\Alert::prettifyCriteria($criteria);
742
        }
743
        if ($this->data['results'] == 'changes-abandoned') {
744
            $this->data['members'] = false;
745
            $this->data['alertsearch'] = '';
746
        }
747
748
        if ($this->data['alertsearch'] && !(isset($this->data['mistakes']['postcode_and']) || $this->data['members'] || $this->data['pid'] || $this->data['constituencies'])) {
749
            $this->data['step'] = 'define';
750
            $this->data['words'] = [$this->data['alertsearch']];
751
            $this->data['keywords'] = [$this->data['alertsearch']];
752
            $this->data['exclusions'] = '';
753
            $this->data['representative'] = '';
754
        } elseif ($this->data['alertsearch'] && ($this->data['members'] || $this->data['pid'])) {
755
            $this->data['mp_step'] = 'mp_alert';
756
            $this->data['mp_search'] = [$this->data['alertsearch']];
757
        } elseif ($this->data['members'] && $this->data['mp_step'] == 'mp_search' && count($this->data['errors']) == 0) {
758
            $this->data['mp_step'] = '';
759
        }
760
761
        $this->data['current_mp'] = false;
762
        $this->data['alerts'] = [];
763
        $this->data['keyword_alerts'] = [];
764
        $this->data['speaker_alerts'] = [];
765
        $this->data['spoken_alerts'] = [];
766
        $this->data['own_member_alerts'] = [];
767
        $this->data['all_keywords'] = [];
768
        $this->data['own_mp_criteria'] = '';
769
        $own_mp_criteria = '';
770
771
        if ($this->data['email_verified']) {
772
            if ($this->user->postcode()) {
773
                $current_mp = new \MySociety\TheyWorkForYou\Member(['postcode' => $this->user->postcode()]);
774
                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...
775
                    $this->data['current_mp'] = $current_mp;
776
                    $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...
777
                }
778
                $own_mp_criteria = $current_mp->full_name();
779
                $this->data['own_mp_criteria'] = $own_mp_criteria;
780
            }
781
            $this->data['alerts'] = \MySociety\TheyWorkForYou\Utility\Alert::forUser($this->data['email']);
782
            foreach ($this->data['alerts'] as $alert) {
783
                if (array_key_exists('spokenby', $alert) and sizeof($alert['spokenby']) == 1 and $alert['spokenby'][0] == $own_mp_criteria) {
784
                    $this->data['own_member_alerts'][] = $alert;
785
                } elseif (array_key_exists('spokenby', $alert)) {
786
                    if (!array_key_exists($alert['spokenby'][0], $this->data['spoken_alerts'])) {
787
                        $this->data['spoken_alerts'][$alert['spokenby'][0]] = [];
788
                    }
789
                    $this->data['spoken_alerts'][$alert['spokenby'][0]][] = $alert;
790
                }
791
            }
792
            foreach ($this->data['alerts'] as $alert) {
793
                $term = implode(' ', $alert['words']);
794
                $add = true;
795
                if (array_key_exists('spokenby', $alert)) {
796
                    $add = false;
797
                } elseif (array_key_exists($term, $this->data['spoken_alerts'])) {
798
                    $add = false;
799
                    $this->data['all_keywords'][] = $term;
800
                    $this->data['spoken_alerts'][$term][] = $alert;
801
                } elseif ($term == $own_mp_criteria) {
802
                    $add = false;
803
                    $this->data['all_keywords'][] = $term;
804
                    $this->data['own_member_alerts'][] = $alert;
805
                } elseif (\MySociety\TheyWorkForYou\Utility\Search::searchMemberDbLookupWithNames($term, true)) {
806
                    if (!array_key_exists($term, $this->data['spoken_alerts'])) {
807
                        $this->data['spoken_alerts'][$term] = [];
808
                    }
809
                    $add = false;
810
                    # need to add this to make it consistent so the front end know where to get the name
811
                    $alert['spokenby'] = [$term];
812
                    $this->data['all_keywords'][] = $term;
813
                    $this->data['spoken_alerts'][$term][] = $alert;
814
                }
815
                if ($add) {
816
                    $this->data['all_keywords'][] = $term;
817
                    // Only fetch search results when displaying the main alert list
818
                    if ($this->data['showing_main_alert_list']) {
819
                        $alert['search_results'] = $this->getRecentResults($alert["raw"]);
820
                    }
821
                    $this->data['keyword_alerts'][] = $alert;
822
                }
823
            }
824
        } else {
825
            if ($this->data['alertsearch'] && $this->data['pc']) {
826
                $this->data['mp_step'] = 'mp_alert';
827
            }
828
        }
829
        if (count($this->data['alerts'])) {
830
            $this->data['delete_token'] = $this->data['alerts'][0]['token'];
831
        }
832
        if ($this->data['addword'] != '' || ($this->data['step'] && count($this->data['errors']) > 0)) {
833
            $this->data["step"] = get_http_var('this_step');
834
        } elseif ($this->data['mp_step'] && count($this->data['errors']) > 0) {
835
            $this->data["mp_step"] = 'mp_alert';
836
        } else {
837
            $this->data['this_step'] = '';
838
        }
839
840
        $this->data["search_term"] = $this->data['alertsearch'];
841
        if ($this->data['mp_search']) {
842
            $this->data["search_term"] = $this->data['mp_search'];
843
        }
844
    }
845
}
846