Passed
Push — master ( 809568...caddf1 )
by
unknown
09:27 queued 04:29
created

person_social_links()   B

Complexity

Conditions 7
Paths 48

Size

Total Lines 54
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 32
c 2
b 0
f 0
nc 48
nop 1
dl 0
loc 54
rs 8.4746

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

1060
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...
1061
1062
    $valid_chambers = ['house-of-commons', 'scottish-parliament', 'northern-ireland-assembly', 'senedd'];
1063
1064
    $lang = LANGUAGE;
1065
1066
    $reg = ['chamber_registers' => [] ];
1067
1068
    foreach ($valid_chambers as $chamber) {
1069
        $key = 'person_regmem_' . $chamber . '_' . $lang;
1070
        $chamber_register = person_register_interests_from_key($key, $extra_info);
1071
        if ($chamber_register) {
1072
            $reg['chamber_registers'][$chamber] = $chamber_register;
1073
        }
1074
    }
1075
    // if chamber_registers is empty, we don't have any data
1076
    if (empty($reg['chamber_registers'])) {
1077
        return;
1078
    }
1079
1080
    // sort chamber registers by published_date
1081
    uasort($reg['chamber_registers'], function ($a, $b) {
1082
        return $a->published_date <=> $b->published_date;
1083
    });
1084
1085
    return $reg;
