Overview
Comment:Refactor of Config class, using AbstractEntity in a key-value model
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | dev
Files: files | file ages | folders
SHA1: 04b6151bfe2c529f1d56b0186294105abe16a1fb
User & Date: bohwaz on 2020-12-12 17:20:47
Other Links: branch diff | manifest | tags
Context
2020-12-12
17:21
More progress on migration to files and web pages check-in: ba3e9fabe2 user: bohwaz tags: dev
17:20
Refactor of Config class, using AbstractEntity in a key-value model check-in: 04b6151bfe user: bohwaz tags: dev
15:36
Working migration, remove categories for now check-in: 916600f4fe user: bohwaz tags: dev
Changes

Modified src/include/init.php from [53a38bd077] to [e6355f8bdd].

317
318
319
320
321
322
323
324
325
326
327
328
329
330
if (!defined('Garradin\INSTALL_PROCESS') && !defined('Garradin\UPGRADE_PROCESS'))
{
	if (!file_exists(DB_FILE))
	{
		Utils::redirect(ADMIN_URL . 'install.php');
	}

	$config = Config::getInstance();

	if (version_compare($config->getVersion(), garradin_version(), '<'))
	{
		Utils::redirect(ADMIN_URL . 'upgrade.php');
	}
}







|

|




317
318
319
320
321
322
323
324
325
326
327
328
329
330
if (!defined('Garradin\INSTALL_PROCESS') && !defined('Garradin\UPGRADE_PROCESS'))
{
	if (!file_exists(DB_FILE))
	{
		Utils::redirect(ADMIN_URL . 'install.php');
	}

	$v = DB::getInstance()->firstColumn('SELECT valeur FROM config WHERE cle = \'version\';');

	if (version_compare($v, garradin_version(), '<'))
	{
		Utils::redirect(ADMIN_URL . 'upgrade.php');
	}
}

Modified src/include/lib/Garradin/Config.php from [85c9d942d5] to [7305829509].

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
<?php

namespace Garradin;





use KD2\SMTP;

class Config
{







    protected $fields_types = null;
















    protected $config = null;
    protected $modified = [];






































    static protected $_instance = null;

    /**
     * Singleton simple
     * @return Config
     */
    static public function getInstance()
    {
        return self::$_instance ?: self::$_instance = new Config;
    }

    static public function deleteInstance()
    {
        self::$_instance = null;
    }

    /**
     * Empêche de cloner l'objet
     * @return void
     */
    private function __clone()
    {

    }

    protected function __construct()
    {
        // Définition des types de données stockées
        $string = '';
        $int = 0;
        $float = 0.0;
        $array = [];
        $bool = false;
        $object = new \stdClass;

        $this->fields_types = [
            'nom_asso'                =>  $string,
            'adresse_asso'            =>  $string,
            'email_asso'              =>  $string,
            'site_asso'               =>  $string,

            'monnaie'                 =>  $string,
            'pays'                    =>  $string,

            'champs_membres'          =>  $object,

            'categorie_membres'       =>  $int,



            'accueil_wiki'            =>  $string,
            'accueil_connexion'       =>  $string,


            'frequence_sauvegardes'   =>  $int,
            'nombre_sauvegardes'      =>  $int,

            'champ_identifiant'       =>  $string,
            'champ_identite'          =>  $string,

            'version'                 =>  $string,
            'last_chart_change'       =>  $int,
            'last_version_check'      =>  $string,

            'couleur1'                =>  $string,
            'couleur2'                =>  $string,
            'image_fond'              =>  $string,

            'desactiver_site'         =>  $bool,
        ];


        $db = DB::getInstance();

        $this->config = $db->getAssoc('SELECT cle, valeur FROM config ORDER BY cle;');

        foreach ($this->config as $key=>&$value)
        {
            if (!array_key_exists($key, $this->fields_types))
            {
                // Ancienne clé de config qui n'est plus utilisée
                continue;
            }

            if (is_array($this->fields_types[$key]))
            {
                $value = explode(',', $value);
            }
            elseif ($key == 'champs_membres')
            {
                $value = new Membres\Champs((string)$value);
            }
            else
            {
                settype($value, gettype($this->fields_types[$key]));
            }
        }
    }

