Passed
Pull Request — master (#1700)
by Matthew
04:12
created

person_error_page()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 42
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 38
nc 6
nop 1
dl 0
loc 42
rs 8.6897
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
$new_style_template = TRUE;
33
34
// Include all the things this page needs.
35
include_once '../../includes/easyparliament/init.php';
36
include_once INCLUDESPATH . 'easyparliament/member.php';
37
include_once INCLUDESPATH . '../../commonlib/phplib/random.php';
38
include_once INCLUDESPATH . '../../commonlib/phplib/auth.php';
39
include_once '../api/api_getGeometry.php';
40
include_once '../api/api_getConstituencies.php';
41
42
// Ensure that page type is set
43
if (get_http_var('pagetype')) {
44
    $pagetype = get_http_var('pagetype');
45
} else {
46
    $pagetype = 'profile';
47
}
48
if ($pagetype == 'profile') {
49
    $pagetype = '';
50
}
51
52
// list of years for which we have WTT response stats in
53
// reverse chronological order. Add new years here as we
54
// get them.
55
// NB: also need to update ./mpinfoin.pl to import the stats
56
$wtt_stats_years = array(2015, 2014, 2013, 2008, 2007, 2006, 2005);
57
58
// Set the PID, name and constituency.
59
$pid = get_http_var('pid') != '' ? get_http_var('pid') : get_http_var('p');
60
$name = strtolower(str_replace('_', ' ', get_http_var('n')));
61
$constituency = strtolower(str_replace('_', ' ', get_http_var('c')));
62
63
// Fix for names with non-ASCII characters
64
if ($name == 'sion simon') {
65
    $name = 'si\xf4n simon';
66
}
67
if ($name == 'sian james') {
68
    $name = 'si\xe2n james';
69
}
70
if ($name == 'lembit opik') {
71
    $name = 'lembit \xf6pik';
72
}
73
if ($name == 'bairbre de brun') {
74
    $name = 'bairbre de br\xfan';
75
}
76
if ($name == 'daithi mckay') {
77
    $name = 'daith\xed mckay';
78
}
79
if ($name == 'caral ni chuilin') {
80
    $name = 'car\xe1l n\xed chuil\xedn';
81
}
82
if ($name == 'caledon du pre') {
83
    $name = 'caledon du pr\xe9';
84
}
85
if ($name == 'sean etchingham') {
86
    $name = 'se\xe1n etchingham';
87
}
88
if ($name == 'john tinne') {
89
    $name = 'john tinn\xe9';
90
}
91
if ($name == 'renee short') {
92
    $name = 'ren\xe9e short';
93
}
94
95
// Fix for common misspellings, name changes etc
96
$name_fix = array(
97
    'a j beith' => 'alan beith',
98
    'micky brady' => 'mickey brady',
99
    'daniel rogerson' => 'dan rogerson',
100
    'andrew slaughter' => 'andy slaughter',
101
    'robert wilson' => array('rob wilson', 'reading east'),
102
    'james mcgovern' => 'jim mcgovern',
103
    'patrick mcfadden' => 'pat mcfadden',
104
    'chris leslie' => 'christopher leslie',
105
    'joseph meale' => 'alan meale',
106
    'james sheridan' => 'jim sheridan',
107
    'chinyelu onwurah' => 'chi onwurah',
108
    'steve rotherham' => 'steve rotheram',
109
    'michael weatherley' => 'mike weatherley',
110
    'louise bagshawe' => 'louise mensch',
111
    'andrew sawford' => 'andy sawford',
112
);
113
114
if (array_key_exists($name, $name_fix)) {
115
    if (is_array($name_fix[$name])) {
116
        if ($constituency == $name_fix[$name][1]) {
117
            $name = $name_fix[$name][0];
118
        }
119
    } else {
120
        $name = $name_fix[$name];
121
    }
122
}
123
124
// Fixes for Ynys Mon, and a Unicode URL
125
if ($constituency == 'ynys mon') {
126
    $constituency = "ynys m\xf4n";
127
}
128
if (preg_match("#^ynys m\xc3\xb4n#i", $constituency)) {
129
    $constituency = "ynys m\xf4n";
130
}
131
132
// If this is a request for recent appearances, redirect to search results
133
if (get_http_var('recent')) {
134
    if ($THEUSER->postcode_is_set() && !$pid) {
135
        $MEMBER = new MySociety\TheyWorkForYou\Member(array('postcode' => $THEUSER->postcode(), 'house' => HOUSE_TYPE_COMMONS));
136
        if ($MEMBER->person_id()) {
137
            $pid = $MEMBER->person_id();
138
        }
139
    }
140
    if ($pid) {
141
        $URL = new \MySociety\TheyWorkForYou\Url('search');
142
        $URL->insert( array('pid'=>$pid, 'pop'=>1) );
143
        header('Location: ' . $URL->generate('none'));
144
        exit;
145
    }
146
}
147
148
/////////////////////////////////////////////////////////
149
// DETERMINE TYPE OF REPRESENTITIVE
150
151
switch (get_http_var('representative_type')) {
152
    case 'peer':
153
        $this_page = 'peer';
154
        break;
155
    case 'royal':
156
        $this_page = 'royal';
157
        break;
158
    case 'mla':
159
        $this_page = 'mla';
160
        break;
161
    case 'msp':
162
        $this_page = 'msp';
163
        break;
164
    case 'ms':
165
        $this_page = 'ms';
166
        break;
167
    case 'london-assembly-member':
168
        $this_page = 'london-assembly-member';
169
        break;
170
    default:
171
        $this_page = 'mp';
172
        break;
173
}
174
175
try {
176
    if (is_numeric($pid)) {
177
        $MEMBER = get_person_by_id($pid);
178
    } elseif (is_numeric(get_http_var('m'))) {
179
        get_person_by_member_id(get_http_var('m'));
180
    } elseif (get_http_var('pc')) {
181
        get_person_by_postcode(get_http_var('pc'));
182
    } elseif ($name) {
183
        $MEMBER = get_person_by_name($name, $constituency);
184
    } elseif ($constituency) {
185
        get_mp_by_constituency($constituency);
186
    } elseif (($this_page == 'msp' || $this_page == 'mla' || $this_page == 'ms') && $THEUSER->postcode_is_set()) {
187
        get_regional_by_user_postcode($THEUSER->postcode(), $this_page);
188
        exit;
189
    } elseif ($THEUSER->postcode_is_set()) {
190
        get_mp_by_user_postcode($THEUSER->postcode());
191
    } else {
192
        twfy_debug ('MP', "We don't have any way of telling what MP to display");
193
        throw new MySociety\TheyWorkForYou\MemberException(gettext('Sorry, but we can’t tell which representative to display.'));
194
    }
195
    if (!isset($MEMBER) || !$MEMBER->valid) {
196
        throw new MySociety\TheyWorkForYou\MemberException(gettext('You haven’t provided a way of identifying which representative you want'));
197
    }
198
} catch (MySociety\TheyWorkForYou\MemberMultipleException $e) {
199
    person_list_page($e->ids);
200
    exit;
201
} catch (MySociety\TheyWorkForYou\MemberException $e) {
202
    person_error_page($e->getMessage());
203
    exit;
204
}
205
206
# We have successfully looked up one person to show now.
207
208
if (!DEVSITE) {
209
    header('Cache-Control: max-age=900');
210
}
211
212
twfy_debug_timestamp("before load_extra_info");
213
$MEMBER->load_extra_info(true);
214
twfy_debug_timestamp("after load_extra_info");
215
216
// Basic name, title and description
217
$member_name = ucfirst($MEMBER->full_name());
218
$title = $member_name;
219
$desc = "Read $member_name's contributions to Parliament, including speeches and questions";
220
221
// Enhance description if this is a current member
222
if ($MEMBER->current_member_anywhere()) {
223
    $desc .= ', investigate their voting record, and get email alerts on their activity';
224
}
225
226
// Enhance title if this is a member of the Commons
227
if ($MEMBER->house(HOUSE_TYPE_COMMONS)) {
228
    if (!$MEMBER->current_member(1)) {
229
        $title .= ', former';
230
    }
231
    $title .= ' MP';
232
    if ($MEMBER->constituency()) {
233
        $title .= ', ' . $MEMBER->constituency();
234
    }
235
}
236
237
// Enhance title if this is a member of NIA
238
if ($MEMBER->house(HOUSE_TYPE_NI)) {
239
    if ($MEMBER->house(HOUSE_TYPE_COMMONS) || $MEMBER->house(HOUSE_TYPE_LORDS)) {
240
        $desc = str_replace('Parliament', 'Parliament and the Northern Ireland Assembly', $desc);
241
    } else {
242
        $desc = str_replace('Parliament', 'the Northern Ireland Assembly', $desc);
243
    }
244
    if (!$MEMBER->current_member(HOUSE_TYPE_NI)) {
245
        $title .= ', former';
246
    }
247
    $title .= ' MLA';
248
    if ($MEMBER->constituency()) {
249
        $title .= ', ' . $MEMBER->constituency();
250
    }
251
}
252
253
// Enhance title if this is a member of Scottish Parliament
254
if ($MEMBER->house(HOUSE_TYPE_SCOTLAND)) {
255
    if ($MEMBER->house(HOUSE_TYPE_COMMONS) || $MEMBER->house(HOUSE_TYPE_LORDS)) {
256
        $desc = str_replace('Parliament', 'the UK and Scottish Parliaments', $desc);
257
    } else {
258
        $desc = str_replace('Parliament', 'the Scottish Parliament', $desc);
259
    }
260
    $desc = str_replace(', and get email alerts on their activity', '', $desc);
261
    if (!$MEMBER->current_member(HOUSE_TYPE_SCOTLAND)) {
262
        $title .= ', former';
263
    }
264
    $title .= ' MSP, '.$MEMBER->constituency();
265
}
266
267
// Enhance title if this is a member of Welsh Parliament
268
if ($MEMBER->house(HOUSE_TYPE_WALES)) {
269
    if ($MEMBER->house(HOUSE_TYPE_COMMONS) || $MEMBER->house(HOUSE_TYPE_LORDS)) {
270
        $desc = str_replace('Parliament', 'the UK and Welsh Parliaments', $desc);
271
    } else {
272
        $desc = str_replace('Parliament', 'the Senedd', $desc);
273
    }
274
    $desc = str_replace(', and get email alerts on their activity', '', $desc);
275
    if (!$MEMBER->current_member(HOUSE_TYPE_WALES)) {
276
        $title .= ', former';
277
    }
278
    $title .= ' MS, '.$MEMBER->constituency();
279
}
280
281
$known_for = '';
282
$current_offices_ignoring_committees = $MEMBER->offices('current', TRUE);
283
if (count($current_offices_ignoring_committees) > 0) {
284
    $known_for = $current_offices_ignoring_committees[0];
285
}
286
287
// Finally, if this is a Votes page, replace the page description with
288
// something more descriptive of the actual data on the page.
289
if ($pagetype == 'votes') {
290
    $title = "Voting record - " . $title;
291
    $desc = 'See how ' . $member_name . ' voted on topics like Employment, Social Issues, Foreign Policy, and more.';
292
}
293
294
// Set page metadata
295
$DATA->set_page_metadata($this_page, 'title', $title);
296
$DATA->set_page_metadata($this_page, 'meta_description', $desc);
297
298
// Build the RSS link and add it to page data.
299
$feedurl = $DATA->page_metadata('mp_rss', 'url') . $MEMBER->person_id() . '.rdf';
300
if (file_exists(BASEDIR . '/' . $feedurl)) {
301
    $DATA->set_page_metadata($this_page, 'rss', $feedurl);
302
}
303
304
// Prepare data for the template
305
$data['full_name'] = $MEMBER->full_name();
306
$data['person_id'] = $MEMBER->person_id();
307
$data['member_id'] = $MEMBER->member_id();
308
309
$data['known_for'] = $known_for;
310
$data['latest_membership'] = $MEMBER->getMostRecentMembership();
311
312
$data['constituency'] = $MEMBER->constituency();
313
$data['party'] = $MEMBER->party_text();
314
$data['current_party_comparison'] = $MEMBER->currentPartyComparison();
315
$data['current_member_anywhere'] = $MEMBER->current_member_anywhere();
316
$data['current_member'] = $MEMBER->current_member();
317
$data['the_users_mp'] = $MEMBER->the_users_mp();
318
$data['user_postcode'] = $THEUSER->postcode;
319
$data['houses'] = $MEMBER->houses();
320
$data['member_url'] = $MEMBER->url();
321
$data['abs_member_url'] = $MEMBER->url(true);
322
// If there's photo attribution information, copy it into data
323
foreach (['photo_attribution_text', 'photo_attribution_link'] as $key) {
324
    if (isset($MEMBER->extra_info[$key])) {
325
        $data[$key] = $MEMBER->extra_info[$key];
326
    }
327
}
328
$data['profile_message'] = isset($MEMBER->extra_info['profile_message']) ? $MEMBER->extra_info['profile_message'] : '';
329
$data['image'] = $MEMBER->image();
330
$data['member_summary'] = person_summary_description($MEMBER);
331
$data['enter_leave'] = $MEMBER->getEnterLeaveStrings();
332
$data['entry_date'] = $MEMBER->getEntryDate();
333
$data['leave_date'] = $MEMBER->getLeftDate();
334
$data['is_new_mp'] = $MEMBER->isNew();
335
$data['other_parties'] = $MEMBER->getOtherPartiesString();
336
$data['other_constituencies'] = $MEMBER->getOtherConstituenciesString();
337
$data['rebellion_rate'] = person_rebellion_rate($MEMBER);
338
$data['recent_appearances'] = person_recent_appearances($MEMBER);
339
$data['useful_links'] = person_useful_links($MEMBER);
340
$data['social_links'] = person_social_links($MEMBER);
341
$data['topics_of_interest'] = person_topics($MEMBER);
342
$data['current_offices'] = $MEMBER->offices('current');
343
$data['previous_offices'] = $MEMBER->offices('previous');
344
$data['register_interests'] = person_register_interests($MEMBER, $MEMBER->extra_info);
345
$data['eu_stance'] = $MEMBER->getEUStance();
346
347
# People who are or were MPs and Lords potentially have voting records, except Sinn Fein MPs
348
$data['has_voting_record'] = ( ($MEMBER->house(HOUSE_TYPE_COMMONS) && $MEMBER->party() != 'Sinn Féin') || $MEMBER->house(HOUSE_TYPE_LORDS) );
349
# Everyone who is currently somewhere has email alert signup, apart from current Sinn Fein MPs who are not MLAs
350
$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)));
351
$data['has_expenses'] = $data['leave_date'] > '2004-01-01';
352
353
$data['pre_2010_expenses'] = False;
354
$data['post_2010_expenses'] = $data['leave_date'] > '2010-05-05';
355
356
if ($data['entry_date'] < '2010-05-05') {
357
    $data['pre_2010_expenses'] = True;
358
    // Set the expenses URL if we know it
359
    if (isset($MEMBER->extra_info['expenses_url'])) {
360
        $data['expenses_url_2004'] = $MEMBER->extra_info['expenses_url'];
361
    } else {
362
        $data['expenses_url_2004'] = 'https://mpsallowances.parliament.uk/mpslordsandoffices/hocallowances/allowances%2Dby%2Dmp/';
363
    }
364
}
365
366
$data['constituency_previous_mps'] = constituency_previous_mps($MEMBER);
367
$data['constituency_future_mps'] = constituency_future_mps($MEMBER);
368
$data['public_bill_committees'] = person_pbc_membership($MEMBER);
369
370
$data['this_page'] = $this_page;
371
$country = MySociety\TheyWorkForYou\Utility\House::getCountryDetails($data['latest_membership']['house']);
372
$data['current_assembly'] = $country[2];
373
374
$data['policy_last_update'] = MySociety\TheyWorkForYou\Divisions::getMostRecentDivisionDate();
375
376
$data['comparison_party'] = $MEMBER->cohortParty();
377
378
// Do any necessary extra work based on the page type, and send for rendering.
379
switch ($pagetype) {
380
381
    case 'votes':
382
        $policy_set = get_http_var('policy');
383
384
        $policiesList = new MySociety\TheyWorkForYou\Policies;
385
        $divisions = new MySociety\TheyWorkForYou\Divisions($MEMBER);
386
        $policySummaries = $divisions->getMemberDivisionDetails();
387
388
        $policyOptions = array( 'summaries' => $policySummaries);
389
390
        // Generate voting segments
391
        $set_descriptions = $policiesList->getSetDescriptions();
392
        if ( $policy_set && array_key_exists($policy_set, $set_descriptions) ) {
0 ignored issues
show
Bug introduced by
It seems like $policy_set can also be of type array and array; however, parameter $key of array_key_exists() does only seem to accept integer|string, 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

392
        if ( $policy_set && array_key_exists(/** @scrutinizer ignore-type */ $policy_set, $set_descriptions) ) {
Loading history...
393
            $sets = array($policy_set);
394
            $data['og_image'] = $MEMBER->url(true) . "/policy_set_png?policy_set=" . $policy_set;
0 ignored issues
show
Bug introduced by
Are you sure $policy_set of type array|mixed|string can be used in concatenation? ( Ignorable by Annotation )

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

394
            $data['og_image'] = $MEMBER->url(true) . "/policy_set_png?policy_set=" . /** @scrutinizer ignore-type */ $policy_set;
Loading history...
395
            $data['page_title'] = $set_descriptions[$policy_set] . ' ' . $title . ' - TheyWorkForYou';
396
            $data['meta_description'] = 'See how ' . $data['full_name'] . ' voted on ' . $set_descriptions[$policy_set];
397
            $data['single_policy_page'] = true;
398
        } else {
399
            $data['single_policy_page'] = false;
400
            $sets = array(
401
                'social', 'foreignpolicy', 'welfare', 'taxation', 'business',
402
                'health', 'education', 'reform', 'home', 'environment',
403
                'transport', 'housing', 'misc'
404
            );
405
            shuffle($sets);
406
        }
407
408
        $data['key_votes_segments'] = array();
409
        foreach ($sets as $key) {
410
            $data['key_votes_segments'][] = array(
411
                'key'   => $key,
412
                'title' => $set_descriptions[$key],
413
                'votes' => new MySociety\TheyWorkForYou\PolicyPositions(
414
                    $policiesList->limitToSet($key), $MEMBER, $policyOptions
415
                )
416
            );
417
        }
418
419
        person_party_policy_diffs($MEMBER, $policiesList, false);
420
421
        // Send the output for rendering
422
        MySociety\TheyWorkForYou\Renderer::output('mp/votes', $data);
423
424
        break;
425
426
    case 'recent':
427
        $divisions = new MySociety\TheyWorkForYou\Divisions($MEMBER);
428
        $data['divisions'] = $divisions->getRecentMemberDivisions();
429
        MySociety\TheyWorkForYou\Renderer::output('mp/recent', $data);
430
        break;
431
432
    case 'divisions':
433
        $policyID = get_http_var('policy');
434
        if ( $policyID ) {
435
            $policiesList = new MySociety\TheyWorkForYou\Policies( $policyID );
436
        } else {
437
            $policiesList = new MySociety\TheyWorkForYou\Policies;
438
        }
439
        $positions = new MySociety\TheyWorkForYou\PolicyPositions( $policiesList, $MEMBER );
440
        $divisions = new MySociety\TheyWorkForYou\Divisions($MEMBER, $positions, $policiesList);
441
442
        if ( $policyID ) {
443
            $data['policydivisions'] = $divisions->getMemberDivisionsForPolicy($policyID);
444
        } else {
445
            $data['policydivisions'] = $divisions->getAllMemberDivisionsByPolicy();
446
        }
447
448
        // Send the output for rendering
449
        MySociety\TheyWorkForYou\Renderer::output('mp/divisions', $data);
450
451
        break;
452
453
    case 'policy_set_svg':
454
        policy_image($data, $MEMBER, 'svg');
455
        break;
456
457
    case 'policy_set_png':
458
        policy_image($data, $MEMBER, 'png');
459
        break;
460
461
    case '':
462
    default:
463
464
        $policiesList = new MySociety\TheyWorkForYou\Policies;
465
        $policies = $policiesList->limitToSet('summary');
466
        $divisions = new MySociety\TheyWorkForYou\Divisions($MEMBER);
467
        $policySummaries = $divisions->getMemberDivisionDetails();
468
469
        $policyOptions = array('limit' => 6, 'summaries' => $policySummaries);
470
471
        // Generate limited voting record list
472
        $data['policyPositions'] = new MySociety\TheyWorkForYou\PolicyPositions($policies, $MEMBER, $policyOptions);
473
474
        person_party_policy_diffs($MEMBER, $policiesList, true);
475
476
        // Send the output for rendering
477
        MySociety\TheyWorkForYou\Renderer::output('mp/profile', $data);
478
479
        break;
480
481
}
482
483
484
/////////////////////////////////////////////////////////
485
// SUPPORTING FUNCTIONS
486
487
/* Person lookup functions */
488
489
function get_person_by_id($pid) {
490
    global $pagetype, $this_page;
491
    $MEMBER = new MySociety\TheyWorkForYou\Member(array('person_id' => $pid));
492
    if (!$MEMBER->valid) {
493
        throw new MySociety\TheyWorkForYou\MemberException('Sorry, that ID number wasn&rsquo;t recognised.');
494
    }
495
    // Ensure that we're actually at the current, correct and canonical URL for the person. If not, redirect.
496
    // No need to worry about other URL syntax forms for vote pages, they shouldn't happen.
497
    $at = str_replace('/mp/', "/$this_page/", get_http_var('url'));
498
    $shouldbe = urldecode($MEMBER->url());
499
    if ($pagetype) {
500
        $shouldbe .= "/$pagetype";
501
    }
502
    if ($at !== $shouldbe) {
503
        member_redirect($MEMBER, 301, $pagetype);
504
    }
505
    return $MEMBER;
506
}
507
508
function get_person_by_member_id($member_id) {
509
    // Got a member id, redirect to the canonical MP page, with a person id.
510
    $MEMBER = new MySociety\TheyWorkForYou\Member(array('member_id' => $member_id));
511
    member_redirect($MEMBER);
512
}
513
514
function get_person_by_postcode($pc) {
515
    global $THEUSER;
516
    $pc = preg_replace('#[^a-z0-9]#i', '', $pc);
517
    if (!validate_postcode($pc)) {
518
        twfy_debug ('MP', "Can't display an MP because the submitted postcode wasn't of a valid form.");
519
        throw new MySociety\TheyWorkForYou\MemberException(sprintf(gettext('Sorry, %s isn’t a valid postcode'), _htmlentities($pc)));
520
    }
521
    twfy_debug ('MP', "MP lookup by postcode");
522
    $constituency = strtolower(MySociety\TheyWorkForYou\Utility\Postcode::postcodeToConstituency($pc));
523
    if ($constituency == "connection_timed_out") {
524
        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.'));
525
    } elseif ($constituency == "") {
526
        twfy_debug ('MP', "Can't display an MP, as submitted postcode didn't match a constituency");
527
        throw new MySociety\TheyWorkForYou\MemberException(sprintf(gettext('Sorry, %s isn’t a known postcode'), _htmlentities($pc)));
528
    } else {
529
        // Redirect to the canonical MP page, with a person id.
530
        $MEMBER = new MySociety\TheyWorkForYou\Member(array('constituency' => $constituency, 'house' => HOUSE_TYPE_COMMONS));
531
        if ($MEMBER->person_id()) {
532
            // This will cookie the postcode.
533
            $THEUSER->set_postcode_cookie($pc);
534
        }
535
        member_redirect($MEMBER, 302);
536
    }
537
}
538
539
function get_person_by_name($name, $const='') {
540
    $MEMBER = new MySociety\TheyWorkForYou\Member(array('name' => $name, 'constituency' => $const));
541
    // Edge case, only attempt further detection if this isn't the Queen.
542
    if (($name !== 'elizabeth the second' && $name !== 'prince charles') || $const) {
543
        twfy_debug ('MP', 'Redirecting for MP found by name/constituency');
544
        member_redirect($MEMBER);
545
    }
546
    return $MEMBER;
547
}
548
549
function get_mp_by_constituency($constituency) {
550
    $MEMBER = new MySociety\TheyWorkForYou\Member(array('constituency' => $constituency, 'house' => HOUSE_TYPE_COMMONS));
551
    member_redirect($MEMBER);
552
}
553
554
function get_regional_by_user_postcode($pc, $page) {
555
    global $this_page;
556
    $this_page = "your$page";
557
    $areas = \MySociety\TheyWorkForYou\Utility\Postcode::postcodeToConstituencies($pc);
558
    if ($page == 'msp' && isset($areas['SPC'])) {
559
        regional_list($pc, 'SPC', $page);
560
    } elseif ($page == 'ms' && isset($areas['WAC'])) {
561
        regional_list($pc, 'WAC', $page);
562
    } elseif ($page == 'mla' && isset($areas['NIE'])) {
563
        regional_list($pc, 'NIE', $page);
564
    } else {
565
        throw new MySociety\TheyWorkForYou\MemberException('Your set postcode is not in the right region.');
566
    }
567
}
568
569
function get_mp_by_user_postcode($pc) {
570
    $MEMBER = new MySociety\TheyWorkForYou\Member(array('postcode' => $pc, 'house' => HOUSE_TYPE_COMMONS));
571
    member_redirect($MEMBER, 302);
572
}
573
574
/**
575
 * Member Redirect
576
 *
577
 * Redirect to the canonical page for a member.
578
 */
579
580
function member_redirect (&$MEMBER, $code = 301, $pagetype = NULL) {
581
    // We come here after creating a MEMBER object by various methods.
582
    // Now we redirect to the canonical MP page, with a person_id.
583
    if ($MEMBER->person_id()) {
584
        $url = $MEMBER->url();
585
        $params = array();
586
        foreach ($_GET as $key => $value) {
587
            if (substr($key, 0, 4) == 'utm_' || $key == 'gclid') {
588
                $params[] = "$key=$value";
589
            }
590
        }
591
        if (count($params)) {
592
            $url .= '?' . join('&', $params);
593
        }
594
        if ($pagetype) {
595
            $pagetype = '/' . $pagetype;
596
        } else {
597
            $pagetype = '';
598
        }
599
        header('Location: ' . $url . $pagetype, true, $code );
600
        exit;
601
    }
602
}
603
604
/* Error list page */
605
606
function person_list_page($ids) {
607
    global $name;
608
    if (!DEVSITE) {
609
        header('Cache-Control: max-age=900');
610
    }
611
    $data = array('mps' => array());
612
    foreach ($ids as $id => $constituency) {
613
        $data['mps'][] = array(
614
            'url'  => WEBPATH . 'mp/?pid=' . $id,
615
            'name' => ucwords(strtolower($name)) . ', ' . $constituency,
616
        );
617
    }
618
    $MPSURL = new \MySociety\TheyWorkForYou\Url('mps');
619
    $data['all_mps_url'] = $MPSURL->generate();
620
    MySociety\TheyWorkForYou\Renderer::output('mp/list', $data);
621
}
622
623
/* Error page */
624
625
function person_error_page($message) {
626
    global $this_page;
627
    $SEARCHURL = '';
628
    switch($this_page) {
629
        case 'peer':
630
            $people = new MySociety\TheyWorkForYou\People\Peers();
631
            $MPSURL = new \MySociety\TheyWorkForYou\Url('peers');
632
            break;
633
        case 'mla':
634
            $people = new MySociety\TheyWorkForYou\People\MLAs();
635
            $SEARCHURL = '/postcode/';
636
            $MPSURL = new \MySociety\TheyWorkForYou\Url('mlas');
637
            break;
638
        case 'msp':
639
            $people = new MySociety\TheyWorkForYou\People\MSPs();
640
            $SEARCHURL = '/postcode/';
641
            $MPSURL = new \MySociety\TheyWorkForYou\Url('msps');
642
            break;
643
        case 'ms':
644
            $people = new MySociety\TheyWorkForYou\People\MSs();
645
            $SEARCHURL = '/postcode/';
646
            $MPSURL = new \MySociety\TheyWorkForYou\Url('mss');
647
            break;
648
        case 'london-assembly-member':
649
            $people = new MySociety\TheyWorkForYou\People\LondonAssemblyMembers();
650
            $MPSURL = new \MySociety\TheyWorkForYou\Url('london-assembly-members');
651
            break;
652
        default:
653
            $people = new MySociety\TheyWorkForYou\People\MPs();
654
            $SEARCHURL = new \MySociety\TheyWorkForYou\Url('mp');
655
            $SEARCHURL = $SEARCHURL->generate();
656
            $MPSURL = new \MySociety\TheyWorkForYou\Url('mps');
657
    }
658
659
    $data = array(
660
        'error' => $message,
661
        'rep_name' => $people->rep_name,
662
        'rep_name_plural' => $people->rep_plural,
663
        'all_mps_url' => $MPSURL->generate(),
664
        'rep_search_url' => $SEARCHURL,
665
    );
666
    MySociety\TheyWorkForYou\Renderer::output('mp/error', $data);
667
}
668
669
/**
670
 * Person Positions Summary
671
 *
672
 * Generate the summary of this person's held positions.
673
 */
674
675
function person_summary_description ($MEMBER) {
676
    $entered_house = $MEMBER->entered_house();
677
    $current_member = $MEMBER->current_member();
678
    $left_house = $MEMBER->left_house();
679
680
    if (in_array(HOUSE_TYPE_ROYAL, $MEMBER->houses())) {
681
        # Royal short-circuit
682
        if (substr($entered_house[HOUSE_TYPE_ROYAL]['date'], 0, 4) == 1952) {
683
            return '<strong>Acceded on ' . $entered_house[HOUSE_TYPE_ROYAL]['date_pretty']
684
                . '<br>Coronated on 2 June 1953</strong></li>';
685
        } else {
686
            return '';
687
        }
688
    }
689
    $desc = '';
690
    foreach ($MEMBER->houses() as $house) {
691
        if ($house==HOUSE_TYPE_COMMONS && isset($entered_house[HOUSE_TYPE_LORDS])) {
692
            # Same info is printed further down
693
            continue;
694
        }
695
696
        $party = $left_house[$house]['party'];
697
        $party_br = '';
698
        if (preg_match('#^(.*?)\s*\((.*?)\)$#', $party, $m)) {
699
            $party_br = " ($m[2])";
700
            $party = $m[1];
701
        }
702
        $pparty = $party != 'unknown' ? _htmlentities($party) : '';
703
704
        if ($house != HOUSE_TYPE_LORDS) {
705
            if ($house == HOUSE_TYPE_COMMONS) {
706
                $type = gettext('<abbr title="Member of Parliament">MP</abbr>');
707
            } elseif ($house == HOUSE_TYPE_NI) {
708
                $type = gettext('<abbr title="Member of the Legislative Assembly">MLA</abbr>');
709
            } elseif ($house == HOUSE_TYPE_SCOTLAND) {
710
                $type = gettext('<abbr title="Member of the Scottish Parliament">MSP</abbr>');
711
            } elseif ($house == HOUSE_TYPE_WALES) {
712
                $type = gettext('<abbr title="Member of the Senedd">MS</abbr>');
713
            } elseif ($house == HOUSE_TYPE_LONDON_ASSEMBLY) {
714
                $type = gettext('Member of the London Assembly');
715
            }
716
717
            if ($party == 'Speaker' || $party == 'Deputy Speaker') {
718
                # XXX: Might go horribly wrong if something odd happens
719
                if ($party == 'Deputy Speaker') {
720
                    $last = end($MEMBER->other_parties);
721
                    $oparty = $last['from'];
722
                } else {
723
                    $oparty = '';
724
                }
725
                if ($current_member[$house]) {
726
                    $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...
727
                } else {
728
                    $line = sprintf(gettext('Former %s, and %s %s for %s'), $pparty, $oparty, $type, $left_house[$house]['constituency']);
729
                }
730
            } elseif ($current_member[$house]) {
731
                $line = sprintf(gettext('%s %s %s for %s'), $pparty, $type, $party_br, $left_house[$house]['constituency']);
732
            } else {
733
                $line = sprintf(gettext('Former %s %s %s for %s'), $pparty, $type, $party_br, $left_house[$house]['constituency']);
734
            }
735
        } elseif ($house == HOUSE_TYPE_LORDS && $party != 'Bishop') {
736
            if ($current_member[$house]) {
737
                $line = sprintf(gettext('%s Peer'), $pparty);
738
            } else {
739
                $line = sprintf(gettext('Former %s Peer'), $pparty);
740
            }
741
        } else {
742
            if ($current_member[$house]) {
743
                $line = $pparty;
744
            } else {
745
                $line = sprintf(gettext('Former %s'), $pparty);
746
            }
747
        }
748
        $desc .= $line . ', ';
749
    }
750
    $desc = preg_replace('#, $#', '', $desc);
751
    return $desc;
752
}
753
754
/**
755
 * Person Rebellion Rate
756
 *
757
 * How often has this person rebelled against their party?
758
 *
759
 * @param MEMBER $member The member to calculate rebellion rate for.
760
 *
761
 * @return string A HTML summary of this person's rebellion rate.
762
 */
763
764
function person_rebellion_rate ($member) {
765
766
    // Rebellion string may be empty.
767
    $rebellion_string = '';
768
769
    if (isset($member->extra_info['public_whip_rebellions']) && $member->extra_info['public_whip_rebellions'] != 'n/a') {
770
        $rebels_term = 'rebelled';
771
772
        $rebellion_string = 'has <a href="https://www.publicwhip.org.uk/mp.php?id=uk.org.publicwhip/member/' . $member->member_id() . '#divisions" title="See more details at Public Whip"><strong>' . _htmlentities($member->extra_info['public_whip_rebel_description']) . ' ' . $rebels_term . '</strong></a> against their party';
773
774
        if (isset($member->extra_info['public_whip_rebelrank'])) {
775
            if ($member->extra_info['public_whip_data_date'] == 'complete') {
776
                $rebellion_string .= ' in their last parliament.';
777
            } else {
778
                $rebellion_string .= ' in the current parliament.';
779
            }
780
        }
781
782
        $rebellion_string .= ' <small><a title="What do the rebellion figures mean exactly?" href="https://www.publicwhip.org.uk/faq.php#clarify">Find out more</a>.</small>';
783
    }
784
785
    return $rebellion_string;
786
787
}
788
789
function person_recent_appearances($member) {
790
    global $DATA, $SEARCHENGINE, $this_page;
791
792
    $out = array();
793
    $out['appearances'] = array();
794
795
    //$this->block_start(array('id'=>'hansard', 'title'=>$title));
796
    // This is really far from ideal - I don't really want $PAGE to know
797
    // anything about HANSARDLIST / DEBATELIST / WRANSLIST.
798
    // But doing this any other way is going to be a lot more work for little
799
    // benefit unfortunately.
800
    twfy_debug_timestamp();
801
802
    $person_id = $member->person_id();
803
804
    $memcache = new MySociety\TheyWorkForYou\Memcache;
805
    $recent = $memcache->get("recent_appear:$person_id:" . LANGUAGE);
806
807
    if (!$recent) {
0 ignored issues
show
introduced by
The condition $recent is always false.
Loading history...
808
        // Initialise the search engine
809
        $searchstring = "speaker:$person_id";
810
        $SEARCHENGINE = new \SEARCHENGINE($searchstring);
811
812
        $hansard = new MySociety\TheyWorkForYou\Hansard();
813
        $args = array (
814
            's' => $searchstring,
815
            'p' => 1,
816
            'num' => 3,
817
            'pop' => 1,
818
            'o' => 'd',
819
        );
820
        $results = $hansard->search($searchstring, $args);
821
        $recent = serialize($results['rows']);
822
        $memcache->set('recent_appear:' . $person_id, $recent);
823
    }
824
    $out['appearances'] = unserialize($recent);
825
    twfy_debug_timestamp();
826
827
    $MOREURL = new \MySociety\TheyWorkForYou\Url('search');
828
    $MOREURL->insert( array('pid'=>$person_id, 'pop'=>1) );
829
830
    $out['more_href'] = $MOREURL->generate() . '#n4';
831
    $out['more_text'] = sprintf(gettext('More of %s’s recent appearances'), ucfirst($member->full_name()));
832
833
    if ($rssurl = $DATA->page_metadata($this_page, 'rss')) {
834
        // If we set an RSS feed for this page.
835
        $HELPURL = new \MySociety\TheyWorkForYou\Url('help');
836
        $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>)';
837
    }
838
839
    return $out;
840
841
}
842
843
function person_useful_links($member) {
844
845
    $links = $member->extra_info();
846
847
    $out = array();
848
849
    if (isset($links['maiden_speech'])) {
850
        $maiden_speech = fix_gid_from_db($links['maiden_speech']);
851
        $out[] = array(
852
                'href' => WEBPATH . 'debate/?id=' . $maiden_speech,
853
                'text' => 'Maiden speech'
854
        );
855
    }
856
857
    // BIOGRAPHY.
858
    global $THEUSER;
859
    if (isset($links['mp_website'])) {
860
        $out[] = array(
861
                'href' => $links['mp_website'],
862
                'text' => 'Personal website'
863
        );
864
    }
865
866
    if (isset($links['sp_url'])) {
867
        $out[] = array(
868
                'href' => $links['sp_url'],
869
                'text' => 'Page on the Scottish Parliament website'
870
        );
871
    }
872
873
    if (isset($links['wikipedia_url'])) {
874
        $out[] = array(
875
                'href' => $links['wikipedia_url'],
876
                'text' => 'Wikipedia page'
877
        );
878
    }
879
880
    if (isset($links['bbc_profile_url'])) {
881
        $out[] = array(
882
                'href' => $links['bbc_profile_url'],
883
                'text' => 'BBC News profile'
884
        );
885
    }
886
887
    if (isset($links['diocese_url'])) {
888
        $out[] = array(
889
                'href' => $links['diocese_url'],
890
                'text' => 'Diocese website'
891
        );
892
    }
893
894
    if ($member->house(HOUSE_TYPE_COMMONS)) {
895
        $out[] = array(
896
                'href' => 'http://www.edms.org.uk/mps/' . $member->person_id(),
897
                'text' => 'Early Day Motions signed by this MP'
898
        );
899
    }
900
901
    if (isset($links['journa_list_link'])) {
902
        $out[] = array(
903
                'href' => $links['journa_list_link'],
904
                'text' => 'Newspaper articles written by this MP'
905
        );
906
    }
907
908
    return $out;
909
}
910
911
function person_social_links($member) {
912
913
    $links = $member->extra_info();
914
915
    $out = array();
916
917
    if (isset($links['twitter_username'])) {
918
        $out[] = array(
919
                'href' => 'https://twitter.com/' . _htmlentities($links['twitter_username']),
920
                'text' => '@' . _htmlentities($links['twitter_username']),
921
                'type' => 'twitter'
922
        );
923
    }
924
925
    if (isset($links['facebook_page'])) {
926
        $out[] = array(
927
                'href' => _htmlentities($links['facebook_page']),
928
                'text' => _htmlentities($links['facebook_page']),
929
                'type' => 'facebook'
930
        );
931
    }
932
933
    return $out;
934
}
935
936
function person_topics($member) {
937
    $out = array();
938
939
    $extra_info = $member->extra_info();
940
941
    if (isset($extra_info['wrans_departments'])) {
942
        $subjects = explode(',', $extra_info['wrans_departments']);
943
        $out = array_merge($out, $subjects);
944
    }
945
946
    if (isset($extra_info['wrans_subjects'])) {
947
        $subjects = explode(',', $extra_info['wrans_subjects']);
948
        $out = array_merge($out, $subjects);
949
    }
950
951
    return $out;
952
}
953
954
function constituency_previous_mps($member) {
955
    if ($member->house(HOUSE_TYPE_COMMONS)) {
956
        return $member->previous_mps();
957
    } else {
958
        return array();
959
    }
960
}
961
962
function constituency_future_mps($member) {
963
    if ($member->house(HOUSE_TYPE_COMMONS)) {
964
        return $member->future_mps();
965
    } else {
966
        return array();
967
    }
968
}
969
970
function person_pbc_membership($member) {
971
972
    $extra_info = $member->extra_info();
973
    $out = array('info'=>'', 'data'=>array());
974
975
    # Public Bill Committees
976
    if (count($extra_info['pbc'])) {
977
        if ($member->party() == 'Scottish National Party') {
978
            $out['info'] = 'SNP MPs only attend sittings where the legislation pertains to Scotland.';
979
        }
980
        foreach ($extra_info['pbc'] as $bill_id => $arr) {
981
            $text = '';
982
            if ($arr['chairman']) {
983
                $text .= 'Chairman, ';
984
            }
985
            $text .= $arr['title'] . ' Committee';
986
            $out['data'][] = array(
987
                'href'      => '/pbc/' . $arr['session'] . '/' . urlencode($arr['title']),
988
                'text'      => $text,
989
                'attending' => $arr['attending'] . ' out of ' . $arr['outof']
990
            );
991
        }
992
    }
993
994
    return $out;
995
}
996
997
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