1086
}
1087
1088
function regional_list($pc, $area_type, $rep_type) {
1089
    $constituencies = MySociety\TheyWorkForYou\Utility\Postcode::postcodeToConstituencies($pc);
1090
    if ($constituencies == 'CONNECTION_TIMED_OUT') {
1091
        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.');
1092
    } elseif (!$constituencies) {
1093
        throw new MySociety\TheyWorkForYou\MemberException('Sorry, ' . htmlentities($pc) . ' isn&rsquo;t a known postcode');
1094
    } elseif (!isset($constituencies[$area_type])) {
1095
        throw new MySociety\TheyWorkForYou\MemberException(htmlentities($pc) . ' does not appear to be a valid postcode');
1096
    }
1097
    global $PAGE;
1098
    $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

1098
    $a = array_values(/** @scrutinizer ignore-type */ $constituencies);
Loading history...
1099
    $db = new ParlDB();
1100
    $query_base = "SELECT member.person_id, given_name, family_name, constituency, house
1101
        FROM member, person_names pn
1102
        WHERE constituency IN ('" . join("','", $a) . "')
1103
            AND member.person_id = pn.person_id AND pn.type = 'name'
1104
            AND pn.end_date = (SELECT MAX(end_date) FROM person_names WHERE person_names.person_id = member.person_id)";
1105
    $q = $db->query($query_base . " AND left_reason = 'still_in_office' AND house in (" . HOUSE_TYPE_NI . "," . HOUSE_TYPE_SCOTLAND . "," . HOUSE_TYPE_WALES . ")");
1106
    $current = true;
1107
    if (!$q->rows() && ($dissolution = MySociety\TheyWorkForYou\Dissolution::db())) {
1108
        $current = false;
1109
        $q = $db->query(
1110
            $query_base . " AND $dissolution[query]",
1111
            $dissolution['params']
1112
        );
1113
    }
1114
    $mcon = [];
1115
    $mreg = [];
1116
    foreach ($q as $row) {
1117
        $house = $row['house'];
1118
        $cons = $row['constituency'];
1119
        if ($house == HOUSE_TYPE_COMMONS) {
1120
            continue;
1121
        } elseif ($house == HOUSE_TYPE_NI) {
1122
            $mreg[] = $row;
1123
        } elseif ($house == HOUSE_TYPE_SCOTLAND) {
1124
            if ($cons == $constituencies['SPC']) {
1125
                $mcon = $row;
1126
            } elseif ($cons == $constituencies['SPE']) {
1127
                $mreg[] = $row;
1128
            }
1129
        } elseif ($house == HOUSE_TYPE_WALES) {
1130
            if ($cons == $constituencies['WAC']) {
1131
                $mcon = $row;
1132
            } elseif ($cons == $constituencies['WAE']) {
1133
                $mreg[] = $row;
1134
            }
1135
        } else {
1136
            throw new MySociety\TheyWorkForYou\MemberException('Odd result returned!' . $house);
1137
        }
1138
    }
1139
    if ($rep_type == 'msp') {
1140
        $name = $mcon['given_name'] . ' ' . $mcon['family_name'];
1141
        $cons = $mcon['constituency'];
1142
        $reg = $constituencies['SPE'];
1143
        $url = '/msp/?p=' . $mcon['person_id'];
1144
        if ($current) {
1145
            $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...
1146
            $data['members_statement'] .= '<p>' . sprintf('Your <strong>constituency MSP</strong> is <a href="%s">%s</a>, MSP for %s.', $url, $name, $cons) . '</p>';
1147
            $data['members_statement'] .= '<p>' . sprintf('Your <strong>%s region MSPs</strong> are:', $reg) . '</p>';
1148
        } else {
1149
            $data['members_statement'] = '<p>' . 'You had one constituency MSP (Member of the Scottish Parliament) and multiple region MSPs.' . '</p>';
1150
            $data['members_statement'] .= '<p>' . sprintf('Your <strong>constituency MSP</strong> was <a href="%s">%s</a>, MSP for %s.', $url, $name, $cons) . '</p>';
1151
            $data['members_statement'] .= '<p>' . sprintf('Your <strong>%s region MSPs</strong> were:', $reg) . '</p>';
1152
        }
1153
    } elseif ($rep_type == 'ms') {
1154
        $name = $mcon['given_name'] . ' ' . $mcon['family_name'];
1155
        $cons = gettext($mcon['constituency']);
1156
        $reg = gettext($constituencies['WAE']);
1157
        $url = '/ms/?p=' . $mcon['person_id'];
1158
        if ($current) {
1159
            $data['members_statement'] = '<p>' . gettext('You have one constituency MS (Member of the Senedd) and multiple region MSs.') . '</p>';
1160
            $data['members_statement'] .= '<p>' . sprintf(gettext('Your <strong>constituency MS</strong> is <a href="%s">%s</a>, MS for %s.'), $url, $name, $cons) . '</p>';
1161
            $data['members_statement'] .= '<p>' . sprintf(gettext('Your <strong>%s region MSs</strong> are:'), $reg) . '</p>';
1162
        } else {
1163
            $data['members_statement'] = '<p>' . gettext('You had one constituency MS (Member of the Senedd) and multiple region MSs.') . '</p>';
1164
            $data['members_statement'] .= '<p>' . sprintf(gettext('Your <strong>constituency MS</strong> was <a href="%s">%s</a>, MS for %s.'), $url, $name, $cons) . '</p>';
1165
            $data['members_statement'] .= '<p>' . sprintf(gettext('Your <strong>%s region MSs</strong> were:'), $reg) . '</p>';
1166
        }
1167
    } else {
1168
        if ($current) {
1169
            $data['members_statement'] = '<p>You have multiple MLAs (Members of the Legislative Assembly) who represent you in ' . $constituencies['NIE'] . '. They are:</p>';
1170
        } else {
1171
            $data['members_statement'] = '<p>You had multiple MLAs (Members of the Legislative Assembly) who represented you in ' . $constituencies['NIE'] . '. They were:</p>';
1172
        }
1173
    }
1174
1175
    foreach($mreg as $reg) {
1176
        $data['members'][] =  [
1177
            'url' => '/' . $rep_type . '/?p=' . $reg['person_id'],
1178
            'name' => $reg['given_name'] . ' ' . $reg['family_name'],
1179
        ];
1180
1181
    }
1182
1183
    // Send the output for rendering
1184
    MySociety\TheyWorkForYou\Renderer::output('mp/regional_list', $data);
1185
1186
}
1187
1188
function policy_image($data, $MEMBER, $format) {
1189
    $policiesList = new MySociety\TheyWorkForYou\Policies();
1190
    $set_descriptions = $policiesList->getSetDescriptions();
1191
    $policy_set = get_http_var('policy_set');
1192
1193
    if (!array_key_exists($policy_set, $set_descriptions)) {
1194
        header('HTTP/1.0 404 Not Found');
1195
        exit();
1196
    }
1197
1198
    // Generate voting segments
1199
    $data['segment'] = [
1200
        'key'   => $policy_set,
1201
        'title' => $policiesList->getSetDescriptions()[$policy_set],
1202
        'votes' => new MySociety\TheyWorkForYou\PolicyPositions(
1203
            $policiesList->limitToSet($policy_set),
1204
            $MEMBER
1205
        ),
1206
    ];
1207
1208
    if ($format === 'png') {
1209
        ob_start();
1210
    }
1211
    MySociety\TheyWorkForYou\Renderer::output('mp/votes_svg', $data, true);
1212
    if ($format === 'svg') {
1213
        return;
1214
    }
1215
1216
    $svg = ob_get_clean();
1217
1218
    $im = new Imagick();
1219
    $im->setOption('-antialias', true);
1220
    $im->readImageBlob($svg);
1221
    $im->setImageFormat("png24");
1222
1223
    $filename = strtolower(str_replace(' ', '_', $MEMBER->full_name() . "_" . $policiesList->getSetDescriptions()[$policy_set] . ".png"));
1224
    header("Content-type: image/png");
1225
    header('Content-Disposition: filename="' . $filename . '"');
1226
    print $im->getImageBlob();
1227
1228
    $im->clear();
1229
    $im->destroy();
1230
}
1231
1232
// generate party policy diffs
1233
function person_party_policy_diffs($MEMBER, $policiesList) {
1234
    global $data;
1235
1236
    $divisions = new MySociety\TheyWorkForYou\Divisions($MEMBER);
1237
    $policySummaries = $divisions->getMemberDivisionDetails(true);
1238
1239
    $party = new MySociety\TheyWorkForYou\Party($MEMBER->party());
1240
    $partyCohort = new MySociety\TheyWorkForYou\PartyCohort($MEMBER->person_id(), $MEMBER->cohortParty());
1241
    $data['party_positions'] = $partyCohort->getAllPolicyPositions($policiesList);
1242
    # house hard coded as this is only used for the party position
1243
    # comparison which is Commons only
1244
    $data['party_member_count'] = $party->getCurrentMemberCount(HOUSE_TYPE_COMMONS);
1245
1246
    $positions = new MySociety\TheyWorkForYou\PolicyPositions($policiesList, $MEMBER, [
1247
        'summaries' => $policySummaries,
1248
    ]);
1249
    $policy_diffs = $MEMBER->getPartyPolicyDiffs($partyCohort, $policiesList, $positions);
1250
    $data['sorted_diffs'] = $policy_diffs;
1251
}
1252