Passed
Push — release_2_0 ( 17ead9...53ebbf )
by Stefan
07:41
created

EntityWithDBProperties::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
/*
3
 * *****************************************************************************
4
 * Contributions to this work were made on behalf of the GÉANT project, a 
5
 * project that has received funding from the European Union’s Framework 
6
 * Programme 7 under Grant Agreements No. 238875 (GN3) and No. 605243 (GN3plus),
7
 * Horizon 2020 research and innovation programme under Grant Agreements No. 
8
 * 691567 (GN4-1) and No. 731122 (GN4-2).
9
 * On behalf of the aforementioned projects, GEANT Association is the sole owner
10
 * of the copyright in all material which was developed by a member of the GÉANT
11
 * project. GÉANT Vereniging (Association) is registered with the Chamber of 
12
 * Commerce in Amsterdam with registration number 40535155 and operates in the 
13
 * UK as a branch of GÉANT Vereniging.
14
 * 
15
 * Registered office: Hoekenrode 3, 1102BR Amsterdam, The Netherlands. 
16
 * UK branch address: City House, 126-130 Hills Road, Cambridge CB2 1PQ, UK
17
 *
18
 * License: see the web/copyright.inc.php file in the file structure or
19
 *          <base_url>/copyright.php after deploying the software
20
 */
21
22
/**
23
 * This file contains Federation, IdP and Profile classes.
24
 * These should be split into separate files later.
25
 *
26
 * @package Developer
27
 */
28
/**
29
 * 
30
 */
31
32
namespace core;
33
use Exception;
34
35
/**
36
 * This class represents an Entity with properties stored in the DB.
37
 * IdPs have properties of their own, and may have one or more Profiles. The
38
 * profiles can override the institution-wide properties.
39
 *
40
 * @author Stefan Winter <[email protected]>
41
 * @author Tomasz Wolniewicz <[email protected]>
42
 *
43
 * @license see LICENSE file in root directory
44
 */
