Passed
Push — release_2_1 ( 584353...81e271 )
by Tomasz
27:15
created

EntityWithDBProperties::getAttributes()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
c 0
b 0
f 0
dl 0
loc 24
rs 8.4444
cc 8
nc 8
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 file contains Federation, IdP and Profile classes.
25
 * These should be split into separate files later.
26
 *
27
 * @package Developer
28
 */
29
/**
30
 * 
31
 */
32
33
namespace core;
34
35
use Exception;
36
37
/**
38
 * This class represents an Entity with properties stored in the DB.
39
 * IdPs have properties of their own, and may have one or more Profiles. The
40
 * profiles can override the institution-wide properties.
41
 *
42
 * @author Stefan Winter <[email protected]>
43
 * @author Tomasz Wolniewicz <[email protected]>
44
 *
45
 * @license see LICENSE file in root directory
46
 */
47
abstract class EntityWithDBProperties extends \core\common\Entity
48
{
49
50
    /**
51
     * This variable gets initialised with the known IdP attributes in the constructor. It never gets updated until the object
52
     * is destroyed. So if attributes change in the database, and IdP attributes are to be queried afterwards, the object
53
     * needs to be re-instantiated to have current values in this variable.
54
     * 
55
     * @var array of entity's attributes
56
     */
57
    protected $attributes;
58
59
    /**
60
     * The database to query for attributes regarding this entity
61
     * 
62
     * @var string DB type
63
     */
64
    protected $databaseType;
65
66
    /**
67
     * This variable contains the name of the table that stores the entity's options
68
     * 
69
     * @var string DB table name
70
     */
71
    protected $entityOptionTable;
72
73
    /**
74
     * column name to find entity in that table
75
     * 
76
     * @var string DB column name of entity
77
     */
78
    protected $entityIdColumn;
79
80
    /**
81
     * We need database access. Be sure to instantiate the singleton, and then
82
     * use its instance (rather than always accessing everything statically)
83
     * 
84
     * @var DBConnection the instance of the default database we talk to usually
85
     */
86
    protected $databaseHandle;
87
88
    /**
89
     * the unique identifier of this entity instance
90
     * refers to the integer row_id name in the DB -> int; Federation has no own
91
     * DB, so the identifier is of no use there -> use Fedearation->$tld
92
     * 
93
     * @var integer identifier of the entity instance
94
     */
95
    public $identifier;
96
97
    /**
98
     * the name of the entity in the current locale
99
     * 
100
     * @var string
101
     */
102
    public $name;
103
104
    /**
105
     * The constructor initialises the entity. Since it has DB properties,
106
     * this means the DB connection is set up for it.
107
     * 
108
     * @throws Exception
109
     */
110
    public function __construct()
111
    {
112
        parent::__construct();
113
        // we are called after the sub-classes have declared their default
114
        // database instance in $databaseType
115
        $handle = DBConnection::handle($this->databaseType);
116
        if ($handle instanceof DBConnection) {
117
            $this->databaseHandle = $handle;
118
        } else {
119
            throw new Exception("This database type is never an array!");
120
        }
121
        $this->attributes = [];
122
    }
123
124
    /**
125
     * How is the object identified in the database?
126
     * @return string|int
127
     * @throws Exception
128
     */
129
    private function getRelevantIdentifier()
130
    {
131
        switch (get_class($this)) {
132
            case "core\ProfileRADIUS":
133
            case "core\ProfileSilverbullet":
134
            case "core\IdP":
135
            case "core\DeploymentManaged":
136
                return $this->identifier;
137
            case "core\Federation":
138
                return $this->tld;
139
            case "core\User":
140
                return $this->userName;
141
            default:
142
                throw new Exception("Operating on a class where we don't know the relevant identifier in the DB - " . get_class($this) . "!");
143
        }
144
    }
145
146
    /**
147
     * This function retrieves the entity's attributes. 
148
     * 
149
     * If called with the optional parameter, only attribute values for the attribute
150
     * name in $optionName are retrieved; otherwise, all attributes are retrieved.
151
     * The retrieval is in-memory from the internal attributes class member - no
152
     * DB callback, so changes in the database during the class instance lifetime
153
     * are not considered.
154
     *
155
     * @param string $optionName optionally, the name of the attribute that is to be retrieved
156
     * @param string$omittedOptionName optionally drop attibutes with that name
0 ignored issues
show
Bug introduced by
The type core\optionally was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
157
     * @return array of arrays of attributes which were set for this IdP
158
     */
159
    public function getAttributes(string $optionName = NULL, string $omittedOptionName = NULL)
160
    {
161
        if ($optionName !== NULL) {
162
            if ($optionName === $omittedOptionName) {
163
                throw new Exception("The attibute to be shown has the same name as that to be omitted");
164
            }
165
            $returnarray = [];
166
            foreach ($this->attributes as $theAttr) {
167
                if ($theAttr['name'] == $optionName) {
168
                    $returnarray[] = $theAttr;
169
                }
170
            }
171
            return $returnarray;
172
        }
173
        if ($omittedOptionName !== NULL) {
174
            $returnarray = [];
175
            foreach ($this->attributes as $theAttr) {
176
                if ($theAttr['name'] !== $omittedOptionName) {
177
                    $returnarray[] = $theAttr;
178
                }
179
            }
180
            return $returnarray;
181
        }
182
        return $this->attributes;
183
    }
184
185
186
    /**
187
     * deletes all attributes in this profile except the _file ones, these are reported as array
188
     *
189
     * @param string $extracondition a condition to append to the deletion query. RADIUS Profiles have eap-level or device-level options which shouldn't be purged; this can be steered in the overriding function.
190
     * @return array list of row_id id's of file-based attributes which weren't deleted
191
     */
192
    public function beginFlushAttributes($extracondition = "")
193
    {
194
        $quotedIdentifier = (!is_int($this->getRelevantIdentifier()) ? "\"" : "") . $this->getRelevantIdentifier() . (!is_int($this->getRelevantIdentifier()) ? "\"" : "");
195
        $this->databaseHandle->exec("DELETE FROM $this->entityOptionTable WHERE $this->entityIdColumn = $quotedIdentifier AND option_name NOT LIKE '%_file' $extracondition");
196
        $this->updateFreshness();
197
        $execFlush = $this->databaseHandle->exec("SELECT row_id FROM $this->entityOptionTable WHERE $this->entityIdColumn = $quotedIdentifier $extracondition");
198
        $returnArray = [];
199
        // SELECT always returns a resource, never a boolean
200
        while ($queryResult = mysqli_fetch_object(/** @scrutinizer ignore-type */ $execFlush)) {
201
            $returnArray[$queryResult->row_id] = "KILLME";
202
        }
203
        return $returnArray;
204
    }
205
206
    /**
207
     * after a beginFlushAttributes, deletes all attributes which are in the tobedeleted array.
208
     *
209
     * @param array $tobedeleted array of database rows which are to be deleted
210
     * @return void
211
     */
212
    public function commitFlushAttributes(array $tobedeleted)
213
    {
214
        $quotedIdentifier = (!is_int($this->getRelevantIdentifier()) ? "\"" : "") . $this->getRelevantIdentifier() . (!is_int($this->getRelevantIdentifier()) ? "\"" : "");
215
        foreach (array_keys($tobedeleted) as $row_id) {
216
            $this->databaseHandle->exec("DELETE FROM $this->entityOptionTable WHERE $this->entityIdColumn = $quotedIdentifier AND row_id = $row_id");
217
            $this->updateFreshness();
218
        }
219
    }
220
221
    /**
222
     * deletes all attributes of this entity from the database
223
     * 
224
     * @return void
225
     */
226
    public function flushAttributes()
227
    {
228
        $this->commitFlushAttributes($this->beginFlushAttributes());
229
    }
230
231
    /**
232
     * Adds an attribute for the entity instance into the database. Multiple instances of the same attribute are supported.
233
     *
234
     * @param string $attrName  Name of the attribute. This must be a well-known value from the profile_option_dict table in the DB.
235
     * @param string $attrLang  language of the attribute. Can be NULL.
236
     * @param mixed  $attrValue Value of the attribute. Can be anything; will be stored in the DB as-is.
237
     * @return void
238
     */
239
    public function addAttribute($attrName, $attrLang, $attrValue)
240
    {
241
        $relevantId = $this->getRelevantIdentifier();
242
        $identifierType = (is_int($relevantId) ? "i" : "s");
243
        $this->databaseHandle->exec("INSERT INTO $this->entityOptionTable ($this->entityIdColumn, option_name, option_lang, option_value) VALUES(?,?,?,?)", $identifierType . "sss", $relevantId, $attrName, $attrLang, $attrValue);
244
        $this->updateFreshness();
245
    }
246
247
    /**
248
     * retrieve attributes from a database. Only does SELECT queries.
249
     * @param string $query sub-classes set the query to execute to get to the options
250
     * @param string $level the retrieved options get flagged with this "level" identifier
251
     * @return array the attributes in one array
252
     * @throws Exception
253
     */
254
    protected function retrieveOptionsFromDatabase($query, $level)
255
    {
256
        if (substr($query, 0, 6) != "SELECT") {
257
            throw new Exception("This function only operates with SELECT queries!");
258
        }
259
        $optioninstance = Options::instance();
260
        $tempAttributes = [];
261
        $relevantId = $this->getRelevantIdentifier();
262
        $attributeDbExec = $this->databaseHandle->exec($query, is_int($relevantId) ? "i" : "s", $relevantId);
263
        if (empty($attributeDbExec)) {
264
            return $tempAttributes;
265
        }
266
        // with SELECTs, we always operate on a resource, not a boolean
267
        while ($attributeQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $attributeDbExec)) {
268
            $optinfo = $optioninstance->optionType($attributeQuery->option_name);
269
            $flag = $optinfo['flag'];
270
            $decoded = $attributeQuery->option_value;
271
            // file attributes always get base64-decoded.
272
            if ($optinfo['type'] == 'file') {
273
                $decoded = base64_decode($decoded);
274
            }
275
            $tempAttributes[] = ["name" => $attributeQuery->option_name, "lang" => $attributeQuery->option_lang, "value" => $decoded, "level" => $level, "row_id" => $attributeQuery->row_id, "flag" => $flag];
276
        }
277
        return $tempAttributes;
278
    }
