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