Overview
Comment:Improve Upgrade process if something fails
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | dev
Files: files | file ages | folders
SHA3-256: 22b37319aa7766a3ecf634f09abd2d8fb9ffcf83c26d0dbbd37953ebd150bed4
User & Date: bohwaz on 2022-03-14 21:15:19
Other Links: branch diff | manifest | tags
Context
2022-03-15
00:40
Implement files::glob method check-in: 7bea175b3c user: bohwaz tags: dev
2022-03-14
21:15
Improve Upgrade process if something fails check-in: 22b37319aa user: bohwaz tags: dev
2022-03-12
02:08
Implement saving of dynamic fields sort order, improve JS drag and sort check-in: 0abf9de2e4 user: bohwaz tags: dev
Changes

Modified src/include/data/1.2.0_migration.sql from [4f16e28fca] to [72795b0652].

1
2
3
4
5
6
7
8
9
10
11
12
13


14



15
16
17
18
19
20
21
-- Already created before, so we need to drop it to migrate
DROP TABLE plugins_signals;

-- The new users table has already been created and copied
ALTER TABLE plugins RENAME TO plugins_old;
ALTER TABLE plugins_signaux RENAME TO plugins_signaux_old;

-- References old membres table
ALTER TABLE services_users RENAME TO services_users_old;
ALTER TABLE services_reminders_sent RENAME TO services_reminders_sent_old;
ALTER TABLE acc_transactions RENAME TO acc_transactions_old;
ALTER TABLE acc_transactions_users RENAME TO acc_transactions_users_old;



.read 1.2.0_schema.sql




INSERT INTO services_users SELECT * FROM services_users_old;

INSERT INTO services_reminders_sent SELECT * FROM services_reminders_sent_old;

INSERT INTO acc_transactions SELECT * FROM acc_transactions_old;














>
>

>
>
>







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
-- Already created before, so we need to drop it to migrate
DROP TABLE plugins_signals;

-- The new users table has already been created and copied
ALTER TABLE plugins RENAME TO plugins_old;
ALTER TABLE plugins_signaux RENAME TO plugins_signaux_old;

-- References old membres table
ALTER TABLE services_users RENAME TO services_users_old;
ALTER TABLE services_reminders_sent RENAME TO services_reminders_sent_old;
ALTER TABLE acc_transactions RENAME TO acc_transactions_old;
ALTER TABLE acc_transactions_users RENAME TO acc_transactions_users_old;

DROP VIEW acc_accounts_balances;

.read 1.2.0_schema.sql

INSERT INTO users_sessions SELECT * FROM membres_sessions;
DROP TABLE membres_sessions;

INSERT INTO services_users SELECT * FROM services_users_old;

INSERT INTO services_reminders_sent SELECT * FROM services_reminders_sent_old;

INSERT INTO acc_transactions SELECT * FROM acc_transactions_old;

39
40
41
42
43
44
45











DROP TABLE recherches;

INSERT INTO config VALUES ('log_retention', 720);
INSERT INTO config VALUES ('log_anonymize', 365);

-- This is now part of the config_users_fields table
DELETE FROM config WHERE key IN ('champs_membres', 'champ_identite', 'champ_identifiant');


















>
>
>
>
>
>
>
>
>
>
>
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
DROP TABLE recherches;

INSERT INTO config VALUES ('log_retention', 720);
INSERT INTO config VALUES ('log_anonymize', 365);

-- This is now part of the config_users_fields table
DELETE FROM config WHERE key IN ('champs_membres', 'champ_identite', 'champ_identifiant');

-- Seems that some installations had this leftover? Let's just drop it.
DROP TABLE IF EXISTS srs_old;

-- Drop membres
DROP TABLE IF EXISTS membres;

-- Manually update foreign keys
PRAGMA writable_schema = 1;
UPDATE sqlite_master SET sql = REPLACE(sql, 'REFERENCES membres', 'REFERENCES users') WHERE sql LIKE '%REFERENCES users' AND type = 'table';
PRAGMA writable_schema = 0;

Modified src/include/data/1.2.0_schema.sql from [6c2af0cde1] to [deb0df031b].

242
243
244
245
246
247
248




























249
250
251
252
253
254
255
    type INTEGER NOT NULL DEFAULT 0, -- type (category) of favourite account: bank, cash, third party, etc.
    user INTEGER NOT NULL DEFAULT 1 -- 0 = is part of the original chart, 0 = has been added by the user
);

