Completed
Push — master ( 01c28b...0d4f0a )
by Andreas
17:26
created

midcom_connection::is_connected()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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