File: MetaDataStorageHandlerSerialize.php

package info (click to toggle)
simplesamlphp 1.19.7-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 42,920 kB
  • sloc: php: 202,044; javascript: 14,867; xml: 2,700; sh: 225; perl: 82; makefile: 70; python: 5
file content (310 lines) | stat: -rw-r--r-- 8,703 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
<?php

declare(strict_types=1);

namespace SimpleSAML\Metadata;

use SimpleSAML\Configuration;
use SimpleSAML\Logger;
use SimpleSAML\Utils;

/**
 * Class for handling metadata files in serialized format.
 *
 * @package SimpleSAMLphp
 */

class MetaDataStorageHandlerSerialize extends MetaDataStorageSource
{
    /**
     * The file extension we use for our metadata files.
     *
     * @var string
     */
    public const EXTENSION = '.serialized';


    /**
     * The base directory where metadata is stored.
     *
     * @var string
     */
    private $directory = '/';


    /**
     * Constructor for this metadata handler.
     *
     * Parses configuration.
     *
     * @param array $config The configuration for this metadata handler.
     */
    public function __construct($config)
    {
        assert(is_array($config));

        $globalConfig = Configuration::getInstance();

        $cfgHelp = Configuration::loadFromArray($config, 'serialize metadata source');

        $this->directory = $cfgHelp->getString('directory');

        /* Resolve this directory relative to the SimpleSAMLphp directory (unless it is
         * an absolute path).
         */
        $this->directory = Utils\System::resolvePath($this->directory, $globalConfig->getBaseDir());
    }


    /**
     * Helper function for retrieving the path of a metadata file.
     *
     * @param string $entityId The entity ID.
     * @param string $set The metadata set.
     *
     * @return string The path to the metadata file.
     */
    private function getMetadataPath(string $entityId, string $set): string
    {
        return $this->directory . '/' . rawurlencode($set) . '/' . rawurlencode($entityId) . self::EXTENSION;
    }


    /**
     * Retrieve a list of all available metadata sets.
     *
     * @return array An array with the available sets.
     */
    public function getMetadataSets()
    {
        $ret = [];

        $dh = @opendir($this->directory);
        if ($dh === false) {
            Logger::warning(
                'Serialize metadata handler: Unable to open directory: ' . var_export($this->directory, true)
            );
            return $ret;
        }

        while (($entry = readdir($dh)) !== false) {
            if ($entry[0] === '.') {
                // skip '..', '.' and hidden files
                continue;
            }

            $path = $this->directory . '/' . $entry;

            if (!is_dir($path)) {
                Logger::warning(
                    'Serialize metadata handler: Metadata directory contained a file where only directories should ' .
                    'exist: ' . var_export($path, true)
                );
                continue;
            }

            $ret[] = rawurldecode($entry);
        }

        closedir($dh);

        return $ret;
    }


    /**
     * Retrieve a list of all available metadata for a given set.
     *
     * @param string $set The set we are looking for metadata in.
     *
     * @return array An associative array with all the metadata for the given set.
     */
    public function getMetadataSet($set)
    {
        assert(is_string($set));

        $ret = [];

        $dir = $this->directory . '/' . rawurlencode($set);
        if (!is_dir($dir)) {
            // probably some code asked for a metadata set which wasn't available
            return $ret;
        }

        $dh = @opendir($dir);
        if ($dh === false) {
            Logger::warning(
                'Serialize metadata handler: Unable to open directory: ' . var_export($dir, true)
            );
            return $ret;
        }

        $extLen = strlen(self::EXTENSION);

        while (($file = readdir($dh)) !== false) {
            if (strlen($file) <= $extLen) {
                continue;
            }

            if (substr($file, -$extLen) !== self::EXTENSION) {
                continue;
            }

            $entityId = substr($file, 0, -$extLen);
            $entityId = rawurldecode($entityId);

            $md = $this->getMetaData($entityId, $set);
            if ($md !== null) {
                $ret[$entityId] = $md;
            }
        }

        closedir($dh);

        return $ret;
    }