CREATE UNIQUE INDEX IF NOT EXISTS acc_accounts_codes ON acc_accounts (code, id_chart);
CREATE INDEX IF NOT EXISTS acc_accounts_type ON acc_accounts (type);
CREATE INDEX IF NOT EXISTS acc_accounts_position ON acc_accounts (position);





























CREATE TABLE IF NOT EXISTS acc_years
-- Years (exercices)
(
    id INTEGER NOT NULL PRIMARY KEY,

    label TEXT NOT NULL,







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
    type INTEGER NOT NULL DEFAULT 0, -- type (category) of favourite account: bank, cash, third party, etc.
    user INTEGER NOT NULL DEFAULT 1 -- 0 = is part of the original chart, 0 = has been added by the user
);

CREATE UNIQUE INDEX IF NOT EXISTS acc_accounts_codes ON acc_accounts (code, id_chart);
CREATE INDEX IF NOT EXISTS acc_accounts_type ON acc_accounts (type);
CREATE INDEX IF NOT EXISTS acc_accounts_position ON acc_accounts (position);

-- Balance des comptes par exercice
CREATE VIEW IF NOT EXISTS acc_accounts_balances
AS
    SELECT id_year, id, label, code, type, debit, credit,
        CASE -- 3 = dynamic asset or liability depending on balance
            WHEN position = 3 AND (debit - credit) > 0 THEN 1 -- 1 = Asset (actif) comptes fournisseurs, tiers créditeurs
            WHEN position = 3 THEN 2 -- 2 = Liability (passif), comptes clients, tiers débiteurs
            ELSE position
        END AS position,
        CASE
            WHEN position IN (1, 4) -- 1 = asset, 4 = expense
                OR (position = 3 AND (debit - credit) > 0)
            THEN
                debit - credit
            ELSE
                credit - debit
        END AS balance,
        CASE WHEN debit - credit > 0 THEN 1 ELSE 0 END AS is_debt
    FROM (
        SELECT t.id_year, a.id, a.label, a.code, a.position, a.type,
            SUM(l.credit) AS credit,
            SUM(l.debit) AS debit
        FROM acc_accounts a
        INNER JOIN acc_transactions_lines l ON l.id_account = a.id
        INNER JOIN acc_transactions t ON t.id = l.id_transaction
        GROUP BY t.id_year, a.id
    );

CREATE TABLE IF NOT EXISTS acc_years
-- Years (exercices)
(
    id INTEGER NOT NULL PRIMARY KEY,

    label TEXT NOT NULL,

Modified src/include/init.php from [8b1eacdc1e] to [dcc287710a].

385
386
387
388
389
390
391

392

393
394
395
396
397
398
399
400
401
402
403
{
	if (PHP_SAPI == 'cli')
	{
		echo $e->getMessage();
	}
	else
	{

		$tpl = Template::getInstance();


		$tpl->assign('error', $e->getMessage());
		$tpl->assign('admin_url', ADMIN_URL);
		$tpl->display('error.tpl');
	}

	exit;
}

// Message d'erreur simple pour les erreurs de l'utilisateur
ErrorManager::setCustomExceptionHandler('\Garradin\UserException', '\Garradin\user_error');







>
|
>



|







385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
{
	if (PHP_SAPI == 'cli')
	{
		echo $e->getMessage();
	}
	else
	{
		// Don't use Template class as there might be an error there due do the context (eg. install/upgrade)
		$tpl = new \KD2\Smartyer(ROOT . '/templates/error.tpl');
		$tpl->setCompiledDir(SMARTYER_CACHE_ROOT);

		$tpl->assign('error', $e->getMessage());
		$tpl->assign('admin_url', ADMIN_URL);
		$tpl->display();
	}

	exit;
}

// Message d'erreur simple pour les erreurs de l'utilisateur
ErrorManager::setCustomExceptionHandler('\Garradin\UserException', '\Garradin\user_error');

Modified src/include/lib/Garradin/Entities/Users/DynamicField.php from [f4e72ae101] to [7162a58dd1].

139
140
141
142
143
144
145
146
147
148
149
150
151
152
153

	public function delete(): bool
	{
		if ($this->system) {
			throw new ValidationException('Ce champ est utilisé en interne, il n\'est pas possible de le supprimer');
		}

		parent::delete();
	}

	public function selfCheck(): void
	{
		$this->name = strtolower($this->name);

		$this->assert($this->read_access == self::ACCESS_ADMIN || $this->read_access == self::ACCESS_USER);







|







139
140
141
142
143
144
145
146
147
148
149
150
151
152
153

	public function delete(): bool
	{
		if ($this->system) {
			throw new ValidationException('Ce champ est utilisé en interne, il n\'est pas possible de le supprimer');
		}

		return parent::delete();
	}

	public function selfCheck(): void
	{
		$this->name = strtolower($this->name);

		$this->assert($this->read_access == self::ACCESS_ADMIN || $this->read_access == self::ACCESS_USER);

Modified src/include/lib/Garradin/Install.php from [675aaa64fd] to [d722f4e2f7].

384
385
386
387
388
389
390
391

392

		</style>
		%s
		</head>
		<body>
		<div class="spinner">
			<h2>%s</h2>
		</div>', $next, htmlspecialchars($message));
	}

}








|
>
|
>
384
385
386
387
388
389
390
391
392
393
394
		</style>
		%s
		</head>
		<body>
		<div class="spinner">
			<h2>%s</h2>
		</div>', $next, htmlspecialchars($message));

		flush();
	}
}