45
abstract class EntityWithDBProperties extends \core\common\Entity {
46
47
    /**
48
     * This variable gets initialised with the known IdP attributes in the constructor. It never gets updated until the object
49
     * is destroyed. So if attributes change in the database, and IdP attributes are to be queried afterwards, the object
50
     * needs to be re-instantiated to have current values in this variable.
51
     * 
52
     * @var array of entity's attributes
53
     */
54
    protected $attributes;
55
56
    /**
57
     * The database to query for attributes regarding this entity
58
     * 
59
     * @var string DB type
60
     */
61
    protected $databaseType;
62
63
    /**
64
     * This variable contains the name of the table that stores the entity's options
65
     * 
66
     * @var string DB table name
67
     */
68
    protected $entityOptionTable;
69
70
    /**
71
     * column name to find entity in that table
72
     * 
73
     * @var string DB column name of entity
74
     */
75
    protected $entityIdColumn;
76
77
    /**
78
     * We need database access. Be sure to instantiate the singleton, and then
79
     * use its instance (rather than always accessing everything statically)
80
     * 
81
     * @var DBConnection the instance of the default database we talk to usually
82
     */
83
    protected $databaseHandle;
84
85
    /**
86
     * the unique identifier of this entity instance
87
     * refers to the integer row name in the DB -> int; Federation has no own
88
     * DB, so the identifier is of no use there -> use Fedearation->$tld
89
     * 
90
     * @var int identifier of the entity instance
91
     */
92
    public $identifier;
93
94
    /**
95
     * the name of the entity in the current locale
96
     */
97
    public $name;
98
99
    /**
100
     * The constructor initialises the entity. Since it has DB properties,
101
     * this means the DB connection is set up for it.
102
     */
103
    public function __construct() {
104
        parent::__construct();
105
        // we are called after the sub-classes have declared their default
106
        // databse instance in $databaseType
107
        $this->databaseHandle = DBConnection::handle($this->databaseType);
108
        $this->attributes = [];
109
    }
110
111
    /**
112
     * How is the object identified in the database?
113
     * @return string|int
114
     * @throws Exception
115
     */
116
    private function getRelevantIdentifier() {
117
        switch (get_class($this)) {
118
            case "core\ProfileRADIUS":
119
            case "core\ProfileSilverbullet":
120
            case "core\IdP":
121
                return $this->identifier;
122
            case "core\Federation":
123
                return $this->tld;
124
            case "core\User":
125
                return $this->userName;
126
            default:
127
                throw new Exception("Operating on a class where we don't know the relevant identifier in the DB - ".get_class($this)."!");
128
        }
129
    }
130
    
131
    /**
132
     * This function retrieves the entity's attributes. 
133
     * 
134
     * If called with the optional parameter, only attribute values for the attribute
135
     * name in $optionName are retrieved; otherwise, all attributes are retrieved.
136
     * The retrieval is in-memory from the internal attributes class member - no
137
     * DB callback, so changes in the database during the class instance lifetime
138
     * are not considered.
139
     *
140
     * @param string $optionName optionally, the name of the attribute that is to be retrieved
141
     * @return array of arrays of attributes which were set for this IdP
142
     */
143
    public function getAttributes(string $optionName = NULL) {
144
        if ($optionName !== NULL) {
145
            $returnarray = [];
146
            foreach ($this->attributes as $theAttr) {
147
                if ($theAttr['name'] == $optionName) {
148
                    $returnarray[] = $theAttr;
149
                }
150
            }
151
            return $returnarray;
152
        }
153
        return $this->attributes;
154
    }
155
    
156
    /**
157
     * deletes all attributes in this profile except the _file ones, these are reported as array
158
     *
159
     * @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.
160
     * @return array list of row id's of file-based attributes which weren't deleted
161
     */
162
    public function beginFlushAttributes($extracondition = "") {
163
        $quotedIdentifier = (!is_int($this->getRelevantIdentifier()) ? "\"" : "") . $this->getRelevantIdentifier() . (!is_int($this->getRelevantIdentifier()) ? "\"" : "");
164
        $this->databaseHandle->exec("DELETE FROM $this->entityOptionTable WHERE $this->entityIdColumn = $quotedIdentifier AND option_name NOT LIKE '%_file' $extracondition");
165
        $this->updateFreshness();
166
        $execFlush = $this->databaseHandle->exec("SELECT row FROM $this->entityOptionTable WHERE $this->entityIdColumn = $quotedIdentifier $extracondition");
167
        $returnArray = [];
168
        // SELECT always returns a resourse, never a boolean
169
        while ($queryResult = mysqli_fetch_object(/** @scrutinizer ignore-type */ $execFlush)) {
170
            $returnArray[$queryResult->row] = "KILLME";
171
        }
172
        return $returnArray;
173
    }
174
175
    /**
176
     * after a beginFlushAttributes, deletes all attributes which are in the tobedeleted array.
177
     *
178
     * @param array $tobedeleted array of database rows which are to be deleted
179
     * @return void
180
     */
181
    public function commitFlushAttributes(array $tobedeleted) {
182
        $quotedIdentifier = (!is_int($this->getRelevantIdentifier()) ? "\"" : "") . $this->getRelevantIdentifier() . (!is_int($this->getRelevantIdentifier()) ? "\"" : "");
183
        foreach (array_keys($tobedeleted) as $row) {
184
            $this->databaseHandle->exec("DELETE FROM $this->entityOptionTable WHERE $this->entityIdColumn = $quotedIdentifier AND row = $row");
185
            $this->updateFreshness();
186
        }
187
    }
188
189
    /**
190
     * deletes all attributes of this entity from the database
191
     * 
192
     * @return void
193
     */
194
    public function flushAttributes() {
195
        $this->commitFlushAttributes($this->beginFlushAttributes());
196
    }
197
198
    /**
199
     * Adds an attribute for the entity instance into the database. Multiple instances of the same attribute are supported.
200
     *
201
     * @param string $attrName  Name of the attribute. This must be a well-known value from the profile_option_dict table in the DB.
202
     * @param string $attrLang  language of the attribute. Can be NULL.
203
     * @param mixed  $attrValue Value of the attribute. Can be anything; will be stored in the DB as-is.
204
     * @return void
205
     */
206
    public function addAttribute($attrName, $attrLang, $attrValue) {
207
        $relevantId = $this->getRelevantIdentifier();
208
        $identifierType = (is_int($relevantId) ? "i" : "s");
209
        $this->databaseHandle->exec("INSERT INTO $this->entityOptionTable ($this->entityIdColumn, option_name, option_lang, option_value) VALUES(?,?,?,?)", $identifierType . "sss", $relevantId, $attrName, $attrLang, $attrValue);
210
        $this->updateFreshness();
211
    }
212
213
    /**
214
     * retrieve attributes from a database. Only does SELECT queries.
215
     * @param string $query sub-classes set the query to execute to get to the options
216
     * @param string $level the retrieved options get flagged with this "level" identifier
217
     * @return array the attributes in one array
218
     */
219
    protected function retrieveOptionsFromDatabase($query, $level) {
220
        if (substr($query, 0, 6) != "SELECT") {
221
            throw new Exception("This function only operates with SELECT queries!");
222
        }
223
        $optioninstance = Options::instance();
224
        $tempAttributes = [];
225
        $relevantId = $this->getRelevantIdentifier();
226
        $attributeDbExec = $this->databaseHandle->exec($query, is_int($relevantId) ? "i" : "s", $relevantId);
227
        if (empty($attributeDbExec)) {
228
            return $tempAttributes;
229
        }
230
        // with SELECTs, we always operate on a resource, not a boolean
231
        while ($attributeQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $attributeDbExec)) {
232
            $optinfo = $optioninstance->optionType($attributeQuery->option_name);
233
            $flag = $optinfo['flag'];
234
            $decoded = $attributeQuery->option_value;
235
            // file attributes always get base64-decoded.
236
            if ($optinfo['type'] == 'file') {
237
                $decoded = base64_decode($decoded);
238
            }
239
            $tempAttributes[] = ["name" => $attributeQuery->option_name, "lang" => $attributeQuery->option_lang, "value" => $decoded, "level" => $level, "row" => $attributeQuery->row, "flag" => $flag];
240
        }
241
        return $tempAttributes;
242
    }
