Skip to content

Commit

Permalink
Fixed installer and app base paths
Browse files Browse the repository at this point in the history
Fixes #93
  • Loading branch information
sergix44 committed Nov 17, 2019
1 parent 3250fa7 commit eccd5d5
Show file tree
Hide file tree
Showing 14 changed files with 91 additions and 80 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ XBackBone require PHP >= `7.1`, with installed the required extensions:
cp config.example.php config.php && nano config.php
```
By default, XBackBone will use Sqlite3 as DB engine, and a `storage` dir in the main directory. You can leave these settings unchanged for a simple personal installation.
You must set the `base_url`, or remove it for get dynamically the url from request (not recommended).
You must set the `base_path`, or remove it for get dynamically the url from request (not recommended).

```php
return [
'base_url' => 'https://example.com', // no trailing slash
'base_path' => '/',
'storage' => [
'driver' => 'local',
'path' => 'storage',
Expand Down
3 changes: 1 addition & 2 deletions app/Factories/ViewFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ public static function createAppInstance(Container $container)

$twig->addGlobal('config', $config);
$twig->addGlobal('request', $request);
$twig->addGlobal('alerts', $container->get('session')->getAlert());
$twig->addGlobal('session', $container->get('session')->all());
$twig->addGlobal('session', $container->get('session'));
$twig->addGlobal('current_lang', $container->get('lang')->getLang());
$twig->addGlobal('maxUploadSize', stringToBytes(ini_get('post_max_size')));
$twig->addGlobal('PLATFORM_VERSION', PLATFORM_VERSION);
Expand Down
4 changes: 4 additions & 0 deletions app/Web/Lang.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ public static function getList()
foreach (glob(self::$langPath.'*.lang.php') as $file) {
$dict = include $file;

if (!is_array($dict)) {
continue;
}

$count = count($dict) - 1;
$percent = min(round(($count / $default) * 100), 100);

Expand Down
6 changes: 3 additions & 3 deletions app/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,10 +185,10 @@ function asset(string $path): string
* @param string $append
* @return string
*/
function urlFor(string $path, string $append = ''): string
function urlFor(string $path = '', string $append = ''): string
{
$baseUrl = resolve('config')['base_url'];
return $baseUrl.$path.$append;
global $app;
return $app->getBasePath().$path.$append;
}
}

Expand Down
6 changes: 3 additions & 3 deletions bin/migrate
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ if (isset($argv[1]) && $argv[1] === '--install') {
$db->query("INSERT INTO `users` (`email`, `username`, `password`, `is_admin`, `user_code`) VALUES ('admin@example.com', 'admin', ?, 1, ?)", [password_hash('admin', PASSWORD_DEFAULT), humanRandomString(5)]);
}

//if (file_exists(__DIR__.'/../install')) {
// removeDirectory(__DIR__.'/../install');
//}
if (file_exists(__DIR__.'/../install')) {
removeDirectory(__DIR__.'/../install');
}

echo 'If you are upgrading from a previous version, please run a "php bin\clean".'.PHP_EOL;
echo 'Done.'.PHP_EOL;
Expand Down
7 changes: 4 additions & 3 deletions bootstrap/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
// Load the config
$config = array_replace_recursive([
'app_name' => 'XBackBone',
'base_url' => isset($_SERVER['HTTPS']) ? 'https://'.$_SERVER['HTTP_HOST'] : 'http://'.$_SERVER['HTTP_HOST'],
'base_path' => $_SERVER['REQUEST_URI'],
'debug' => false,
'maintenance' => false,
'db' => [
Expand Down Expand Up @@ -145,6 +145,7 @@
]);

$app = Bridge::create($builder->build());
$app->setBasePath(substr($config['base_path'], 0, -1));

if (!$config['debug']) {
$app->getRouteCollector()->setCacheFile(BASE_DIR.'resources/cache/routes.cache.php');
Expand All @@ -154,11 +155,11 @@
$app->add(RememberMiddleware::class);

// Permanently redirect paths with a trailing slash to their non-trailing counterpart
$app->add(function (Request $request, RequestHandler $handler) {
$app->add(function (Request $request, RequestHandler $handler) use (&$config) {
$uri = $request->getUri();
$path = $uri->getPath();

if ($path !== '/' && substr($path, -1) === '/') {
if ($path !== $config['base_path'] && substr($path, -1) === '/') {
// permanently redirect paths with a trailing slash
// to their non-trailing counterpart
$uri = $uri->withPath(substr($path, 0, -1));
Expand Down
35 changes: 18 additions & 17 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion config.example.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php
return [
'base_url' => 'http://localhost',
'base_path' => '/',
'db' => [
'connection' => 'sqlite',
'dsn' => 'resources/database/xbackbone.db',
Expand Down
71 changes: 39 additions & 32 deletions install/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

// default config
$config = [
'base_url' => str_replace('/install/', '', (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')."://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"),
'base_path' => $_SERVER['REQUEST_URI'],
'debug' => true,
'db' => [
'connection' => 'sqlite',
Expand Down Expand Up @@ -106,10 +106,10 @@
]);

$app = Bridge::create($builder->build());
$app->setBasePath($_SERVER['REQUEST_URI']);
$app->addRoutingMiddleware();
$app->setBasePath('/install');

$app->get('/', function (Response $response, View $view, Session $session) {
$app->get('', function (Response $response, View $view, Session $session) use (&$config) {

if (!extension_loaded('gd')) {
$session->alert('The required "gd" extension is not loaded.', 'danger');
Expand Down Expand Up @@ -143,18 +143,19 @@

return $view->render($response, 'install.twig', [
'installed' => $installed,
'app_path' => str_replace('install/', '', $config['base_path']),
]);
});
})->setName('install');

$app->post('/', function (Request $request, Response $response, Filesystem $storage, Session $session) use (&$config) {
$app->post('', function (Request $request, Response $response, Filesystem $storage, Session $session) use (&$config) {

// Check if there is a previous installation, if not, setup the config file
$installed = true;
if (!file_exists(__DIR__.'/../config.php')) {
$installed = false;

// config file setup
$config['base_url'] = param($request, 'base_url');
$config['base_path'] = param($request, 'base_path');
$config['storage']['driver'] = param($request, 'storage_driver');
unset($config['debug']);
$config['db']['connection'] = param($request, 'connection');
Expand All @@ -176,6 +177,10 @@
$config['storage']['token'] = param($request, 'storage_token');
break;
case 'ftp':
if (!extension_loaded('ftp')) {
$session->alert('The "ftp" extension is not loaded.', 'danger');
return redirect($response, urlFor());
}
$config['storage']['host'] = param($request, 'storage_host');
$config['storage']['username'] = param($request, 'storage_username');
$config['storage']['password'] = param($request, 'storage_password');
Expand All @@ -194,30 +199,24 @@
$config['storage']['path'] = param($request, 'storage_path');
break;
}
}

// check if the storage is valid
$storageTestFile = 'storage_test.xbackbone.txt';
// check if the storage is valid
$storageTestFile = 'storage_test.xbackbone.txt';
try {
try {
try {
$success = $storage->write($storageTestFile, 'XBACKBONE_TEST_FILE');
} catch (FileExistsException $fileExistsException) {
$success = $storage->update($storageTestFile, 'XBACKBONE_TEST_FILE');
}

if (!$success) {
throw new Exception('The storage is not writable.');
}
$storage->readAndDelete($storageTestFile);
} catch (Exception $e) {
$session->alert("Storage setup error: {$e->getMessage()} [{$e->getCode()}]", 'danger');
return redirect($response, '/install');
$success = $storage->write($storageTestFile, 'XBACKBONE_TEST_FILE');
} catch (FileExistsException $fileExistsException) {
$success = $storage->update($storageTestFile, 'XBACKBONE_TEST_FILE');
}

$ret = file_put_contents(__DIR__.'/../config.php', '<?php'.PHP_EOL.'return '.var_export($config, true).';');
if ($ret === false) {
$session->alert('The config folder is not writable ('.__DIR__.'/../config.php'.')', 'danger');
return redirect($response, '/install');
if (!$success) {
throw new Exception('The storage is not writable.');
}
$storage->readAndDelete($storageTestFile);
} catch (Exception $e) {
$session->alert("Storage setup error: {$e->getMessage()} [{$e->getCode()}]", 'danger');
return redirect($response, urlFor());
}

// if from older installations with no support of other than local driver
Expand All @@ -228,6 +227,13 @@
unset($config['storage_dir']);
}

// if from 2.x versions
// update the config
if ($installed && isset($config['base_url'])) {
$path = parse_url($config['base_url'], PHP_URL_PATH);
$config['base_path'] = $path.'/';
unset($config['base_url']);
}

// Build the dns string and run the migrations
try {
Expand All @@ -245,7 +251,7 @@
$migrator->migrate();
} catch (PDOException $e) {
$session->alert("Cannot connect to the database: {$e->getMessage()} [{$e->getCode()}]", 'danger');
return redirect($response, '/install');
return redirect($response, urlFor());
}

// if not installed, create the default admin account
Expand All @@ -262,17 +268,18 @@
// if is upgrading and existing installation, put it out maintenance
if ($installed) {
unset($config['maintenance']);
}

$ret = file_put_contents(__DIR__.'/../config.php', '<?php'.PHP_EOL.'return '.var_export($config, true).';');
if ($ret === false) {
$session->alert('The config folder is not writable ('.__DIR__.'/../config.php'.')', 'danger');
return redirect($response, '/install');
}
// Finally write the config
$ret = file_put_contents(__DIR__.'/../config.php', '<?php'.PHP_EOL.'return '.var_export($config, true).';');
if ($ret === false) {
$session->alert('The config folder is not writable ('.__DIR__.'/../config.php'.')', 'danger');
return redirect($response, '/install');
}

// Installed successfully, destroy the installer session
$session->destroy();
return redirect($response, "{$config['base_url']}/?afterInstall=true");
return redirect($response, "{$config['base_path']}?afterInstall=true");
});

$app->run();
7 changes: 3 additions & 4 deletions install/templates/install.twig
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,9 @@
<form method="post" action="">
{% if not installed %}
<div class="form-group row">
<label for="base_url" class="col-sm-3 col-form-label">Base URL</label>
<label for="base_path" class="col-sm-3 col-form-label">Base Path</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="base_url" name="base_url" value="{{ config.base_url }}" autocomplete="off" required>
<small>No trailing slash.</small>
<input type="text" class="form-control" id="base_path" name="base_path" value="{{ app_path }}" autocomplete="off" required>
</div>
</div>
<hr>
Expand Down Expand Up @@ -205,7 +204,7 @@
</div>
</div>
</div>
<div class="modal fade" id="modalLoading" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal" id="modalLoading" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
Expand Down
4 changes: 2 additions & 2 deletions resources/templates/base.twig
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<link href="{{ asset('/static/app/app.css') }}" rel="stylesheet">
<script>
window.AppConfig = {
'base_url': '{{ config.base_url }}',
'base_path': '{{ config.base_path }}',
'max_upload_size': {{ maxUploadSize }},
'lang': {'publish': '{{ lang('publish') }}', 'hide': '{{ lang('hide') }}', 'dropzone': '{{ lang('drop_to_upload') }}'}
}
Expand All @@ -33,7 +33,7 @@
{% block content %}{% endblock %}
{% block footer %}
<div class="container-fluid footer" style="display: none; font-size: 0.8rem">
<div class="text-muted">Proudly powered by <a href="https://github.com/SergiX44/XBackBone">XBackBone{% if session.admin %} v{{ PLATFORM_VERSION }}{% endif %}</a> — <i class="fas fa-fw fa-balance-scale"></i> AGPL v3.0</div>
<div class="text-muted">Proudly powered by <a href="https://github.com/SergiX44/XBackBone">XBackBone{% if session.get('admin') %} v{{ PLATFORM_VERSION }}{% endif %}</a> — <i class="fas fa-fw fa-balance-scale"></i> AGPL v3.0</div>
</div>
{% endblock %}
<script src="{{ asset('/static/jquery/jquery.min.js') }}"></script>
Expand Down
2 changes: 1 addition & 1 deletion resources/templates/comp/alert.twig
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% for alert in alerts %}
{% for alert in session.getAlert() %}
{% for type, message in alert %}
<div class="alert alert-{{ type }} alert-dismissible fade show" role="alert">
{{ message }}
Expand Down
Loading

0 comments on commit eccd5d5

Please sign in to comment.