Passed
Push — master ( 7dcdd9...287ee3 )
by Stefan
08:07 queued 17s
created

EntityWithDBProperties::commitFlushAttributes()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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