    public function __destruct()
    {
        if (!empty($this->modified))
        {
            // FIXME: on devrait loguer/envoyer une erreur ici si on a modifié quelque chose sans le sauver
            //echo '<div style="color: red; background: #fff;">Il y a des champs modifiés non sauvés dans '.__CLASS__.' !</div>';

        }
    }

    public function save()

    {
        if (empty($this->modified))
            return true;

        $values = [];
        $db = DB::getInstance();

        // Image files
        if (isset($this->modified['image_fond'])) {
            $key = 'image_fond';
            $value =& $this->config[$key];

            if ($current = $db->firstColumn('SELECT valeur FROM config WHERE cle = ?;', $key))
            {

                try {
                    $f = new Fichiers($current);
                    $f->remove();
                }
                catch (\InvalidArgumentException $e) {
                    // Ignore: the file has already been deleted
                }
            }

            if (strlen($value) > 0)
            {
                $content = $value;
                $value = null;
                $f = Fichiers::storeFromBase64($key . '.png', $content);
                $value = $f->id;
                unset($f);
            }
        }

        unset($value, $key);

        $db->begin();

        foreach ($this->modified as $key=>$modified)
        {
            $value = $this->config[$key];

            if (is_array($value))
            {
                $value = implode(',', $value);
            }
            elseif (is_object($value))
            {
                $value = (string) $value;
            }

            $db->preparedQuery('INSERT OR REPLACE INTO config (cle, valeur) VALUES (?, ?);',
                [$key, $value]);
        }

        if (!empty($this->modified['champ_identifiant']))
        {
            // Mettre les champs identifiant vides à NULL pour pouvoir créer un index unique
            $db->exec('UPDATE membres SET '.$this->get('champ_identifiant').' = NULL
                WHERE '.$this->get('champ_identifiant').' = "";');

            // Création de l'index unique
            $db->exec('DROP INDEX IF EXISTS membres_identifiant;');
            $db->exec('CREATE UNIQUE INDEX membres_identifiant ON membres ('.$this->get('champ_identifiant').');');
        }

        $db->commit();

        $this->modified = [];

        return true;
    }

    public function get($key)
    {
        if (!array_key_exists($key, $this->fields_types))
        {
            throw new \OutOfBoundsException('Ce champ est inconnu.');
        }

        if (!array_key_exists($key, $this->config))
        {
            return null;
        }

        return $this->config[$key];
    }

    public function getVersion()
    {
        if (!array_key_exists('version', $this->config))
        {
            return '0';
        }

        return $this->config['version'];
    }

    public function setVersion($version)
    {
        $this->config['version'] = $version;

        $db = DB::getInstance();
        $db->preparedQuery('INSERT OR REPLACE INTO config (cle, valeur) VALUES (?, ?);',
                ['version', $version]);

        return true;
    }

    public function set($key, $value)
    {
        if (!array_key_exists($key, $this->fields_types))
        {
            throw new \OutOfBoundsException('Ce champ est inconnu.');
        }

        if (is_array($this->fields_types[$key]))
        {
            $value = !empty($value) ? (array) $value : [];
        }
        elseif (is_int($this->fields_types[$key]))
        {

            $value = (int) $value;
        }
        elseif (is_float($this->fields_types[$key]))
        {
            $value = (float) $value;
        }
        elseif (is_bool($this->fields_types[$key]))
        {
            $value = (bool) $value;
        }
        elseif (is_string($this->fields_types[$key]))
        {
            $value = (string) $value;
        }

        switch ($key)
        {
            case 'nom_asso':
            {
                if (!trim($value))
                {
                    throw new UserException('Le nom de l\'association ne peut rester vide.');
                }
                break;
            }
            case 'accueil_wiki':
            case 'accueil_connexion':
            {
                $value = trim($value);
                $name = str_replace('accueil_', '', $key);

                if ($value === '')
                {
                    throw new UserException(sprintf('Le nom de la page d\'accueil %s ne peut rester vide.', $name));
                }


                $db = DB::getInstance();


                if (!$db->test('wiki_pages', $db->where('uri', $value))) {
                    throw new UserException(sprintf('Le nom de la page d\'accueil %s ne correspond à aucune page existante, merci de la créer auparavant.', $name));
                }
                break;
            }
            case 'email_asso':
            {
                if (!SMTP::checkEmailIsValid($value, false))
                {
                    throw new UserException('Adresse e-mail invalide.');
                }
                break;
            }
            case 'champs_membres':
            {
                if (!($value instanceOf Membres\Champs))

                {
                    throw new \UnexpectedValueException('$value doit être de type Membres\Champs');
                }
                break;
            }
            case 'champ_identite':
            case 'champ_identifiant':
            {

                $champs = $this->get('champs_membres');
                $db = DB::getInstance();

                // Vérification que le champ existe bien
                if (!$champs->get($value))
                {
                    throw new UserException('Le champ '.$value.' n\'existe pas pour la configuration de '.$key);
                }

                // Vérification que le champ est unique pour l'identifiant
                if ($key == 'champ_identifiant'
                    && !$db->firstColumn('SELECT (COUNT(DISTINCT lower('.$value.')) = COUNT(*))

                        FROM membres WHERE '.$value.' IS NOT NULL AND '.$value.' != \'\';'))
                {
                    throw new UserException('Le champ '.$value.' comporte des doublons et ne peut donc pas servir comme identifiant pour la connexion.');
                }
                break;
            }
            case 'categorie_membres':
            {
                $db = DB::getInstance();
                if (!$db->firstColumn('SELECT 1 FROM membres_categories WHERE id = ?;', $value))
                {
                    throw new UserException('La catégorie de membres par défaut numéro \''.$value.'\' ne semble pas exister.');
                }
                break;
            }
            case 'monnaie':
            {
                if (!trim($value))
                {
                    throw new UserException('La monnaie doit être renseignée.');
                }

                break;
            }
            case 'pays':
            {
                if (!trim($value) || !Utils::getCountryName($value))
                {
                    throw new UserException('Le pays renseigné est invalide.');
                }

                break;
            }
            default:
                break;
        }

        if (!isset($this->config[$key]) || $value !== $this->config[$key])
        {
            $this->config[$key] = $value;
            $this->modified[$key] = true;
        }

        return true;
    }

    public function getFieldsTypes()
    {
        return $this->fields_types;
    }

    public function getConfig()
    {
        return $this->config;
    }
}




>
>
>
>


|

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

|

|
|
|
|
|
|
|
|

|
|
|
|

<
<
<
<
|
|
>
|

|
|
<
|
<
<
<
<
<

|
<
<
<
<

<
<
|
<

<
>
>

|
<

>
|
<

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

>
|
|
<
|
<
|
|
<
<
<
|
<
<
<
<
<
<
<
|
<
<
<
|
|
|
<
<
|
|
|
<
<
<
>
|
|
|
<
>
|
|
|

|
|
|
<
|
<
|
|
<
<
>
|
<
<
|
<
<
|
<
<
<
<
|
<
<
<
<
|
|
<
|

|

|
|
|

|
|
|
|
|
|
|
|

|
|
|

|
|
|
|
|

|
|
|
|

|

|

|
|

|
|
<
<
<
<
|
<
<
<
|

<
<
<
|
|
<
<
|
|

<
<
<
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
<
<
<
<
<
>
|
|
<
|
<
<
<
<
<
<
<
<
|
<
|
|
<
|
<
|
<
<
<
<
<
|
<
<
|
<
|
|
<
<
<
|
>
|
>
|
|
<
<
|
<
<
<
<
<
|
|
<
|
<
|
<
>
|
<
<
<
<
<
<
<
>
|
<
|
<
<
<
<
<
|
<
<
<
>
|
|
<
<
<
<
|
<
<
<
|
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
|
<
|
<
<
<
|
<
<
|
<
<
|
<
|
|
<
|
|
|

|
|
|
|

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
<?php

namespace Garradin;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\Membres\Champs;

use KD2\SMTP;

class Config extends Entity
{
	protected $nom_asso;
	protected $adresse_asso;
	protected $email_asso;
	protected $telephone_asso;
	protected $site_asso;