279
280
    /**
281
     * Retrieves data from the underlying tables, for situations where instantiating the IdP or Profile object is inappropriate
282
     * 
283
     * @param string $table institution_option or profile_option
284
     * @param int    $row_id   rowindex
285
     * @return string|boolean the data, or FALSE if something went wrong
286
     */
287
    public static function fetchRawDataByIndex($table, $row_id)
288
    {
289
        // only for select tables!
290
        switch ($table) {
291
            case "institution_option":
292
            // fall-through intended
293
            case "profile_option":
294
            // fall-through intended
295
            case "federation_option":
296
                break;
297
            default:
298
                return FALSE;
299
        }
300
        $handle = DBConnection::handle("INST");
301
        $blobQuery = $handle->exec("SELECT option_value from $table WHERE row_id = $row_id");
302
        // SELECT -> returns resource, not boolean
303
        $dataset = mysqli_fetch_row(/** @scrutinizer ignore-type */ $blobQuery);
304
        return $dataset[0] ?? FALSE;
305
    }
306
307
    /**
308
     * Checks if a raw data pointer is public data (return value FALSE) or if 
309
     * yes who the authorised admins to view it are (return array of user IDs)
310
     * 
311
     * @param string $table which database table is this about
312
     * @param int    $row_id   row_id index of the table
313
     * @return mixed FALSE if the data is public, an array of owners of the data if it is NOT public
314
     */
