Overview
Comment:Fix reset when the storage quota is low
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk | stable
Files: files | file ages | folders
SHA3-256: 131b5910610ba09103ce93f5b823266175ad73a0e6f8b0fa17b81e3e92e08db1
User & Date: bohwaz on 2022-11-03 01:20:21
Other Links: manifest | tags
Context
2022-11-03
13:08
Emails queue: write sent messages to DB every 50 messages check-in: 5e2a63f1b0 user: bohwaz tags: trunk, stable
01:20
Fix reset when the storage quota is low check-in: 131b591061 user: bohwaz tags: trunk, stable
2022-10-29
13:06
Fix possible numeric error on users details and multiple choice select check-in: 8be85e618a user: bohwaz tags: trunk, stable
Changes

Modified src/include/lib/Garradin/Files/Storage/FileSystem.php from [3a2659d851] to [d336ee3df1].

121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
	}

	static public function delete(File $file): bool
	{
		$path = self::getFullPath($file);

		if ($file->type == File::TYPE_DIRECTORY) {
			return Utils::deleteRecursive($path);
		}

		return Utils::safe_unlink($path);
	}

	static public function move(File $file, string $new_path): bool
	{







|







121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
	}

	static public function delete(File $file): bool
	{
		$path = self::getFullPath($file);

		if ($file->type == File::TYPE_DIRECTORY) {
			return Utils::deleteRecursive($path, true);
		}

		return Utils::safe_unlink($path);
	}

	static public function move(File $file, string $new_path): bool
	{
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
	{
		$quota = @disk_free_space(self::_getRoot());
		return $quota === false ? (float) \PHP_INT_MAX : (float) $quota;
	}

	static public function truncate(): void
	{
		Utils::deleteRecursive(self::_getRoot());
	}

	static public function lock(): void
	{
		touch(self::_getRoot() . DIRECTORY_SEPARATOR . '.lock');
	}








|







299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
	{
		$quota = @disk_free_space(self::_getRoot());
		return $quota === false ? (float) \PHP_INT_MAX : (float) $quota;
	}

	static public function truncate(): void
	{
		Utils::deleteRecursive(self::_getRoot(), false);
	}

	static public function lock(): void
	{
		touch(self::_getRoot() . DIRECTORY_SEPARATOR . '.lock');
	}

Modified src/include/lib/Garradin/Install.php from [6bb35e0b66] to [05bc4693db].

1
2
3
4
5
6
7
8
9

10
11
12
13
14
15
16
<?php

namespace Garradin;

use Garradin\Accounting\Charts;
use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Year;
use Garradin\Entities\Users\Category;
use Garradin\Entities\Files\File;

use Garradin\Membres\Session;

use KD2\HTTP;

/**
 * Pour procéder à l'installation de l'instance Garradin
 * Utile pour automatiser l'installation sans passer par la page d'installation









>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php

namespace Garradin;

use Garradin\Accounting\Charts;
use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Year;
use Garradin\Entities\Users\Category;
use Garradin\Entities\Files\File;
use Garradin\Files\Files;
use Garradin\Membres\Session;

use KD2\HTTP;

/**
 * Pour procéder à l'installation de l'instance Garradin
 * Utile pour automatiser l'installation sans passer par la page d'installation
71
72
73
74
75
76
77
78












79
80
81
82
83
84
85
			throw new UserException('L\'utilisateur connecté ne dispose pas de nom, merci de le renseigner.');
		}

		if (!trim($user->email)) {
			throw new UserException('L\'utilisateur connecté ne dispose pas d\'adresse e-mail, merci de la renseigner.');
		}

		(new Sauvegarde)->create(date('Y-m-d-His-') . 'avant-remise-a-zero');













		Config::deleteInstance();
		DB::getInstance()->close();
		DB::deleteInstance();

		file_put_contents(CACHE_ROOT . '/reset', json_encode([
			'password'     => $session::hashPassword($password),







|
>
>
>
>
>
>
>
>
>
>
>
>







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
			throw new UserException('L\'utilisateur connecté ne dispose pas de nom, merci de le renseigner.');
		}

		if (!trim($user->email)) {
			throw new UserException('L\'utilisateur connecté ne dispose pas d\'adresse e-mail, merci de la renseigner.');
		}

		$name = date('Y-m-d-His-') . 'avant-remise-a-zero';

		$s = new Sauvegarde;
		$s->create($name);

		// Keep a backup file of files
		if (FILE_STORAGE_BACKEND == 'FileSystem') {
			$name = 'documents_' . $name . '.zip';
			$s->dumpFilesZip(CACHE_ROOT . '/' . $name);
			Files::callStorage('truncate');
			@mkdir(FILE_STORAGE_CONFIG . '/documents');
			@rename(CACHE_ROOT . '/' . $name, FILE_STORAGE_CONFIG . '/documents/' . $name);
		}

		Config::deleteInstance();
		DB::getInstance()->close();
		DB::deleteInstance();

		file_put_contents(CACHE_ROOT . '/reset', json_encode([
			'password'     => $session::hashPassword($password),
105
106
107
108
109
110
111

112
113
114
115
116
117
118
119








120
121
122
123
124
125
126

		$data = json_decode(file_get_contents(CACHE_ROOT . '/reset'));

		if (!$data) {
			throw new \LogicException('Invalid reset data');
		}


		// We can't use the real password, as it might not be valid (too short or compromised)
		$ok = self::install($data->organization ?? 'Association', $data->name, $data->email, md5($data->password));

		// Restore password
		DB::getInstance()->preparedQuery('UPDATE membres SET passe = ? WHERE id = 1;', [$data->password]);

		if (defined('\Garradin\LOCAL_LOGIN') && \Garradin\LOCAL_LOGIN) {
			Session::getInstance()->refresh();








		}

		@unlink(CACHE_ROOT . '/reset');

		Utils::redirect('!config/advanced/?msg=RESET');
	}








>
|
|

|
|

|
|
>
>
>
>
>
>
>
>







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

		$data = json_decode(file_get_contents(CACHE_ROOT . '/reset'));

		if (!$data) {
			throw new \LogicException('Invalid reset data');
		}

		try {
			// We can't use the real password, as it might not be valid (too short or compromised)
			$ok = self::install($data->organization ?? 'Association', $data->name, $data->email, md5($data->password));

			// Restore password
			DB::getInstance()->preparedQuery('UPDATE membres SET passe = ? WHERE id = 1;', [$data->password]);

			if (defined('\Garradin\LOCAL_LOGIN') && \Garradin\LOCAL_LOGIN) {
				Session::getInstance()->refresh();
			}
		}
		catch (\Exception $e) {
			Config::deleteInstance();
			DB::getInstance()->close();
			DB::deleteInstance();
			Utils::safe_unlink(DB_FILE);
			throw $e;
		}

		@unlink(CACHE_ROOT . '/reset');

		Utils::redirect('!config/advanced/?msg=RESET');
	}

161
162
163
164
165
166
167

168
169
170
171
172
173
174
	static public function install(string $name, string $user_name, string $user_email, string $user_password, ?string $welcome_text = null): void
	{
		if (file_exists(DB_FILE)) {
			throw new UserException('La base de données existe déjà.');
		}

		self::checkAndCreateDirectories();

		$db = DB::getInstance();

		// Création de la base de données
		$db->begin();
		$db->exec('PRAGMA application_id = ' . DB::APPID . ';');
		$db->setVersion(garradin_version());
		$db->exec(file_get_contents(DB_SCHEMA));







>







183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
	static public function install(string $name, string $user_name, string $user_email, string $user_password, ?string $welcome_text = null): void
	{
		if (file_exists(DB_FILE)) {
			throw new UserException('La base de données existe déjà.');
		}

		self::checkAndCreateDirectories();
		Files::disableQuota();
		$db = DB::getInstance();

		// Création de la base de données
		$db->begin();
		$db->exec('PRAGMA application_id = ' . DB::APPID . ';');
		$db->setVersion(garradin_version());
		$db->exec(file_get_contents(DB_SCHEMA));
304
305
306
307
308
309
310

311
312
313
314
315
316
317
		$has_welcome_plugin = Plugin::getPath('welcome', false);

		if ($has_welcome_plugin) {
			Plugin::install('welcome', true);
		}

		$config->save();

	}

	static public function checkAndCreateDirectories()
	{
		// Vérifier que les répertoires vides existent, sinon les créer
		$paths = [
			DATA_ROOT,







>







327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
		$has_welcome_plugin = Plugin::getPath('welcome', false);

		if ($has_welcome_plugin) {
			Plugin::install('welcome', true);
		}

		$config->save();
		Files::enableQuota();
	}

	static public function checkAndCreateDirectories()
	{
		// Vérifier que les répertoires vides existent, sinon les créer
		$paths = [
			DATA_ROOT,
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346

		foreach ($paths as $path)
		{
			Utils::safe_mkdir($path, 0777, true);

			if (!is_dir($path))
			{
				throw new UserException('Le répertoire '.$path.' n\'existe pas ou n\'est pas un répertoire.');
			}

			// On en profite pour vérifier qu'on peut y lire et écrire
			if (!is_writable($path) || !is_readable($path))
			{
				throw new UserException('Le répertoire '.$path.' n\'est pas accessible en lecture/écriture.');
			}

			// Some basic safety against misconfigured hosts
			file_put_contents($path . '/index.html', '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL was not found on this server.</p></body></html>');
		}

		return true;







|





|







350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370

		foreach ($paths as $path)
		{
			Utils::safe_mkdir($path, 0777, true);

			if (!is_dir($path))
			{
				throw new \RuntimeException('Le répertoire '.$path.' n\'existe pas ou n\'est pas un répertoire.');
			}

			// On en profite pour vérifier qu'on peut y lire et écrire
			if (!is_writable($path) || !is_readable($path))
			{
				throw new \RuntimeException('Le répertoire '.$path.' n\'est pas accessible en lecture/écriture.');
			}

			// Some basic safety against misconfigured hosts
			file_put_contents($path . '/index.html', '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL was not found on this server.</p></body></html>');
		}

		return true;

Modified src/include/lib/Garradin/Sauvegarde.php from [955ef36c50] to [01f81185a6].

267
268
269
270
271
272
273
274
275

276
277
278
279

280
281
282
283
284
285
286
287
		echo sha1_file($file);

		if (null !== $tmp_file) {
			@unlink($tmp_file);
		}
	}

	public function dumpFilesZip(): void
	{

		$name = Config::getInstance()->get('nom_asso') . ' - Documents.zip';
		header('Content-type: application/zip');
		header(sprintf('Content-Disposition: attachment; filename="%s"', $name));


		$zip = new ZipWriter('php://output');
		$zip->setCompression(0);

		$add_directory = function ($path) use ($zip, &$add_directory) {
			try {
				$list = Files::list($path);
			}
			catch (ValidationException $e) {







|

>
|
|
|
|
>
|







267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
		echo sha1_file($file);

		if (null !== $tmp_file) {
			@unlink($tmp_file);
		}
	}

	public function dumpFilesZip(?string $target = null): void
	{
		if (!$target) {
			$name = Config::getInstance()->get('nom_asso') . ' - Documents.zip';
			header('Content-type: application/zip');
			header(sprintf('Content-Disposition: attachment; filename="%s"', $name));
		}

		$zip = new ZipWriter($target ?? 'php://output');
		$zip->setCompression(0);

		$add_directory = function ($path) use ($zip, &$add_directory) {
			try {
				$list = Files::list($path);
			}
			catch (ValidationException $e) {

Modified src/include/lib/Garradin/Utils.php from [f1bbe00471] to [eab571b52d].

663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679


680

681
682
683
684
685
686
687
        while ($file = $dir->read())
        {
            if ($file == '.' || $file == '..')
                continue;

            if (is_dir($path . DIRECTORY_SEPARATOR . $file))
            {
                if (!self::deleteRecursive($path . DIRECTORY_SEPARATOR . $file))
                    return false;
            }
            else
            {
                self::safe_unlink($path . DIRECTORY_SEPARATOR . $file);
            }
        }

        $dir->close();


        rmdir($path);


        return true;
    }

    static public function plugin_url($params = [])
    {
        if (isset($params['id']))







|









>
>
|
>







663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
        while ($file = $dir->read())
        {
            if ($file == '.' || $file == '..')
                continue;

            if (is_dir($path . DIRECTORY_SEPARATOR . $file))
            {
                if (!self::deleteRecursive($path . DIRECTORY_SEPARATOR . $file, true))
                    return false;
            }
            else
            {
                self::safe_unlink($path . DIRECTORY_SEPARATOR . $file);
            }
        }

        $dir->close();

        if ($delete_self) {
            rmdir($path);
        }

        return true;
    }

    static public function plugin_url($params = [])
    {
        if (isset($params['id']))

Modified src/templates/admin/config/advanced/index.tpl from [6ff7fd5e0e] to [e8b8d4662d].

90
91
92
93
94
95
96
97
98







99
100
101
102
103
104
105
106
107

<h2 class="ruler">Actions destructrices</h2>

<form method="post" action="{$self_url_no_qs}">

<fieldset>
	<legend>Remise à zéro</legend>
	<p class="block error">
		Attention : toutes les données seront effacées&nbsp;! Ceci inclut les membres, les écritures comptables, les pages du wiki, etc.







		Seul votre compte membre sera re-créé avec le même email et mot de passe.
	</p>
	<p class="help">
		Une sauvegarde sera automatiquement créée avant de procéder à la remise à zéro.
	</p>
	<dl>
		<dt><label for="f_passe_verif">Votre mot de passe</label> (pour vérification)</dt>
		<dd><input type="password" name="passe_verif" id="f_passe_verif" /></dd>
	</dl>







|
|
>
>
>
>
>
>
>
|
|







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

<h2 class="ruler">Actions destructrices</h2>

<form method="post" action="{$self_url_no_qs}">

<fieldset>
	<legend>Remise à zéro</legend>
	<div class="block error">
		<h3>Attention : toutes les données seront effacées&nbsp;!</h3>
		<ul>
			<li>Les membres seront supprimés, ainsi que les activités et l'historique d'inscription</li>
			<li>Les écritures et exercices comptables seront aussi supprimés, avec toutes les autres données comptables</li>
			<li>Le contenu du site web</li>
			<li>Les documents, etc.</li>
			<li>Bref : tout sera effacé !</li>
		</ul>
		<p>Seul votre compte membre sera re-créé avec le même email et mot de passe.</p>
	</div>
	<p class="help">
		Une sauvegarde sera automatiquement créée avant de procéder à la remise à zéro.
	</p>
	<dl>
		<dt><label for="f_passe_verif">Votre mot de passe</label> (pour vérification)</dt>
		<dd><input type="password" name="passe_verif" id="f_passe_verif" /></dd>
	</dl>

Modified src/www/admin/install.php from [76f9b18d41] to [4b6812239c].

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
require_once __DIR__ . '/../../include/init.php';

if (file_exists(DB_FILE))
{
    throw new UserException('Garradin est déjà installé');
}

try {
    Install::checkAndCreateDirectories();
	Install::checkReset();
}
catch (UserException $e) {
    echo $e->getMessage();
    exit;
}

function f($key)
{
    return \KD2\Form::get($key);
}

$tpl = Template::getInstance();







<
|
|
<
<
<
<
<







9
10
11
12
13
14
15

16
17





18
19
20
21
22
23
24
require_once __DIR__ . '/../../include/init.php';

if (file_exists(DB_FILE))
{
    throw new UserException('Garradin est déjà installé');
}


Install::checkAndCreateDirectories();
Install::checkReset();






function f($key)
{
    return \KD2\Form::get($key);
}

$tpl = Template::getInstance();