]> jfr.im git - irc/unrealircd/unrealircd-webpanel.git/blob - inc/common.php
ec237fc8b2b0e6d7f69ae5a385a47a9ec868cef5
[irc/unrealircd/unrealircd-webpanel.git] / inc / common.php
1 <?php
2 function check_requirements()
3 {
4 if (version_compare(PHP_VERSION, '8.0.0', '<'))
5 {
6 die("This webserver is using PHP version ".PHP_VERSION." but we require at least PHP 8.0.0.<br>".
7 "If you already installed PHP8 but are still seeing this error, then it means ".
8 "apache/nginx/.. is loading an older PHP version. Eg. on Debian/Ubuntu you need ".
9 "<code>apt-get install libapache2-mod-php8.2</code> (or a similar version) and ".
10 "<code>apt-get remove libapache2-mod-php7.4</code> (or a similar version). ".
11 "You may also need to choose again the PHP module to load in apache via <code>a2enmod php8.2</code>");
12 }
13
14 $loaded_extensions = get_loaded_extensions();
15 $required_extensions = ["mbstring", "sodium"];
16 $missing_extensions = [];
17 foreach ($required_extensions as $mod)
18 if (!in_array($mod, $loaded_extensions))
19 $missing_extensions[] = $mod;
20
21 if (count($missing_extensions) > 0)
22 {
23 $text = "<html>The following PHP module(s) need to be loaded:<br>\n<ul>\n";
24 $cmd = 'apt-get install';
25 foreach($missing_extensions as $mod)
26 {
27 $text .= "<li>$mod</li>\n";
28 $cmd .= " php-$mod";
29 }
30 $text .= "</ul>\n";
31 $text .= "You need to install/enable these PHP packages and restart the webserver.<br>".
32 "If you are on Debian/Ubuntu then run <code>$cmd</code> ".
33 "and restart your webserver (eg: <code>systemctl restart apache2</code> for apache).";
34 die($text);
35 }
36 }
37
38 check_requirements(); /* very early !! */
39
40 define('UPATH', dirname(__DIR__));
41
42 function get_config($setting)
43 {
44 GLOBAL $config;
45
46 $item = $config;
47 foreach(explode("::", $setting) as $x)
48 {
49 if (isset($item[$x]))
50 $item = $item[$x];
51 else
52 return NULL;
53 }
54 return $item;
55 }
56
57 function get_current_page_helper($name, $p, &$title)
58 {
59 if (isset($p["script"]))
60 {
61 if (($p["script"] != '') && str_ends_with($_SERVER['SCRIPT_FILENAME'],$p["script"]))
62 {
63 // MATCH
64 if (isset($p["title"]))
65 $title = $p["title"];
66 else
67 $title = $name;
68 return $p;
69 }
70 return null;
71 }
72 foreach ($p as $k=>$v)
73 {
74 $ret = get_current_page_helper($k, $v, $title);
75 if ($ret !== null)
76 return $ret;
77 }
78 return null;
79 }
80
81 /** Get current page and title */
82 function get_current_page(&$title)
83 {
84 GLOBAL $pages;
85 foreach ($pages as $k=>$v)
86 {
87 $ret = get_current_page_helper($k, $v, $title);
88 if ($ret !== null)
89 return $ret;
90 }
91 }
92
93 function page_requires_no_config()
94 {
95 if (str_ends_with($_SERVER['SCRIPT_FILENAME'],"install.php") ||
96 str_ends_with($_SERVER['SCRIPT_FILENAME'],"installation.php"))
97 {
98 return TRUE;
99 }
100 return FALSE;
101 }
102
103 function page_requires_no_login()
104 {
105 if (str_ends_with($_SERVER['SCRIPT_FILENAME'],"login/index.php") ||
106 page_requires_no_config())
107 {
108 return TRUE;
109 }
110 return FALSE;
111 }
112
113 function read_config_file()
114 {
115 GLOBAL $config;
116 GLOBAL $config_transition_unreal_server;
117
118 $config = Array();
119 if (!file_exists(UPATH."/config/config.php") && file_exists(UPATH."/config.php"))
120 {
121 require_once UPATH . "/config.php";
122 require_once UPATH . "/config/compat.php";
123 }
124 if ((@include(UPATH . "/config/config.php")) !== 1)
125 return false;
126 if (isset($config['unrealircd']))
127 $config_transition_unreal_server = true;
128 /* Upgrade needed? */
129 $plugins_modified = false;
130 foreach ($config["plugins"] as $k=>$v)
131 {
132 if ($v == "sql_auth")
133 {
134 $config["plugins"][$k] = "sql_db";
135 $plugins_modified = true;
136 } else
137 if ($v == "file_auth")
138 {
139 $config["plugins"][$k] = "file_db";
140 $plugins_modified = true;
141 }
142 }
143 if ($plugins_modified)
144 write_config_file();
145
146 return true;
147 }
148
149 function read_config_db()
150 {
151 GLOBAL $config;
152
153 if (page_requires_no_config())
154 return;
155
156 $merge = DbSettings::get();
157 /* DB settings overwrite config.php keys: */
158 $config = array_merge($config, $merge);
159 }
160
161 function config_is_file_item($name)
162 {
163 if (($name == "plugins") ||
164 ($name == "mysql") ||
165 ($name == "base_url") ||
166 ($name == "secrets"))
167 {
168 return true;
169 }
170 return false;
171 }
172
173 function write_config_file()
174 {
175 GLOBAL $config;
176
177 $file_settings = [];
178 foreach($config as $k=>$v)
179 {
180 if (config_is_file_item($k))
181 $file_settings[$k] = $v;
182 }
183
184 $cfg_filename = UPATH.'/config/config.php';
185 $tmpfile = UPATH.'/config/config.tmp.'.bin2hex(random_bytes(8)).'.php';
186 $fd = fopen($tmpfile, "w");
187 if (!$fd)
188 die("Could not write to temporary config file $tmpfile.<br>We need write permissions on the config/ directory!<br>");
189
190 $str = var_export($file_settings, true);
191 if ($str === null)
192 die("Error while running write_config_file() -- weird!");
193 if (!fwrite($fd, "<?php\n".
194 "/* This config file is written automatically by the UnrealIRCd webpanel.\n".
195 " * You are not really supposed to edit it manually.\n".
196 " */\n".
197 '$config = '.$str.";\n"))
198 {
199 die("Error writing to config file $tmpfile (on fwrite).<br>");
200 }
201 if (!fclose($fd))
202 die("Error writing to config file $tmpfile (on close).<br>");
203 /* Now atomically rename the file */
204 if (!rename($tmpfile, $cfg_filename))
205 die("Could not write (rename) to file ".$cfg_filename."<br>");
206 if (function_exists('opcache_invalidate'))
207 opcache_invalidate($cfg_filename);
208
209 /* Do not re-read config, as it would reinitialize config
210 * without having the DB settings read. (And it also
211 * serves no purpose)
212 */
213 return true;
214 }
215
216 // XXX: handle unsetting of config items :D - explicit unset function ?
217
218 function write_config($setting = null)
219 {
220 GLOBAL $config;
221
222 /* Specific request? Easy, write only this setting to the DB (never used for file) */
223 if ($setting !== null)
224 {
225 return DbSettings::set($setting, $config[$setting]);
226 }
227
228 /* Otherwise write the whole config.
229 * TODO: avoid writing settings file if unneeded,
230 * as it is more noisy than db settings.
231 */
232 $db_settings = [];
233
234 foreach($config as $k=>$v)
235 {
236 if (!config_is_file_item($k))
237 $db_settings[$k] = $v;
238 }
239
240 if (!write_config_file())
241 return false;
242
243 foreach($db_settings as $k=>$v)
244 {
245 $ret = DbSettings::set($k, $v);
246 if (!$ret)
247 return $ret;
248 }
249
250 return true;
251 }
252
253 function get_version()
254 {
255 $fd = @fopen(UPATH."/.git/FETCH_HEAD", "r");
256 if ($fd === false)
257 return "unknown";
258 $line = fgets($fd, 512);
259 fclose($fd);
260 $commit = substr($line, 0, 8);
261 return $commit; /* short git commit id */
262 }
263
264 function generate_secrets()
265 {
266 GLOBAL $config;
267
268 if (!isset($config['secrets']))
269 $config['secrets'] = Array();
270
271 if (!isset($config['secrets']['pepper']))
272 $config['secrets']['pepper'] = rtrim(base64_encode(random_bytes(16)),'=');
273
274 if (!isset($config['secrets']['key']))
275 $config['secrets']['key'] = rtrim(base64_encode(sodium_crypto_aead_xchacha20poly1305_ietf_keygen()),'=');
276 }
277
278 function get_active_rpc_server()
279 {
280 $servers = get_config("unrealircd");
281 if (empty($servers))
282 return;
283 // TODO: make user able to override this - either in user or in session
284
285 foreach ($servers as $displayname=>$e)
286 {
287 if (isset($e["default"]) && $e["default"])
288 return $displayname;
289 }
290 return null;
291 }
292
293 /* Set a new default RPC server */
294 function set_default_rpc_server($name)
295 {
296 GLOBAL $config;
297
298 /* Mark all other servers as non-default */
299 foreach ($config["unrealircd"] as $n=>$e)
300 if ($n != $name)
301 $config["unrealircd"][$n]["default"] = false;
302 $config["unrealircd"][$name]["default"] = true;
303 }
304
305 /* Ensure at least 1 server is default */
306 function set_at_least_one_default_rpc_server()
307 {
308 GLOBAL $config;
309
310 $has_default_rpc_server = false;
311 foreach ($config["unrealircd"] as $name=>$e)
312 if ($e["default"])
313 $has_default_rpc_server = true;
314 if (!$has_default_rpc_server)
315 {
316 /* Make first server in the list the default */
317 foreach ($config["unrealircd"] as $name=>$e)
318 {
319 $config["unrealircd"][$name]["default"] = true;
320 break;
321 }
322 }
323 }
324
325 function secret_encrypt(string $text)
326 {
327 GLOBAL $config;
328
329 $key = base64_decode($config['secrets']['key']);
330 $nonce = \random_bytes(\SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES);
331 $encrypted_text = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt($text, '', $nonce, $key);
332 return "secret:".rtrim(base64_encode($nonce),'=').':'.rtrim(base64_encode($encrypted_text),'='); // secret:base64(NONCE):base64(ENCRYPTEDTEXT)
333 }
334
335 function secret_decrypt(string $crypted)
336 {
337 GLOBAL $config;
338
339 $key = base64_decode($config['secrets']['key']);
340 $d = explode(":", $crypted);
341 if (count($d) != 3)
342 return null;
343 $nonce = base64_decode($d[1]);
344 $ciphertext = base64_decode($d[2]);
345
346 $ret = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt($ciphertext, '', $nonce, $key);
347 if ($ret === false)
348 return null;
349 return $ret;
350 }
351
352 function upgrade_check()
353 {
354 GLOBAL $config_transition_unreal_server;
355 GLOBAL $config;
356
357 /* Moving of a config.php item to DB: */
358 if ($config_transition_unreal_server)
359 write_config();
360
361 /* Our own stuff may need upgrading.. */
362 /* - generating secrets */
363 if (!isset($config['secrets']))
364 {
365 generate_secrets();
366 write_config_file();
367 }
368 /* - encrypting rpc_password */
369 if (isset($config['unrealircd']) &&
370 isset($config['unrealircd']['rpc_password']) &&
371 !str_starts_with($config['unrealircd']['rpc_password'], "secret:"))
372 {
373 $ret = secret_encrypt($config['unrealircd']['rpc_password']);
374 if ($ret !== false)
375 {
376 $config['unrealircd']['rpc_password'] = $ret;
377 write_config('unrealircd');
378 }
379 }
380 /* $config["unrealircd"] should be an array now.. */
381 if (isset($config['unrealircd']) && isset($config['unrealircd']['rpc_password']))
382 {
383 $config["unrealircd"]["default"] = true;
384 $config['unrealircd'] = [
385 "Primary" => $config['unrealircd']];
386 write_config("unrealircd");
387 }
388
389 $version = get_version();
390 if (!isset($config['webpanel_version']))
391 $config['webpanel_version'] = '';
392 if ($version != $config['webpanel_version'])
393 {
394 $versioninfo = [
395 "old_version" => $config['webpanel_version'],
396 "new_version" => $version
397 ];
398 /* And inform the hook (eg the database backends) */
399 Hook::run(HOOKTYPE_UPGRADE, $versioninfo);
400 /* And set the new version now that the upgrade is "done" */
401 $config['webpanel_version'] = $version;
402 write_config("webpanel_version");
403 }
404 }
405
406 function panel_start_session($user = false)
407 {
408 if (!isset($_SESSION))
409 {
410 session_set_cookie_params(86400); // can't set this to session_timeout due to catch-22
411 session_start();
412 }
413
414 if ($user === false)
415 {
416 $user = unreal_get_current_user();
417 if ($user === false)
418 return false;
419 }
420
421 $timeout = 3600;
422 if (isset($user->user_meta['session_timeout']))
423 $timeout = (INT)$user->user_meta['session_timeout'];
424
425 if (!isset($_SESSION['session_timeout']))
426 $_SESSION['session_timeout'] = $timeout;
427
428 $_SESSION['last-activity'] = time();
429 return true;
430 }
431
432 /* Now read the config, and redirect to install screen if we don't have it */
433 $config_transition_unreal_server = false;
434 if (!read_config_file())
435 {
436 if (page_requires_no_config())
437 {
438 /* Allow empty conf */
439 } else
440 if (!file_exists(UPATH."/config/config.php") && !file_exists(UPATH."/config.php"))
441 {
442 header("Location: settings/install.php");
443 die();
444 }
445 }
446
447 require_once UPATH . "/Classes/class-hook.php";
448 if (!is_dir(UPATH . "/vendor"))
449 die("The vendor/ directory is missing. Most likely the admin forgot to run 'composer install'\n");
450 require_once UPATH . '/vendor/autoload.php';
451 require_once UPATH . "/Classes/class-cmodes.php";
452 require_once UPATH . "/inc/defines.php";
453 require_once UPATH . "/misc/strings.php";
454 require_once UPATH . "/misc/channel-lookup-misc.php";
455 require_once UPATH . "/misc/user-lookup-misc.php";
456 require_once UPATH . "/misc/server-lookup-misc.php";
457 require_once UPATH . "/misc/ip-whois-misc.php";
458 require_once UPATH . "/Classes/class-log.php";
459 require_once UPATH . "/Classes/class-message.php";
460 require_once UPATH . "/Classes/class-rpc.php";
461 require_once UPATH . "/Classes/class-paneluser.php";
462 require_once UPATH . "/plugins.php";
463
464 /* Do various checks and reading, except during setup step 1. */
465 if (!page_requires_no_config())
466 {
467 /* Now that plugins are loaded, read config from DB */
468 read_config_db();
469
470 /* Check if anything needs upgrading (eg on panel version change) */
471 upgrade_check();
472
473 /* And a check... */
474 if (!get_config("base_url"))
475 die("The base_url was not found in your config. Setup went wrong?");
476 }
477
478 $pages = [
479 "Overview" => ["script"=>""],
480 "Users" => ["script"=>"users/index.php"],
481 "Channels" => ["script"=>"channels/index.php"],
482 "Servers" => ["script"=>"servers/index.php"],
483 "Server Bans" => [
484 "Server Bans" => ["script" => "server-bans/index.php"],
485 "Name Bans" => ["script" => "server-bans/name-bans.php"],
486 "Ban Exceptions" => ["script" => "server-bans/ban-exceptions.php"],
487 ],
488 "Spamfilter" => ["script" => "spamfilter.php"],
489 "Logs" => ["script" => "logs/index.php"],
490 "Tools" => [
491 "IP WHOIS" => ["script" => "tools/ip-whois.php","no_irc_server_required"=>true],
492 ],
493 "Settings" => [
494 "RPC Servers" => ["script" => "settings/rpc-servers.php","no_irc_server_required"=>true],
495 ],
496
497 "News" => ["script" => "news.php","no_irc_server_required"=>true],
498 ];
499
500 if (!panel_start_session())
501 {
502 if (!page_requires_no_login())
503 {
504 if (!is_auth_provided())
505 die("No authentication plugin loaded. You must load either sql_db, file_db, or a similar auth plugin!");
506 $current_page = $_SERVER['REQUEST_URI'];
507 header("Location: ".get_config("base_url")."login/?redirect=".urlencode($current_page));
508 die;
509 }
510 } else {
511 $pages["Settings"]["Accounts"] = [
512 "script" => "settings/index.php",
513 "no_irc_server_required"=>true
514 ];
515 if (current_user_can(PERMISSION_MANAGE_USERS))
516 {
517 $pages["Settings"]["Role Editor"] = [
518 "script"=>"settings/user-role-edit.php",
519 "no_irc_server_required"=>true
520 ];
521 }
522 if (current_user_can(PERMISSION_MANAGE_PLUGINS))
523 {
524 $pages["Settings"]["Plugins"] = ["script" => "settings/plugins.php"];
525 }
526 $user = unreal_get_current_user();
527 if ($user)
528 {
529 /* Add logout page, if logged in */
530 $pages["Logout"] = [
531 "script"=>"login/?logout=true",
532 "no_irc_server_required"=>true
533 ];
534 }
535 }
536
537 Hook::run(HOOKTYPE_NAVBAR, $pages);
538
539 /* Example to add new menu item:
540 *
541 * class MyPlugin
542 * {
543 *
544 * function __construct()
545 * {
546 * Hook::func(HOOKTYPE_NAVBAR, [$this, 'add_menu'])
547 * }
548 *
549 * function add_menu(&$pages) // this should pass by reference (using the & prefix)
550 * {
551 * $page_name = "My New Page";
552 * $page_link = "link/to/page.php";
553 * $pages[$page_name] = $page_link;
554 * }
555 * }
556 */
557
558 $current_page = get_current_page($current_page_name);
559
560
561 global $rightClickMenu;
562 $rightClickMenu = [
563 [
564 "text" => "Copy",
565 "onclick" => "copy_to_clipboard(window.getSelection().toString())",
566 "icon" => "fa-clipboard"
567 ],
568 [
569 "text" => "Paste",
570 "onclick" => "paste_from_clipboard()",
571 "icon" => "fa-paint-brush",
572 ],
573 ];
574
575 // register our menu
576 Hook::run(HOOKTYPE_RIGHTCLICK_MENU, $rightClickMenu);