315
    public static function isDataRestricted($table, $row_id)
316
    {
317
        if ($table != "institution_option" && $table != "profile_option" && $table != "federation_option" && $table != "user_options") {
318
            return []; // better safe than sorry: that's an error, so assume nobody is authorised to act on that data
319
        }
320
        // we need to create our own DB handle as this is a static method
321
        $handle = DBConnection::handle("INST");
322
        switch ($table) {
323
            case "profile_option": // both of these are similar
324
                $columnName = "profile_id";
325
            // fall-through intended
326
            case "institution_option":
327
                $blobId = -1;
328
                $columnName = $columnName ?? "institution_id";
329
                $blobQuery = $handle->exec("SELECT $columnName as id from $table WHERE row_id = ?", "i", $row_id);
330
                // SELECT always returns a resource, never a boolean
331
                while ($idQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $blobQuery)) { // only one row_id
332
                    $blobId = $idQuery->id;
333
                }
334
                if ($blobId == -1) {
335
                    return []; // err on the side of caution: we did not find any data. It's a severe error, but not fatal. Nobody owns non-existent data.
336
                }
337
338
                if ($table == "profile_option") { // is the profile in question public?
339
                    $profile = ProfileFactory::instantiate($blobId);
340
                    if ($profile->readinessLevel() == AbstractProfile::READINESS_LEVEL_SHOWTIME) { // public data
341
                        return FALSE;
342
                    }
343
                    // okay, so it's NOT public. prepare to return the owner
344
                    $inst = new IdP($profile->institution);
345
                } else { // does the IdP have at least one public profile?
346
                    $inst = new IdP($blobId);
347
                    // if at least one of the profiles belonging to the inst is public, the data is public
348
                    if ($inst->maxProfileStatus() == IdP::PROFILES_SHOWTIME) { // public data
349
                        return FALSE;
350
                    }
351
                }
352
                // okay, so it's NOT public. return the owner
353
                return $inst->listOwners();
354
            case "federation_option":
355
                // federation metadata is always public
356
                return FALSE;
357
            // user options are never public
358
            case "user_options":
359
                return [];
360
            default:
361
                return []; // better safe than sorry: that's an error, so assume nobody is authorised to act on that data
362
        }
363
    }
364
365
    /**
366
     * join new attributes to existing ones, but only if not already defined on
367
     * a different level in the existing set
368
     * 
369
     * @param array  $existing the already existing attributes
370
     * @param array  $new      the new set of attributes
371
     * @param string $newlevel the level of the new attributes
372
     * @return array the new set of attributes
373
     */
374
    protected function levelPrecedenceAttributeJoin($existing, $new, $newlevel)
375
    {
376
        foreach ($new as $attrib) {
377
            $ignore = "";
378
            foreach ($existing as $approvedAttrib) {
379
                if (($attrib["name"] == $approvedAttrib["name"] && $approvedAttrib["level"] != $newlevel) && ($approvedAttrib["name"] != "device-specific:redirect")) {
380
                    $ignore = "YES";
381
                }
382
            }
383
            if ($ignore != "YES") {
384
                $existing[] = $attrib;
385
            }
386
        }
387
        return $existing;
388
    }
389
390
    /**
391
     * when options in the DB change, this can mean generated installers become stale. sub-classes must define whether this is the case for them
392
     * 
393
     * @return void
394
     */
395
    abstract public function updateFreshness();
396
}
397