	protected $monnaie;
	protected $pays;

	protected $champs_membres;
	protected $categorie_membres;

	protected $admin_homepage;

	protected $frequence_sauvegardes;
	protected $nombre_sauvegardes;

	protected $champ_identifiant;
	protected $champ_identite;

	protected $version;
	protected $last_chart_change;
	protected $last_version_check;

	protected $couleur1;
	protected $couleur2;

	protected $image_fond;

	protected $desactiver_site;

	protected $_types = [
		'nom_asso'              => 'string',
		'adresse_asso'          => '?string',
		'email_asso'            => 'string',
		'telephone_asso'        => '?string',
		'site_asso'             => '?string',

		'monnaie'               => 'string',
		'pays'                  => 'string',

		'champs_membres'        => Champs::class,

		'categorie_membres'     => 'int',

		'admin_homepage'        => '?Garradin\Entities\Files\File',

		'frequence_sauvegardes' => 'int',
		'nombre_sauvegardes'    => 'int',

		'champ_identifiant'     => 'string',
		'champ_identite'        => 'string',

		'version'               => 'string',
		'last_chart_change'     => '?int',
		'last_version_check'    => '?string',

		'couleur1'              => '?string',
		'couleur2'              => '?string',
		'image_fond'            => '?Garradin\Entities\Files\File',

		'desactiver_site'       => 'bool',
	];