Modified src/include/lib/Garradin/Sauvegarde.php from [4fb461abaf] to [f39ba19919].

102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
		$backup = str_replace('.sqlite', sprintf('.%s.sqlite', $suffix), DB_FILE);

		$this->make($backup);

		return basename($backup);
	}

	protected function make(string $dest)
	{
		// Acquire lock
		$version = \SQLite3::version();
		$db = DB::getInstance();

		Utils::safe_unlink($dest);








|







102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
		$backup = str_replace('.sqlite', sprintf('.%s.sqlite', $suffix), DB_FILE);

		$this->make($backup);

		return basename($backup);
	}

	public function make(string $dest)
	{
		// Acquire lock
		$version = \SQLite3::version();
		$db = DB::getInstance();

		Utils::safe_unlink($dest);

480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
		{
			throw new UserException('Ce fichier n\'est pas une sauvegarde Garradin (application_id ne correspond pas).', self::NO_APP_ID);
		}

		$session = Session::getInstance();

		// Empêchons l'admin de se tirer une balle dans le pied
		if ($session->isLogged())
		{
			if (version_compare($version, '1.1', '<')) { // FIXME remove in 1.2
				$sql = 'SELECT 1 FROM membres_categories WHERE id = (SELECT id_categorie FROM membres WHERE id = %d) AND droit_connexion >= %d AND droit_config >= %d';
			}
			else {
				$sql = 'SELECT 1 FROM users_categories WHERE id = (SELECT id_category FROM membres WHERE id = %d) AND perm_connect >= %d AND perm_config >= %d';
			}

			$sql = sprintf($sql, $session->getUser()->id, Session::ACCESS_READ, Session::ACCESS_ADMIN);
			$is_still_admin = $db->querySingle($sql);

			if (!$is_still_admin)
			{







|

|
|


|







480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
		{
			throw new UserException('Ce fichier n\'est pas une sauvegarde Garradin (application_id ne correspond pas).', self::NO_APP_ID);
		}

		$session = Session::getInstance();

		// Empêchons l'admin de se tirer une balle dans le pied
		if ($session->isLogged(true))
		{
			if (version_compare($version, '1.2', '<')) { // FIXME remove in 1.3
				$sql = 'SELECT 1 FROM users_categories WHERE id = (SELECT id_category FROM membres WHERE id = %d) AND perm_connect >= %d AND perm_config >= %d';
			}
			else {
				$sql = 'SELECT 1 FROM users_categories WHERE id = (SELECT id_category FROM users WHERE id = %d) AND perm_connect >= %d AND perm_config >= %d';
			}

			$sql = sprintf($sql, $session->getUser()->id, Session::ACCESS_READ, Session::ACCESS_ADMIN);
			$is_still_admin = $db->querySingle($sql);

			if (!$is_still_admin)
			{
548
549
550
551
552
553
554






555
556
557
558
559
560
561

			// Check and upgrade plugins, if a software upgrade is necessary, plugins will be upgraded after the upgrade
			Plugin::upgradeAllIfRequired();
		}

		return $return;
	}







	/**
	 * Taille de la base de données actuelle
	 * @return integer Taille en octets du fichier SQLite
	 */
	public function getDBSize($signed = false)
	{







>
>
>
>
>
>







548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567

			// Check and upgrade plugins, if a software upgrade is necessary, plugins will be upgraded after the upgrade
			Plugin::upgradeAllIfRequired();
		}

		return $return;
	}

	public function restore(string $file)
	{
		DB::getInstance()->close();
		return copy($file, DB_FILE);
	}

	/**
	 * Taille de la base de données actuelle
	 * @return integer Taille en octets du fichier SQLite
	 */
	public function getDBSize($signed = false)
	{

Modified src/include/lib/Garradin/Template.php from [b430a84845] to [dcd0c8e1a9].

75
76
77
78
79
80
81

82
83
84
85
86
87
88
89
90
91
		$this->assign('www_url', WWW_URL);
		$this->assign('help_url', HELP_URL);
		$this->assign('admin_url', ADMIN_URL);
		$this->assign('self_url', Utils::getSelfURI());
		$this->assign('self_url_no_qs', Utils::getSelfURI(false));

		$session = Session::getInstance();


		$this->assign('is_logged', $session->isLogged());
		$this->assign('logged_user', $session->getUser());
		$this->assign('session', $session);
		$this->assign('config', Config::getInstance());
		$this->assign('dialog', isset($_GET['_dialog']));

		$this->assign('password_pattern', sprintf('.{%d,}', Session::MINIMUM_PASSWORD_LENGTH));
		$this->assign('password_length', Session::MINIMUM_PASSWORD_LENGTH);








>

|
|







75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
		$this->assign('www_url', WWW_URL);
		$this->assign('help_url', HELP_URL);
		$this->assign('admin_url', ADMIN_URL);
		$this->assign('self_url', Utils::getSelfURI());
		$this->assign('self_url_no_qs', Utils::getSelfURI(false));

		$session = Session::getInstance();
		$logged = $session->isLogged(true);

		$this->assign('is_logged', $logged);
		$this->assign('logged_user', $logged ? $session->getUser() : null);
		$this->assign('session', $session);
		$this->assign('config', Config::getInstance());
		$this->assign('dialog', isset($_GET['_dialog']));

		$this->assign('password_pattern', sprintf('.{%d,}', Session::MINIMUM_PASSWORD_LENGTH));
		$this->assign('password_length', Session::MINIMUM_PASSWORD_LENGTH);

Modified src/include/lib/Garradin/Upgrade.php from [056dd9e67c] to [70de025310].

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

use KD2\HTTP;

use KD2\FossilInstaller;

class Upgrade
{
	const MIN_REQUIRED_VERSION = '1.1.0';

	static protected $installer = null;

	static public function preCheck(): bool
	{
		$v = DB::getInstance()->version();








|







9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

use KD2\HTTP;

use KD2\FossilInstaller;

class Upgrade
{
	const MIN_REQUIRED_VERSION = '1.1.19';

	static protected $installer = null;

	static public function preCheck(): bool
	{
		$v = DB::getInstance()->version();

48
49
50
51
52
53
54

55
56
57
58
59
60
61

62
63
64
65
66
67
68
69
		$session->isLogged(true);
		return true;
	}

	static public function upgrade()
	{
		$db = DB::getInstance();

		$v = $db->version();

		Plugin::toggleSignals(false);

		Static_Cache::store('upgrade', 'Mise à jour en cours.');

		// Créer une sauvegarde automatique

		$backup_name = (new Sauvegarde)->create(false, 'pre-upgrade-' . garradin_version());

		try {
			if (version_compare($v, '1.1.1', '<')) {
				// Reset admin_background if the file does not exist
				$bg = $db->firstColumn('SELECT value FROM config WHERE key = \'admin_background\';');

				if ($bg) {







>




|


>
|







48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
		$session->isLogged(true);
		return true;
	}

	static public function upgrade()
	{
		$db = DB::getInstance();
		$backup = new Sauvegarde;
		$v = $db->version();

		Plugin::toggleSignals(false);

		Static_Cache::store('upgrade', 'Updating');

		// Créer une sauvegarde automatique
		$backup_file = sprintf(DATA_ROOT . '/association.pre_upgrade-%s.sqlite', garradin_version());
		$backup->make($backup_file);

		try {
			if (version_compare($v, '1.1.1', '<')) {
				// Reset admin_background if the file does not exist
				$bg = $db->firstColumn('SELECT value FROM config WHERE key = \'admin_background\';');

				if ($bg) {
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
				// Set new types for accounts
				$db->import(ROOT . '/include/data/1.1.19_migration.sql');

				$db->commitSchemaUpdate();
			}

			if (version_compare($v, '1.1.21', '<')) {
				$db->begin();
				// Add id_analytical column to services_fees
				$db->import(ROOT . '/include/data/1.1.21_migration.sql');
				$db->commit();
			}

			if (version_compare($v, '1.1.22', '<')) {
				$db->begin();
				// Create acc_accounts_balances view
				$db->import(ROOT . '/include/data/1.1.0_schema.sql');
				$db->commit();
			}

			if (version_compare($v, '1.2.0', '<')) {
				$config = (object) $db->getAssoc('SELECT key, value FROM config WHERE key IN (\'champs_membres\', \'champ_identifiant\', \'champ_identite\');');
				$db->begin();

				// Create config_users_fields table
				$db->import(ROOT . '/include/data/1.2.0_schema.sql');


				// Migrate users table
				$df = \Garradin\Users\DynamicFields::fromOldINI($config->champs_membres, $config->champ_identifiant, $config->champ_identite, 'numero');
				$df->save();

				// Migrate other stuff





				$db->import(ROOT . '/include/data/1.2.0_migration.sql');
				$db->commit();
			}






			// Vérification de la cohérence des clés étrangères
			$db->foreignKeyCheck();

			// Delete local cached files
			Utils::resetCache(USER_TEMPLATES_CACHE_ROOT);
			Utils::resetCache(STATIC_CACHE_ROOT);







|


|



|


|




|



<






>
>
>
>
>

|

>
>
>
>
>







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
				// Set new types for accounts
				$db->import(ROOT . '/include/data/1.1.19_migration.sql');

				$db->commitSchemaUpdate();
			}

			if (version_compare($v, '1.1.21', '<')) {
				$db->beginSchemaUpdate();
				// Add id_analytical column to services_fees
				$db->import(ROOT . '/include/data/1.1.21_migration.sql');
				$db->commitSchemaUpdate();
			}

			if (version_compare($v, '1.1.22', '<')) {
				$db->beginSchemaUpdate();
				// Create acc_accounts_balances view
				$db->import(ROOT . '/include/data/1.1.0_schema.sql');
				$db->commitSchemaUpdate();
			}

			if (version_compare($v, '1.2.0', '<')) {
				$config = (object) $db->getAssoc('SELECT key, value FROM config WHERE key IN (\'champs_membres\', \'champ_identifiant\', \'champ_identite\');');
				$db->beginSchemaUpdate();

				// Create config_users_fields table
				$db->import(ROOT . '/include/data/1.2.0_schema.sql');


				// Migrate users table
				$df = \Garradin\Users\DynamicFields::fromOldINI($config->champs_membres, $config->champ_identifiant, $config->champ_identite, 'numero');
				$df->save();

				// Migrate other stuff
				$db->commitSchemaUpdate();
				$db->close();

				ini_set('sqlite3.defensive', 0);
				$db->beginSchemaUpdate();
				$db->import(ROOT . '/include/data/1.2.0_migration.sql');
				$db->commitSchemaUpdate();
			}

			// Réinstaller les plugins système si nécessaire
			Plugin::checkAndInstallSystemPlugins();

			Plugin::upgradeAllIfRequired();

			// Vérification de la cohérence des clés étrangères
			$db->foreignKeyCheck();

			// Delete local cached files
			Utils::resetCache(USER_TEMPLATES_CACHE_ROOT);
			Utils::resetCache(STATIC_CACHE_ROOT);
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
			file_put_contents($cache_version_file, garradin_version());
			$db->setVersion(garradin_version());

			// reset last version check
			$db->exec('UPDATE config SET value = NULL WHERE key = \'last_version_check\';');

			Static_Cache::remove('upgrade');

			// Réinstaller les plugins système si nécessaire
			Plugin::checkAndInstallSystemPlugins();

			Plugin::upgradeAllIfRequired();
		}
		catch (\Exception $e)
		{
			if ($db->inTransaction()) {
				$db->rollback();
			}

			$s = new Sauvegarde;
			$s->restoreFromLocal($backup_name);
			$s->remove($backup_name);
			Static_Cache::remove('upgrade');
			throw $e;
		}


		$session = Session::getInstance();
		$user_is_logged = $session->isLogged(true);

		// Forcer à rafraîchir les données de la session si elle existe
		if ($user_is_logged)
		{







<
<
<
<
<







|
|
|



<







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
			file_put_contents($cache_version_file, garradin_version());
			$db->setVersion(garradin_version());

			// reset last version check
			$db->exec('UPDATE config SET value = NULL WHERE key = \'last_version_check\';');

			Static_Cache::remove('upgrade');





		}
		catch (\Exception $e)
		{
			if ($db->inTransaction()) {
				$db->rollback();
			}

			$db->close();
			rename($backup_file, DB_FILE);

			Static_Cache::remove('upgrade');
			throw $e;
		}


		$session = Session::getInstance();
		$user_is_logged = $session->isLogged(true);

		// Forcer à rafraîchir les données de la session si elle existe
		if ($user_is_logged)
		{

Modified src/include/lib/Garradin/Users/DynamicFields.php from [6468421ece] to [4fb2df2bc7].

193
194
195
196
197
198
199











200
201
202
203
204
205
206
		return $this->_fields_by_type[$type] ?? [];
	}

	public function fieldByKey(string $key): ?DynamicField
	{
		return $this->_fields[$key] ?? null;
	}












	public function fieldsBySystemUse(string $use): array
	{
		return $this->_fields_by_system_use[$use] ?? [];
	}

	public function getEntityTypes(): array







>
>
>
>
>
>
>
>
>
>
>







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
		return $this->_fields_by_type[$type] ?? [];
	}

	public function fieldByKey(string $key): ?DynamicField
	{
		return $this->_fields[$key] ?? null;
	}

	public function fieldById(int $id): ?DynamicField
	{
		foreach ($this->_fields as $field) {
			if ($field->id === $id) {
				return $field;
			}
		}

		return null;
	}

	public function fieldsBySystemUse(string $use): array
	{
		return $this->_fields_by_system_use[$use] ?? [];
	}

	public function getEntityTypes(): array
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504

505
506
507
508
509
510
511
		return $sql;
	}

	public function getCopyFields(): array
	{
		// Champs à recopier
		$copy = array_keys(DynamicField::SYSTEM_FIELDS) + array_keys($this->_fields);
		return $copy;
	}

	public function getSQLCopy(string $old_table_name, string $new_table_name = User::TABLE, array $fields = null): string
	{
		if (null === $fields) {
			$fields = $this->getCopyFields();
		}

		$db = DB::getInstance();

		return sprintf('INSERT INTO %s (id, %s) SELECT id, %s FROM %s;',
			$new_table_name,
			implode(', ', array_map([$db, 'quoteIdentifier'], $fields)),
			implode(', ', array_map([$db, 'quoteIdentifier'], array_keys($fields))),
			$old_table_name
		);
	}

	public function copy(string $old_table_name, string $new_table_name = User::TABLE, array $fields = null): void
	{

		DB::getInstance()->exec($this->getSQLCopy($old_table_name, $new_table_name, $fields));
	}

	public function create(string $table_name = User::TABLE)
	{
		$db = DB::getInstance();
		$db->begin();







|




















>







488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
		return $sql;
	}

	public function getCopyFields(): array
	{
		// Champs à recopier
		$copy = array_keys(DynamicField::SYSTEM_FIELDS) + array_keys($this->_fields);
		return array_combine($copy, $copy);
	}

	public function getSQLCopy(string $old_table_name, string $new_table_name = User::TABLE, array $fields = null): string
	{
		if (null === $fields) {
			$fields = $this->getCopyFields();
		}

		$db = DB::getInstance();

		return sprintf('INSERT INTO %s (id, %s) SELECT id, %s FROM %s;',
			$new_table_name,
			implode(', ', array_map([$db, 'quoteIdentifier'], $fields)),
			implode(', ', array_map([$db, 'quoteIdentifier'], array_keys($fields))),
			$old_table_name
		);
	}

	public function copy(string $old_table_name, string $new_table_name = User::TABLE, array $fields = null): void
	{
		//var_dump($this->getSQLCopy($old_table_name, $new_table_name, $fields)); exit;
		DB::getInstance()->exec($this->getSQLCopy($old_table_name, $new_table_name, $fields));
	}

	public function create(string $table_name = User::TABLE)
	{
		$db = DB::getInstance();
		$db->begin();
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589





590

591




592
593
594
595
596
597
598
	 * Enregistre les changements de champs en base de données
	 * @return boolean true
	 */
	public function rebuildUsersTable()
	{
		$db = DB::getInstance();

		$db->exec('PRAGMA foreign_keys = OFF;');

		$db->begin();
		$this->createTable(User::TABLE . '_tmp');
		$this->copy(User::TABLE, User::TABLE . '_tmp');
		$db->exec(sprintf('DROP TABLE IF EXISTS %s;', User::TABLE));
		$db->exec(sprintf('ALTER TABLE %s_tmp RENAME TO %1$s;', User::TABLE));

		$this->createIndexes(User::TABLE);

		$db->commit();
		$db->exec('PRAGMA foreign_keys = ON;');

		return true;
	}

	public function preview(array $fields)
	{
	}

	public function add(DynamicField $df)
	{
		$this->_fields[$df->name] = $df;
		$this->reloadCache();
	}

	public function delete(string $name)
	{





		unset($this->_fields[$name]);

		$this->reloadCache();




	}

	public function save()
	{
		if (empty($this->_fields_by_system_use['number'])) {
			throw new ValidationException('Aucun champ de numéro de membre n\'existe');
		}







<
<
|







|
<
















>
>
>
>
>

>
|
>
>
>
>







567
568
569
570
571
572
573


574
575
576
577
578
579
580
581
582

583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
	 * Enregistre les changements de champs en base de données
	 * @return boolean true
	 */
	public function rebuildUsersTable()
	{
		$db = DB::getInstance();



		$db->beginSchemaUpdate();
		$this->createTable(User::TABLE . '_tmp');
		$this->copy(User::TABLE, User::TABLE . '_tmp');
		$db->exec(sprintf('DROP TABLE IF EXISTS %s;', User::TABLE));
		$db->exec(sprintf('ALTER TABLE %s_tmp RENAME TO %1$s;', User::TABLE));

		$this->createIndexes(User::TABLE);

		$db->commitSchemaUpdate();


		return true;
	}

	public function preview(array $fields)
	{
	}

	public function add(DynamicField $df)
	{
		$this->_fields[$df->name] = $df;
		$this->reloadCache();
	}

	public function delete(string $name)
	{
		$db = DB::getInstance();

		$db->begin();

		$this->_fields[$name]->delete();
		unset($this->_fields[$name]);

		$this->reload();
		// FIXME/TODO: use ALTER TABLE ... DROP COLUMN for SQLite 3.35.0+
		$this->rebuildUsersTable();

		$db->commit();
	}

	public function save()
	{
		if (empty($this->_fields_by_system_use['number'])) {
			throw new ValidationException('Aucun champ de numéro de membre n\'existe');
		}

Modified src/include/lib/Garradin/Users/Session.php from [a5ae9b91f2] to [a6264911af].

174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
		return $logged;
	}

	public function forceLogin(int $id)
	{
		// On va chercher le premier membre avec le droit de gérer la config
		if (-1 === $id) {
			$id = $this->db->firstColumn('SELECT id FROM membres
				WHERE id_category IN (SELECT id FROM users_categories WHERE perm_config = ?)
				LIMIT 1', self::ACCESS_ADMIN);
		}

		$logged = parent::isLogged();

		// Only login if required







|







174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
		return $logged;
	}

	public function forceLogin(int $id)
	{
		// On va chercher le premier membre avec le droit de gérer la config
		if (-1 === $id) {
			$id = $this->db->firstColumn('SELECT id FROM users
				WHERE id_category IN (SELECT id FROM users_categories WHERE perm_config = ?)
				LIMIT 1', self::ACCESS_ADMIN);
		}

		$logged = parent::isLogged();

		// Only login if required

Modified src/templates/admin/config/fields/index.tpl from [3fb3d0a0e0] to [aba9e76cf1].

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
					{button shape="menu" title="Cliquer, glisser et déposer pour modifier l'ordre"}
					<input type="hidden" name="sort_order[]" value="{$field.name}" />
				</td>
				<th>{$field.label}</th>
				<td>{if $field.list_row}Oui{else}Non{/if}</td>
				<td class="actions">
					{if !$field.system || ($field.system && !($field.system | $field::PRESET))}
						{linkbutton shape="delete" label="Supprimer" href="delete.php?id=%d"|args:$field.id}
					{/if}
					{linkbutton shape="edit" label="Modifier" href="edit.php?id=%d"|args:$field.id}
				</td>
			</tr>
		{/foreach}
		</tbody>
	</table>

	<p class="submit">







|

|







35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
					{button shape="menu" title="Cliquer, glisser et déposer pour modifier l'ordre"}
					<input type="hidden" name="sort_order[]" value="{$field.name}" />
				</td>
				<th>{$field.label}</th>
				<td>{if $field.list_row}Oui{else}Non{/if}</td>
				<td class="actions">
					{if !$field.system || ($field.system && !($field.system | $field::PRESET))}
						{linkbutton shape="delete" label="Supprimer" href="delete.php?id=%d"|args:$field.id target="_dialog"}
					{/if}
					{linkbutton shape="edit" label="Modifier" href="edit.php?id=%d"|args:$field.id target="_dialog"}
				</td>
			</tr>
		{/foreach}
		</tbody>
	</table>

	<p class="submit">

Modified src/www/admin/static/scripts/global.js from [0ed8a5d92b] to [e9641af360].

502
503
504
505
506
507
508










509
510
511
512
513
514
515
	});

	g.onload(() => {
		if (document.querySelector('input[type="file"][data-enhanced]')) {
			g.script('scripts/file_input.js');
		}
	});











	// To be able to select a whole table line just by clicking the row
	g.onload(function () {
		var tableActions = document.querySelectorAll('form table tfoot .actions select');

		for (var i = 0; i < tableActions.length; i++)
		{







>
>
>
>
>
>
>
>
>
>







502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
	});

	g.onload(() => {
		if (document.querySelector('input[type="file"][data-enhanced]')) {
			g.script('scripts/file_input.js');
		}
	});

	g.onload(() => {
		let forms = document.forms;

		if (forms.length != 1) return;

		forms[0].addEventListener('submit', () => {
			forms[0].classList.add('progressing');
		})
	});

	// To be able to select a whole table line just by clicking the row
	g.onload(function () {
		var tableActions = document.querySelectorAll('form table tfoot .actions select');

		for (var i = 0; i < tableActions.length; i++)
		{

Modified src/www/admin/static/styles/03-forms.css from [22984e2204] to [316be8e461].

641
642
643
644
645
646
647
648
649
650
651



652


653
654

655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
.file-selector table.list .num {
    text-align: right;
}

/**
 * Progress spinner
 */
.progressing {
    position: relative;
}




fieldset.progressing > dl, fieldset.progressing > p {


    opacity: 0.5;
    filter: blur(3px);

}

.progressing::after {
    display: inline-block;
    content: " ";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 50px;
    height: 50px;
    border: 5px solid #666;
    border-radius: 50%;
    border-top-color: #ccc;
    animation: spin 1s ease-in-out infinite;
    filter: none;
}

.progress-status {
    display: none;
}







|



>
>
>
|
>
>


>













|

|







641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
.file-selector table.list .num {
    text-align: right;
}

/**
 * Progress spinner
 */
form.progressing {
    position: relative;
}

form fieldset, form p.submit {
    transition: .5s filter linear;
}

form.progressing fieldset, form.progressing p.submit {
    pointer-events: none;
    opacity: 0.5;
    filter: blur(3px);
    filter: grayscale(100%) blur(3px);
}

.progressing::after {
    display: inline-block;
    content: " ";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 50px;
    height: 50px;
    border: 5px solid var(--gBorderColor);
    border-radius: 50%;
    border-top-color: var(--gLightBackgroundColor);
    animation: spin 1s ease-in-out infinite;
    filter: none;
}

.progress-status {
    display: none;
}

Modified src/www/admin/upgrade.php from [f17b581907] to [2aa1609a28].

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

<?php

namespace Garradin;

const UPGRADE_PROCESS = true;

require_once __DIR__ . '/../../include/test_required.php';
require_once __DIR__ . '/../../include/init.php';

if (!Upgrade::preCheck()) {
	throw new UserException('Aucune mise à jour à effectuer, tout est à jour :-)');
}

echo '<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=device-dpi" />
    <link rel="stylesheet" type="text/css" href="static/admin.css" media="all" />
    <script type="text/javascript" src="static/scripts/loader.js"></script>
    <title>Mise à jour</title>
</head>
<body>
<header class="header">
    <nav class="menu"></nav>
    <h1>Mise à jour de Garradin vers la version '.garradin_version().'...</h1>
</header>
<main>
<div id="loader" class="loader" style="margin: 2em 0; height: 50px;"></div>
<script>
animatedLoader(document.getElementById("loader"), 5);
</script>';

flush();

Upgrade::upgrade();

echo '<h2>Mise à jour terminée.</h2>
<p><a href="'.ADMIN_URL.'">Retour</a></p>

<script type="text/javascript">
window.setTimeout(function () { 
    window.location.href = "'.ADMIN_URL.'"; 
    stopAnimatedLoader();


}, 1000);
</script>
</main>
</body>
</html>';














<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
|

|
<
|
<
|
<
<
>
>
|
<
<
<
<
>
1
2
3
4
5
6
7
8
9
10
11
12
13



















14


15
16
17

18

19


20
21
22




23
<?php

namespace Garradin;

const UPGRADE_PROCESS = true;

require_once __DIR__ . '/../../include/test_required.php';
require_once __DIR__ . '/../../include/init.php';

if (!Upgrade::preCheck()) {
	throw new UserException('Aucune mise à jour à effectuer, tout est à jour :-)');
}




















if (isset($_GET['next'])) {


    Upgrade::upgrade();

    Install::showProgressSpinner('!', 'Mise à jour terminée');

}

else {


    Install::showProgressSpinner('!upgrade.php?next',
        sprintf('Mise à jour de version : %s → %s', DB::getInstance()->version(), garradin_version())
    );




}