    /**
     * Retrieve a metadata entry.
     *
     * @param string $index The entityId we are looking up.
     * @param string $set The set we are looking for metadata in.
     *
     * @return array|null An associative array with metadata for the given entity, or NULL if we are unable to
     *         locate the entity.
     */
    public function getMetaData($index, $set)
    {
        assert(is_string($index));
        assert(is_string($set));

        $filePath = $this->getMetadataPath($index, $set);

        if (!file_exists($filePath)) {
            return null;
        }

        $data = @file_get_contents($filePath);
        if ($data === false) {
            /** @var array $error */
            $error = error_get_last();
            Logger::warning(
                'Error reading file ' . $filePath . ': ' . $error['message']
            );
            return null;
        }

        $data = @unserialize($data);
        if ($data === false) {
            Logger::warning('Error unserializing file: ' . $filePath);
            return null;
        }

        if (!array_key_exists('entityid', $data)) {
            $data['entityid'] = $index;
        }

        return $data;
    }


    /**
     * Save a metadata entry.
     *
     * @param string $entityId The entityId of the metadata entry.
     * @param string $set The metadata set this metadata entry belongs to.
     * @param array $metadata The metadata.
     *
     * @return bool True if successfully saved, false otherwise.
     */
    public function saveMetadata($entityId, $set, $metadata)
    {
        assert(is_string($entityId));
        assert(is_string($set));
        assert(is_array($metadata));

        $filePath = $this->getMetadataPath($entityId, $set);
        $newPath = $filePath . '.new';

        $dir = dirname($filePath);
        if (!is_dir($dir)) {
            Logger::info('Creating directory: ' . $dir);
            $res = @mkdir($dir, 0777, true);
            if ($res === false) {
                /** @var array $error */
                $error = error_get_last();
                Logger::error('Failed to create directory ' . $dir . ': ' . $error['message']);
                return false;
            }
        }

        $data = serialize($metadata);

        Logger::debug('Writing: ' . $newPath);

        $res = file_put_contents($newPath, $data);
        if ($res === false) {
            /** @var array $error */
            $error = error_get_last();
            Logger::error('Error saving file ' . $newPath . ': ' . $error['message']);
            return false;
        }

        $res = rename($newPath, $filePath);
        if ($res === false) {
            /** @var array $error */
            $error = error_get_last();
            Logger::error('Error renaming ' . $newPath . ' to ' . $filePath . ': ' . $error['message']);
            return false;
        }

        return true;
    }


    /**
     * Delete a metadata entry.
     *
     * @param string $entityId The entityId of the metadata entry.
     * @param string $set The metadata set this metadata entry belongs to.
     * @return void
     */
    public function deleteMetadata($entityId, $set)
    {
        assert(is_string($entityId));
        assert(is_string($set));

        $filePath = $this->getMetadataPath($entityId, $set);

        if (!file_exists($filePath)) {
            Logger::warning(
                'Attempted to erase nonexistent metadata entry ' .
                var_export($entityId, true) . ' in set ' . var_export($set, true) . '.'
            );
            return;
        }

        $res = unlink($filePath);
        if ($res === false) {
            /** @var array $error */
            $error = error_get_last();
            Logger::error(
                'Failed to delete file ' . $filePath .
                ': ' . $error['message']
            );
        }
    }

    /**
     * This function loads the metadata for entity IDs in $entityIds. It is returned as an associative array
     * where the key is the entity id. An empty array may be returned if no matching entities were found
     * @param array $entityIds The entity ids to load
     * @param string $set The set we want to get metadata from.
     * @return array An associative array with the metadata for the requested entities, if found.
     */
    public function getMetaDataForEntities(array $entityIds, $set)
    {
        return $this->getMetaDataForEntitiesIndividually($entityIds, $set);
    }
}