	static protected $_instance = null;

	/**
	 * Singleton simple
	 * @return Config
	 */
	static public function getInstance()
	{
		return self::$_instance ?: self::$_instance = new self;
	}

	static public function deleteInstance()
	{
		self::$_instance = null;
	}





	public function __clone()
	{
		throw new \LogicException('Cannot clone config');
	}

	protected function __construct()
	{

		parent::__construct();






		$db = DB::getInstance();







		$config = $db->getAssoc('SELECT cle, valeur FROM config ORDER BY cle;');



		$default = array_fill_keys(array_keys($this->_types), null);
		$config = array_merge($default, $config);

		$config['champs_membres'] = new Champs($config['champs_membres']);


		foreach ($this->_types as $key => $type) {
			$value = $config[$key];




			if ($type[0] == '?' && $value === null) {



				continue;



			}



			if ($type == File::class || substr($type, 1) == File::class) {
				$config[$key] = Files::get((int) $value);
			}

		}


		$this->load($config);











		$this->champs_membres = new Membres\Champs((string)$value);



		$this->accueil_connexion = $this->accueil_connexion ? Files::get($this->accueil_connexion) : null;
	}



	public function save(): bool
	{
		if (!count($this->_modified)) {



			return true;
		}

		$values = [];

		$db = DB::getInstance();

		foreach ($this->_modified as $key => $modified) {
			$value = $this->$key;

			if ($this->_types[$key] == File::class && null === $value && $this->$key !== null) {
				$this->$key->delete();
			}

			elseif ($this->_types[$key] == File::class && null !== $value) {

				$value = $value->id();
			}


			else if ($this->_types[$key] == Champs::class) {
				$value = $value->toString();


			}







			$values[$key] = $value;




		}


		unset($value, $key, $modified);

		$db->begin();

		foreach ($this->modified as $key=>$modified)
		{
			$value = $this->config[$key];

			if (is_array($value))
			{
				$value = implode(',', $value);
			}
			elseif (is_object($value))
			{
				$value = (string) $value;
			}

			$db->preparedQuery('INSERT OR REPLACE INTO config (cle, valeur) VALUES (?, ?);',
				[$key, $value]);
		}

		if (!empty($this->modified['champ_identifiant']))
		{
			// Mettre les champs identifiant vides à NULL pour pouvoir créer un index unique
			$db->exec('UPDATE membres SET '.$this->get('champ_identifiant').' = NULL
				WHERE '.$this->get('champ_identifiant').' = "";');

			// Création de l'index unique
			$db->exec('DROP INDEX IF EXISTS membres_identifiant;');
			$db->exec('CREATE UNIQUE INDEX membres_identifiant ON membres ('.$this->get('champ_identifiant').');');
		}

		$db->commit();

		$this->_modified = [];

		return true;
	}

	public function delete(): bool
	{




		throw new \LogicException('Cannot delete config');



	}




	public function getVersion(): string
	{


		return $this->get('version');
	}




	public function setVersion(string $version): void
	{
		$this->config->version = $version;














		$db = DB::getInstance();






		$db->preparedQuery('INSERT OR REPLACE INTO config (cle, valeur) VALUES (?, ?);',
			['version', $version]);
	}










	protected function _filterType(string $key, $value)

	{
		switch ($this->_types[$key]) {

			case 'int':

				return (int) $value;





			case 'bool':


				return (bool) $value;

			case 'string':
				return (string) $value;



			case File::class:
			case Champs::class:
				if (!is_object($value) || !($value instanceof $this->_types[$key])) {
					throw new \InvalidArgumentException(sprintf('"%s" is not of type "%s"', $key, $this->_types[$key]));
				}
				return $value;


			default:





				throw new \InvalidArgumentException(sprintf('"%s" has unknown type "%s"', $key, $this->_types[$key]));
		}

	}



	public function selfCheck(): void
	{







		$this->assert(trim($this->nom_asso) != '', 'Le nom de l\'association ne peut rester vide.');
		$this->assert(trim($this->monnaie) != '', 'La monnaie ne peut rester vide.');

		$this->assert(trim($this->pays) != '' && Utils::getCountryName($this->pays), 'Le pays ne peut rester vide.');





		$this->assert(trim($this->email_asso) != '' && SMTP::checkEmailIsValid($this->email_asso, false), 'L\'adresse e-mail de l\'association est  invalide.');



		$this->assert(null === $this->admin_homepage || $this->admin_homepage instanceof File, 'Page d\'accueil invalide');
		$this->assert($this->champs_membres instanceof Champs, 'Objet champs membres invalide');





		$champs = $this->champs_membres;














		$this->assert(!empty($champs->get($this->champ_identite)), sprintf('Le champ spécifié pour identité, "%s" n\'existe pas', $this->champ_identite));








		$this->assert(!empty($champs->get($this->champ_identifiant)), sprintf('Le champ spécifié pour identifiant, "%s" n\'existe pas', $this->champ_identifiant));





		$db = DB::getInstance();


		$sql = sprintf('SELECT (COUNT(DISTINCT %s) = COUNT(*)) FROM membres WHERE %1$s IS NOT NULL AND %1$s != \'\';', $this->champ_identifiant);


		$is_unique = $db->firstColumn($sql);


		$this->assert($is_unique, sprintf('Le champ "%s" comporte des doublons et ne peut donc pas servir comme identifiant unique de connexion.', $this->champ_identifiant));


		$this->assert($db->test('membres_categories', 'id = ?', $this->categorie_membres), 'Catégorie de membres inconnue');
	}

	public function getConfig()
	{
		return $this->asArray();
	}
}

Modified src/include/lib/Garradin/Upgrade.php from [4f89931cf7] to [6af05bf96b].

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
<?php

namespace Garradin;

use Garradin\Membres\Session;

class Upgrade
{


