Passed
Pull Request — master (#1868)
by
unknown
35:27
created

policy_image()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 42
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 28
nc 5
nop 3
dl 0
loc 42
rs 9.472
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * index.php
5
 *
6
 * For displaying info about a person for a postcode or constituency.
7
 *
8
 * This page accepts either 'm' (a member_id), 'pid' (a person_id),
9
 * 'c' (a postcode or constituency), or 'n' (a name).
10
 *
11
 * First, we check to see if a person_id's been submitted.
12
 * If so, we display that person.
13
 *
14
 * Else, we check to see if a member_id's been submitted.
15
 * If so, we display that person.
16
 *
17
 * Otherwise, we then check to see if a postcode's been submitted.
18
 * If it's valid we put it in a cookie.
19
 *
20
 * If no postcode, we check to see if a constituency's been submitted.
21
 *
22
 * If neither has been submitted, we see if either the user is logged in
23
 * and has a postcode set or the user has a cookied postcode from a previous
24
 * search.
25
 *
26
 * If we have a valid constituency after all this, we display its MP.
27
 *
28
 * Either way, we print the forms.
29
 */
30
31
// Disable the old PAGE class.
32
33
use MySociety\TheyWorkForYou\PolicyDistributionCollection;
34
use MySociety\TheyWorkForYou\PolicyComparisonPeriod;
35
36
$new_style_template = true;
37
38
// Include all the things this page needs.
39
include_once '../../includes/easyparliament/init.php';
40
include_once INCLUDESPATH . 'easyparliament/member.php';
41
include_once INCLUDESPATH . '../../commonlib/phplib/random.php';
42
include_once INCLUDESPATH . '../../commonlib/phplib/auth.php';
43
include_once '../api/api_getGeometry.php';
44
include_once '../api/api_getConstituencies.php';
45
46
// Ensure that page type is set
47
$allowed_page_types = ['divisions', 'votes', 'policy_set_svg', 'policy_set_png', 'recent', 'register', 'election_register'];
48
49
if (get_http_var('pagetype')) {
50
    $pagetype = get_http_var('pagetype');
51
} else {
52
    $pagetype = 'profile';
53
}
54
if (!in_array($pagetype, $allowed_page_types)) {
55
    $pagetype = 'profile';
56
}
57
if ($pagetype == 'profile') {
58
    $pagetype = '';
59
}
60
61
// list of years for which we have WTT response stats in
62
// reverse chronological order. Add new years here as we
63
// get them.
64
// NB: also need to update ./mpinfoin.pl to import the stats
65
$wtt_stats_years = [2015, 2014, 2013, 2008, 2007, 2006, 2005];
66
67
// Set the PID, name and constituency.
68
$pid = get_http_var('pid') != '' ? get_http_var('pid') : get_http_var('p');
69
$name = strtolower(str_replace('_', ' ', get_http_var('n')));
70
$constituency = strtolower(str_replace('_', ' ', get_http_var('c')));
71
72
// Fix for names with non-ASCII characters
73
if ($name == 'sion simon') {
74
    $name = 'si\xf4n simon';
75
}
76
if ($name == 'sian james') {
77
    $name = 'si\xe2n james';
78
}
79
if ($name == 'lembit opik') {
80
    $name = 'lembit \xf6pik';
81
}
82
if ($name == 'bairbre de brun') {
83
    $name = 'bairbre de br\xfan';
84
}
85
if ($name == 'daithi mckay') {
86
    $name = 'daith\xed mckay';
87
}
88
if ($name == 'caral ni chuilin') {
89
    $name = 'car\xe1l n\xed chuil\xedn';
90
}
91
if ($name == 'caledon du pre') {
92
    $name = 'caledon du pr\xe9';
93
}
94
if ($name == 'sean etchingham') {
95
    $name = 'se\xe1n etchingham';
96
}
97
if ($name == 'john tinne') {
98
    $name = 'john tinn\xe9';
99
}
100
if ($name == 'renee short') {
101
    $name = 'ren\xe9e short';
102
}
103
104
// Fix for common misspellings, name changes etc
105
$name_fix = [
106
    'a j beith' => 'alan beith',
107
    'micky brady' => 'mickey brady',
108
    'daniel rogerson' => 'dan rogerson',
109
    'andrew slaughter' => 'andy slaughter',
110
    'robert wilson' => ['rob wilson', 'reading east'],
111
    'james mcgovern' => 'jim mcgovern',
112
    'patrick mcfadden' => 'pat mcfadden',
113
    'chris leslie' => 'christopher leslie',
114
    'joseph meale' => 'alan meale',
115
    'james sheridan' => 'jim sheridan',
116
    'chinyelu onwurah' => 'chi onwurah',
117
    'steve rotherham' => 'steve rotheram',
118
    'michael weatherley' => 'mike weatherley',
119
    'louise bagshawe' => 'louise mensch',
120
    'andrew sawford' => 'andy sawford',
121
];
122
123
if (array_key_exists($name, $name_fix)) {
124
    if (is_array($name_fix[$name])) {
125
        if ($constituency == $name_fix[$name][1]) {
126
            $name = $name_fix[$name][0];
127
        }
128
    } else {
129
        $name = $name_fix[$name];
130
    }
131
}
132
133
// Fixes for Ynys Mon, and a Unicode URL
134
if ($constituency == 'ynys mon') {
135
    $constituency = "ynys m\xf4n";
136
}
137
if (preg_match("#^ynys m\xc3\xb4n#i", $constituency)) {
138
    $constituency = "ynys m\xf4n";
139
}
140
141
// If this is a request for recent appearances, redirect to search results
142
if (get_http_var('recent')) {
143
    if ($THEUSER->postcode_is_set() && !$pid) {
144
        $MEMBER = new MySociety\TheyWorkForYou\Member(['postcode' => $THEUSER->postcode(), 'house' => HOUSE_TYPE_COMMONS]);
145
        if ($MEMBER->person_id()) {
146
            $pid = $MEMBER->person_id();
147
        }
148
    }
149
    if ($pid) {
150
        $URL = new \MySociety\TheyWorkForYou\Url('search');
151
        $URL->insert(['pid' => $pid, 'pop' => 1]);
152
        header('Location: ' . $URL->generate('none'));
153
        exit;
154
    }
155
}
156
157
/////////////////////////////////////////////////////////
158
// DETERMINE TYPE OF REPRESENTITIVE
159
160
switch (get_http_var('representative_type')) {
161
    case 'peer':
162
        $this_page = 'peer';
163
        break;
164
    case 'royal':
165
        $this_page = 'royal';
166
        break;
167
    case 'mla':
168
        $this_page = 'mla';
169
        break;
170
    case 'msp':
171
        $this_page = 'msp';
172
        break;
173
    case 'ms':
174
        $this_page = 'ms';
175
        break;
176
    case 'london-assembly-member':
177
        $this_page = 'london-assembly-member';
178
        break;
179
    default:
180
        $this_page = 'mp';
181
        break;
182
}
183
184
try {
185
    if (is_numeric($pid)) {
186
        $MEMBER = get_person_by_id($pid);
187
    } elseif (is_numeric(get_http_var('m'))) {
188
        get_person_by_member_id(get_http_var('m'));
189
    } elseif (get_http_var('pc')) {
190
        get_person_by_postcode(get_http_var('pc'));
191
    } elseif ($name) {
192
        $MEMBER = get_person_by_name($name, $constituency);
193
    } elseif ($constituency) {
194
        get_mp_by_constituency($constituency);
195
    } elseif (($this_page == 'msp' || $this_page == 'mla' || $this_page == 'ms') && $THEUSER->postcode_is_set()) {
196
        get_regional_by_user_postcode($THEUSER->postcode(), $this_page);
197
        exit;
198
    } elseif ($THEUSER->postcode_is_set()) {
199
        get_mp_by_user_postcode($THEUSER->postcode());
200
    } else {
201
        twfy_debug('MP', "We don't have any way of telling what MP to display");
202
        throw new MySociety\TheyWorkForYou\MemberException(gettext('Sorry, but we can’t tell which representative to display.'));
203
    }
204
    if (!isset($MEMBER) || !$MEMBER->valid) {
205
        throw new MySociety\TheyWorkForYou\MemberException(gettext('You haven’t provided a way of identifying which representative you want'));
206
    }
207
} catch (MySociety\TheyWorkForYou\MemberMultipleException $e) {
208
    person_list_page($e->ids);
209
    exit;
210
} catch (MySociety\TheyWorkForYou\MemberException $e) {
211
    person_error_page($e->getMessage());
212
    exit;
213
}
214
215
# We have successfully looked up one person to show now.
216
217
if (!DEVSITE) {
218
    header('Cache-Control: max-age=900');
219
}
220
221
twfy_debug_timestamp("before load_extra_info");
222
$MEMBER->load_extra_info(true);
223
twfy_debug_timestamp("after load_extra_info");
224
225
// Basic name, title and description
226
$member_name = ucfirst($MEMBER->full_name());
227
$title = $member_name;
228
$desc = "Read $member_name's contributions to Parliament, including speeches and questions";
229
230
// Enhance description if this is a current member
231
if ($MEMBER->current_member_anywhere()) {
232
    $desc .= ', investigate their voting record, and get email alerts on their activity';
233
}
234
235
// Enhance title if this is a member of the Commons
236
if ($MEMBER->house(HOUSE_TYPE_COMMONS)) {
237
    if (!$MEMBER->current_member(1)) {
238
        $title .= ', former';
239
    }
240
    $title .= ' MP';
241
    if ($MEMBER->constituency()) {
242
        $title .= ', ' . $MEMBER->constituency();
243
    }
244
}
245
246
// Enhance title if this is a member of NIA
247
if ($MEMBER->house(HOUSE_TYPE_NI)) {
248
    if ($MEMBER->house(HOUSE_TYPE_COMMONS) || $MEMBER->house(HOUSE_TYPE_LORDS)) {
249
        $desc = str_replace('Parliament', 'Parliament and the Northern Ireland Assembly', $desc);
250
    } else {
251
        $desc = str_replace('Parliament', 'the Northern Ireland Assembly', $desc);
252
    }
253
    if (!$MEMBER->current_member(HOUSE_TYPE_NI)) {
254
        $title .= ', former';
255
    }
256
    $title .= ' MLA';
257
    if ($MEMBER->constituency()) {
258
        $title .= ', ' . $MEMBER->constituency();
259
    }
260
}
261
262
// Enhance title if this is a member of Scottish Parliament
263
if ($MEMBER->house(HOUSE_TYPE_SCOTLAND)) {
264
    if ($MEMBER->house(HOUSE_TYPE_COMMONS) || $MEMBER->house(HOUSE_TYPE_LORDS)) {
265
        $desc = str_replace('Parliament', 'the UK and Scottish Parliaments', $desc);
266
    } else {
267
        $desc = str_replace('Parliament', 'the Scottish Parliament', $desc);
268
    }
269
    $desc = str_replace(', and get email alerts on their activity', '', $desc);
270
    if (!$MEMBER->current_member(HOUSE_TYPE_SCOTLAND)) {
271
        $title .= ', former';
272
    }
273
    $title .= ' MSP, ' . $MEMBER->constituency();
274
}
275
276
// Enhance title if this is a member of Welsh Parliament
277
if ($MEMBER->house(HOUSE_TYPE_WALES)) {
278
    if ($MEMBER->house(HOUSE_TYPE_COMMONS) || $MEMBER->house(HOUSE_TYPE_LORDS)) {
279
        $desc = str_replace('Parliament', 'the UK and Welsh Parliaments', $desc);
280
    } else {
281
        $desc = str_replace('Parliament', 'the Senedd', $desc);
282
    }
283
    $desc = str_replace(', and get email alerts on their activity', '', $desc);
284
    if (!$MEMBER->current_member(HOUSE_TYPE_WALES)) {
285
        $title .= ', former';
286
    }
287
    $title .= ' MS, ' . $MEMBER->constituency();
288
}
289
290
$known_for = '';
291
$current_offices_ignoring_committees = $MEMBER->offices('current', true);
292
if (count($current_offices_ignoring_committees) > 0) {
293
    $known_for = $current_offices_ignoring_committees[0];
294
}
295
296
// Finally, if this is a Votes page, replace the page description with
297
// something more descriptive of the actual data on the page.
298
if ($pagetype == 'votes') {
299
    $title = "Voting record - " . $title;
300
    $desc = 'See how ' . $member_name . ' voted on topics like Employment, Social Issues, Foreign Policy, and more.';
301
}
302
303
// Set page metadata
304
$DATA->set_page_metadata($this_page, 'title', $title);
305
$DATA->set_page_metadata($this_page, 'meta_description', $desc);
306
307
// Build the RSS link and add it to page data.
308
$feedurl = $DATA->page_metadata('mp_rss', 'url') . $MEMBER->person_id() . '.rdf';
309
if (file_exists(BASEDIR . '/' . $feedurl)) {
310
    $DATA->set_page_metadata($this_page, 'rss', $feedurl);
311
}
312
313
// Prepare data for the template
314
$data["pagetype"] = $pagetype;
315
$data['full_name'] = $MEMBER->full_name();
316
$data['person_id'] = $MEMBER->person_id();
317
$data['member_id'] = $MEMBER->member_id();
318
319
$data['known_for'] = $known_for;
320
$data['latest_membership'] = $MEMBER->getMostRecentMembership();
321
322
$data['constituency'] = $MEMBER->constituency();
323
$data['party'] = $MEMBER->party_text();
324
$data['current_party_comparison'] = $MEMBER->currentPartyComparison();
325
$data['current_member_anywhere'] = $MEMBER->current_member_anywhere();
326
$data['current_member'] = $MEMBER->current_member();
327
$data['the_users_mp'] = $MEMBER->the_users_mp();
328
$data['user_postcode'] = $THEUSER->postcode;
329
$data['houses'] = $MEMBER->houses();
330
$data['member_url'] = $MEMBER->url();
331
$data['abs_member_url'] = $MEMBER->url(true);
332
// If there's photo attribution information, copy it into data
333
foreach (['photo_attribution_text', 'photo_attribution_link'] as $key) {
334
    if (isset($MEMBER->extra_info[$key])) {
335
        $data[$key] = $MEMBER->extra_info[$key];
336
    }
337
}
338
$data['profile_message'] = $MEMBER->extra_info['profile_message'] ?? '';
339
$data['image'] = $MEMBER->image();
340
$data['member_summary'] = person_summary_description($MEMBER);
341
$data['enter_leave'] = $MEMBER->getEnterLeaveStrings();
342
$data['entry_date'] = $MEMBER->getEntryDate(HOUSE_TYPE_COMMONS);
343
$data['leave_date'] = $MEMBER->getLeftDate(HOUSE_TYPE_COMMONS);
344
$data['is_new_mp'] = $MEMBER->isNew();
345
$data['other_parties'] = $MEMBER->getOtherPartiesString();
346
$data['other_constituencies'] = $MEMBER->getOtherConstituenciesString();
347
$data['rebellion_rate'] = person_rebellion_rate($MEMBER);
348
$data['recent_appearances'] = person_recent_appearances($MEMBER);
349
$data['useful_links'] = person_useful_links($MEMBER);
350
$data['social_links'] = person_social_links($MEMBER);
351
$data['topics_of_interest'] = person_topics($MEMBER);
352
$data['current_offices'] = $MEMBER->offices('current');
353
$data['previous_offices'] = $MEMBER->offices('previous');
354
$data['register_interests'] = person_register_interests($MEMBER, $MEMBER->extra_info);
355
$data['register_2024_enriched'] = person_register_interests_from_key('person_regmem_enriched2024_en', $MEMBER->extra_info);
356
$data['eu_stance'] = $MEMBER->getEUStance();
357
$data['standing_down_2024'] = $MEMBER->extra_info['standing_down_2024'] ?? '';
358
359
# People who are or were MPs and Lords potentially have voting records, except Sinn Fein MPs
360
$data['has_voting_record'] = (($MEMBER->house(HOUSE_TYPE_COMMONS) && $MEMBER->party() != 'Sinn Féin') || $MEMBER->house(HOUSE_TYPE_LORDS));
361
# Everyone who is currently somewhere has email alert signup, apart from current Sinn Fein MPs who are not MLAs
362
$data['has_email_alerts'] = ($MEMBER->current_member_anywhere() && !($MEMBER->current_member(HOUSE_TYPE_COMMONS) && $MEMBER->party() == 'Sinn Féin' && !$MEMBER->current_member(HOUSE_TYPE_NI)));
363
$data['has_expenses'] = $data['leave_date'] > '2004-01-01';
364
365
$data['pre_2010_expenses'] = false;
366
$data['post_2010_expenses'] = $data['leave_date'] > '2010-05-05' ? ($MEMBER->extra_info['datadotparl_id'] ?? '') : '';
367
368
if ($data['entry_date'] < '2010-05-05') {
369
    $data['pre_2010_expenses'] = true;
370
    // Set the expenses URL if we know it
371
    $data['expenses_url_2004'] = $MEMBER->extra_info['expenses_url'] ?? 'https://mpsallowances.parliament.uk/mpslordsandoffices/hocallowances/allowances%2Dby%2Dmp/';
372
}
373
374
$data['constituency_previous_mps'] = constituency_previous_mps($MEMBER);
375
$data['constituency_future_mps'] = constituency_future_mps($MEMBER);
376
$data['public_bill_committees'] = person_pbc_membership($MEMBER);
377
378
$data['this_page'] = $this_page;
379
$country = MySociety\TheyWorkForYou\Utility\House::getCountryDetails($data['latest_membership']['house']);
380
$data['current_assembly'] = $country[2];
381
382
$data['policy_last_update'] = MySociety\TheyWorkForYou\Divisions::getMostRecentDivisionDate();
383
384
$data['comparison_party'] = $MEMBER->cohortParty();
385
$data['unslugified_comparison_party'] = ucwords(str_replace('-', ' ', $data['comparison_party']));
386
387
// is the party we're comparing this MP to different from the party they're currently in?
388
$data['party_switcher'] = (slugify($data['current_party_comparison']) != slugify($data["comparison_party"]));
389
390
// Do any necessary extra work based on the page type, and send for rendering.
391
switch ($pagetype) {
392
393
    case 'votes':
394
        $policy_set = get_http_var('policy');
395
396
        $policiesList = new MySociety\TheyWorkForYou\Policies();
397
        $divisions = new MySociety\TheyWorkForYou\Divisions($MEMBER);
398
        // Generate voting segments
399
        $set_descriptions = $policiesList->getSetDescriptions();
400
        if ($policy_set && array_key_exists($policy_set, $set_descriptions)) {
401
            $sets = [$policy_set];
402
            $data['og_image'] = $MEMBER->url(true) . "/policy_set_png?policy_set=" . $policy_set;
403
            $data['page_title'] = $set_descriptions[$policy_set] . ' ' . $title . ' - TheyWorkForYou';
404
            $data['meta_description'] = 'See how ' . $data['full_name'] . ' voted on ' . $set_descriptions[$policy_set];
405
            $data['single_policy_page'] = true;
406
        } else {
407
            $data['single_policy_page'] = false;
408
            $sets = [
409
                'social', 'foreignpolicy', 'welfare', 'taxation', 'business',
410
                'health', 'education', 'reform', 'home', 'environment',
411
                'transport', 'housing', 'misc',
412
            ];
413
            shuffle($sets);
414
        }
415
        $house = HOUSE_TYPE_COMMONS;
416
        $party = new MySociety\TheyWorkForYou\Party($MEMBER->party());
417
        $voting_comparison_period_slug = get_http_var('comparison_period') ?: 'all_time';
418
        $voting_comparison_period = new PolicyComparisonPeriod($voting_comparison_period_slug, $house);
419
        $data["comparison_period"] = $voting_comparison_period;
420
        $data['available_periods'] = PolicyComparisonPeriod::getComparisonPeriodsForPerson($MEMBER->person_id(), $house);
421
        $data['key_votes_segments'] = PolicyDistributionCollection::getPersonDistributions($sets, $MEMBER->person_id(), $MEMBER->cohortParty(), $voting_comparison_period->slug, HOUSE_TYPE_COMMONS);
422
        // shuffle the key_votes_segments for a random order
423
        shuffle($data['key_votes_segments']);
424
        $data["sig_diff_policy"] = PolicyDistributionCollection::getSignificantDistributions($data['key_votes_segments']);
425
        $data['party_member_count'] = $party->getCurrentMemberCount($house);
426
427
        // Send the output for rendering
428
        MySociety\TheyWorkForYou\Renderer::output('mp/votes', $data);
429
430
        break;
431
432
    case 'recent':
433
        $divisions = new MySociety\TheyWorkForYou\Divisions($MEMBER);
434
        $data['divisions'] = $divisions->getRecentMemberDivisions();
435
        MySociety\TheyWorkForYou\Renderer::output('mp/recent', $data);
436
        break;
437
438
    case 'election_register':
439
        // Send the output for rendering
440
441
        $memcache = new \MySociety\TheyWorkForYou\Memcache();
442
        $mem_key = "highlighted_interests" . $MEMBER->person_id();
443
444
        $highlighted_for_this_mp = $memcache->get($mem_key);
445
446
        if (!$highlighted_for_this_mp) {
0 ignored issues
show
introduced by
The condition $highlighted_for_this_mp is always false.
Loading history...
447
            $highlighted_register = MySociety\TheyWorkForYou\DataClass\Regmem\Register::getMisc("highlighted_interests.json");
448
            $str_id = "uk.org.publicwhip/person/" . $MEMBER->person_id();
449
            $highlighted_for_this_mp = $highlighted_register->getPersonFromId($str_id);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $highlighted_for_this_mp is correct as $highlighted_register->getPersonFromId($str_id) targeting MySociety\TheyWorkForYou...ster::getPersonFromId() 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...
450
            $memcache->set($mem_key, $highlighted_for_this_mp, 60 * 60 * 24);
451
        }
452
453
        $data['mp_has_highlighted_interests'] = (bool) $highlighted_for_this_mp;
454
        $overlapping_interests = [];
455
456
        MySociety\TheyWorkForYou\Renderer::output('mp/election_register', $data);
457
458
        // no break
459
    case 'register':
460
        // Send the output for rendering
461
        MySociety\TheyWorkForYou\Renderer::output('mp/register', $data);
462
463
        // no break
464
    case '':
465
    default:
466
        // if extra detail needed for overview page in future
467
468
        // Send the output for rendering
469
        MySociety\TheyWorkForYou\Renderer::output('mp/profile', $data);
470
471
        break;
472
473
}
474
475
476
/////////////////////////////////////////////////////////
477
// SUPPORTING FUNCTIONS
478
479
/* Person lookup functions */
480
481
function get_person_by_id($pid) {
482
    global $pagetype, $this_page;
483
    $MEMBER = new MySociety\TheyWorkForYou\Member(['person_id' => $pid]);
484
    if (!$MEMBER->valid) {
485
        throw new MySociety\TheyWorkForYou\MemberException('Sorry, that ID number wasn&rsquo;t recognised.');
486
    }
487
    // Ensure that we're actually at the current, correct and canonical URL for the person. If not, redirect.
488
    // No need to worry about other URL syntax forms for vote pages, they shouldn't happen.
489
    $at = str_replace('/mp/', "/$this_page/", get_http_var('url'));
490
    $shouldbe = urldecode($MEMBER->url());
491
    if ($pagetype) {
492
        $shouldbe .= "/$pagetype";
493
    }
494
    if ($at !== $shouldbe) {
495
        member_redirect($MEMBER, 301, $pagetype);
496
    }
497
    return $MEMBER;
498
}
499
500
function get_person_by_member_id($member_id) {
501
    // Got a member id, redirect to the canonical MP page, with a person id.
502
    $MEMBER = new MySociety\TheyWorkForYou\Member(['member_id' => $member_id]);
503
    member_redirect($MEMBER);
504
}
505
506
function get_person_by_postcode($pc) {
507
    global $THEUSER;
508
    $pc = preg_replace('#[^a-z0-9]#i', '', $pc);
509
    if (!validate_postcode($pc)) {
510
        twfy_debug('MP', "Can't display an MP because the submitted postcode wasn't of a valid form.");
511
        throw new MySociety\TheyWorkForYou\MemberException(sprintf(gettext('Sorry, %s isn’t a valid postcode'), _htmlentities($pc)));
512
    }
513
    twfy_debug('MP', "MP lookup by postcode");
514
    $constituency = strtolower(MySociety\TheyWorkForYou\Utility\Postcode::postcodeToConstituency($pc));
515
    if ($constituency == "connection_timed_out") {
516
        throw new MySociety\TheyWorkForYou\MemberException(gettext('Sorry, we couldn’t check your postcode right now, as our postcode lookup server is under quite a lot of load.'));
517
    } elseif ($constituency == "") {
518
        twfy_debug('MP', "Can't display an MP, as submitted postcode didn't match a constituency");
519
        throw new MySociety\TheyWorkForYou\MemberException(sprintf(gettext('Sorry, %s isn’t a known postcode'), _htmlentities($pc)));
520
    } else {
521
        // Redirect to the canonical MP page, with a person id.
522
        $MEMBER = new MySociety\TheyWorkForYou\Member(['constituency' => $constituency, 'house' => HOUSE_TYPE_COMMONS]);
523
        if ($MEMBER->person_id()) {
524
            // This will cookie the postcode.
525
            $THEUSER->set_postcode_cookie($pc);
526
        }
527
        member_redirect($MEMBER, 302);
528
    }
529
}
530
531
function get_person_by_name($name, $const = '') {
532
    $MEMBER = new MySociety\TheyWorkForYou\Member(['name' => $name, 'constituency' => $const]);
533
    // Edge case, only attempt further detection if this isn't the Queen.
534
    if (($name !== 'elizabeth the second' && $name !== 'prince charles') || $const) {
535
        twfy_debug('MP', 'Redirecting for MP found by name/constituency');
536
        member_redirect($MEMBER);
537
    }
538
    return $MEMBER;
539
}
540
541
function get_mp_by_constituency($constituency) {
542
    $MEMBER = new MySociety\TheyWorkForYou\Member(['constituency' => $constituency, 'house' => HOUSE_TYPE_COMMONS]);
543
    member_redirect($MEMBER);
544
}
545
546
function get_regional_by_user_postcode($pc, $page) {
547
    global $this_page;
548
    $this_page = "your$page";
549
    $areas = \MySociety\TheyWorkForYou\Utility\Postcode::postcodeToConstituencies($pc);
550
    if ($page == 'msp' && isset($areas['SPC'])) {
551
        regional_list($pc, 'SPC', $page);
552
    } elseif ($page == 'ms' && isset($areas['WAC'])) {
553
        regional_list($pc, 'WAC', $page);
554
    } elseif ($page == 'mla' && isset($areas['NIE'])) {
555
        regional_list($pc, 'NIE', $page);
556
    } else {
557
        throw new MySociety\TheyWorkForYou\MemberException('Your set postcode is not in the right region.');
558
    }
559
}
560
561
function get_mp_by_user_postcode($pc) {
562
    $MEMBER = new MySociety\TheyWorkForYou\Member(['postcode' => $pc, 'house' => HOUSE_TYPE_COMMONS]);
563
    member_redirect($MEMBER, 302);
564
}
565
566
/**
567
 * Member Redirect
568
 *
569
 * Redirect to the canonical page for a member.
570
 */
571
572
function member_redirect(&$MEMBER, $code = 301, $pagetype = null) {
573
    // We come here after creating a MEMBER object by various methods.
574
    // Now we redirect to the canonical MP page, with a person_id.
575
    if ($MEMBER->person_id()) {
576
        $url = $MEMBER->url();
577
        $params = [];
578
        foreach ($_GET as $key => $value) {
579
            if (substr($key, 0, 4) == 'utm_' || $key == 'gclid') {
580
                $params[] = urlencode($key) . "=" . urlencode($value);
581
            }
582
        }
583
        if ($pagetype) {
584
            $url .= '/' . $pagetype;
585
        }
586
        if (count($params)) {
587
            $url .= '?' . join('&', $params);
588
        }
589
        header('Location: ' . $url, true, $code);
590
        exit;
591
    }
592
}
593
594
/* Error list page */
595
596
function person_list_page($ids) {
597
    global $name;
598
    if (!DEVSITE) {
599
        header('Cache-Control: max-age=900');
600
    }
601
    $data = ['mps' => []];
602
    foreach ($ids as $id => $constituency) {
603
        $data['mps'][] = [
604
            'url'  => WEBPATH . 'mp/?pid=' . $id,
605
            'name' => ucwords(strtolower($name)) . ', ' . $constituency,
606
        ];
607
    }
608
    $MPSURL = new \MySociety\TheyWorkForYou\Url('mps');
609
    $data['all_mps_url'] = $MPSURL->generate();
610
    MySociety\TheyWorkForYou\Renderer::output('mp/list', $data);
611
}
612
613
/* Error page */
614
615
function person_error_page($message) {
616
    global $this_page;
617
    $SEARCHURL = '';
618
    switch($this_page) {
619
        case 'peer':
620
            $people = new MySociety\TheyWorkForYou\People\Peers();
621
            $MPSURL = new \MySociety\TheyWorkForYou\Url('peers');
622
            break;
623
        case 'mla':
624
            $people = new MySociety\TheyWorkForYou\People\MLAs();
625
            $SEARCHURL = '/postcode/';
626
            $MPSURL = new \MySociety\TheyWorkForYou\Url('mlas');
627
            break;
628
        case 'msp':
629
            $people = new MySociety\TheyWorkForYou\People\MSPs();
630
            $SEARCHURL = '/postcode/';
631
            $MPSURL = new \MySociety\TheyWorkForYou\Url('msps');
632
            break;
633
        case 'ms':
634
            $people = new MySociety\TheyWorkForYou\People\MSs();
635
            $SEARCHURL = '/postcode/';
636
            $MPSURL = new \MySociety\TheyWorkForYou\Url('mss');
637
            break;
638
        case 'london-assembly-member':
639
            $people = new MySociety\TheyWorkForYou\People\LondonAssemblyMembers();
640
            $MPSURL = new \MySociety\TheyWorkForYou\Url('london-assembly-members');
641
            break;
642
        default:
643
            $people = new MySociety\TheyWorkForYou\People\MPs();
644
            $SEARCHURL = new \MySociety\TheyWorkForYou\Url('mp');
645
            $SEARCHURL = $SEARCHURL->generate();
646
            $MPSURL = new \MySociety\TheyWorkForYou\Url('mps');
647
    }
648
649
    $data = [
650
        'error' => $message,
651
        'rep_name' => $people->rep_name,
652
        'rep_name_plural' => $people->rep_plural,
653
        'all_mps_url' => $MPSURL->generate(),
654
        'rep_search_url' => $SEARCHURL,
655
    ];
656
    MySociety\TheyWorkForYou\Renderer::output('mp/error', $data);
657
}
658
659
/**
660
 * Person Positions Summary
661
 *
662
 * Generate the summary of this person's held positions.
663
 */
664
665
function person_summary_description($MEMBER) {
666
    $entered_house = $MEMBER->entered_house();
667
    $current_member = $MEMBER->current_member();
668
    $left_house = $MEMBER->left_house();
669
670
    if (in_array(HOUSE_TYPE_ROYAL, $MEMBER->houses())) {
671
        # Royal short-circuit
672
        if (substr($entered_house[HOUSE_TYPE_ROYAL]['date'], 0, 4) == 1952) {
673
            return '<strong>Acceded on ' . $entered_house[HOUSE_TYPE_ROYAL]['date_pretty']
674
                . '<br>Coronated on 2 June 1953</strong></li>';
675
        } else {
676
            return '';
677
        }
678
    }
679
    $desc = '';
680
    foreach ($MEMBER->houses() as $house) {
681
        if ($house == HOUSE_TYPE_COMMONS && isset($entered_house[HOUSE_TYPE_LORDS])) {
682
            # Same info is printed further down
683
            continue;
684
        }
685
686
        $party = $left_house[$house]['party'];
687
        $party_br = '';
688
        if (preg_match('#^(.*?)\s*\((.*?)\)$#', $party, $m)) {
689
            $party_br = " ($m[2])";
690
            $party = $m[1];
691
        }
692
        $pparty = $party != 'unknown' ? _htmlentities($party) : '';
693
694
        if ($house != HOUSE_TYPE_LORDS) {
695
            if ($house == HOUSE_TYPE_COMMONS) {
696
                $type = gettext('<abbr title="Member of Parliament">MP</abbr>');
697
            } elseif ($house == HOUSE_TYPE_NI) {
698
                $type = gettext('<abbr title="Member of the Legislative Assembly">MLA</abbr>');
699
            } elseif ($house == HOUSE_TYPE_SCOTLAND) {
700
                $type = gettext('<abbr title="Member of the Scottish Parliament">MSP</abbr>');
701
            } elseif ($house == HOUSE_TYPE_WALES) {
702
                $type = gettext('<abbr title="Member of the Senedd">MS</abbr>');
703
            } elseif ($house == HOUSE_TYPE_LONDON_ASSEMBLY) {
704
                $type = gettext('Member of the London Assembly');
705
            }
706
707
            if ($party == 'Speaker' || $party == 'Deputy Speaker') {
708
                # XXX: Might go horribly wrong if something odd happens
709
                if ($party == 'Deputy Speaker') {
710
                    $last = end($MEMBER->other_parties);
711
                    $oparty = $last['from'];
712
                } else {
713
                    $oparty = '';
714
                }
715
                if ($current_member[$house]) {
716
                    $line = sprintf(gettext('%s, and %s %s for %s'), $pparty, $oparty, $type, $left_house[$house]['constituency']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $type does not seem to be defined for all execution paths leading up to this point.
Loading history...
717
                } else {
718
                    $line = sprintf(gettext('Former %s, and %s %s for %s'), $pparty, $oparty, $type, $left_house[$house]['constituency']);
719
                }
720
            } elseif ($current_member[$house]) {
721
                $line = sprintf(gettext('%s %s %s for %s'), $pparty, $type, $party_br, $left_house[$house]['constituency']);
722
            } else {
723
                $line = sprintf(gettext('Former %s %s %s for %s'), $pparty, $type, $party_br, $left_house[$house]['constituency']);
724
            }
725
        } elseif ($house == HOUSE_TYPE_LORDS && $party != 'Bishop') {
726
            if ($current_member[$house]) {
727
                $line = sprintf(gettext('%s Peer'), $pparty);
728
            } else {
729
                $line = sprintf(gettext('Former %s Peer'), $pparty);
730
            }
731
        } else {
732
            if ($current_member[$house]) {
733
                $line = $pparty;
734
            } else {
735
                $line = sprintf(gettext('Former %s'), $pparty);
736
            }
737
        }
738
        $desc .= $line . ', ';
739
    }
740
    $desc = preg_replace('#, $#', '', $desc);
741
    return $desc;
742
}
743
744
/**
745
 * Person Rebellion Rate
746
 *
747
 * How often has this person rebelled against their party?
748
 *
749
 * @param MEMBER $member The member to calculate rebellion rate for.
750
 *
751
 * @return string A HTML summary of this person's rebellion rate.
752
 */
753
754
function person_rebellion_rate($member) {
755
756
    // Rebellion string may be empty.
757
    $rebellion_string = '';
758
759
    if (isset($member->extra_info['party_vote_alignment_last_year'])) {
760
761
        // unserialise the data from json
762
        $data = json_decode($member->extra_info['party_vote_alignment_last_year'], true);
763
        $total_votes = $data['total_votes'];
764
        $avg_diff_from_party = $data['avg_diff_from_party'];
765
766
        // as int %
767
        $avg_diff_str = number_format((1 - $avg_diff_from_party) * 100, 0) . '%';
768
769
        if ($total_votes == 0) {
770
            return '';
771
        }
772
        $votes_help_url = TWFY_VOTES_URL . "/help/about#voting-breakdowns-and-party-alignment";
0 ignored issues
show
Bug introduced by
The constant TWFY_VOTES_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
773
774
        $rebellion_string .= 'In the last year, ' . $member->full_name() . ' has an alignment score of ' . $avg_diff_str . ' with their party (over ' . $total_votes . ' votes).';
775
        $rebellion_string .= ' <small><a title="More about party alignment" href="' . $votes_help_url . '">Find out more</a>.</small>';
776
        return $rebellion_string;
777
    }
778
}
779
780
function person_recent_appearances($member) {
781
    global $DATA, $SEARCHENGINE, $this_page;
782
783
    $out = [];
784
    $out['appearances'] = [];
785
786
    //$this->block_start(array('id'=>'hansard', 'title'=>$title));
787
    // This is really far from ideal - I don't really want $PAGE to know
788
    // anything about HANSARDLIST / DEBATELIST / WRANSLIST.
789
    // But doing this any other way is going to be a lot more work for little
790
    // benefit unfortunately.
791
    twfy_debug_timestamp();
792
793
    $person_id = $member->person_id();
794
795
    $memcache = new MySociety\TheyWorkForYou\Memcache();
796
    $recent = $memcache->get("recent_appear:$person_id:" . LANGUAGE);
797
798
    if (!$recent) {
0 ignored issues
show
introduced by
The condition $recent is always false.
Loading history...
799
        // Initialise the search engine
800
        $searchstring = "speaker:$person_id";
801
        $SEARCHENGINE = new \SEARCHENGINE($searchstring);
802
803
        $hansard = new MySociety\TheyWorkForYou\Hansard();
804
        $args =  [
805
            's' => $searchstring,
806
            'p' => 1,
807
            'num' => 3,
808
            'pop' => 1,
809
            'o' => 'd',
810
        ];
811
        $results = $hansard->search($searchstring, $args);
812
        $recent = serialize($results['rows']);
813
        $memcache->set('recent_appear:' . $person_id, $recent);
814
    }
815
    $out['appearances'] = unserialize($recent);
816
    twfy_debug_timestamp();
817
818
    $MOREURL = new \MySociety\TheyWorkForYou\Url('search');
819
    $MOREURL->insert(['pid' => $person_id, 'pop' => 1]);
820
821
    $out['more_href'] = $MOREURL->generate() . '#n4';
822
    $out['more_text'] = sprintf(gettext('More of %s’s recent appearances'), ucfirst($member->full_name()));
823
824
    if ($rssurl = $DATA->page_metadata($this_page, 'rss')) {
825
        // If we set an RSS feed for this page.
826
        $HELPURL = new \MySociety\TheyWorkForYou\Url('help');
827
        $out['additional_links'] = '<a href="' . WEBPATH . $rssurl . '" title="XML version of this person&rsquo;s recent appearances">RSS feed</a> (<a href="' . $HELPURL->generate() . '#rss" title="An explanation of what RSS feeds are for">?</a>)';
828
    }
829
830
    return $out;
831
832
}
833
834
function person_useful_links($member) {
835
836
    $links = $member->extra_info();
837
838
    $out = [];
839
840
    if (isset($links['maiden_speech'])) {
841
        $maiden_speech = fix_gid_from_db($links['maiden_speech']);
842
        $out[] = [
843
            'href' => WEBPATH . 'debate/?id=' . $maiden_speech,
844
            'text' => 'Maiden speech',
845
        ];
846
    }
847
848
    // BIOGRAPHY.
849
    global $THEUSER;
850
    if (isset($links['mp_website'])) {
851
        $out[] = [
852
            'href' => $links['mp_website'],
853
            'text' => 'Personal website',
854
        ];
855
    }
856
857
    if (isset($links['sp_url'])) {
858
        $out[] = [
859
            'href' => $links['sp_url'],
860
            'text' => 'Page on the Scottish Parliament website',
861
        ];
862
    }
863
864
    if (isset($links['wikipedia_url'])) {
865
        $out[] = [
866
            'href' => $links['wikipedia_url'],
867
            'text' => 'Wikipedia page',
868
        ];
869
    }
870
871
    if (isset($links['bbc_profile_url'])) {
872
        $out[] = [
873
            'href' => $links['bbc_profile_url'],
874
            'text' => 'BBC News profile',
875
        ];
876
    }
877
878
    if (isset($links['diocese_url'])) {
879
        $out[] = [
880
            'href' => $links['diocese_url'],
881
            'text' => 'Diocese website',
882
        ];
883
    }
884
885
    return $out;
886
}
887
888
function person_social_links($member) {
889
890
    $links = $member->extra_info();
891
892
    $out = [];
893
894
895
    if (isset($links['bluesky_handle'])) {
896
        $out[] = [
897
            'href' => 'https://bsky.app/profile/' . _htmlentities($links['bluesky_handle']),
898
            'text' => '@' . _htmlentities($links['bluesky_handle']),
899
            'type' => 'bluesky',
900
        ];
901
    }
902
903
    if (isset($links['twitter_username'])) {
904
        $out[] = [
905
            'href' => 'https://twitter.com/' . _htmlentities($links['twitter_username']),
906
            'text' => '@' . _htmlentities($links['twitter_username']),
907
            'type' => 'twitter',
908
        ];
909
    }
910
911
    if (isset($links['facebook_page'])) {
912
        $out[] = [
913
            'href' => _htmlentities($links['facebook_page']),
914
            'text' => _htmlentities("Facebook"),
915
            'type' => 'facebook',
916
        ];
917
    }
918
919
    $official_keys = [
920
        'profile_url_uk_parl' => 'UK Parliament Profile',
921
        'profile_url_scot_parl' => 'Scottish Parliament Profile',
922
        'profile_url_ni_assembly' => 'Northern Ireland Assembly Profile',
923
    ];
924
925
    if (LANGUAGE == 'cy') {
0 ignored issues
show
introduced by
The condition LANGUAGE == 'cy' is always false.
Loading history...
926
        $official_keys['profile_url_senedd_cy'] = 'Proffil Senedd';
927
    } else {
928
        $official_keys['profile_url_senedd_en'] = 'Senedd Profile';
929
    }
930
931
    foreach ($official_keys as $key => $text) {
932
        if (isset($links[$key])) {
933
            $out[] = [
934
                'href' => $links[$key],
935
                'text' => $text,
936
                'type' => 'official',
937
            ];
938
        }
939
    }
940
941
    return $out;
942
}
943
944
function person_topics($member) {
945
    $out = [];
946
947
    $extra_info = $member->extra_info();
948
949
    if (isset($extra_info['wrans_departments'])) {
950
        $subjects = explode(',', $extra_info['wrans_departments']);
951
        $out = array_merge($out, $subjects);
952
    }
953
954
    if (isset($extra_info['wrans_subjects'])) {
955
        $subjects = explode(',', $extra_info['wrans_subjects']);
956
        $out = array_merge($out, $subjects);
957
    }
958
959
    return $out;
960
}
961
962
function constituency_previous_mps($member) {
963
    if ($member->house(HOUSE_TYPE_COMMONS)) {
964
        return $member->previous_mps();
965
    } else {
966
        return [];
967
    }
968
}
969
970
function constituency_future_mps($member) {
971
    if ($member->house(HOUSE_TYPE_COMMONS)) {
972
        return $member->future_mps();
973
    } else {
974
        return [];
975
    }
976
}
977
978
function person_pbc_membership($member) {
979
980
    $extra_info = $member->extra_info();
981
    $out = ['info' => '', 'data' => []];
982
983
    # Public Bill Committees
984
    if (count($extra_info['pbc'])) {
985
        if ($member->party() == 'Scottish National Party') {
986
            $out['info'] = 'SNP MPs only attend sittings where the legislation pertains to Scotland.';
987
        }
988
        foreach ($extra_info['pbc'] as $bill_id => $arr) {
989
            $text = '';
990
            if ($arr['chairman']) {
991
                $text .= 'Chairman, ';
992
            }
993
            $text .= $arr['title'] . ' Committee';
994
            $out['data'][] = [
995
                'href'      => '/pbc/' . $arr['session'] . '/' . urlencode($arr['title']),
996
                'text'      => $text,
997
                'attending' => $arr['attending'] . ' out of ' . $arr['outof'],
998
            ];
999
        }
1000
    }
1001
1002
    return $out;
1003
}
1004
1005
function person_register_interests_from_key($key, $extra_info): ?MySociety\TheyWorkForYou\DataClass\Regmem\Person {
1006
    $lang = LANGUAGE;
0 ignored issues
show
Unused Code introduced by
The assignment to $lang is dead and can be removed.
Loading history...
1007
    $reg = null;
1008
    if (isset($extra_info[$key])) {
1009
        $reg = MySociety\TheyWorkForYou\DataClass\Regmem\Person::fromJson($extra_info[$key]);
1010
    }
1011
    return $reg;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $reg could return the type MySociety\TheyWorkForYou\DataClass\BaseInterface which includes types incompatible with the type-hinted return MySociety\TheyWorkForYou...lass\Regmem\Person|null. Consider adding an additional type-check to rule them out.
Loading history...
1012
}
1013
1014
function person_register_interests($member, $extra_info) {
0 ignored issues
show
Unused Code introduced by
The parameter $member is not used and could be removed. ( Ignorable by Annotation )

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

1014
function person_register_interests(/** @scrutinizer ignore-unused */ $member, $extra_info) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1015
1016
    $valid_chambers = ['house-of-commons', 'scottish-parliament', 'northern-ireland-assembly', 'senedd'];
1017
1018
    $lang = LANGUAGE;
1019
1020
    $reg = ['chamber_registers' => [] ];
1021
1022
    foreach ($valid_chambers as $chamber) {
1023
        $key = 'person_regmem_' . $chamber . '_' . $lang;
1024
        $chamber_register = person_register_interests_from_key($key, $extra_info);
1025
        if ($chamber_register) {
1026
            $reg['chamber_registers'][$chamber] = $chamber_register;
1027
        }
1028
    }
1029
    // if chamber_registers is empty, we don't have any data
1030
    if (empty($reg['chamber_registers'])) {
1031
        return;
1032
    }
1033
1034
    // sort chamber registers by published_date
1035
    uasort($reg['chamber_registers'], function ($a, $b) {
1036
        return $a->published_date <=> $b->published_date;
1037
    });
1038
1039
    return $reg;
1040
}
1041
1042
function regional_list($pc, $area_type, $rep_type) {
1043
    $constituencies = MySociety\TheyWorkForYou\Utility\Postcode::postcodeToConstituencies($pc);
1044
    if ($constituencies == 'CONNECTION_TIMED_OUT') {
1045
        throw new MySociety\TheyWorkForYou\MemberException('Sorry, we couldn&rsquo;t check your postcode right now, as our postcode lookup server is under quite a lot of load.');
1046
    } elseif (!$constituencies) {
1047
        throw new MySociety\TheyWorkForYou\MemberException('Sorry, ' . htmlentities($pc) . ' isn&rsquo;t a known postcode');
1048
    } elseif (!isset($constituencies[$area_type])) {
1049
        throw new MySociety\TheyWorkForYou\MemberException(htmlentities($pc) . ' does not appear to be a valid postcode');
1050
    }
1051
    global $PAGE;
1052
    $a = array_values($constituencies);
0 ignored issues
show
Bug introduced by
It seems like $constituencies can also be of type string; however, parameter $array of array_values() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

1052
    $a = array_values(/** @scrutinizer ignore-type */ $constituencies);
Loading history...
1053
    $db = new ParlDB();
1054
    $query_base = "SELECT member.person_id, given_name, family_name, constituency, house
1055
        FROM member, person_names pn
1056
        WHERE constituency IN ('" . join("','", $a) . "')
1057
            AND member.person_id = pn.person_id AND pn.type = 'name'
1058
            AND pn.end_date = (SELECT MAX(end_date) FROM person_names WHERE person_names.person_id = member.person_id)";
1059
    $q = $db->query($query_base . " AND left_reason = 'still_in_office' AND house in (" . HOUSE_TYPE_NI . "," . HOUSE_TYPE_SCOTLAND . "," . HOUSE_TYPE_WALES . ")");
1060
    $current = true;
1061
    if (!$q->rows() && ($dissolution = MySociety\TheyWorkForYou\Dissolution::db())) {
1062
        $current = false;
1063
        $q = $db->query(
1064
            $query_base . " AND $dissolution[query]",
1065
            $dissolution['params']
1066
        );
1067
    }
1068
    $mcon = [];
1069
    $mreg = [];
1070
    foreach ($q as $row) {
1071
        $house = $row['house'];
1072
        $cons = $row['constituency'];
1073
        if ($house == HOUSE_TYPE_COMMONS) {
1074
            continue;
1075
        } elseif ($house == HOUSE_TYPE_NI) {
1076
            $mreg[] = $row;
1077
        } elseif ($house == HOUSE_TYPE_SCOTLAND) {
1078
            if ($cons == $constituencies['SPC']) {
1079
                $mcon = $row;
1080
            } elseif ($cons == $constituencies['SPE']) {
1081
                $mreg[] = $row;
1082
            }
1083
        } elseif ($house == HOUSE_TYPE_WALES) {
1084
            if ($cons == $constituencies['WAC']) {
1085
                $mcon = $row;
1086
            } elseif ($cons == $constituencies['WAE']) {
1087
                $mreg[] = $row;
1088
            }
1089
        } else {
1090
            throw new MySociety\TheyWorkForYou\MemberException('Odd result returned!' . $house);
1091
        }
1092
    }
1093
    if ($rep_type == 'msp') {
1094
        $name = $mcon['given_name'] . ' ' . $mcon['family_name'];
1095
        $cons = $mcon['constituency'];
1096
        $reg = $constituencies['SPE'];
1097
        $url = '/msp/?p=' . $mcon['person_id'];
1098
        if ($current) {
1099
            $data['members_statement'] = '<p>You have one constituency MSP (Member of the Scottish Parliament) and multiple region MSPs.</p>';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
1100
            $data['members_statement'] .= '<p>' . sprintf('Your <strong>constituency MSP</strong> is <a href="%s">%s</a>, MSP for %s.', $url, $name, $cons) . '</p>';
1101
            $data['members_statement'] .= '<p>' . sprintf('Your <strong>%s region MSPs</strong> are:', $reg) . '</p>';
1102
        } else {
1103
            $data['members_statement'] = '<p>' . 'You had one constituency MSP (Member of the Scottish Parliament) and multiple region MSPs.' . '</p>';
1104
            $data['members_statement'] .= '<p>' . sprintf('Your <strong>constituency MSP</strong> was <a href="%s">%s</a>, MSP for %s.', $url, $name, $cons) . '</p>';
1105
            $data['members_statement'] .= '<p>' . sprintf('Your <strong>%s region MSPs</strong> were:', $reg) . '</p>';
1106
        }
1107
    } elseif ($rep_type == 'ms') {
1108
        $name = $mcon['given_name'] . ' ' . $mcon['family_name'];
1109
        $cons = gettext($mcon['constituency']);
1110
        $reg = gettext($constituencies['WAE']);
1111
        $url = '/ms/?p=' . $mcon['person_id'];
1112
        if ($current) {
1113
            $data['members_statement'] = '<p>' . gettext('You have one constituency MS (Member of the Senedd) and multiple region MSs.') . '</p>';
1114
            $data['members_statement'] .= '<p>' . sprintf(gettext('Your <strong>constituency MS</strong> is <a href="%s">%s</a>, MS for %s.'), $url, $name, $cons) . '</p>';
1115
            $data['members_statement'] .= '<p>' . sprintf(gettext('Your <strong>%s region MSs</strong> are:'), $reg) . '</p>';
1116
        } else {
1117
            $data['members_statement'] = '<p>' . gettext('You had one constituency MS (Member of the Senedd) and multiple region MSs.') . '</p>';
1118
            $data['members_statement'] .= '<p>' . sprintf(gettext('Your <strong>constituency MS</strong> was <a href="%s">%s</a>, MS for %s.'), $url, $name, $cons) . '</p>';
1119
            $data['members_statement'] .= '<p>' . sprintf(gettext('Your <strong>%s region MSs</strong> were:'), $reg) . '</p>';
1120
        }
1121
    } else {
1122
        if ($current) {
1123
            $data['members_statement'] = '<p>You have multiple MLAs (Members of the Legislative Assembly) who represent you in ' . $constituencies['NIE'] . '. They are:</p>';
1124
        } else {
1125
            $data['members_statement'] = '<p>You had multiple MLAs (Members of the Legislative Assembly) who represented you in ' . $constituencies['NIE'] . '. They were:</p>';
1126
        }
1127
    }
1128
1129
    foreach($mreg as $reg) {
1130
        $data['members'][] =  [
1131
            'url' => '/' . $rep_type . '/?p=' . $reg['person_id'],
1132
            'name' => $reg['given_name'] . ' ' . $reg['family_name'],
1133
        ];
1134
1135
    }
1136
1137
    // Send the output for rendering
1138
    MySociety\TheyWorkForYou\Renderer::output('mp/regional_list', $data);
1139
1140
}
1141