Passed
Push — master ( 018ad3...689ead )
by Andreas
20:46
created

midcom_connection::get_error_string()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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