Passed
Push — master ( 2bb8d1...bedc70 )
by Stefan
03:11
created

Entity::uuid()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 2
1
<?php
2
3
/*
4
 * ******************************************************************************
5
 * Copyright 2011-2017 DANTE Ltd. and GÉANT on behalf of the GN3, GN3+, GN4-1 
6
 * and GN4-2 consortia
7
 *
8
 * License: see the web/copyright.php file in the file structure
9
 * ******************************************************************************
10
 */
11
12
/**
13
 * This file contains Federation, IdP and Profile classes.
14
 * These should be split into separate files later.
15
 *
16
 * @package Developer
17
 */
18
/**
19
 * 
20
 */
21
22
namespace core\common;
23
24
use Exception;
25
26
/**
27
 * This class represents an Entity in its widest sense. Every entity can log
28
 * and query/change the language settings where needed.
29
 *
30
 * @author Stefan Winter <[email protected]>
31
 * @author Tomasz Wolniewicz <[email protected]>
32
 *
33
 * @license see LICENSE file in root directory
34
 *
35
 * @package Developer
36
 */
37
abstract class Entity {
38
39
    const L_OK = 0;
40
    const L_REMARK = 4;
41
    const L_WARN = 32;
42
    const L_ERROR = 256;
43
44
    /**
45
     * We occasionally log stuff (debug/audit). Have an initialised Logging
46
     * instance nearby is sure helpful.
47
     * 
48
     * @var Logging
49
     */
50
    protected $loggerInstance;
51
52
    /**
53
     * access to language settings to be able to switch textDomain
54
     * 
55
     * @var Language
56
     */
57
    protected $languageInstance;
58
59
    /**
60
     * initialise the entity.
61
     * 
62
     * Logs the start of lifetime of the entity to the debug log on levels 3 and higher.
63
     */
64
    public function __construct() {
65
        $this->loggerInstance = new Logging();
66
        $this->loggerInstance->debug(3, "--- BEGIN constructing class " . get_class($this) . " .\n");
67
        $this->languageInstance = new Language();
68
    }
69
70
    /**
71
     * destroys the entity.
72
     * 
73
     * Logs the end of lifetime of the entity to the debug log on level 5.
74
     */
75
    public function __destruct() {
76
        (new Logging())->debug(5, "--- KILL Destructing class " . get_class($this) . " .\n");
77
    }
78
79
    /**
80
     * This is a helper fuction to retrieve a value from two-dimensional arrays
81
     * The function tests if the value for the first indes is defined and then
82
     * the same with the second and finally returns the value
83
     * if something on the way is not defined, NULL is returned
84
     * 
85
     * @param array $attributeArray 
86
     * @param string|int $index1 
87
     * @param string|int $index2
88
     * @return mixed
89
     */
90
    public static function getAttributeValue($attributeArray, $index1, $index2) {
91
        if (isset($attributeArray[$index1]) && isset($attributeArray[$index1][$index2])) {
92
            return($attributeArray[$index1][$index2]);
93
        } else {
94
            return(NULL);
95
        }
96
    }
97
98
    /**
99
     * create a temporary directory and return the location
100
     * @param string $purpose one of 'installer', 'logo', 'test' defined the purpose of the directory
101
     * @param bool $failIsFatal decides if a creation failure should cause an error; defaults to true
102
     * @return array the tuple of: base path, absolute path for directory, directory name
103
     */
104
    public function createTemporaryDirectory($purpose = 'installer', $failIsFatal = 1) {
105
        $loggerInstance = new Logging();
106
        $name = md5(time() . rand());
107
        $path = ROOT;
108
        switch ($purpose) {
109
            case 'silverbullet':
110
                $path .= '/var/silverbullet';
111
                break;
112
            case 'installer':
113
                $path .= '/var/installer_cache';
114
                break;
115
            case 'logo':
116
                $path .= '/web/downloads/logos';
117
                break;
118
            case 'test':
119
                $path .= '/var/tmp';
120
                break;
121
            default:
122
                throw new Exception("unable to create temporary directory due to unknown purpose: $purpose\n");
123
        }
124
        $tmpDir = $path . '/' . $name;
125
        $loggerInstance->debug(4, "temp dir: $purpose : $tmpDir\n");
126
        if (!mkdir($tmpDir, 0700, true)) {
127
            if ($failIsFatal) {
128
                throw new Exception("unable to create temporary directory: $tmpDir\n");
129
            }
130
            $loggerInstance->debug(4, "Directory creation failed for $tmpDir\n");
131
            return ['base' => $path, 'dir' => '', $name => ''];
132
        }
133
        $loggerInstance->debug(4, "Directory created: $tmpDir\n");
134
        return ['base' => $path, 'dir' => $tmpDir, 'name' => $name];
135
    }
136
137
    /**
138
     * this direcory delete function has been copied from PHP documentation
139
     * 
140
     * @param string $dir name of the directory to delete
141
     */
142
    public static function rrmdir($dir) {
143
        foreach (glob($dir . '/*') as $file) {
144
            if (is_dir($file)) {
145
                Entity::rrmdir($file);
146
            } else {
147
                unlink($file);
148
            }
149
        }
150
        rmdir($dir);
151
    }
152
153
    /**
154
     * generates a UUID, for the devices which identify file contents by UUID
155
     *
156
     * @param string $prefix an extra prefix to set before the UUID
157
     * @return string UUID (possibly prefixed)
158
     */
159
    public static function uuid($prefix = '', $deterministicSource = NULL) {
160
        if ($deterministicSource === NULL) {
161
            $chars = md5(uniqid(mt_rand(), true));
162
        } else {
163
            $chars = md5($deterministicSource);
164
        }
165
        // these substr() are guaranteed to yield actual string data, as the
166
        // base string is an MD5 hash - has sufficient length
167
        $uuid = /** @scrutinizer ignore-type */ substr($chars, 0, 8) . '-';
168
        $uuid .= /** @scrutinizer ignore-type */ substr($chars, 8, 4) . '-';
169
        $uuid .= /** @scrutinizer ignore-type */ substr($chars, 12, 4) . '-';
170
        $uuid .= /** @scrutinizer ignore-type */ substr($chars, 16, 4) . '-';
171
        $uuid .= /** @scrutinizer ignore-type */ substr($chars, 20, 12);
172
        return $prefix . $uuid;
173
    }
174
    
175
        /**
176
     * produces a random string
177
     * @param int $length the length of the string to produce
178
     * @param string $keyspace the pool of characters to use for producing the string
179
     * @return string
180
     * @throws Exception
181
     */
182
    public static function randomString(
183
    $length, $keyspace = '23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
184
    ) {
185
        $str = '';
186
        $max = strlen($keyspace) - 1;
187
        if ($max < 1) {
188
            throw new Exception('$keyspace must be at least two characters long');
189
        }
190
        for ($i = 0; $i < $length; ++$i) {
191
            $str .= $keyspace[random_int(0, $max)];
192
        }
193
        return $str;
194
    }
195
196
}
197