-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
install.php
448 lines (391 loc) · 18.3 KB
/
install.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
<?php
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
use Box\Mod\Email\Service;
use FOSSBilling\Environment;
use Ramsey\Uuid\Uuid;
use Symfony\Component\HttpClient\HttpClient;
use Twig\Loader\FilesystemLoader;
date_default_timezone_set('UTC');
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('display_startup_errors', 1);
ini_set('log_errors', '1');
ini_set('error_log', 'php_error.log');
define('PATH_ROOT', dirname(__DIR__));
const PATH_LIBRARY = PATH_ROOT . DIRECTORY_SEPARATOR . 'library';
const PATH_VENDOR = PATH_ROOT . DIRECTORY_SEPARATOR . 'vendor';
const PATH_INSTALL_THEMES = PATH_ROOT . DIRECTORY_SEPARATOR . 'install';
const PATH_THEMES = PATH_ROOT . DIRECTORY_SEPARATOR . 'themes';
const PATH_LICENSE = PATH_ROOT . DIRECTORY_SEPARATOR . 'LICENSE';
const PATH_SQL = PATH_ROOT . DIRECTORY_SEPARATOR . 'install/sql/structure.sql';
const PATH_SQL_DATA = PATH_ROOT . DIRECTORY_SEPARATOR . 'install/sql/content.sql';
const PATH_INSTALL = PATH_ROOT . DIRECTORY_SEPARATOR . 'install';
const PATH_CONFIG = PATH_ROOT . DIRECTORY_SEPARATOR . 'config.php';
const PATH_CONFIG_SAMPLE = PATH_ROOT . DIRECTORY_SEPARATOR . 'config-sample.php';
const PATH_CRON = PATH_ROOT . DIRECTORY_SEPARATOR . 'cron.php';
const PATH_LANGS = PATH_ROOT . DIRECTORY_SEPARATOR . 'locale';
const PATH_MODS = PATH_ROOT . DIRECTORY_SEPARATOR . 'modules';
const PATH_CACHE = PATH_ROOT . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache';
const PATH_LOG = PATH_ROOT . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'log';
const HURAGA_CONFIG = PATH_THEMES . DIRECTORY_SEPARATOR . 'huraga' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings_data.json';
const HURAGA_CONFIG_TEMPLATE = PATH_THEMES . DIRECTORY_SEPARATOR . 'huraga' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings_data.json.example';
const PATH_HTACCESS = PATH_ROOT . DIRECTORY_SEPARATOR . '.htaccess';
const PAGE_INSTALL = './assets/install.html.twig';
const PAGE_RESULT = './assets/result.html.twig';
// Some functions and classes reference this, so we define it here to avoid errors.
const DEBUG = false;
// Set default include path
set_include_path(implode(PATH_SEPARATOR, [
PATH_LIBRARY,
get_include_path(),
]));
// Load autoloader
require PATH_VENDOR . DIRECTORY_SEPARATOR . 'autoload.php';
include PATH_LIBRARY . DIRECTORY_SEPARATOR . 'FOSSBilling' . DIRECTORY_SEPARATOR . 'Autoloader.php';
// Build the environment
$loader = new FOSSBilling\AutoLoader();
$loader->register();
$protocol = FOSSBilling\Tools::isHTTPS() ? 'https' : 'http';
// Detect if FOSSBilling is behind a proxy server
if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
$host = $_SERVER['HTTP_X_FORWARDED_HOST'];
} else {
$host = $_SERVER['HTTP_HOST'];
}
$url = $protocol . '://' . $host . $_SERVER['REQUEST_URI'];
$current_url = pathinfo($url, PATHINFO_DIRNAME);
$root_url = str_replace('/install', '', $current_url) . '/';
define('SYSTEM_URL', $root_url);
const URL_INSTALL = SYSTEM_URL . 'install/';
const URL_ADMIN = SYSTEM_URL . 'admin';
// Load action and initialize the installer
$action = $_GET['a'] ?? 'index';
$installer = new FOSSBilling_Installer();
// Run the installer only in non-CLI mode
if (!Environment::isCLI()) {
$installer->run($action);
}
// Inline installer class.
final class FOSSBilling_Installer
{
private readonly Session $session;
private PDO $pdo;
public function __construct()
{
require_once 'session.php';
$this->session = new Session();
}
/**
* Action router.
*
* @param string $action
*/
public function run($action): void
{
switch ($action) {
case 'install':
// Make sure this is a POST request
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
header('Location: ' . URL_INSTALL);
exit;
}
// Installer validation
try {
// Make sure we are not already installed. Prevents tampered requests from being able to trigger the installer.
if ($this->isAlreadyInstalled()) {
throw new Exception('FOSSBilling is already installed.');
}
// Set if they've opted into error reporting
$this->session->set('error_reporting', $_POST['error_reporting']);
// Handle database information
$this->session->set('database_hostname', $_POST['database_hostname']);
$this->session->set('database_port', $_POST['database_port']);
$this->session->set('database_name', $_POST['database_name']);
$this->session->set('database_username', $_POST['database_username']);
$this->session->set('database_password', $_POST['database_password']);
$this->connectDatabase();
// Handle admin information
$this->session->set('admin_name', $_POST['admin_name']);
$this->session->set('admin_email', $_POST['admin_email']);
$this->session->set('admin_password', $_POST['admin_password']);
if (Environment::isTesting()) {
$this->session->set('admin_api_token', $_POST['admin_api_token'] ?? null);
} else {
$this->session->set('admin_api_token', null);
}
$this->validateAdmin();
// Set up default currency
$this->session->set('currency_code', $_POST['currency_code']);
$this->session->set('currency_title', $_POST['currency_title']);
$this->session->set('currency_format', $_POST['currency_format'] ?? '${{price}}');
// Attempt installation
$this->install();
$this->generateEmailTemplates();
session_destroy();
// Installation is successful
echo $this->render(PAGE_RESULT, [
'success' => true,
'config_file_path' => PATH_CONFIG,
'cron_path' => PATH_CRON,
'install_module_path' => PATH_INSTALL,
'url_customer' => SYSTEM_URL,
'url_admin' => URL_ADMIN,
]);
// Try to remove install folder
try {
// Delete install directory only if debug mode is NOT enabled.
$config = require PATH_CONFIG;
if (!$config['debug_and_monitoring']['debug']) {
unlink(__DIR__ . DIRECTORY_SEPARATOR . 'install.php');
}
} catch (Exception) {
// Do nothing and fail silently. New warnings are presented on the installation completed page for a leftover install directory.
}
} catch (Exception $e) {
// Route to result page with exception information
echo $this->render(PAGE_RESULT, [
'success' => false,
'message' => $e->getMessage(),
]);
}
break;
case 'index':
default:
$requirements = new FOSSBilling\Requirements();
$compatibility = $requirements->checkCompat();
$vars = [
'compatibility' => $compatibility,
'os' => PHP_OS,
'os_ok' => (str_starts_with(strtoupper(PHP_OS), 'WIN')) ? false : true,
'is_subfolder' => $this->isSubfolder(),
'fossbilling_ver' => FOSSBilling\Version::VERSION,
'canInstall' => !$this->isSubfolder() && $compatibility['can_install'],
'alreadyInstalled' => $this->isAlreadyInstalled(),
'database_hostname' => $this->session->get('database_hostname'),
'database_name' => $this->session->get('database_name'),
'database_username' => $this->session->get('database_username'),
'database_password' => $this->session->get('database_password'),
'admin_name' => $this->session->get('admin_name'),
'admin_email' => $this->session->get('admin_email'),
'admin_password' => $this->session->get('admin_password'),
'currency_code' => $this->session->get('currency_code') ?: 'USD',
'currency_title' => $this->session->get('currency_title') ?: 'US Dollar',
'currency_format' => $this->session->get('currency_format') ?: '${{price}}',
'install_module_path' => PATH_INSTALL,
'cron_path' => PATH_CRON,
'config_file_path' => PATH_CONFIG,
'live_site' => SYSTEM_URL,
'admin_site' => URL_ADMIN,
'domain' => pathinfo(SYSTEM_URL, PATHINFO_BASENAME),
];
echo $this->render(PAGE_INSTALL, $vars);
break;
}
}
/**
* Render a page with Twig.
*
* @param string $name
* @param array $vars
*/
private function render($name, $vars = []): string
{
$options = [
'paths' => [PATH_INSTALL_THEMES],
'debug' => true,
'charset' => 'utf-8',
'optimizations' => 1,
'autoescape' => 'html',
'auto_reload' => true,
'cache' => false,
];
$loader = new FilesystemLoader($options['paths']);
$twig = new Twig\Environment($loader, $options);
$twig->addGlobal('request', $_REQUEST);
$twig->addGlobal('version', FOSSBilling\Version::VERSION);
return $twig->render($name, $vars);
}
/**
* Attempt to open the database connection.
*/
private function connectDatabase(): void
{
// Open the connection
$this->pdo = new PDO('mysql:host=' . $this->session->get('database_hostname') . ';' . $this->session->get('database_port'),
$this->session->get('database_username'),
$this->session->get('database_password'),
[
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
// Set required MySQL environment settings
$this->pdo->exec('SET NAMES "utf8"');
$this->pdo->exec('SET CHARACTER SET utf8');
$this->pdo->exec('SET CHARACTER_SET_CONNECTION = utf8');
$this->pdo->exec('SET character_set_results = utf8');
$this->pdo->exec('SET character_set_server = utf8');
$this->pdo->exec('SET SESSION interactive_timeout = 28800');
$this->pdo->exec('SET SESSION wait_timeout = 28800');
// Attempt to create the database.
try {
$this->pdo->exec('CREATE DATABASE `' . $this->session->get('database_name') . '` CHARACTER SET utf8 COLLATE utf8_general_ci;');
} catch (PDOException) {
// Silently fail if the database already exists.
}
// Select the database as default for future queries
$this->pdo->query('USE `' . $this->session->get('database_name') . '`;');
}
/**
* Validate admin information meets all required parameters.
*/
private function validateAdmin(): bool
{
if (!filter_var($this->session->get('admin_email'), FILTER_VALIDATE_EMAIL)) {
throw new Exception('The admin email is not a valid address.');
}
if (strlen($this->session->get('admin_password')) < 8) {
throw new Exception('Minimum admin password length is 8 characters.');
}
if (!preg_match('#[0-9]+#', $this->session->get('admin_password'))) {
throw new Exception('Admin password must include at least one number.');
}
if (!preg_match('#[a-z]+#', $this->session->get('admin_password'))) {
throw new Exception('Admin password must include at least one lowercase letter.');
}
if (!preg_match('#[A-Z]+#', $this->session->get('admin_password'))) {
throw new Exception('Admin password must include at least one uppercase letter.');
}
if (empty($this->session->get('admin_name'))) {
throw new Exception('You must enter an Admin Name.');
}
return true;
}
/**
* Attempt to detect if the application is under a subfolder.
*/
private function isSubfolder(): bool
{
return substr_count(URL_INSTALL, '/') > 4 ? true : false;
}
/**
* Check if we are already installed.
*/
public function isAlreadyInstalled(): bool
{
return file_exists(PATH_CONFIG) ? true : false;
}
/**
* Installation processor.
*/
private function install(): bool
{
// Load database structure
$sql = file_get_contents(PATH_SQL);
$sql_content = file_get_contents(PATH_SQL_DATA);
if (!$sql || !$sql_content) {
throw new Exception('Could not read structure.sql file');
}
// Read content, parse queries into an array, then loop and execute each query
$sql .= $sql_content;
$sql = preg_split('/\;[\r]*\n/ism', $sql);
$sql = array_map('trim', $sql);
foreach ($sql as $query) {
if (!trim($query)) {
continue;
}
$this->pdo->query($query);
}
// Create default administrator
$passwordObject = new FOSSBilling\PasswordManager();
$stmt = $this->pdo->prepare("INSERT INTO admin (role, name, email, pass, protected, created_at, updated_at, api_token) VALUES('admin', :admin_name, :admin_email, :admin_password, 1, NOW(), NOW(), :api_token);");
$stmt->execute([
'admin_name' => $this->session->get('admin_name'),
'admin_email' => $this->session->get('admin_email'),
'admin_password' => $passwordObject->hashIt($this->session->get('admin_password')),
'api_token' => $this->session->get('admin_api_token'),
]);
// Delete default currency from content file and use currency passed in the installer
$stmt = $this->pdo->prepare("DELETE FROM currency WHERE code='USD'");
$stmt->execute();
$stmt = $this->pdo->prepare('INSERT INTO currency (id, title, code, is_default, conversion_rate, format, price_format, created_at, updated_at) VALUES(1, :currency_title, :currency_code, 1, 1.000000, :currency_format, 1, NOW(), NOW());');
$stmt->execute([
'currency_title' => $this->session->get('currency_title'),
'currency_code' => $this->session->get('currency_code'),
'currency_format' => $this->session->get('currency_format'),
]);
$stmt = $this->pdo->prepare('INSERT INTO setting (param, value, created_at, updated_at) VALUES (:param, :value, NOW(), NOW())');
$stmt->execute([
':param' => 'last_error_reporting_nudge',
':value' => FOSSBilling\Version::VERSION,
]);
// Copy config templates when applicable
if (!file_exists(HURAGA_CONFIG) && file_exists(HURAGA_CONFIG_TEMPLATE)) {
copy(HURAGA_CONFIG_TEMPLATE, HURAGA_CONFIG); // Copy the file instead of renaming it. This allows local dev instances to not need to restore the original file manually.
}
// If .htaccess doesn't exist, fetch the latest from GitHub.
if (!file_exists(PATH_HTACCESS)) {
try {
$client = HttpClient::create();
$response = $client->request('GET', 'https://raw.githubusercontent.com/FOSSBilling/FOSSBilling/main/src/.htaccess');
file_put_contents(PATH_HTACCESS, $response->getContent());
} catch (Exception $e) {
throw new Exception('Unable to write required .htaccess file to ' . PATH_HTACCESS . '. Check file and folder permissions.', $e->getCode());
}
}
// Create the configuration file
$output = $this->getConfigOutput();
if (!file_put_contents(PATH_CONFIG, $output)) {
throw new Exception('Configuration file is not writable or does not exist. Please create the file at ' . PATH_CONFIG . ' and make it writable', 101);
}
// Installation completed successfully
return true;
}
/**
* Generate the `config.php` file using the `config-sample.php` as a template.
*/
private function getConfigOutput(): string
{
$updateBranch = FOSSBilling\Version::isPreviewVersion() ? 'preview' : 'release';
// Load default sample config
$data = require PATH_CONFIG_SAMPLE;
// Handle dynamic configs
$data['security']['force_https'] = FOSSBilling\Tools::isHTTPS();
$data['debug_and_monitoring']['report_errors'] = (bool) $this->session->get('error_reporting');
$data['update_branch'] = $updateBranch;
$data['info']['instance_id'] = Uuid::uuid4()->toString();
$data['url'] = SYSTEM_URL;
$data['path_data'] = PATH_ROOT . DIRECTORY_SEPARATOR . 'data';
$data['db'] = [
'type' => 'mysql',
'host' => $this->session->get('database_hostname'),
'port' => $this->session->get('database_port'),
'name' => $this->session->get('database_name'),
'user' => $this->session->get('database_username'),
'password' => $this->session->get('database_password'),
];
$data['twig']['cache'] = PATH_CACHE;
// Build and return data
$output = '<?php ' . PHP_EOL;
return $output . ('return ' . var_export($data, true) . ';');
}
/**
* Generate the default email templates.
*/
private function generateEmailTemplates(): bool
{
$emailService = new Service();
$di = include PATH_ROOT . DIRECTORY_SEPARATOR . 'di.php';
$di['translate']();
$emailService->setDi($di);
return $emailService->templateBatchGenerate();
}
}