Test Failed
Pull Request — master (#281)
by
unknown
22:49
created

UserNetAPI::jsonOrderIdentityProviders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
/*
4
 * *****************************************************************************
5
 * Contributions to this work were made on behalf of the GÉANT project, a 
6
 * project that has received funding from the European Union’s Framework 
7
 * Programme 7 under Grant Agreements No. 238875 (GN3) and No. 605243 (GN3plus),
8
 * Horizon 2020 research and innovation programme under Grant Agreements No. 
9
 * 691567 (GN4-1) and No. 731122 (GN4-2).
10
 * On behalf of the aforementioned projects, GEANT Association is the sole owner
11
 * of the copyright in all material which was developed by a member of the GÉANT
12
 * project. GÉANT Vereniging (Association) is registered with the Chamber of 
13
 * Commerce in Amsterdam with registration number 40535155 and operates in the 
14
 * UK as a branch of GÉANT Vereniging.
15
 * 
16
 * Registered office: Hoekenrode 3, 1102BR Amsterdam, The Netherlands. 
17
 * UK branch address: City House, 126-130 Hills Road, Cambridge CB2 1PQ, UK
18
 *
19
 * License: see the web/copyright.inc.php file in the file structure or
20
 *          <base_url>/copyright.php after deploying the software
21
 */
22
23
/**
24
 * This is the collection of methods dedicated for the user GUI
25
 * @author Tomasz Wolniewicz <[email protected]>
26
 * @author Stefan Winter <[email protected]>
27
 * @package UserAPI
28
 *
29
 * Parts of this code are based on simpleSAMLPhp discojuice module.
30
 * This product includes GeoLite data created by MaxMind, available from
31
 * http://www.maxmind.com
32
 */
33
34
namespace core;
35
36
use \Exception;
37
38
/**
39
 * This class collect methods used for communication via network UserAPI
40
 * The methods are generally wrappers around more general UserAPI ones
41
 */
42
class UserNetAPI extends UserAPI
43
{
44
45
    /**
46
     * nothing special to be done here.
47
     */
48
    public function __construct()
49
    {
50
        parent::__construct();
51
    }
52
53
    /**
54
     *  wrapper JSON function
55
     * 
56
     * @param array|bool|null $data      the core data to be converted to JSON
57
     * @param int             $status    extra status information, defaults to 1
58
     * @param array           $otherData additional data to include
59
     * @return string JSON encoded data
60
     * @throws \Exception
61
     */
62
    public function returnJSON($data, $status = 1, $otherData = [])
63
    {
64
        if (headers_sent()) {
65
            throw new \Exception('We were going to send JSON, but there has been sent other data already.');
66
        }
67
        $validator = new \web\lib\common\InputValidation();
68
        $host = $validator->hostname($_SERVER['SERVER_NAME']);
69
        if ($host === FALSE) {
70
            throw new \Exception("We don't know our own hostname?!? Giving up.");
71
        }
72
        $returnArray = [];
73
        $returnArray['status'] = $status;
74
        $returnArray['data'] = $data;
75
        $returnArray['tou'] = "Please consult Terms of Use at: //".$host.\core\CAT::getRootUrlPath()."/tou.php";
76
        if (!empty($otherData)) {
77
            $returnArray['otherdata'] = $otherData;
78
        }
79
        header('Content-Type: application/json');
80
        return(json_encode($returnArray), \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_THROW_ON_ERROR) . "\n";
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected ',' on line 80 at column 40
Loading history...
81
    }
82
83
    /**
84
     * outputs the list of supported languages.
85
     * 
86
     * @return void creates direct output
87
     */
88
    public function jsonListLanguages()
89
    {
90
        $returnArray = [];
91
        foreach (\config\Master::LANGUAGES as $id => $val) {
92
            $returnArray[] = ['lang' => $id, 'display' => $val['display'], 'locale' => $val['locale']];
93
        }
94
        echo $this->returnJSON($returnArray);
95
    }
96
97
    /**
98
     * outputs the list of countries with configured IdPs
99
     *
100
     * @return void creates direct output
101
     */
102
    public function jsonListCountries()
103
    {
104
        $federations = $this->printCountryList(1);
105
        $returnArray = [];
106
        foreach ($federations as $id => $val) {
107
            $returnArray[] = ['federation' => $id, 'display' => $val];
108
        }
109
        echo $this->returnJSON($returnArray);
110
    }
111
112
    /**
113
     * outputs the list of IdPs in a given country
114
     *
115
     * @param string $country the country we are interested in
116
     * @return void creates direct output
117
     */
118
    public function jsonListIdentityProviders($country)
119
    {
120
        $idps = $this->listAllIdentityProviders(1, $country);
121
        $returnArray = [];
122
        foreach ($idps as $idp) {
123
            $returnArray[] = ['idp' => $idp['entityID'], 'id' => $idp['entityID'], 'display' => $idp['title']];
124
        }
125
        echo $this->returnJSON($returnArray);
126
    }
127
128
    /**
129
     * outputs the list of all active IdPs
130
     * The IdP list is formatted for DiscoJuice consumption
131
     * 
132
     * @return void creates direct output
133
     */
134
    public function jsonListIdentityProvidersForDisco()
135
    {
136
        $idps = $this->listAllIdentityProviders(1);
137
        $returnArray = [];
138
        foreach ($idps as $idp) {
139
            $idp['idp'] = $idp['entityID'];
140
            $idp['id'] = $idp['entityID'];
141
            $returnArray[] = $idp;
142
        }
143
        echo json_encode($returnArray);
144
    }
145
146
    /**
147
     * outputs the list of IdPs in a given country ordered with respect to their distance to the user's location
148
     * 
149
     * @param string $country  the country in question
150
     * @param array  $location the coordinates of the approximate user location
151
     * @return void creates direct output
152
     */
153
    public function jsonOrderIdentityProviders($country, $location)
154
    {
155
        $idps = $this->orderIdentityProviders($country, $location);
156
        $returnArray = [];
157
        foreach ($idps as $idp) {
158
            $returnArray[] = ['idp' => $idp['id'], 'display' => $idp['title']];
159
        }
160
        echo $this->returnJSON($returnArray);
161
    }
162
163
    /**
164
     * outputs a list of profiles available for a given IdP
165
     *
166
     * @param int $idpIdentifier the IdP identifier
167
     * @param int $sort          should the result set be sorted? 0 = no, 1 = yes
168
     * @return void creates direct output
169
     */
170
    public function jsonListProfiles($idpIdentifier, $sort = 0)
171
    {
172
        $returnArray = [];
173
        try {
174
            $idp = new IdP($idpIdentifier);
175
        } catch (\Exception $fail) {
176
            echo $this->returnJSON($returnArray, 0);
177
            return;
178
        }
179
        $hasLogo = 0;
180
        $logo = $idp->getAttributes('general:logo_file');
181
        if (count($logo) > 0) {
182
            $hasLogo = 1;
183
        }
184
        $fed = new Federation($idp->federation);
185
        $fedUrl = $idp->languageInstance->getLocalisedValue($fed->getAttributes('fed:url'));
186
        $fedName = $idp->languageInstance->getLocalisedValue($fed->getAttributes('fed:realname'));
187
        $otherData = [];
188
        if (!empty($fedUrl)) {
189
            $otherData['fedurl'] = $fedUrl;
190
        }
191
        if (!empty($fedName)) {
192
            $otherData['fedname'] = $fedName;
193
        }
194
        $profiles = $idp->listProfiles(TRUE);
195
        if ($sort == 1) {
196
            usort($profiles, ["UserAPI", "profileSort"]);
197
        }
198
        foreach ($profiles as $profile) {
199
            $returnArray[] = ['profile' => $profile->identifier, 'id' => $profile->identifier, 'display' => $profile->name, 'idp_name' => $profile->instName, 'logo' => $hasLogo];
200
        }
201
        echo $this->returnJSON($returnArray, 1, $otherData);
202
    }
203
    
204
    /**
205
     * outputs a full list of IdPs containing the fllowing data:
206
     * institution_is, institution name in all available languages,
207
     * list of production profiles.
208
     * For eache profile the profile identifier, profile name in all languages
209
     * and redirect values (empty rediret value means that no redirect has been
210
     * set).
211
     * @return array of identity providers with attributes
212
     */
213
    public function jsonListIdentityProvidersWithProfiles() {
214
        echo $this->returnJSON($this->listIdentityProvidersWithProfiles());
215
    }
216
217
    /**
218
     * outputs the list of devices available for the given profile
219
     *
220
     * @param int $profileId the Profile identifier
221
     * @return void creates direct output
222
     */
223
    public function jsonListDevices($profileId)
224
    {
225
        $returnArray = [];
226
        $profileAttributes = $this->profileAttributes($profileId);
227
        $thedevices = $profileAttributes['devices'];
228
        foreach ($thedevices as $D) {
229
            $hidden = \core\common\Entity::getAttributeValue($D, 'options', 'hidden');
230
            if ($hidden === 1 || $hidden === 2) {
231
                continue;
232
            }
233
            if ($D['id'] === '0') { // This is a global profile level redirect therefore no device name is available
234
                $disp = '';
235
            } else {
236
                $disp = $D['display'];
237
            }
238
            $returnArray[] = ['device' => $D['id'], 'display' => $disp, 'status' => $D['status'], 'redirect' => $D['redirect']];
239
        }
240
        echo $this->returnJSON($returnArray);
241
    }
242
243
    /**
244
     * outputs the link to the installers (additionally, actually generates it or takes it from cache)
245
     *
246
     * @param string $device  identifier as in {@link devices.php}
247
     * @param int    $prof_id profile identifier
248
     * @return void creates direct output
249
     */
250
    public function jsonGenerateInstaller($device, $prof_id, $openRoaming = 0)
251
    {
252
        $this->loggerInstance->debug(4, "JSON::generateInstaller arguments: $device,$prof_id, $openRoaming\n");
253
        $output = $this->generateInstaller($device, $prof_id, 'user', $openRoaming);
254
        $this->loggerInstance->debug(4, "output from GUI::generateInstaller:");
255
        $this->loggerInstance->debug(4, print_r($output, true));
256
        $this->loggerInstance->debug(4, json_encode($output));
257
//    header('Content-type: application/json; utf-8');
258
        echo $this->returnJSON($output);
259
    }
260
261
    /**
262
     * outputs OS guess in JSON
263
     * 
264
     * @return void creates direct output
265
     */
266
    public function jsonDetectOS()
267
    {
268
        $status = 1;
269
        $returnArray = $this->detectOS();
270
        if ($returnArray === FALSE) {
271
            $status = 0;
272
        }
273
        echo $this->returnJSON($returnArray, $status);
274
    }
275
276
    /**
277
     * outputs user certificates pertaining to a given token in JSON
278
     * @param string $token the token for which we want certs
279
     * @return void creates direct output
280
     */
281
    public function jsonGetUserCerts($token)
282
    {
283
        $status = 1;
284
        $returnArrayE = $this->getUserCerts($token);
285
        $returnArray = [];
286
        if ($returnArrayE === FALSE) {
287
            $status = 0;
288
        }
289
        if ($status === 1) {
290
            foreach ($returnArrayE as $element) {
291
                $returnArray[] = $element->getBasicInfo();
292
            }
293
        }
294
        echo $this->returnJSON($returnArray, $status);
295
    }
296
297
    /**
298
     * outputs the user location as JSON
299
     * 
300
     * @return void creates direct output
301
     */
302
    public function jsonLocateUser()
303
    {
304
        header('Content-type: application/json; utf-8');
305
        echo json_encode($this->locateDevice());
306
    }
307
308
    /**
309
     * outputs support data prepared within {@link GUI::profileAttributes()}
310
     * 
311
     * @param integer $profileId the profile ID
312
     * @return void creates direct output
313
     */
314
    public function jsonProfileAttributes($profileId)
315
    {
316
//    header('Content-type: application/json; utf-8');
317
        echo $this->returnJSON($this->profileAttributes($profileId));
318
    }
319
320
    /**
321
     * outputs a logo
322
     * 
323
     * @param int|string $identifier identifier of the object whose logo is sought
324
     * @param string     $type       "federation" or "idp"
325
     * @param integer    $width      desired target width
326
     * @param integer    $height     desired target height
327
     * @return void creates direct output
328
     */
329
    public function sendLogo($identifier, $type, $width, $height)
330
    {
331
        $logo = $this->getLogo($identifier, $type, $width, $height);
332
        header("Content-type: ".$logo['filetype']);
333
        header("Cache-Control:max-age=36000, must-revalidate");
334
        header($logo['expires']);
335
        echo $logo['blob'];
336
    }
337
}
338