Completed
Push — master ( 10885e...e41e62 )
by Andreas
13:56
created

midcom_connection::is_admin()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @package midcom
4
 * @author CONTENT CONTROL http://www.contentcontrol-berlin.de/
5
 * @copyright CONTENT CONTROL http://www.contentcontrol-berlin.de/
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
use midgard\portable\storage\connection;
10
use midgard\portable\api\error\exception as mgd_exception;
11
use midgard\portable\api\mgdobject;
12
13
/**
14
 * Wrapper for Midgard-related functionality
15
 *
16
 * @package midcom
17
 */
18
class midcom_connection
19
{
20
    /**
21
     * Private cache for connection information
22
     *
23
     * @var array
24
     */
25
    private static $_data = [];
26
27
    /**
28
     * DB connection setup routine
29
     *
30
     * @param string $basedir The directory to look for config files if necessary
31
     * @throws Exception We use regular exceptions here, because this might run before things are properly set up
32
     * @return boolean Indicating success
33
     */
34
    public static function setup($basedir = null)
35
    {
36
        if (file_exists($basedir . 'config/midgard-portable.inc.php')) {
37
            include $basedir . 'config/midgard-portable.inc.php';
38
            return midgard_connection::get_instance()->is_connected();
39
        }
40
        if (file_exists($basedir . 'config/midgard-portable-default.inc.php')) {
41
            include $basedir . 'config/midgard-portable-default.inc.php';
42
            //default config has in-memory db, so all the tables may be missing
43
            return midgard_storage::class_storage_exists('midgard_user');
44
        }
45
        throw new Exception("Could not connect to database, configuration file not found");
46
    }
47
48
    /**
49
     * Check whether Midgard database connection exists
50
     *
51
     * @return boolean
52
     */
53
    static function is_connected()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
54
    {
55
        return midgard_connection::get_instance()->is_connected();
56
    }
57
58
    /**
59
     * Set Midgard log level
60
     *
61
     * @param string $loglevel Midgard log level
62
     */
63
    static function set_loglevel($loglevel)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
64
    {
65
        return midgard_connection::get_instance()->set_loglevel($loglevel);
66
    }
67
68
    /**
69
     * Set Midgard error code
70
     *
71
     * @param int $errorcode Midgard error code
72
     */
73 8
    public static function set_error($errorcode)
74
    {
75 8
        return midgard_connection::get_instance()->set_error($errorcode);
76
    }
77
78
    /**
79
     * Get Midgard error code
80
     *
81
     * @return int Midgard error code
82
     */
83 70
    public static function get_error()
84
    {
85 70
        return midgard_connection::get_instance()->get_error();
86
    }
87
88
    /**
89
     * Get Midgard error message
90
     *
91
     * @return string Midgard error message
92
     */
93 72
    public static function get_error_string()
94
    {
95 72
        return midgard_connection::get_instance()->get_error_string();
96
    }
97
98
    /**
99
     * Perform a login against the midgard backend
100
     *
101
     * @param string $username The username as entered
102
     * @param string $password The password as entered
103
     * @param boolean $trusted Use trusted auth
104
     * @return boolean|midgard_user The appropriate object or false
105
     */
106 58
    public static function login($username, $password, $trusted = false)
107
    {
108
        $login_tokens = [
109 58
            'login' => $username,
110 58
            'authtype' => midcom::get()->config->get('auth_type'),
111
        ];
112
113
        try {
114 58
            $user = new midgard_user($login_tokens);
115
        } catch (mgd_exception $e) {
116
            return false;
117
        }
118 58
        if (!$trusted && !self::verify_password($password, $user->password)) {
119 1
            return false;
120
        }
121
122 58
        if (!$user->login()) {
123
            return false;
124
        }
125 58
        return $user;
126
    }
127
128 63
    public static function verify_password($password, $hash)
129
    {
130 63
        if (midcom::get()->config->get('auth_type') == 'Legacy') {
131 63
            return password_verify($password, $hash);
132
        }
133
        if (midcom::get()->config->get('auth_type') == 'SHA256') {
134
            $password = hash('sha256', $password);
135
        }
136
137
        return $password === $hash;
138
    }
139
140 81
    public static function prepare_password($password)
141
    {
142 81
        if (midcom::get()->config->get('auth_type') == 'Legacy') {
143 81
            return password_hash($password, PASSWORD_DEFAULT);
144
        }
145
        if (midcom::get()->config->get('auth_type') == 'SHA256') {
146
            return hash('sha256', $password);
147
        }
148
149
        return $password;
150
    }
151
152 1
    public static function is_user($person)
153
    {
154 1
        if (empty($person->guid)) {
155
            return false;
156
        }
157 1
        $qb = new midgard_query_builder('midgard_user');
158 1
        $qb->add_constraint('person', '=', $person->guid);
159 1
        return $qb->count() > 0;
160
    }
161
162
    /**
163
     * Get current Midgard user
164
     *
165
     * @return int The current user ID
166
     */
167 81
    public static function get_user()
168
    {
169 81
        if ($user = midgard_connection::get_instance()->get_user()) {
170 41
            return $user->get_person()->id;
171
        }
172 40
        return 0;
173
    }
174
175
    /**
176
     * Check if the current user is admin
177
     *
178
     * @return boolean True or false
179
     */
180
    public static function is_admin()
181
    {
182
        if ($user = midgard_connection::get_instance()->get_user()) {
183
            return $user->is_admin();
184
        }
185
        return false;
186
    }
187
188
    /**
189
     * Logout the current user, if any
190
     */
191 1
    public static function logout()
192
    {
193 1
        if ($user = midgard_connection::get_instance()->get_user()) {
194 1
            $user->logout();
195
        }
196 1
    }
197
198 409
    private static function _get($key)
199
    {
200 409
        if (isset(self::$_data[$key])) {
201 409
            return self::$_data[$key];
202
        }
203
204 1
        return null;
205
    }
206
207
    /**
208
     * Lists all available MgdSchema types
209
     *
210
     * @return array A list of class names
211
     */
212 7
    public static function get_schema_types()
213
    {
214 7
        if (!isset(self::$_data['schema_types'])) {
215
            $classnames = connection::get_em()->getConfiguration()->getMetadataDriverImpl()->getAllClassNames();
216
217
            self::$_data['schema_types'] = array_filter($classnames, function($input) {
218
                return is_subclass_of($input, mgdobject::class);
219
            });
220
        }
221 7
        return self::$_data['schema_types'];
222
    }
223
224
    /**
225
     * Get various pieces of information extracted from the URL
226
     *
227
     * @return mixed The data for the requested key or null if it doesn't exist
228
     */
229 409
    public static function get_url($key)
230
    {
231 409
        static $parsed = false;
232 409
        if (!$parsed) {
233
            $url_components = parse_url("http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
234
            if (OPENPSA2_PREFIX !== '/') {
235
                $url_components['path'] = preg_replace('|^' . OPENPSA2_PREFIX . '|', '/', $url_components['path']);
236
            }
237
            self::_parse_url($url_components['path'], OPENPSA2_PREFIX, substr(OPENPSA2_PREFIX, 0, -1));
238
            $parsed = true;
239
        }
240
241 409
        return self::_get($key);
242
    }
243
244
    /**
245
     * Enables themes to have subdirectories (which have a similar effect to mgd1 pages)
246
     *
247
     * @param string $uri The request path
248
     * @param string $self The instance's root URL
249
     * @param string $prefix The root URL's prefix, if any (corresponds to mgd1 host)
250
     */
251 1
    private static function _parse_url($uri, $self, $prefix)
252
    {
253 1
        $uri = preg_replace('/\/[\/]+/i', '/', $uri);
254 1
        $path_parts = explode('/', $uri);
255 1
        $page_style = '';
256 1
        $path = $self;
257
258 1
        self::$_data['argv'] = [];
259 1
        $args_started = false;
260 1
        foreach ($path_parts as $part) {
261 1
            if ($part === '') {
262 1
                continue;
263
            }
264 1
            if (    midcom::get()->config->get('theme')
265 1
                 && !$args_started
266 1
                 && self::check_page_exists($part)) {
267
                $page_style .= '/' . $part;
268
                $self .= $part . '/';
269
            } else {
270 1
                self::$_data['argv'][] = $part;
271 1
                $path .= $part . '/';
272 1
                $args_started = true;
273
            }
274
        }
275
276 1
        self::$_data['page_style'] = $page_style;
277 1
        self::$_data['uri'] = $path;
278 1
        self::$_data['self'] = $self;
279 1
        self::$_data['prefix'] = $prefix;
280 1
    }
281
282
283
    /**
284
     * Iterate through possible page directories in style-tree and check if the page exists (as a folder).
285
     *
286
     * @param string $page_name
287
     */
288 1
    private static function check_page_exists($page_name)
289
    {
290 1
        $path_array = explode('/', midcom::get()->config->get('theme'));
291
292 1
        while (!empty($path_array)) {
293 1
            $theme_path = implode('/', $path_array);
294 1
            if (is_dir(OPENPSA2_THEME_ROOT . $theme_path . '/style/' . $page_name)) {
295
                return true;
296
            }
297 1
            array_pop($path_array);
298
        }
299 1
        return false;
300
    }
301
302 1
    public static function get_unique_host_name()
303
    {
304 1
        if (null === self::_get('unique_host_name')) {
305 1
            self::$_data['unique_host_name'] = str_replace(':', '_', $_SERVER['SERVER_NAME']) . '_' . str_replace('/', '_', self::get_url('prefix'));
306
        }
307
308 1
        return self::$_data['unique_host_name'];
309
    }
310
}
311