243
244
    /**
245
     * Retrieves data from the underlying tables, for situations where instantiating the IdP or Profile object is inappropriate
246
     * 
247
     * @param string $table institution_option or profile_option
248
     * @param string $row   rowindex
249
     * @return string|boolean the data, or FALSE if something went wrong
250
     */
251
    public static function fetchRawDataByIndex($table, $row) {
252
        // only for select tables!
253
        if ($table != "institution_option" && $table != "profile_option" && $table != "federation_option") {
254
            return FALSE;
255
        }
256
        if (!is_numeric($row)) {
257
            return FALSE;
258
        }
259
260
        $handle = DBConnection::handle("INST");
261
        $blobQuery = $handle->exec("SELECT option_value from $table WHERE row = $row");
262
        // SELECT -> returns resource, not boolean
263
        $dataset = mysqli_fetch_row(/** @scrutinizer ignore-type */ $blobQuery);
264
        return $dataset[0] ?? FALSE;
265
    }
266
267
    /**
268
     * Checks if a raw data pointer is public data (return value FALSE) or if 
269
     * yes who the authorised admins to view it are (return array of user IDs)
270
     * 
271
     * @param string $table which database table is this about
272
     * @param int    $row   row index of the table
273
     * @return mixed FALSE if the data is public, an array of owners of the data if it is NOT public
274
     */
275
    public static function isDataRestricted($table, $row) {
276
        if ($table != "institution_option" && $table != "profile_option" && $table != "federation_option" && $table != "user_options") {
277
            return []; // better safe than sorry: that's an error, so assume nobody is authorised to act on that data
278
        }
279
        // we need to create our own DB handle as this is a static method
280
        $handle = DBConnection::handle("INST");
281
        switch ($table) {
282
            case "profile_option": // both of these are similar
283
                $columnName = "profile_id";
284
                // fall-through intended
285
            case "institution_option":
286
                $blobId = -1;
287
                $columnName = $columnName ?? "institution_id";
288
                $blobQuery = $handle->exec("SELECT $columnName as id from $table WHERE row = ?", "i", $row);
289
                // SELECT always returns a resourse, never a boolean
290
                while ($idQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $blobQuery)) { // only one row
291
                    $blobId = $idQuery->id;
292
                }
293
                if ($blobId == -1) {
294
                    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.
295
                }
296
                
297
                if ($table == "profile_option") { // is the profile in question public?
298
                    $profile = ProfileFactory::instantiate($blobId);
299
                    if ($profile->readinessLevel() == AbstractProfile::READINESS_LEVEL_SHOWTIME) { // public data
300
                        return FALSE;
301
                    }
302
                    // okay, so it's NOT public. prepare to return the owner
303
                    $inst = new IdP($profile->institution);
304
                } else { // does the IdP have at least one public profile?
305
                    $inst = new IdP($blobId);
306
                    // if at least one of the profiles belonging to the inst is public, the data is public
307
                    if ($inst->maxProfileStatus() == IdP::PROFILES_SHOWTIME) { // public data
308
                        return FALSE;
309
                    }
310
                }
311
                // okay, so it's NOT public. return the owner
312
                return $inst->listOwners();
313
            case "federation_option":
314
                // federation metadata is always public
315
                return FALSE;
316
            // user options are never public
317
            case "user_options":
318
                return [];
319
            default:
320
                return []; // better safe than sorry: that's an error, so assume nobody is authorised to act on that data
321
        }
322
    }
323
324
    /**
325
     * when options in the DB change, this can mean generated installers become stale. sub-classes must define whether this is the case for them
326
     * 
327
     * @return void
328
     */
329
    abstract public function updateFreshness();
330
}
331