Debian Codegraph @

classes/Core.php

raw symbols SCIP
1 <?php
2
3 /**
4 * dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
5 * Copyright (C) 2020-2025 Aleksey Andreev (liuch)
6 *
7 * Available at:
8 * https://github.com/liuch/dmarc-srg
9 *
10 * This program is free software: you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the Free
12 * Software Foundation, either version 3 of the License.
13 *
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
17 * more details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * this program. If not, see <http://www.gnu.org/licenses/>.
21 *
22 * =========================
23 *
24 * This file contains the Core class
25 *
26 * @category API
27 * @package DmarcSrg
28 * @author Aleksey Andreev (liuch)
29 * @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
30 */
31
32 namespace Liuch\DmarcSrg;
33
34 use Liuch\DmarcSrg\Users\User;
35 use Liuch\DmarcSrg\Users\DbUser;
36 use Liuch\DmarcSrg\Users\UserList;
37 use Liuch\DmarcSrg\Users\AdminUser;
38 use Liuch\DmarcSrg\Exception\SoftException;
39 use Liuch\DmarcSrg\Exception\LogicException;
40 use Liuch\DmarcSrg\Exception\ForbiddenException;
41
42 /**
43 * It's class for accessing to most methods for working with http, json data,
44 * getting instances of some classes
45 */
46 class Core
47 {
48 private $user = null;
49 private $modules = [];
50 private $template = null;
51
52 /** @var self|null */
53 private static $instance = null;
54
55 /**
56 * The constructor
57 *
58 * @param array $params Array with modules to be bind to
59 */
60 public function __construct($params)
61 {
62 foreach ([ 'admin', 'auth', 'config', 'database', 'ehandler', 'session', 'status' ] as $key) {
63 if (isset($params[$key])) {
64 $this->modules[$key] = $params[$key];
65 }
66 }
67 if (isset($params['template'])) {
68 $this->template = $params['template'];
69 }
70 if (!self::$instance) {
71 self::$instance = $this;
72 }
73 }
74
75 /**
76 * Returns the method of the current http request.
77 *
78 * @return string http method
79 */
80 public static function requestMethod(): string
81 {
82 return $_SERVER['REQUEST_METHOD'];
83 }
84
85 /**
86 * Determines whether the current invocation is being run via a web server
87 *
88 * @return bool
89 */
90 public static function isWEB(): bool
91 {
92 return isset($_SERVER['REQUEST_METHOD']);
93 }
94
95 /**
96 * Returns an instance of the current user
97 *
98 * @return User|null
99 */
100 public function getCurrentUser()
101 {
102 $session = $this->session();
103 if (!$this->auth()->isEnabled()) {
104 return $this->user = new AdminUser($this);
105 }
106
107 if (!$this->user) {
108 $data = $session->getData();
109 if (isset($data['user']) && gettype($data['user']) == 'array') {
110 if ($data['user']['name'] === 'admin') {
111 if (($data['user']['id'] ?? -1) !== 0 || ($data['user']['level'] ?? -1) !== User::LEVEL_ADMIN) {
112 throw new ForbiddenException('The user session has been broken!');
113 }
114 $this->user = new AdminUser($this);
115 $session->commit();
116 } elseif ($this->config('users/user_management', false)) {
117 try {
118 $this->user = new DbUser($data['user'], $this->database());
119 $cts = (new DateTime())->getTimestamp();
120 if (($data['s_time'] ?? 0) + 5 <= $cts) {
121 if (isset($data['s_id']) &&
122 $this->user->session() === $data['s_id'] &&
123 $this->user->isEnabled()
124 ) {
125 $data['s_time'] = $cts;
126 $data['user']['level'] = $this->user->level();
127 $session->setData($data);
128 $session->commit();
129 } else {
130 $this->user = null;
131 $session->destroy();
132 }
133 } else {
134 $session->commit();
135 }
136 } catch (SoftException $e) {
137 if (!$this->user->exists()) {
138 $this->user = null;
139 $session->destroy();
140 }
141 throw $e;
142 }
143 } else {
144 $session->destroy();
145 }
146 }
147 }
148 return $this->user;
149 }
150
151 /**
152 * Sets the passed user as the current user
153 *
154 * @param User|string|null $user User (instance, name or none) to set
155 *
156 * @return void
157 */
158 public function setCurrentUser($user): void
159 {
160 if (gettype($user) == 'string') {
161 $user = UserList::getUserByName($user, $this);
162 } elseif (!is_null($user) && !($user instanceof User)) {
163 throw new LogicException('Wrong user object was passed');
164 }
165 $this->user = $user;
166 if (self::isWEB()) {
167 $session = $this->session();
168 $session->destroy();
169 if ($user) {
170 $session->setData([
171 'user' => [
172 'id' => $user->id(),
173 'name' => $user->name(),
174 'level' => $user->level()
175 ],
176 's_id' => $user->session(),
177 's_time' => (new DateTime())->getTimestamp()
178 ]);
179 $session->commit();
180 }
181 }
182 }
183
184 /**
185 * Returns true if the http request asks for json data.
186 *
187 * @return bool
188 */
189 public static function isJson(): bool
190 {
191 return ($_SERVER['HTTP_ACCEPT'] ?? '') === 'application/json';
192 }
193
194 /**
195 * Sends the html file to the client and inserts a link with a custom CSS file if necessary
196 *
197 * @return void
198 */
199 public function sendHtml(): void
200 {
201 if (is_readable($this->template)) {
202 $ccf = $this->config('custom_css', '');
203 if (substr_compare($ccf, '.css', -4) === 0) { // replacement for str_ends_with
204 $ccf = '<link rel="stylesheet" href="' . htmlspecialchars($ccf) . '" type="text/css" />';
205 } else {
206 $ccf = '';
207 }
208 $fd = fopen($this->template, 'r');
209 if ($fd) {
210 while (($buffer = fgets($fd)) !== false) {
211 if (substr_compare($buffer, "<!-- Custom CSS -->\n", -20) === 0) {
212 if (!empty($ccf)) {
213 $buffer = str_replace('<!-- Custom CSS -->', $ccf, $buffer);
214 echo $buffer;
215 }
216 } else {
217 echo $buffer;
218 }
219 }
220 fclose($fd);
221 }
222 }
223 }
224
225 /**
226 * Sends data from an array as json string to the client.
227 *
228 * @param array $data - Data to send.
229 *
230 * @return void
231 */
232 public static function sendJson(array $data): void
233 {
234 $res_str = json_encode($data);
235 if ($res_str === false) {
236 $res_str = '[]';
237 }
238 header('content-type: application/json; charset=UTF-8');
239 echo $res_str;
240 }
241
242 /**
243 * Sends a Bad Request response to the client.
244 *
245 * @return void
246 */
247 public static function sendBad(): void
248 {
249 http_response_code(400);
250 echo 'Bad request';
251 }
252
253 /**
254 * Retrieves json data from the request and return it as an array.
255 *
256 * Returns an array with data or null if there is an error.
257 *
258 * @return array|null Data from the request
259 */
260 public static function getJsonData()
261 {
262 $res = null;
263 if (($_SERVER['CONTENT_TYPE'] ?? $_SERVER['HTTP_CONTENT_TYPE'] ?? '') === 'application/json') {
264 $str = file_get_contents('php://input');
265 if ($str) {
266 $res = json_decode($str, true);
267 }
268 }
269 return $res;
270 }
271
272 /**
273 * Checks if the dependencies passed in the parameter are installed
274 *
275 * @param string $deps Comma-separated string of dependency names to be checked
276 *
277 * @return void
278 */
279 public function checkDependencies(string $deps): void
280 {
281 $adeps = explode(',', $deps);
282 $no_deps = [];
283 foreach ($adeps as $ext) {
284 $no_dep = null;
285 switch ($ext) {
286 case 'flyfs':
287 if (!class_exists('League\Flysystem\Filesystem')) {
288 $no_dep = 'Flysystem';
289 }
290 break;
291 case 'imap-engine':
292 if (!class_exists('DirectoryTree\ImapEngine\Mailbox')) {
293 $no_dep = 'ImapEngine';
294 }
295 break;
296 default:
297 if (!extension_loaded($ext)) {
298 $no_dep = 'ext-' . $ext;
299 }
300 break;
301 }
302 if ($no_dep) {
303 $no_deps[] = $no_dep;
304 $no_dep = null;
305 }
306 }
307 if (count($no_deps)) {
308 if (count($no_deps) === 1) {
309 $s1 = 'y';
310 $s2 = 'is';
311 } else {
312 $s1 = 'ies';
313 $s2 = 'are';
314 }
315 $msg = "Required dependenc$s1 $s2 missing";
316 $usr = $this->getCurrentUser();
317 if ($usr && $usr->level() === User::LEVEL_ADMIN) {
318 $msg .= ': ' . implode(', ', $no_deps) . '.';
319 } else {
320 $msg .= '. Contact the administrator.';
321 }
322 throw new SoftException($msg);
323 }
324 }
325
326 /**
327 * Returns an instance of the class Auth.
328 *
329 * @return Auth
330 */
331 public function auth()
332 {
333 return $this->getModule('auth', true);
334 }
335
336 /**
337 * Returns an instance of the class Status.
338 *
339 * @return Status instance of Status
340 */
341 public function status()
342 {
343 return $this->getModule('status', true);
344 }
345
346 /**
347 * Returns an instance of the Session class
348 *
349 * @return Session
350 */
351 public function session()
352 {
353 return $this->getModule('session', false);
354 }
355
356 /**
357 * Returns an instance of the class Admin.
358 *
359 * @return Admin instance of Admin
360 */
361 public function admin()
362 {
363 return $this->getModule('admin', true);
364 }
365
366 /**
367 * Returns an instance of the class Database.
368 *
369 * @return Database\DatabaseController
370 */
371 public function database()
372 {
373 return $this->getModule('database', true);
374 }
375
376 /**
377 * Returns an instance of the class ErrorHandler
378 *
379 * @return ErrorHandler
380 */
381 public function errorHandler()
382 {
383 return $this->getModule('ehandler', true);
384 }
385
386 /**
387 * Returns the current logger.
388 * Just a proxy method to return the logger from ErrorHandler
389 *
390 * @return Log\LoggerInterface
391 */
392 public function logger()
393 {
394 return $this->errorHandler()->logger();
395 }
396
397 /**
398 * Returns instance of the object
399 *
400 * @return self
401 */
402 public static function instance()
403 {
404 return self::$instance;
405 }
406
407 /**
408 * Returns the config value by its name
409 *
410 * @param string $name Config item name. Hierarchy supported via '/'
411 * @param mixed $default Value to be returned if the required config item is missing or null
412 *
413 * @return mixed
414 */
415 public function config(string $name, $default = null)
416 {
417 return $this->getModule('config', false)->get($name, $default);
418 }
419
420 /**
421 * Returns a module instance by its name. Lazy initialization is used.
422 *
423 * @param string $name Module name
424 * @param bool $core Whether to pass $this to the constructor
425 *
426 * @return object
427 */
428 private function getModule(string $name, bool $core)
429 {
430 $module = $this->modules[$name] ?? null;
431 switch (gettype($module)) {
432 case 'array':
433 if ($core) {
434 $module = new $module[0]($this, ...($module[1] ?? []));
435 } else {
436 $module = new $module[0](...($module[1] ?? []));
437 }
438 $this->modules[$name] = $module;
439 break;
440 case 'NULL':
441 throw new LogicException('Attempt to initiate an unloaded module ' . $name);
442 }
443 return $module;
444 }
445 }