997
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...
998
    if (!isset($extra_info['register_member_interests_html'])) {
999
        return;
1000
    }
1001
1002
    $reg = array( 'date' => '', 'data' => '<p>Nil</p>' );
1003
    if (isset($extra_info['register_member_interests_date'])) {
1004
        $reg['date'] = format_date($extra_info['register_member_interests_date'], SHORTDATEFORMAT);
1005
    }
1006
    if ($extra_info['register_member_interests_html'] != '') {
1007
        $reg['data'] = $extra_info['register_member_interests_html'];
1008
    }
1009
    return $reg;
1010
}
1011
1012
function regional_list($pc, $area_type, $rep_type) {
1013
    $constituencies = MySociety\TheyWorkForYou\Utility\Postcode::postcodeToConstituencies($pc);
1014
    if ($constituencies == 'CONNECTION_TIMED_OUT') {
1015
        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.');
1016
    } elseif (!$constituencies) {
1017
        throw new MySociety\TheyWorkForYou\MemberException('Sorry, ' . htmlentities($pc) . ' isn&rsquo;t a known postcode');
1018
    } elseif (!isset($constituencies[$area_type])) {
1019
        throw new MySociety\TheyWorkForYou\MemberException(htmlentities($pc) . ' does not appear to be a valid postcode');
1020
    }
1021
    global $PAGE;
1022
    $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

1022
    $a = array_values(/** @scrutinizer ignore-type */ $constituencies);
Loading history...
1023
    $db = new ParlDB;
1024
    $query_base = "SELECT member.person_id, given_name, family_name, constituency, house
1025
        FROM member, person_names pn
1026
        WHERE constituency IN ('" . join("','", $a) . "')
1027
            AND member.person_id = pn.person_id AND pn.type = 'name'
1028
            AND pn.end_date = (SELECT MAX(end_date) FROM person_names WHERE person_names.person_id = member.person_id)";
1029
    $q = $db->query($query_base . " AND left_reason = 'still_in_office' AND house in (" . HOUSE_TYPE_NI . "," . HOUSE_TYPE_SCOTLAND . "," . HOUSE_TYPE_WALES . ")");
1030
    $current = true;
1031
    if (!$q->rows() && ($dissolution = MySociety\TheyWorkForYou\Dissolution::db())) {
1032
        $current = false;
1033
        $q = $db->query($query_base . " AND $dissolution[query]",
1034
            $dissolution['params']);
1035
    }
1036
    $mcon = array(); $mreg = array();
1037
    foreach ($q as $row) {
1038
        $house = $row['house'];
1039
        $cons = $row['constituency'];
1040
        if ($house == HOUSE_TYPE_COMMONS) {
1041
            continue;
1042
        } elseif ($house == HOUSE_TYPE_NI) {
1043
            $mreg[] = $row;
1044
        } elseif ($house == HOUSE_TYPE_SCOTLAND) {
1045
            if ($cons == $constituencies['SPC']) {
1046
                $mcon = $row;
1047
            } elseif ($cons == $constituencies['SPE']) {
1048
                $mreg[] = $row;
1049
            }
1050
        } elseif ($house == HOUSE_TYPE_WALES) {
1051
            if ($cons == $constituencies['WAC']) {
1052
                $mcon = $row;
1053
            } elseif ($cons == $constituencies['WAE']) {
1054
                $mreg[] = $row;
1055
            }
1056
        } else {
1057
            throw new MySociety\TheyWorkForYou\MemberException('Odd result returned!' . $house);
1058
        }
1059
    }
1060
    if ($rep_type == 'msp') {
1061
        $name = $mcon['given_name'] . ' ' . $mcon['family_name'];
1062
        $cons = $mcon['constituency'];
1063
        $reg = $constituencies['SPE'];
1064
        $url = '/msp/?p=' . $mcon['person_id'];
1065
        if ($current) {
1066
            $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...
1067
            $data['members_statement'] .= '<p>' . sprintf('Your <strong>constituency MSP</strong> is <a href="%s">%s</a>, MSP for %s.', $url, $name, $cons) . '</p>';
1068
            $data['members_statement'] .= '<p>' . sprintf('Your <strong>%s region MSPs</strong> are:', $reg) . '</p>';
1069
        } else {
1070
            $data['members_statement'] = '<p>' . 'You had one constituency MSP (Member of the Scottish Parliament) and multiple region MSPs.' . '</p>';
1071
            $data['members_statement'] .= '<p>' . sprintf('Your <strong>constituency MSP</strong> was <a href="%s">%s</a>, MSP for %s.', $url, $name, $cons) . '</p>';
1072
            $data['members_statement'] .= '<p>' . sprintf('Your <strong>%s region MSPs</strong> were:', $reg) . '</p>';
1073
        }
1074
    } elseif ($rep_type == 'ms') {
1075
        $name = $mcon['given_name'] . ' ' . $mcon['family_name'];
1076
        $cons = gettext($mcon['constituency']);
1077
        $reg = gettext($constituencies['WAE']);
1078
        $url = '/ms/?p=' . $mcon['person_id'];
1079
        if ($current) {
1080
            $data['members_statement'] = '<p>' . gettext('You have one constituency MS (Member of the Senedd) and multiple region MSs.') . '</p>';
1081
            $data['members_statement'] .= '<p>' . sprintf(gettext('Your <strong>constituency MS</strong> is <a href="%s">%s</a>, MS for %s.'), $url, $name, $cons) . '</p>';
1082
            $data['members_statement'] .= '<p>' . sprintf(gettext('Your <strong>%s region MSs</strong> are:'), $reg) . '</p>';
1083
        } else {
1084
            $data['members_statement'] = '<p>' . gettext('You had one constituency MS (Member of the Senedd) and multiple region MSs.') . '</p>';
1085
            $data['members_statement'] .= '<p>' . sprintf(gettext('Your <strong>constituency MS</strong> was <a href="%s">%s</a>, MS for %s.'), $url, $name, $cons) . '</p>';
1086
            $data['members_statement'] .= '<p>' . sprintf(gettext('Your <strong>%s region MSs</strong> were:'), $reg) . '</p>';
1087
        }
1088
    } else {
1089
        if ($current) {
1090
            $data['members_statement'] = '<p>You have multiple MLAs (Members of the Legislative Assembly) who represent you in ' . $constituencies['NIE'] . '. They are:</p>';
1091
        } else {
1092
            $data['members_statement'] = '<p>You had multiple MLAs (Members of the Legislative Assembly) who represented you in ' . $constituencies['NIE'] . '. They were:</p>';
1093
        }
1094
    }
1095
1096
    foreach($mreg as $reg) {
1097
        $data['members'][] = array (
1098
            'url' => '/' . $rep_type . '/?p=' . $reg['person_id'],
1099
            'name' => $reg['given_name'] . ' ' . $reg['family_name']
1100
        );
1101
1102
    }
1103
1104
    // Send the output for rendering
1105
    MySociety\TheyWorkForYou\Renderer::output('mp/regional_list', $data);
1106
1107
}
1108
1109
function policy_image($data, $MEMBER, $format) {
1110
    $policiesList = new MySociety\TheyWorkForYou\Policies;
1111
    $set_descriptions = $policiesList->getSetDescriptions();
1112
    $policy_set = get_http_var('policy_set');
1113
1114
    if (!array_key_exists($policy_set, $set_descriptions)) {
0 ignored issues
show
Bug introduced by
It seems like $policy_set can also be of type array and array; however, parameter $key of array_key_exists() does only seem to accept integer|string, 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

1114
    if (!array_key_exists(/** @scrutinizer ignore-type */ $policy_set, $set_descriptions)) {
Loading history...
1115
        header('HTTP/1.0 404 Not Found');
1116
        exit();
1117
    }
1118
1119
    // Generate voting segments
1120
    $data['segment'] = array(
1121
        'key'   => $policy_set,
1122
        'title' => $policiesList->getSetDescriptions()[$policy_set],
1123
        'votes' => new MySociety\TheyWorkForYou\PolicyPositions(
1124
            $policiesList->limitToSet($policy_set), $MEMBER
0 ignored issues
show
Bug introduced by
It seems like $policy_set can also be of type array and array; however, parameter $set of MySociety\TheyWorkForYou\Policies::limitToSet() does only seem to accept string, 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

1124
            $policiesList->limitToSet(/** @scrutinizer ignore-type */ $policy_set), $MEMBER
Loading history...
1125
        )
1126
    );
1127
1128
    if ($format === 'png') {
1129
        ob_start();
1130
    }
1131
    MySociety\TheyWorkForYou\Renderer::output('mp/votes_svg', $data, true);
1132
    if ($format === 'svg') {
1133
        return;
1134
    }
1135
1136
    $svg = ob_get_clean();
1137
1138
    $im = new Imagick();
1139
    $im->setOption('-antialias', true);
1140
    $im->readImageBlob($svg);
1141
    $im->setImageFormat("png24");
1142
1143
    $filename = strtolower(str_replace(' ', '_', $MEMBER->full_name() . "_" . $policiesList->getSetDescriptions()[$policy_set] . ".png"));
1144
    header("Content-type: image/png");
1145
    header('Content-Disposition: filename="' . $filename . '"');
1146
    print $im->getImageBlob();
1147
1148
    $im->clear();
1149
    $im->destroy();
1150
}
1151
1152
// generate party policy diffs
1153
function person_party_policy_diffs($MEMBER, $policiesList, $only_diffs) {
1154
    global $data;
1155
1156
    $divisions = new MySociety\TheyWorkForYou\Divisions($MEMBER);
1157
    $policySummaries = $divisions->getMemberDivisionDetails();
1158
1159
    $party = new MySociety\TheyWorkForYou\Party($MEMBER->party());
1160
    $partyCohort = new MySociety\TheyWorkForYou\PartyCohort($MEMBER->cohortKey());
1161
    $data['party_positions'] = $partyCohort->getAllPolicyPositions($policiesList);
1162
    # house hard coded as this is only used for the party position
1163
    # comparison which is Commons only
1164
    $data['party_member_count'] = $party->getCurrentMemberCount(HOUSE_TYPE_COMMONS);
1165
1166
    $positions = new MySociety\TheyWorkForYou\PolicyPositions( $policiesList, $MEMBER, [
1167
        'summaries' => $policySummaries,
1168
    ]);
1169
    $policy_diffs = $MEMBER->getPartyPolicyDiffs($partyCohort, $policiesList, $positions, $only_diffs);
1170
    $data['sorted_diffs'] = $policy_diffs;
1171
}
1172