	static public function preCheck(): bool
	{
		$config = Config::getInstance();
		$v = $config->getVersion();

		if (version_compare($v, garradin_version(), '>='))
		{
			return false;
		}

		if (!$v || version_compare($v, '0.9.8', '<'))
		{
			throw new UserException("Votre version de Garradin est trop ancienne pour être mise à jour. Mettez à jour vers Garradin 0.9.8 avant de faire la mise à jour vers cette version.");
		}

		Install::checkAndCreateDirectories();

		if (Static_Cache::exists('upgrade'))
		{
			$path = Static_Cache::getPath('upgrade');








>
>


|
<






|

|







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
<?php

namespace Garradin;

use Garradin\Membres\Session;

class Upgrade
{
	const MIN_REQUIRED_VERSION = '1.0.0-rc8';

	static public function preCheck(): bool
	{
		$v = DB::getInstance()->firstColumn('SELECT valeur FROM config WHERE cle = \'version\';');


		if (version_compare($v, garradin_version(), '>='))
		{
			return false;
		}

		if (!$v || version_compare($v, self::MIN_REQUIRED_VERSION, '<'))
		{
			throw new UserException(sprintf("Votre version de Garradin est trop ancienne pour être mise à jour. Mettez à jour vers Garradin %s avant de faire la mise à jour vers cette version.", self::MIN_REQUIRED_VERSION));
		}

		Install::checkAndCreateDirectories();

		if (Static_Cache::exists('upgrade'))
		{
			$path = Static_Cache::getPath('upgrade');
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
		$session = new Session;
		$user_is_logged = $session->isLogged(true);
		return true;
	}

	static public function upgrade()
	{
		$config = Config::getInstance();
		$v = $config->getVersion();

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

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

		$db = DB::getInstance();

		// Créer une sauvegarde automatique
		$backup_name = (new Sauvegarde)->create('pre-upgrade-' . garradin_version());

		try {
			if (version_compare($v, '1.0.0-alpha1', '<'))
			{
				$db->beginSchemaUpdate();
				$db->import(ROOT . '/include/data/1.0.0_migration.sql');
				$db->commitSchemaUpdate();

				// Import nouveau plan comptable
				$chart = new \Garradin\Entities\Accounting\Chart;
				$chart->label = 'Plan comptable associatif 2018';
				$chart->country = 'FR';
				$chart->code = 'PCA2018';
				$chart->save();
				$chart->accounts()->importCSV(ROOT . '/include/data/charts/fr_2018.csv');
			}

			if (version_compare($v, '1.0.0-beta1', '>=') && version_compare($v, '1.0.0-beta6', '<'))
			{
				$db->beginSchemaUpdate();
				$db->import(ROOT . '/include/data/1.0.0-beta6_migration.sql');
				$db->commitSchemaUpdate();
			}

			if (version_compare($v, '1.0.0-beta6', '>=') && version_compare($v, '1.0.0-beta8', '<'))
			{
				$db->beginSchemaUpdate();
				$db->import(ROOT . '/include/data/1.0.0-beta8_migration.sql');
				$db->commitSchemaUpdate();
			}

			if (version_compare($v, '1.0.0-beta1', '>=') && version_compare($v, '1.0.0-rc3', '<'))
			{
				$db->beginSchemaUpdate();
				$db->import(ROOT . '/include/data/1.0.0-rc3_migration.sql');
				$db->commitSchemaUpdate();
			}

			if (version_compare($v, '1.0.0-beta1', '>=') && version_compare($v, '1.0.0-rc10', '<'))
			{
				$db->beginSchemaUpdate();
				$db->import(ROOT . '/include/data/1.0.0-rc10_migration.sql');
				$db->commitSchemaUpdate();
			}

			if (version_compare($v, '1.0.0-beta1', '>=') && version_compare($v, '1.0.0-rc11', '<'))
			{
				// Missing trigger
				$db->beginSchemaUpdate();
				$db->import(ROOT . '/include/data/1.0.0_schema.sql');
				$db->commitSchemaUpdate();
			}

			if (version_compare($v, '1.1.0', '<='))
			{
				// Missing trigger
				$db->beginSchemaUpdate();
				$db->createFunction('sha1', 'sha1');
				$db->import(ROOT . '/include/data/1.1.0_migration.sql');
				$db->commitSchemaUpdate();
			}

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

			Utils::clearCaches();

			$config->setVersion(garradin_version());

			Static_Cache::remove('upgrade');

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

			// Mettre à jour les plugins si nécessaire







|
<












<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














|







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
		$session = new Session;
		$user_is_logged = $session->isLogged(true);
		return true;
	}

	static public function upgrade()
	{
		$v = DB::getInstance()->firstColumn('SELECT valeur FROM config WHERE cle = \'version\';');


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

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

		$db = DB::getInstance();

		// Créer une sauvegarde automatique
		$backup_name = (new Sauvegarde)->create('pre-upgrade-' . garradin_version());

		try {



















































			if (version_compare($v, '1.1.0', '<='))
			{
				// Missing trigger
				$db->beginSchemaUpdate();
				$db->createFunction('sha1', 'sha1');
				$db->import(ROOT . '/include/data/1.1.0_migration.sql');
				$db->commitSchemaUpdate();
			}

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

			Utils::clearCaches();

			DB::getInstance()->update('config', ['valeur' => garradin_version()], 'cle = \'version\';');

			Static_Cache::remove('upgrade');

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

			// Mettre à jour les plugins si nécessaire