Changes In Branch dev Through [bd250771e3] Excluding Merge-Ins

This is equivalent to a diff from 93aeaacac6 to bd250771e3

2021-05-10
12:19
Re-add missing merges before [93aeaacac6] check-in: 561aebe80c user: bohwaz tags: trunk, stable
2021-04-02
14:42
Accept absolute URIs in links check-in: e26b1d4970 user: bohwaz tags: dev
14:21
Fix background image saving check-in: bd250771e3 user: bohwaz tags: dev
13:40
Forgot to change title check-in: 7fdc2560e8 user: bohwaz tags: dev
2021-03-22
13:17
Exclude volunteering accounts from graphs check-in: 41ea740544 user: bohwaz tags: trunk, stable
2021-03-19
23:09
Merge trunk fixes check-in: 0e4057ab65 user: bohwaz tags: dev
2021-03-12
19:22
Validation error when trying to create a transaction to a non-existing user or year check-in: 93aeaacac6 user: bohwaz tags: trunk, stable
19:16
Make sure that the correct chart is shown as it can change between one fee and the other check-in: 365aa02d2a user: bohwaz tags: trunk, stable

Modified src/.htaccess.www from [34b16e1e96] to [3ae6d113cf].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Désactiver le multiviews (conflit avec /admin/plugin.php) et les index (sécurité)
Options -MultiViews -Indexes
DirectoryIndex disabled
DirectoryIndex index.php index.html

# Au cas où
<IfModule mod_alias.c>
	RedirectMatch 403 /include/
	RedirectMatch 403 /cache/
	RedirectMatch 403 /plugins/
	RedirectMatch 403 /templates/
	RedirectMatch 403 ^/scripts/
	RedirectMatch 403 /.*\.sqlite
	RedirectMatch 403 /.*\.log
	RedirectMatch 403 /(README|VERSION|COPYING|Makefile|cron\.php)
	RedirectMatch 403 /config\.(.*)\.php
	RedirectMatch 403 /sous-domaine\.html
	RedirectMatch 403 _inc\.php
</IfModule>









<
<


|







1
2
3
4
5
6
7
8


9
10
11
12
13
14
15
16
17
18
# Désactiver le multiviews (conflit avec /admin/plugin.php) et les index (sécurité)
Options -MultiViews -Indexes
DirectoryIndex disabled
DirectoryIndex index.php index.html

# Au cas où
<IfModule mod_alias.c>
	RedirectMatch 403 /include/


	RedirectMatch 403 /templates/
	RedirectMatch 403 ^/scripts/
	RedirectMatch 403 /data/
	RedirectMatch 403 /.*\.log
	RedirectMatch 403 /(README|VERSION|COPYING|Makefile|cron\.php)
	RedirectMatch 403 /config\.(.*)\.php
	RedirectMatch 403 /sous-domaine\.html
	RedirectMatch 403 _inc\.php
</IfModule>

Modified src/VERSION from [ef29a5ff49] to [1ee05564ba].

1
1.0.6
|
1
1.1.0-beta1

Deleted src/cache/index.html version [abe89f9bfb].

1
<!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>
<


Modified src/config.dist.php from [35e054b963] to [9300d4dd65].

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
 * Défaut : répertoire racine de Garradin (__DIR__)
 */

//const ROOT = __DIR__;

/**
 * Répertoire où sont situées les données de Garradin
 * (incluant la base de données SQLite, les sauvegardes, le cache et les fichiers locaux)
 *
 * Défaut : identique à ROOT
 */

//const DATA_ROOT = ROOT;

/**
 * Répertoire où est situé le cache (fichiers temporaires utilisés pour accélérer le chargement des pages)

 *
 * Défaut : sous-répertoire 'cache' de DATA_ROOT
 */

//const CACHE_ROOT = ROOT . '/cache';











/**
 * Emplacement du fichier de base de données de Garradin
 *
 * Défaut : DATA_ROOT . '/association.sqlite'
 */








|

|


|


|
>




|
>
>
>
>
>
>
>
>
>
>







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
 * Défaut : répertoire racine de Garradin (__DIR__)
 */

//const ROOT = __DIR__;

/**
 * Répertoire où sont situées les données de Garradin
 * (incluant la base de données SQLite, les sauvegardes, le cache, les fichiers locaux et les plugins)
 *
 * Défaut : sous-répertoire "data" de la racine
 */

//const DATA_ROOT = ROOT . '/data';

/**
 * Répertoire où est situé le cache,
 * exemples : graphiques de statistiques, templates Brindille, etc.
 *
 * Défaut : sous-répertoire 'cache' de DATA_ROOT
 */

//const CACHE_ROOT = DATA_ROOT . '/cache';

/**
 * Répertoire où est situé le cache partagé entre instances
 * Garradin utilisera ce répertoire pour stocker le cache susceptible d'être partagé entre instances, comme
 * le code PHP généré à partir des templates Smartyer.
 *
 * Défaut : sous-répertoire 'shared' de CACHE_ROOT
 */

//const SHARED_CACHE_ROOT = CACHE_ROOT . '/shared';

/**
 * Emplacement du fichier de base de données de Garradin
 *
 * Défaut : DATA_ROOT . '/association.sqlite'
 */

201
202
203
204
205
206
207

208
209
210
211
212
213
214
215

// const ERRORS_TEMPLATE = null;

/**
 * Activation des détails techniques (utile en auto-hébergement) :
 * - version de PHP
 * - page permettant de visualiser les erreurs présentes dans le error.log

 * - vérification de nouvelle version
 *
 * Ces infos ne sont visibles que par les membres ayant accès à la configuration.
 *
 * Défaut : true
 * (Afin d'aider au rapport de bugs des instances auto-hébergées)
 */








>
|







212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

// const ERRORS_TEMPLATE = null;

/**
 * Activation des détails techniques (utile en auto-hébergement) :
 * - version de PHP
 * - page permettant de visualiser les erreurs présentes dans le error.log
 * - permettre de migrer d'un stockage de fichiers à l'autre
 * - vérification de nouvelle version (sur la page configuration)
 *
 * Ces infos ne sont visibles que par les membres ayant accès à la configuration.
 *
 * Défaut : true
 * (Afin d'aider au rapport de bugs des instances auto-hébergées)
 */

362
363
364
365
366
367
368

















































 *
 * sinon la personnalisation des couleurs ne fonctionnera pas
 *
 * Défaut : [ADMIN_URL]static/gdin_bg.png
 */

//const ADMIN_BACKGROUND_IMAGE = 'http://mon-asso.fr/fond_garradin.png';
























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
 *
 * sinon la personnalisation des couleurs ne fonctionnera pas
 *
 * Défaut : [ADMIN_URL]static/gdin_bg.png
 */

//const ADMIN_BACKGROUND_IMAGE = 'http://mon-asso.fr/fond_garradin.png';


/**
 * Stockage des fichiers
 *
 * Indiquer ici le nom d'une classe de stockage de fichiers
 * (parmis celles disponibles dans lib/Garradin/Files/Backend)
 *
 * Indiquer NULL si vous souhaitez stocker les fichier dans la base
 * de données SQLite (valeur par défaut).
 *
 * Classes de stockage possibles :
 * - SQLite : enregistre dans la base de données (défaut)
 * - FileSystem : enregistrement des fichiers dans le système de fichier
 *
 * Défaut : null
 */

//const FILE_STORAGE_BACKEND = null;

/**
 * Configuration du stockage des fichiers
 *
 * Indiquer dans cette constante la configuration de la classe de stockage
 * des fichiers.
 *
 * Valeurs possibles :
 * - SQLite : aucune configuration possible
 * - FileSystem : (string) chemin du répertoire où doivent être stockés les fichiers
 *
 * Pour migrer d'un stockage de fichiers à l'autre,
 * voir Configuration > Avancé (accessible uniquement si ENABLE_TECH_DETAILS est à true)
 *
 * Défaut : null
 */

//const FILE_STORAGE_CONFIG = null;

/**
 * Forcer le quota disponible pour les fichiers
 *
 * Si cette constante est renseignée (en octets) alors il ne sera
 * pas possible de stocker plus que cette valeur.
 * Tout envoi de fichier sera refusé.
 *
 * Défaut : null (dans ce cas c'est le stockage qui détermine la taille disponible, donc généralement l'espace dispo sur le disque dur !)
 */

//const FILE_STORAGE_QUOTA = 10000; // Forcer le quota alloué à 10 Mo, quel que soit le backend de stockage

Added src/data/index.html version [abe89f9bfb].



>
1
<!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>

Modified src/include/data/1.0.0_migration.sql from [04228da44a] to [4e16391488].

128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
UPDATE acc_transactions_lines SET reconciled = 1 WHERE id_transaction IN (SELECT id_operation FROM compta_rapprochement);

--------- MIGRATION COTISATIONS ----------

-- A edge-case where the end date is after the start date, let's fix it…
UPDATE cotisations SET fin = debut WHERE fin < debut;

-- Another edge-case
UPDATE cotisations SET duree = NULL WHERE duree = 0;

INSERT INTO services SELECT id, intitule, description, duree, debut, fin FROM cotisations;

INSERT INTO services_fees (id, label, amount, id_service, id_account, id_year)
	SELECT id, intitule, CASE WHEN montant IS NOT NULL THEN CAST(montant*100 AS integer) ELSE NULL END, id,
		(SELECT id FROM acc_accounts WHERE code = (SELECT compte FROM compta_categories WHERE id = id_categorie_compta)),
		(SELECT MAX(id) FROM acc_years WHERE closed = 0)
	FROM cotisations;







<
<
<







128
129
130
131
132
133
134



135
136
137
138
139
140
141
UPDATE acc_transactions_lines SET reconciled = 1 WHERE id_transaction IN (SELECT id_operation FROM compta_rapprochement);

--------- MIGRATION COTISATIONS ----------

-- A edge-case where the end date is after the start date, let's fix it…
UPDATE cotisations SET fin = debut WHERE fin < debut;




INSERT INTO services SELECT id, intitule, description, duree, debut, fin FROM cotisations;

INSERT INTO services_fees (id, label, amount, id_service, id_account, id_year)
	SELECT id, intitule, CASE WHEN montant IS NOT NULL THEN CAST(montant*100 AS integer) ELSE NULL END, id,
		(SELECT id FROM acc_accounts WHERE code = (SELECT compte FROM compta_categories WHERE id = id_categorie_compta)),
		(SELECT MAX(id) FROM acc_years WHERE closed = 0)
	FROM cotisations;

Added src/include/data/1.1.0_migration.sql version [32c4e00c3b].















































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
-- Remove triggers in case they interact with the migration
DROP TRIGGER IF EXISTS wiki_recherche_delete;
DROP TRIGGER IF EXISTS wiki_recherche_update;
DROP TRIGGER IF EXISTS wiki_recherche_contenu_insert;
DROP TRIGGER IF EXISTS wiki_recherche_contenu_chiffre;

-- Fix some rare edge cases where date_inscription is incorrect
UPDATE membres SET date_inscription = date() WHERE date(date_inscription) IS NULL;

-- Uh, force another login id if email is not correct
UPDATE config SET valeur = 'numero' WHERE cle = 'champ_identifiant' AND valeur = 'email'
	AND (SELECT COUNT(*) FROM membres GROUP BY LOWER(email) HAVING COUNT(*) > 1 LIMIT 1);

-- Other weird things to fix before migration
UPDATE wiki_pages SET uri = 'page_' || id WHERE uri = '' OR uri IS NULL;
DELETE FROM config WHERE cle = 'connexion' OR cle = 'wiki';

ALTER TABLE membres_categories RENAME TO membres_categories_old;

INSERT OR IGNORE INTO config (cle, valeur) VALUES ('desactiver_site', '0');
ALTER TABLE config RENAME TO config_old;

.read 1.1.0_schema.sql

INSERT INTO config SELECT * FROM config_old;
DROP TABLE config_old;

-- This is not used anymore
DELETE FROM config WHERE key = 'version';
DELETE FROM config WHERE key = 'accueil_wiki';

-- New config key
INSERT INTO config (key, value) VALUES ('telephone_asso', NULL);

-- Create directories
INSERT INTO files (parent, name, path, type) VALUES ('', 'documents', 'documents', 2);
INSERT INTO files (parent, name, path, type) VALUES ('', 'config', 'config', 2);
INSERT INTO files (parent, name, path, type) VALUES ('', 'transaction', 'transaction', 2);
INSERT INTO files (parent, name, path, type) VALUES ('', 'skel', 'skel', 2);
INSERT INTO files (parent, name, path, type) VALUES ('', 'user', 'user', 2);
INSERT INTO files (parent, name, path, type) VALUES ('', 'web', 'web', 2);

-- Copy droit_wiki value to droit_web and droit_documents
INSERT INTO users_categories
	SELECT id, nom,
		droit_wiki, -- perm_web
		droit_wiki, -- perm_documents
		droit_membres,
		droit_compta,
		droit_inscription,
		droit_connexion,
		droit_config,
		cacher
	FROM membres_categories_old;

DROP TABLE membres_categories_old;

UPDATE recherches SET contenu = REPLACE(contenu, 'id_categorie', 'id_category') WHERE cible = 'membres' AND contenu LIKE '%id_categorie%';

CREATE TEMP TABLE files_transactions (old_id, old_transaction, old_name, new_path, new_id, same_name);

-- Adding an extra step as some file names can have the same name
INSERT INTO files_transactions
	SELECT f.id, t.id, f.nom, NULL, NULL, NULL
	FROM fichiers f
		INNER JOIN fichiers_acc_transactions t ON t.fichier = f.id;

UPDATE files_transactions SET same_name = old_id || '_'
	WHERE old_id IN (SELECT old_id FROM files_transactions GROUP BY old_transaction, old_name HAVING COUNT(*) > 1);

-- Make file name is unique!
UPDATE files_transactions SET new_path = 'transaction/' || old_transaction || '/' || COALESCE(old_id || '_', '') || old_name;

-- Copy existing files for transactions
INSERT INTO files (path, parent, name, type, mime, modified, size, image)
	SELECT
		ft.new_path,
		dirname(ft.new_path),
		basename(ft.new_path),
		1, f.type, f.datetime, c.taille, f.image
	FROM files_transactions ft
		INNER JOIN fichiers f ON f.id = ft.old_id
		INNER JOIN fichiers_contenu c ON c.id = f.id_contenu;

UPDATE files_transactions SET new_id = (SELECT id FROM files WHERE path = new_path);

INSERT INTO files_contents (id, compressed, content)
	SELECT ft.new_id, 0, c.contenu
	FROM fichiers f
		INNER JOIN files_transactions ft ON ft.old_id = f.id
		INNER JOIN fichiers_contenu c ON c.id = f.id_contenu;

-- Copy wiki pages content
CREATE TEMP TABLE wiki_as_files (old_id, new_id, path, content, title, uri,
	old_parent, new_parent, created, modified, author_id, encrypted, type, public);

INSERT INTO wiki_as_files
	SELECT
		id, NULL, '', CASE WHEN contenu IS NULL THEN '' ELSE contenu END, titre, uri,
		parent, parent, date_creation, date_modification, id_auteur, chiffrement,
		CASE WHEN (SELECT 1 FROM wiki_pages pp WHERE pp.parent = p.id LIMIT 1) THEN 1 ELSE 2 END, -- Type, 1 = category, 2 = page
		CASE WHEN droit_lecture = -1 THEN 1 ELSE 0 END -- public
	FROM wiki_pages p
	LEFT JOIN wiki_revisions r ON r.id_page = p.id AND r.revision = p.revision;

-- Build path
WITH RECURSIVE path(level, uri, parent, id) AS (
	SELECT 0, uri, old_parent, old_id
	FROM wiki_as_files
	UNION ALL
	SELECT path.level + 1,
	wiki_as_files.uri,
	wiki_as_files.old_parent,
	path.id
	FROM wiki_as_files
	JOIN path ON wiki_as_files.old_id = path.parent
	WHERE level <= 8 -- max level = 8 to avoid recursion
),
path_from_root AS (
	SELECT group_concat(uri, '/') AS path, id
	FROM (SELECT id, uri FROM path ORDER BY level DESC)
	GROUP BY id
)
UPDATE wiki_as_files SET path = (SELECT path FROM path_from_root WHERE id = wiki_as_files.old_id);

-- remove recursion
UPDATE wiki_as_files SET path = uri WHERE path IS NULL OR LENGTH(path) - LENGTH(REPLACE(path, '/', '')) >= 8;

-- Copy into files
INSERT INTO files (path, parent, name, type, mime, modified, size)
	SELECT
		'web/' || path || '/index.txt',
		'web/' || path,
		'index.txt',
		1,
		'text/plain',
		modified,
		0 -- size will be set after
	FROM wiki_as_files;

UPDATE wiki_as_files SET new_id = (SELECT id FROM files WHERE files.path = 'web/' || (CASE WHEN wiki_as_files.path IS NOT NULL THEN wiki_as_files.path || '/' ELSE '' END) || wiki_as_files.uri || '/index.txt');

-- x'0a' == \n
INSERT INTO files_contents (id, compressed, content)
	SELECT f.id, 0,
		'Title: ' || title || x'0a' || 'Published: ' || created || x'0a' || 'Status: '
		|| (CASE WHEN public THEN 'Online' ELSE 'Draft' END)
		|| x'0a' || 'Format: ' || (CASE WHEN encrypted THEN 'Skriv/Encrypted' ELSE 'Skriv' END)
		|| x'0a' || x'0a' || '----' || x'0a' || x'0a' || content
	FROM wiki_as_files waf
	INNER JOIN files f ON f.path = 'web/' || waf.path || '/index.txt';

-- Copy to search
INSERT INTO files_search (path, title, content)
	SELECT
		'web/' || path || '/index.txt',
		title,
		CASE WHEN encrypted THEN NULL ELSE content END
	FROM wiki_as_files WHERE encrypted = 0;

-- Copy to web_pages
INSERT INTO web_pages (id, parent, path, uri, file_path, type, status, title, published, modified, format, content)
	SELECT new_id,
	CASE WHEN dirname(path) = '.' THEN '' ELSE dirname(path) END,
	path,
	uri,
	'web/' || path || '/index.txt',
	type,
	CASE WHEN public THEN 'online' ELSE 'draft' END,
	title, created, modified,
	CASE WHEN encrypted THEN 'skriv/encrypted' ELSE 'skriv' END,
	content
	FROM wiki_as_files;

CREATE TEMP TABLE files_wiki (old_id, wiki_id, web_path, old_name, new_path, new_id);

-- Adding an extra step as some file names can have the same name
INSERT INTO files_wiki
	SELECT f.id, w.id, waf.path, f.nom, 'web/' || waf.path || '/' || f.id || '_' || f.nom, NULL
	FROM fichiers f
		INNER JOIN fichiers_wiki_pages w ON w.fichier = f.id
		INNER JOIN wiki_as_files waf ON w.id = waf.old_id;

-- Copy files linked to wiki pages
INSERT INTO files (path, parent, name, type, mime, modified, size, image)
	SELECT
		fw.new_path,
		dirname(fw.new_path),
		basename(fw.new_path),
		1,
		f.type,
		f.datetime,
		c.taille,
		f.image
	FROM fichiers f
		INNER JOIN fichiers_contenu c ON c.id = f.id_contenu
		INNER JOIN files_wiki fw ON fw.old_id = f.id;

UPDATE files_wiki SET new_id = (SELECT id FROM files WHERE path = new_path);

INSERT INTO files_contents (id, compressed, content)
	SELECT
		fw.new_id, 0, c.contenu
	FROM files_wiki fw
		INNER JOIN fichiers f ON f.id = fw.old_id
		INNER JOIN fichiers_contenu c ON c.id = f.id_contenu;

-- Create parent directories
INSERT INTO files (type, path, parent, name, modified)
	SELECT 2,
		'web/' || waf.path,
		dirname('web/' || waf.path),
		waf.uri,
		modified
	FROM wiki_as_files waf;

INSERT OR IGNORE INTO files (type, path, parent, name) SELECT 2, parent, dirname(parent), basename(parent) FROM files WHERE type = 2 AND dirname(parent) != '.' AND dirname(parent) != '' AND (SELECT 1 FROM files f2 WHERE f2.path = dirname(files.parent) LIMIT 1) IS NULL;
INSERT OR IGNORE INTO files (type, path, parent, name) SELECT 2, parent, dirname(parent), basename(parent) FROM files WHERE type = 2 AND dirname(parent) != '.' AND dirname(parent) != '' AND (SELECT 1 FROM files f2 WHERE f2.path = dirname(files.parent) LIMIT 1) IS NULL;
INSERT OR IGNORE INTO files (type, path, parent, name) SELECT 2, parent, dirname(parent), basename(parent) FROM files WHERE type = 2 AND dirname(parent) != '.' AND dirname(parent) != '' AND (SELECT 1 FROM files f2 WHERE f2.path = dirname(files.parent) LIMIT 1) IS NULL;
INSERT OR IGNORE INTO files (type, path, parent, name) SELECT 2, parent, dirname(parent), basename(parent) FROM files WHERE type = 2 AND dirname(parent) != '.' AND dirname(parent) != '' AND (SELECT 1 FROM files f2 WHERE f2.path = dirname(files.parent) LIMIT 1) IS NULL;
INSERT OR IGNORE INTO files (type, path, parent, name) SELECT 2, parent, dirname(parent), basename(parent) FROM files WHERE type = 2 AND dirname(parent) != '.' AND dirname(parent) != '' AND (SELECT 1 FROM files f2 WHERE f2.path = dirname(files.parent) LIMIT 1) IS NULL;
INSERT OR IGNORE INTO files (type, path, parent, name) SELECT 2, parent, dirname(parent), basename(parent) FROM files WHERE type = 2 AND dirname(parent) != '.' AND dirname(parent) != '' AND (SELECT 1 FROM files f2 WHERE f2.path = dirname(files.parent) LIMIT 1) IS NULL;
INSERT OR IGNORE INTO files (type, path, parent, name) SELECT 2, parent, dirname(parent), basename(parent) FROM files WHERE type = 2 AND dirname(parent) != '.' AND dirname(parent) != '' AND (SELECT 1 FROM files f2 WHERE f2.path = dirname(files.parent) LIMIT 1) IS NULL;
INSERT OR IGNORE INTO files (type, path, parent, name) SELECT 2, parent, dirname(parent), basename(parent) FROM files WHERE type = 2 AND dirname(parent) != '.' AND dirname(parent) != '' AND (SELECT 1 FROM files f2 WHERE f2.path = dirname(files.parent) LIMIT 1) IS NULL;
INSERT OR IGNORE INTO files (type, path, parent, name) SELECT 2, parent, dirname(parent), basename(parent) FROM files WHERE type = 2 AND dirname(parent) != '.' AND dirname(parent) != '' AND (SELECT 1 FROM files f2 WHERE f2.path = dirname(files.parent) LIMIT 1) IS NULL;
INSERT OR IGNORE INTO files (type, path, parent, name) SELECT 2, parent, dirname(parent), basename(parent) FROM files WHERE type = 2 AND dirname(parent) != '.' AND dirname(parent) != '' AND (SELECT 1 FROM files f2 WHERE f2.path = dirname(files.parent) LIMIT 1) IS NULL;

-- Copy existing config files
INSERT INTO files (path, parent, name, type, mime, modified, size, image)
	SELECT 'config/admin_bg.png', 'config', 'admin_bg.png', 1, type, datetime, c.taille, image
	FROM fichiers f
		INNER JOIN fichiers_contenu c ON c.id = f.id_contenu
	WHERE f.id = (SELECT c.value FROM config c WHERE key = 'image_fond') LIMIT 1;

INSERT INTO files_contents (id, compressed, content)
	SELECT f2.id, 0, c.contenu
	FROM files AS f2
		INNER JOIN fichiers f ON f2.path = 'config/admin_bg.png'
		INNER JOIN fichiers_contenu c ON c.id = f.id_contenu
		WHERE f.id = (SELECT c.value FROM config c WHERE key = 'image_fond') LIMIT 1;

-- Rename
UPDATE config SET key = 'admin_background', value = 'config/admin_bg.png' WHERE key = 'image_fond';

-- Copy connection page as a single file
INSERT INTO files (path, parent, name, type, mime, modified, size, image)
	SELECT 'config/admin_homepage.skriv', 'config', 'admin_homepage.skriv', 1, 'text/plain', datetime(), LENGTH(content), 0
	FROM wiki_as_files
	WHERE uri = (SELECT value FROM config WHERE key = 'accueil_connexion');

INSERT INTO files_contents (id, compressed, content)
	SELECT f.id, 0, waf.content
	FROM files f
		INNER JOIN wiki_as_files waf ON waf.uri = (SELECT value FROM config WHERE key = 'accueil_connexion')
	WHERE f.path = 'config/admin_homepage.skriv';

-- Rename
UPDATE config SET key = 'admin_homepage', value = 'config/admin_homepage.skriv' WHERE key = 'accueil_connexion';
UPDATE config SET key = 'site_disabled' WHERE key = 'desactiver_site';

-- Create transaction directories
INSERT INTO files (path, parent, name, type) SELECT 'transaction/' || id, 'transaction', id, 2 FROM fichiers_acc_transactions GROUP BY id;

-- Set file size
UPDATE files SET size = (SELECT LENGTH(content) FROM files_contents WHERE id = files.id) WHERE type = 1;

DELETE FROM plugins_signaux WHERE signal LIKE 'boucle.%';

DROP TABLE wiki_recherche;

DROP TABLE wiki_pages;
DROP TABLE wiki_revisions;

DROP TABLE fichiers_wiki_pages;
DROP TABLE fichiers_acc_transactions;
DROP TABLE fichiers_membres;

DROP TABLE fichiers;
DROP TABLE fichiers_contenu;

Added src/include/data/1.1.0_schema.sql version [3456f2416e].



































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
CREATE TABLE IF NOT EXISTS config (
    key TEXT PRIMARY KEY NOT NULL,
    value TEXT NULL
);

CREATE TABLE IF NOT EXISTS users_categories
-- Users categories, mainly used to manage rights
(
    id INTEGER PRIMARY KEY NOT NULL,
    name TEXT NOT NULL,

    -- Permissions, 0 = no access, 1 = read-only, 2 = read-write, 9 = admin
    perm_web INTEGER NOT NULL DEFAULT 1,
    perm_documents INTEGER NOT NULL DEFAULT 1,
    perm_users INTEGER NOT NULL DEFAULT 1,
    perm_accounting INTEGER NOT NULL DEFAULT 1,

    perm_subscribe INTEGER NOT NULL DEFAULT 0,
    perm_connect INTEGER NOT NULL DEFAULT 1,
    perm_config INTEGER NOT NULL DEFAULT 0,

    hidden INTEGER NOT NULL DEFAULT 0
);

CREATE INDEX users_categories_hidden ON users_categories (hidden);

-- Membres de l'asso
-- Table dynamique générée par l'application
-- voir Garradin\Membres\Champs.php

CREATE TABLE IF NOT EXISTS membres_sessions
-- Sessions
(
    selecteur TEXT NOT NULL,
    hash TEXT NOT NULL,
    id_membre INTEGER NOT NULL REFERENCES membres (id) ON DELETE CASCADE,
    expire INT NOT NULL,

    PRIMARY KEY (selecteur, id_membre)
);

CREATE TABLE IF NOT EXISTS services
-- Types de services (cotisations)
(
    id INTEGER PRIMARY KEY NOT NULL,

    label TEXT NOT NULL,
    description TEXT NULL,

    duration INTEGER NULL CHECK (duration IS NULL OR duration > 0), -- En jours
    start_date TEXT NULL CHECK (start_date IS NULL OR date(start_date) = start_date),
    end_date TEXT NULL CHECK (end_date IS NULL OR (date(end_date) = end_date AND date(end_date) >= date(start_date)))
);

CREATE TABLE IF NOT EXISTS services_fees
(
    id INTEGER PRIMARY KEY NOT NULL,

    label TEXT NOT NULL,
    description TEXT NULL,

    amount INTEGER NULL,
    formula TEXT NULL, -- Formule de calcul du montant de la cotisation, si cotisation dynamique (exemple : membres.revenu_imposable * 0.01)

    id_service INTEGER NOT NULL REFERENCES services (id) ON DELETE CASCADE,
    id_account INTEGER NULL REFERENCES acc_accounts (id) ON DELETE SET NULL CHECK (id_account IS NULL OR id_year IS NOT NULL), -- NULL si le type n'est pas associé automatiquement à la compta
    id_year INTEGER NULL REFERENCES acc_years (id) ON DELETE SET NULL -- NULL si le type n'est pas associé automatiquement à la compta
);

CREATE TABLE IF NOT EXISTS services_users
-- Enregistrement des cotisations et activités
(
    id INTEGER NOT NULL PRIMARY KEY,
    id_user INTEGER NOT NULL REFERENCES membres (id) ON DELETE CASCADE,
    id_service INTEGER NOT NULL REFERENCES services (id) ON DELETE CASCADE,
    id_fee INTEGER NULL REFERENCES services_fees (id) ON DELETE CASCADE,

    paid INTEGER NOT NULL DEFAULT 0,
    expected_amount INTEGER NULL,

    date TEXT NOT NULL DEFAULT CURRENT_DATE CHECK (date(date) IS NOT NULL AND date(date) = date),
    expiry_date TEXT NULL CHECK (date(expiry_date) IS NULL OR date(expiry_date) = expiry_date)
);

CREATE UNIQUE INDEX IF NOT EXISTS su_unique ON services_users (id_user, id_service, date);

CREATE INDEX IF NOT EXISTS su_service ON services_users (id_service);
CREATE INDEX IF NOT EXISTS su_fee ON services_users (id_fee);
CREATE INDEX IF NOT EXISTS su_paid ON services_users (paid);
CREATE INDEX IF NOT EXISTS su_expiry ON services_users (expiry_date);

CREATE TABLE IF NOT EXISTS services_reminders
-- Rappels de devoir renouveller une cotisation
(
    id INTEGER NOT NULL PRIMARY KEY,
    id_service INTEGER NOT NULL REFERENCES services (id) ON DELETE CASCADE,

    delay INTEGER NOT NULL, -- Délai en jours pour envoyer le rappel

    subject TEXT NOT NULL,
    body TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS services_reminders_sent
-- Enregistrement des rappels envoyés à qui et quand
(
    id INTEGER NOT NULL PRIMARY KEY,

    id_user INTEGER NOT NULL REFERENCES membres (id) ON DELETE CASCADE,
    id_service INTEGER NOT NULL REFERENCES services (id) ON DELETE CASCADE,
    id_reminder INTEGER NOT NULL REFERENCES services_reminders (id) ON DELETE CASCADE,

    date TEXT NOT NULL DEFAULT CURRENT_DATE CHECK (date(date) IS NOT NULL AND date(date) = date)
);

CREATE UNIQUE INDEX IF NOT EXISTS srs_index ON services_reminders_sent (id_user, id_service, id_reminder, date);

CREATE INDEX IF NOT EXISTS srs_reminder ON services_reminders_sent (id_reminder);
CREATE INDEX IF NOT EXISTS srs_user ON services_reminders_sent (id_user);

--
-- COMPTA
--

CREATE TABLE IF NOT EXISTS acc_charts
-- Plans comptables : il peut y en avoir plusieurs
(
    id INTEGER NOT NULL PRIMARY KEY,
    country TEXT NOT NULL,
    code TEXT NULL, -- NULL = plan comptable créé par l'utilisateur
    label TEXT NOT NULL,
    archived INTEGER NOT NULL DEFAULT 0 -- 1 = archivé, non-modifiable
);

CREATE TABLE IF NOT EXISTS acc_accounts
-- Comptes des plans comptables
(
    id INTEGER NOT NULL PRIMARY KEY,
    id_chart INTEGER NOT NULL REFERENCES acc_charts ON DELETE CASCADE,

    code TEXT NOT NULL, -- peut contenir des lettres, eg. 53A, 53B, etc.

    label TEXT NOT NULL,
    description TEXT NULL,

    position INTEGER NOT NULL, -- position actif/passif/charge/produit
    type INTEGER NOT NULL DEFAULT 0, -- Type de compte spécial : banque, caisse, en attente d'encaissement, etc.
    user INTEGER NOT NULL DEFAULT 1 -- 1 = fait partie du plan comptable original, 0 = a été ajouté par l'utilisateur
);

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
-- Exercices
(
    id INTEGER NOT NULL PRIMARY KEY,

    label TEXT NOT NULL,

    start_date TEXT NOT NULL CHECK (date(start_date) IS NOT NULL AND date(start_date) = start_date),
    end_date TEXT NOT NULL CHECK (date(end_date) IS NOT NULL AND date(end_date) = end_date),

    closed INTEGER NOT NULL DEFAULT 0,

    id_chart INTEGER NOT NULL REFERENCES acc_charts (id)
);

CREATE INDEX IF NOT EXISTS acc_years_closed ON acc_years (closed);

CREATE TABLE IF NOT EXISTS acc_transactions
-- Opérations comptables
(
    id INTEGER PRIMARY KEY NOT NULL,

    type INTEGER NOT NULL DEFAULT 0, -- Type d'écriture, 0 = avancée (normale)
    status INTEGER NOT NULL DEFAULT 0, -- Statut (bitmask)

    label TEXT NOT NULL,
    notes TEXT NULL,
    reference TEXT NULL, -- N° de pièce comptable

    date TEXT NOT NULL DEFAULT CURRENT_DATE CHECK (date(date) IS NOT NULL AND date(date) = date),

    validated INTEGER NOT NULL DEFAULT 0, -- 1 = écriture validée, non modifiable

    hash TEXT NULL,
    prev_hash TEXT NULL,

    id_year INTEGER NOT NULL REFERENCES acc_years(id),
    id_creator INTEGER NULL REFERENCES membres(id) ON DELETE SET NULL,
    id_related INTEGER NULL REFERENCES acc_transactions(id) ON DELETE SET NULL -- écriture liée (par ex. remboursement d'une dette)
);

CREATE INDEX IF NOT EXISTS acc_transactions_year ON acc_transactions (id_year);
CREATE INDEX IF NOT EXISTS acc_transactions_date ON acc_transactions (date);
CREATE INDEX IF NOT EXISTS acc_transactions_related ON acc_transactions (id_related);
CREATE INDEX IF NOT EXISTS acc_transactions_type ON acc_transactions (type, id_year);
CREATE INDEX IF NOT EXISTS acc_transactions_status ON acc_transactions (status);

CREATE TABLE IF NOT EXISTS acc_transactions_lines
-- Lignes d'écritures d'une opération
(
    id INTEGER PRIMARY KEY NOT NULL,

    id_transaction INTEGER NOT NULL REFERENCES acc_transactions (id) ON DELETE CASCADE,
    id_account INTEGER NOT NULL REFERENCES acc_accounts (id), -- N° du compte dans le plan comptable

    credit INTEGER NOT NULL,
    debit INTEGER NOT NULL,

    reference TEXT NULL, -- Référence de paiement, eg. numéro de chèque
    label TEXT NULL,

    reconciled INTEGER NOT NULL DEFAULT 0,

    id_analytical INTEGER NULL REFERENCES acc_accounts(id) ON DELETE SET NULL,

    CONSTRAINT line_check1 CHECK ((credit * debit) = 0),
    CONSTRAINT line_check2 CHECK ((credit + debit) > 0)
);

CREATE INDEX IF NOT EXISTS acc_transactions_lines_transaction ON acc_transactions_lines (id_transaction);
CREATE INDEX IF NOT EXISTS acc_transactions_lines_account ON acc_transactions_lines (id_account);
CREATE INDEX IF NOT EXISTS acc_transactions_lines_analytical ON acc_transactions_lines (id_analytical);
CREATE INDEX IF NOT EXISTS acc_transactions_lines_reconciled ON acc_transactions_lines (reconciled);

CREATE TABLE IF NOT EXISTS acc_transactions_users
-- Liaison des écritures et des membres
(
    id_user INTEGER NOT NULL REFERENCES membres (id) ON DELETE CASCADE,
    id_transaction INTEGER NOT NULL REFERENCES acc_transactions (id) ON DELETE CASCADE,
    id_service_user INTEGER NULL REFERENCES services_users (id) ON DELETE SET NULL,

    PRIMARY KEY (id_user, id_transaction)
);

CREATE INDEX IF NOT EXISTS acc_transactions_users_service ON acc_transactions_users (id_service_user);

CREATE TABLE IF NOT EXISTS plugins
(
    id TEXT NOT NULL PRIMARY KEY,
    officiel INTEGER NOT NULL DEFAULT 0,
    nom TEXT NOT NULL,
    description TEXT NULL,
    auteur TEXT NULL,
    url TEXT NULL,
    version TEXT NOT NULL,
    menu INTEGER NOT NULL DEFAULT 0,
    menu_condition TEXT NULL,
    config TEXT NULL
);

CREATE TABLE IF NOT EXISTS plugins_signaux
-- Association entre plugins et signaux (hooks)
(
    signal TEXT NOT NULL,
    plugin TEXT NOT NULL REFERENCES plugins (id),
    callback TEXT NOT NULL,
    PRIMARY KEY (signal, plugin)
);

---------- FILES ----------------

CREATE TABLE IF NOT EXISTS files
-- Files metadata
(
    id INTEGER NOT NULL PRIMARY KEY,
    path TEXT NOT NULL,
    parent TEXT NOT NULL,
    name TEXT NOT NULL, -- File name
    type INTEGER NOT NULL, -- File type, 1 = file, 2 = directory
    mime TEXT NULL,
    size INT NULL,
    modified TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP CHECK (datetime(modified) = modified),
    image INT NOT NULL DEFAULT 0,

    CHECK (type = 2 OR (mime IS NOT NULL AND size IS NOT NULL))
);

-- Unique index as this is used to make up a file path
CREATE UNIQUE INDEX IF NOT EXISTS files_unique ON files (path);
CREATE INDEX IF NOT EXISTS files_parent ON files (parent);
CREATE INDEX IF NOT EXISTS files_name ON files (name);
CREATE INDEX IF NOT EXISTS files_modified ON files (modified);

CREATE TABLE IF NOT EXISTS files_contents
-- Files contents (empty if using another storage backend)
(
    id INTEGER NOT NULL PRIMARY KEY REFERENCES files(id) ON DELETE CASCADE,
    compressed INT NOT NULL DEFAULT 0,
    content BLOB NOT NULL
);

CREATE VIRTUAL TABLE IF NOT EXISTS files_search USING fts4
-- Search inside files content
(
    tokenize=unicode61, -- Available from SQLITE 3.7.13 (2012)
    path TEXT NOT NULL,
    title TEXT NULL,
    content TEXT NOT NULL, -- Text content
    notindexed=path
);

CREATE TABLE IF NOT EXISTS web_pages
(
    id INTEGER NOT NULL PRIMARY KEY,
    parent TEXT NOT NULL, -- Parent path, empty = web root
    path TEXT NOT NULL, -- Full page directory name
    uri TEXT NOT NULL, -- Page identifier
    file_path TEXT NOT NULL, -- Full file path for contents
    type INTEGER NOT NULL, -- 1 = Category, 2 = Page
    status TEXT NOT NULL,
    format TEXT NOT NULL,
    published TEXT NOT NULL CHECK (datetime(published) = published),
    modified TEXT NOT NULL CHECK (datetime(modified) = modified),
    title TEXT NOT NULL,
    content TEXT NOT NULL
);

CREATE UNIQUE INDEX web_pages_path ON web_pages (path);
CREATE UNIQUE INDEX web_pages_file_path ON web_pages (file_path);
CREATE INDEX web_pages_parent ON web_pages (parent);
CREATE INDEX web_pages_published ON web_pages (published);
CREATE INDEX web_pages_title ON web_pages (title);

-- FIXME: rename to english
CREATE TABLE IF NOT EXISTS recherches
-- Recherches enregistrées
(
    id INTEGER NOT NULL PRIMARY KEY,
    id_membre INTEGER NULL REFERENCES membres (id) ON DELETE CASCADE, -- Si non NULL, alors la recherche ne sera visible que par le membre associé
    intitule TEXT NOT NULL,
    creation TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP CHECK (datetime(creation) IS NOT NULL AND datetime(creation) = creation),
    cible TEXT NOT NULL, -- "membres" ou "compta"
    type TEXT NOT NULL, -- "json" ou "sql"
    contenu TEXT NOT NULL
);


CREATE TABLE IF NOT EXISTS compromised_passwords_cache
-- Cache des hash de mots de passe compromis
(
    hash TEXT NOT NULL PRIMARY KEY
);

CREATE TABLE IF NOT EXISTS compromised_passwords_cache_ranges
-- Cache des préfixes de mots de passe compromis
(
    prefix TEXT NOT NULL PRIMARY KEY,
    date INTEGER NOT NULL
);

Modified src/include/data/champs_membres.ini from [f5ad8e1d8e] to [adac130192].

131
132
133
134
135
136
137






editable = true

[notes]
type = textarea
title = "Notes"
editable = false
private = true













>
>
>
>
>
>
131
132
133
134
135
136
137
138
139
140
141
142
143
editable = true

[notes]
type = textarea
title = "Notes"
editable = false
private = true

[photo]
type = file
title = "Photo"
editable = false
private = false

Modified src/include/data/schema.sql from [bdddcd8200] to [3456f2416e].





1
































































































































































































































































































































































1.0.0_schema.sql




























































































































































































































































































































































>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
CREATE TABLE IF NOT EXISTS config (
    key TEXT PRIMARY KEY NOT NULL,
    value TEXT NULL
);

CREATE TABLE IF NOT EXISTS users_categories
-- Users categories, mainly used to manage rights
(
    id INTEGER PRIMARY KEY NOT NULL,
    name TEXT NOT NULL,

    -- Permissions, 0 = no access, 1 = read-only, 2 = read-write, 9 = admin
    perm_web INTEGER NOT NULL DEFAULT 1,
    perm_documents INTEGER NOT NULL DEFAULT 1,
    perm_users INTEGER NOT NULL DEFAULT 1,
    perm_accounting INTEGER NOT NULL DEFAULT 1,

    perm_subscribe INTEGER NOT NULL DEFAULT 0,
    perm_connect INTEGER NOT NULL DEFAULT 1,
    perm_config INTEGER NOT NULL DEFAULT 0,

    hidden INTEGER NOT NULL DEFAULT 0
);

CREATE INDEX users_categories_hidden ON users_categories (hidden);

-- Membres de l'asso
-- Table dynamique générée par l'application
-- voir Garradin\Membres\Champs.php

CREATE TABLE IF NOT EXISTS membres_sessions
-- Sessions
(
    selecteur TEXT NOT NULL,
    hash TEXT NOT NULL,
    id_membre INTEGER NOT NULL REFERENCES membres (id) ON DELETE CASCADE,
    expire INT NOT NULL,

    PRIMARY KEY (selecteur, id_membre)
);

CREATE TABLE IF NOT EXISTS services
-- Types de services (cotisations)
(
    id INTEGER PRIMARY KEY NOT NULL,

    label TEXT NOT NULL,
    description TEXT NULL,

    duration INTEGER NULL CHECK (duration IS NULL OR duration > 0), -- En jours
    start_date TEXT NULL CHECK (start_date IS NULL OR date(start_date) = start_date),
    end_date TEXT NULL CHECK (end_date IS NULL OR (date(end_date) = end_date AND date(end_date) >= date(start_date)))
);

CREATE TABLE IF NOT EXISTS services_fees
(
    id INTEGER PRIMARY KEY NOT NULL,

    label TEXT NOT NULL,
    description TEXT NULL,

    amount INTEGER NULL,
    formula TEXT NULL, -- Formule de calcul du montant de la cotisation, si cotisation dynamique (exemple : membres.revenu_imposable * 0.01)

    id_service INTEGER NOT NULL REFERENCES services (id) ON DELETE CASCADE,
    id_account INTEGER NULL REFERENCES acc_accounts (id) ON DELETE SET NULL CHECK (id_account IS NULL OR id_year IS NOT NULL), -- NULL si le type n'est pas associé automatiquement à la compta
    id_year INTEGER NULL REFERENCES acc_years (id) ON DELETE SET NULL -- NULL si le type n'est pas associé automatiquement à la compta
);

CREATE TABLE IF NOT EXISTS services_users
-- Enregistrement des cotisations et activités
(
    id INTEGER NOT NULL PRIMARY KEY,
    id_user INTEGER NOT NULL REFERENCES membres (id) ON DELETE CASCADE,
    id_service INTEGER NOT NULL REFERENCES services (id) ON DELETE CASCADE,
    id_fee INTEGER NULL REFERENCES services_fees (id) ON DELETE CASCADE,

    paid INTEGER NOT NULL DEFAULT 0,
    expected_amount INTEGER NULL,

    date TEXT NOT NULL DEFAULT CURRENT_DATE CHECK (date(date) IS NOT NULL AND date(date) = date),
    expiry_date TEXT NULL CHECK (date(expiry_date) IS NULL OR date(expiry_date) = expiry_date)
);

CREATE UNIQUE INDEX IF NOT EXISTS su_unique ON services_users (id_user, id_service, date);

CREATE INDEX IF NOT EXISTS su_service ON services_users (id_service);
CREATE INDEX IF NOT EXISTS su_fee ON services_users (id_fee);
CREATE INDEX IF NOT EXISTS su_paid ON services_users (paid);
CREATE INDEX IF NOT EXISTS su_expiry ON services_users (expiry_date);

CREATE TABLE IF NOT EXISTS services_reminders
-- Rappels de devoir renouveller une cotisation
(
    id INTEGER NOT NULL PRIMARY KEY,
    id_service INTEGER NOT NULL REFERENCES services (id) ON DELETE CASCADE,

    delay INTEGER NOT NULL, -- Délai en jours pour envoyer le rappel

    subject TEXT NOT NULL,
    body TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS services_reminders_sent
-- Enregistrement des rappels envoyés à qui et quand
(
    id INTEGER NOT NULL PRIMARY KEY,

    id_user INTEGER NOT NULL REFERENCES membres (id) ON DELETE CASCADE,
    id_service INTEGER NOT NULL REFERENCES services (id) ON DELETE CASCADE,
    id_reminder INTEGER NOT NULL REFERENCES services_reminders (id) ON DELETE CASCADE,

    date TEXT NOT NULL DEFAULT CURRENT_DATE CHECK (date(date) IS NOT NULL AND date(date) = date)
);

CREATE UNIQUE INDEX IF NOT EXISTS srs_index ON services_reminders_sent (id_user, id_service, id_reminder, date);

CREATE INDEX IF NOT EXISTS srs_reminder ON services_reminders_sent (id_reminder);
CREATE INDEX IF NOT EXISTS srs_user ON services_reminders_sent (id_user);

--
-- COMPTA
--

CREATE TABLE IF NOT EXISTS acc_charts
-- Plans comptables : il peut y en avoir plusieurs
(
    id INTEGER NOT NULL PRIMARY KEY,
    country TEXT NOT NULL,
    code TEXT NULL, -- NULL = plan comptable créé par l'utilisateur
    label TEXT NOT NULL,
    archived INTEGER NOT NULL DEFAULT 0 -- 1 = archivé, non-modifiable
);

CREATE TABLE IF NOT EXISTS acc_accounts
-- Comptes des plans comptables
(
    id INTEGER NOT NULL PRIMARY KEY,
    id_chart INTEGER NOT NULL REFERENCES acc_charts ON DELETE CASCADE,

    code TEXT NOT NULL, -- peut contenir des lettres, eg. 53A, 53B, etc.

    label TEXT NOT NULL,
    description TEXT NULL,

    position INTEGER NOT NULL, -- position actif/passif/charge/produit
    type INTEGER NOT NULL DEFAULT 0, -- Type de compte spécial : banque, caisse, en attente d'encaissement, etc.
    user INTEGER NOT NULL DEFAULT 1 -- 1 = fait partie du plan comptable original, 0 = a été ajouté par l'utilisateur
);

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
-- Exercices
(
    id INTEGER NOT NULL PRIMARY KEY,

    label TEXT NOT NULL,

    start_date TEXT NOT NULL CHECK (date(start_date) IS NOT NULL AND date(start_date) = start_date),
    end_date TEXT NOT NULL CHECK (date(end_date) IS NOT NULL AND date(end_date) = end_date),

    closed INTEGER NOT NULL DEFAULT 0,

    id_chart INTEGER NOT NULL REFERENCES acc_charts (id)
);

CREATE INDEX IF NOT EXISTS acc_years_closed ON acc_years (closed);

CREATE TABLE IF NOT EXISTS acc_transactions
-- Opérations comptables
(
    id INTEGER PRIMARY KEY NOT NULL,

    type INTEGER NOT NULL DEFAULT 0, -- Type d'écriture, 0 = avancée (normale)
    status INTEGER NOT NULL DEFAULT 0, -- Statut (bitmask)

    label TEXT NOT NULL,
    notes TEXT NULL,
    reference TEXT NULL, -- N° de pièce comptable

    date TEXT NOT NULL DEFAULT CURRENT_DATE CHECK (date(date) IS NOT NULL AND date(date) = date),

    validated INTEGER NOT NULL DEFAULT 0, -- 1 = écriture validée, non modifiable

    hash TEXT NULL,
    prev_hash TEXT NULL,

    id_year INTEGER NOT NULL REFERENCES acc_years(id),
    id_creator INTEGER NULL REFERENCES membres(id) ON DELETE SET NULL,
    id_related INTEGER NULL REFERENCES acc_transactions(id) ON DELETE SET NULL -- écriture liée (par ex. remboursement d'une dette)
);

CREATE INDEX IF NOT EXISTS acc_transactions_year ON acc_transactions (id_year);
CREATE INDEX IF NOT EXISTS acc_transactions_date ON acc_transactions (date);
CREATE INDEX IF NOT EXISTS acc_transactions_related ON acc_transactions (id_related);
CREATE INDEX IF NOT EXISTS acc_transactions_type ON acc_transactions (type, id_year);
CREATE INDEX IF NOT EXISTS acc_transactions_status ON acc_transactions (status);

CREATE TABLE IF NOT EXISTS acc_transactions_lines
-- Lignes d'écritures d'une opération
(
    id INTEGER PRIMARY KEY NOT NULL,

    id_transaction INTEGER NOT NULL REFERENCES acc_transactions (id) ON DELETE CASCADE,
    id_account INTEGER NOT NULL REFERENCES acc_accounts (id), -- N° du compte dans le plan comptable

    credit INTEGER NOT NULL,
    debit INTEGER NOT NULL,

    reference TEXT NULL, -- Référence de paiement, eg. numéro de chèque
    label TEXT NULL,

    reconciled INTEGER NOT NULL DEFAULT 0,

    id_analytical INTEGER NULL REFERENCES acc_accounts(id) ON DELETE SET NULL,

    CONSTRAINT line_check1 CHECK ((credit * debit) = 0),
    CONSTRAINT line_check2 CHECK ((credit + debit) > 0)
);

CREATE INDEX IF NOT EXISTS acc_transactions_lines_transaction ON acc_transactions_lines (id_transaction);
CREATE INDEX IF NOT EXISTS acc_transactions_lines_account ON acc_transactions_lines (id_account);
CREATE INDEX IF NOT EXISTS acc_transactions_lines_analytical ON acc_transactions_lines (id_analytical);
CREATE INDEX IF NOT EXISTS acc_transactions_lines_reconciled ON acc_transactions_lines (reconciled);

CREATE TABLE IF NOT EXISTS acc_transactions_users
-- Liaison des écritures et des membres
(
    id_user INTEGER NOT NULL REFERENCES membres (id) ON DELETE CASCADE,
    id_transaction INTEGER NOT NULL REFERENCES acc_transactions (id) ON DELETE CASCADE,
    id_service_user INTEGER NULL REFERENCES services_users (id) ON DELETE SET NULL,

    PRIMARY KEY (id_user, id_transaction)
);

CREATE INDEX IF NOT EXISTS acc_transactions_users_service ON acc_transactions_users (id_service_user);

CREATE TABLE IF NOT EXISTS plugins
(
    id TEXT NOT NULL PRIMARY KEY,
    officiel INTEGER NOT NULL DEFAULT 0,
    nom TEXT NOT NULL,
    description TEXT NULL,
    auteur TEXT NULL,
    url TEXT NULL,
    version TEXT NOT NULL,
    menu INTEGER NOT NULL DEFAULT 0,
    menu_condition TEXT NULL,
    config TEXT NULL
);

CREATE TABLE IF NOT EXISTS plugins_signaux
-- Association entre plugins et signaux (hooks)
(
    signal TEXT NOT NULL,
    plugin TEXT NOT NULL REFERENCES plugins (id),
    callback TEXT NOT NULL,
    PRIMARY KEY (signal, plugin)
);

---------- FILES ----------------

CREATE TABLE IF NOT EXISTS files
-- Files metadata
(
    id INTEGER NOT NULL PRIMARY KEY,
    path TEXT NOT NULL,
    parent TEXT NOT NULL,
    name TEXT NOT NULL, -- File name
    type INTEGER NOT NULL, -- File type, 1 = file, 2 = directory
    mime TEXT NULL,
    size INT NULL,
    modified TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP CHECK (datetime(modified) = modified),
    image INT NOT NULL DEFAULT 0,

    CHECK (type = 2 OR (mime IS NOT NULL AND size IS NOT NULL))
);

-- Unique index as this is used to make up a file path
CREATE UNIQUE INDEX IF NOT EXISTS files_unique ON files (path);
CREATE INDEX IF NOT EXISTS files_parent ON files (parent);
CREATE INDEX IF NOT EXISTS files_name ON files (name);
CREATE INDEX IF NOT EXISTS files_modified ON files (modified);

CREATE TABLE IF NOT EXISTS files_contents
-- Files contents (empty if using another storage backend)
(
    id INTEGER NOT NULL PRIMARY KEY REFERENCES files(id) ON DELETE CASCADE,
    compressed INT NOT NULL DEFAULT 0,
    content BLOB NOT NULL
);

CREATE VIRTUAL TABLE IF NOT EXISTS files_search USING fts4
-- Search inside files content
(
    tokenize=unicode61, -- Available from SQLITE 3.7.13 (2012)
    path TEXT NOT NULL,
    title TEXT NULL,
    content TEXT NOT NULL, -- Text content
    notindexed=path
);

CREATE TABLE IF NOT EXISTS web_pages
(
    id INTEGER NOT NULL PRIMARY KEY,
    parent TEXT NOT NULL, -- Parent path, empty = web root
    path TEXT NOT NULL, -- Full page directory name
    uri TEXT NOT NULL, -- Page identifier
    file_path TEXT NOT NULL, -- Full file path for contents
    type INTEGER NOT NULL, -- 1 = Category, 2 = Page
    status TEXT NOT NULL,
    format TEXT NOT NULL,
    published TEXT NOT NULL CHECK (datetime(published) = published),
    modified TEXT NOT NULL CHECK (datetime(modified) = modified),
    title TEXT NOT NULL,
    content TEXT NOT NULL
);

CREATE UNIQUE INDEX web_pages_path ON web_pages (path);
CREATE UNIQUE INDEX web_pages_file_path ON web_pages (file_path);
CREATE INDEX web_pages_parent ON web_pages (parent);
CREATE INDEX web_pages_published ON web_pages (published);
CREATE INDEX web_pages_title ON web_pages (title);

-- FIXME: rename to english
CREATE TABLE IF NOT EXISTS recherches
-- Recherches enregistrées
(
    id INTEGER NOT NULL PRIMARY KEY,
    id_membre INTEGER NULL REFERENCES membres (id) ON DELETE CASCADE, -- Si non NULL, alors la recherche ne sera visible que par le membre associé
    intitule TEXT NOT NULL,
    creation TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP CHECK (datetime(creation) IS NOT NULL AND datetime(creation) = creation),
    cible TEXT NOT NULL, -- "membres" ou "compta"
    type TEXT NOT NULL, -- "json" ou "sql"
    contenu TEXT NOT NULL
);


CREATE TABLE IF NOT EXISTS compromised_passwords_cache
-- Cache des hash de mots de passe compromis
(
    hash TEXT NOT NULL PRIMARY KEY
);

CREATE TABLE IF NOT EXISTS compromised_passwords_cache_ranges
-- Cache des préfixes de mots de passe compromis
(
    prefix TEXT NOT NULL PRIMARY KEY,
    date INTEGER NOT NULL
);

Modified src/include/init.php from [43f2c1664b] to [feb523c315].

89
90
91
92
93
94
95
96




97
98
99
100
101
102
103
104
105
	}

	if (file_exists($path)) {
		require_once $path;
	}
}, true);

if (!defined('Garradin\DATA_ROOT'))




{
	define('Garradin\DATA_ROOT', ROOT);
}

if (!defined('Garradin\WWW_URI'))
{
	try {
		$uri = \KD2\HTTP::getRootURI(ROOT);
	}







|
>
>
>
>
|
|







89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
	}

	if (file_exists($path)) {
		require_once $path;
	}
}, true);

if (!defined('Garradin\DATA_ROOT')) {
	// Migrate plugins, cache and SQLite to data/ subdirectory (version 1.1)
	if (!file_exists(ROOT . '/data/association.sqlite') && file_exists(ROOT . '/association.sqlite')) {
		Upgrade::moveDataRoot();
	}

	define('Garradin\DATA_ROOT', ROOT . '/data');
}

if (!defined('Garradin\WWW_URI'))
{
	try {
		$uri = \KD2\HTTP::getRootURI(ROOT);
	}
140
141
142
143
144
145
146

147
148
149
150
151
152
153

if (!defined('Garradin\WWW_URL')) {
	define('Garradin\WWW_URL', \KD2\HTTP::getScheme() . '://' . $host . WWW_URI);
}

static $default_config = [
	'CACHE_ROOT'            => DATA_ROOT . '/cache',

	'DB_FILE'               => DATA_ROOT . '/association.sqlite',
	'DB_SCHEMA'             => ROOT . '/include/data/schema.sql',
	'PLUGINS_ROOT'          => DATA_ROOT . '/plugins',
	'PREFER_HTTPS'          => false,
	'ALLOW_MODIFIED_IMPORT' => true,
	'PLUGINS_SYSTEM'        => '',
	'SHOW_ERRORS'           => true,







>







144
145
146
147
148
149
150
151
152
153
154
155
156
157
158

if (!defined('Garradin\WWW_URL')) {
	define('Garradin\WWW_URL', \KD2\HTTP::getScheme() . '://' . $host . WWW_URI);
}

static $default_config = [
	'CACHE_ROOT'            => DATA_ROOT . '/cache',
	'SHARED_CACHE_ROOT'     => DATA_ROOT . '/cache/shared',
	'DB_FILE'               => DATA_ROOT . '/association.sqlite',
	'DB_SCHEMA'             => ROOT . '/include/data/schema.sql',
	'PLUGINS_ROOT'          => DATA_ROOT . '/plugins',
	'PREFER_HTTPS'          => false,
	'ALLOW_MODIFIED_IMPORT' => true,
	'PLUGINS_SYSTEM'        => '',
	'SHOW_ERRORS'           => true,
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
	'SMTP_PORT'             => 587,
	'SMTP_SECURITY'         => 'STARTTLS',
	'ADMIN_URL'             => WWW_URL . 'admin/',
	'NTP_SERVER'            => 'fr.pool.ntp.org',
	'ENABLE_AUTOMATIC_BACKUPS' => true,
	'ADMIN_COLOR1'          => '#9c4f15',
	'ADMIN_COLOR2'          => '#d98628',





];

foreach ($default_config as $const => $value)
{
	$const = sprintf('Garradin\\%s', $const);

	if (!defined($const))
	{
		define($const, $value);
	}
}

if (!defined('Garradin\ADMIN_BACKGROUND_IMAGE')) {
	define('Garradin\ADMIN_BACKGROUND_IMAGE', ADMIN_URL . 'static/gdin_bg.png');
}

const WEBSITE = 'https://fossil.kd2.org/garradin/';
const PLUGINS_URL = 'https://garradin.eu/plugins/list.json';






// PHP devrait être assez intelligent pour chopper la TZ système mais nan
// il sait pas faire (sauf sur Debian qui a le bon patch pour ça), donc pour
// éviter le message d'erreur à la con on définit une timezone par défaut
// Pour utiliser une autre timezone, il suffit de définir date.timezone dans
// un .htaccess ou dans config.local.php
if (!ini_get('date.timezone'))







>
>
>
>
>


















>
>
>
>
>







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
	'SMTP_PORT'             => 587,
	'SMTP_SECURITY'         => 'STARTTLS',
	'ADMIN_URL'             => WWW_URL . 'admin/',
	'NTP_SERVER'            => 'fr.pool.ntp.org',
	'ENABLE_AUTOMATIC_BACKUPS' => true,
	'ADMIN_COLOR1'          => '#9c4f15',
	'ADMIN_COLOR2'          => '#d98628',
	'FILE_STORAGE_BACKEND'  => 'SQLite',
	'FILE_STORAGE_CONFIG'   => null,
	'FILE_STORAGE_QUOTA'    => null,
	'API_USER'              => null,
	'API_PASSWORD'          => null,
];

foreach ($default_config as $const => $value)
{
	$const = sprintf('Garradin\\%s', $const);

	if (!defined($const))
	{
		define($const, $value);
	}
}

if (!defined('Garradin\ADMIN_BACKGROUND_IMAGE')) {
	define('Garradin\ADMIN_BACKGROUND_IMAGE', ADMIN_URL . 'static/gdin_bg.png');
}

const WEBSITE = 'https://fossil.kd2.org/garradin/';
const PLUGINS_URL = 'https://garradin.eu/plugins/list.json';

const USER_TEMPLATES_CACHE_ROOT = CACHE_ROOT . '/utemplates';
const STATIC_CACHE_ROOT = CACHE_ROOT . '/static';
const SHARED_USER_TEMPLATES_CACHE_ROOT = SHARED_CACHE_ROOT . '/utemplates';
const SMARTYER_CACHE_ROOT = SHARED_CACHE_ROOT . '/compiled';

// PHP devrait être assez intelligent pour chopper la TZ système mais nan
// il sait pas faire (sauf sur Debian qui a le bon patch pour ça), donc pour
// éviter le message d'erreur à la con on définit une timezone par défaut
// Pour utiliser une autre timezone, il suffit de définir date.timezone dans
// un .htaccess ou dans config.local.php
if (!ini_get('date.timezone'))
209
210
211
212
213
214
215




216
217
218
219
220
221
222
class UserException extends \LogicException
{
}

class ValidationException extends UserException
{
}





// activer le gestionnaire d'erreurs/exceptions
ErrorManager::enable(SHOW_ERRORS ? ErrorManager::DEVELOPMENT : ErrorManager::PRODUCTION);
ErrorManager::setLogFile(DATA_ROOT . '/error.log');

// activer l'envoi de mails si besoin est
if (MAIL_ERRORS)







>
>
>
>







224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
class UserException extends \LogicException
{
}

class ValidationException extends UserException
{
}

class APIException extends \LogicException
{
}

// activer le gestionnaire d'erreurs/exceptions
ErrorManager::enable(SHOW_ERRORS ? ErrorManager::DEVELOPMENT : ErrorManager::PRODUCTION);
ErrorManager::setLogFile(DATA_ROOT . '/error.log');

// activer l'envoi de mails si besoin est
if (MAIL_ERRORS)
320
321
322
323
324
325
326
327
328
329
330
331
332
333
		if (in_array('install.php', get_included_files())) {
			die('Erreur de redirection en boucle : problème de configuration ?');
		}

		Utils::redirect(ADMIN_URL . 'install.php');
	}

	$config = Config::getInstance();

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







|

|




339
340
341
342
343
344
345
346
347
348
349
350
351
352
		if (in_array('install.php', get_included_files())) {
			die('Erreur de redirection en boucle : problème de configuration ?');
		}

		Utils::redirect(ADMIN_URL . 'install.php');
	}

	$v = DB::getInstance()->version();

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

Added src/include/lib/Garradin/API.php version [fca20dc380].























































































































































































































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

namespace Garradin;

class API
{
	protected $body;
	protected $params;
	protected $method;

	protected function body(): string
	{
		if (null == $this->body) {
			$this->body = trim(file_get_contents('php://input'));
		}

		return $this->body;
	}

	protected function download()
	{
		if ($this->method != 'GET') {
			throw new APIException('Wrong request method', 400);
		}

		(new Sauvegarde)->dump();
		return null;
	}

	protected function sql()
	{
		if ($this->method != 'POST') {
			throw new APIException('Wrong request method', 400);
		}

		$body = $this->body();

		if ($body === '') {
			throw new APIException('Missing SQL statement', 400);
		}

		try {
			return ['results' => Recherche::rawSQL($body)];
		}
		catch (\Exception $e) {
			http_response_code(400);
			return ['error' => 'Error in SQL statement', 'sql_error' => $e->getMessage()];
		}
	}

	public function checkAuth(): void
	{
		if (!isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
			throw new APIException('No username or password supplied', 401);
		}

		if ($_SERVER['PHP_AUTH_USER'] !== API_USER || $_SERVER['PHP_AUTH_PW'] !== API_PASSWORD) {
			throw new APIException('Invalid username or password', 403);
		}
	}

	public function dispatch(string $fn)
	{
		$this->checkAuth();

		switch ($fn) {
			case 'sql':
				return $this->sql();
			case 'download':
				return $this->download();
			default:
				throw new APIException('Unknown path', 404);
		}
	}

	static public function dispatchURI(string $uri)
	{
		$fn = strtok($uri, '/');

		$api = new self;

		$api->method = $_SERVER['REQUEST_METHOD'] ?? null;

		http_response_code(200);

		try {
			$return = $api->dispatch($fn);

			if (null !== $return) {
				echo json_encode($return);
			}
		}
		catch (\Exception $e) {
			if ($e instanceof APIException) {
				http_response_code($e->getCode());
				echo json_encode(['error' => $e->getMessage()]);
			}
			elseif ($e instanceof UserException || $e instanceof ValidationException) {
				http_response_code(400);
				echo json_encode(['error' => $e->getMessage()]);
			}
			else {
				throw $e;
			}
		}
	}
}

Modified src/include/lib/Garradin/Accounting/Reports.php from [b07c8619b9] to [5ea34ddcf7].

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
			INNER JOIN acc_accounts a ON a.id = l.id_analytical
			INNER JOIN acc_years y ON y.id = t.id_year
			GROUP BY %s
			ORDER BY %s;';

		if ($by_year) {
			$group = 'y.id, a.id';
			$order = 'y.start_date DESC, a.label COLLATE NOCASE';
		}
		else {
			$group = 'a.id, y.id';
			$order = 'a.label COLLATE NOCASE, y.id';
		}

		$sql = sprintf($sql, Account::EXPENSE, Account::REVENUE, $group, $order);

		$current = null;

		static $sums = ['credit', 'debit', 'sum'];







|



|







84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
			INNER JOIN acc_accounts a ON a.id = l.id_analytical
			INNER JOIN acc_years y ON y.id = t.id_year
			GROUP BY %s
			ORDER BY %s;';

		if ($by_year) {
			$group = 'y.id, a.id';
			$order = 'y.start_date DESC, a.code COLLATE NOCASE';
		}
		else {
			$group = 'a.id, y.id';
			$order = 'a.code COLLATE NOCASE, y.id';
		}

		$sql = sprintf($sql, Account::EXPENSE, Account::REVENUE, $group, $order);

		$current = null;

		static $sums = ['credit', 'debit', 'sum'];

Modified src/include/lib/Garradin/Accounting/Transactions.php from [1236717366] to [33dd074d49].

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
	{
		$db = DB::getInstance();
		$db->begin();

		try {
			$ids = [];
			foreach ($journal as $row) {
				if (!array_key_exists($row->id, $checked)) {
					continue;
				}

				$ids[] = (int)$row->id;

				$line = new Line;
				$line->importForm([
					'reference'  => $row->line_reference,
					'id_account' => $row->id_account,
				]);

				$line->credit = $row->debit;

				$transaction->addLine($line);
			}

			$transaction->save();
			$ids = implode(',', $ids);







|










>







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
	{
		$db = DB::getInstance();
		$db->begin();

		try {
			$ids = [];
			foreach ($journal as $row) {
				if (!array_key_exists($row->id_line, $checked)) {
					continue;
				}

				$ids[] = (int)$row->id;

				$line = new Line;
				$line->importForm([
					'reference'  => $row->line_reference,
					'id_account' => $row->id_account,
				]);

				$line->credit = $row->debit;

				$transaction->addLine($line);
			}

			$transaction->save();
			$ids = implode(',', $ids);
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
		$db = DB::getInstance();

		if (null !== $id_analytical && !$db->test(Account::TABLE, 'type = ? AND id = ?', Account::TYPE_ANALYTICAL, $id_analytical)) {
			throw new \InvalidArgumentException('Chosen account ID is not analytical');
		}

		if (isset($transactions, $lines) || ($transactions === null && $lines === null)) {
			throw new BadMethodCallException('Only one of transactions or lines should be set');
		}

		$selection = array_map('intval', $transactions ?? $lines);
		$where = sprintf($transactions ? 'id_transaction IN (%s)' : 'id IN (%s)', implode(', ', $selection));

		return $db->exec(sprintf('UPDATE acc_transactions_lines SET id_analytical = %s WHERE %s;',
			(int)$id_analytical ?: 'NULL', $where));







|







364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
		$db = DB::getInstance();

		if (null !== $id_analytical && !$db->test(Account::TABLE, 'type = ? AND id = ?', Account::TYPE_ANALYTICAL, $id_analytical)) {
			throw new \InvalidArgumentException('Chosen account ID is not analytical');
		}

		if (isset($transactions, $lines) || ($transactions === null && $lines === null)) {
			throw new \BadMethodCallException('Only one of transactions or lines should be set');
		}

		$selection = array_map('intval', $transactions ?? $lines);
		$where = sprintf($transactions ? 'id_transaction IN (%s)' : 'id IN (%s)', implode(', ', $selection));

		return $db->exec(sprintf('UPDATE acc_transactions_lines SET id_analytical = %s WHERE %s;',
			(int)$id_analytical ?: 'NULL', $where));

Modified src/include/lib/Garradin/CSV.php from [b79b34dab0] to [58e95c673d].

150
151
152
153
154
155
156
157
158
159
160
161
162
163
164

		$fp = fopen('php://output', 'w');

		if ($header) {
			fputs($fp, self::row($header));
		}

		if ($iterator->valid()) {
			foreach ($iterator as $row) {
				foreach ($row as $key => &$v) {
					if (is_object($v)&& $v instanceof \DateTimeInterface) {
						$v = $v->format('d/m/Y');
					}
				}








|







150
151
152
153
154
155
156
157
158
159
160
161
162
163
164

		$fp = fopen('php://output', 'w');

		if ($header) {
			fputs($fp, self::row($header));
		}

		if (!($iterator instanceof \Iterator) || $iterator->valid()) {
			foreach ($iterator as $row) {
				foreach ($row as $key => &$v) {
					if (is_object($v)&& $v instanceof \DateTimeInterface) {
						$v = $v->format('d/m/Y');
					}
				}

185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
		$ods = new ODSWriter;
		$ods->table_name = $name;

		if ($header) {
			$ods->add((array) $header);
		}

		if ($iterator->valid()) {
			foreach ($iterator as $row) {
				$row = self::rowToArray($row, $row_map_callback);

				if (!$header)
				{
					$ods->add(array_keys($row));
					$header = true;







|







185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
		$ods = new ODSWriter;
		$ods->table_name = $name;

		if ($header) {
			$ods->add((array) $header);
		}

		if (!($iterator instanceof \Iterator) || $iterator->valid()) {
			foreach ($iterator as $row) {
				$row = self::rowToArray($row, $row_map_callback);

				if (!$header)
				{
					$ods->add(array_keys($row));
					$header = true;

Modified src/include/lib/Garradin/Config.php from [e6ef6cc161] to [362169af35].

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
<?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))
        {
            $this->save();

        }
    }

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

namespace Garradin;

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

use KD2\SMTP;

class Config extends Entity
{
	const ADMIN_BACKGROUND_FILENAME = File::CONTEXT_CONFIG . '/admin_bg.png';

	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 $last_chart_change;
	protected $last_version_check;

	protected $couleur1;
	protected $couleur2;

	protected $admin_background;

	protected $site_disabled;

	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'        => '?string',

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

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

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

		'couleur1'              => '?string',
		'couleur2'              => '?string',
		'admin_background'      => '?string',

		'site_disabled'         => 'bool',
	];

	static protected $_instance = null;

	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 key, value FROM config ORDER BY key;');



		if (empty($config)) {


			return;
		}





		$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;
			}
		}



		$this->load($config);



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







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


			return true;
		}

		$this->selfCheck();





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


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

			$value = $this->$key;
			$type = ltrim($this->_types[$key], '?');









			if ($type == Champs::class) {
				$value = $value->toString();
			}
			elseif (is_object($value)) {
				throw new \UnexpectedValueException('Unexpected object as value: ' . get_class($value));
			}


			$values[$key] = $value;




		}


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

		$db->begin();




		foreach ($values as $key => $value)

		{







			$db->preparedQuery('INSERT OR REPLACE INTO config (key, value) VALUES (?, ?);', $key, $value);

		}

		if (!empty($values['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 importForm($source = null): void
	{
		if (null === $source) {

			$source = $_POST;
		}



		// N'enregistrer les couleurs que si ce ne sont pas les couleurs par défaut

		if (!isset($source['couleur1'], $source['couleur2'])
			|| ($source['couleur1'] == ADMIN_COLOR1 && $source['couleur2'] == ADMIN_COLOR2))
		{

			$source['couleur1'] = null;



			$source['couleur2'] = null;

		}







		if (isset($source['admin_background']) && trim($source['admin_background']) == 'RESET') {



			$source['admin_background'] = null;
		}
		elseif (isset($source['admin_background']) && strlen($source['admin_background'])) {

			$file = Files::get(self::ADMIN_BACKGROUND_FILENAME);

			if ($file) {


				$file->storeFromBase64($source['admin_background']);
			}
			else {


				$file = File::createFromBase64(Utils::dirname(self::ADMIN_BACKGROUND_FILENAME), Utils::basename(self::ADMIN_BACKGROUND_FILENAME), $source['admin_background']);
			}




			$source['admin_background'] = $file->path;







		}







		parent::importForm($source);



	}



	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 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(null === $this->site_asso || filter_var($this->site_asso, FILTER_VALIDATE_URL), 'L\'adresse URL du site web est invalide.');

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





		$this->assert(strlen($this->admin_homepage) > 0, '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('users_categories', 'id = ?', $this->categorie_membres), 'Catégorie de membres inconnue');
	}
}

Modified src/include/lib/Garradin/DB.php from [dad60ad267] to [8dd3841b1b].

9
10
11
12
13
14
15


16
17
18
19
20
21
22
    /**
     * Application ID pour SQLite
     * @link https://www.sqlite.org/pragma.html#pragma_application_id
     */
    const APPID = 0x5da2d811;

    static protected $_instance = null;



    static public function getInstance($create = false, $readonly = false)
    {
        if (null === self::$_instance) {
            self::$_instance = new DB('sqlite', ['file' => DB_FILE]);
        }








>
>







9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    /**
     * Application ID pour SQLite
     * @link https://www.sqlite.org/pragma.html#pragma_application_id
     */
    const APPID = 0x5da2d811;

    static protected $_instance = null;

    protected $_version = -1;

    static public function getInstance($create = false, $readonly = false)
    {
        if (null === self::$_instance) {
            self::$_instance = new DB('sqlite', ['file' => DB_FILE]);
        }

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
        $this->db->busyTimeout(10 * 1000);

        // Performance enhancement
        // see https://www.cs.utexas.edu/~jaya/slides/apsys17-sqlite-slides.pdf
        // https://ericdraken.com/sqlite-performance-testing/
        $this->exec(sprintf('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA journal_size_limit = %d;', 32 * 1024 * 1024));

        $this->db->createFunction('transliterate_to_ascii', ['Garradin\Utils', 'transliterateToAscii']);

































































































    }

    public function close(): void
    {
        parent::close();
        self::$_instance = null;
    }

    public function beginSchemaUpdate()
    {
        $this->toggleForeignKeys(false);
        $this->begin();
    }

    public function commitSchemaUpdate()
    {
        $this->commit();
        $this->toggleForeignKeys(true);
    }






    /**
     * @see https://www.sqlite.org/lang_altertable.html
     */
    public function toggleForeignKeys($enable)
    {
        assert(is_bool($enable));







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



















>
>
>
>
>







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
        $this->db->busyTimeout(10 * 1000);

        // Performance enhancement
        // see https://www.cs.utexas.edu/~jaya/slides/apsys17-sqlite-slides.pdf
        // https://ericdraken.com/sqlite-performance-testing/
        $this->exec(sprintf('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA journal_size_limit = %d;', 32 * 1024 * 1024));

        $this->db->createFunction('dirname', [Utils::class, 'dirname']);
        $this->db->createFunction('basename', [Utils::class, 'basename']);
        $this->db->createCollation('NOCASE', [Utils::class, 'unicodeCaseComparison']);
    }

    public function version(): ?string
    {
        if (-1 === $this->_version) {
            $this->connect();
            $this->_version = self::getVersion($this->db);
        }

        return $this->_version;
    }

    static public function getVersion($db)
    {
        $v = (int) $db->querySingle('PRAGMA user_version;');
        $v = self::parseVersion($v);

        if (null === $v) {
            // For legacy version before 1.1.0
            $v = $db->querySingle('SELECT valeur FROM config WHERE cle = \'version\';');
        }

        return $v ?: null;
    }

    static public function parseVersion(int $v): ?string
    {
        if ($v > 0) {
            $major = intval($v / 1000000);
            $v -= $major * 1000000;
            $minor = intval($v / 10000);
            $v -= $minor * 10000;
            $release = intval($v / 100);
            $v -= $release * 100;
            $type = $v;

            if ($type == 0) {
                $type = '';
            }
            // Corrective release: 1.2.3.1
            elseif ($type > 75) {
                $type = '.' . ($type - 75);
            }
            // RC release
            elseif ($type > 50) {
                $type = '-rc' . ($type - 50);
            }
            // Beta
            elseif ($type > 25) {
                $type = '-beta' . ($type - 25);
            }
            // Alpha
            else {
                $type = '-alpha' . $type;
            }

            $v = sprintf('%d.%d.%d%s', $major, $minor, $release, $type);
        }

        return $v ?: null;
    }

    /**
     * Save version to database
     * rc, alpha, beta and corrective release (4th number) are limited to 24 versions each
     * @param string $version Version string, eg. 1.2.3-rc2
     */
    public function setVersion(string $version): void
    {
        if (!preg_match('/^(\d+)\.(\d+)\.(\d+)(?:(?:-(alpha|beta|rc)|\.)(\d+)|)?$/', $version, $match)) {
            throw new \InvalidArgumentException('Invalid version number: ' . $version);
        }

        $version = ($match[1] * 100 * 100 * 100) + ($match[2] * 100 * 100) + ($match[3] * 100);

        if (isset($match[5])) {
            if ($match[5] > 24) {
                throw new \InvalidArgumentException('Invalid version number: cannot have a 4th component larger than 24: ' . $version);
            }

            if ($match[4] == 'rc') {
                $version += $match[5] + 50;
            }
            elseif ($match[4] == 'beta') {
                $version += $match[5] + 25;
            }
            elseif ($match[4] == 'alpha') {
                $version += $match[5];
            }
            else {
                $version += $match[5] + 75;
            }
        }

        $this->db->exec(sprintf('PRAGMA user_version = %d;', $version));
    }

    public function close(): void
    {
        parent::close();
        self::$_instance = null;
    }

    public function beginSchemaUpdate()
    {
        $this->toggleForeignKeys(false);
        $this->begin();
    }

    public function commitSchemaUpdate()
    {
        $this->commit();
        $this->toggleForeignKeys(true);
    }

    public function lastErrorMsg()
    {
        return $this->db->lastErrorMsg();
    }

    /**
     * @see https://www.sqlite.org/lang_altertable.html
     */
    public function toggleForeignKeys($enable)
    {
        assert(is_bool($enable));

Modified src/include/lib/Garradin/Entities/Accounting/Transaction.php from [6a877f3358] to [d39e3b122c].

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






15
16
17
18
19
20
21
<?php

namespace Garradin\Entities\Accounting;

use KD2\DB\EntityManager;
use Garradin\Entity;
use Garradin\Fichiers;
use Garradin\Accounting\Accounts;
use Garradin\ValidationException;
use Garradin\DB;
use Garradin\Config;
use Garradin\Utils;
use Garradin\UserException;







class Transaction extends Entity
{
	const TABLE = 'acc_transactions';

	const TYPE_ADVANCED = 0;
	const TYPE_REVENUE = 1;
	const TYPE_EXPENSE = 2;





|
|
<
<





>
>
>
>
>
>







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

namespace Garradin\Entities\Accounting;

use KD2\DB\EntityManager;

use Garradin\Entity;


use Garradin\DB;
use Garradin\Config;
use Garradin\Utils;
use Garradin\UserException;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;

use Garradin\Accounting\Accounts;
use Garradin\ValidationException;

class Transaction extends Entity
{
	const TABLE = 'acc_transactions';

	const TYPE_ADVANCED = 0;
	const TYPE_REVENUE = 1;
	const TYPE_EXPENSE = 2;
83
84
85
86
87
88
89



90
91
92
93
94
95
96
		'reference' => 'string|max:200',
		'date'      => 'required|date_format:d/m/Y',
	];

	protected $_lines;
	protected $_old_lines = [];




	protected $_related;

	static public function getTypeFromAccountType(int $account_type)
	{
		switch ($account_type) {
			case Account::TYPE_REVENUE:
				return self::TYPE_REVENUE;







>
>
>







87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
		'reference' => 'string|max:200',
		'date'      => 'required|date_format:d/m/Y',
	];

	protected $_lines;
	protected $_old_lines = [];

	/**
	 * @var Transaction
	 */
	protected $_related;

	static public function getTypeFromAccountType(int $account_type)
	{
		switch ($account_type) {
			case Account::TYPE_REVENUE:
				return self::TYPE_REVENUE;
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307

	public function save(): bool
	{
		if ($this->validated && empty($this->_modified['validated'])) {
			throw new ValidationException('Il n\'est pas possible de modifier une écriture qui a été validée');
		}

		$exists = $this->exists();

		$db = DB::getInstance();

		if ($db->test(Year::TABLE, 'id = ? AND closed = 1', $this->id_year)) {
			throw new ValidationException('Il n\'est pas possible de créer ou modifier une écriture dans un exercice clôturé');
		}

		if (!parent::save()) {







<
<







299
300
301
302
303
304
305


306
307
308
309
310
311
312

	public function save(): bool
	{
		if ($this->validated && empty($this->_modified['validated'])) {
			throw new ValidationException('Il n\'est pas possible de modifier une écriture qui a été validée');
		}



		$db = DB::getInstance();

		if ($db->test(Year::TABLE, 'id = ? AND closed = 1', $this->id_year)) {
			throw new ValidationException('Il n\'est pas possible de créer ou modifier une écriture dans un exercice clôturé');
		}

		if (!parent::save()) {
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330

		foreach ($this->_old_lines as $line)
		{
			$line->delete();
		}

		// Remove flag
		if (!$exists && $this->_related) {
			$this->_related->markPaid();
			$this->_related->save();
		}

		return true;
	}








|







321
322
323
324
325
326
327
328
329
330
331
332
333
334
335

		foreach ($this->_old_lines as $line)
		{
			$line->delete();
		}

		// Remove flag
		if ((self::TYPE_DEBT == $this->type || self::TYPE_CREDIT == $this->type) && $this->_related) {
			$this->_related->markPaid();
			$this->_related->save();
		}

		return true;
	}

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

		$db = DB::getInstance();

		if ($db->test(Year::TABLE, 'id = ? AND closed = 1', $this->id_year)) {
			throw new ValidationException('Il n\'est pas possible de supprimer une écriture qui fait partie d\'un exercice clôturé');
		}

		Fichiers::deleteLinkedFiles(Fichiers::LIEN_COMPTA, $this->id());

		return parent::delete();
	}

	public function selfCheck(): void
	{
		parent::selfCheck();

		$db = DB::getInstance();
		$config = Config::getInstance();

		// ID d'exercice obligatoire
		if (null === $this->id_year) {
			throw new \LogicException('Aucun exercice spécifié.');
		}

		if (!$db->test(Year::TABLE, 'id = ? AND start_date <= ? AND end_date >= ?;', $this->id_year, $this->date->format('Y-m-d'), $this->date->format('Y-m-d')))







|









<







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

371
372
373
374
375
376
377

		$db = DB::getInstance();

		if ($db->test(Year::TABLE, 'id = ? AND closed = 1', $this->id_year)) {
			throw new ValidationException('Il n\'est pas possible de supprimer une écriture qui fait partie d\'un exercice clôturé');
		}

		Files::delete($this->getAttachementsDirectory());

		return parent::delete();
	}

	public function selfCheck(): void
	{
		parent::selfCheck();

		$db = DB::getInstance();


		// ID d'exercice obligatoire
		if (null === $this->id_year) {
			throw new \LogicException('Aucun exercice spécifié.');
		}

		if (!$db->test(Year::TABLE, 'id = ? AND start_date <= ? AND end_date >= ?;', $this->id_year, $this->date->format('Y-m-d'), $this->date->format('Y-m-d')))
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
		if (0 !== $total) {
			throw new ValidationException(sprintf('Écriture non équilibrée : déséquilibre (%s) entre débits et crédits', Utils::money_format($total)));
		}

		if (!array_key_exists($this->type, self::TYPES_NAMES)) {
			throw new ValidationException('Type d\'écriture inconnu : ' . $this->type);
		}

		$this->assert($db->test('acc_years', 'id = ?', $this->id_year), 'L\'exercice sélectionné n\'existe pas');
		$this->assert($this->id_creator === null || $db->test('membres', 'id = ?', $this->id_creator), 'Le compte membre créateur de l\'écriture n\'existe pas');
	}

	public function importFromDepositForm(?array $source = null): void
	{
		if (null === $source) {
			$source = $_POST;
		}

		if (empty($source['amount'])) {
			throw new UserException('Montant non précisé');
		}

		$this->type = self::TYPE_TRANSFER;
		$amount = $source['amount'];

		$key = 'account_transfer';
		$account = isset($source[$key]) && @count($source[$key]) ? key($source[$key]) : null;

		$line = new Line;
		$line->importForm([







<
<
<












|







391
392
393
394
395
396
397



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
		if (0 !== $total) {
			throw new ValidationException(sprintf('Écriture non équilibrée : déséquilibre (%s) entre débits et crédits', Utils::money_format($total)));
		}

		if (!array_key_exists($this->type, self::TYPES_NAMES)) {
			throw new ValidationException('Type d\'écriture inconnu : ' . $this->type);
		}



	}

	public function importFromDepositForm(?array $source = null): void
	{
		if (null === $source) {
			$source = $_POST;
		}

		if (empty($source['amount'])) {
			throw new UserException('Montant non précisé');
		}

		$this->type = self::TYPE_ADVANCED;
		$amount = $source['amount'];

		$key = 'account_transfer';
		$account = isset($source[$key]) && @count($source[$key]) ? key($source[$key]) : null;

		$line = new Line;
		$line->importForm([
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478

			$lines = Utils::array_transpose($source['lines']);

			foreach ($lines as $i => $line) {
				$line['id_account'] = @count($line['account']) ? key($line['account']) : null;

				if (!$line['id_account']) {
					throw new ValidationException('Numéro de compte invalide sur la ligne ' . ($i+1));
				}

				$line = (new Line)->import($line);
				$this->addLine($line);
			}
		}
		else {
			$details = self::getTypesDetails();

			if (!array_key_exists($type, $details)) {
				throw new ValidationException('Type d\'écriture inconnu');
			}

			if (!empty($this->_related) && ($type == self::TYPE_DEBT || $type == self::TYPE_CREDIT)) {
				$this->set('type', self::TYPE_ADVANCED);
			}
			elseif (!$this->exists() && ($type == self::TYPE_DEBT || $type == self::TYPE_CREDIT)) {
				$this->addStatus(self::STATUS_WAITING);
			}

			if (empty($source['amount'])) {
				throw new UserException('Montant non précisé');
			}

			$amount = $source['amount'];








|













|
|

|
|








446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479

			$lines = Utils::array_transpose($source['lines']);

			foreach ($lines as $i => $line) {
				$line['id_account'] = @count($line['account']) ? key($line['account']) : null;

				if (!$line['id_account']) {
					throw new ValidationException('Numéro de compte invalide sur la ligne ' . ((int) $i+1));
				}

				$line = (new Line)->import($line);
				$this->addLine($line);
			}
		}
		else {
			$details = self::getTypesDetails();

			if (!array_key_exists($type, $details)) {
				throw new ValidationException('Type d\'écriture inconnu');
			}

			if (empty($this->_related) && ($type == self::TYPE_DEBT || $type == self::TYPE_CREDIT)) {
				$this->addStatus(self::STATUS_WAITING);
			}
			else {
				$this->removeStatus(self::STATUS_WAITING);
			}

			if (empty($source['amount'])) {
				throw new UserException('Montant non précisé');
			}

			$amount = $source['amount'];

575
576
577
578
579
580
581


582



583
584
585
586
587
588
589
	public function year()
	{
		return EntityManager::findOneById(Year::class, $this->id_year);
	}

	public function listFiles()
	{


		return Fichiers::listLinkedFiles(Fichiers::LIEN_COMPTA, $this->id());



	}

	public function linkToUser(int $user_id, ?int $service_id = null)
	{
		$db = EntityManager::getInstance(self::class)->DB();

		return $db->preparedQuery('INSERT OR IGNORE INTO acc_transactions_users (id_transaction, id_user, id_service_user) VALUES (?, ?, ?);',







>
>
|
>
>
>







576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
	public function year()
	{
		return EntityManager::findOneById(Year::class, $this->id_year);
	}

	public function listFiles()
	{
		return Files::list($this->getAttachementsDirectory());
	}

	public function getAttachementsDirectory(): string
	{
		return File::CONTEXT_TRANSACTION . '/' . $this->id();
	}

	public function linkToUser(int $user_id, ?int $service_id = null)
	{
		$db = EntityManager::getInstance(self::class)->DB();

		return $db->preparedQuery('INSERT OR IGNORE INTO acc_transactions_users (id_transaction, id_user, id_service_user) VALUES (?, ?, ?);',

Modified src/include/lib/Garradin/Entities/Accounting/Year.php from [82f91d0f84] to [f33e68404f].

1
2
3
4
5
6
7
8
9
10


11
12
13
14
15
16
17
<?php

namespace Garradin\Entities\Accounting;

use KD2\DB\EntityManager;
use Garradin\DB;
use Garradin\Entity;
use Garradin\Fichiers;
use Garradin\UserException;
use Garradin\Accounting\Accounts;



class Year extends Entity
{
	const TABLE = 'acc_years';

	protected $id;
	protected $label;







<


>
>







1
2
3
4
5
6
7

8
9
10
11
12
13
14
15
16
17
18
<?php

namespace Garradin\Entities\Accounting;

use KD2\DB\EntityManager;
use Garradin\DB;
use Garradin\Entity;

use Garradin\UserException;
use Garradin\Accounting\Accounts;
use Garradin\Files\Files;
use Garradin\Entities\Files\File;

class Year extends Entity
{
	const TABLE = 'acc_years';

	protected $id;
	protected $label;
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
			throw new \LogicException('Cet exercice est déjà clôturé');
		}

		if ($target->closed) {
			throw new \LogicException('L\'exercice cible est déjà clôturé');
		}

		if ($target->id_chart != $this->id_chart) {
			throw new UserException('Il n\'est pas possible de déplacer les écritures dans un exercices dont le plan comptable est différent');
		}

		DB::getInstance()->preparedQuery('UPDATE acc_transactions SET id_year = ? WHERE id_year = ? AND date > ?;',
			$target->id(), $this->id(), $date->format('Y-m-d'));
	}

	public function delete(): bool
	{
		// Manual delete of transactions, as there is a voluntary safeguard in SQL: no cascade
		DB::getInstance()->preparedQuery('DELETE FROM acc_transactions WHERE id_year = ?;', $this->id());

		// Clean up files




		Fichiers::deleteUnlinkedFiles();



		return parent::delete();
	}

	public function countTransactions(): int
	{
		$db = DB::getInstance();







<
<
<
<






|
|

|
>
>
>
>
|
>
>







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
			throw new \LogicException('Cet exercice est déjà clôturé');
		}

		if ($target->closed) {
			throw new \LogicException('L\'exercice cible est déjà clôturé');
		}





		DB::getInstance()->preparedQuery('UPDATE acc_transactions SET id_year = ? WHERE id_year = ? AND date > ?;',
			$target->id(), $this->id(), $date->format('Y-m-d'));
	}

	public function delete(): bool
	{
		$db = DB::getInstance();
		$ids = $db->getAssoc('SELECT id, id FROM acc_transactions WHERE id_year = ?;', $this->id());


		// Delete all files
		foreach ($ids as $id) {
			Files::delete(File::CONTEXT_TRANSACTION . '/' . $id);
		}

		// Manual delete of transactions, as there is a voluntary safeguard in SQL: no cascade
		$db->preparedQuery('DELETE FROM acc_transactions WHERE id_year = ?;', $this->id());

		return parent::delete();
	}

	public function countTransactions(): int
	{
		$db = DB::getInstance();

Added src/include/lib/Garradin/Entities/Files/File.php version [6c19806068].























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
<?php

namespace Garradin\Entities\Files;

use KD2\Graphics\Image;
use KD2\DB\EntityManager as EM;

use Garradin\DB;
use Garradin\Entity;
use Garradin\Plugin;
use Garradin\UserException;
use Garradin\ValidationException;
use Garradin\Membres\Session;
use Garradin\Static_Cache;
use Garradin\Utils;
use Garradin\Entities\Web\Page;

use Garradin\Files\Files;

use const Garradin\{WWW_URL, ENABLE_XSENDFILE};

/**
 * This is a virtual entity, it cannot be saved to a SQL table
 */
class File extends Entity
{
	const TABLE = 'files';

	protected $id;

	/**
	 * Parent directory of file
	 */
	protected $parent;

	/**
	 * File name
	 */
	protected $name;

	protected $path;
	protected $type = self::TYPE_FILE;
	protected $mime;
	protected $size;
	protected $modified;
	protected $image;

	protected $_types = [
		'id'           => '?int',
		'path'         => 'string',
		'parent'       => '?string',
		'name'         => 'string',
		'type'         => 'int',
		'mime'         => '?string',
		'size'         => '?int',
		'modified'     => 'DateTime',
		'image'        => 'int',
	];

	const TYPE_FILE = 1;
	const TYPE_DIRECTORY = 2;
	const TYPE_LINK = 3;

	/**
	 * Tailles de miniatures autorisées, pour ne pas avoir 500 fichiers générés avec 500 tailles différentes
	 * @var array
	 */
	const ALLOWED_THUMB_SIZES = [200, 500];

	const THUMB_CACHE_ID = 'file.thumb.%s.%d';

	const THUMB_SIZE_TINY = 200;
	const THUMB_SIZE_SMALL = 500;

	const FILE_EXT_ENCRYPTED = '.skriv.enc';
	const FILE_EXT_SKRIV = '.skriv';

	const EDITOR_WEB = 'web';
	const EDITOR_ENCRYPTED = 'encrypted';
	const EDITOR_CODE = 'code';

	const CONTEXT_DOCUMENTS = 'documents';
	const CONTEXT_USER = 'user';
	const CONTEXT_TRANSACTION = 'transaction';
	const CONTEXT_CONFIG = 'config';
	const CONTEXT_WEB = 'web';
	const CONTEXT_SKELETON = 'skel';

	const CONTEXTS_NAMES = [
		self::CONTEXT_DOCUMENTS => 'Documents',
		self::CONTEXT_USER => 'Membre',
		self::CONTEXT_TRANSACTION => 'Écriture comptable',
		self::CONTEXT_CONFIG => 'Configuration',
		self::CONTEXT_WEB => 'Site web',
		self::CONTEXT_SKELETON => 'Squelettes',
	];

	const IMAGE_TYPES = [
		'image/png',
		'image/gif',
		'image/jpeg',
		'image/webp',
	];

	const PREVIEW_TYPES = [
		'application/pdf',
		'audio/mpeg',
		'audio/ogg',
		'audio/wave',
		'audio/wav',
		'audio/x-wav',
		'audio/x-pn-wav',
		'audio/webm',
		'video/webm',
		'video/ogg',
		'application/ogg',
		'video/mp4',
		'image/png',
		'image/gif',
		'image/jpeg',
		'image/webp',
		'image/svg+xml',
		'text/plain',
		'text/html',
	];

	static public function getColumns(): array
	{
		return array_keys((new self)->_types);
	}

	public function selfCheck(): void
	{
		$this->assert($this->type === self::TYPE_DIRECTORY || $this->type === self::TYPE_FILE, 'Unknown file type');
		$this->assert($this->type === self::TYPE_DIRECTORY || $this->size !== null, 'File size must be set');
		$this->assert($this->image === 0 || $this->image === 1, 'Unknown image value');
		$this->assert(trim($this->name) !== '', 'Le nom de fichier ne peut rester vide');
		$this->assert(strlen($this->path), 'Le chemin ne peut rester vide');
		$this->assert(strlen($this->parent) || null === $this->parent, 'Le chemin ne peut rester vide');
	}

	public function context(): string
	{
		return strtok($this->path, '/');
	}

	public function fullpath(): string
	{
		$path = Files::callStorage('getFullPath', $this);

		if (null === $path) {
			throw new \RuntimeException('File does not exist: ' . $this->path);
		}

		return $path;
	}

	public function canPreview(): bool
	{
		return in_array($this->mime, self::PREVIEW_TYPES);
	}

	public function delete(): bool
	{
		Files::callStorage('checkLock');

		// Delete actual file content
		Files::callStorage('delete', $this);

		Plugin::fireSignal('files.delete', ['file' => $this]);

		// clean up thumbnails
		foreach (self::ALLOWED_THUMB_SIZES as $size)
		{
			Static_Cache::remove(sprintf(self::THUMB_CACHE_ID, $this->pathHash(), $size));
		}

		if ($this->exists()) {
			return parent::delete();
		}

		return true;
	}

	public function move(string $target): bool
	{
		return $this->rename($target . '/' . $this->name);
	}

	public function rename(string $new_path): bool
	{
		self::validatePath($new_path);

		if ($new_path == $this->path || 0 === strpos($new_path, $this->path)) {
			throw new UserException('Impossible de renommer ou déplacer un fichier vers lui-même');
		}

		$return = Files::callStorage('move', $this, $new_path);

		Plugin::fireSignal('files.move', ['file' => $this, 'new_path' => $new_path]);

		return $return;
	}

	public function setContent(string $content): self
	{
		$this->set('modified', new \DateTime);
		$this->store(null, rtrim($content));
		$this->indexForSearch(null, $content);
		return $this;
	}

	public function store(?string $source_path, ?string $source_content, bool $index_search = true): self
	{
		if ($source_path && !$source_content)
		{
			$this->set('size', filesize($source_path));
		}
		else
		{
			$this->set('size', strlen($source_content));
		}

		Files::checkQuota($this->size);

		// Check that it's a real image
		if ($this->image) {
			try {
				if ($source_path && !$source_content) {
					$i = new Image($source_path);
				}
				else {
					$i = Image::createFromBlob($source_content);
				}

				// Recompress PNG files from base64, assuming they are coming
				// from JS canvas which doesn't know how to gzip (d'oh!)
				if ($i->format() == 'png' && null !== $source_content) {
					$source_content = $i->output('png', true);
					$this->set('size', strlen($source_content));
				}

				unset($i);
			}
			catch (\RuntimeException $e) {
				$this->set('image', 0);
			}
		}

		Files::callStorage('checkLock');

		// If a file of the same name already exists, define a new name
		if (Files::callStorage('exists', $this->path) && !$this->exists()) {
			$pos = strrpos($this->name, '.');
			$new_name = substr($this->name, 0, $pos) . '.' . substr(sha1(random_bytes(16)), 0, 10) . substr($this->name, $pos);
			$this->set('name', $new_name);
		}

		if (!$this->modified) {
			$this->set('modified', new \DateTime);
		}

		if (null !== $source_path) {
			$return = Files::callStorage('storePath', $this, $source_path);
		}
		else {
			$return = Files::callStorage('storeContent', $this, $source_content);
		}

		if (!$return) {
			throw new UserException('Le fichier n\'a pas pu être enregistré.');
		}

		Plugin::fireSignal('files.store', ['file' => $this]);

		if (!$index_search) {
			$this->indexForSearch($source_path, $source_content);
		}

		return $this;
	}

	public function indexForSearch(?string $source_path, ?string $source_content, ?string $title = null): void
	{
		// Store content in search table
		if (substr($this->mime, 0, 5) == 'text/') {
			$content = $source_content !== null ? $source_content : Files::callStorage('fetch', $this);

			if ($this->customType() == self::FILE_EXT_ENCRYPTED) {
				$content = null;
			}
			else if ($this->mime === 'text/html' || $this->mime == 'text/xml') {
				$content = strip_tags($content);
			}
		}
		else {
			$content = null;
		}

		// Only index valid UTF-8
		if (isset($content) && preg_match('//u', $content)) {
			// Truncate content at 150KB
			$content = substr(trim($content), 0, 150*1024);
		}
		else {
			$content = null;
		}

		$db = DB::getInstance();
		$db->preparedQuery('DELETE FROM files_search WHERE path = ?;', $this->path);
		$db->preparedQuery('INSERT INTO files_search (path, title, content) VALUES (?, ?, ?);', $this->path, $title ?? $this->name, $content);
	}

	static public function createAndStore(string $path, string $name, ?string $source_path, ?string $source_content): self
	{
		$file = self::create($path, $name, $source_path, $source_content);

		$file->store($source_path, $source_content);

		return $file;
	}

	static public function createDirectory(string $path, string $name, bool $create_parent = true): self
	{
		$name = self::filterName($name);

		$fullpath = trim($path . '/' . $name, '/');

		self::validatePath($fullpath);
		Files::checkQuota();

		if (Files::callStorage('exists', $fullpath)) {
			throw new ValidationException('Le nom de répertoire choisi existe déjà: ' . $fullpath);
		}

		if ($path !== '' && $create_parent) {
			self::ensureDirectoryExists($path);
		}

		$file = new self;
		$file->set('path', $fullpath);
		$file->set('name', $name);
		$file->set('parent', $path);
		$file->set('type', self::TYPE_DIRECTORY);
		$file->set('image', 0);
		$file->set('modified', new \DateTime);

		Files::callStorage('mkdir', $file);

		Plugin::fireSignal('files.mkdir', ['file' => $file]);

		return $file;
	}

	static public function ensureDirectoryExists(string $path): void
	{
		$db = DB::getInstance();
		$parts = explode('/', $path);
		$tree = '';

		foreach ($parts as $part) {
			$tree = trim($tree . '/' . $part, '/');
			$exists = $db->test(File::TABLE, 'type = ? AND path = ?', self::TYPE_DIRECTORY, $tree);

			if (!$exists) {
				try {
					self::createDirectory(Utils::dirname($tree), Utils::basename($tree), false);
				}
				catch (ValidationException $e) {
					// Ignore when directory already exists
				}
			}
		}
	}

	static public function create(string $path, string $name, ?string $source_path, ?string $source_content): self
	{
		if (!isset($source_path) && !isset($source_content)) {
			throw new \InvalidArgumentException('Either source path or source content should be set but not both');
		}

		self::ensureDirectoryExists($path);

		$finfo = \finfo_open(\FILEINFO_MIME_TYPE);
		$file = new self;
		$file->set('path', $path . '/' . $name);
		$file->set('parent', $path);
		$file->set('name', $name);

		if ($source_path && !$source_content) {
			$file->set('mime', finfo_file($finfo, $source_path));
			$file->set('size', filesize($source_path));
		}
		else {
			$file->set('mime', finfo_buffer($finfo, $source_content));
			$file->set('size', strlen($source_content));
		}

		$file->set('image', (int) in_array($file->mime, self::IMAGE_TYPES));

		// Force empty files as text/plain
		if ($file->mime == 'application/x-empty' && !$file->size) {
			$file->set('mime', 'text/plain');
		}

		return $file;
	}

	/**
	 * Create a file from an encoded base64 string
	 */
	static public function createFromBase64(string $path, string $name, string $encoded_content): self
	{
		$content = base64_decode($encoded_content);
		return self::createAndStore($path, $name, null, $content);
	}

	/**
	 * Modify a file from an encoded base64 string
	 */
	public function storeFromBase64(string $encoded_content): self
	{
		$content = base64_decode($encoded_content);
		return $this->store(null, $content);
	}

	/**
	 * Upload du fichier par POST
	 */
	static public function upload(string $path, string $key): self
	{
		if (!isset($_FILES[$key]) || !is_array($_FILES[$key])) {
			throw new UserException('Aucun fichier reçu');
		}

		$file = $_FILES[$key];

		if (!empty($file['error'])) {
			throw new UserException(self::getErrorMessage($file['error']));
		}

		if (empty($file['size']) || empty($file['name'])) {
			throw new UserException('Fichier reçu invalide : vide ou sans nom de fichier.');
		}

		if (!is_uploaded_file($file['tmp_name'])) {
			throw new \RuntimeException('Le fichier n\'a pas été envoyé de manière conventionnelle.');
		}

		$name = preg_replace('/\s+/', '_', $file['name']);
		$name = self::filterName($name);

		return self::createAndStore($path, $name, $file['tmp_name'], null);
	}


	/**
	 * Récupération du message d'erreur
	 * @param  integer $error Code erreur du $_FILE
	 * @return string Message d'erreur
	 */
	static public function getErrorMessage($error)
	{
		switch ($error)
		{
			case UPLOAD_ERR_INI_SIZE:
				return 'Le fichier excède la taille permise par la configuration.';
			case UPLOAD_ERR_FORM_SIZE:
				return 'Le fichier excède la taille permise par le formulaire.';
			case UPLOAD_ERR_PARTIAL:
				return 'L\'envoi du fichier a été interrompu.';
			case UPLOAD_ERR_NO_FILE:
				return 'Aucun fichier n\'a été reçu.';
			case UPLOAD_ERR_NO_TMP_DIR:
				return 'Pas de répertoire temporaire pour stocker le fichier.';
			case UPLOAD_ERR_CANT_WRITE:
				return 'Impossible d\'écrire le fichier sur le disque du serveur.';
			case UPLOAD_ERR_EXTENSION:
				return 'Une extension du serveur a interrompu l\'envoi du fichier.';
			default:
				return 'Erreur inconnue: ' . $error;
		}
	}

	public function url(bool $download = false): string
	{
		if ($this->context() == self::CONTEXT_WEB) {
			$path = Utils::basename(Utils::dirname($this->path)) . '/' . Utils::basename($this->path);
		}
		else {
			$path = $this->path;
		}


		$url = WWW_URL . $path;

		if ($download) {
			$url .= '?download';
		}

		return $url;
	}

	public function thumb_url(?int $size = null): string
	{
		$size = $size ? self::_findNearestThumbSize($size) : min(self::ALLOWED_THUMB_SIZES);
		return sprintf('%s?%dpx', $this->url(), $size);
	}

	/**
	 * Renvoie la taille de miniature la plus proche de la taille demandée
	 * @param  integer $size Taille demandée
	 * @return integer       Taille possible
	 */
	static protected function _findNearestThumbSize($size)
	{
		$size = (int) $size;

		if (in_array($size, self::ALLOWED_THUMB_SIZES))
		{
			return $size;
		}

		foreach (self::ALLOWED_THUMB_SIZES as $s)
		{
			if ($s >= $size)
			{
				return $s;
			}
		}

		return max(self::ALLOWED_THUMB_SIZES);
	}

	/**
	 * Envoie le fichier au client HTTP
	 */
	public function serve(?Session $session = null, bool $download = false): void
	{
		if (!$this->checkReadAccess($session)) {
			header('HTTP/1.1 403 Forbidden', true, 403);
			throw new UserException('Vous n\'avez pas accès à ce fichier.');
			return;
		}

		// Only simple files can be served, not directories
		if ($this->type != self::TYPE_FILE) {
			header('HTTP/1.1 404 Not Found', true, 404);
			throw new UserException('Page non trouvée');
		}

		$path = Files::callStorage('getFullPath', $this);
		$content = null === $path ? Files::callStorage('fetch', $this) : null;

		$this->_serve($path, $content, $download);
	}

	/**
	 * Envoie une miniature à la taille indiquée au client HTTP
	 */
	public function serveThumbnail(?Session $session = null, ?int $width = null): void
	{
		if (!$this->checkReadAccess($session)) {
			header('HTTP/1.1 403 Forbidden', true, 403);
			throw new UserException('Accès interdit');
			return;
		}

		if (!$this->image) {
			throw new UserException('Il n\'est pas possible de fournir une miniature pour un fichier qui n\'est pas une image.');
		}

		if (!$width) {
			$width = reset(self::ALLOWED_THUMB_SIZES);
		}

		if (!in_array($width, self::ALLOWED_THUMB_SIZES)) {
			throw new UserException('Cette taille de miniature n\'est pas autorisée.');
		}

		$cache_id = sprintf(self::THUMB_CACHE_ID, $this->pathHash(), $width);
		$destination = Static_Cache::getPath($cache_id);

		// La miniature n'existe pas dans le cache statique, on la crée
		if (!Static_Cache::exists($cache_id))
		{
			try {
				if ($path = Files::callStorage('getFullPath', $this)) {
					(new Image($path))->resize($width)->save($destination);
				}
				elseif ($content = Files::callStorage('fetch', $this)) {
					Image::createFromBlob($content)->resize($width)->save($destination);
				}
				else {
					throw new \RuntimeException('Unable to fetch file');
				}
			}
			catch (\RuntimeException $e) {
				throw new UserException('Impossible de créer la miniature');
			}
		}

		$this->_serve($destination, null);
	}

	/**
	 * Servir un fichier local en HTTP
	 * @param  string $path Chemin vers le fichier local
	 * @param  string $type Type MIME du fichier
	 * @param  string $name Nom du fichier avec extension
	 * @param  integer $size Taille du fichier en octets (facultatif)
	 */
	protected function _serve(?string $path, ?string $content, bool $download = false): void
	{
		if ($this->isPublic()) {
			Utils::HTTPCache(md5($this->path . $this->size . $this->modified->getTimestamp()), $this->modified->getTimestamp());
		}
		else {
			// Disable browser cache
			header('Pragma: private');
			header('Expires: -1');
			header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0');
		}

		$type = $this->mime;

		// Force CSS mimetype
		if (substr($this->name, -4) == '.css') {
			$type = 'text/css';
		}
		elseif (substr($this->name, -3) == '.js') {
			$type = 'text/javascript';
		}

		if (substr($type, 0, 5) == 'text/') {
			$type .= ';charset=utf-8';
		}

		header(sprintf('Content-Type: %s', $type));
		header(sprintf('Content-Disposition: %s; filename="%s"', $download ? 'attachment' : 'inline', $this->name));

		// Utilisation de XSendFile si disponible
		if (null !== $path && ENABLE_XSENDFILE && isset($_SERVER['SERVER_SOFTWARE']))
		{
			if (stristr($_SERVER['SERVER_SOFTWARE'], 'apache')
				&& function_exists('apache_get_modules')
				&& in_array('mod_xsendfile', apache_get_modules()))
			{
				header('X-Sendfile: ' . $path);
				return;
			}
			else if (stristr($_SERVER['SERVER_SOFTWARE'], 'lighttpd'))
			{
				header('X-Sendfile: ' . $path);
				return;
			}
		}

		// Désactiver gzip
		if (function_exists('apache_setenv'))
		{
			@apache_setenv('no-gzip', 1);
		}

		@ini_set('zlib.output_compression', 'Off');

		header(sprintf('Content-Length: %d', $path ? filesize($path) : strlen($content)));

		if (@ob_get_length()) {
			@ob_clean();
		}

		flush();

		if (null !== $path) {
			readfile($path);
		}
		else {
			echo $content;
		}
	}

	public function fetch()
	{
		return Files::callStorage('fetch', $this);
	}

	public function render(array $options = [])
	{
		$type = $this->customType();
		/*
		if (substr($this->name, -strlen(self::FILE_EXT_HTML)) == self::FILE_EXT_HTML) {
			return \Garradin\Web\Render\HTML::render($this, null, $options);
		}*/

		if ($type == self::FILE_EXT_SKRIV) {
			return \Garradin\Web\Render\Skriv::render($this, null, $options);
		}
		else if ($type == self::FILE_EXT_ENCRYPTED) {
			return \Garradin\Web\Render\EncryptedSkriv::render($this, null);
		}
		else if (substr($this->mime, 0, 5) == 'text/') {
			return sprintf('<pre>%s</pre>', htmlspecialchars($this->fetch()));
		}

		throw new \LogicException('Cannot render file of this type');
	}

	public function checkReadAccess(?Session $session): bool
	{
		// Web pages and config files are always public
		if ($this->isPublic()) {
			return true;
		}

		$context = $this->context();
		$ref = strtok(substr($this->path, strpos($this->path, '/')), '/');

		if (null === $session || !$session->isLogged()) {
			return false;
		}

		if ($context == self::CONTEXT_TRANSACTION && $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ)) {
			return true;
		}
		// The user can access his own profile files
		else if ($context == self::CONTEXT_USER && $ref == $session->getUser()->id) {
			return true;
		}
		// Only users able to manage users can see their profile files
		else if ($context == self::CONTEXT_USER && $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)) {
			return true;
		}
		// Only users with right to access documents can read documents
		else if ($context == self::CONTEXT_DOCUMENTS && $session->canAccess($session::SECTION_DOCUMENTS, $session::ACCESS_READ)) {
			return true;
		}

		return false;
	}

	public function checkWriteAccess(?Session $session): bool
	{
		if (null === $session) {
			return false;
		}

		switch ($this->context()) {
			case self::CONTEXT_WEB:
				return $session->canAccess($session::SECTION_WEB, $session::ACCESS_WRITE);
			case self::CONTEXT_DOCUMENTS:
				// Only admins can delete files
				return $session->canAccess($session::SECTION_DOCUMENTS, $session::ACCESS_WRITE);
			case self::CONTEXT_CONFIG:
				return $session->canAccess($session::SECTION_CONFIG, $session::ACCESS_ADMIN);
			case self::CONTEXT_TRANSACTION:
				return $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_WRITE);
			case self::CONTEXT_SKELETON:
				return $session->canAccess($session::SECTION_WEB, $session::ACCESS_ADMIN);
			case self::CONTEXT_USER:
				return $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE);
		}

		return false;
	}

	public function checkDeleteAccess(?Session $session): bool
	{
		if (null === $session) {
			return false;
		}

		switch ($this->context()) {
			case self::CONTEXT_WEB:
				return $session->canAccess($session::SECTION_WEB, $session::ACCESS_WRITE);
			case self::CONTEXT_DOCUMENTS:
				// Only admins can delete files
				return $session->canAccess($session::SECTION_DOCUMENTS, $session::ACCESS_ADMIN);
			case self::CONTEXT_CONFIG:
				return $session->canAccess($session::SECTION_CONFIG, $session::ACCESS_ADMIN);
			case self::CONTEXT_TRANSACTION:
				return $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);
			case self::CONTEXT_SKELETON:
				return $session->canAccess($session::SECTION_WEB, $session::ACCESS_ADMIN);
			case self::CONTEXT_USER:
				return $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE);
		}

		return false;
	}

	static public function checkCreateAccess(string $path, ?Session $session): bool
	{
		if (null === $session) {
			return false;
		}

		$context = strtok($path, '/');

		switch ($context) {
			case self::CONTEXT_WEB:
				return $session->canAccess($session::SECTION_WEB, $session::ACCESS_WRITE);
			case self::CONTEXT_DOCUMENTS:
				return $session->canAccess($session::SECTION_DOCUMENTS, $session::ACCESS_WRITE);
			case self::CONTEXT_CONFIG:
				return $session->canAccess($session::SECTION_CONFIG, $session::ACCESS_ADMIN);
			case self::CONTEXT_TRANSACTION:
				return $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_WRITE);
			case self::CONTEXT_SKELETON:
				return $session->canAccess($session::SECTION_WEB, $session::ACCESS_ADMIN);
			case self::CONTEXT_USER:
				return $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE);
		}

		return false;
	}

	public function pathHash(): string
	{
		return sha1($this->path);
	}

	public function isPublic(): bool
	{
		$context = $this->context();

		if ($context == self::CONTEXT_SKELETON || $context == self::CONTEXT_CONFIG || $context == self::CONTEXT_WEB) {
			return true;
		}

		return false;
	}

	public function getEditor(): ?string
	{
		if ($this->customType() == self::FILE_EXT_SKRIV) {
			return self::EDITOR_WEB;
		}
		elseif ($this->customType() == self::FILE_EXT_ENCRYPTED) {
			return self::EDITOR_ENCRYPTED;
		}
		elseif (substr($this->mime, 0, 5) == 'text/') {
			return self::EDITOR_CODE;
		}

		return null;
	}

	static public function filterName(string $name): string
	{
		return preg_replace('/[^\w\d\p{L}_. -]+/iu', '-', $name);
	}

	static public function validatePath(string $path): array
	{
		$path = explode('/', $path);

		if (count($path) < 1) {
			throw new ValidationException('Invalid file path');
		}

		if (!array_key_exists($path[0], self::CONTEXTS_NAMES)) {
			throw new ValidationException('Chemin invalide');
		}

		$context = array_shift($path);

		foreach ($path as $part) {
			if (substr($part, 0, 1) == '.') {
				throw new ValidationException('Chemin invalide');
			}
		}

		$name = array_pop($path);
		$ref = implode('/', $path);
		return [$context, $ref ?: null, $name];
	}

	public function customType(): ?string
	{
		static $extensions = [self::FILE_EXT_ENCRYPTED, self::FILE_EXT_SKRIV];

		foreach ($extensions as $ext) {
			if (substr($this->name, -strlen($ext)) == $ext) {
				return $ext;
			}
		}

		return null;
	}
}

Modified src/include/lib/Garradin/Entities/Services/Fee.php from [7ce45f39a7] to [0f3df37a82].

138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
		$columns = [
			'id_user' => [
				'select' => 'su.id_user',
			],
			'identity' => [
				'label' => 'Membre',
				'select' => 'm.' . $identity,
				'order' => sprintf('transliterate_to_ascii(m.%s) COLLATE NOCASE %%s', $identity),
			],
			'paid' => [
				'label' => 'Payé ?',
				'select' => 'su.paid',
			],
			'paid_amount' => [
				'label' => 'Montant payé',







<







138
139
140
141
142
143
144

145
146
147
148
149
150
151
		$columns = [
			'id_user' => [
				'select' => 'su.id_user',
			],
			'identity' => [
				'label' => 'Membre',
				'select' => 'm.' . $identity,

			],
			'paid' => [
				'label' => 'Payé ?',
				'select' => 'su.paid',
			],
			'paid_amount' => [
				'label' => 'Montant payé',
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
		$tables = 'services_users su
			INNER JOIN membres m ON m.id = su.id_user
			INNER JOIN services_fees sf ON sf.id = su.id_fee
			INNER JOIN (SELECT id, MAX(date) FROM services_users GROUP BY id_user, id_fee) AS su2 ON su2.id = su.id
			LEFT JOIN acc_transactions_users tu ON tu.id_service_user = su.id
			LEFT JOIN acc_transactions_lines l ON l.id_transaction = tu.id_transaction';
		$conditions = sprintf('su.id_fee = %d AND su.paid = 1 AND (su.expiry_date >= date() OR su.expiry_date IS NULL)
			AND m.id_categorie NOT IN (SELECT id FROM membres_categories WHERE cacher = 1)', $this->id());

		$list = new DynamicList($columns, $tables, $conditions);
		$list->groupBy('su.id_user');
		$list->orderBy('date', true);
		$list->setCount('COUNT(DISTINCT su.id_user)');
		return $list;
	}

	public function unpaidUsersList(): DynamicList
	{
		$list = $this->paidUsersList();
		$conditions = sprintf('su.id_fee = %d AND su.paid = 0 AND m.id_categorie NOT IN (SELECT id FROM membres_categories WHERE cacher = 1)', $this->id());
		$list->setConditions($conditions);
		return $list;
	}

	public function expiredUsersList(): DynamicList
	{
		$list = $this->paidUsersList();
		$conditions = sprintf('su.id_fee = %d AND su.expiry_date < date() AND m.id_categorie NOT IN (SELECT id FROM membres_categories WHERE cacher = 1)', $this->id());
		$list->setConditions($conditions);
		return $list;
	}
}







|











|







|




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
		$tables = 'services_users su
			INNER JOIN membres m ON m.id = su.id_user
			INNER JOIN services_fees sf ON sf.id = su.id_fee
			INNER JOIN (SELECT id, MAX(date) FROM services_users GROUP BY id_user, id_fee) AS su2 ON su2.id = su.id
			LEFT JOIN acc_transactions_users tu ON tu.id_service_user = su.id
			LEFT JOIN acc_transactions_lines l ON l.id_transaction = tu.id_transaction';
		$conditions = sprintf('su.id_fee = %d AND su.paid = 1 AND (su.expiry_date >= date() OR su.expiry_date IS NULL)
			AND m.id_category NOT IN (SELECT id FROM users_categories WHERE hidden = 1)', $this->id());

		$list = new DynamicList($columns, $tables, $conditions);
		$list->groupBy('su.id_user');
		$list->orderBy('date', true);
		$list->setCount('COUNT(DISTINCT su.id_user)');
		return $list;
	}

	public function unpaidUsersList(): DynamicList
	{
		$list = $this->paidUsersList();
		$conditions = sprintf('su.id_fee = %d AND su.paid = 0 AND m.id_category NOT IN (SELECT id FROM users_categories WHERE hidden = 1)', $this->id());
		$list->setConditions($conditions);
		return $list;
	}

	public function expiredUsersList(): DynamicList
	{
		$list = $this->paidUsersList();
		$conditions = sprintf('su.id_fee = %d AND su.expiry_date < date() AND m.id_category NOT IN (SELECT id FROM users_categories WHERE hidden = 1)', $this->id());
		$list->setConditions($conditions);
		return $list;
	}
}

Modified src/include/lib/Garradin/Entities/Services/Reminder.php from [391cf74d50] to [4702329012].

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
		$columns = [
			'id_user' => [
				'select' => 'srs.id_user',
			],
			'identity' => [
				'label' => 'Membre',
				'select' => 'm.' . $identity,
				'order' => sprintf('transliterate_to_ascii(m.%s) COLLATE NOCASE %%s', $identity),
			],
			'email' => [
				'label' => 'Adresse e-mail',
				'select' => 'm.email',
			],
			'date' => [
				'label' => 'Date',







<







70
71
72
73
74
75
76

77
78
79
80
81
82
83
		$columns = [
			'id_user' => [
				'select' => 'srs.id_user',
			],
			'identity' => [
				'label' => 'Membre',
				'select' => 'm.' . $identity,

			],
			'email' => [
				'label' => 'Adresse e-mail',
				'select' => 'm.email',
			],
			'date' => [
				'label' => 'Date',

Modified src/include/lib/Garradin/Entities/Services/Service.php from [04841ea319] to [1865b4e6a7].

75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
			'id_user' => [
			],
			'end_date' => [
			],
			'identity' => [
				'label' => 'Membre',
				'select' => 'm.' . $identity,
				'order' => sprintf('transliterate_to_ascii(m.%s) COLLATE NOCASE %%s', $identity),
			],
			'status' => [
				'label' => 'Statut',
				'select' => 'CASE WHEN su.expiry_date < date() THEN -1 WHEN su.expiry_date >= date() THEN 1 ELSE 0 END',
			],
			'paid' => [
				'label' => 'Payé ?',







<







75
76
77
78
79
80
81

82
83
84
85
86
87
88
			'id_user' => [
			],
			'end_date' => [
			],
			'identity' => [
				'label' => 'Membre',
				'select' => 'm.' . $identity,

			],
			'status' => [
				'label' => 'Statut',
				'select' => 'CASE WHEN su.expiry_date < date() THEN -1 WHEN su.expiry_date >= date() THEN 1 ELSE 0 END',
			],
			'paid' => [
				'label' => 'Payé ?',
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

		$tables = 'services_users su
			INNER JOIN membres m ON m.id = su.id_user
			INNER JOIN services s ON s.id = su.id_service
			INNER JOIN services_fees sf ON sf.id = su.id_fee
			INNER JOIN (SELECT id, MAX(date) FROM services_users GROUP BY id_user, id_service) AS su2 ON su2.id = su.id';
		$conditions = sprintf('su.id_service = %d AND su.paid = 1 AND (su.expiry_date >= date() OR su.expiry_date IS NULL)
			AND m.id_categorie NOT IN (SELECT id FROM membres_categories WHERE cacher = 1)', $this->id());

		$list = new DynamicList($columns, $tables, $conditions);
		$list->groupBy('su.id_user');
		$list->orderBy('date', true);
		$list->setCount('COUNT(DISTINCT su.id_user)');
		return $list;
	}

	public function unpaidUsersList(): DynamicList
	{
		$list = $this->paidUsersList();
		$conditions = sprintf('su.id_service = %d AND su.paid = 0 AND m.id_categorie NOT IN (SELECT id FROM membres_categories WHERE cacher = 1)', $this->id());
		$list->setConditions($conditions);
		return $list;
	}

	public function expiredUsersList(): DynamicList
	{
		$list = $this->paidUsersList();
		$conditions = sprintf('su.id_service = %d AND su.expiry_date < date() AND m.id_categorie NOT IN (SELECT id FROM membres_categories WHERE cacher = 1)', $this->id());
		$list->setConditions($conditions);
		return $list;
	}
}







|











|







|




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

		$tables = 'services_users su
			INNER JOIN membres m ON m.id = su.id_user
			INNER JOIN services s ON s.id = su.id_service
			INNER JOIN services_fees sf ON sf.id = su.id_fee
			INNER JOIN (SELECT id, MAX(date) FROM services_users GROUP BY id_user, id_service) AS su2 ON su2.id = su.id';
		$conditions = sprintf('su.id_service = %d AND su.paid = 1 AND (su.expiry_date >= date() OR su.expiry_date IS NULL)
			AND m.id_category NOT IN (SELECT id FROM users_categories WHERE hidden = 1)', $this->id());

		$list = new DynamicList($columns, $tables, $conditions);
		$list->groupBy('su.id_user');
		$list->orderBy('date', true);
		$list->setCount('COUNT(DISTINCT su.id_user)');
		return $list;
	}

	public function unpaidUsersList(): DynamicList
	{
		$list = $this->paidUsersList();
		$conditions = sprintf('su.id_service = %d AND su.paid = 0 AND m.id_category NOT IN (SELECT id FROM users_categories WHERE hidden = 1)', $this->id());
		$list->setConditions($conditions);
		return $list;
	}

	public function expiredUsersList(): DynamicList
	{
		$list = $this->paidUsersList();
		$conditions = sprintf('su.id_service = %d AND su.expiry_date < date() AND m.id_category NOT IN (SELECT id FROM users_categories WHERE hidden = 1)', $this->id());
		$list->setConditions($conditions);
		return $list;
	}
}

Added src/include/lib/Garradin/Entities/Users/Category.php version [2e075cd1f0].



















































































































































































































































































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

namespace Garradin\Entities\Users;

use Garradin\Membres\Session;
use Garradin\Config;
use Garradin\DB;
use Garradin\UserException;
use Garradin\Entity;

class Category extends Entity
{
	const TABLE = 'users_categories';

	protected $id;
	protected $name;

	protected $hidden = 0;

	protected $perm_web = 0;
	protected $perm_documents = 0;
	protected $perm_users = 0;
	protected $perm_accounting = 0;

	protected $perm_subscribe = 0;
	protected $perm_connect = 0;
	protected $perm_config = 0;

	protected $_types = [
		'id'              => 'int',
		'name'            => 'string',
		'hidden'          => 'int',
		'perm_web'        => 'int',
		'perm_documents'  => 'int',
		'perm_users'      => 'int',
		'perm_accounting' => 'int',
		'perm_subscribe'  => 'int',
		'perm_connect'    => 'int',
		'perm_config'     => 'int',
	];

	const PERMISSIONS = [
		'connect' => [
			'label' => 'Les membres de cette catégorie peuvent-ils se connecter ?',
			'shape' => 'C',
			'options' => [
				Session::ACCESS_NONE => 'N\'a pas le droit de se connecter',
				Session::ACCESS_READ => 'A le droit de se connecter',
			],
		],
		'users' => [
			'label' => 'Gestion des membres',
			'shape' => 'M',
			'options' => [
				Session::ACCESS_NONE => 'Pas d\'accès',
				Session::ACCESS_READ => 'Lecture uniquement (peut voir les informations personnelles de tous les membres, y compris leurs inscriptions à des activités)',
				Session::ACCESS_WRITE => 'Lecture & écriture (peut ajouter et modifier des membres, mais pas les supprimer ni les changer de catégorie, peut inscrire des membres à des activités)',
				Session::ACCESS_ADMIN => 'Administration (peut tout faire)',
			],
		],
		'accounting' => [
			'label' => 'Comptabilité',
			'shape' => '€',
			'options' => [
				Session::ACCESS_NONE => 'Pas d\'accès',
				Session::ACCESS_READ => 'Lecture uniquement (peut lire toutes les informations de tous les exercices)',
				Session::ACCESS_WRITE => 'Lecture & écriture (peut ajouter des écritures, mais pas les modifier ni les supprimer)',
				Session::ACCESS_ADMIN => 'Administration (peut modifier et supprimer des écritures, gérer les comptes, les exercices, etc.)',
			],
		],
		'documents' => [
			'label' => 'Documents',
			'shape' => 'D',
			'options' => [
				Session::ACCESS_NONE => 'Pas d\'accès',
				Session::ACCESS_READ => 'Lecture uniquement (peut lire tous les fichiers)',
				Session::ACCESS_WRITE => 'Lecture & écriture (peut lire, ajouter, modifier et déplacer des fichiers, mais pas les supprimer)',
				Session::ACCESS_ADMIN => 'Administration (peut tout faire)',
			],
		],
		'web' => [
			'label' => 'Gestion du site web',
			'shape' => 'W',
			'options' => [
				Session::ACCESS_NONE => 'Pas d\'accès',
				Session::ACCESS_READ => 'Lecture uniquement (peut lire les pages)',
				Session::ACCESS_WRITE => 'Lecture & écriture (peut ajouter, modifier et supprimer des pages et catégories, mais pas modifier la configuration)',
				Session::ACCESS_ADMIN => 'Administration (peut tout faire)',
			],
		],
		'config' => [
			'label' => 'Les membres de cette catégorie peuvent-ils modifier la configuration ?',
			'shape' => '☑',
			'options' => [
				Session::ACCESS_NONE => 'Ne peut pas modifier la configuration',
				Session::ACCESS_ADMIN => 'Peut modifier la configuration',
			],
		],
	];

	public function selfCheck(): void
	{
		parent::selfCheck();

		$this->assert(trim($this->name) !== '', 'Le nom de catégorie ne peut rester vide.');
		$this->assert($this->hidden === 0 || $this->hidden === 1, 'Wrong value for hidden');

		foreach (self::PERMISSIONS as $key => $perm) {
			$this->assert(array_key_exists($this->{'perm_' . $key}, $perm['options']), 'Invalid value for perm_' . $key);
		}
	}

	public function delete(): bool
	{
		$db = DB::getInstance();
		$config = Config::getInstance();

		if ($this->id() == $config->get('categorie_membres')) {
			throw new UserException('Il est interdit de supprimer la catégorie définie par défaut dans la configuration.');
		}

		if ($db->test('membres', 'id_category = ?', $this->id())) {
			throw new UserException('La catégorie contient encore des membres, il n\'est pas possible de la supprimer.');
		}

		return parent::delete();
	}

	public function setAllPermissions(int $access): void
	{
		foreach (self::PERMISSIONS as $key => $perm) {
			// Restrict to the maximum access level, as some permissions only allow up to READ
			$perm_access = min($access, max(array_keys($perm['options'])));
			$this->set('perm_' . $key, $perm_access);
		}
	}
}

Added src/include/lib/Garradin/Entities/Web/Page.php version [e9e7fc4699].













































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
<?php

namespace Garradin\Entities\Web;

use Garradin\DB;
use Garradin\Entity;
use Garradin\UserException;
use Garradin\Utils;
use Garradin\Entities\Files\File;
use Garradin\Files\Files;
use Garradin\Web\Render\Skriv;

use KD2\DB\EntityManager as EM;

use const Garradin\WWW_URL;

class Page extends Entity
{
	const TABLE = 'web_pages';

	protected $id;
	protected $parent;
	protected $path;
	protected $uri;
	protected $_name = 'index.txt';
	protected $file_path;
	protected $title;
	protected $type;
	protected $status;
	protected $format;
	protected $published;
	protected $modified;
	protected $content;

	protected $_types = [
		'id'        => 'int',
		'parent'    => 'string',
		'path'      => 'string',
		'uri'       => 'string',
		'file_path' => 'string',
		'title'     => 'string',
		'type'      => 'int',
		'status'    => 'string',
		'format'    => 'string',
		'published' => 'DateTime',
		'modified'  => 'DateTime',
		'content'   => 'string',
	];

	const FORMAT_SKRIV = 'skriv';
	const FORMAT_ENCRYPTED = 'skriv/encrypted';

	const FORMATS_LIST = [
		self::FORMAT_SKRIV => 'SkrivML',
		self::FORMAT_ENCRYPTED => 'Chiffré',
	];

	const STATUS_ONLINE = 'online';
	const STATUS_DRAFT = 'draft';

	const STATUS_LIST = [
		self::STATUS_ONLINE => 'En ligne',
		self::STATUS_DRAFT => 'Brouillon',
	];

	const TYPE_CATEGORY = 1;
	const TYPE_PAGE = 2;

	const TEMPLATES = [
		self::TYPE_PAGE => 'article.html',
		self::TYPE_CATEGORY => 'category.html',
	];

	protected $_file;
	protected $_attachments;

	static public function create(int $type, ?string $parent, string $title, string $status = self::STATUS_ONLINE): self
	{
		$page = new self;
		$data = compact('type', 'parent', 'title', 'status');
		$data['content'] = '';

		$page->importForm($data);
		$page->published = new \DateTime;
		$page->modified = new \DateTime;
		$page->file_path = $page->filepath();
		$page->type = $type;

		$db = DB::getInstance();
		if ($db->test(self::TABLE, 'uri = ?', $page->uri)) {
			$page->importForm(['uri' => $page->uri . date('-Y-m-d-His')]);
		}

		return $page;
	}

	public function file(bool $force_reload = false)
	{
		if (null === $this->_file || $force_reload) {
			$this->_file = Files::get($this->filepath());
		}

		return $this->_file;
	}

	public function load(array $data): void
	{
		parent::load($data);

		if ($this->file() && $this->file()->modified != $this->modified) {
			$this->loadFromFile($this->file());
			$this->save();
		}
	}

	public function url(): string
	{
		return WWW_URL . $this->uri;
	}

	public function template(): string
	{
		return self::TEMPLATES[$this->type];
	}

	public function asTemplateArray(): array
	{
		$out = $this->asArray();
		$out['url'] = $this->url();
		$out['html'] = $this->render();
		return $out;
	}

	public function render(array $options = []): string
	{
		if (!$this->file()) {
			throw new \LogicException('File does not exist: '  . $this->file_path);
		}
		if ($this->format == self::FORMAT_SKRIV) {
			return \Garradin\Web\Render\Skriv::render($this->file(), $this->content, $options);
		}
		else if ($this->format == self::FORMAT_ENCRYPTED) {
			return \Garradin\Web\Render\EncryptedSkriv::render($this->file(), $this->content);
		}

		throw new \LogicException('Invalid format: ' . $this->format);
	}

	public function preview(string $content): string
	{
		return Skriv::render($this->file(), $content, ['prefix' => '#']);
	}

	public function filepath(bool $stored = true): string
	{
		return $stored && isset($this->file_path) ? $this->file_path : File::CONTEXT_WEB . '/' . $this->path . '/' . $this->_name;
	}

	public function path(): string
	{
		return $this->path;
	}

	public function syncFile(): void
	{
		$export = $this->export();
		$path = $this->filepath();
		$target = $this->filepath(false);

		// Move parent directory if needed
		if ($path !== $target) {
			$dir = Files::get(Utils::dirname($path));
			$dir->rename(Utils::dirname($target));
			$this->set('file_path', $target);
			$this->_file = null;
		}

		if (!$this->file()) {
			$file = $this->_file = File::createAndStore(Utils::dirname($target), Utils::basename($target), null, $export);
			$this->set('modified', new \DateTime);
		}
		elseif ($this->file()->fetch() !== $export) {
			$this->file()->store(null, $this->export());
			$this->set('modified', $this->file()->modified);
		}

		$this->syncSearch();
	}

	public function syncSearch(): void
	{
		$content = $this->format == self::FORMAT_ENCRYPTED ? null : strip_tags($this->render());
		$this->file()->indexForSearch(null, $content, $this->title);
	}

	public function save(): bool
	{
		$this->syncFile();
		parent::save();

		return true;
	}

	public function delete(): bool
	{
		Files::get(Utils::dirname($this->file_path))->delete();
		return parent::delete();
	}

	public function selfCheck(): void
	{
		$db = DB::getInstance();
		$this->assert($this->type === self::TYPE_CATEGORY || $this->type === self::TYPE_PAGE, 'Unknown page type');
		$this->assert(array_key_exists($this->status, self::STATUS_LIST), 'Unknown page status');
		$this->assert(array_key_exists($this->format, self::FORMATS_LIST), 'Unknown page format');
		$this->assert(trim($this->title) !== '', 'Le titre ne peut rester vide');
		$this->assert(trim($this->file_path) !== '', 'Le chemin de fichier ne peut rester vide');
		$this->assert(trim($this->path) !== '', 'Le chemin ne peut rester vide');
		$this->assert(trim($this->uri) !== '', 'L\'URI ne peut rester vide');
		$this->assert($this->path !== $this->parent, 'Invalid parent page');
		$this->assert($this->parent === '' || $db->test(self::TABLE, 'path = ?', $this->parent), 'Page parent inexistante');

		$this->assert(!$this->exists() || !$db->test(self::TABLE, 'path = ? AND id != ?', $this->path, $this->id()), 'Cette adresse URI est déjà utilisée par une autre page, merci d\'en choisir une autre : ' . $this->uri);
		$this->assert($this->exists() || !$db->test(self::TABLE, 'path = ?', $this->path), 'Cette adresse URI est déjà utilisée par une autre page, merci d\'en choisir une autre : ' . $this->path);
	}

	public function importForm(array $source = null)
	{
		if (null === $source) {
			$source = $_POST;
		}

		if (isset($source['date']) && isset($source['date_time'])) {
			$source['published'] = $source['date'] . ' ' . $source['date_time'];
		}

		$parent = $this->parent;

		if (isset($source['title']) && is_null($this->path)) {
			$source['uri'] = $source['title'];
		}

		if (isset($source['uri'])) {
			$source['uri'] = Utils::transformTitleToURI($source['uri']);
			$source['path'] = trim($parent . '/' . $source['uri'], '/');
		}

		$uri = $source['uri'] ?? $this->uri;

		if (array_key_exists('parent', $source)) {
			if (is_array($source['parent'])) {
				$source['parent'] = key($source['parent']);
			}

			if (empty($source['parent'])) {
				$source['parent'] = '';
			}

			$parent = $source['parent'];
			$source['path'] = trim($parent . '/' . $uri, '/');
		}

		if (!empty($source['encryption']) ) {
			$this->set('format', self::FORMAT_ENCRYPTED);
		}
		else {
			$this->set('format', self::FORMAT_SKRIV);
		}

		return parent::importForm($source);
	}

	public function getBreadcrumbs(): array
	{
		$sql = '
			WITH RECURSIVE parents(title, parent, path, level) AS (
				SELECT title, parent, path, 1 FROM web_pages WHERE id = ?
				UNION ALL
				SELECT p.title, p.parent, p.path, level + 1
				FROM web_pages p
					JOIN parents ON parents.parent = p.path
			)
			SELECT path, title FROM parents ORDER BY level DESC;';
		return DB::getInstance()->getAssoc($sql, $this->id());
	}

	public function listAttachments(): array
	{
		if (null === $this->_attachments) {
			$list = Files::list(Utils::dirname($this->filepath()));

			// Remove the page itself
			$list = array_filter($list, function ($a) {
				return $a->name != $this->_name && $a->type != $a::TYPE_DIRECTORY;
			});

			$this->_attachments = $list;
		}

		return $this->_attachments;
	}

	static public function findTaggedAttachments(string $text): array
	{
		preg_match_all('/<<?(?:file|image)\s*(?:\|\s*)?([\w\d_.-]+)/ui', $text, $match, PREG_PATTERN_ORDER);
		preg_match_all('/#(?:file|image):\[([\w\d_.-]+)\]/ui', $text, $match2, PREG_PATTERN_ORDER);

		return array_merge($match[1], $match2[1]);
	}

	/**
	 * Return list of images
	 * If $all is FALSE then this will only return images that are not present in the content
	 */
	public function getImageGallery(bool $all = true): array
	{
		return $this->getAttachmentsGallery($all, true);
	}

	/**
	 * Return list of files
	 * If $all is FALSE then this will only return files that are not present in the content
	 */
	public function getAttachmentsGallery(bool $all = true, bool $images = false): array
	{
		$out = [];
		$tagged = [];

		if (!$all) {
			$tagged = $this->findTaggedAttachments($this->content);
		}

		foreach ($this->listAttachments() as $a) {
			if ($images && !$a->image) {
				continue;
			}
			elseif (!$images && $a->image) {
				continue;
			}

			// Skip
			if (!$all && in_array($a->name, $tagged)) {
				continue;
			}

			$out[] = $a;
		}

		return $out;
	}

	public function export(): string
	{
		$meta = [
			'Title' => str_replace("\n", '', trim($this->title)),
			'Status' => $this->status,
			'Published' => $this->published->format('Y-m-d H:i:s'),
			'Format' => $this->format,
		];

		$out = '';

		foreach ($meta as $key => $value) {
			$out .= sprintf("%s: %s\n", $key, $value);
		}

		$out .= "\n----\n\n" . $this->content;

		return $out;
	}

	public function importFromRaw(string $str): bool
	{
		$str = preg_replace("/\r\n|\r|\n/", "\n", $str);
		$str = explode("\n\n----\n\n", $str, 2);

		if (count($str) !== 2) {
			return false;
		}

		list($meta, $content) = $str;

		$meta = explode("\n", trim($meta));

		foreach ($meta as $line) {
			$key = strtolower(trim(strtok($line, ':')));
			$value = trim(strtok(''));

			if ($key == 'title') {
				$this->set('title', $value);
			}
			elseif ($key == 'published') {
				$this->set('published', new \DateTime($value));
			}
			elseif ($key == 'format') {
				$value = strtolower($value);

				if (!array_key_exists($value, self::FORMATS_LIST)) {
					throw new \LogicException('Unknown format: ' . $value);
				}

				$this->set('format', $value);
			}
			elseif ($key == 'status') {
				$value = strtolower($value);

				if (!array_key_exists($value, self::STATUS_LIST)) {
					throw new \LogicException('Unknown status: ' . $value);
				}

				$this->set('status', $value);
			}
			else {
				// Ignore other metadata
			}
		}

		$this->set('content', trim($content, "\n\r"));

		return true;
	}

	public function loadFromFile(File $file): void
	{
		if (!$this->importFromRaw($file->fetch())) {
			throw new \LogicException('Invalid page content: ' . $file->parent);
		}

		$this->set('modified', $file->modified);

		foreach (Files::list($file->parent) as $subfile) {
			if ($subfile->type == File::TYPE_DIRECTORY) {
				$this->set('type', self::TYPE_CATEGORY);
				return;
			}
		}

		$this->set('type', self::TYPE_PAGE); // Default
	}

	static public function fromFile(File $file): self
	{
		$page = new self;

		// Path is relative to web root
		$page->set('file_path', $file->path);
		$page->set('path', substr(Utils::dirname($file->path), strlen(File::CONTEXT_WEB . '/')));
		$page->set('uri', Utils::basename($page->path));
		$page->set('parent', Utils::dirname($page->path) == '.' ? '' : Utils::dirname($page->path));

		$page->loadFromFile($file);
		return $page;
	}
}

Modified src/include/lib/Garradin/Entity.php from [4ef751c359] to [e19cdc4d7b].

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

































			elseif (preg_match('!^\d{2}/\d{2}/\d{4}$!', $value)) {
				return \DateTime::createFromFormat('d/m/Y', $value);
			}
			elseif (null !== $value) {
				throw new ValidationException('Format de date invalide (merci d\'utiliser le format JJ/MM/AAAA) : ' . $value);
			}
		}
		else {

			return parent::filterUserValue($type, $value, $key);
		}



	}

	protected function assert(?bool $test, string $message = null): void
	{
		if ($test) {
			return;
		}

		if (null === $message) {
			$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
			$caller_class = array_pop($backtrace);
			$caller = array_pop($backtrace);
			$message = sprintf('Entity assertion fail from class %s on line %d', $caller_class['class'], $caller['line']);
			throw new \UnexpectedValueException($message);
		}
		else {
			throw new ValidationException($message);
		}
	}
}








































|
>
|
|
>
>
>



















|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
			elseif (preg_match('!^\d{2}/\d{2}/\d{4}$!', $value)) {
				return \DateTime::createFromFormat('d/m/Y', $value);
			}
			elseif (null !== $value) {
				throw new ValidationException('Format de date invalide (merci d\'utiliser le format JJ/MM/AAAA) : ' . $value);
			}
		}
		elseif ($type == 'DateTime') {
			if (preg_match('!^\d{2}/\d{2}/\d{4}\s\d{2}:\d{2}$!', $value)) {
				return \DateTime::createFromFormat('d/m/Y H:i', $value);
			}
		}

		return parent::filterUserValue($type, $value, $key);
	}

	protected function assert(?bool $test, string $message = null): void
	{
		if ($test) {
			return;
		}

		if (null === $message) {
			$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
			$caller_class = array_pop($backtrace);
			$caller = array_pop($backtrace);
			$message = sprintf('Entity assertion fail from class %s on line %d', $caller_class['class'], $caller['line']);
			throw new \UnexpectedValueException($message);
		}
		else {
			throw new ValidationException($message);
		}
	}

	// Add plugin signals to save/delete
	public function save(): bool
	{
		$name = get_class($this);
		$name = str_replace('Garradin\Entities', '', $name);
		$name = 'entity.' . $name . '.save';

		if (Plugin::fireSignal($name . '.before', ['entity' => $this])) {
			return true;
		}

		$return = parent::save();
		Plugin::fireSignal($name . '.after', ['entity' => $this, 'success' => $return]);

		return $return;
	}

	public function delete(): bool
	{
		$name = get_class($this);
		$name = str_replace('Garradin\Entities', '', $name);
		$name = 'entity.' . $name . '.delete';

		if (Plugin::fireSignal($name . '.before', ['entity' => $this])) {
			return true;
		}

		$return = parent::delete();
		Plugin::fireSignal($name . '.after', ['entity' => $this, 'success' => $return]);

		return $return;
	}
}

Deleted src/include/lib/Garradin/Fichiers.php version [76103311d2].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
<?php

namespace Garradin;

use KD2\Graphics\Image;
use Garradin\Membres\Session;

class Fichiers
{
	public $id;
	public $nom;
	public $type;
	public $image;
	public $datetime;
	public $hash;
	public $taille;
	public $id_contenu;

	/**
	 * Tailles de miniatures autorisées, pour ne pas avoir 500 fichiers générés avec 500 tailles différentes
	 * @var array
	 */
	protected static $allowed_thumb_sizes = [200, 500];

	const LIEN_COMPTA = 'acc_transactions';
	const LIEN_WIKI = 'wiki_pages';
	const LIEN_MEMBRES = 'membres';

	/**
	 * Renvoie l'URL vers un fichier
	 * @param  integer $id   Numéro du fichier
	 * @param  string  $nom  Nom de fichier avec extension
	 * @param  integer $size Taille de la miniature désirée (pour les images)
	 * @return string        URL du fichier
	 */
	static public function _getURL(int $id, string $nom, string $hash, $size = false): string
	{
		$url = sprintf('%sf/%s/%s?', WWW_URL, base_convert((int)$id, 10, 36), $nom);

		if ($size)
		{
			$url .= self::_findThumbSize($size) . 'px&';
		}

		$url .= substr($hash, 0, 10);

		return $url;
	}

	/**
	 * Renvoie la taille de miniature la plus proche de la taille demandée
	 * @param  integer $size Taille demandée
	 * @return integer       Taille possible
	 */
	static protected function _findThumbSize($size)
	{
		$size = (int) $size;

		if (in_array($size, self::$allowed_thumb_sizes))
		{
			return $size;
		}

		foreach (self::$allowed_thumb_sizes as $s)
		{
			if ($s >= $size)
			{
				return $s;
			}
		}

		return max(self::$allowed_thumb_sizes);
	}

	/**
	 * Constructeur de l'objet pour un fichier
	 * @param integer $id Numéro unique du fichier
	 * @param $data array|object File data to populate object
	 */
	public function __construct(int $id, $data = null)
	{
		if (is_null($data))
		{
			$data = DB::getInstance()->first('SELECT fichiers.*, fc.hash, fc.taille,
				strftime(\'%s\', datetime) AS datetime
				FROM fichiers INNER JOIN fichiers_contenu AS fc ON fc.id = fichiers.id_contenu
				WHERE fichiers.id = ?;', (int)$id);
		}

		if (!$data)
		{
			throw new \InvalidArgumentException('Ce fichier n\'existe pas.');
		}

		foreach ((array)$data as $key => $value)
		{
			$this->$key = $value;
		}
	}

	/**
	 * Renvoie l'adresse d'accès au fichier
	 * @param  boolean $size Taille éventuelle de la miniature demandée
	 * @return string        URL d'accès au fichier
	 */
	public function getURL($size = false)
	{
		return self::_getURL($this->id, $this->nom, $this->hash, $size);
	}

	/**
	 * Lier un fichier à un contenu
	 * @param  string $type       Type de contenu (constantes LIEN_*)
	 * @param  integer $foreign_id ID du contenu lié
	 * @return boolean TRUE en cas de succès
	 */
	public function linkTo($type, $foreign_id)
	{
		$db = DB::getInstance();
		$check = [self::LIEN_MEMBRES, self::LIEN_WIKI, self::LIEN_COMPTA];

		if (!in_array($type, $check))
		{
			throw new \LogicException('Type de lien de fichier inconnu.');
		}

		// Vérifier que le fichier n'est pas déjà lié à un autre type
		$query = [];

		foreach ($check as $check_type)
		{
			// Ne pas chercher dans le type qu'on veut lier
			if ($check_type == $type)
			{
				continue;
			}

			$query[] = sprintf('SELECT 1 FROM fichiers_%s WHERE fichier = %d', $check_type, $this->id);
		}

		$query = implode(' UNION ', $query) . ';';

		if ($db->firstColumn($query))
		{
			throw new \LogicException('Ce fichier est déjà lié à un autre contenu : ' . $check_type);
		}

		return $db->preparedQuery('INSERT OR IGNORE INTO fichiers_' . $type . ' (fichier, id) VALUES (?, ?);',
			[(int)$this->id, (int)$foreign_id]);
	}

	public function getLinkedId(string $type)
	{
		$check = [self::LIEN_MEMBRES, self::LIEN_WIKI, self::LIEN_COMPTA];

		if (!in_array($type, $check))
		{
			throw new \LogicException('Type de lien de fichier inconnu.');
		}


		return DB::getInstance()->firstColumn(sprintf('SELECT id FROM fichiers_%s WHERE fichier = %d;', $type, $this->id));
	}

	public function isPublic(&$wiki = null): bool
	{
		$config = Config::getInstance();

		if ($config->get('image_fond') == $this->id)
		{
			return true;
		}

		// On regarde déjà si le fichier n'est pas lié au wiki
		$query = sprintf('SELECT wp.droit_lecture FROM fichiers_%s AS link
			INNER JOIN wiki_pages AS wp ON wp.id = link.id
			WHERE link.fichier = ? LIMIT 1;', self::LIEN_WIKI);
		$wiki = DB::getInstance()->firstColumn($query, (int)$this->id);

		// Page wiki publique, aucune vérification à faire, seul cas d'accès à un fichier en dehors de l'espace admin
		if ($wiki !== false && $wiki == Wiki::LECTURE_PUBLIC)
		{
			return true;
		}

		return false;
	}

	/**
	 * Vérifie que l'utilisateur a bien le droit d'accéder à ce fichier
	 * @param  mixed   $user Tableau contenant les infos sur l'utilisateur connecté, provenant de Session::getUser, ou false
	 * @return boolean       TRUE si l'utilisateur a le droit d'accéder au fichier, sinon FALSE
	 */
	public function checkAccess(Session $session, bool $require_admin = false)
	{
		$wiki = null;

		if ($this->isPublic($wiki) && !$require_admin) {
			return true;
		}

		// Pas d'utilisateur connecté, pas d'accès aux fichiers de l'espace admin
		if (!$session->isLogged())
		{
			return false;
		}

		$user = $session->getUser();

		if ($wiki !== false)
		{
			// S'il n'a même pas droit à accéder au wiki c'est mort
			if (!$session->canAccess('wiki', Membres::DROIT_ACCES))
			{
				return false;
			}

			// On renvoie à l'objet Wiki pour savoir si l'utilisateur a le droit de lire ce fichier
			$_w = new Wiki;
			$_w->setRestrictionCategorie($user->id_categorie, $user->droit_wiki);
			return $require_admin ? $_w->canWritePage($wiki) : $_w->canReadPage($wiki);
		}

		$level = $require_admin ? Membres::DROIT_ADMIN : Membres::DROIT_ACCES;

		$db = DB::getInstance();

		// On regarde maintenant si le fichier est lié à la compta
		$query = sprintf('SELECT 1 FROM fichiers_%s WHERE fichier = ? LIMIT 1;', self::LIEN_COMPTA);
		$compta = $db->firstColumn($query, (int)$this->id);

		if ($compta)
		{
			// OK si accès à la compta
			return $session->canAccess('compta', $level);
		}

		// Enfin, si le fichier est lié à un membre
		$query = sprintf('SELECT id FROM fichiers_%s WHERE fichier = ? LIMIT 1;', self::LIEN_MEMBRES);
		$membre = $db->firstColumn($query, (int)$this->id);

		if ($membre !== false)
		{
			// De manière évidente, l'utilisateur a le droit d'accéder aux fichiers liés à son profil
			if ((int)$membre == $user->id)
			{
				return true;
			}

			// Pour voir les fichiers des membres il faut pouvoir les gérer
			if ($level == Membres::DROIT_ACCES) {
				$level = Membres::DROIT_ECRITURE;
			}

			if ($session->canAccess('membres', $level))
			{
				return true;
			}
		}

		return false;
	}

	/**
	 * Supprime le fichier
	 * @return boolean TRUE en cas de succès
	 */
	public function remove()
	{
		$db = DB::getInstance();
		$db->begin();
		$db->delete('fichiers_' . self::LIEN_COMPTA, 'fichier = ?', (int)$this->id);
		$db->delete('fichiers_' . self::LIEN_WIKI, 'fichier = ?', (int)$this->id);
		$db->delete('fichiers_' . self::LIEN_MEMBRES, 'fichier = ?', (int)$this->id);

		$db->delete('fichiers', 'id = ?', (int)$this->id);

		// Suppression du contenu s'il n'est pas utilisé par un autre fichier
		if (!$db->firstColumn('SELECT 1 FROM fichiers WHERE id_contenu = ? AND id != ? LIMIT 1;', 
			(int)$this->id_contenu, (int)$this->id))
		{
			$db->delete('fichiers_contenu', 'id = ?', (int)$this->id_contenu);
		}

		$cache_id = 'fichiers.' . $this->id_contenu;
		
		Static_Cache::remove($cache_id);

		foreach (self::$allowed_thumb_sizes as $size)
		{
			Static_Cache::remove($cache_id . '.thumb.' . (int)$size);
		}

		return $db->commit();
	}

	/**
	 * Renvoie le chemin vers le fichier local en cache, et le crée s'il n'existe pas
	 * @return string Chemin local
	 */
	protected function getFilePathFromCache()
	{
		// Le cache est géré par ID contenu, pas ID fichier, pour minimiser l'espace disque utilisé
		$cache_id = 'fichiers.' . $this->id_contenu;

		// Le fichier n'existe pas dans le cache statique, on l'enregistre
		if (!Static_Cache::exists($cache_id))
		{
			$blob = DB::getInstance()->openBlob('fichiers_contenu', 'contenu', (int)$this->id_contenu);
			Static_Cache::storeFromPointer($cache_id, $blob);
			fclose($blob);
		}

		return Static_Cache::getPath($cache_id);
	}

	/**
	 * Envoie le fichier au client HTTP
	 * @return void
	 */
	public function serve()
	{
		return $this->_serve($this->getFilePathFromCache(), $this->type, ($this->image ? false : $this->nom), $this->taille, $this->isPublic());
	}

	/**
	 * Envoie une miniature à la taille indiquée au client HTTP
	 * @return void
	 */
	public function serveThumbnail($width = null)
	{
		if (!$this->image)
		{
			throw new UserException('Il n\'est pas possible de fournir une miniature pour un fichier qui n\'est pas une image.');
		}

		if (!$width)
		{
			$width = reset(self::$allowed_thumb_sizes);
		}

		if (!in_array($width, self::$allowed_thumb_sizes))
		{
			throw new UserException('Cette taille de miniature n\'est pas autorisée.');
		}

		$cache_id = 'fichiers.' . $this->id_contenu . '.thumb.' . (int)$width;
		$path = Static_Cache::getPath($cache_id);

		// La miniature n'existe pas dans le cache statique, on la crée
		if (!Static_Cache::exists($cache_id))
		{
			$source = $this->getFilePathFromCache();

			try {
				(new Image($source))->resize($width)->save($path);
			}
			catch (\RuntimeException $e) {
				throw new UserException('Impossible de créer la miniature');
			}
		}

		return $this->_serve($path, $this->type);
	}

	/**
	 * Servir un fichier local en HTTP
	 * @param  string $path Chemin vers le fichier local
	 * @param  string $type Type MIME du fichier
	 * @param  string $name Nom du fichier avec extension
	 * @param  integer $size Taille du fichier en octets (facultatif)
	 * @return boolean TRUE en cas de succès
	 */
	protected function _serve($path, $type, $name = false, $size = null, bool $public = false)
	{
		if ($public) {
			Utils::HTTPCache($this->hash, $this->datetime);
		}
		else {
			// Désactiver le cache
			header('Pragma: public');
			header('Expires: -1');
			header('Cache-Control: public, must-revalidate, post-check=0, pre-check=0');
		}

		header('Content-Type: '.$type);

		if ($name)
		{
			header('Content-Disposition: attachment; filename="' . $name . '"');
		}

		// Utilisation de XSendFile si disponible
		if (ENABLE_XSENDFILE && isset($_SERVER['SERVER_SOFTWARE']))
		{
			if (stristr($_SERVER['SERVER_SOFTWARE'], 'apache') 
				&& function_exists('apache_get_modules') 
				&& in_array('mod_xsendfile', apache_get_modules()))
			{
				header('X-Sendfile: ' . $path);
				return true;
			}
			else if (stristr($_SERVER['SERVER_SOFTWARE'], 'lighttpd'))
			{
				header('X-Sendfile: ' . $path);
				return true;
			}
		}

		// Désactiver gzip
		if (function_exists('apache_setenv'))
		{
			@apache_setenv('no-gzip', 1);
		}

		@ini_set('zlib.output_compression', 'Off');

		if ($size)
		{
			header('Content-Length: '. (int)$size);
		}

		if (@ob_get_length()) {
			@ob_clean();
		}

		flush();

		// Sinon on envoie le fichier à la mano
		return readfile($path);
	}

	/**
	 * Vérifie si le hash fourni n'est pas déjà stocké
	 * Utile pour par exemple reconnaître un ficher dont le contenu est déjà stocké, et éviter un nouvel upload
	 * @param  string $hash Hash SHA1
	 * @return boolean      TRUE si le hash est déjà présent dans fichiers_contenu, FALSE sinon
	 */
	static public function checkHash($hash)
	{
		return (boolean) DB::getInstance()->firstColumn(
			'SELECT 1 FROM fichiers_contenu WHERE hash = ?;', 
			trim(strtolower($hash))
		);
	}

	/**
	 * Retourne un tableau de hash trouvés dans la DB parmi une liste de hash fournis
	 * @param  array  $list Liste de hash à vérifier
	 * @return array        Liste des hash trouvés
	 */
	static public function checkHashList($list)
	{
		$db = DB::getInstance();

		array_walk($list, function (&$a) use ($db) {
			$a = $db->quote($a);
		});

		$query = sprintf('SELECT hash, 1 FROM fichiers_contenu WHERE hash IN (%s);', 
			implode(', ', $list));
		return $db->getAssoc($query);
	}

	/**
	 * Récupération du message d'erreur
	 * @param  integer $error Code erreur du $_FILE
	 * @return string Message d'erreur
	 */
	static public function getErrorMessage($error)
	{
		switch ($error)
		{
			case UPLOAD_ERR_INI_SIZE:
				return 'Le fichier excède la taille permise par la configuration du serveur.';
			case UPLOAD_ERR_FORM_SIZE:
				return 'Le fichier excède la taille permise par le formulaire.';
			case UPLOAD_ERR_PARTIAL:
				return 'L\'envoi du fichier a été interrompu.';
			case UPLOAD_ERR_NO_FILE:
				return 'Aucun fichier n\'a été reçu.';
			case UPLOAD_ERR_NO_TMP_DIR:
				return 'Pas de répertoire temporaire pour stocker le fichier.';
			case UPLOAD_ERR_CANT_WRITE:
				return 'Impossible d\'écrire le fichier sur le disque du serveur.';
			case UPLOAD_ERR_EXTENSION:
				return 'Une extension du serveur a interrompu l\'envoi du fichier.';
			default:
				return 'Erreur inconnue: ' . $error;
		}
	}

	/**
	 * Upload du fichier par POST
	 * @param  array  $file  Caractéristiques du fichier envoyé
	 * @return Fichiers
	 */
	static public function upload($file)
	{
		if (!empty($file['error']))
		{
			throw new UserException(self::getErrorMessage($file['error']));
		}

		if (empty($file['size']) || empty($file['name']))
		{
			throw new UserException('Fichier reçu invalide : vide ou sans nom de fichier.');
		}

		if (!is_uploaded_file($file['tmp_name']))
		{
			throw new \RuntimeException('Le fichier n\'a pas été envoyé de manière conventionnelle.');
		}

		$name = preg_replace('/\s+/', '_', $file['name']);
		$name = preg_replace('/[^\d\w._-]/ui', '', $name);

		return self::storeFile($name, $file['tmp_name']);
	}

	/**
	 * Upload de fichier à partir d'une chaîne en base64
	 * @param  string $name
	 * @param  string $content
	 * @return Fichiers
	 */
	static public function storeFromBase64($name, $content)
	{
		$content = base64_decode($content);
		return self::storeFile($name, null, $content);
	}

	/**
	 * Upload de fichier (interne)
	 *
	 * @param  string $name
	 * @param  string $path Chemin du fichier
	 * @param  string $content Ou contenu du fichier
	 * @return Fichiers
	 */
	static protected function storeFile($name, $path = null, $content = null)
	{
		assert($path || $content);

		if ($path && !$content)
		{
			$hash = sha1_file($path);
			$size = filesize($path);
			$bytes = file_get_contents($path, false, null, -1, 1024);
		}
		else
		{
			$hash = sha1($content);
			$size = strlen($content);
			$bytes = substr($content, 0, 1024);
		}

		$type = \KD2\FileInfo::guessMimeType($bytes);

		if (!$type)
		{
			$ext = substr($name, strrpos($name, '.')+1);
			$ext = strtolower($ext);

			$type = \KD2\FileInfo::getMimeTypeFromFileExtension($ext);
		}

		$is_image = preg_match('/^image\/(?:png|jpe?g|gif)$/', $type);

		// Check that it's a real image
		if ($is_image) {
			try {
				if ($path && !$content) {
					$i = new Image($path);
				}
				else {
					$i = Image::createFromBlob($content);
				}

				// Recompress PNG files from base64, assuming they are coming
				// from JS canvas which doesn't know how to gzip (d'oh!)
				if ($i->format() == 'png' && null !== $content) {
					$content = $i->output('png', true);
					$hash = sha1($content);
					$size = strlen($content);
				}

				unset($i);
			}
			catch (\RuntimeException $e) {
				if (strstr($e->getMessage(), 'No suitable image library found')) {
					throw new UserException('Le serveur n\'a aucune bibliothèque de gestion d\'image installée, et ne peut donc pas accepter les images. Installez Imagick ou GD.');
				}

				throw new UserException('Fichier image invalide');
			}
		}

		$db = DB::getInstance();

		$db->begin();

		// Il peut arriver que l'on renvoie ici un fichier déjà stocké, auquel cas, ne pas le re-stocker
		if (!($id_contenu = $db->firstColumn('SELECT id FROM fichiers_contenu WHERE hash = ?;', $hash))) {
			$db->preparedQuery('INSERT INTO fichiers_contenu (hash, taille, contenu) VALUES (?, ?, zeroblob(?));',
				[$hash, (int)$size, (int)$size]);
			$id_contenu = $db->lastInsertRowID();

			// Écrire le contenu
			$blob = $db->openBlob('fichiers_contenu', 'contenu', $id_contenu, 'main', SQLITE3_OPEN_READWRITE);

			if (null !== $content) {
				fwrite($blob, $content);
			}
			else{
				fwrite($blob, file_get_contents($path));
			}

			fclose($blob);
		}

		$db->insert('fichiers', [
			'id_contenu'	=>	(int)$id_contenu,
			'nom'			=>	$name,
			'type'			=>	$type,
			'image'			=>	(int)$is_image,
		]);

		$db->commit();

		return new Fichiers($db->lastInsertRowID());
	}

	/**
	 * Envoie un fichier déjà stocké
	 * 
	 * @param  string $name Nom du fichier
	 * @param  string $hash Hash SHA1 du contenu du fichier
	 * @return object       Un objet Fichiers en cas de succès
	 */
	static public function uploadExistingHash($name, $hash)
	{
		$db = DB::getInstance();
		$name = preg_replace('/[^\d\w._-]/ui', '', $name);

		$file = $db->first('SELECT * FROM fichiers 
			INNER JOIN fichiers_contenu AS fc ON fc.id = fichiers.id_contenu AND fc.hash = ?;', trim($hash));

		if (!$file)
		{
			throw new UserException('Le fichier à copier n\'existe pas (aucun hash ne correspond à '.$hash.').');
		}

		$db->insert('fichiers', [
			'id_contenu' =>	(int)$file->id_contenu,
			'nom'        =>	$name,
			'type'       =>	$file->type,
			'image'      =>	(int)$file->image,
		]);

		return new Fichiers($db->lastInsertRowID());
	}

	/**
	 * Récupère la liste des fichiers liés à une ressource
	 * 
	 * @param  string  $type    Type de ressource
	 * @param  integer $id      Numéro de ressource
	 * @param  boolean|null $images  TRUE pour retourner seulement les images,
	 * FALSE pour retourner les fichiers sans images, NULL pour tout retourner
	 * @return array          Liste des fichiers
	 */
	static public function listLinkedFiles($type, $id, $images = null)
	{
		$check = [self::LIEN_MEMBRES, self::LIEN_WIKI, self::LIEN_COMPTA];

		if (!in_array($type, $check))
		{
			throw new \LogicException('Type de lien de fichier inconnu.');
		}

		$images = is_null($images) ? '' : ' AND image = ' . (int)$images;

		$query = sprintf('SELECT fichiers.*, c.hash, c.taille
			FROM fichiers 
			INNER JOIN fichiers_%s AS fwp ON fwp.fichier = fichiers.id
			INNER JOIN fichiers_contenu AS c ON c.id = fichiers.id_contenu
			WHERE fwp.id = ? %s
			ORDER BY fichiers.nom COLLATE NOCASE;', $type, $images);

		$files = DB::getInstance()->get($query, (int)$id);

		foreach ($files as &$file)
		{
			$file->url = self::_getURL($file->id, $file->nom, $file->hash);
			$file->thumb = $file->image ? self::_getURL($file->id, $file->nom, $file->hash, 200) : false;
		}

		return $files;
	}

	static public function deleteLinkedFiles($type, int $id)
	{
		static $check = [self::LIEN_MEMBRES, self::LIEN_WIKI, self::LIEN_COMPTA];

		if (!in_array($type, $check))
		{
			throw new \LogicException('Type de lien de fichier inconnu.');
		}

		$files = DB::getInstance()->delete('fichiers_' . $type, 'id = ?', $id);
		return self::deleteUnlinkedFiles();
	}

	static public function deleteUnlinkedFiles()
	{
		static $all = [self::LIEN_MEMBRES, self::LIEN_WIKI, self::LIEN_COMPTA];
		$id_background = Config::getInstance()->get('image_fond');

		$list = DB::getInstance()->iterate(sprintf('SELECT f.id, f.id_contenu FROM fichiers f
			LEFT JOIN fichiers_%s a ON a.fichier = f.id
			LEFT JOIN fichiers_%s b ON b.fichier = f.id
			LEFT JOIN fichiers_%s c ON c.fichier = f.id
			WHERE a.id IS NULL AND b.id IS NULL AND c.id IS NULL;',
			self::LIEN_MEMBRES,
			self::LIEN_WIKI,
			self::LIEN_COMPTA));

		foreach ($list as $file) {
			if ($file->id == $id_background) { // FIXME: want to use something cleaner here!
				continue;
			}

			$f = new Fichiers($file->id, (array) $file);
			$f->remove();
		}
	}

	/**
	 * Enlève d'une liste de fichiers ceux qui sont mentionnés dans un texte wiki
	 * @param  array $files Liste de fichiers
	 * @param  string $text  texte wiki
	 * @return array        Un tableau qui ne contient pas les fichiers mentionnés dans $text
	 */
	static public function filterFilesUsedInText($files, $text)
	{
		$used = self::listFilesUsedInText($text);

		return array_filter($files, function ($row) use ($used) {
			return !in_array($row->id, $used);
		});
	}

	/**
	 * Renvoie une liste d'ID de fichiers mentionnées dans un texte wiki
	 * @param  string $text Texte wiki
	 * @return array       Liste des IDs de fichiers mentionnés
	 */
	static public function listFilesUsedInText($text)
	{
		preg_match_all('/<<?(?:fichier|image)\s*(?:\|\s*)?(\d+)/', $text, $match, PREG_PATTERN_ORDER);
		preg_match_all('/(?:fichier|image):\/\/(\d+)/', $text, $match2, PREG_PATTERN_ORDER);

		return array_merge($match[1], $match2[1]);
	}

	/**
	 * Callback utilisé pour l'extension <<fichier>> dans le wiki-texte
	 * @param array $args    Arguments passés à l'extension
	 * @param string $content Contenu éventuel (en mode bloc)
	 * @param object $skriv   Objet SkrivLite
	 */
	static public function SkrivFichier($args, $content, $skriv)
	{
		$id = $caption = null;

		foreach ($args as $value)
		{
			if (preg_match('/^\d+$/', $value) && !$id)
			{
				$id = (int)$value;
				break;
			}
			else
			{
				$caption = trim($value);
			}
		}

		if (empty($id))
		{
			return $skriv->parseError('/!\ Tag fichier : aucun numéro de fichier indiqué.');
		}

		try {
			$file = new Fichiers($id);
		}
		catch (\InvalidArgumentException $e)
		{
			return $skriv->parseError('/!\ Tag fichier : ' . $e->getMessage());
		}

		if (empty($caption))
		{
			$caption = $file->nom;
		}

		$out = '<aside class="fichier" data-type="'.$skriv->escape($file->type).'">';
		$out.= '<a href="'.$file->getURL().'" class="internal-file">'.$skriv->escape($caption).'</a> ';
		$out.= '<small>('.$skriv->escape(($file->type ? $file->type . ', ' : '') . Utils::format_bytes($file->taille)).')</small>';
		$out.= '</aside>';
		return $out;
	}

	/**
	 * Callback utilisé pour l'extension <<image>> dans le wiki-texte
	 * @param array $args    Arguments passés à l'extension
	 * @param string $content Contenu éventuel (en mode bloc)
	 * @param object $skriv   Objet SkrivLite
	 */
	static public function SkrivImage($args, $content, $skriv)
	{
		static $align_values = ['droite', 'gauche', 'centre'];

		$align = '';
		$id = $caption = null;

		foreach ($args as $value)
		{
			if (preg_match('/^\d+$/', $value) && !$id)
			{
				$id = (int)$value;
			}
			else if (in_array($value, $align_values) && !$align)
			{
				$align = $value;
			}
			else
			{
				$caption = $value;
			}
		}

		if (!$id)
		{
			return $skriv->parseError('/!\ Tag image : aucun numéro de fichier indiqué.');
		}

		try {
			$file = new Fichiers($id);
		}
		catch (\InvalidArgumentException $e)
		{
			return $skriv->parseError('/!\ Tag image : ' . $e->getMessage());
		}

		if (!$file->image)
		{
			return $skriv->parseError('/!\ Tag image : ce fichier n\'est pas une image.');
		}

		$out = '<a href="'.$file->getURL().'" class="internal-image">';
		$out .= '<img src="'.$file->getURL($align == 'centre' ? 500 : 200).'" alt="';

		if ($caption)
		{
			$out .= htmlspecialchars($caption, ENT_QUOTES, 'UTF-8');
		}

		$out .= '" /></a>';

		if (!empty($align))
		{
			$out = '<figure class="image ' . $align . '">' . $out;

			if ($caption)
			{
				$out .= '<figcaption>' . htmlspecialchars($caption, ENT_QUOTES, 'UTF-8') . '</figcaption>';
			}

			$out .= '</figure>';
		}

		return $out;
	}
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Added src/include/lib/Garradin/Files/Files.php version [97e4ccbc5c].





























































































































































































































































































































































































































































































































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

namespace Garradin\Files;

use Garradin\Static_Cache;
use Garradin\DB;
use Garradin\Utils;
use Garradin\ValidationException;
use Garradin\Membres\Session;
use Garradin\Entities\Files\File;
use Garradin\Entities\Web\Page;

use KD2\DB\EntityManager as EM;

use const Garradin\{FILE_STORAGE_BACKEND, FILE_STORAGE_QUOTA, FILE_STORAGE_CONFIG};

class Files
{
	static public function search(string $search, string $path = null): array
	{
		if (strlen($search) > 100) {
			throw new ValidationException('Recherche trop longue : maximum 100 caractères');
		}

		$where = '';
		$params = [trim($search)];

		if (null !== $path) {
			$where = ' AND path LIKE ?';
			$params[] = $path;
		}

		$query = sprintf('SELECT
			*,
			dirname(path) AS parent,
			snippet(files_search, \'<b>\', \'</b>\', \'…\', 2) AS snippet,
			rank(matchinfo(files_search), 0, 1.0, 1.0) AS points
			FROM files_search
			WHERE files_search MATCH ? %s
			ORDER BY points DESC
			LIMIT 0,50;', $where);

		return DB::getInstance()->get($query, ...$params);
	}

	static public function list(string $parent = ''): array
	{
		if ($parent !== '') {
			File::validatePath($parent);
		}

		// Update this path
		return self::callStorage('list', $parent);
	}

	static public function delete(string $path): void
	{
		$file = self::get($path);

		if (!$file) {
			return;
		}

		$file->delete();
	}

	static public function callStorage(string $function, ...$args)
	{
		$class_name = __NAMESPACE__ . '\\Storage\\' . FILE_STORAGE_BACKEND;

		call_user_func([$class_name, 'configure'], FILE_STORAGE_CONFIG);

		return call_user_func_array([$class_name, $function], $args);
	}

	/**
	 * Copy all files from a storage backend to another one
	 * This can be used to move from SQLite to FileSystem for example
	 * Note that this only copies files, and is not removing them from the source storage backend.
	 */
	static public function migrateStorage(string $from, string $to, $from_config = null, $to_config = null, ?callable $callback = null): void
	{
		$from = __NAMESPACE__ . '\\Storage\\' . $from;
		$to = __NAMESPACE__ . '\\Storage\\' . $to;

		if (!class_exists($from)) {
			throw new \InvalidArgumentException('Invalid storage: ' . $from);
		}

		if (!class_exists($to)) {
			throw new \InvalidArgumentException('Invalid storage: ' . $to);
		}

		call_user_func([$from, 'configure'], $from_config);
		call_user_func([$to, 'configure'], $to_config);

		try {
			call_user_func([$from, 'checkLock']);
			call_user_func([$to, 'checkLock']);

			call_user_func([$from, 'lock']);
			call_user_func([$to, 'lock']);

			$db = DB::getInstance();
			$db->begin();
			$i = 0;

			self::migrateDirectory($from, $to, '', $i, $callback);

			$db->commit();
		}
		finally {
			call_user_func([$from, 'unlock']);
			call_user_func([$to, 'unlock']);
		}
	}

	static protected function migrateDirectory(string $from, string $to, string $path, int &$i, ?callable $callback)
	{
		$db = DB::getInstance();

		foreach (call_user_func([$from, 'list'], $path) as $file) {
			if (++$i >= 100) {
				$db->commit();
				$db->begin();
				$i = 0;
			}

			if ($file->type == File::TYPE_DIRECTORY) {
				call_user_func([$to, 'mkdir'], $file);
				self::migrateDirectory($from, $to, $file->path, $i, $callback);
			}
			else {
				$from_path = call_user_func([$from, 'getFullPath'], $file);
				call_user_func([$to, 'storePath'], $file, $from_path);
			}

			if (null !== $callback) {
				$callback($file);
			}

			unset($file);
		}
	}

	/**
	 * Delete all files from a storage backend
	 */
	static public function truncateStorage(string $backend, $config = null): void
	{
		$backend = __NAMESPACE__ . '\\Storage\\' . $backend;

		call_user_func([$backend, 'configure'], $config);

		if (!class_exists($backend)) {
			throw new \InvalidArgumentException('Invalid storage: ' . $backend);
		}

		call_user_func([$backend, 'truncate']);
	}

	static public function get(string $path, int $type = null): ?File
	{
		try {
			File::validatePath($path);
		}
		catch (ValidationException $e) {
			return null;
		}

		$file = self::callStorage('get', $path);

		if (!$file || ($type && $file->type != $type)) {
			return null;
		}

		return $file;
	}

	static public function getFromURI(string $uri): ?File
	{
		$uri = trim($uri, '/');
		$uri = rawurldecode($uri);

		return self::get($uri, File::TYPE_FILE);
	}

	static public function getContext(string $path): ?string
	{
		$context = strtok($path, '/');

		if (!array_key_exists($context, File::CONTEXTS_NAMES)) {
			return null;
		}

		return $context;
	}

	static public function getContextRef(string $path): ?string
	{
		$context = strtok($path, '/');
		return strtok('/') ?: null;
	}

	static public function getBreadcrumbs(string $path): array
	{
		$parts = explode('/', $path);
		$breadcrumbs = [];
		$path = '';

		foreach ($parts as $part) {
			$path = trim($path . '/' . $part, '/');
			$breadcrumbs[$path] = $part;
		}

		return $breadcrumbs;
	}

	static public function getQuota(): int
	{
		return FILE_STORAGE_QUOTA ?? self::callStorage('getQuota');
	}

	static public function getUsedQuota(bool $force_refresh = false): int
	{
		if ($force_refresh || Static_Cache::expired('used_quota', 3600)) {
			$quota = self::callStorage('getTotalSize');
			Static_Cache::store('used_quota', $quota);
		}
		else {
			$quota = (int) Static_Cache::get('used_quota');
		}

		return $quota;
	}

	static public function getRemainingQuota(bool $force_refresh = false): int
	{
		if (FILE_STORAGE_QUOTA !== null) {
			return FILE_STORAGE_QUOTA - self::getUsedQuota($force_refresh);
		}

		return self::callStorage('getRemainingQuota');
	}

	static public function checkQuota(int $size = 0): void
	{
		$remaining = self::getRemainingQuota(true);

		if (($remaining - $size) < 0) {
			throw new ValidationException('L\'espace disque est insuffisant pour réaliser cette opération');
		}
	}
}

Added src/include/lib/Garradin/Files/Storage/FileSystem.php version [7b08898a49].































































































































































































































































































































































































































































































































































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

namespace Garradin\Files\Storage;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\DB;
use Garradin\Utils;

/**
 * This class provides storage in the file system
 * You need to configure FILE_STORAGE_CONFIG to give a file path
 */
class FileSystem implements StorageInterface
{
	static protected $_size;
	static protected $_root;

	static public function configure(?string $config): void
	{
		if (!$config) {
			throw new \RuntimeException('Le stockage de fichier n\'a pas été configuré (FILE_STORAGE_CONFIG est vide).');
		}

		if (!is_writable($config) && !Utils::safe_mkdir($config)) {
			throw new \RuntimeException('Le répertoire de stockage des fichiers est protégé contre l\'écriture.');
		}

		$target = rtrim($config, DIRECTORY_SEPARATOR);
		self::$_root = realpath($target);
	}

	static protected function _getRoot()
	{
		if (!self::$_root) {
			throw new \RuntimeException('Le stockage de fichier n\'a pas été configuré (FILE_STORAGE_CONFIG est vide ?).');
		}

		return self::$_root;
	}

	static protected function ensureDirectoryExists(string $path): void
	{
		if (is_dir($path)) {
			return;
		}

		$permissions = fileperms(self::_getRoot());

		Utils::safe_mkdir($path, $permissions & 0777, true);
	}

	static public function storePath(File $file, string $source_path): bool
	{
		$target = self::getFullPath($file);
		self::ensureDirectoryExists(dirname($target));

		$return = copy($source_path, $target);

		if ($return) {
			touch($target, $file->modified->getTimestamp());
		}

		return $return;
	}

	static public function storeContent(File $file, string $source_content): bool
	{
		$target = self::getFullPath($file);
		self::ensureDirectoryExists(dirname($target));

		$return = file_put_contents($target, $source_content) === false ? false : true;

		if ($return) {
			touch($target, $file->modified->getTimestamp());
		}

		return $return;
	}

	static public function mkdir(File $file): bool
	{
		return Utils::safe_mkdir(self::getFullPath($file));
	}

	static public function touch(string $path): bool
	{
		return touch(self::_getRealPath($path));
	}

	static protected function _getRealPath(string $path): ?string
	{
		$path = self::_getRoot() . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $path);

		$parts = explode(DIRECTORY_SEPARATOR, $path);

		foreach ($parts as $part) {
			if (substr($part, 0, 1) === '.') {
				return null;
			}
		}

		return $path;
	}

	static public function getFullPath(File $file): ?string
	{
		return self::_getRealPath($file->path);
	}

	static public function display(File $file): void
	{
		readfile(self::getFullPath($file));
	}

	static public function fetch(File $file): string
	{
		return file_get_contents(self::getFullPath($file));
	}

	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
	{
		$source = self::getFullPath($file);
		$target = self::_getRealPath($new_path);

		self::ensureDirectoryExists(dirname($target));

		return rename($source, $target);
	}

	static public function exists(string $path): bool
	{
		return file_exists(self::_getRealPath($path));
	}

	static public function get(string $path): ?File
	{
		$file = new \SplFileInfo(self::_getRealPath($path));

		if (!$file->getRealPath()) {
			return null;
		}

		return self::_SplToFile($file);
	}

	static protected function _SplToFile(\SplFileInfo $spl): File
	{
		$path = str_replace(self::_getRoot() . DIRECTORY_SEPARATOR, '', $spl->getPathname());
		$path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
		$parent = Utils::dirname($path);

		if ($parent == '.' || !$parent) {
			$parent = '';
		}

		$data = [
			'id'       => null,
			// may return slash
			// see comments https://www.php.net/manual/fr/splfileinfo.getfilename.php
			// don't use getBasename as it is locale-dependent!
			'name'     => trim($spl->getFilename(), '/'),
			'path'     => $path,
			'parent'   => $parent,
			'modified' => new \DateTime('@' . $spl->getMTime()),
			'size'     => $spl->getSize(),
			'type'     => $spl->isDir() ? File::TYPE_DIRECTORY : File::TYPE_FILE,
			'mime'     => mime_content_type($spl->getRealPath()),
		];

		$data['modified']->setTimeZone(new \DateTimeZone(date_default_timezone_get()));

		$data['image'] = (int) in_array($data['mime'], File::IMAGE_TYPES);

		$file = new File;
		$file->load($data);

		return $file;
	}

	static public function list(string $path): array
	{
		$fullpath = self::_getRoot() . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $path);
		$fullpath = rtrim($fullpath, DIRECTORY_SEPARATOR);

		if (!file_exists($fullpath)) {
			return [];
		}

		$files = [];

		foreach (new \FilesystemIterator($fullpath, \FilesystemIterator::SKIP_DOTS) as $file) {
			// Used to make sorting easier
			// directory_blabla
			// file_image.jpeg
			$files[$file->getType() . '_' .$file->getFilename()] = self::_SplToFile($file);
		}

		return Utils::knatcasesort($files);
	}

	static public function getTotalSize(): int
	{
		if (null !== self::$_size) {
			return self::$_size;
		}

		$total = 0;

		$path = self::_getRoot();

		foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS,), \RecursiveIteratorIterator::CATCH_GET_CHILD) as $p) {
			$total += $p->getSize();
		}

		self::$_size = (int) $total;

		return self::$_size;
	}

	/**
	 * @see https://www.crazyws.fr/dev/fonctions-php/fonction-disk-free-space-et-disk-total-space-pour-ovh-2JMH9.html
	 * @see https://github.com/jdel/sspks/commit/a890e347f32e9e3e50a0dd82398947633872bf38
	 */
	static public function getQuota(): int
	{
		$quota = @disk_total_space(self::_getRoot());
		return $quota === false ? \PHP_INT_MAX : (int) $quota;
	}

	static public function getRemainingQuota(): int
	{
		$quota = @disk_free_space(self::_getRoot());
		return $quota === false ? \PHP_INT_MAX : (int) $quota;
	}

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

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

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

	static public function checkLock(): void
	{
		$lock = file_exists(self::_getRoot() . DIRECTORY_SEPARATOR . '.lock');

		if ($lock) {
			throw new \RuntimeException('File storage is locked');
		}
	}
}

Added src/include/lib/Garradin/Files/Storage/SQLite.php version [1733617c6f].



























































































































































































































































































































































































































































































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

namespace Garradin\Files\Storage;

use Garradin\Entities\Files\File;
use Garradin\Files\Files;

use Garradin\Static_Cache;
use Garradin\DB;
use Garradin\Utils;

use KD2\DB\EntityManager as EM;

use const Garradin\{DB_FILE, DATA_ROOT};

class SQLite implements StorageInterface
{
	static public function configure(?string $config): void
	{
	}

	/**
	 * Renvoie le chemin vers le fichier local en cache, et le crée s'il n'existe pas
	 * @return string Chemin local
	 */
	static protected function _getFilePathFromCache(File $file): string
	{
		$cache_id = 'files.' . $file->pathHash();

		if (!Static_Cache::exists($cache_id))
		{
			$db = DB::getInstance();

			try {
				$blob = $db->openBlob('files_contents', 'content', $file->id());
			}
			catch (\Exception $e) {
				if (!strstr($e->getMessage(), 'no such rowid')) {
					throw $e;
				}

				throw new \RuntimeException('File does not exist in DB: ' . $file->path);
			}

			Static_Cache::storeFromPointer($cache_id, $blob);
			fclose($blob);
		}

		return Static_Cache::getPath($cache_id);
	}

	static public function storePath(File $file, string $source_path): bool
	{
		return self::store($file, $source_path, null);
	}

	static public function storeContent(File $file, string $source_content): bool
	{
		return self::store($file, null, $source_content);
	}

	static protected function store(File $file, ?string $source_path, ?string $source_content): bool
	{
		if (!isset($source_path) && !isset($source_content)) {
			throw new \InvalidArgumentException('Either source_path or source_content must be supplied');
		}

		$db = DB::getInstance();

		$file->size = $source_content !== null ? strlen($source_content) : filesize($source_path);

		$file->save();

		$id = $file->id();

		$db->preparedQuery('INSERT OR REPLACE INTO files_contents (id, content) VALUES (?, zeroblob(?));',
			$id, $file->size);

		$blob = $db->openBlob('files_contents', 'content', $id, 'main', \SQLITE3_OPEN_READWRITE);

		if (null !== $source_content) {
			fwrite($blob, $source_content);
		}
		else {
			$in = fopen($source_path, 'r');
			stream_copy_to_stream($in, $blob);
			fclose($in);
		}

		fclose($blob);

		$cache_id = 'files.' . $file->pathHash();
		Static_Cache::remove($cache_id);

		if ($file->parent) {
			self::touch($file->parent);
		}

		return true;
	}

	static public function getFullPath(File $file): ?string
	{
		return self::_getFilePathFromCache($file);
	}

	static public function display(File $file): void
	{
		readfile(self::getFullPath($file));
	}

	static public function fetch(File $file): string
	{
		return file_get_contents(self::getFullPath($file));
	}

	static public function get(string $path): ?File
	{
		$sql = 'SELECT * FROM @TABLE WHERE path = ? LIMIT 1;';
		return EM::findOne(File::class, $sql, $path);
	}

	static public function list(string $path): array
	{
		return EM::getInstance(File::class)->all('SELECT * FROM @TABLE WHERE parent = ? ORDER BY type DESC, name COLLATE NOCASE ASC;', $path);
	}

	static public function exists(string $path): bool
	{
		return DB::getInstance()->test('files', 'path = ? AND name = ?', Utils::dirname($path), Utils::basename($path));
	}

	static public function delete(File $file): bool
	{
		$db = DB::getInstance();

		$cache_id = 'files.' . $file->pathHash();
		Static_Cache::remove($cache_id);

		$db->delete('files_contents', 'id = ?', $file->id());

		// Delete recursively
		if ($file->type == File::TYPE_DIRECTORY) {
			foreach (Files::list($file->path) as $subfile) {
				$subfile->delete();
			}
		}

		if ($file->parent) {
			self::touch($file->parent);
		}

		return true;
	}

	static public function move(File $file, string $new_path): bool
	{
		$current_path = $file->path;
		$file->set('path', $new_path);
		$file->set('parent', Utils::dirname($new_path));
		$file->set('name', Utils::basename($new_path));
		$file->save();

		if ($file->type == File::TYPE_DIRECTORY) {
			// Move sub-directories and sub-files
			DB::getInstance()->preparedQuery('UPDATE files SET parent = ?, path = TRIM(? || \'/\' || name, \'/\') WHERE parent = ?;', $new_path, $new_path, $current_path);
		}

		if ($file->parent) {
			self::touch($file->parent);
		}

		return true;
	}

	static public function touch(string $path): bool
	{
		return DB::getInstance()->preparedQuery('UPDATE files SET modified = ? WHERE path = ?;', new \DateTime, $path);
	}

	static public function mkdir(File $file): bool
	{
		$file->save();

		if ($file->parent) {
			self::touch($file->parent);
		}

		return true;
	}

	static public function getTotalSize(): int
	{
		return (int) DB::getInstance()->firstColumn('SELECT SUM(size) FROM files;');
	}

	/**
	 * @see https://www.crazyws.fr/dev/fonctions-php/fonction-disk-free-space-et-disk-total-space-pour-ovh-2JMH9.html
	 * @see https://github.com/jdel/sspks/commit/a890e347f32e9e3e50a0dd82398947633872bf38
	 */
	static public function getQuota(): int
	{
		$quota = @disk_total_space(DATA_ROOT);
		return $quota === false ? \PHP_INT_MAX : (int) $quota;
	}

	static public function getRemainingQuota(): int
	{
		$quota = @disk_free_space(DATA_ROOT);
		return $quota === false ? \PHP_INT_MAX : (int) $quota;
	}

	static public function truncate(): void
	{
		$db = DB::getInstance();
		$db->exec('DELETE FROM files_contents; DELETE FROM files; VACUUM;');
	}

	static public function lock(): void
	{
		DB::getInstance()->exec('INSERT INTO files (name, path, parent, type) VALUES (\'.lock\', \'.lock\', \'\', 2);');
	}

	static public function unlock(): void
	{
		DB::getInstance()->exec('DELETE FROM files WHERE path = \'.lock\';');
	}

	static public function checkLock(): void
	{
		$lock = DB::getInstance()->firstColumn('SELECT 1 FROM files WHERE path = \'.lock\';');

		if ($lock) {
			throw new \RuntimeException('File storage is locked');
		}
	}
}

Added src/include/lib/Garradin/Files/Storage/StorageInterface.php version [a0c0da8a45].



































































































































































































































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

namespace Garradin\Files\Storage;

use Garradin\Entities\Files\File;

interface StorageInterface
{
	/**
	 * Configures the storage backend for subsequent calls
	 */
	static public function configure(?string $config): void;

	/**
	 * Stores a file in this backend from a local path
	 */
	static public function storePath(File $file, string $source_path): bool;

	/**
	 * Stores a file from a content binary string
	 */
	static public function storeContent(File $file, string $source_content): bool;

	/**
	 * Create an empty directory
	 */
	static public function mkdir(File $file): bool;

	/**
	 * Should return full local file access path.
	 * If storage backend cannot store the file locally, return NULL.
	 * In that case a subsequent call to fetch() will be done.
	 */
	static public function getFullPath(File $file): ?string;

	/**
	 * Returns the binary of a content to php://output
	 */
	static public function display(File $file): void;

	/**
	 * Returns the binary content of a file
	 */
	static public function fetch(File $file): string;

	/**
	 * Delete a file
	 */
	static public function delete(File $file): bool;

	/**
	 * Change file mtime
	 */
	static public function touch(string $path): bool;

	/**
	 * Return TRUE if file exists
	 */
	static public function exists(string $path): bool;

	/**
	 * Return a File object from a given path or NULL if the file doesn't exist
	 */
	static public function get(string $path): ?File;

	/**
	 * Return an array of File objects for a given path
	 */
	static public function list(string $path): array;

	/**
	 * Moves a file to a new path, when its name or path has changed
	 */
	static public function move(File $file, string $new_path): bool;

	/**
	 * Return total size of used space by files stored in this backed
	 */
	static public function getTotalSize(): int;

	/**
	 * Return total disk space
	 * This will only be called if FILE_STORAGE_QUOTA constant is null
	 */
	static public function getQuota(): int;

	/**
	 * Return available free disk space
	 * This will only be called if FILE_STORAGE_QUOTA constant is null
	 */
	static public function getRemainingQuota(): int;

	/**
	 * Delete all stored content in this backend
	 */
	static public function truncate(): void;

	/**
	 * Lock storage backend against changes
	 * This is used when migrating from one storage to another
	 */
	static public function lock(): void;

	/**
	 * Unlock storage backend against changes
	 */
	static public function unlock(): void;

	/**
	 * Throw a \RuntimeException if the lock is active
	 */
	static public function checkLock(): void;
}

Modified src/include/lib/Garradin/Form.php from [8f5c821c3d] to [e04e8790f9].

35
36
37
38
39
40
41




42
43
44
45
46
47
48
			return false;
		}

		try {
			call_user_func($fn);

			if (null !== $redirect) {




				Utils::redirect($redirect);
			}

			return true;
		}
		catch (UserException $e) {
			$this->addError($e->getMessage());







>
>
>
>







35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
			return false;
		}

		try {
			call_user_func($fn);

			if (null !== $redirect) {
				if (array_key_exists('_dialog', $_GET)) {
					Utils::reloadParentFrame();
				}

				Utils::redirect($redirect);
			}

			return true;
		}
		catch (UserException $e) {
			$this->addError($e->getMessage());

Modified src/include/lib/Garradin/Install.php from [1e3ce59b3f] to [87cbe58842].

1
2
3
4
5
6
7



8
9
10
11
12
13
14
<?php

namespace Garradin;

use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Chart;
use Garradin\Entities\Accounting\Year;




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







>
>
>







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

namespace Garradin;

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

/**
 * Pour procéder à l'installation de l'instance Garradin
 * Utile pour automatiser l'installation sans passer par la page d'installation
 */
class Install
{
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
			// Force l'installation de plugin système
			Plugin::checkAndInstallSystemPlugins();
		}

		return $ok;
	}








	static public function install($nom_asso, $nom_membre, $email_membre, $passe_membre)
	{

		$db = DB::getInstance(true);

		// Taille de la page de DB, on force à 4096 (défaut dans les dernières




		// versions de SQLite mais pas les vieilles)

		$db->exec('PRAGMA page_size = 4096;');


		$db->exec('VACUUM;');














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

		$db->exec(file_get_contents(DB_SCHEMA));
		$db->commit();



		// Configuration de base
		// c'est dans Config::set que sont vérifiées les données utilisateur (renvoie UserException)
		$config = Config::getInstance();
		$config->set('nom_asso', $nom_asso);
		$config->set('email_asso', $email_membre);
		$config->set('site_asso', WWW_URL);
		$config->set('monnaie', '€');
		$config->set('pays', 'FR');
		$config->setVersion(garradin_version());

		$champs = Membres\Champs::importInstall();
		$champs->save(false); // Pas de copie car pas de table membres existante


		$config->set('champ_identifiant', 'email');
		$config->set('champ_identite', 'nom');

		// Création catégories
		$cats = new Membres\Categories;

		$id = $cats->add([
			'nom' => 'Membres actifs',

		]);


		$config->set('categorie_membres', $id);



		$id = $cats->add([
			'nom' => 'Anciens membres',
			'droit_inscription' => Membres::DROIT_AUCUN,
			'droit_wiki' => Membres::DROIT_AUCUN,
			'droit_membres' => Membres::DROIT_AUCUN,
			'droit_compta' => Membres::DROIT_AUCUN,
			'droit_config' => Membres::DROIT_AUCUN,
			'droit_connexion' => Membres::DROIT_AUCUN,
			'cacher' => 1,
		]);

		$id = $cats->add([
			'nom' => 'Administrateurs',
			'droit_inscription' => Membres::DROIT_AUCUN,
			'droit_wiki' => Membres::DROIT_ADMIN,
			'droit_membres' => Membres::DROIT_ADMIN,
			'droit_compta' => Membres::DROIT_ADMIN,
			'droit_config' => Membres::DROIT_ADMIN,
		]);

		// Création premier membre
		$membres = new Membres;
		$id_membre = $membres->add([
			'id_categorie'  =>  $id,
			'nom'           =>  $nom_membre,
			'email'         =>  $email_membre,
			'passe'         =>  $passe_membre,
			'pays'          =>  'FR',
		]);

		// Création wiki
		$page = Wiki::transformTitleToURI($nom_asso);
		$wiki = new Wiki;
		$id_page = $wiki->create([

			'titre' =>  $nom_asso,
			'uri'   =>  $page,
		]);

		$wiki->editRevision($id_page, 0, [
			'id_auteur' =>  $id_membre,
			'contenu'   =>  "Bienvenue dans le wiki de ".$nom_asso." !\n\nCliquez sur le bouton « éditer » pour modifier cette page.",
		]);

		// Création page wiki connexion
		$page = Wiki::transformTitleToURI('Bienvenue');

		$id_page = $wiki->create([
			'titre' =>  'Bienvenue',



			'uri'   =>  $page,
		]);
		$config->set('accueil_wiki', $page);

		$wiki->editRevision($id_page, 0, [
			'id_auteur' =>  $id_membre,
			'contenu'   =>  "Bienvenue dans l'administration de ".$nom_asso." !\n\n"
				.   "Utilisez le menu à gauche pour accéder aux différentes rubriques.",
		]);

		$config->set('accueil_connexion', $page);

        // Import plan comptable
        $chart = new Chart;
        $chart->label = 'Plan comptable associatif 2020 (Règlement ANC n°2018-06)';
        $chart->country = 'FR';
        $chart->code = 'PCA2018';
        $chart->save();
        $chart->accounts()->importCSV(ROOT . '/include/data/charts/fr_2018.csv');

        // Premier exercice
        $year = new Year;
        $year->label = sprintf('Exercice %d', date('Y'));
        $year->start_date = new \DateTime('January 1st');
        $year->end_date = new \DateTime('December 31');
        $year->id_chart = $chart->id();
        $year->save();

        // Compte bancaire
        $account = new Account;
        $account->import([
        	'label' => 'Compte courant',
        	'code' => '512A',
        	'type' => Account::TYPE_BANK,
        	'position' => Account::ASSET_OR_LIABILITY,
        	'id_chart' => $chart->id(),
        	'user' => 1,
        ]);
        $account->save();

		// Ajout d'une recherche avancée en exemple (membres)
		$query = (object) [
			'query' => [[
				'operator' => 'AND',
				'conditions' => [
					[
						'column'   => 'lettre_infos',
						'operator' => '= 1',
						'values'   => [],
					],
				],
			]],
			'order' => 'numero',
			'desc' => true,
			'limit' => '10000',
		];

		$recherche = new Recherche;
		$recherche->add('Membres inscrits à la lettre d\'information', null, $recherche::TYPE_JSON, 'membres', $query);

		// Ajout d'une recherche avancée en exemple (compta)
		$query = (object) [
			'query' => [[
				'operator' => 'AND',
				'conditions' => [
					[
						'column'   => 'a2.code',
						'operator' => 'IS NULL',







>
>
>
>
>
>
>
|

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



>


>
>




|
|
<


|


|
>




|
|
>
|
|
>

>
>
|

>
>
|
|
<
<
<
<
<
<
|

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

|
<
|
<
>
|
<

|
<
<
<
|

|
<
>
|
|
>
>
>
|

<

<
<
<
|
|
>
|

|







|







|











|

















|

|







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
			// Force l'installation de plugin système
			Plugin::checkAndInstallSystemPlugins();
		}

		return $ok;
	}

	static protected function assert(bool $assertion, string $message)
	{
		if (!$assertion) {
			throw new ValidationException($message);
		}
	}

	static public function installFromForm(array $source = null)
	{
		if (null === $source) {
			$source = $_POST;
		}

		self::assert(isset($source['name']) && trim($source['name']) !== '', 'Le nom de l\'association n\'est pas renseigné');
		self::assert(isset($source['user_name']) && trim($source['user_name']) !== '', 'Le nom du membre n\'est pas renseigné');
		self::assert(isset($source['user_email']) && trim($source['user_email']) !== '', 'L\'adresse email du membre n\'est pas renseignée');
		self::assert(isset($source['user_password']) && isset($source['user_password_confirm']) && trim($source['user_password']) !== '', 'Le mot de passe n\'est pas renseigné');

		self::assert((bool)filter_var($source['user_email'], FILTER_VALIDATE_EMAIL), 'Adresse email invalide');

		self::assert(strlen($source['user_password']) >= Session::MINIMUM_PASSWORD_LENGTH, 'Le mot de passe est trop court');
		self::assert($source['user_password'] === $source['user_password_confirm'], 'La vérification du mot de passe ne correspond pas');

		try {
			return self::install($source['name'], $source['user_name'], $source['user_email'], $source['user_password']);
		}
		catch (\Exception $e) {
			@unlink(DB_FILE);
			throw $e;
		}
	}

	static public function install(string $name, string $user_name, string $user_email, string $user_password, ?string $welcome_text = null)
	{
		self::checkAndCreateDirectories();
		$db = DB::getInstance(true);

		// 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));
		$db->commit();

		file_put_contents(SHARED_CACHE_ROOT . '/version', garradin_version());

		// Configuration de base
		// c'est dans Config::set que sont vérifiées les données utilisateur (renvoie UserException)
		$config = Config::getInstance();
		$config->set('nom_asso', $name);
		$config->set('email_asso', $user_email);

		$config->set('monnaie', '€');
		$config->set('pays', 'FR');
		$config->set('site_disabled', true);

		$champs = Membres\Champs::importInstall();
		$champs->create(); // Pas de copie car pas de table membres existante
		$config->set('champs_membres', $champs);

		$config->set('champ_identifiant', 'email');
		$config->set('champ_identite', 'nom');

		// Create default category for common users
		$cat = new Category;
		$cat->setAllPermissions(Session::ACCESS_NONE);
		$cat->importForm([
			'name' => 'Membres actifs',
			'perm_connect' => Session::ACCESS_READ,
		]);
		$cat->save();

		$config->set('categorie_membres', $cat->id());

		// Create default category for ancient users
		$cat = new Category;
		$cat->importForm([
			'name' => 'Anciens membres',






			'hidden' => 1,
		]);
		$cat->setAllPermissions(Session::ACCESS_NONE);








		$cat->save();










		// Create default category for admins

		$cat = new Category;

		$cat->importForm([
			'name' => 'Administrateurs',

		]);
		$cat->setAllPermissions(Session::ACCESS_ADMIN);



		$cat->save();

		// Create first user

		$membres = new Membres;
		$id_membre = $membres->add([
			'id_category' => $cat->id(),
			'nom'         => $user_name,
			'email'       => $user_email,
			'passe'       => $user_password,
			'pays'        => 'FR',
		]);





		$welcome_text = $welcome_text ?? sprintf("Bienvenue dans l'administration de %s !\n\nUtilisez le menu à gauche pour accéder aux différentes sections.", $name);

		$file = File::createAndStore(File::CONTEXT_CONFIG, 'admin_homepage.skriv', null, $welcome_text);
		$config->set('admin_homepage', $file->path);

        // Import accounting chart
        $chart = new Chart;
        $chart->label = 'Plan comptable associatif 2020 (Règlement ANC n°2018-06)';
        $chart->country = 'FR';
        $chart->code = 'PCA2018';
        $chart->save();
        $chart->accounts()->importCSV(ROOT . '/include/data/charts/fr_2018.csv');

        // Create first accounting year
        $year = new Year;
        $year->label = sprintf('Exercice %d', date('Y'));
        $year->start_date = new \DateTime('January 1st');
        $year->end_date = new \DateTime('December 31');
        $year->id_chart = $chart->id();
        $year->save();

        // Create a first bank account
        $account = new Account;
        $account->import([
        	'label' => 'Compte courant',
        	'code' => '512A',
        	'type' => Account::TYPE_BANK,
        	'position' => Account::ASSET_OR_LIABILITY,
        	'id_chart' => $chart->id(),
        	'user' => 1,
        ]);
        $account->save();

		// Create an example saved search (users)
		$query = (object) [
			'query' => [[
				'operator' => 'AND',
				'conditions' => [
					[
						'column'   => 'lettre_infos',
						'operator' => '= 1',
						'values'   => [],
					],
				],
			]],
			'order' => 'numero',
			'desc' => true,
			'limit' => '10000',
		];

		$recherche = new Recherche;
		$recherche->add('Inscrits à la lettre d\'information', null, $recherche::TYPE_JSON, 'membres', $query);

		// Create an example saved search (accounting)
		$query = (object) [
			'query' => [[
				'operator' => 'AND',
				'conditions' => [
					[
						'column'   => 'a2.code',
						'operator' => 'IS NULL',
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

		return $config->save();
	}

	static public function checkAndCreateDirectories()
	{
		// Vérifier que les répertoires vides existent, sinon les créer
		$paths = [DATA_ROOT, PLUGINS_ROOT, CACHE_ROOT, CACHE_ROOT . '/static', CACHE_ROOT . '/compiled'];










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

			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.');
			}



		}

		return true;
	}

	static public function setLocalConfig($key, $value)
	{







|
>
>
>
>
>
>
>
>
>



|











>
>
>







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

		return $config->save();
	}

	static public function checkAndCreateDirectories()
	{
		// Vérifier que les répertoires vides existent, sinon les créer
		$paths = [
			DATA_ROOT,
			PLUGINS_ROOT,
			CACHE_ROOT,
			SHARED_CACHE_ROOT,
			USER_TEMPLATES_CACHE_ROOT,
			STATIC_CACHE_ROOT,
			SMARTYER_CACHE_ROOT,
			SHARED_USER_TEMPLATES_CACHE_ROOT,
		];

		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;
	}

	static public function setLocalConfig($key, $value)
	{

Modified src/include/lib/Garradin/Membres.php from [084ee701a4] to [0cee6f72d9].

1
2
3
4
5
6
7
8
9

10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

namespace Garradin;

use KD2\Security;
use KD2\SMTP;
use Garradin\Membres\Session;

class Membres

{
    const DROIT_AUCUN = 0;
    const DROIT_ACCES = 1;
    const DROIT_ECRITURE = 2;
    const DROIT_ADMIN = 9;

    const ITEMS_PER_PAGE = 50;

    // Gestion des données ///////////////////////////////////////////////////////

    public function _checkFields(&$data, $check_editable = true, $check_password = true)
    {
        $champs = Config::getInstance()->get('champs_membres');








|
>
|
<
|
<
<
|







1
2
3
4
5
6
7
8
9
10
11

12


13
14
15
16
17
18
19
20
<?php

namespace Garradin;

use KD2\Security;
use KD2\SMTP;
use Garradin\Membres\Session;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;


class Membres


{
    const ITEMS_PER_PAGE = 50;

    // Gestion des données ///////////////////////////////////////////////////////

    public function _checkFields(&$data, $check_editable = true, $check_password = true)
    {
        $champs = Config::getInstance()->get('champs_membres');
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
            $data['passe'] = Session::hashPassword($data['passe']);
        }
        else
        {
            unset($data['passe']);
        }

        if (empty($data['id_categorie']))
        {
            $data['id_categorie'] = Config::getInstance()->get('categorie_membres');
        }

        $db->insert('membres', $data);
        $id = $db->lastInsertRowId();

        Plugin::fireSignal('membre.nouveau', array_merge(['id' => $id], $data));








|

|







163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
            $data['passe'] = Session::hashPassword($data['passe']);
        }
        else
        {
            unset($data['passe']);
        }

        if (empty($data['id_category']))
        {
            $data['id_category'] = Config::getInstance()->get('categorie_membres');
        }

        $db->insert('membres', $data);
        $id = $db->lastInsertRowId();

        Plugin::fireSignal('membre.nouveau', array_merge(['id' => $id], $data));

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
            $data['passe'] = Session::hashPassword($data['passe']);
        }
        else
        {
            unset($data['passe']);
        }

        if (isset($data['id_categorie']) && empty($data['id_categorie']))
        {
            $data['id_categorie'] = Config::getInstance()->get('categorie_membres');
        }

        if (empty($data))
        {
            return true;
        }








|

|







219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
            $data['passe'] = Session::hashPassword($data['passe']);
        }
        else
        {
            unset($data['passe']);
        }

        if (isset($data['id_category']) && empty($data['id_category']))
        {
            $data['id_category'] = Config::getInstance()->get('categorie_membres');
        }

        if (empty($data))
        {
            return true;
        }

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
    public function delete($ids)
    {
        if (!is_array($ids))
        {
            $ids = [(int)$ids];
        }

        $session = new Session;

        if ($session->isLogged())
        {
            $user = $session->getUser();

            foreach ($ids as $id)
            {
                if ($user->id == $id)
                {
                    throw new UserException('Il n\'est pas possible de supprimer son propre compte.');
                }
            }
        }

        return self::_deleteMembres($ids);
    }

    public function getNom($id)
    {
        $db = DB::getInstance();
        $config = Config::getInstance();








|














|







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
    public function delete($ids)
    {
        if (!is_array($ids))
        {
            $ids = [(int)$ids];
        }

        $session = Session::getInstance();

        if ($session->isLogged())
        {
            $user = $session->getUser();

            foreach ($ids as $id)
            {
                if ($user->id == $id)
                {
                    throw new UserException('Il n\'est pas possible de supprimer son propre compte.');
                }
            }
        }

        return $this->_deleteMembres($ids);
    }

    public function getNom($id)
    {
        $db = DB::getInstance();
        $config = Config::getInstance();

358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
        {
            Utils::sendEmail(Utils::EMAIL_CONTEXT_BULK, $config->get('email_asso'), $subject, $message);
        }

        return true;
    }

    public function listAllByCategory($id_categorie, $only_with_email = false)
    {
        $where = $only_with_email ? ' AND email IS NOT NULL' : '';
        return DB::getInstance()->get('SELECT id, email FROM membres WHERE id_categorie = ?' . $where, (int)$id_categorie);
    }

    public function listByCategory(?int $category_id): DynamicList
    {
        $config = Config::getInstance();
        $db = DB::getInstance();
        $identity = $config->get('champ_identite');
        $champs = $config->get('champs_membres');

        $columns = [







|


|


|







356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
        {
            Utils::sendEmail(Utils::EMAIL_CONTEXT_BULK, $config->get('email_asso'), $subject, $message);
        }

        return true;
    }

    public function listAllByCategory($id_category, $only_with_email = false)
    {
        $where = $only_with_email ? ' AND email IS NOT NULL' : '';
        return DB::getInstance()->get('SELECT id, email FROM membres WHERE id_category = ?' . $where, (int)$id_category);
    }

    public function listByCategory(?int $id_category): DynamicList
    {
        $config = Config::getInstance();
        $db = DB::getInstance();
        $identity = $config->get('champ_identite');
        $champs = $config->get('champs_membres');

        $columns = [
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441





442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
            if (isset($columns[$key])) {
                continue;
            }

            $columns[$key] = [
                'label' => $config->title
            ];

            if ($champs->isText($key)) {
                $columns[$key]['order'] = sprintf('transliterate_to_ascii(%s) COLLATE NOCASE %%s', $db->quoteIdentifier($key));
            }

        }

        $tables = 'membres';
        $conditions = $category_id ? sprintf('id_categorie = %d', $category_id) : sprintf('id_categorie NOT IN (SELECT id FROM membres_categories WHERE cacher = 1)');

        $order = $identity;

        if (!isset($columns[$order])) {
            $order = $champs->getFirstListed();
        }

        $list = new DynamicList($columns, $tables, $conditions);
        $list->orderBy($order, false);
        return $list;
    }

    public function countByCategory($cat = 0)
    {
        $db = DB::getInstance();

        $query = 'SELECT COUNT(*) FROM membres ';

        if (is_int($cat) && $cat)
        {
            $query .= sprintf('WHERE id_categorie = %d', $cat);
        }
        elseif (is_array($cat))
        {
            $query .= sprintf('WHERE id_categorie IN (%s)', implode(',', $cat));
        }

        $query .= ';';

        return $db->firstColumn($query);
    }

    public function countAllButHidden()
    {
        $db = DB::getInstance();
        return $db->firstColumn('SELECT COUNT(*) FROM membres WHERE id_categorie NOT IN (SELECT id FROM membres_categories WHERE cacher = 1);');





    }

    static public function changeCategorie($id_cat, $membres)
    {
        foreach ($membres as &$id)
        {
            $id = (int) $id;
        }

        $db = DB::getInstance();
        return $db->update('membres',
            ['id_categorie' => (int)$id_cat],
            sprintf('id IN (%s)', implode(',', $membres))
        );
    }

    static protected function _deleteMembres($membres)
    {
        foreach ($membres as &$id)
        {
            $id = (int) $id;

            // Suppression des fichiers liés
            $files = Fichiers::listLinkedFiles(Fichiers::LIEN_MEMBRES, $id, null);

            foreach ($files as $file)
            {
                $file = new Fichiers($file->id, $file);
                $file->remove();
            }
        }

        Plugin::fireSignal('membre.suppression', $membres);

        $db = DB::getInstance();

        // Suppression du membre
        return $db->delete('membres', $db->where('id', $membres));
    }
}







<
<
<
<
<



|




















|



|










|
>
>
>
>
>











|




|





<
<
|
<
<
<
<
<










388
389
390
391
392
393
394





395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461


462





463
464
465
466
467
468
469
470
471
472
            if (isset($columns[$key])) {
                continue;
            }

            $columns[$key] = [
                'label' => $config->title
            ];





        }

        $tables = 'membres';
        $conditions = $id_category ? sprintf('id_category = %d', $id_category) : sprintf('id_category IN (SELECT id FROM users_categories WHERE hidden = 0)');

        $order = $identity;

        if (!isset($columns[$order])) {
            $order = $champs->getFirstListed();
        }

        $list = new DynamicList($columns, $tables, $conditions);
        $list->orderBy($order, false);
        return $list;
    }

    public function countByCategory($cat = 0)
    {
        $db = DB::getInstance();

        $query = 'SELECT COUNT(*) FROM membres ';

        if (is_int($cat) && $cat)
        {
            $query .= sprintf('WHERE id_category = %d', $cat);
        }
        elseif (is_array($cat))
        {
            $query .= sprintf('WHERE id_category IN (%s)', implode(',', $cat));
        }

        $query .= ';';

        return $db->firstColumn($query);
    }

    public function countAllButHidden()
    {
        $db = DB::getInstance();
        return $db->firstColumn('SELECT COUNT(*) FROM membres WHERE id_category NOT IN (SELECT id FROM users_categories WHERE hidden = 1);');
    }

    public function getAttachementsDirectory(int $id)
    {
        return File::CONTEXT_USER . '/' . $id;
    }

    static public function changeCategorie($id_cat, $membres)
    {
        foreach ($membres as &$id)
        {
            $id = (int) $id;
        }

        $db = DB::getInstance();
        return $db->update('membres',
            ['id_category' => (int)$id_cat],
            sprintf('id IN (%s)', implode(',', $membres))
        );
    }

    protected function _deleteMembres(array $membres)
    {
        foreach ($membres as &$id)
        {
            $id = (int) $id;



            Files::delete($this->getAttachementsDirectory($id));





        }

        Plugin::fireSignal('membre.suppression', $membres);

        $db = DB::getInstance();

        // Suppression du membre
        return $db->delete('membres', $db->where('id', $membres));
    }
}

Deleted src/include/lib/Garradin/Membres/Categories.php version [2ef27a72a7].

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

namespace Garradin\Membres;

use Garradin\Membres;
use Garradin\Config;
use Garradin\DB;
use Garradin\Wiki;
use Garradin\UserException;

class Categories
{
    protected $droits = [
        'inscription'=> Membres::DROIT_AUCUN,
        'connexion' =>  Membres::DROIT_ACCES,
        'membres'   =>  Membres::DROIT_AUCUN,
        'compta'    =>  Membres::DROIT_AUCUN,
        'wiki'      =>  Membres::DROIT_ACCES,
        'config'    =>  Membres::DROIT_AUCUN,
    ];

    protected function _checkData(&$data)
    {
        $db = DB::getInstance();

        if (!isset($data['nom']) || !trim($data['nom']))
        {
            throw new UserException('Le nom de catégorie ne peut rester vide.');
        }
    }

    public function add($data)
    {
        $this->_checkData($data);

        foreach ($this->droits as $key=>$value)
        {
            if (!isset($data['droit_'.$key]))
                $data['droit_'.$key] = $value;
            else
                $data['droit_'.$key] = (int)$data['droit_'.$key];
        }

        $db = DB::getInstance();
        $db->insert('membres_categories', $data);

        return $db->lastInsertRowId();
    }

    public function edit($id, $data)
    {
        $this->_checkData($data);

        foreach ($this->droits as $key=>$value)
        {
            if (isset($data['droit_'.$key]))
                $data['droit_'.$key] = (int)$data['droit_'.$key];
        }

        if (!isset($data['cacher']) || $data['cacher'] != 1)
            $data['cacher'] = 0;

        $db = DB::getInstance();
        return $db->update('membres_categories', $data, 'id = '.(int)$id);
    }

    public function get($id)
    {
        $db = DB::getInstance();

        return $db->first('SELECT * FROM membres_categories WHERE id = ?;',
            (int) $id);
    }

    public function remove($id)
    {
        $db = DB::getInstance();
        $config = Config::getInstance();

        if ($id == $config->get('categorie_membres'))
        {
            throw new UserException('Il est interdit de supprimer la catégorie définie par défaut dans la configuration.');
        }

        if ($db->test('membres', 'id_categorie = ?', (int)$id))
        {
            throw new UserException('La catégorie contient encore des membres, il n\'est pas possible de la supprimer.');
        }

        $db->update(
            'wiki_pages',
            [
                'droit_lecture'     =>  Wiki::LECTURE_NORMAL,
                'droit_ecriture'    =>  Wiki::ECRITURE_NORMAL,
            ],
            'droit_lecture = '.(int)$id.' OR droit_ecriture = '.(int)$id
        );

        return $db->delete('membres_categories', 'id = ?', (int) $id);
    }

    public function listSimple()
    {
        $db = DB::getInstance();
        return $db->getAssoc('SELECT id, nom FROM membres_categories ORDER BY nom;');
    }

    public function listComplete()
    {
        $db = DB::getInstance();
        return $db->get('SELECT * FROM membres_categories ORDER BY nom;');
    }

    public function listCompleteWithStats()
    {
        $db = DB::getInstance();
        return $db->get('SELECT *, (SELECT COUNT(*) FROM membres WHERE id_categorie = membres_categories.id) AS nombre FROM membres_categories ORDER BY nom;');
    }


    public function listHidden()
    {
        $db = DB::getInstance();
        return $db->getAssoc('SELECT id, nom FROM membres_categories WHERE cacher = 1;');
    }

    public function listNotHidden()
    {
        $db = DB::getInstance();
        return $db->getAssoc('SELECT id, nom FROM membres_categories WHERE cacher = 0;');
    }
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































































































Modified src/include/lib/Garradin/Membres/Champs.php from [5d64a9e45c] to [9c3a83a513].

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

namespace Garradin\Membres;

use Garradin\Config;
use Garradin\DB;
use Garradin\Utils;
use Garradin\UserException;

class Champs
{


	protected $champs = null;

    protected $system_fields = [
        'date_connexion',
        'date_inscription',
        'clef_pgp',
        'secret_otp',
        'id',
        'id_categorie',
    ];

	protected $types = [
		'email'		=>	'Adresse E-Mail',
		'url'		=>	'Adresse URL',
		'checkbox'	=>	'Case à cocher',
		'date'		=>	'Date',
		'datetime'	=>	'Date et heure',
		//'file'		=>	'Fichier',
        'password'  =>  'Mot de passe',
		'number'	=>	'Numéro',
		'tel'		=>	'Numéro de téléphone',
		'select'	=>	'Sélecteur à choix unique',
        'multiple'  =>  'Sélecteur à choix multiple',
		'country'	=>	'Sélecteur de pays',
		'text'		=>	'Texte',











>
>








|








|







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

namespace Garradin\Membres;

use Garradin\Config;
use Garradin\DB;
use Garradin\Utils;
use Garradin\UserException;

class Champs
{
    const TABLE = 'membres';

	protected $champs = null;

    protected $system_fields = [
        'date_connexion',
        'date_inscription',
        'clef_pgp',
        'secret_otp',
        'id',
        'id_category',
    ];

	protected $types = [
		'email'		=>	'Adresse E-Mail',
		'url'		=>	'Adresse URL',
		'checkbox'	=>	'Case à cocher',
		'date'		=>	'Date',
		'datetime'	=>	'Date et heure',
        'file'      =>  'Fichier',
        'password'  =>  'Mot de passe',
		'number'	=>	'Numéro',
		'tel'		=>	'Numéro de téléphone',
		'select'	=>	'Sélecteur à choix unique',
        'multiple'  =>  'Sélecteur à choix multiple',
		'country'	=>	'Sélecteur de pays',
		'text'		=>	'Texte',
173
174
175
176
177
178
179















180
181
182
183
184
185
186
    public function getList()
    {
        $champs = clone $this->champs;
        unset($champs->passe);

        return $champs;
    }
















    public function getMultiples()
    {
        $out = [];

        foreach ($this->champs as $id => $champ) {
            if ($champ->type == 'multiple') {







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







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
    public function getList()
    {
        $champs = clone $this->champs;
        unset($champs->passe);

        return $champs;
    }

    public function listAssocNames()
    {
        $out = [];

        foreach ($this->champs as $key => $config) {
            if ($key == 'passe') {
                continue;
            }

            $out[$key] = $config->title;
        }

        return $out;
    }

    public function getMultiples()
    {
        $out = [];

        foreach ($this->champs as $id => $champ) {
            if ($champ->type == 'multiple') {
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
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
599



600





601







602


603

604
605

606
607
608
609


610

611



612

613






614
615








616


617
618
619


620
621
622
623
624
625

626

627
628

629


630

631



632
633
634
635
636
637
638
639

640
641


642





643
644
645
646
647
648
649
650
651

652


653























654
655
656
657
658
659
660
661
662
663
        }

        $this->champs = $champs;

        return true;
    }

    /**
     * Enregistre les changements de champs en base de données
     * @param  boolean $enable_copy Recopier les anciennes champs dans les nouveaux ?
     * @return boolean true
     */
    public function save($enable_copy = true)
    {
        $db = DB::getInstance();
        $config = Config::getInstance();

        // Champs à créer
        $create = [
            'id INTEGER PRIMARY KEY, -- Numéro attribué automatiquement',
            'id_categorie INTEGER NOT NULL,',
            'date_connexion TEXT NULL CHECK (date_connexion IS NULL OR datetime(date_connexion) = date_connexion), -- Date de dernière connexion',
            'date_inscription TEXT NOT NULL DEFAULT CURRENT_DATE CHECK (date(date_inscription) IS NOT NULL AND date(date_inscription) = date_inscription), -- Date d\'inscription',
            'secret_otp TEXT NULL, -- Code secret pour TOTP',
            'clef_pgp TEXT NULL, -- Clé publique PGP'
        ];

        // Clés à créer, permet aussi de clôturer la syntaxe du tableau, noter l'absence de virgule dans cette ligne
        $create_keys = [
            'FOREIGN KEY (id_categorie) REFERENCES membres_categories (id)'
        ];

    	// Champs à recopier
    	$copy = [
    		'id' => 'id',
    		'id_categorie' => 'id_categorie',
            'date_connexion' => 'date_connexion',
            'date_inscription' => 'date_inscription',
    	];

        $anciens_champs = $config->get('champs_membres');
    	$anciens_champs = is_null($anciens_champs) ? $this->champs : $anciens_champs->getAll();

        if (property_exists($anciens_champs, 'secret_otp'))
        {
            $copy['secret_otp'] = 'secret_otp';
            $copy['clef_pgp'] = 'clef_pgp';
        }

    	foreach ($this->champs as $key=>$cfg)
    	{
    		if ($cfg->type == 'number' || $cfg->type == 'multiple' || $cfg->type == 'checkbox')
    			$type = 'INTEGER';
    		elseif ($cfg->type == 'file')
    			$type = 'BLOB';
    		else
    			$type = 'TEXT';

    		$line = sprintf('"%s" %s,', $key, $type);





            if (!empty($cfg->title))
            {
                $line .= ' -- ' . str_replace(["\n", "\r"], '', $cfg->title);
            }

            $create[] = $line;

    		if (property_exists($anciens_champs, $key))



    		{





    			$copy[$key] = $key;







    		}


            elseif ($key == 'numero')

            {
                // Copie des numéros de membre à partir du champ ID

                $copy[$key] = 'id';
            }
    	}



    	$create = array_merge($create, $create_keys);





    	$create = 'CREATE TABLE membres_tmp (' . "\n\t" . implode("\n\t", $create) . "\n);";

    	$copy = 'INSERT INTO membres_tmp (' . implode(', ', array_keys($copy)) . ') SELECT ' . implode(', ', $copy) . ' FROM membres;';







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








    	$db->begin();


    	$db->exec($create);
    	
    	if ($enable_copy) {


    		$db->exec($copy);
    	}
    	
        $db->exec('DROP TABLE IF EXISTS membres;');
    	$db->exec('ALTER TABLE membres_tmp RENAME TO membres;');
        $db->exec('CREATE INDEX membres_id_categorie ON membres (id_categorie);'); // Index



        if ($config->get('champ_identifiant'))
        {

            // Mettre les champs identifiant vides à NULL pour pouvoir créer un index unique


            $db->exec('UPDATE membres SET '.$config->get('champ_identifiant').' = NULL 

                WHERE '.$config->get('champ_identifiant').' = "";');




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

        if (isset($this->champs->numero))
        {
            $db->exec('CREATE UNIQUE INDEX membres_numero ON membres (numero);');

        }



        // Création des index pour les champs affichés dans la liste des membres





        $listed_fields = array_keys((array) $this->getListedFields());
        foreach ($listed_fields as $field)
        {
            if ($field === $config->get('champ_identifiant'))
            {
                // Il y a déjà un index
                continue;
            }


            $db->exec('CREATE INDEX membres_liste_' . $field . ' ON membres (' . $field . ');');


        }
























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

    	$config->set('champs_membres', $this);
    	$config->save();

    	return true;
    }
}







<
<
<
<
<
|

|
|




|






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

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

|
>
>
>
>







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

|

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

>
>
|
>
|
>
>
>


|


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

|
<
|
<




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










549
550
551
552
553
554
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619

620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
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
684
685
686
687
688
689
690
691
692
693
694
695
696

697

698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
        }

        $this->champs = $champs;

        return true;
    }






    public function getSQLSchema(string $table_name = self::TABLE): string
    {
        $config = Config::getInstance();
        $db = DB::getInstance();

        // Champs à créer
        $create = [
            'id INTEGER PRIMARY KEY, -- Numéro attribué automatiquement',
            'id_category INTEGER NOT NULL REFERENCES users_categories(id),',
            'date_connexion TEXT NULL CHECK (date_connexion IS NULL OR datetime(date_connexion) = date_connexion), -- Date de dernière connexion',
            'date_inscription TEXT NOT NULL DEFAULT CURRENT_DATE CHECK (date(date_inscription) IS NOT NULL AND date(date_inscription) = date_inscription), -- Date d\'inscription',
            'secret_otp TEXT NULL, -- Code secret pour TOTP',
            'clef_pgp TEXT NULL, -- Clé publique PGP'
        ];





        end($this->champs);







        $last_one = key($this->champs);









        foreach ($this->champs as $key=>$cfg)
        {
            if ($cfg->type == 'number' || $cfg->type == 'multiple' || $cfg->type == 'checkbox')
                $type = 'INTEGER';
            elseif ($cfg->type == 'file')
                $type = 'BLOB';
            else
                $type = 'TEXT COLLATE NOCASE';

            $line = sprintf('%s %s', $db->quoteIdentifier($key), $type);

            if ($last_one != $key) {
                $line .= ',';
            }

            if (!empty($cfg->title))
            {
                $line .= ' -- ' . str_replace(["\n", "\r"], '', $cfg->title);
            }

            $create[] = $line;
        }

        $sql = sprintf("CREATE TABLE %s\n(\n\t%s\n);", $table_name, implode("\n\t", $create));
        return $sql;
    }

    public function getCopyFields(): array
    {
        $config = Config::getInstance();

        // Champs à recopier
        $copy = [
            'id'               => 'id',
            'id_category'      => 'id_category',
            'date_connexion'   => 'date_connexion',
            'date_inscription' => 'date_inscription',
            'secret_otp'       => 'secret_otp',
            'clef_pgp'         => 'clef_pgp',
        ];

        $anciens_champs = $config->get('champs_membres');
        $anciens_champs = is_null($anciens_champs) ? $this->champs : $anciens_champs->getAll();

        foreach ($this->champs as $key=>$cfg)
        {

            if (property_exists($anciens_champs, $key)) {
                $copy[$key] = $key;
            }
        }

        return $copy;
    }

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

        $db = DB::getInstance();

        return sprintf('INSERT INTO %s (%s) SELECT %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 = self::TABLE, array $fields = null): void
    {
        DB::getInstance()->exec($this->getSQLCopy($old_table_name, $new_table_name, $fields));
    }

    public function create(string $table_name = self::TABLE)
    {
        $db = DB::getInstance();
        $db->begin();
        $this->createTable($table_name);
        $this->createIndexes($table_name);
        $db->commit();
    }

    public function createTable(string $table_name = self::TABLE): void
    {
        DB::getInstance()->exec($this->getSQLSchema($table_name));
    }




    public function createIndexes(string $table_name = self::TABLE): void
    {
        $db = DB::getInstance();
        $config = Config::getInstance();

        if ($id_field = $config->get('champ_identifiant')) {
            // Mettre les champs identifiant vides à NULL pour pouvoir créer un index unique
            $db->exec(sprintf('UPDATE %s SET %s = NULL WHERE %2$s = \'\';',
                $table_name, $id_field));

            $collation = '';

            if ($this->isText($id_field)) {
                $collation = ' COLLATE NOCASE';
            }

            // Création de l'index unique
            $db->exec(sprintf('CREATE UNIQUE INDEX users_id_field ON %s (%s%s);', $table_name, $id_field, $collation));
        }



        $db->exec(sprintf('CREATE UNIQUE INDEX user_number ON %s (numero);', $table_name));
        $db->exec(sprintf('CREATE INDEX users_category ON %s (id_category);', $table_name));

        // Create index on listed columns
        // FIXME: these indexes are currently unused by SQLite in the default user list
        // when there is more than one non-hidden category, as this makes SQLite merge multiple results
        // and so the index is not useful in that case sadly.
        // EXPLAIN QUERY PLAN SELECT * FROM membres WHERE "id_category" IN (3) ORDER BY "nom" ASC LIMIT 0,100;
        // --> SEARCH TABLE membres USING INDEX users_list_nom (id_category=?)
        // EXPLAIN QUERY PLAN SELECT * FROM membres WHERE "id_category" IN (3, 7) ORDER BY "nom" ASC LIMIT 0,100;
        // --> SEARCH TABLE membres USING INDEX user_category (id_category=?)
        // USE TEMP B-TREE FOR ORDER BY
        $listed_fields = array_keys((array) $this->getListedFields());
        foreach ($listed_fields as $field) {

            if ($field === $config->get('champ_identifiant')) {

                // Il y a déjà un index
                continue;
            }

            $collation = '';

            if ($this->isText($field)) {
                $collation = ' COLLATE NOCASE';
            }

            $db->exec(sprintf('CREATE INDEX users_list_%s ON %s (id_category, %1$s%s);', $field, $table_name, $collation));
        }
    }

    /**
     * Enregistre les changements de champs en base de données
     * @return boolean true
     */
    public function save()
    {
        $db = DB::getInstance();
        $config = Config::getInstance();

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

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

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

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

    	$config->set('champs_membres', $this);
    	$config->save();

    	return true;
    }
}

Modified src/include/lib/Garradin/Membres/Import.php from [807575f8f7] to [2afb2583d8].

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
		$membres = new Membres;

		// On récupère les champs qu'on peut importer
		$champs_membres = Config::getInstance()->get('champs_membres');
		$champs_multiples = $champs_membres->getMultiples();
		$champs = $champs_membres->getKeys();
		$champs[] = 'date_inscription';
		//$champs[] = 'date_connexion';
		//$champs[] = 'id';
		//$champs[] = 'id_categorie';

		$line = 0;
		$delim = CSV::findDelimiter($fp);
		CSV::skipBOM($fp);

		while (!feof($fp))
		{







<
<
<







86
87
88
89
90
91
92



93
94
95
96
97
98
99
		$membres = new Membres;

		// On récupère les champs qu'on peut importer
		$champs_membres = Config::getInstance()->get('champs_membres');
		$champs_multiples = $champs_membres->getMultiples();
		$champs = $champs_membres->getKeys();
		$champs[] = 'date_inscription';




		$line = 0;
		$delim = CSV::findDelimiter($fp);
		CSV::skipBOM($fp);

		while (!feof($fp))
		{
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
			$list = array_map('intval', $list);
			$where = sprintf('WHERE m.%s', $db->where('id', $list));
		}
		else {
			$where = '';
		}

		$sql = sprintf('SELECT %s, c.nom AS "Catégorie membre" FROM membres AS m
			INNER JOIN membres_categories AS c ON m.id_categorie = c.id
			%s ORDER BY c.id;', $fields, $where);

		$res = $db->iterate($sql);

		return [
			array_keys((array) $res->current()),
			$res,







|
|







212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
			$list = array_map('intval', $list);
			$where = sprintf('WHERE m.%s', $db->where('id', $list));
		}
		else {
			$where = '';
		}

		$sql = sprintf('SELECT %s, c.name AS "Catégorie membre" FROM membres AS m
			INNER JOIN users_categories AS c ON m.id_category = c.id
			%s ORDER BY c.id;', $fields, $where);

		$res = $db->iterate($sql);

		return [
			array_keys((array) $res->current()),
			$res,

Modified src/include/lib/Garradin/Membres/Session.php from [dd76dcbfbe] to [08959104e6].

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
use KD2\Security;
use KD2\Security_OTP;
use KD2\Graphics\QRCode;
use KD2\HTTP;

class Session extends \KD2\UserSession
{













	// Personalisation de la config de UserSession
	protected $cookie_name = 'gdin';
	protected $remember_me_cookie_name = 'gdinp';
	protected $remember_me_expiry = '+3 months';

	const MINIMUM_PASSWORD_LENGTH = 8;




























	static public function checkPasswordValidity($password)
	{
		if (strlen($password) < self::MINIMUM_PASSWORD_LENGTH)
		{
			throw new UserException(sprintf('Le mot de passe doit faire au moins %d caractères.', self::MINIMUM_PASSWORD_LENGTH));
		}

		$session = new Session();
		$session->http = new HTTP;

		if ($session->isPasswordCompromised($password)) {
			throw new UserException('Ce mot de passe figure dans une liste de mots de passe compromis. Si vous l\'avez utilisé sur d\'autres sites il est recommandé de le changer sur ces autres sites également.');
		}
	}

	public function isPasswordCompromised($password)
	{
		// Vérifier s'il n'y a pas un plugin qui gère déjà cet aspect
		// notamment en installation mutualisée c'est plus efficace
		$return = ['is_compromised' => null];
		$called = Plugin::fireSignal('motdepasse.compromis', ['password' => $password], $return);

		if ($called !== null) {
			return $return['is_compromised'];
		}

		return parent::isPasswordCompromised($password);
	}

	// Extension des méthodes de UserSession
	public function __construct()
	{
		$url = parse_url(ADMIN_URL);

		parent::__construct(DB::getInstance(), [
			'cookie_domain' => $url['host'],
			'cookie_path'   => preg_replace('!/admin/$!', '/', $url['path']),
			'cookie_secure' => (\Garradin\PREFER_HTTPS >= 2) ? true : false,
		]);
	}

	protected function getUserForLogin($login)
	{
		$champ_id = Config::getInstance()->get('champ_identifiant');

		// Ne renvoie un membre que si celui-ci a le droit de se connecter
		$query = 'SELECT m.id, m.%1$s AS login, m.passe AS password, m.secret_otp AS otp_secret
			FROM membres AS m
			INNER JOIN membres_categories AS mc ON mc.id = m.id_categorie
			WHERE m.%1$s = ? COLLATE NOCASE AND mc.droit_connexion >= %2$d
			LIMIT 1;';

		$query = sprintf($query, $champ_id, Membres::DROIT_ACCES);

		return $this->db->first($query, $login);
	}

	protected function getUserDataForSession($id)
	{
		// Mettre à jour la date de connexion
		$this->db->preparedQuery('UPDATE membres SET date_connexion = datetime() WHERE id = ?;', [$id]);
		$config = Config::getInstance();

		return $this->db->first('SELECT m.*, m.'.$config->get('champ_identite').' AS identite,
			c.droit_connexion, c.droit_wiki, 
			c.droit_membres, c.droit_compta, c.droit_config, c.droit_membres
			FROM membres AS m
			INNER JOIN membres_categories AS c ON m.id_categorie = c.id
			WHERE m.id = ? LIMIT 1;', $id);
	}

	protected function storeRememberMeSelector($selector, $hash, $expiry, $user_id)
	{
		return $this->db->insert('membres_sessions', [
			'selecteur' => $selector,







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






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








|



|

















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







|
|


|











|
|

|







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
use KD2\Security;
use KD2\Security_OTP;
use KD2\Graphics\QRCode;
use KD2\HTTP;

class Session extends \KD2\UserSession
{
	const SECTION_WEB = 'web';
	const SECTION_DOCUMENTS = 'documents';
	const SECTION_USERS = 'users';
	const SECTION_ACCOUNTING = 'accounting';
	const SECTION_CONNECT = 'connect';
	const SECTION_CONFIG = 'config';
	const SECTION_SUBSCRIBE = 'subscribe';

	const ACCESS_NONE = 0;
	const ACCESS_READ = 1;
	const ACCESS_WRITE = 2;
	const ACCESS_ADMIN = 9;

	// Personalisation de la config de UserSession
	protected $cookie_name = 'gdin';
	protected $remember_me_cookie_name = 'gdinp';
	protected $remember_me_expiry = '+3 months';

	const MINIMUM_PASSWORD_LENGTH = 8;

	static protected $_instance = null;

	static public function getInstance()
	{
		return self::$_instance ?: self::$_instance = new self;
	}

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

	public function __construct()
	{
		if (self::$_instance !== null) {
			throw new \LogicException('Wrong call, use getInstance');
		}

		$url = parse_url(ADMIN_URL);

		parent::__construct(DB::getInstance(), [
			'cookie_domain' => $url['host'],
			'cookie_path'   => preg_replace('!/admin/$!', '/', $url['path']),
			'cookie_secure' => (\Garradin\PREFER_HTTPS >= 2) ? true : false,
		]);
	}

	static public function checkPasswordValidity($password)
	{
		if (strlen($password) < self::MINIMUM_PASSWORD_LENGTH)
		{
			throw new UserException(sprintf('Le mot de passe doit faire au moins %d caractères.', self::MINIMUM_PASSWORD_LENGTH));
		}

		$session = self::getInstance();
		$session->http = new HTTP;

		if ($session->isPasswordCompromised($password)) {
			throw new UserException('Ce mot de passe figure dans une liste de mots de passe compromis, il ne peut donc être utilisé ici. Si vous l\'avez utilisé sur d\'autres sites il est recommandé de le changer sur ces autres sites également.');
		}
	}

	public function isPasswordCompromised($password)
	{
		// Vérifier s'il n'y a pas un plugin qui gère déjà cet aspect
		// notamment en installation mutualisée c'est plus efficace
		$return = ['is_compromised' => null];
		$called = Plugin::fireSignal('motdepasse.compromis', ['password' => $password], $return);

		if ($called !== null) {
			return $return['is_compromised'];
		}

		return parent::isPasswordCompromised($password);
	}













	protected function getUserForLogin($login)
	{
		$champ_id = Config::getInstance()->get('champ_identifiant');

		// Ne renvoie un membre que si celui-ci a le droit de se connecter
		$query = 'SELECT m.id, m.%1$s AS login, m.passe AS password, m.secret_otp AS otp_secret
			FROM membres AS m
			INNER JOIN users_categories AS c ON c.id = m.id_category
			WHERE m.%1$s = ? COLLATE NOCASE AND c.perm_connect >= %2$d
			LIMIT 1;';

		$query = sprintf($query, $champ_id, self::ACCESS_READ);

		return $this->db->first($query, $login);
	}

	protected function getUserDataForSession($id)
	{
		// Mettre à jour la date de connexion
		$this->db->preparedQuery('UPDATE membres SET date_connexion = datetime() WHERE id = ?;', [$id]);
		$config = Config::getInstance();

		return $this->db->first('SELECT m.*, m.'.$config->get('champ_identite').' AS identite,
			c.perm_connect, c.perm_web, c.perm_users, c.perm_documents,
			c.perm_subscribe, c.perm_accounting, c.perm_config
			FROM membres AS m
			INNER JOIN users_categories AS c ON m.id_category = c.id
			WHERE m.id = ? LIMIT 1;', $id);
	}

	protected function storeRememberMeSelector($selector, $hash, $expiry, $user_id)
	{
		return $this->db->insert('membres_sessions', [
			'selecteur' => $selector,
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

	protected function deleteAllRememberMeSelectors($user_id)
	{
		return $this->db->delete('membres_sessions', $this->db->where('id_membre', $user_id));
	}

	// Ajout de la gestion de LOCAL_LOGIN
	public function isLogged($disable_local_login = false)
	{
		$logged = parent::isLogged();

		if (!$disable_local_login && defined('\Garradin\LOCAL_LOGIN'))
		{
			$login_id = \Garradin\LOCAL_LOGIN;

			// On va chercher le premier membre avec le droit de gérer la config
			if (-1 === $login_id) {
				$login_id = $this->db->firstColumn('SELECT id FROM membres
					WHERE id_categorie IN (SELECT id FROM membres_categories WHERE droit_config = ?)
					LIMIT 1', Membres::DROIT_ADMIN);
			}

			if ($login_id > 0 && (!$logged || ($logged && $this->user->id != $login_id)))
			{
				$logged = $this->create($login_id);
			}
		}

		return $logged;
	}






	// Ici checkOTP utilise NTP en second recours
	public function checkOTP($secret, $code)
	{
		if (Security_OTP::TOTP($secret, $code))
		{
			return true;







|










|
|










>
>
>
>
>







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

	protected function deleteAllRememberMeSelectors($user_id)
	{
		return $this->db->delete('membres_sessions', $this->db->where('id_membre', $user_id));
	}

	// Ajout de la gestion de LOCAL_LOGIN
	public function isLogged(bool $disable_local_login = false)
	{
		$logged = parent::isLogged();

		if (!$disable_local_login && defined('\Garradin\LOCAL_LOGIN'))
		{
			$login_id = \Garradin\LOCAL_LOGIN;

			// On va chercher le premier membre avec le droit de gérer la config
			if (-1 === $login_id) {
				$login_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);
			}

			if ($login_id > 0 && (!$logged || ($logged && $this->user->id != $login_id)))
			{
				$logged = $this->create($login_id);
			}
		}

		return $logged;
	}

	public function forceLogin(int $id)
	{
		return $this->create($id);
	}

	// Ici checkOTP utilise NTP en second recours
	public function checkOTP($secret, $code)
	{
		if (Security_OTP::TOTP($secret, $code))
		{
			return true;
300
301
302
303
304
305
306













307
308
309
310
311
312
313
314



315
316
317
318
319
320
321
322
	public function editUser($data)
	{
		(new Membres)->edit($this->user->id, $data, false);
		$this->refresh(false);

		return true;
	}














	public function canAccess($category, $permission)
	{
		if (!$this->user)
		{
			return false;
		}




		return ($this->user->{'droit_' . $category} >= $permission);
	}

	public function requireAccess($category, $permission)
	{
		if (!$this->canAccess($category, $permission))
		{
			throw new UserException('Vous n\'avez pas le droit d\'accéder à cette page.');







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



|




>
>
>
|







333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
	public function editUser($data)
	{
		(new Membres)->edit($this->user->id, $data, false);
		$this->refresh(false);

		return true;
	}

	public function getUser()
	{
		$user = parent::getUser();

		// Force refresh of session when it's too old (FIXME: remove at version 1.2+)
		if (!property_exists($this->user, 'perm_users')) {
			$this->refresh();
			$user = $this->getUser();
		}

		return $user;
	}

	public function canAccess($category, $permission)
	{
		if (!$this->getUser())
		{
			return false;
		}

		$perm_name = 'perm_' . $category;
		$perm = $this->getUser()->$perm_name;

		return ($perm >= $permission);
	}

	public function requireAccess($category, $permission)
	{
		if (!$this->canAccess($category, $permission))
		{
			throw new UserException('Vous n\'avez pas le droit d\'accéder à cette page.');

Modified src/include/lib/Garradin/Plugin.php from [5aa9774a1a] to [1f8c21a59a].

1
2
3
4


5
6
7
8
9
10
11
<?php

namespace Garradin;



class Plugin
{
	const PLUGIN_ID_SYNTAX = '[a-z]+(?:_[a-z]+)*';

	protected $id = null;
	protected $plugin = null;
	protected $config_changed = false;




>
>







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

namespace Garradin;

use Garradin\Membres\Session;

class Plugin
{
	const PLUGIN_ID_SYNTAX = '[a-z]+(?:_[a-z]+)*';

	protected $id = null;
	protected $plugin = null;
	protected $config_changed = false;
431
432
433
434
435
436
437
438
439
440
441
442
443




















444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464


465

466
467



468
469
470
471
472
473
474
		return true;
	}

	/**
	 * Liste les plugins qui doivent être affichés dans le menu
	 * @return array Tableau associatif id => nom (ou un tableau vide si aucun plugin ne doit être affiché)
	 */
	static public function listMenu($user)
	{
		self::checkAndInstallSystemPlugins();

		$db = DB::getInstance();
		$list = $db->getGrouped('SELECT id, nom, menu_condition FROM plugins WHERE menu = 1 ORDER BY nom;');





















		foreach ($list as $id => &$row)
		{
			if (!self::getPath($row->id, false))
			{
				// Ne pas lister les plugins dont le code a disparu
				unset($list[$id]);
				continue;
			}

			if (!$row->menu_condition)
			{
				$row = $row->nom;
				continue;
			}

			$condition = strtr($row->menu_condition, [
				'{Membres::DROIT_AUCUN}' => Membres::DROIT_AUCUN,
				'{Membres::DROIT_ACCES}' => Membres::DROIT_ACCES,
				'{Membres::DROIT_ECRITURE}' => Membres::DROIT_ECRITURE,
				'{Membres::DROIT_ADMIN}' => Membres::DROIT_ADMIN,


			]);


			$condition = preg_replace_callback('/\{\$user\.(\w+)\}/', function ($m) use ($user) { return $user->{$m[1]}; }, $condition);



			$query = 'SELECT 1 WHERE ' . $condition . ';';

			$res = $db->protectSelect(['membres' => []], $query);

			if (!$db->firstColumn($query))
			{
				unset($list[$id]);







|





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
















|
|
|
|
|
>
>
|
>

|
>
>
>







433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
		return true;
	}

	/**
	 * Liste les plugins qui doivent être affichés dans le menu
	 * @return array Tableau associatif id => nom (ou un tableau vide si aucun plugin ne doit être affiché)
	 */
	static public function listMenu(Session $session)
	{
		self::checkAndInstallSystemPlugins();

		$db = DB::getInstance();
		$list = $db->getGrouped('SELECT id, nom, menu_condition FROM plugins WHERE menu = 1 ORDER BY nom;');

		// FIXME deprecated
		$fix_legacy = [
			'{Membres::DROIT_AUCUN}' => '{ACCESS_NONE}',
			'{Membres::DROIT_ACCES}' => '{ACCESS_READ}',
			'{Membres::DROIT_ECRITURE}' => '{ACCESS_WRITE}',
			'{Membres::DROIT_ADMIN}' => '{ACCESS_ADMIN}',
			'{$user.droit_compta}' => '{$user.perm_accounting}',
			'{$user.droit_membres}' => '{$user.perm_users}',
			'{$user.droit_config}' => '{$user.perm_config}',
			'{$user.droit_wiki}' => '{$user.perm_documents}',
		];

		$user = $session->getUser();
		$permissions = [
			'{ACCESS_NONE}'  => $session::ACCESS_NONE,
			'{ACCESS_READ}'  => $session::ACCESS_READ,
			'{ACCESS_WRITE}' => $session::ACCESS_WRITE,
			'{ACCESS_ADMIN}' => $session::ACCESS_ADMIN,
		];

		foreach ($list as $id => &$row)
		{
			if (!self::getPath($row->id, false))
			{
				// Ne pas lister les plugins dont le code a disparu
				unset($list[$id]);
				continue;
			}

			if (!$row->menu_condition)
			{
				$row = $row->nom;
				continue;
			}

			$new_condition = strtr($row->menu_condition, $fix_legacy);

			// FIXME: legacy
			if ($new_condition != $row->menu_condition) {
				$db->update('plugins', ['menu_condition' => $new_condition], 'id = :id', ['id' => $id]);
				$row->menu_condition = $new_condition;
			}

			$condition = strtr($row->menu_condition, $permissions);

			$condition = preg_replace_callback('/\{\$user\.(\w+)\}/', function ($m) use ($user, $db) {
				return property_exists($user, $m[1]) ? $db->quote($user->{$m[1]}) : 'NULL';
			}, $condition);

			$query = 'SELECT 1 WHERE ' . $condition . ';';

			$res = $db->protectSelect(['membres' => []], $query);

			if (!$db->firstColumn($query))
			{
				unset($list[$id]);

Modified src/include/lib/Garradin/Recherche.php from [e91118fdd9] to [ee18756339].

222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
		$columns = [];
		$db = DB::getInstance();

		if ($target == 'membres')
		{
			$champs = Config::getInstance()->get('champs_membres');

			$columns['id_categorie'] = (object) [
					'textMatch'=> false,
					'label'    => 'Catégorie',
					'type'     => 'enum',
					'null'     => false,
					'values'   => $db->getAssoc('SELECT id, nom FROM membres_categories ORDER BY nom;'),
				];

			foreach ($champs->getList() as $champ => $config)
			{
				$column = (object) [
					'textMatch'=> $champs->isText($champ),
					'label'    => $config->title,







|




|







222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
		$columns = [];
		$db = DB::getInstance();

		if ($target == 'membres')
		{
			$champs = Config::getInstance()->get('champs_membres');

			$columns['id_category'] = (object) [
					'textMatch'=> false,
					'label'    => 'Catégorie',
					'type'     => 'enum',
					'null'     => false,
					'values'   => $db->getAssoc('SELECT id, name FROM users_categories ORDER BY name COLLATE NOCASE;'),
				];

			foreach ($champs->getList() as $champ => $config)
			{
				$column = (object) [
					'textMatch'=> $champs->isText($champ),
					'label'    => $config->title,
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
					// après avoir modifié les fiches de membres
					throw new UserException('Cette recherche fait référence à une colonne qui n\'existe pas : ' . $condition['column']);
				}

				$query_columns[] = $condition['column'];
				$column = $target_columns[$condition['column']];

				if ($column->textMatch == 'text' && !in_array($condition['operator'], $no_transform_operators))
				{
					$query = sprintf('transliterate_to_ascii(%s) COLLATE NOCASE %s', $db->quoteIdentifier($condition['column']), $condition['operator']);
				}
				else
				{
					$query = sprintf('%s %s', $db->quoteIdentifier($condition['column']), $condition['operator']);
				}

				$values = isset($condition['values']) ? $condition['values'] : [];

				$values = array_map(['Garradin\Utils', 'transliterateToAscii'], $values);

				if (!empty($column->originalType)) {
					if ($column->originalType == 'tel') {
						// Normaliser le numéro de téléphone
						$values = array_map(['Garradin\Utils', 'normalizePhoneNumber'], $values);
					}
					elseif ($column->originalType == 'money') {
						$values = array_map(['Garradin\Utils', 'moneyToInteger'], $values);







<
<
<
<
<
<
|
<



<
<







450
451
452
453
454
455
456






457

458
459
460


461
462
463
464
465
466
467
					// après avoir modifié les fiches de membres
					throw new UserException('Cette recherche fait référence à une colonne qui n\'existe pas : ' . $condition['column']);
				}

				$query_columns[] = $condition['column'];
				$column = $target_columns[$condition['column']];







				$query = sprintf('%s %s', $db->quoteIdentifier($condition['column']), $condition['operator']);


				$values = isset($condition['values']) ? $condition['values'] : [];



				if (!empty($column->originalType)) {
					if ($column->originalType == 'tel') {
						// Normaliser le numéro de téléphone
						$values = array_map(['Garradin\Utils', 'normalizePhoneNumber'], $values);
					}
					elseif ($column->originalType == 'money') {
						$values = array_map(['Garradin\Utils', 'moneyToInteger'], $values);
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
			$query_columns = array_merge(['t.id', 't.date', 't.label', 'l.debit', 'l.credit', 'a.code'], $query_columns);
		}

		$query_columns[] = $order;

		if ($target_columns[$order]->textMatch)
		{
			$order = sprintf('transliterate_to_ascii(%s) COLLATE NOCASE', $db->quoteIdentifier($order));
		}
		else
		{
			$order = $db->quoteIdentifier($order);
		}

		$query_columns = array_unique($query_columns);







|







536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
			$query_columns = array_merge(['t.id', 't.date', 't.label', 'l.debit', 'l.credit', 'a.code'], $query_columns);
		}

		$query_columns[] = $order;

		if ($target_columns[$order]->textMatch)
		{
			$order = sprintf('%s COLLATE NOCASE', $db->quoteIdentifier($order));
		}
		else
		{
			$order = $db->quoteIdentifier($order);
		}

		$query_columns = array_unique($query_columns);
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
			$query .= ' LIMIT 100';
		}

		try {
			$db = DB::getInstance();
			static $allowed = [
				'compta' => ['acc_transactions' => null, 'acc_transactions_lines' => null, 'acc_accounts' => null, 'acc_charts' => null, 'acc_years' => null, 'acc_transactions_users' => null],
				'membres' => ['membres' => null, 'membres_categories' => null],
			];

			if ($unprotected) {
				$allowed_tables = null;
			}
			else {
				$allowed_tables = $allowed[$target];







|







623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
			$query .= ' LIMIT 100';
		}

		try {
			$db = DB::getInstance();
			static $allowed = [
				'compta' => ['acc_transactions' => null, 'acc_transactions_lines' => null, 'acc_accounts' => null, 'acc_charts' => null, 'acc_years' => null, 'acc_transactions_users' => null],
				'membres' => ['membres' => null, 'users_categories' => null],
			];

			if ($unprotected) {
				$allowed_tables = null;
			}
			else {
				$allowed_tables = $allowed[$target];
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
	public function schema(string $target)
	{
		$db = DB::getInstance();

		if ($target == 'membres') {
			$tables = [
				'membres'    => $db->firstColumn('SELECT sql FROM sqlite_master WHERE type = \'table\' AND name = \'membres\';'),
				'categories' => $db->firstColumn('SELECT sql FROM sqlite_master WHERE type = \'table\' AND name = \'membres_categories\';'),
			];
		}
		elseif ($target == 'compta') {
			$tables = [
				'acc_transactions'       => $db->firstColumn('SELECT sql FROM sqlite_master WHERE type = \'table\' AND name = \'acc_transactions\';'),
				'acc_transactions_lines' => $db->firstColumn('SELECT sql FROM sqlite_master WHERE type = \'table\' AND name = \'acc_transactions_lines\';'),
			];







|







698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
	public function schema(string $target)
	{
		$db = DB::getInstance();

		if ($target == 'membres') {
			$tables = [
				'membres'    => $db->firstColumn('SELECT sql FROM sqlite_master WHERE type = \'table\' AND name = \'membres\';'),
				'users_categories' => $db->firstColumn('SELECT sql FROM sqlite_master WHERE type = \'table\' AND name = \'users_categories\';'),
			];
		}
		elseif ($target == 'compta') {
			$tables = [
				'acc_transactions'       => $db->firstColumn('SELECT sql FROM sqlite_master WHERE type = \'table\' AND name = \'acc_transactions\';'),
				'acc_transactions_lines' => $db->firstColumn('SELECT sql FROM sqlite_master WHERE type = \'table\' AND name = \'acc_transactions_lines\';'),
			];

Modified src/include/lib/Garradin/Sauvegarde.php from [d455e0ab72] to [df94c55305].

1
2
3
4





5
6
7
8
9
10
11
<?php

namespace Garradin;






class Sauvegarde
{
	const NEED_UPGRADE = 0x01 << 2;
	const NOT_AN_ADMIN = 0x01 << 3;

	const INTEGRITY_FAIL = 41;
	const NOT_A_DB = 42;




>
>
>
>
>







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

namespace Garradin;

use Garradin\Membres\Session;
use Garradin\Files\Files;

use KD2\ZipWriter;

class Sauvegarde
{
	const NEED_UPGRADE = 0x01 << 2;
	const NOT_AN_ADMIN = 0x01 << 3;

	const INTEGRITY_FAIL = 41;
	const NOT_A_DB = 42;
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

			// Skip non-auto files
			if ($auto_only && !$auto) {
				continue;
			}

			$db = new \SQLite3(DATA_ROOT . '/' . $file, \SQLITE3_OPEN_READONLY);
			$version = $db->querySingle('SELECT valeur FROM config WHERE cle = \'version\';');

			$db->close();

			$out[$file] = (object) [
				'filename'    => $file,
				'date'        => filemtime(DATA_ROOT . '/' . $file),
				'name'        => $name != $file ? $name : null,
				'version'     => $version,







<
|







59
60
61
62
63
64
65

66
67
68
69
70
71
72
73

			// Skip non-auto files
			if ($auto_only && !$auto) {
				continue;
			}

			$db = new \SQLite3(DATA_ROOT . '/' . $file, \SQLITE3_OPEN_READONLY);

			$version = DB::getVersion($db);
			$db->close();

			$out[$file] = (object) [
				'filename'    => $file,
				'date'        => filemtime(DATA_ROOT . '/' . $file),
				'name'        => $name != $file ? $name : null,
				'version'     => $version,
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

	/**
	 * Crée une nouvelle sauvegarde
	 * @param  boolean $auto Si true le nom de fichier sera celui de la sauvegarde automatique courante,
	 * sinon le nom sera basé sur la date (sauvegarde manuelle)
	 * @return string Le nom de fichier de la sauvegarde ainsi créée
	 */
	public function create(bool $auto = false, ?string $dest = null): string
	{
		$suffix = is_string($auto) ? $auto : ($auto ? 'auto.1' : date('Y-m-d-His'));

		$backup = str_replace('.sqlite', sprintf('.%s.sqlite', $suffix), DB_FILE);

		$this->make($backup);

		return basename($backup);
	}







|

|







89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

	/**
	 * Crée une nouvelle sauvegarde
	 * @param  boolean $auto Si true le nom de fichier sera celui de la sauvegarde automatique courante,
	 * sinon le nom sera basé sur la date (sauvegarde manuelle)
	 * @return string Le nom de fichier de la sauvegarde ainsi créée
	 */
	public function create(bool $auto = false, ?string $name = null): string
	{
		$suffix = $name ?? ($auto ? 'auto.1' : date('Y-m-d-His'));

		$backup = str_replace('.sqlite', sprintf('.%s.sqlite', $suffix), DB_FILE);

		$this->make($backup);

		return basename($backup);
	}
215
216
217
218
219
220
221

222
223
224
225
226
227
228

	/**
	 * Renvoie sur la sortie courante le contenu du fichier de base de données sélectionné ou courant
	 */
	public function dump(?string $file = null): void
	{
		$config = Config::getInstance();


		if (null === $file) {
			$file = DB_FILE;
			$name = sprintf('%s - Sauvegarde données - %s.sqlite', $config->get('nom_asso'), date('Y-m-d'));

			$tmp_file = tempnam(sys_get_temp_dir(), 'gdin');
			$this->make($tmp_file);







>







219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

	/**
	 * Renvoie sur la sortie courante le contenu du fichier de base de données sélectionné ou courant
	 */
	public function dump(?string $file = null): void
	{
		$config = Config::getInstance();
		$tmp_file = null;

		if (null === $file) {
			$file = DB_FILE;
			$name = sprintf('%s - Sauvegarde données - %s.sqlite', $config->get('nom_asso'), date('Y-m-d'));

			$tmp_file = tempnam(sys_get_temp_dir(), 'gdin');
			$this->make($tmp_file);
249
250
251
252
253
254
255

256

























257
258
259
260
261
262
263
		header(sprintf('Content-Length: %d', filesize($file) + $hash_length));

		readfile($file);

		// Add integrity hash
		echo sha1_file($file);


		@unlink($tmp_file);

























	}

	/**
	 * Restaure une sauvegarde locale
	 * @param  string $file Le nom de fichier à utiliser comme point de restauration
	 * @return boolean true si la restauration a fonctionné, false sinon
	 */







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







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
		header(sprintf('Content-Length: %d', filesize($file) + $hash_length));

		readfile($file);

		// Add integrity hash
		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) {
			foreach (Files::list($path) as $file) {
				if ($file->type == $file::TYPE_DIRECTORY) {
					$add_directory($file->path);
				}
				else {
					$zip->add($file->path, null, $file->fullpath());
				}
			}
		};

		$add_directory('');
		$zip->close();
	}

	/**
	 * Restaure une sauvegarde locale
	 * @param  string $file Le nom de fichier à utiliser comme point de restauration
	 * @return boolean true si la restauration a fonctionné, false sinon
	 */
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450

		if (!$table)
		{
			throw new UserException('Le fichier fourni ne semble pas contenir de données liées à Garradin.');
		}

		// On récupère la version
		$version = $db->querySingle('SELECT valeur FROM config WHERE cle=\'version\';');

		// On ne permet pas de restaurer une vieille version
		if (version_compare($version, Upgrade::MIN_REQUIRED_VERSION, '<'))
		{
			throw new UserException(sprintf('Ce fichier a été créé avec une version trop ancienne (%s), il n\'est pas possible de le restaurer.', $version));
		}

		// Vérification de l'AppID
		$appid = $db->querySingle('PRAGMA application_id;', false);

		if ($appid !== DB::APPID)
		{
			throw new UserException('Ce fichier n\'est pas une sauvegarde Garradin (application_id ne correspond pas).', self::NO_APP_ID);
		}

		if ($user_id)
		{
			// Empêchons l'admin de se tirer une balle dans le pied
			$is_still_admin = $db->querySingle('SELECT 1 FROM membres_categories
				WHERE id = (SELECT id_categorie FROM membres WHERE id = ' . (int) $user_id . ')
				AND droit_config >= ' . Membres::DROIT_ADMIN . '
				AND droit_connexion >= ' . Membres::DROIT_ACCES);

			if (!$is_still_admin)
			{
				$return |= self::NOT_AN_ADMIN;
			}
		}








|


















|
|
|
|







445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481

		if (!$table)
		{
			throw new UserException('Le fichier fourni ne semble pas contenir de données liées à Garradin.');
		}

		// On récupère la version
		$version = DB::getVersion($db);

		// On ne permet pas de restaurer une vieille version
		if (version_compare($version, Upgrade::MIN_REQUIRED_VERSION, '<'))
		{
			throw new UserException(sprintf('Ce fichier a été créé avec une version trop ancienne (%s), il n\'est pas possible de le restaurer.', $version));
		}

		// Vérification de l'AppID
		$appid = $db->querySingle('PRAGMA application_id;', false);

		if ($appid !== DB::APPID)
		{
			throw new UserException('Ce fichier n\'est pas une sauvegarde Garradin (application_id ne correspond pas).', self::NO_APP_ID);
		}

		if ($user_id)
		{
			// Empêchons l'admin de se tirer une balle dans le pied
			$is_still_admin = $db->querySingle('SELECT 1 FROM users_categories
				WHERE id = (SELECT id_category FROM membres WHERE id = ' . (int) $user_id . ')
				AND perm_config >= ' . Session::ACCESS_ADMIN . '
				AND perm_connect >= ' . Session::ACCESS_READ);

			if (!$is_still_admin)
			{
				$return |= self::NOT_AN_ADMIN;
			}
		}

468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484

		unlink($backup);

		if ($return & self::NOT_AN_ADMIN)
		{
			// Forcer toutes les catégories à pouvoir gérer les droits
			$db = DB::getInstance();
			$db->update('membres_categories', [
				'droit_membres' => Membres::DROIT_ADMIN,
				'droit_connexion' => Membres::DROIT_ACCES
			]);
		}

		if ($version != garradin_version())
		{
			$return |= self::NEED_UPGRADE;
		}







|
|
|







499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515

		unlink($backup);

		if ($return & self::NOT_AN_ADMIN)
		{
			// Forcer toutes les catégories à pouvoir gérer les droits
			$db = DB::getInstance();
			$db->update('users_categories', [
				'perm_users' => Session::ACCESS_ADMIN,
				'perm_connect' => Session::ACCESS_READ
			]);
		}

		if ($version != garradin_version())
		{
			$return |= self::NEED_UPGRADE;
		}
505
506
507
508
509
510
511
512
513
514
	/**
	 * Taille occupée par les fichiers dans la base de données
	 * @return integer Taille en octets
	 */
	public function getDBFilesSize()
	{
		$db = DB::getInstance();
		return (int) $db->firstColumn('SELECT SUM(taille) FROM fichiers_contenu;');
	}
}







|


536
537
538
539
540
541
542
543
544
545
	/**
	 * Taille occupée par les fichiers dans la base de données
	 * @return integer Taille en octets
	 */
	public function getDBFilesSize()
	{
		$db = DB::getInstance();
		return (int) $db->firstColumn('SELECT SUM(size) FROM files;');
	}
}

Modified src/include/lib/Garradin/Services/Fees.php from [5a3f0428c1] to [98acb50ff8].

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

namespace Garradin\Services;

use Garradin\Config;
use Garradin\DB;
use Garradin\Membres\Categories;
use Garradin\Entities\Services\Fee;
use Garradin\Entities\Accounting\Year;
use KD2\DB\EntityManager;

class Fees
{
	protected $service_id;






|







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

namespace Garradin\Services;

use Garradin\Config;
use Garradin\DB;
use Garradin\Users\Categories;
use Garradin\Entities\Services\Fee;
use Garradin\Entities\Accounting\Year;
use KD2\DB\EntityManager;

class Fees
{
	protected $service_id;
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

		return $result;
	}

	public function listWithStats()
	{
		$db = DB::getInstance();
		$hidden_cats = array_keys((new Categories)->listHidden());

		$condition = sprintf('SELECT COUNT(DISTINCT su.id_user) FROM services_users su
			INNER JOIN (SELECT id, MAX(date) FROM services_users GROUP BY id_user, id_fee) su2 ON su2.id = su.id
			INNER JOIN membres m ON m.id = su.id_user WHERE su.id_fee = f.id AND m.id_categorie NOT IN (%s)',
			implode(',', $hidden_cats));

		$sql = sprintf('SELECT f.*,
			(%s AND (expiry_date IS NULL OR expiry_date >= date()) AND paid = 1) AS nb_users_ok,
			(%1$s AND expiry_date < date()) AS nb_users_expired,
			(%1$s AND paid = 0) AS nb_users_unpaid
			FROM services_fees f
			WHERE id_service = ?
			ORDER BY amount, transliterate_to_ascii(label) COLLATE NOCASE;', $condition);

		return $db->get($sql, $this->service_id);
	}
}







|



|








|




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

		return $result;
	}

	public function listWithStats()
	{
		$db = DB::getInstance();
		$hidden_cats = array_keys(Categories::listHidden());

		$condition = sprintf('SELECT COUNT(DISTINCT su.id_user) FROM services_users su
			INNER JOIN (SELECT id, MAX(date) FROM services_users GROUP BY id_user, id_fee) su2 ON su2.id = su.id
			INNER JOIN membres m ON m.id = su.id_user WHERE su.id_fee = f.id AND m.id_category NOT IN (%s)',
			implode(',', $hidden_cats));

		$sql = sprintf('SELECT f.*,
			(%s AND (expiry_date IS NULL OR expiry_date >= date()) AND paid = 1) AS nb_users_ok,
			(%1$s AND expiry_date < date()) AS nb_users_expired,
			(%1$s AND paid = 0) AS nb_users_unpaid
			FROM services_fees f
			WHERE id_service = ?
			ORDER BY amount, label COLLATE NOCASE;', $condition);

		return $db->get($sql, $this->service_id);
	}
}

Modified src/include/lib/Garradin/Services/Reminders.php from [2eefb08a6c] to [a76c257944].

127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
			m.email, m.%s AS identity
			FROM services_users su
			INNER JOIN services s ON s.id = su.id_service
			INNER JOIN services_reminders sr ON sr.id_service = su.id_service
			-- Join with users, but not ones part of a hidden category
			INNER JOIN membres m ON su.id_user = m.id
				AND m.email IS NOT NULL
				AND (m.id_categorie NOT IN (SELECT id FROM membres_categories WHERE cacher = 1))
			-- Join with sent reminders to exclude users that already have received this reminder
			LEFT JOIN services_reminders_sent srs ON srs.id_reminder = sr.id AND srs.id_user = su.id_user
			WHERE
				date() > date(su.expiry_date, sr.delay || \' days\')
				AND srs.id IS NULL
			GROUP BY su.id_user, s.id
			ORDER BY su.id_user;';







|







127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
			m.email, m.%s AS identity
			FROM services_users su
			INNER JOIN services s ON s.id = su.id_service
			INNER JOIN services_reminders sr ON sr.id_service = su.id_service
			-- Join with users, but not ones part of a hidden category
			INNER JOIN membres m ON su.id_user = m.id
				AND m.email IS NOT NULL
				AND (m.id_category NOT IN (SELECT id FROM users_categories WHERE hidden = 1))
			-- Join with sent reminders to exclude users that already have received this reminder
			LEFT JOIN services_reminders_sent srs ON srs.id_reminder = sr.id AND srs.id_user = su.id_user
			WHERE
				date() > date(su.expiry_date, sr.delay || \' days\')
				AND srs.id IS NULL
			GROUP BY su.id_user, s.id
			ORDER BY su.id_user;';

Modified src/include/lib/Garradin/Services/Services.php from [99a3b0f3b3] to [b29aba829c].

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

namespace Garradin\Services;

use Garradin\Config;
use Garradin\DB;
use Garradin\Membres\Categories;
use Garradin\Entities\Services\Service;
use KD2\DB\EntityManager;

class Services
{
	static public function get(int $id)
	{






|







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

namespace Garradin\Services;

use Garradin\Config;
use Garradin\DB;
use Garradin\Users\Categories;
use Garradin\Entities\Services\Service;
use KD2\DB\EntityManager;

class Services
{
	static public function get(int $id)
	{
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

		return $out;
	}

	static public function listWithStats()
	{
		$db = DB::getInstance();
		$hidden_cats = array_keys((new Categories)->listHidden());

		$condition = sprintf('SELECT COUNT(DISTINCT su.id_user) FROM services_users su
			INNER JOIN (SELECT id, MAX(date) FROM services_users GROUP BY id_user, id_service) su2 ON su2.id = su.id
			INNER JOIN membres m ON m.id = su.id_user WHERE su.id_service = s.id AND m.id_categorie NOT IN (%s)',
			implode(',', $hidden_cats));

		$sql = sprintf('SELECT s.*,
			(%s AND (expiry_date IS NULL OR expiry_date >= date()) AND paid = 1) AS nb_users_ok,
			(%1$s AND expiry_date < date()) AS nb_users_expired,
			(%1$s AND paid = 0) AS nb_users_unpaid
			FROM services s
			ORDER BY transliterate_to_ascii(s.label) COLLATE NOCASE;', $condition);

		return $db->get($sql);
	}
}







|



|







|




51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

		return $out;
	}

	static public function listWithStats()
	{
		$db = DB::getInstance();
		$hidden_cats = array_keys(Categories::listHidden());

		$condition = sprintf('SELECT COUNT(DISTINCT su.id_user) FROM services_users su
			INNER JOIN (SELECT id, MAX(date) FROM services_users GROUP BY id_user, id_service) su2 ON su2.id = su.id
			INNER JOIN membres m ON m.id = su.id_user WHERE su.id_service = s.id AND m.id_category NOT IN (%s)',
			implode(',', $hidden_cats));

		$sql = sprintf('SELECT s.*,
			(%s AND (expiry_date IS NULL OR expiry_date >= date()) AND paid = 1) AS nb_users_ok,
			(%1$s AND expiry_date < date()) AS nb_users_expired,
			(%1$s AND paid = 0) AS nb_users_unpaid
			FROM services s
			ORDER BY s.label COLLATE NOCASE;', $condition);

		return $db->get($sql);
	}
}

Deleted src/include/lib/Garradin/Squelette.php version [1036393224].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
<?php

namespace Garradin;

class Squelette_Snippet
{
    const TEXT = 0;
    const PHP = 1;
    const GUESS = 2;
    const OBJ = 3;

    protected $_content = [];

    protected function _getType($type, $value)
    {
        if ($type == self::GUESS)
        {
            if ($value instanceof Squelette_Snippet)
                return self::OBJ;
            else
                return self::TEXT;
        }

        return $type;
    }

    public function __construct($type = self::TEXT, $value = '')
    {
        $type = $this->_getType($type, $value);

        if ($type == self::OBJ)
        {
            $this->_content = $value->get();
        }
        else
        {
            $this->_content[] = (string) (int) $type . $value;
        }

        unset($value);
    }

    public function prepend($type = self::TEXT, $value, $pos = false)
    {
        $type = $this->_getType($type, $value);

        if ($type == self::OBJ)
        {
            if ($pos)
            {
                array_splice($this->_content, $pos, 0, $value->get());
            }
            else
            {
                $this->_content = array_merge($value->get(), $this->_content);
            }
        }
        else
        {
            $value = (string) (int) $type . $value;

            if ($pos)
            {
                array_splice($this->_content, $pos, 0, $value);
            }
            else
            {
                array_unshift($this->_content, $value);
            }
        }

        unset($value);
    }

    public function append($type = self::TEXT, $value, $pos = false)
    {
        $type = $this->_getType($type, $value);

        if ($type == self::OBJ)
        {
            if ($pos)
            {
                array_splice($this->_content, $pos + 1, 0, $value->get());
            }
            else
            {
                $this->_content = array_merge($this->_content, $value->get());
            }
        }
        else
        {
            $value = (string) (int) $type . $value;

            if ($pos)
            {
                array_splice($this->_content, $pos + 1, 0, $value);
            }
            else
            {
                array_push($this->_content, $value);
            }
        }

        unset($value);
    }

    public function output($in_php = false)
    {
        $out = '';
        $php = $in_php ?: false;

        foreach ($this->_content as $line)
        {
            if ($line[0] == self::PHP && !$php)
            {
                $php = true;
                $out .= '<?php ';
            }
            elseif ($line[0] == self::TEXT && $php)
            {
                $php = false;
                $out .= ' ?>';
            }

            $out .= substr($line, 1);

            if ($line[0] == self::PHP)
            {
                $out .= "\n";
            }
        }

        if ($php && !$in_php)
        {
            $out .= ' ?>';
        }

        $this->_content = [];

        return $out;
    }

    public function __toString()
    {
        return $this->output(false);
    }

    public function get()
    {
        return $this->_content;
    }

    public function replace($key, $type = self::TEXT, $value)
    {
        $type = $this->_getType($type, $value);

        if ($type == self::OBJ)
        {
            array_splice($this->_content, $key, 1, $value->get());
        }
        else
        {
            $this->_content[$key] = (string) (int) $type . $value;
        }

        unset($value);
    }
}

class Squelette extends \KD2\MiniSkel
{
    private $parent = null;
    private $current = null;
    private $_vars = [];

    private function _registerDefaultModifiers()
    {
        foreach (Squelette_Filtres::$filtres_php as $func=>$name)
        {
            if (is_string($func))
                $this->register_modifier($name, $func);
            else
                $this->register_modifier($name, $name);
        }

        foreach (get_class_methods('Garradin\Squelette_Filtres') as $name)
        {
            $this->register_modifier($name, ['Garradin\Squelette_Filtres', $name]);
        }

        foreach (Squelette_Filtres::$filtres_alias as $name=>$func)
        {
            $this->register_modifier($name, ['Garradin\Squelette_Filtres', $func]);
        }

        if (file_exists(DATA_ROOT . '/www/squelettes/mes_filtres.php'))
        {
            require_once DATA_ROOT . '/www/squelettes/mes_filtres.php';
        }
    }

    private function _registerDefaultTags()
    {
        $config = Config::getInstance();

        $this->assign('nom_asso', $config->get('nom_asso'));
        $this->assign('adresse_asso', $config->get('adresse_asso'));
        $this->assign('email_asso', $config->get('email_asso'));
        $this->assign('site_asso', $config->get('site_asso'));

        $this->assign('url_racine', WWW_URL);
        $this->assign('url_site', WWW_URL);
        $this->assign('url_atom', WWW_URL . 'feed/atom/');
        $this->assign('url_elements', WWW_URL . 'squelettes/');
        $this->assign('url_admin', ADMIN_URL);

        $url = file_exists(DATA_ROOT . '/www/squelettes/default.css')
            ? WWW_URL . 'squelettes/default.css'
            : WWW_URL . 'squelettes-dist/default.css';

        $this->assign('url_css_defaut', $url);

        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
        {
            if (function_exists('locale_accept_from_http'))
            {
	           $lang = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
            }
            else
            {
                $lang = preg_replace('/[^a-z]/i', '', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
                $lang = strtolower(substr($lang, 0, 2));
            }

	        $lang = strtolower(substr($lang, 0, 2));
	    }
	    else
	    {
	    	$lang = '';
	    }

        $this->assign('langue_visiteur', $lang);
    }

    public function __construct()
    {
        $this->_registerDefaultModifiers();
        $this->_registerDefaultTags();
    }

    protected function processInclude($args)
    {
        if (empty($args))
            throw new \KD2\MiniSkelMarkupException("Le tag INCLURE demande à préciser le fichier à inclure.");

        $file = key($args);

        if (empty($file) || !preg_match('!^[\w\d_-]+(?:\.[\w\d_-]+)*$!', $file))
            throw new \KD2\MiniSkelMarkupException("INCLURE: le nom de fichier ne peut contenir que des caractères alphanumériques.");

        return new Squelette_Snippet(1, '$this->fetch("'.$file.'", false);');
    }

    protected function processVariable($name, $applyDefault, $modifiers, $pre, $post, $context)
    {
        if ($context == self::CONTEXT_IN_ARG)
        {
            $out = new Squelette_Snippet(1, '$this->getVariable(\''.$name.'\')');

            if ($pre)
            {
                $out->prepend(2, $pre);
            }

            if ($post)
            {
                $out->append(2, $post);
            }

            return $out;
        }

        $out = new Squelette_Snippet(1, '$value = $this->getVariable(\''.$name.'\');');

        // We process modifiers
        foreach ($modifiers as &$modifier)
        {
            if (!isset($this->modifiers[$modifier['name']]))
            {
                throw new \KD2\MiniSkelMarkupException('Filtre '.$modifier['name'].' inconnu !');
            }

            $out->append(1, '$value = call_user_func_array('.var_export($this->modifiers[$modifier['name']], true).', [$value, ');

            foreach ($modifier['arguments'] as $arg)
            {
                if ($arg == 'debut_liste')
                {
                    $out->append(1, '$this->getVariable(\'debut_liste\')');
                }
                elseif ($arg instanceOf Squelette_Snippet)
                {
                    $out->append(3, $arg);
                }
                else
                {
                    //if (preg_match('!getVariable!', $arg)) throw new Exception("lol");
                    $out->append(1, '"'.str_replace('"', '\\"', $arg).'"');
                }

                $out->append(1, ', ');
            }

            $out->append(1, ']);');

            if (in_array($modifier['name'], Squelette_Filtres::$desactiver_defaut))
            {
                $applyDefault = false;
            }
        }

        if ($applyDefault)
        {
            $out->append(1, 'if (is_string($value) && trim($value)) $value = htmlspecialchars($value, ENT_QUOTES, \'UTF-8\', false);');
        }

        $out->append(1, 'if ($value === true || trim($value) !== \'\'):');

        // Getting pre-content
        if ($pre)
        {
            $out->append(2, $pre);
        }

        $out->append(1, 'echo is_bool($value) ? "" : $value;');

        // Getting post-content
        if ($post)
        {
            $out->append(2, $post);
        }

        $out->append(1, 'endif;');

        return $out;
    }

    protected function processLoop($loopName, $loopType, $loopCriterias, $loopContent, $preContent, $postContent, $altContent)
    {
        $query = $loop_start = '';
        $query_args = [];
        $db = DB::getInstance();

        $statement_code = '';

        // Types de boucles natifs
        if ($loopType == 'articles' || $loopType == 'rubriques' || $loopType == 'pages')
        {
            $where = $order = '';
            $limit = $begin = 0;

            $query = 'SELECT w.*, ';
            $query.= 'strftime(\'%s\', w.date_creation) AS date_creation, ';
            $query.= 'strftime(\'%s\', w.date_modification) AS date_modification';

            if (trim($loopContent))
            {
                $query .= ', r.contenu AS texte FROM wiki_pages AS w LEFT JOIN wiki_revisions AS r ON (w.id = r.id_page AND w.revision = r.revision) ';
            }
            else
            {
                $query .= '\'\' AS texte FROM wiki_pages AS w ';
            }

            $where = 'WHERE w.droit_lecture = -1 ';

            if ($loopType == 'articles')
            {
                $where .= 'AND (SELECT COUNT(id) FROM wiki_pages WHERE parent = w.id AND droit_lecture = -1) = 0 ';
            }
            elseif ($loopType == 'rubriques')
            {
                $where .= 'AND (SELECT COUNT(id) FROM wiki_pages WHERE parent = w.id AND droit_lecture = -1) > 0 ';
            }

            $allowed_fields = ['id', 'uri', 'titre', 'date', 'date_creation', 'date_modification',
                'parent', 'rubrique', 'revision', 'points', 'recherche', 'texte', 'age'];
            $search = $search_rank = false;

            foreach ($loopCriterias as $criteria_id => $criteria)
            {
                if (isset($criteria['field']))
                {
                    if (!in_array($criteria['field'], $allowed_fields))
                    {
                        throw new \KD2\MiniSkelMarkupException("Critère '".$criteria['field']."' invalide pour la boucle ".$loopName." de type ".$loopType.".");
                    }
                    elseif ($criteria['field'] == 'rubrique')
                    {
                        $criteria['field'] = 'parent';
                    }
                    elseif ($criteria['field'] == 'date')
                    {
                        $criteria['field'] = 'date_creation';
                    }
                    elseif ($criteria['field'] == 'points')
                    {
                        if ($criteria['action'] != \KD2\MiniSkel::ACTION_ORDER_BY)
                        {
                            throw new \KD2\MiniSkelMarkupException("Le critère 'points' n\'est pas valide dans ce contexte.");
                        }

                        $search_rank = true;
                    }
                    elseif ($criteria['field'] == 'age')
                    {
                        $criteria['field'] = 'julianday() - julianday(date_creation)';
                        $criteria['value'] = (int)$criteria['value'];
                    }
                }

                switch ($criteria['action'])
                {
                    case \KD2\MiniSkel::ACTION_ORDER_BY:
                        if (!$order)
                            $order = 'ORDER BY '.$criteria['field'].'';
                        else
                            $order .= ', '.$criteria['field'].'';
                        break;
                    case \KD2\MiniSkel::ACTION_ORDER_DESC:
                        if ($order)
                            $order .= ' DESC';
                        break;
                    case \KD2\MiniSkel::ACTION_LIMIT:
                        $begin = $criteria['begin'];
                        $limit = $criteria['number'];
                        break;
                    case \KD2\MiniSkel::ACTION_MATCH_FIELD_BY_VALUE:
                        $where .= ' AND '.$criteria['field'].' '.$criteria['comparison'].' ?';
                        $query_args[] = $criteria['value'];
                        break;
                    case \KD2\MiniSkel::ACTION_MATCH_FIELD:
                    {
                        if ($criteria['field'] == 'recherche')
                        {
                            $query = 'SELECT w.*, r.contenu AS texte, rank(matchinfo(wiki_recherche), 0, 1.0, 1.0) AS points FROM wiki_pages AS w INNER JOIN wiki_recherche AS r ON (w.id = r.id) ';
                            $where .= ' AND wiki_recherche MATCH ?';
                            $search = true;
                        }
                        else
                        {
                            $where .= ' AND '.$criteria['field'].' = ?';

                            if ($criteria['field'] == 'parent')
                            {
                                $criteria['field'] = 'id';
                            }
                        }
                        
                        $query_args[] = ['$this->getVariable(\'' . $criteria['field'] . '\')'];
                        break;
                    }
                    default:
                        break;
                }
            }

            if ($search_rank && !$search)
            {
                throw new \KD2\MiniSkelMarkupException("Le critère par points n'est possible que dans les boucles de recherche.");
            }

            if (trim($loopContent))
            {
                $loop_start .= '$row[\'url\'] = WWW_URL . $row[\'uri\']; ';
            }

            $query .= $where . ' ' . $order;

            if (!$limit || $limit > 100)
                $limit = 100;

            if ($limit)
            {
                $query .= ' LIMIT ';

                if (is_numeric($begin))
                {
                    $query .= (int) $begin;
                }
                else
                {
                    $query .= '?';
                    $query_args[] = ['\'.$this->variables[\'debut_liste\'].\''];
                }
                
                $query .= ','.(int)$limit;
            }
        }
        else if ($loopType == 'documents' || $loopType == 'images' || $loopType == 'fichiers')
        {
            $where = $order = '';
            $limit = $begin = 0;

            $query = 'SELECT f.*, fc.hash, fc.taille, strftime(\'%s\', f.datetime) AS date ';
            $query.= ' FROM fichiers AS f INNER JOIN fichiers_contenu AS fc ON fc.id = f.id_contenu ';
            $query.= ' INNER JOIN fichiers_wiki_pages AS fwp ON fwp.fichier = f.id ';
            $query.= ' INNER JOIN wiki_pages AS w ON w.id = fwp.id AND w.droit_lecture = -1 ';
            $where = 'WHERE 1 ';

            $allowed_fields = ['id', 'nom', 'type', 'date', 'image', 'hash', 'taille',
                'parent', 'page', 'rubrique', 'article', 'sauf_mention'];

            if ($loopType == 'images')
            {
                $where .= ' AND image = 1 ';
            }
            else if ($loopType == 'documents')
            {
                $where .= ' AND image = 0 ';
            }

            foreach ($loopCriterias as $criteria_id => $criteria)
            {
                if (isset($criteria['field']))
                {
                    if (!in_array($criteria['field'], $allowed_fields))
                    {
                        throw new \KD2\MiniSkelMarkupException("Critère '".$criteria['field']."' invalide pour la boucle ".$loopName." de type ".$loopType.".");
                    }
                    elseif ($criteria['field'] == 'rubrique' || $criteria['field'] == 'page' 
                        || $criteria['field'] == 'article' || $criteria['field'] == 'parent')
                    {
                        $criteria['field'] = 'w.id';
                    }
                    elseif ($criteria['field'] == 'date')
                    {
                        $criteria['field'] = 'datetime';
                    }
                }

                switch ($criteria['action'])
                {
                    case \KD2\MiniSkel::ACTION_ORDER_BY:
                        if (!$order)
                            $order = 'ORDER BY '.$criteria['field'].'';
                        else
                            $order .= ', '.$criteria['field'].'';
                        break;
                    case \KD2\MiniSkel::ACTION_ORDER_DESC:
                        if ($order)
                            $order .= ' DESC';
                        break;
                    case \KD2\MiniSkel::ACTION_LIMIT:
                        $begin = $criteria['begin'];
                        $limit = $criteria['number'];
                        break;
                    case \KD2\MiniSkel::ACTION_MATCH_FIELD_BY_VALUE:
                        $where .= ' AND '.$criteria['field'].' '.$criteria['comparison'].' ?';
                        $query_args[] = $criteria['value'];
                        break;
                    case \KD2\MiniSkel::ACTION_MATCH_FIELD:
                    {
                        if ($criteria['field'] == 'sauf_mention')
                        {
                            $where .= " AND f.id NOT IN (:php_implode) ";
                            $query_args[':php_implode'] = '\'.implode(",", Fichiers::listFilesUsedInText($this->getVariable(\'texte\'))).\'';
                            break;
                        }

                        $where .= ' AND '.$criteria['field'].' = ?';

                        if ($criteria['field'] == 'w.id')
                        {
                            $criteria['field'] = 'id';
                        }

                        $query_args[] = ['$this->getVariable(\'' . $criteria['field'] . '\')'];
                        break;
                    }
                    default:
                        break;
                }
            }

            if (trim($loopContent))
            {
                $loop_start .= '$row[\'url\'] = Fichiers::_getURL($row[\'id\'], $row[\'nom\'], $row[\'hash\']); ';
                $loop_start .= '$row[\'miniature\'] = $row[\'image\'] ? Fichiers::_getURL($row[\'id\'], $row[\'nom\'], $row[\'hash\'], 200) : \'\'; ';
                $loop_start .= '$row[\'moyenne\'] = $row[\'image\'] ? Fichiers::_getURL($row[\'id\'], $row[\'nom\'], $row[\'hash\'], 500) : \'\'; ';
            }

            $query .= $where . ' ' . $order;

            if (!$limit || $limit > 100)
                $limit = 100;

            if ($limit)
            {
                $query .= ' LIMIT ';

                if (is_numeric($begin))
                {
                    $query .= (int) $begin;
                }
                else
                {
                    $query .= '?';
                    $query_args[] = ['\'.$this->variables[\'debut_liste\'].\''];
                }

                $query .= ','.(int)$limit;
            }
        }
        else
        {
            $params = [
                'loopName'  =>  $loopName,
                'loopType'  =>  $loopType,
                'loopCriterias' =>  $loopCriterias,
                'loopContent'   =>  $loopContent,
                'preContent'    =>  $preContent,
                'postContent'   =>  $postContent,
                'altContent'    =>  $altContent,
            ];

            $callback_return = [
                'query'         =>  &$query,
                'query_args'    =>  &$query_args,
                'loop_start'    =>  &$loop_start,
                'code'          =>  &$statement_code,
            ];

            // Appel du plugin lié à cette boucle, si ça existe
            $return = Plugin::fireSignal('boucle.' . $loopType, $params, $callback_return);

            // Si aucun plugin n'a été appelé c'est que le type de boucle n'est pas défini
            if (!$return)
            {
                throw new \KD2\MiniSkelMarkupException("Le type de boucle '".$loopType."' est inconnu.");
            }

            if (empty($query))
            {
                $query = 'SELECT 0 LIMIT 0;';
            }
        }

        try {
            // Sécurité anti injection, à la compilation seulement
            $statement = $db->protectSelect(null, $query);
        }
        catch (\Exception $e)
        {
            throw new \KD2\MiniSkelMarkupException("Erreur SQL dans la requête : ".$e->getMessage() . "\n " . $query);
        }

        $hash = sha1(uniqid(mt_rand(), true));
        $out = new Squelette_Snippet();
        $out->append(1, '$parent_hash = @$this->current[\'_self_hash\'];');
        $out->append(1, '$this->parent =& $parent_hash ? $this->_vars[$parent_hash] : null;');

        if (!empty($search))
        {
            $out->append(1, 'if (trim($this->getVariable(\'recherche\'))) { ');
        }

        $query = var_export($query, true);

        foreach ($query_args as $k=>$arg)
        {
            if (substr($k, 0, 4) == ':php')
            {
                $query = str_replace($k, $arg, $query);
                unset($query_args[$k]);
            }
        }

        // Si le plugin a donné du code à exécuter à la place d'une requête SQL
        if ($statement_code)
        {
            $out->append(1, str_replace('$OBJ_VAR', '$result_' . $hash, $statement_code));
            $out->append(1, '$nb_rows = $result_'.$hash.'->countRows();');
        }
        else
        {
            $out->append(1, '$statement = $db->prepare('.$query.'); ');

            foreach ($query_args as $k=>$arg)
            {
                $out->append(1, '$value = ' . (is_array($arg) ? $arg[0] : var_export($arg, true)) . ';');
                $out->append(1, '$statement->bindValue(' . ($k+1) . ', $value, $db->getArgType($value));');
            }

            $out->append(1, '$result_'.$hash.' = $statement->execute(); ');
            $out->append(1, '$nb_rows = $db->countRows($result_'.$hash.'); ');
        }

        if (!empty($search))
        {
            $out->append(1, '} else { $result_'.$hash.' = false; $nb_rows = 0; }');
        }

        $out->append(1, '$this->_vars[\''.$hash.'\'] = [\'_self_hash\' => \''.$hash.'\', \'_parent_hash\' => $parent_hash, \'total_boucle\' => $nb_rows, \'compteur_boucle\' => 0];');
        $out->append(1, '$this->current =& $this->_vars[\''.$hash.'\']; ');
        $out->append(1, 'if ($nb_rows > 0):');

        // Ajout contenu avant tag
        if ($preContent)
        {
            $out->append(2, $this->parse($preContent, $loopName, self::PRE_CONTENT));
        }

        $out->append(1, 'while ($row = $result_'.$hash.'->fetchArray(SQLITE3_ASSOC)): ');
        $out->append(1, '$this->_vars[\''.$hash.'\'][\'compteur_boucle\'] += 1; ');
        $out->append(1, $loop_start);
        $out->append(1, '$this->_vars[\''.$hash.'\'] = array_merge($this->_vars[\''.$hash.'\'], $row); ');

        $out->append(2, $this->parseVariables($loopContent));

        $out->append(1, 'endwhile;');

        // we put the post-content after the loop content
        if ($postContent)
        {
            $out->append(2, $this->parse($postContent, $loopName, self::POST_CONTENT));
        }

        if ($altContent)
        {
            $out->append(1, 'else:');
            $out->append(2, $this->parse($altContent, $loopName, self::ALT_CONTENT));
        }

        $out->append(1, 'endif; ');
        $out->append(1, '$parent_hash = $this->_vars[\''.$hash.'\'][\'_parent_hash\']; ');
        $out->append(1, 'unset($result_'.$hash.', $nb_rows, $this->_vars[\''.$hash.'\']); ');
        $out->append(1, 'if ($parent_hash) { $this->current =& $this->_vars[$parent_hash]; $parent_hash = $this->current[\'_parent_hash\']; } ');
        $out->append(1, 'else { $this->current = null; }');
        $out->append(1, '$this->parent =& $parent_hash ? $this->_vars[$parent_hash] : null;');

        return $out;
    }

    public function fetch($template, $no_display = false)
    {
        $this->currentTemplate = $template;

        $path = file_exists(DATA_ROOT . '/www/squelettes/' . $template)
            ? DATA_ROOT . '/www/squelettes/' . $template
            : ROOT . '/www/squelettes-dist/' . $template;

        $tpl_id = basename(dirname($path)) . '/' . $template;

        if (!self::compile_check($tpl_id, $path))
        {
            if (!file_exists($path))
            {
                throw new \KD2\MiniSkelMarkupException('Le squelette "'.$tpl_id.'" n\'existe pas.');
            }

            $content = file_get_contents($path);
            $content = strtr($content, ['<?php' => '&lt;?php', '<?' => '<?php echo \'<?\'; ?>']);
            $out = new Squelette_Snippet(2, $this->parse($content));
            $out->prepend(1, '/* '.$tpl_id.' */ '.
                'namespace Garradin; $db = DB::getInstance(); '.
                'if ($this->parent) $parent_hash = $this->parent[\'_self_hash\']; '. // For included files
                'else $parent_hash = false;');

            if (!$no_display)
            {
                self::compile_store($tpl_id, $out);
            }
        }


        if (!$no_display)
        {
            require self::compile_get_path($tpl_id);
        }
        else
        {
            eval($tpl_id);
        }

        return null;
    }

    public function dispatchURI()
    {
        $uri = !empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';

        header('HTTP/1.1 200 OK', 200, true);

        if ($pos = strpos($uri, '?'))
        {
            $uri = substr($uri, 0, $pos);
        }
        else
        {
            // WWW_URI inclus toujours le slash final, mais on veut le conserver ici
            $uri = substr($uri, strlen(WWW_URI) - 1);
        }

        if ($uri == '/')
        {
            $skel = 'sommaire.html';
        }
        elseif ($uri == '/feed/atom/')
        {
            header('Content-Type: application/atom+xml');
            $skel = 'atom.xml';
        }
        elseif ($uri == '/favicon.ico')
        {
            header('Location: ' . ADMIN_URL . 'static/icon.png');
            exit;
        }
        elseif (substr($uri, -1) == '/')
        {
            $skel = 'rubrique.html';
            $_GET['uri'] = $_REQUEST['uri'] = substr($uri, 1, -1);
        }
        elseif (preg_match('!^/admin/!', $uri))
        {
            http_response_code(404);
            throw new UserException('Cette page n\'existe pas.');
        }
        else
        {
            $_GET['uri'] = $_REQUEST['uri'] = substr($uri, 1);

            if (preg_match('!^[\w\d_-]+$!i', $_GET['uri'])
                && file_exists(DATA_ROOT . '/www/squelettes/' . strtolower($_GET['uri']) . '.html'))
            {
                $skel = strtolower($_GET['uri']) . '.html';
            }
            else
            {
                $skel = 'article.html';
            }
        }

        $this->display($skel);
    }

    static private function compile_get_path($path)
    {
        $hash = sha1($path);
        return CACHE_ROOT . '/compiled/s_' . $hash . '.php';
    }

    static private function compile_check($tpl, $check)
    {
        if (!file_exists(self::compile_get_path($tpl)))
            return false;

        $time = filemtime(self::compile_get_path($tpl));

        if (empty($time))
        {
            return false;
        }

        if ($time < filemtime($check))
            return false;
        return $time;
    }

    static private function compile_store($tpl, $content)
    {
        $path = self::compile_get_path($tpl);

        if (!file_exists(dirname($path)))
        {
            Utils::safe_mkdir(dirname($path), 0777, true);
        }

        file_put_contents($path, $content);
        return true;
    }

    static public function compile_clear($tpl)
    {
        $path = self::compile_get_path($tpl);

        if (file_exists($path))
        {
            Utils::safe_unlink($path);
        }

        return true;
    }

    protected function getVariable($var)
    {
        if (isset($this->current[$var]))
        {
            return $this->current[$var];
        }
        elseif (isset($this->parent[$var]))
        {
            return $this->parent[$var];
        }
        elseif (isset($this->variables[$var]))
        {
            return $this->variables[$var];
        }
        elseif (isset($_REQUEST[$var]))
        {
            return $_REQUEST[$var];
        }
        else
        {
            return null;
        }
    }

    static public function getSource($template)
    {
        if (!preg_match('!^[\w\d_-]+(?:\.[\w\d_-]+)*$!i', $template)) {
            return null;
        }

        $path = file_exists(DATA_ROOT . '/www/squelettes/' . $template)
            ? DATA_ROOT . '/www/squelettes/' . $template
            : ROOT . '/www/squelettes-dist/' . $template;

        if (!file_exists($path)) {
            return null;
        }

        return file_get_contents($path);
    }

    static public function editSource($template, $content)
    {
        if (!preg_match('!^[\w\d_-]+(?:\.[\w\d_-]+)*$!i', $template))
            return false;

        $path = DATA_ROOT . '/www/squelettes/' . $template;

        return file_put_contents($path, $content);
    }

    static public function resetSource($template)
    {
        if (!preg_match('!^[\w\d_-]+(?:\.[\w\d_-]+)*$!i', $template))
            return false;

        if (file_exists(DATA_ROOT . '/www/squelettes/' . $template))
        {
            return Utils::safe_unlink(DATA_ROOT . '/www/squelettes/' . $template);
        }

        return false;
    }

    static public function listSources()
    {
        if (!file_exists(DATA_ROOT . '/www/squelettes'))
        {
            Utils::safe_mkdir(DATA_ROOT . '/www/squelettes', 0775, true);
        }

        $sources = [];

        $dir = dir(ROOT . '/www/squelettes-dist');

        while ($file = $dir->read())
        {
            if ($file[0] == '.')
                continue;

            if (!preg_match('/\.(?:css|x?html?|atom|rss|xml|svg|txt)$/i', $file))
                continue;

            $sources[$file] = false;
        }

        $dir->close();

        $dir = dir(DATA_ROOT . '/www/squelettes');

        while ($file = $dir->read())
        {
            if ($file[0] == '.')
                continue;

            if (!preg_match('/\.(?:css|x?html?|atom|rss|xml|svg|txt)$/i', $file))
                continue;

            $sources[$file] = [
                // Est-ce que le fichier fait partie de la distribution de Garradin?
                // (Si non pas possible de faire un reset)
                'dist'  =>  array_key_exists($file, $sources),
                'mtime' =>  filemtime($dir->path.'/'.$file),
            ];
        }

        $dir->close();

        ksort($sources);

        return $sources;
    }

}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted src/include/lib/Garradin/Squelette_Filtres.php version [4a8a3bb75b].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
<?php

namespace Garradin;

class Squelette_Filtres
{
    static private $alt = [];

    static public $filtres_php = [
        'strtolower',
        'strtoupper',
        'ucfirst',
        'ucwords',
        'str_rot13',
        'str_shuffle',
        'htmlentities',
        'htmlspecialchars',
        'trim',
        'ltrim',
        'rtrim',
        'lcfirst',
        'md5',
        'sha1',
        'metaphone',
        'nl2br',
        'soundex',
        'str_split',
        'str_word_count',
        'strrev',
        'strlen',
        'wordwrap',
        'strip_tags' => 'supprimer_tags',
        'var_dump',
    ];

    static public $filtres_alias = [
        '!='    =>  'different_de',
        '=='    =>  'egal_a',
        '?'     =>  'choixsivide',
        '>'     =>  'superieur_a',
        '>='    =>  'superieur_ou_egal_a',
        '<'     =>  'inferieur_a',
        '<='    =>  'inferieur_ou_egal_a',
        'yes'   =>  'oui',
        'no'    =>  'non',
        'and'   =>  'et',
        'or'    =>  'ou',
        'xor'   =>  'xou',
        'supprimer_spip' => 'supprimer_skriv',
    ];

    static public $desactiver_defaut = [
        'formatter_texte',
        'entites_html',
        'proteger_contact',
        'echapper_xml',
    ];

    static public function date($date, $format)
    {
        return strftime($format, $date);
    }

    static public function date_en_francais($date)
    {
        return ucfirst(strtolower(Utils::strftime_fr($date, '%A %e %B %Y')));
    }

    static public function heure_en_francais($date)
    {
        return Utils::strftime_fr($date, '%Hh%M');
    }

    static public function mois_en_francais($date)
    {
        return Utils::strftime_fr($date, '%B %Y');
    }

    static public function date_perso($date, $format)
    {
        return Utils::strftime_fr($date, $format);
    }

    static public function date_intelligente($date, $avec_heure = true)
    {
        $jour = null;
        $heure = date('H\hi', $date);

        if (date('Ymd', $date) == date('Ymd'))
        {
            $jour = 'aujourd\'hui';
        }
        elseif (date('Ymd', $date) == date('Ymd', strtotime('yesterday')))
        {
            $jour = 'hier';
        }
        elseif (date('Ymd', $date) == date('Ymd', strtotime('tomorrow')))
        {
            $jour = 'demain';
        }
        elseif (date('Y', $date) == date('Y'))
        {
            $jour = strtolower(Utils::strftime_fr($date, '%A %e %B'));
        }
        else
        {
            $jour = strtolower(Utils::strftime_fr($date, '%e %B %Y'));
        }

        if ($avec_heure)
        {
            return sprintf('%s, %s', $jour, $heure);
        }

        return $jour;
    }

    static public function date_atom($date)
    {
        return date(DATE_ATOM, $date);
    }

    static public function alterner($v, $name, $valeur1, $valeur2)
    {
        if (!array_key_exists($name, self::$alt))
        {
            self::$alt[$name] = 0;
        }

        if (self::$alt[$name]++ % 2 == 0)
            return $valeur1;
        else
            return $valeur2;
    }

    static public function proteger_contact($contact)
    {
        if (!trim($contact))
            return '';

        if (strpos($contact, '@')) {
            $reversed = strrev($contact);
            // https://unicode-table.com/en/FF20/
            $reversed = strtr($reversed, ['@' => '@']);

            return sprintf('<a href="#error" onclick="this.href = (this.innerText + \':otliam\').split(\'\').reverse().join(\'\').replace(/@/, \'@\');"><span style="unicode-bidi:bidi-override;direction: rtl;">%s</span></a>',
                htmlspecialchars($reversed));
        }
        else {
            return '<a href="'.htmlspecialchars($contact, ENT_QUOTES, 'UTF-8').'">'.htmlspecialchars($contact, ENT_QUOTES, 'UTF-8').'</a>';
        }
    }

    static public function entites_html($texte)
    {
        return htmlspecialchars($texte, ENT_QUOTES, 'UTF-8');
    }

    static public function echapper_xml($texte)
    {
        return str_replace('&#039;', '&apos;', htmlspecialchars($texte, ENT_QUOTES, 'UTF-8'));
    }

    static public function formatter_texte($texte)
    {
        $texte = Utils::SkrivToHTML($texte);
        $texte = self::typo_fr($texte);

        // Liens wiki
        $texte = preg_replace_callback('!<a href="([^/.:@]+)">!i', function ($matches) {
            return '<a href="' . WWW_URL . Wiki::transformTitleToURI($matches[1]) . '">';
        }, $texte);

        return $texte;
    }

    static public function typo_fr($str, $html = true)
    {
        $space = $html ? '&nbsp;' : ' ';
        $str = preg_replace('/(?:[\h]|&nbsp;)*([?!:»])(\s+|$)/u', $space.'\\1\\2', $str);
        $str = preg_replace('/(^|\s+)([«])(?:[\h]|&nbsp;)*/u', '\\1\\2'.$space, $str);
        return $str;
    }

    static public function pagination($total, $debut, $par_page)
    {
        $max_page = ceil($total / $par_page);
        $current = ($debut > 0) ? ceil($debut / $par_page) + 1 : 1;
        $out = '';

        if ($current > 1)
        {
            $out .= '<a href="./'.($current > 2 ? '+' . ($debut - $par_page) : '').'">&laquo; Page pr&eacute;c&eacute;dente</a> - ';
        }

        for ($i = 1; $i <= $max_page; $i++)
        {
            $link = ($i == 1) ? './' : './+' . (($i - 1) * $par_page);

            if ($i == $current)
                $out .= '<strong>'.$i.'</strong> - ';
            else
                $out .= '<a href="'.$link.'">'.$i.'</a> - ';
        }

        if ($current < $max_page)
        {
            $out .= '<a href="./+'.($debut + $par_page).'">Page suivante &raquo;</a>';
        }
        else
        {
            $out = substr($out, 0, -3);
        }

        return $out;
    }

    // Compatibilité SPIP

    static public function egal_a($value, $test)
    {
        if ($value == $test)
            return true;
        else
            return false;
    }

    static public function different_de($value, $test)
    {
        if ($value != $test)
            return true;
        else
            return false;
    }

    // disponible aussi avec : | ?{sioui, sinon}
    static public function choixsivide($value, $un, $deux = '')
    {
        if (empty($value) || !trim($value))
            return $deux;
        else
            return $un;
    }

    static public function sinon($value, $sinon = '')
    {
        if ($value)
            return $value;
        else
            return $sinon;
    }

    static public function choixsiegal($value, $test, $un, $deux)
    {
        return ($value == $test) ? $un : $deux;
    }

    static public function supprimer_tags($value, $replace = '')
    {
        return preg_replace('!<[^>]*>!', $replace, $value);
    }

    static public function supprimer_skriv($value)
    {
        $value = self::formatter_texte($value);
        return self::supprimer_tags($value);
    }

    static public function couper($texte, $taille, $etc = ' (...)')
    {
        if (strlen($texte) > $taille)
        {
            $texte = substr($texte, 0, $taille);
            $taille -= ($taille * 0.1);

            $texte = preg_replace('!([\s.,;:\!?])[^\s.,;:\!?]*?$!', '\\1', $texte);
            $texte.= $etc;
        }

        return $texte;
    }

    static public function replace($texte, $expression, $replace, $modif='UsimsS')
    {
        return preg_replace('/'.$expression.'/'.$modif, $replace, $texte);
    }

    static public function plus($a, $b)
    {
        return $a + $b;
    }

    static public function moins($a, $b)
    {
        return $a - $b;
    }

    static public function mult($a, $b)
    {
        return $a * $b;
    }

    static public function div($a, $b)
    {
        return $b ? $a / $b : 0;
    }

    static public function modulo($a, $mod, $add)
    {
        return ($mod ? $a % $mod : 0) + $add;
    }

    static public function vide($value)
    {
        return '';
    }

    static public function concat()
    {
        return implode('', func_get_args());
    }

    static public function singulier_ou_pluriel($nb, $singulier, $pluriel, $var = null)
    {
        if (!$nb)
            return '';

        if ($nb == 1)
            return str_replace('@'.$var.'@', $nb, $singulier);
        else
            return str_replace('@'.$var.'@', $nb, $pluriel);
    }

    static public function date_w3c($date)
    {
        return date(DATE_W3C, $date);
    }

    static public function et($value, $test)
    {
        return ($value && $test) ? true : false;
    }

    static public function ou($value, $test)
    {
        return ($value || $test) ? true : false;
    }

    static public function xou($value, $test)
    {
        return ($value XOR $test) ? true : false;
    }

    static public function oui($value)
    {
        return $value ? true : false;
    }

    static public function non($value)
    {
        return !$value ? true : false;
    }

    static public function superieur_a($value, $test)
    {
        return ($value > $test) ? true : false;
    }

    static public function superieur_ou_egal_a($value, $test)
    {
        return ($value >= $test) ? true : false;
    }

    static public function inferieur_a($value, $test)
    {
        return ($value < $test) ? true : false;
    }

    static public function inferieur_ou_egal_a($value, $test)
    {
        return ($value <= $test) ? true : false;
    }

    static public function euros($value)
    {
        return str_replace(' ', '&nbsp;', number_format($value, (round($value) == round($value, 2) ? 0 : 2), ',', ' ')) . '&nbsp;€';
    }

    static public function taille_en_octets($value)
    {
        return Utils::format_bytes($value);
    }
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































































































































































































































































































































































































































































































































































































































































































Modified src/include/lib/Garradin/Static_Cache.php from [73b33ffa77] to [6c89dae4c6].

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

namespace Garradin;

class Static_Cache
{
	const EXPIRE = 3600; // 1h
	const CLEAN_EXPIRE = 86400; // 1 day

	protected static function _getCacheDir()
	{
		$dir = CACHE_ROOT . '/static';

		if (!file_exists($dir))
		{
			Utils::safe_mkdir(CACHE_ROOT . '/static', 0777, true);
		}

		return CACHE_ROOT . '/static';
	}

	protected static function _getCachePath($id)
	{
		$id = 'cache_' . sha1(DB_FILE . $id);
		return self::_getCacheDir() . '/' . $id;
	}











|



|


|







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

namespace Garradin;

class Static_Cache
{
	const EXPIRE = 3600; // 1h
	const CLEAN_EXPIRE = 86400; // 1 day

	protected static function _getCacheDir()
	{
		$dir = STATIC_CACHE_ROOT;

		if (!file_exists($dir))
		{
			Utils::safe_mkdir($dir, 0777, true);
		}

		return $dir;
	}

	protected static function _getCachePath($id)
	{
		$id = 'cache_' . sha1(DB_FILE . $id);
		return self::_getCacheDir() . '/' . $id;
	}

Modified src/include/lib/Garradin/Template.php from [cf65df4d0f] to [5d1bf1759c].

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

namespace Garradin;

use KD2\Form;
use KD2\HTTP;
use KD2\Translate;
use Garradin\Membres\Session;
use Garradin\Entities\Accounting\Account;




class Template extends \KD2\Smartyer
{
	static protected $_instance = null;

	static public function getInstance()
	{
		return self::$_instance ?: self::$_instance = new Template;
	}

	private function __clone()
	{
	}

	public function __construct()
	{
		parent::__construct();

		if (!file_exists(CACHE_ROOT . '/compiled'))
		{

			Utils::safe_mkdir(CACHE_ROOT . '/compiled', 0777, true);
		}

		$this->setTemplatesDir(ROOT . '/templates');
		$this->setCompiledDir(CACHE_ROOT . '/compiled');
		$this->setNamespace('Garradin');

		// Hash de la version pour les éléments statiques (cache)
		// On ne peut pas utiliser la version directement comme query string
		// pour les éléments statiques (genre /admin/static/admin.css?v0.9.0)
		// car cela dévoilerait la version de Garradin utilisée, posant un souci
		// en cas de faille, on cache donc la version utilisée, chaque instance









>
>
>


















|
|
>
|



|







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

namespace Garradin;

use KD2\Form;
use KD2\HTTP;
use KD2\Translate;
use Garradin\Membres\Session;
use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Users\Category;
use Garradin\UserTemplate\CommonModifiers;
use Garradin\Web\Render\Skriv;

class Template extends \KD2\Smartyer
{
	static protected $_instance = null;

	static public function getInstance()
	{
		return self::$_instance ?: self::$_instance = new Template;
	}

	private function __clone()
	{
	}

	public function __construct()
	{
		parent::__construct();

		$cache_dir = SMARTYER_CACHE_ROOT;

		if (!file_exists($cache_dir)) {
			Utils::safe_mkdir($cache_dir, 0777, true);
		}

		$this->setTemplatesDir(ROOT . '/templates');
		$this->setCompiledDir($cache_dir);
		$this->setNamespace('Garradin');

		// Hash de la version pour les éléments statiques (cache)
		// On ne peut pas utiliser la version directement comme query string
		// pour les éléments statiques (genre /admin/static/admin.css?v0.9.0)
		// car cela dévoilerait la version de Garradin utilisée, posant un souci
		// en cas de faille, on cache donc la version utilisée, chaque instance
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

		$this->register_compile_function('continue', function ($pos, $block, $name, $raw_args) {
			if ($block == 'continue')
			{
				return 'continue;';
			}
		});








		$this->register_function('form_errors', [$this, 'formErrors']);
		$this->register_function('show_error', [$this, 'showError']);
		$this->register_function('form_field', [$this, 'formField']);
		$this->register_function('html_champ_membre', [$this, 'formChampMembre']);
		$this->register_function('input', [$this, 'formInput']);


		$this->register_function('custom_colors', [$this, 'customColors']);
		$this->register_function('plugin_url', ['Garradin\Utils', 'plugin_url']);
		$this->register_function('diff', [$this, 'diff']);
		$this->register_function('pagination', [$this, 'pagination']);
		$this->register_function('format_droits', [$this, 'formatDroits']);

		$this->register_function('csrf_field', function ($params) {
			return Form::tokenHTML($params['key']);
		});

		$this->register_function('icon', [$this, 'widgetIcon']);
		$this->register_function('button', [$this, 'widgetButton']);
		$this->register_function('linkbutton', [$this, 'widgetLinkButton']);

		$this->register_modifier('strlen', 'strlen');
		$this->register_modifier('dump', ['KD2\ErrorManager', 'dump']);
		$this->register_modifier('get_country_name', ['Garradin\Utils', 'getCountryName']);
		$this->register_modifier('format_tel', [$this, 'formatPhoneNumber']);
		$this->register_modifier('abs', 'abs');
		$this->register_modifier('display_champ_membre', [$this, 'displayChampMembre']);

		$this->register_modifier('format_bytes', ['Garradin\Utils', 'format_bytes']);
		$this->register_modifier('strftime_fr', [Utils::class, 'strftime_fr']);
		$this->register_modifier('date_fr', [Utils::class, 'date_fr']);
		$this->register_modifier('date_long', [Utils::class, 'date_fr']);

		$this->register_modifier('date_short', function ($dt) {
			return Utils::date_fr($dt, 'd/m/Y');
		});

		$this->register_modifier('html_money', [$this, 'htmlMoney']);
		$this->register_modifier('money_currency', [$this, 'htmlMoneyCurrency']);

		$this->register_modifier('format_wiki', function ($str) {
			$str = Utils::SkrivToHTML($str);
			$str = Squelette_Filtres::typo_fr($str);
			return $str;
		});

		$this->register_modifier('liens_wiki', function ($str, $prefix) {
			return preg_replace_callback('!<a href="([^/.:@]+)">!i', function ($matches) use ($prefix) {
				return '<a href="' . $prefix . Wiki::transformTitleToURI($matches[1]) . '">';
			}, $str);
		});

	}

	protected function htmlMoney($number, bool $hide_empty = true): string
	{
		if ($hide_empty && !$number) {
			return '';
		}

		return sprintf('<b class="money">%s</b>', Utils::money_format($number, ',', '&nbsp;', $hide_empty));
	}

	protected function htmlMoneyCurrency($number, bool $hide_empty = true): string
	{
		$out = $this->htmlMoney($number, $hide_empty);

		if ($out !== '') {
			$out .= '&nbsp;' . Config::getInstance()->get('monnaie');
		}

		return $out;
	}

	protected function formErrors($params)
	{
		$form = $this->getTemplateVars('form');

		if (!$form->hasErrors())
		{







>
>
>
>
>
>
>






>




|
<
















|
<
<
<
|
<
<


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

<
<
<
|
<
<
|

<
<







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

		$this->register_compile_function('continue', function ($pos, $block, $name, $raw_args) {
			if ($block == 'continue')
			{
				return 'continue;';
			}
		});

		$this->register_compile_function('use', function ($pos, $block, $name, $raw_args) {
			if ($name == 'use')
			{
				return sprintf('use %s;', $raw_args);
			}
		});

		$this->register_function('form_errors', [$this, 'formErrors']);
		$this->register_function('show_error', [$this, 'showError']);
		$this->register_function('form_field', [$this, 'formField']);
		$this->register_function('html_champ_membre', [$this, 'formChampMembre']);
		$this->register_function('input', [$this, 'formInput']);
		$this->register_function('password_change', [$this, 'passwordChangeInput']);

		$this->register_function('custom_colors', [$this, 'customColors']);
		$this->register_function('plugin_url', ['Garradin\Utils', 'plugin_url']);
		$this->register_function('diff', [$this, 'diff']);
		$this->register_function('display_permissions', [$this, 'displayPermissions']);


		$this->register_function('csrf_field', function ($params) {
			return Form::tokenHTML($params['key']);
		});

		$this->register_function('icon', [$this, 'widgetIcon']);
		$this->register_function('button', [$this, 'widgetButton']);
		$this->register_function('linkbutton', [$this, 'widgetLinkButton']);

		$this->register_modifier('strlen', 'strlen');
		$this->register_modifier('dump', ['KD2\ErrorManager', 'dump']);
		$this->register_modifier('get_country_name', ['Garradin\Utils', 'getCountryName']);
		$this->register_modifier('format_tel', [$this, 'formatPhoneNumber']);
		$this->register_modifier('abs', 'abs');
		$this->register_modifier('display_champ_membre', [$this, 'displayChampMembre']);

		$this->register_modifier('format_skriv', function ($str) {



			return Skriv::render(null, $str);


		});



		foreach (CommonModifiers::MODIFIERS_LIST as $key => $name) {





			$this->register_modifier(is_int($key) ? $name : $key, is_int($key) ? [CommonModifiers::class, $name] : $name);





		}

		foreach (CommonModifiers::FUNCTIONS_LIST as $key => $name) {





			$this->register_function(is_int($key) ? $name : $key, is_int($key) ? [CommonModifiers::class, $name] : $name);

		}




		$this->register_modifier('local_url', [Utils::class, 'getLocalURL']);


	}




	protected function formErrors($params)
	{
		$form = $this->getTemplateVars('form');

		if (!$form->hasErrors())
		{
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
		$shape = $params['shape'];
		$label = $params['label'];

		// href can be prefixed with '!' to make the URL relative to ADMIN_URL
		if (substr($href, 0, 1) == '!') {
			$href = ADMIN_URL . substr($params['href'], 1);
		}







		unset($params['href'], $params['shape'], $params['label']);

		array_walk($params, function (&$v, $k) {
			$v = sprintf('%s="%s"', $k, $this->escape($v));
		});

		$params = implode(' ', $params);

		return sprintf('<a class="icn-btn" data-icon="%s" href="%s" %s>%s</a>', Utils::iconUnicode($shape), $this->escape($href), $params, $this->escape($label));


























	}

	protected function formInput(array $params)
	{
		static $params_list = ['value', 'default', 'type', 'help', 'label', 'name', 'options', 'source'];

		// Extract params and keep attributes separated
		$attributes = array_diff_key($params, array_flip($params_list));
		$params = array_intersect_key($params, array_flip($params_list));
		extract($params, \EXTR_SKIP);

		if (!isset($name, $type)) {
			throw new \InvalidArgumentException('Missing name or type');
		}












		$current_value = null;
		$current_value_from_user = false;

		if (isset($_POST[$name])) {
			$current_value = $_POST[$name];
			$current_value_from_user = true;
		}
		elseif (isset($source) && is_object($source) && isset($source->$name)) {
			$current_value = $source->$name;
		}
		elseif (isset($source) && is_array($source) && isset($source[$name])) {
			$current_value = $source[$name];
		}
		elseif (isset($default) && ($type != 'checkbox' || empty($_POST))) {
			$current_value = $default;
		}

		if ($type == 'date' && is_object($current_value) && $current_value instanceof \DateTimeInterface) {
			$current_value = $current_value->format('d/m/Y');



		}
		elseif ($type == 'date' && is_string($current_value)) {
			if ($v = \DateTime::createFromFormat('!Y-m-d', $current_value)) {
				$current_value = $v->format('d/m/Y');
			}
		}


		$attributes['id'] = 'f_' . $name;
		$attributes['name'] = $name;

		if (!isset($attributes['autocomplete']) && ($type == 'money' || $type == 'password')) {
			$attributes['autocomplete'] = 'off';
		}

		if ($type == 'radio' || $type == 'checkbox') {







>
>
>
>
>
>









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














>
>
>
>
>
>
>
>
>
>
>








|











>
>
>







>
|







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
		$shape = $params['shape'];
		$label = $params['label'];

		// href can be prefixed with '!' to make the URL relative to ADMIN_URL
		if (substr($href, 0, 1) == '!') {
			$href = ADMIN_URL . substr($params['href'], 1);
		}

		if (!isset($params['class'])) {
			$params['class'] = '';
		}

		$params['class'] .= ' icn-btn';

		unset($params['href'], $params['shape'], $params['label']);

		array_walk($params, function (&$v, $k) {
			$v = sprintf('%s="%s"', $k, $this->escape($v));
		});

		$params = implode(' ', $params);

		return sprintf('<a data-icon="%s" href="%s" %s>%s</a>', Utils::iconUnicode($shape), $this->escape($href), $params, $this->escape($label));
	}

	protected function passwordChangeInput(array $params)
	{
		$out = $this->formInput(array_merge($params, [
			'type' => 'password',
			'help' => sprintf('(Minimum %d caractères)', Session::MINIMUM_PASSWORD_LENGTH),
			'minlength' => Session::MINIMUM_PASSWORD_LENGTH,
		]));

		$out.= '<dd class="help">Astuce : un mot de passe de quatre mots choisis au hasard dans le dictionnaire est plus sûr et plus simple à retenir qu\'un mot de passe composé de 10 lettres et chiffres.</dd>';

		$suggestion = Utils::suggestPassword();

		$out .= sprintf('<dd class="help">Pas d\'idée&nbsp;? Voici une suggestion choisie au hasard&nbsp;:
                <input type="text" readonly="readonly" title="Cliquer pour utiliser cette suggestion comme mot de passe" id="f_%s_suggest" value="%s" autocomplete="off" size="%d" /></dd>', $params['name'], $suggestion, strlen($suggestion));

		$out .= $this->formInput([
			'type' => 'password',
			'label' => 'Répéter le mot de passe',
			'required' => true,
			'name' => $params['name'] . '_confirm',
			'minlength' => Session::MINIMUM_PASSWORD_LENGTH,
		]);

		return $out;
	}

	protected function formInput(array $params)
	{
		static $params_list = ['value', 'default', 'type', 'help', 'label', 'name', 'options', 'source'];

		// Extract params and keep attributes separated
		$attributes = array_diff_key($params, array_flip($params_list));
		$params = array_intersect_key($params, array_flip($params_list));
		extract($params, \EXTR_SKIP);

		if (!isset($name, $type)) {
			throw new \InvalidArgumentException('Missing name or type');
		}

		$suffix = null;

		if ($type == 'datetime') {
			$type = 'date';
			$tparams = func_get_arg(0);
			$tparams['type'] = 'time';
			$tparams['name'] = sprintf('%s_time', $name);
			unset($tparams['label']);
			$suffix = self::formInput($tparams);
		}

		$current_value = null;
		$current_value_from_user = false;

		if (isset($_POST[$name])) {
			$current_value = $_POST[$name];
			$current_value_from_user = true;
		}
		elseif (isset($source) && is_object($source) && isset($source->$name) && !is_null($source->$name)) {
			$current_value = $source->$name;
		}
		elseif (isset($source) && is_array($source) && isset($source[$name])) {
			$current_value = $source[$name];
		}
		elseif (isset($default) && ($type != 'checkbox' || empty($_POST))) {
			$current_value = $default;
		}

		if ($type == 'date' && is_object($current_value) && $current_value instanceof \DateTimeInterface) {
			$current_value = $current_value->format('d/m/Y');
		}
		elseif ($type == 'time' && is_object($current_value) && $current_value instanceof \DateTimeInterface) {
			$current_value = $current_value->format('H:i');
		}
		elseif ($type == 'date' && is_string($current_value)) {
			if ($v = \DateTime::createFromFormat('!Y-m-d', $current_value)) {
				$current_value = $v->format('d/m/Y');
			}
		}


		$attributes['id'] = 'f_' . str_replace(['[', ']'], '', $name);
		$attributes['name'] = $name;

		if (!isset($attributes['autocomplete']) && ($type == 'money' || $type == 'password')) {
			$attributes['autocomplete'] = 'off';
		}

		if ($type == 'radio' || $type == 'checkbox') {
276
277
278
279
280
281
282








283
284
285
286
287
288
289
			$type = 'text';
			$attributes['placeholder'] = 'JJ/MM/AAAA';
			$attributes['data-input'] = 'date';
			$attributes['size'] = 12;
			$attributes['maxlength'] = 10;
			$attributes['pattern'] = '\d\d?/\d\d?/\d{4}';
		}









		// Create attributes string
		if (array_key_exists('required', $attributes)) {
			$attributes['required'] = 'required';
		}

		if (!empty($attributes['disabled'])) {







>
>
>
>
>
>
>
>







304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
			$type = 'text';
			$attributes['placeholder'] = 'JJ/MM/AAAA';
			$attributes['data-input'] = 'date';
			$attributes['size'] = 12;
			$attributes['maxlength'] = 10;
			$attributes['pattern'] = '\d\d?/\d\d?/\d{4}';
		}
		elseif ($type == 'time') {
			$type = 'text';
			$attributes['placeholder'] = 'HH:MM';
			$attributes['data-input'] = 'time';
			$attributes['size'] = 8;
			$attributes['maxlength'] = 5;
			$attributes['pattern'] = '\d\d?:\d\d?';
		}

		// Create attributes string
		if (array_key_exists('required', $attributes)) {
			$attributes['required'] = 'required';
		}

		if (!empty($attributes['disabled'])) {
382
383
384
385
386
387
388


389
390
391
392
393
394
395

			return $input;
		}

		if ($type == 'file') {
			$input .= sprintf('<input type="hidden" name="MAX_FILE_SIZE" value="%d" id="f_maxsize" />', Utils::return_bytes(Utils::getMaxUploadSize()));
		}



		$label = sprintf('<label for="%s">%s</label>', $attributes['id'], $this->escape($label));

		if ($type == 'radio' || $type == 'checkbox') {
			$out = sprintf('<dd>%s %s', $input, $label);

			if (isset($help)) {







>
>







418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433

			return $input;
		}

		if ($type == 'file') {
			$input .= sprintf('<input type="hidden" name="MAX_FILE_SIZE" value="%d" id="f_maxsize" />', Utils::return_bytes(Utils::getMaxUploadSize()));
		}

		$input .= $suffix;

		$label = sprintf('<label for="%s">%s</label>', $attributes['id'], $this->escape($label));

		if ($type == 'radio' || $type == 'checkbox') {
			$out = sprintf('<dd>%s %s', $input, $label);

			if (isset($help)) {
409
410
411
412
413
414
415



416
417
418
419
420
421
422
				$out .= sprintf('<dd class="help">%s</dd>', $this->escape($help));
			}
		}

		return $out;
	}




	protected function formField(array $params, $escape = true)
	{
		if (!isset($params['name']))
		{
			throw new \BadFunctionCallException('name argument is mandatory');
		}








>
>
>







447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
				$out .= sprintf('<dd class="help">%s</dd>', $this->escape($help));
			}
		}

		return $out;
	}

	/**
	 * @deprecated
	 */
	protected function formField(array $params, $escape = true)
	{
		if (!isset($params['name']))
		{
			throw new \BadFunctionCallException('name argument is mandatory');
		}

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
512
513
514
515
516
517
518

	protected function customColors()
	{
		$config = Config::getInstance();

		$couleur1 = $config->get('couleur1') ?: ADMIN_COLOR1;
		$couleur2 = $config->get('couleur2') ?: ADMIN_COLOR2;
		$image_fond = ADMIN_BACKGROUND_IMAGE;

		if ($config->get('image_fond'))
		{
			try {
				$f = new Fichiers($config->get('image_fond'));
				$image_fond = $f->getURL();
			}
			catch (\InvalidArgumentException $e)
			{
				// Fichier qui n'existe pas/plus
			}
		}

		// Transformation Hexa vers décimal
		$couleur1 = implode(', ', sscanf($couleur1, '#%02x%02x%02x'));
		$couleur2 = implode(', ', sscanf($couleur2, '#%02x%02x%02x'));

		$out = '
		<style type="text/css">
		:root {
			--gMainColor: %s;
			--gSecondColor: %s;
			--gBgImage: url("%s");
		}
		</style>';

		return sprintf($out, $couleur1, $couleur2, $image_fond);
	}

	protected function displayChampMembre($v, $config = null)
	{
		if (is_string($config)) {
			$config = Config::getInstance()->get('champs_membres')->get($config);
		}







|

|
<
<
<
|
<
<
<
<
<















|







518
519
520
521
522
523
524
525
526
527



528





529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551

	protected function customColors()
	{
		$config = Config::getInstance();

		$couleur1 = $config->get('couleur1') ?: ADMIN_COLOR1;
		$couleur2 = $config->get('couleur2') ?: ADMIN_COLOR2;
		$admin_background = ADMIN_BACKGROUND_IMAGE;

		if ($f = $config->get('admin_background')) {



			$admin_background = WWW_URL . $f;





		}

		// Transformation Hexa vers décimal
		$couleur1 = implode(', ', sscanf($couleur1, '#%02x%02x%02x'));
		$couleur2 = implode(', ', sscanf($couleur2, '#%02x%02x%02x'));

		$out = '
		<style type="text/css">
		:root {
			--gMainColor: %s;
			--gSecondColor: %s;
			--gBgImage: url("%s");
		}
		</style>';

		return sprintf($out, $couleur1, $couleur2, $admin_background);
	}

	protected function displayChampMembre($v, $config = null)
	{
		if (is_string($config)) {
			$config = Config::getInstance()->get('champs_membres')->get($config);
		}
565
566
567
568
569
570
571





572
573
574
575
576
577
578
		$config = $params['config'];
		$type = $config->type;

		if ($params['name'] == 'passe' || (!empty($params['user_mode']) && !empty($config->private)))
		{
			return '';
		}






		$options = [];

		if ($type == 'select' || $type == 'multiple')
		{
			if (empty($config->options))
			{







>
>
>
>
>







598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
		$config = $params['config'];
		$type = $config->type;

		if ($params['name'] == 'passe' || (!empty($params['user_mode']) && !empty($config->private)))
		{
			return '';
		}

		// Files are managed out of the form
		if ($config->type == 'file') {
			return '';
		}

		$options = [];

		if ($type == 'select' || $type == 'multiple')
		{
			if (empty($config->options))
			{
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
			$prev = $i;
		}

		$out .= '</table>';
		return $out;
	}

	protected function pagination(array $params)
	{
		if (!isset($params['url']) || !isset($params['page']) || !isset($params['bypage']) || !isset($params['total']))
			throw new \BadFunctionCallException("Paramètre manquant pour pagination");

		if ($params['total'] == -1)
			return '';

		$pagination = Utils::getGenericPagination($params['page'], $params['total'], $params['bypage']);

		if (empty($pagination))
			return '';

		$out = '<ul class="pagination">';
		$encoded_url = rawurlencode('[ID]');

		foreach ($pagination as &$page)
		{
			$attributes = '';

			if (!empty($page['class']))
				$attributes .= ' class="' . htmlspecialchars($page['class']) . '" ';

			$out .= '<li'.$attributes.'>';

			$attributes = '';

			if (!empty($page['accesskey']))
				$attributes .= ' accesskey="' . htmlspecialchars($page['accesskey']) . '" ';

			$out .= '<a' . $attributes . ' href="' . str_replace(['[ID]', $encoded_url], htmlspecialchars($page['id']), $params['url']) . '">';
			$out .= htmlspecialchars($page['label']);
			$out .= '</a>';
			$out .= '</li>' . "\n";
		}

		$out .= '</ul>';

		return $out;
	}

	protected function formatDroits(array $params)
	{
		$droits = $params['droits'];

		$out = ['connexion' => '', 'inscription' => '', 'membres' => '', 'compta' => '',
			'wiki' => '', 'config' => ''];
		$classes = [
			Membres::DROIT_AUCUN   =>  'aucun',
			Membres::DROIT_ACCES   =>  'acces',
			Membres::DROIT_ECRITURE=>  'ecriture',
			Membres::DROIT_ADMIN   =>  'admin',
		];

		foreach ($droits as $cle=>$droit)
		{
			$cle = str_replace('droit_', '', $cle);

			if (array_key_exists($cle, $out))
			{

				$class = $classes[$droit];
				$desc = false;
				$s = false;

				if ($cle == 'connexion')
				{
					if ($droit == Membres::DROIT_AUCUN)
						$desc = 'N\'a pas le droit de se connecter';
					else
						$desc = 'A le droit de se connecter';
				}
				elseif ($cle == 'inscription')
				{
					if ($droit == Membres::DROIT_AUCUN)
						$desc = 'N\'a pas le droit de s\'inscrire seul';
					else
						$desc = 'A le droit de s\'inscrire seul';
				}
				elseif ($cle == 'config')
				{
					$s = '&#x2611;';

					if ($droit == Membres::DROIT_AUCUN)
						$desc = 'Ne peut modifier la configuration';
					else
						$desc = 'Peut modifier la configuration';
				}
				elseif ($cle == 'compta')
				{
					$s = '&euro;';
				}

				if (!$s)
					$s = strtoupper($cle[0]);

				if (!$desc)
				{
					$desc = ucfirst($cle). ' : ';

					if ($droit == Membres::DROIT_AUCUN)
						$desc .= 'Pas accès';
					elseif ($droit == Membres::DROIT_ACCES)
						$desc .= 'Lecture uniquement';
					elseif ($droit == Membres::DROIT_ECRITURE)
						$desc .= 'Lecture & écriture';
					else
						$desc .= 'Administration';
				}

				$out[$cle] = '<b class="'.$class.' '.$cle.'" title="'
					.htmlspecialchars($desc, ENT_QUOTES, 'UTF-8').'">'.$s.'</b>';
			}
		}

		return implode(' ', $out);
	}
}







|

<
<
|
<
<

<
<
<
<
<
|
<

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





842
843
844
845
846
847
848
849
850


851


852





853

854



855


856

857

858






















































































859
860
861
862
863
			$prev = $i;
		}

		$out .= '</table>';
		return $out;
	}

	protected function displayPermissions(array $params): string
	{


		$perms = $params['permissions'];








		$out = [];





		foreach (Category::PERMISSIONS as $name => $config) {


			$access = $perms->{'perm_' . $name};

			$label = $config['options'][$access];

			$out[$name] = sprintf('<b class="access_%s %s" title="%s">%s</b>', $access, $name, htmlspecialchars($label), $config['shape']);






















































































		}

		return implode(' ', $out);
	}
}

Modified src/include/lib/Garradin/Upgrade.php from [1ba0449d54] to [b274b8c987].

1
2
3
4
5



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

namespace Garradin;

use Garradin\Membres\Session;




class Upgrade
{
	const MIN_REQUIRED_VERSION = '0.9.8';

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

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

		if (!$v || version_compare($v, self::MIN_REQUIRED_VERSION, '<'))





>
>
>







|
<







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;

use Garradin\Membres\Session;
use Garradin\Membres\Champs;

use Garradin\Files\Files;

class Upgrade
{
	const MIN_REQUIRED_VERSION = '0.9.8';

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


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

		if (!$v || version_compare($v, self::MIN_REQUIRED_VERSION, '<'))
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
			throw new UserException('Une mise à jour est déjà en cours.'
				. PHP_EOL . 'Si celle-ci a échouée et que vous voulez ré-essayer, supprimez le fichier suivant:'
				. PHP_EOL . $path);
		}

		// Voir si l'utilisateur est loggé, on le fait ici pour le cas où
		// il y aurait déjà eu des entêtes envoyés au navigateur plus bas
		$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();

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

		// 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-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-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.0.0-rc14', '<'))
			{
				// Missing trigger
				$db->beginSchemaUpdate();
				$db->import(ROOT . '/include/data/1.0.0-rc14_migration.sql');
				$db->commitSchemaUpdate();
			}

			if (version_compare($v, '1.0.0-rc16', '<'))
			{
				// Missing trigger
				$db->beginSchemaUpdate();
				$db->import(ROOT . '/include/data/1.0.0-rc16_migration.sql');
				$db->commitSchemaUpdate();
			}

			if (version_compare($v, '1.0.1', '<'))
			{
				// Missing trigger
				$db->begin();
				$db->import(ROOT . '/include/data/1.0.1_migration.sql');
				$db->commit();
			}







|
|





|
|
<
<
<



<
<
<
<
<

|


|














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







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
			throw new UserException('Une mise à jour est déjà en cours.'
				. PHP_EOL . 'Si celle-ci a échouée et que vous voulez ré-essayer, supprimez le fichier suivant:'
				. PHP_EOL . $path);
		}

		// Voir si l'utilisateur est loggé, on le fait ici pour le cas où
		// il y aurait déjà eu des entêtes envoyés au navigateur plus bas
		$session = Session::getInstance();
		$session->start();
		return true;
	}

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




		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.0.0', '<'))
			{
				$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.1', '<'))
			{
				// Missing trigger
				$db->begin();
				$db->import(ROOT . '/include/data/1.0.1_migration.sql');
				$db->commit();
			}
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



















			if (version_compare($v, '1.0.6', '<'))
			{
				// Missing trigger
				$db->begin();
				$db->import(ROOT . '/include/data/1.0.6_migration.sql');
				$db->commit();
			}





































































			// 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();

			Plugin::upgradeAllIfRequired();
		}
		catch (\Exception $e)
		{
			$s = new Sauvegarde;
			$s->restoreFromLocal($backup_name);
			$s->remove($backup_name);
			Static_Cache::remove('upgrade');
			throw $e;
		}





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



























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



>
>
>
|
>
>

>
>
>
>
>
>
|
>
>
>

















>
>
>
>






|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
			if (version_compare($v, '1.0.6', '<'))
			{
				// Missing trigger
				$db->begin();
				$db->import(ROOT . '/include/data/1.0.6_migration.sql');
				$db->commit();
			}

			if (version_compare($v, '1.1.0-beta1', '<='))
			{
				// Missing trigger
				$db->beginSchemaUpdate();

				$attachments = $db->getAssoc('SELECT id, id || \'_\' || nom FROM fichiers;');

				// Update Skriv content for attachments
				foreach ($db->iterate('SELECT rowid, contenu FROM wiki_revisions;') as $r) {
					$content = preg_replace_callback('!<<(image|fichier)\s*\|\s*(\d+)\s*(?:\|\s*(gauche|droite|centre))?\s*(?:\|\s*(.+)\s*)?>>!', function ($match) use ($attachments) {
						$name = $attachments[$match[2]] ?? '_ERREUR_fichier_inconnu_' . $match[2];

						if (isset($match[3])) {
							$align = '|' . ($match[3] == 'centre' ? 'center' : ($match[3] == 'gauche' ? 'left' : 'right'));
						}
						else {
							$align = '';
						}

						$caption = isset($match[4]) ? '|' . $match[4] : '';

						return sprintf('<<%s|%s%s%s>>', $match[1] == 'fichier' ? 'file' : 'image', $name, $align, $caption);
					}, $r->contenu);

					$content = preg_replace_callback('!(image|fichier)://(\d+)!', function ($match) use ($attachments) {
						$name = $attachments[$match[2]] ?? '_ERREUR_fichier_inconnu_' . $match[2];
						return sprintf('#file:[%s]', $name);
					}, $content);

					if ($content != $r->contenu) {
						$db->update('wiki_revisions', ['contenu' => $content], 'rowid = :id', ['id' => $r->rowid]);
					}
				}

				$champs = new Champs($db->firstColumn('SELECT valeur FROM config WHERE cle = \'champs_membres\';'));
				$db->import(ROOT . '/include/data/1.1.0_migration.sql');

				// Rename membres table
				$champs->createTable($champs::TABLE  .'_tmp');

				$fields = $champs->getCopyFields();
				unset($fields['id_category']);
				$fields['id_categorie'] = 'id_category';
				$champs->copy($champs::TABLE, $champs::TABLE . '_tmp', $fields);

				$db->exec(sprintf('DROP TABLE IF EXISTS %s;', $champs::TABLE));
				$db->exec(sprintf('ALTER TABLE %s_tmp RENAME TO %1$s;', $champs::TABLE));

				$champs->createIndexes($champs::TABLE);

				$db->commitSchemaUpdate();

				// Migrate to a different storage
				if (FILE_STORAGE_BACKEND != 'SQLite') {
					Files::migrateStorage('SQLite', FILE_STORAGE_BACKEND, null, FILE_STORAGE_CONFIG);
					Files::truncateStorage('SQLite', null);
				}

				$pages = $db->iterate('SELECT * FROM web_pages;');

				foreach ($pages as $data) {
					$page = new \Garradin\Entities\Web\Page;
					$page->exists(true);
					$page->load((array) $data);
					$page->syncSearch();
				}
			}

			// 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);

			$cache_version_file = SHARED_CACHE_ROOT . '/version';
			$cache_version = file_exists($cache_version_file) ? trim(file_get_contents($cache_version_file)) : null;

			// Only delete system cache when it's required
			if (garradin_version() !== $cache_version) {
				Utils::resetCache(SMARTYER_CACHE_ROOT);
			}

			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)
		{
			$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)
		{
			$session->refresh();
		}
	}

	/**
	 * Move data from root to data/ subdirectory
	 * (migration from 1.0 to 1.1 version)
	 */
	static public function moveDataRoot(): void
	{
		Utils::safe_mkdir(ROOT . '/data');
		file_put_contents(ROOT . '/data/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>');

		rename(ROOT . '/cache', ROOT . '/data/cache');
		rename(ROOT . '/plugins', ROOT . '/data/plugins');

		$files = glob(ROOT . '/*.sqlite');

		foreach ($files as $file) {
			rename($file, ROOT . '/data/' . basename($file));
		}
	}
}

Added src/include/lib/Garradin/UserTemplate/CommonModifiers.php version [a93847ed3f].



















































































































































































































































































































































































































































































































































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

namespace Garradin\UserTemplate;

use Garradin\Config;
use Garradin\Utils;

/**
 * Common modifiers and functions used by Template (Smartyer) and UserTemplate
 */
class CommonModifiers
{
	const MODIFIERS_LIST = [
		'money',
		'money_currency',
		'relative_date',
		'date_short',
		'date_long',
		'date_hour',
		'date',
		'strftime',
		'size_in_bytes' => [Utils::class, 'format_bytes'],
		'typo',
	];

	const FUNCTIONS_LIST = [
		'pagination',
	];

	static public function money($number, bool $hide_empty = true): string
	{
		if ($hide_empty && !$number) {
			return '';
		}

		return sprintf('<b class="money">%s</b>', Utils::money_format($number, ',', '&nbsp;', $hide_empty));
	}

	static public function money_currency($number, bool $hide_empty = true): string
	{
		$out = self::money($number, $hide_empty);

		if ($out !== '') {
			$out .= '&nbsp;' . Config::getInstance()->get('monnaie');
		}

		return $out;
	}

	static public function date_long($ts, bool $with_hour = false): ?string
	{
		return Utils::strftime_fr($ts, '%A %e %B %Y' . ($with_hour ? ' à %Hh%M' : ''));
	}

	static public function date_short($ts, bool $with_hour = false): ?string
	{
		return Utils::date_fr($ts, 'd/m/Y' . ($with_hour ? ' à H\hi' : ''));
	}

	static public function date_hour($ts, bool $minutes_only_if_required = false): ?string
	{
		$ts = Utils::get_datetime($ts);

		if ($minutes_only_if_required && $ts->format('i') == '00') {
			return $ts->format('H\h');
		}
		else {
			return $ts->format('H\hi');
		}
	}

	static public function strftime($ts, string $format, string $locale = 'fr'): ?string
	{
		if ($locale == 'fr') {
			return Utils::strftime_fr($ts, $format);
		}

		$ts = Utils::get_datetime($ts);

		if (!$ts) {
			return $ts;
		}

		return strftime($format, $ts->getTimestamp());
	}

	static public function date($ts, string $format = null, string $locale = 'fr'): ?string
	{
		if (preg_match('/^DATE_[\w\d]+$/', $format)) {
			$format = constant('DateTime::' . $format);
		}

		if (null === $format) {
			$format = 'd/m/Y à H:i';
		}

		if ($locale == 'fr') {
			return Utils::date_fr($ts, $format);
		}

		$ts = Utils::get_datetime($ts);
		return date($format, $ts);
	}

	static public function relative_date($ts, bool $with_hour = false): string
	{
		$day = null;

		if (null === $ts) {
			return '';
		}

		$date = Utils::get_datetime($ts);

		if ($date->format('Ymd') == date('Ymd'))
		{
			$day = 'aujourd\'hui';
		}
		elseif ($date->format('Ymd') == date('Ymd', strtotime('yesterday')))
		{
			$day = 'hier';
		}
		elseif ($date->format('Ymd') == date('Ymd', strtotime('tomorrow')))
		{
			$day = 'demain';
		}
		elseif ($date->format('Y') == date('Y'))
		{
			$day = strtolower(Utils::strftime_fr($date, '%A %e %B'));
		}
		else
		{
			$day = strtolower(Utils::strftime_fr($date, '%e %B %Y'));
		}

		if ($with_hour)
		{
			$hour = $date->format('H\hi');
			return sprintf('%s, %s', $day, $hour);
		}

		return $day;
	}

	static public function typo($str, $locale = 'fr')
	{
		$str = preg_replace('/[\h]*([?!:»])(\s+|$)/u', '&nbsp;\\1\\2', $str);
		$str = preg_replace('/(^|\s+)([«])[\h]*/u', '\\1\\2&nbsp;', $str);
		return $str;
	}

	static public function pagination(array $params): string
	{
		if (!isset($params['url'], $params['page'], $params['bypage'], $params['total'])) {
			throw new \BadFunctionCallException("Paramètre manquant pour pagination");
		}

		if ($params['total'] == -1)
			return '';

		$pagination = self::getGenericPagination($params['page'], $params['total'], $params['bypage']);

		if (empty($pagination))
			return '';

		$out = '<ul class="pagination">';
		$encoded_url = rawurlencode('[ID]');

		foreach ($pagination as &$page)
		{
			$attributes = '';

			if (!empty($page['class']))
				$attributes .= ' class="' . htmlspecialchars($page['class']) . '" ';

			$out .= '<li'.$attributes.'>';

			$attributes = '';

			if (!empty($page['accesskey']))
				$attributes .= ' accesskey="' . htmlspecialchars($page['accesskey']) . '" ';

			$out .= '<a' . $attributes . ' href="' . str_replace(['[ID]', $encoded_url], htmlspecialchars($page['id']), $params['url']) . '">';
			$out .= htmlspecialchars($page['label']);
			$out .= '</a>';
			$out .= '</li>' . "\n";
		}

		$out .= '</ul>';

		return $out;
	}

	/**
	 * Génération pagination à partir de la page courante ($current),
	 * du nombre d'items total ($total), et du nombre d'items par page ($bypage).
	 * $listLength représente la longueur d'items de la pagination à génerer
	 *
	 * @param int $current
	 * @param int $total
	 * @param int $bypage
	 * @param int $listLength
	 * @param bool $showLast Toggle l'affichage du dernier élément de la pagination
	 * @return array|null
	 */
	static public function getGenericPagination($current, $total, $bypage, $listLength = 11, $showLast = true)
	{
		if ($total <= $bypage)
			return null;

		$total = ceil($total / $bypage);

		if ($total < $current)
			return null;

		$length = ($listLength / 2);

		$begin = $current - ceil($length);
		if ($begin < 1)
		{
			$begin = 1;
		}

		$end = $begin + $listLength;
		if($end > $total)
		{
			$begin -= ($end - $total);
			$end = $total;
		}
		if ($begin < 1)
		{
			$begin = 1;
		}
		if($end==($total-1)) {
			$end = $total;
		}
		if($begin == 2) {
			$begin = 1;
		}
		$out = [];

		if ($current > 1) {
			$out[] = ['id' => $current - 1, 'label' =>  '« ' . 'Page précédente', 'class' => 'prev', 'accesskey' => 'a'];
		}

		if ($begin > 1) {
			$out[] = ['id' => 1, 'label' => '1 ...', 'class' => 'first'];
		}

		for ($i = $begin; $i <= $end; $i++)
		{
			$out[] = ['id' => $i, 'label' => $i, 'class' => ($i == $current) ? 'current' : ''];
		}

		if ($showLast && $end < $total) {
			$out[] = ['id' => $total, 'label' => '... ' . $total, 'class' => 'last'];
		}

		if ($current < $total) {
			$out[] = ['id' => $current + 1, 'label' => 'Page suivante' . ' »', 'class' => 'next', 'accesskey' => 'z'];
		}

		return $out;
	}
}

Added src/include/lib/Garradin/UserTemplate/Functions.php version [3fe8fa9c3f].





















































































































































































































































































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

namespace Garradin\UserTemplate;

use KD2\Brindille;
use KD2\Brindille_Exception;
use KD2\ErrorManager;

use Garradin\Web\Skeleton;

use const Garradin\WWW_URL;

class Functions
{
	const FUNCTIONS_LIST = [
		'include',
		'http',
		'dump',
	];

	static public function dump(array $params, Brindille $tpl)
	{
		if (!count($params)) {
			$params = $tpl->getAllVariables();
		}

		$dump = htmlspecialchars(ErrorManager::dump($params));

		// FIXME: only send back HTML when content-type is text/html, or send raw text
		return sprintf('<pre style="background: yellow; padding: 5px; overflow: auto">%s</pre>', $dump);
	}

	static public function include(array $params, UserTemplate $ut, int $line): void
	{
		if (empty($params['file'])) {
			throw new Brindille_Exception(sprintf('Ligne %d: argument "file" manquant pour la fonction "include"', $line));
		}

		// Avoid recursive loops
		$from = $ut->get('included_from') ?? [];

		if (in_array($params['file'], $from)) {
			throw new Brindille_Exception(sprintf('Ligne %d : boucle infinie d\'inclusion détectée : %s', $line, $params['file']));
		}

		$s = new Skeleton($params['file']);

		if (!$s->exists()) {
			throw new Brindille_Exception(sprintf('Ligne %d : fonction "include" : le fichier à inclure "%s" n\'existe pas', $line, $params['file']));
		}

		$params['included_from'] = array_merge($from, [$params['file']]);

		$s->display($params);
	}

	static public function http(array $params): void
	{
		if (headers_sent()) {
			return;
		}

		if (isset($params['code'])) {
			static $codes = [
				100 => 'Continue',
				101 => 'Switching Protocols',
				102 => 'Processing',
				200 => 'OK',
				201 => 'Created',
				202 => 'Accepted',
				203 => 'Non-Authoritative Information',
				204 => 'No Content',
				205 => 'Reset Content',
				206 => 'Partial Content',
				207 => 'Multi-Status',
				300 => 'Multiple Choices',
				301 => 'Moved Permanently',
				302 => 'Found',
				303 => 'See Other',
				304 => 'Not Modified',
				305 => 'Use Proxy',
				306 => 'Switch Proxy',
				307 => 'Temporary Redirect',
				400 => 'Bad Request',
				401 => 'Unauthorized',
				402 => 'Payment Required',
				403 => 'Forbidden',
				404 => 'Not Found',
				405 => 'Method Not Allowed',
				406 => 'Not Acceptable',
				407 => 'Proxy Authentication Required',
				408 => 'Request Timeout',
				409 => 'Conflict',
				410 => 'Gone',
				411 => 'Length Required',
				412 => 'Precondition Failed',
				413 => 'Request Entity Too Large',
				414 => 'Request-URI Too Long',
				415 => 'Unsupported Media Type',
				416 => 'Requested Range Not Satisfiable',
				417 => 'Expectation Failed',
				418 => 'I\'m a teapot',
				422 => 'Unprocessable Entity',
				423 => 'Locked',
				424 => 'Failed Dependency',
				425 => 'Unordered Collection',
				426 => 'Upgrade Required',
				449 => 'Retry With',
				450 => 'Blocked by Windows Parental Controls',
				500 => 'Internal Server Error',
				501 => 'Not Implemented',
				502 => 'Bad Gateway',
				503 => 'Service Unavailable',
				504 => 'Gateway Timeout',
				505 => 'HTTP Version Not Supported',
				506 => 'Variant Also Negotiates',
				507 => 'Insufficient Storage',
				509 => 'Bandwidth Limit Exceeded',
				510 => 'Not Extended',
			];

			if (!isset($codes[$params['code']])) {
				throw new Brindille_Exception('Code HTTP inconnu');
			}

			header(sprintf('HTTP/1.1 %d %s', $params['code'], $codes[$params['code']]), true);
		}
		elseif (isset($params['redirect'])) {
			header('Location: ' . WWW_URL . $params['redirect'], true);
		}
		elseif (isset($params['type'])) {
			header('Content-Type: ' . $params['type'], true);
		}
		else {
			throw new Brindille_Exception('No valid parameter found for http function');
		}
	}
}

Added src/include/lib/Garradin/UserTemplate/Modifiers.php version [f62964524d].





























































































































































































































































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

namespace Garradin\UserTemplate;

use Garradin\Utils;

class Modifiers
{
	const PHP_MODIFIERS_LIST = [
		'strtolower',
		'strtoupper',
		'ucfirst',
		'ucwords',
		'htmlentities',
		'htmlspecialchars',
		'trim',
		'ltrim',
		'rtrim',
		'lcfirst',
		'md5',
		'sha1',
		'metaphone',
		'nl2br',
		'soundex',
		'str_split',
		'str_word_count',
		'strrev',
		'strlen',
		'wordwrap',
		'strip_tags',
		'strlen',
	];

	const MODIFIERS_LIST = [
		'truncate',
		'excerpt',
		'protect_contact',
		'atom_date',
		'xml_escape',
		'replace',
		'regexp_replace',
	];

	static public function replace($str, $find, $replace): string
	{
		return str_replace($find, $replace, $str);
	}

	static public function regexp_replace($str, $pattern, $replace)
	{
		return preg_replace($pattern, $replace, $str);
	}

	/**
	 * UTF-8 aware intelligent substr
	 * @param  string  $str         UTF-8 string
	 * @param  integer $length      Maximum string length
	 * @param  string  $placeholder Placeholder text to append at the string if it has been cut
	 * @param  boolean $strict_cut  If true then will cut in the middle of words
	 * @return string 				String cut to $length or shorter
	 * @example |truncate:10:" (click to read more)":true
	 */
	static public function truncate($str, $length = 80, $placeholder = '…', $strict_cut = false): string
	{
		// Don't try to use unicode if the string is not valid UTF-8
		$u = preg_match('//u', $str) ? 'u' : '';

		// Shorter than $length + 1
		if (!preg_match('/^.{' . ((int)$length + 1) . '}/s' . $u, $str))
		{
			return $str;
		}

		// Cut at 80 characters
		$str = preg_replace('/^(.{0,' . (int)$length . '}).*$/s' . $u, '$1', $str);

		if (!$strict_cut)
		{
			$cut = preg_replace('/[^\s.,:;!?]*?$/s' . $u, '', $str);

			if (trim($cut) == '') {
				$cut = $str;
			}

			$str = $cut;
		}

		return trim($str) . $placeholder;
	}

	static public function excerpt($str, $length = 600): string
	{
		$str = strip_tags($str);
		$str = self::truncate($str, $length);
		$str = preg_replace("/\n{2,}/", '</p><p>', $str);
		return '<p>' . $str . '</p>';
	}

	static public function protect_contact(string $contact): string
	{
		if (!trim($contact))
			return '';

		if (strpos($contact, '@')) {
			$reversed = strrev($contact);
			// https://unicode-table.com/en/FF20/
			$reversed = strtr($reversed, ['@' => '@']);

			return sprintf('<a href="#error" onclick="this.href = (this.innerText + \':otliam\').split(\'\').reverse().join(\'\').replace(/@/, \'@\');"><span style="unicode-bidi:bidi-override;direction: rtl;">%s</span></a>',
				htmlspecialchars($reversed));
		}
		else {
			return '<a href="'.htmlspecialchars($contact, ENT_QUOTES, 'UTF-8').'">'.htmlspecialchars($contact, ENT_QUOTES, 'UTF-8').'</a>';
		}
	}

	static public function atom_date($date)
	{
		return Utils::date_fr(DATE_ATOM, $date);
	}

	static public function xml_escape($str)
	{
		return htmlspecialchars($str, ENT_XML1);
	}
}

Added src/include/lib/Garradin/UserTemplate/Sections.php version [edc615ff84].











































































































































































































































































































































































































































































































































































































































































































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

namespace Garradin\UserTemplate;

use KD2\Brindille_Exception;
use Garradin\DB;
use Garradin\Utils;
use Garradin\Entities\Web\Page;
use Garradin\Web\Web;
use Garradin\Files\Files;
use Garradin\Entities\Files\File;

use const Garradin\WWW_URL;

class Sections
{
	const SECTIONS_LIST = [
		'categories',
		'articles',
		'pages',
		'images',
		'breadcrumbs',
		'documents',
		'files',
		'sql',
	];

	static protected $_cache = [];

	static protected function cache(string $id, callable $callback)
	{
		if (!array_key_exists($id, self::$_cache)) {
			self::$_cache[$id] = $callback();
		}

		return self::$_cache[$id];
	}

	static public function breadcrumbs(array $params, UserTemplate $tpl, int $line): \Generator
	{
		if (!isset($params['path'])) {
			throw new Brindille_Exception('"path" parameter is mandatory and is missing');
		}

		$paths = [];
		$path = '';

		foreach (explode('/', $params['path']) as $part) {
			$path = trim($path . '/' . $part, '/');
			$paths[$path] = null;
		}

		$db = DB::getInstance();
		$sql = sprintf('SELECT path, title FROM web_pages WHERE %s ORDER BY path ASC;', $db->where('path', array_keys($paths)));

		$result = $db->preparedQuery($sql);

		while ($row = $result->fetchArray(\SQLITE3_ASSOC))
		{
			$row['url'] = WWW_URL . $row['path'];
			yield $row;
		}
	}

	static public function categories(array $params, UserTemplate $tpl, int $line): \Generator
	{
		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
		}

		$params['where'] .= ' AND w.type = ' . Page::TYPE_CATEGORY;
		return self::pages($params, $tpl, $line);
	}

	static public function articles(array $params, UserTemplate $tpl, int $line): \Generator
	{
		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
		}

		$params['where'] .= ' AND w.type = ' . Page::TYPE_PAGE;
		return self::pages($params, $tpl, $line);
	}

	static public function pages(array $params, UserTemplate $tpl, int $line): \Generator
	{
		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
		}

		$params['select'] = 'w.*';
		$params['tables'] = 'web_pages w';
		$params['where'] .= ' AND status = :status';
		$params[':status'] = Page::STATUS_ONLINE;

		if (array_key_exists('search', $params)) {
			if (trim($params['search']) === '') {
				return;
			}

			$params[':search'] = substr(trim($params['search']), 0, 100);
			unset($params['search']);

			$params['tables'] .= ' INNER JOIN files_search ON files_search.path = w.file_path';
			$params['select'] .= ', rank(matchinfo(files_search), 0, 1.0, 1.0) AS points, snippet(files_search, \'<b>\', \'</b>\', \'…\', 2) AS snippet';
			$params['where'] .= ' AND files_search MATCH :search';

			$params['order'] = 'points DESC';
			$params['limit'] = '30';
		}

		if (isset($params['uri'])) {
			$params['where'] .= ' AND w.uri = :uri';
			$params['limit'] = 1;
			$params[':uri'] = $params['uri'];
			unset($params['uri']);
		}

		if (isset($params['path'])) {
			$params['where'] .= ' AND w.path = :path';
			$params['limit'] = 1;
			$params[':path'] = $params['path'];
			unset($params['path']);
		}

		if (array_key_exists('parent', $params)) {
			$params['where'] .= ' AND w.parent = :parent';
			$params[':parent'] = trim($params['parent']);

			unset($params['parent']);
		}

		if (isset($params['future'])) {
			$params['where'] .= sprintf(' AND w.published %s datetime(\'now\', \'localtime\')', $params['future'] ? '>' : '<=');
			unset($params['future']);
		}

		foreach (self::sql($params, $tpl, $line) as $row) {
			if (empty($params['count'])) {
				$data = $row;
				unset($data['points'], $data['snippet']);

				$page = new Page;
				$page->exists(true);
				$page->load($data);

				if (!$page->file()) {
					continue;
				}

				$row = array_merge($row, $page->asTemplateArray());
			}

			yield $row;
		}
	}

	static public function images(array $params, UserTemplate $tpl, int $line): \Generator
	{
		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
		}

		$params['where'] .= ' AND image = 1';
		return self::files($params, $tpl, $line);
	}

	static public function documents(array $params, UserTemplate $tpl, int $line): \Generator
	{
		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
		}

		$params['where'] .= ' AND image = 0';
		return self::files($params, $tpl, $line);
	}

	static public function files(array $params, UserTemplate $tpl, int $line): \Generator
	{
		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
		}

		if (empty($params['parent'])) {
			throw new Brindille_Exception('La section "files" doit obligatoirement comporter un paramètre "parent"');
		}

		$parent = $params['parent'];

		// Fetch page
		$page = self::cache('page_' . md5($parent), function () use ($parent) {
			$page = Web::get($parent);

			if (!$page) {
				return null;
			}

			// Store attachments in temp table
			$db = DB::getInstance();
			$db->begin();
			$db->exec('CREATE TEMP TABLE IF NOT EXISTS web_pages_attachments (page_id, path, name, modified, image);');
			$page_file_name = Utils::basename($page->file_path);

			foreach ($page->listAttachments() as $file) {
				if ($file->name == $page_file_name || $file->type != File::TYPE_FILE) {
					continue;
				}

				$db->preparedQuery('INSERT OR REPLACE INTO web_pages_attachments VALUES (?, ?, ?, ?, ?);',
					$page->id(), $file->path, $file->name, $file->modified, $file->image);
			}

			$db->commit();

			return $page;
		});

		if (!$page) {
			return;
		}

		$params['select'] = 'path';
		$params['tables'] = 'web_pages_attachments';
		$params['where'] .= ' AND page_id = :page';
		$params[':page'] = $page->id();
		unset($params['parent']);

		// Generate a temporary table containing the list of files included in the text
		if (!empty($params['except_in_text'])) {
			// Don't regenerate that table for each section called in the page,
			// we assume the content and list of files will not change between sections
			self::cache('page_files_text_' . $parent, function () use ($page) {
				$db = DB::getInstance();
				$db->begin();

				// Put files mentioned in the text in a temporary table
				$db->exec('CREATE TEMP TABLE IF NOT EXISTS files_tmp_in_text (page_id, name);');

				foreach (Page::findTaggedAttachments($page->content) as $name) {
					$db->insert('files_tmp_in_text', ['page_id' => $page->id(), 'name' => $name]);
				}

				$db->commit();
			});

			$params['where'] .= sprintf(' AND name NOT IN (SELECT name FROM files_tmp_in_text WHERE page_id = %d)', $page->id());
		}

		if (empty($params['order'])) {
			$params['order'] = 'name';
		}

		if ($params['order'] == 'name') {
			$params['order'] .= ' COLLATE NOCASE';
		}

		foreach (self::sql($params, $tpl, $line) as $row) {
			$file = Files::get($row['path']);

			if (null === $file) {
				continue;
			}

			$row = $file->asArray();
			$row['url'] = $file->url();
			$row['download_url'] = $file->url(true);
			$row['thumb_url'] = $file->thumb_url();
			$row['small_url'] = $file->thumb_url(File::THUMB_SIZE_SMALL);
			yield $row;
		}
	}

	static public function sql(array $params, UserTemplate $tpl, int $line): \Generator
	{
		static $defaults = [
			'select' => '*',
			'order' => '1',
			'begin' => 0,
			'limit' => 100,
			'where' => '',
		];

		if (!isset($params['tables'])) {
			throw new Brindille_Exception('Missing parameter "tables"');
		}

		foreach ($defaults as $key => $default_value) {
			if (!isset($params[$key])) {
				$params[$key] = $default_value;
			}
		}

		// Allow for count=true, count=1 and also count="DISTINCT user_id" count="id"
		if (!empty($params['count'])) {
			$params['select'] = sprintf('COUNT(%s) AS count', $params['count'] == 1 ? '*' : $params['count']);
			$params['order'] = '1';
		}

		$sql = sprintf('SELECT %s FROM %s WHERE 1 %s %s ORDER BY %s LIMIT %d,%d;',
			$params['select'],
			$params['tables'],
			$params['where'] ?? '',
			isset($params['group']) ? 'GROUP BY ' . $params['group'] : '',
			$params['order'],
			$params['begin'],
			$params['limit']
		);

		$db = DB::getInstance();

		try {
			$statement = $db->protectSelect(null, $sql);

			$args = [];

			foreach ($params as $key => $value) {
				if (substr($key, 0, 1) == ':') {
					$args[$key] = $value;
				}
			}

			foreach ($args as $key => $value) {
				$statement->bindValue($key, $value, $db->getArgType($value));
			}

			if (!empty($params['debug'])) {
				echo sprintf('<pre style="padding: 5px; background: yellow; white-space: normal;">%s</pre>', htmlspecialchars($statement->getSQL(true)));
			}

			$result = $statement->execute();
		}
		catch (\Exception $e) {
			throw new Brindille_Exception(sprintf("Erreur SQL à la ligne %d : %s\nRequête exécutée : %s", $line, $db->lastErrorMsg(), $sql));
		}

		while ($row = $result->fetchArray(\SQLITE3_ASSOC))
		{
			yield $row;
		}
	}
}

Added src/include/lib/Garradin/UserTemplate/UserTemplate.php version [8a0473ee5b].

































































































































































































































































































































































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

namespace Garradin\UserTemplate;

use KD2\Brindille;
use KD2\Brindille_Exception;

use Garradin\Config;
use Garradin\Plugin;
use Garradin\Utils;

use Garradin\Web\Skeleton;
use Garradin\Entities\Files\File;

use Garradin\UserTemplate\Modifiers;
use Garradin\UserTemplate\Functions;
use Garradin\UserTemplate\Sections;

use const Garradin\{WWW_URL, ADMIN_URL, SHARED_USER_TEMPLATES_CACHE_ROOT, USER_TEMPLATES_CACHE_ROOT, DATA_ROOT};

class UserTemplate extends Brindille
{
	protected $path;
	protected $modified;
	protected $file;

	static protected $root_variables;

	static public function getRootVariables()
	{
		if (null !== self::$root_variables) {
			return self::$root_variables;
		}

		static $keys = ['adresse_asso', 'champ_identifiant', 'champ_identite', 'couleur1', 'couleur2', 'email_asso', 'monnaie', 'nom_asso', 'pays', 'site_asso', 'telephone_asso'];

		if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
		{
			if (function_exists('locale_accept_from_http'))
			{
			   $lang = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
			}
			else
			{
				$lang = preg_replace('/[^a-z]/i', '', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
				$lang = strtolower(substr($lang, 0, 2));
			}

			$lang = strtolower(substr($lang, 0, 2));
		}
		else
		{
			$lang = '';
		}

		$config = Config::getInstance();

		$config = array_intersect_key($config->asArray(), array_flip($keys));

		self::$root_variables = [
			'root_url'     => WWW_URL,
			'admin_url'    => ADMIN_URL,
			'_GET'         => &$_GET,
			'_POST'        => &$_POST,
			'visitor_lang' => $lang,
			'config'       => $config,
		];

		return self::$root_variables;
	}

	public function __construct(?File $file = null)
	{
		if ($file) {
			$this->file = $file;
			$this->modified = $file->modified->getTimestamp();
		}

		$this->assignArray(self::getRootVariables());

		$this->registerAll();

		Plugin::fireSignal('usertemplate.init', ['template' => $this]);
	}

	public function registerAll()
	{
		// Register default Brindille modifiers
		$this->registerDefaults();

		// Common modifiers
		foreach (CommonModifiers::MODIFIERS_LIST as $key => $name) {
			$this->registerModifier(is_int($key) ? $name : $key, is_int($key) ? [CommonModifiers::class, $name] : $name);
		}

		foreach (CommonModifiers::FUNCTIONS_LIST as $key => $name) {
			$this->registerFunction(is_int($key) ? $name : $key, is_int($key) ? [CommonModifiers::class, $name] : $name);
		}

		// PHP modifiers
		foreach (Modifiers::PHP_MODIFIERS_LIST as $name) {
			$this->registerModifier($name, $name);
		}

		// Local modifiers
		foreach (Modifiers::MODIFIERS_LIST as $name) {
			$this->registerModifier($name, [Modifiers::class, $name]);
		}

		// Local functions
		foreach (Functions::FUNCTIONS_LIST as $name) {
			$this->registerFunction($name, [Functions::class, $name]);
		}

		// Local sections
		foreach (Sections::SECTIONS_LIST as $name) {
			$this->registerSection($name, [Sections::class, $name]);
		}
	}

	public function setSource(string $path)
	{
		$this->path = $path;
		$this->modified = filemtime($path);
	}

	public function display(): void
	{
		// Use custom cache for user templates
		if ($this->file) {
			$compiled_path = sprintf('%s/%s.php', USER_TEMPLATES_CACHE_ROOT, sha1($this->file->path));
		}
		// Use shared cache for default templates
		else {
			$compiled_path = sprintf('%s/%s.php', SHARED_USER_TEMPLATES_CACHE_ROOT, sha1($this->path));
		}

		if (file_exists($compiled_path) && filemtime($compiled_path) >= $this->modified) {
			require $compiled_path;
			return;
		}

		$tmp_path = $compiled_path . '.tmp';

		$source = $this->file ? $this->file->fetch() : file_get_contents($this->path);

		try {
			$code = $this->compile($source);
			file_put_contents($tmp_path, $code);

			require $tmp_path;
		}
		catch (Brindille_Exception $e) {
			throw new Brindille_Exception(sprintf("Erreur de syntaxe dans '%s' : %s",
				$this->file ? $this->file->name : Utils::basename($this->path),
				$e->getMessage()), 0, $e);
		}
		catch (\Throwable $e) {
			// Don't delete temporary file as it can be used to debug
			throw $e;
		}

		if (!file_exists(Utils::dirname($compiled_path))) {
			Utils::safe_mkdir(Utils::dirname($compiled_path), 0777, true);
		}

		rename($tmp_path, $compiled_path);
	}

	public function fetch(): string
	{
		ob_start();
		$this->display();
		return ob_get_clean();
	}
}

Added src/include/lib/Garradin/Users/Categories.php version [b3ce602bbd].















































































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

namespace Garradin\Users;

use Garradin\DB;
use Garradin\Entities\Users\Category;
use KD2\DB\EntityManager as EM;

class Categories
{
	static public function get(int $id): ?Category
	{
		return EM::findOneById(Category::class, $id);
	}

	static public function listSimple(): array
	{
		return DB::getInstance()->getAssoc(sprintf('SELECT id, name FROM %s ORDER BY name COLLATE NOCASE;', Category::TABLE));
	}

	static public function listWithStats(): array
	{
		return DB::getInstance()->getGrouped(sprintf('SELECT c.id, c.*,
			(SELECT COUNT(*) FROM membres WHERE id_category = c.id) AS count
			FROM %s c ORDER BY c.name COLLATE NOCASE;', Category::TABLE));
	}

	static public function listHidden(): array
	{
		return DB::getInstance()->getAssoc(sprintf('SELECT id, name FROM %s WHERE hidden = 1
			ORDER BY name COLLATE NOCASE;', Category::TABLE));
	}

	static public function listNotHidden(): array
	{
		return DB::getInstance()->getAssoc(sprintf('SELECT id, name FROM %s WHERE hidden = 0
			ORDER BY name COLLATE NOCASE;', Category::TABLE));
	}
}

Modified src/include/lib/Garradin/Utils.php from [9771f61ae9] to [8c1e367a44].

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

class Utils
{
    const EMAIL_CONTEXT_BULK = 'bulk';
    const EMAIL_CONTEXT_PRIVATE = 'private';
    const EMAIL_CONTEXT_SYSTEM = 'system';

    static protected $skriv = null;

    const FRENCH_DATE_NAMES = [
        'January'=>'Janvier', 'February'=>'Février', 'March'=>'Mars', 'April'=>'Avril', 'May'=>'Mai',
        'June'=>'Juin', 'July'=>'Juillet', 'August'=>'Août', 'September'=>'Septembre', 'October'=>'Octobre',
        'November'=>'Novembre', 'December'=>'Décembre', 'Monday'=>'Lundi', 'Tuesday'=>'Mardi', 'Wednesday'=>'Mercredi',
        'Thursday'=>'Jeudi','Friday'=>'Vendredi','Saturday'=>'Samedi','Sunday'=>'Dimanche',
        'Feb'=>'Fév','Apr'=>'Avr','Jun'=>'Juin', 'Jul'=>'Juil','Aug'=>'Aout','Dec'=>'Déc',
        'Mon'=>'Lun','Tue'=>'Mar','Wed'=>'Mer','Thu'=>'Jeu','Fri'=>'Ven','Sat'=>'Sam','Sun'=>'Dim'];

    static public function get_datetime($ts)
    {
        if (is_object($ts) && $ts instanceof \DateTimeInterface) {
            return $ts;
        }
        elseif (is_numeric($ts)) {
            return new \DateTime('@' . $ts);


        }
        elseif (strlen($ts) == 10) {
            return \DateTime::createFromFormat('!Y-m-d', $ts);
        }
        elseif (strlen($ts) == 19) {
            return \DateTime::createFromFormat('Y-m-d H:i:s', $ts);
        }







|















|
>
>







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

class Utils
{
    const EMAIL_CONTEXT_BULK = 'bulk';
    const EMAIL_CONTEXT_PRIVATE = 'private';
    const EMAIL_CONTEXT_SYSTEM = 'system';

    static protected $collator;

    const FRENCH_DATE_NAMES = [
        'January'=>'Janvier', 'February'=>'Février', 'March'=>'Mars', 'April'=>'Avril', 'May'=>'Mai',
        'June'=>'Juin', 'July'=>'Juillet', 'August'=>'Août', 'September'=>'Septembre', 'October'=>'Octobre',
        'November'=>'Novembre', 'December'=>'Décembre', 'Monday'=>'Lundi', 'Tuesday'=>'Mardi', 'Wednesday'=>'Mercredi',
        'Thursday'=>'Jeudi','Friday'=>'Vendredi','Saturday'=>'Samedi','Sunday'=>'Dimanche',
        'Feb'=>'Fév','Apr'=>'Avr','Jun'=>'Juin', 'Jul'=>'Juil','Aug'=>'Aout','Dec'=>'Déc',
        'Mon'=>'Lun','Tue'=>'Mar','Wed'=>'Mer','Thu'=>'Jeu','Fri'=>'Ven','Sat'=>'Sam','Sun'=>'Dim'];

    static public function get_datetime($ts)
    {
        if (is_object($ts) && $ts instanceof \DateTimeInterface) {
            return $ts;
        }
        elseif (is_numeric($ts)) {
            $ts = new \DateTime('@' . $ts);
            $ts->setTimezone(new \DateTimeZone(date_default_timezone_get()));
            return $ts;
        }
        elseif (strlen($ts) == 10) {
            return \DateTime::createFromFormat('!Y-m-d', $ts);
        }
        elseif (strlen($ts) == 19) {
            return \DateTime::createFromFormat('Y-m-d H:i:s', $ts);
        }
206
207
208
209
210
211
212





























213
214
215
216
217
218
219
220
    }

    static public function getModifiedURL(string $new)
    {
        return HTTP::mergeURLs(self::getSelfURL(), $new);
    }






























    public static function redirect($destination=false, $exit=true)
    {
        $destination = self::getLocalURL($destination);

        if (PHP_SAPI == 'cli') {
            echo 'Please visit ' . $destination . PHP_EOL;
            exit;
        }







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







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
    }

    static public function getModifiedURL(string $new)
    {
        return HTTP::mergeURLs(self::getSelfURL(), $new);
    }

    static public function reloadParentFrame(?string $destination = null): void
    {
        $url = self::getLocalURL($destination ?? '!');

        echo '
            <!DOCTYPE html>
            <html>
            <head>
                <script type="text/javascript">';

        if (null === $destination) {
            echo 'window.parent.location.reload();';
        }
        else {
            printf('window.parent.location.href = %s;', json_encode($url));
        }

        echo '
                </script>
            </head>

            <body>
            <p style="visibility: hidden;"><a href="' . htmlspecialchars($url) . '">Cliquer ici pour continuer</a>
            </body>
            </html>';

        exit;
    }

    public static function redirect($destination = '', $exit=true)
    {
        $destination = self::getLocalURL($destination);

        if (PHP_SAPI == 'cli') {
            echo 'Please visit ' . $destination . PHP_EOL;
            exit;
        }
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

        if (!isset($list[$code]))
            return false;

        return $list[$code];
    }

    /**
     * Génération pagination à partir de la page courante ($current),
     * du nombre d'items total ($total), et du nombre d'items par page ($bypage).
     * $listLength représente la longueur d'items de la pagination à génerer
     *
     * @param int $current
     * @param int $total
     * @param int $bypage
     * @param int $listLength
     * @param bool $showLast Toggle l'affichage du dernier élément de la pagination
     * @return array|null
     */
    public static function getGenericPagination($current, $total, $bypage, $listLength=11, $showLast = true)
    {
        if ($total <= $bypage)
            return null;

        $total = ceil($total / $bypage);

        if ($total < $current)
            return null;

        $length = ($listLength / 2);

        $begin = $current - ceil($length);
        if ($begin < 1)
        {
            $begin = 1;
        }

        $end = $begin + $listLength;
        if($end > $total)
        {
            $begin -= ($end - $total);
            $end = $total;
        }
        if ($begin < 1)
        {
            $begin = 1;
        }
        if($end==($total-1)) {
            $end = $total;
        }
        if($begin == 2) {
            $begin = 1;
        }
        $out = [];

        if ($current > 1) {
            $out[] = ['id' => $current - 1, 'label' =>  '« ' . 'Page précédente', 'class' => 'prev', 'accesskey' => 'a'];
        }

        if ($begin > 1) {
            $out[] = ['id' => 1, 'label' => '1 ...', 'class' => 'first'];
        }

        for ($i = $begin; $i <= $end; $i++)
        {
            $out[] = ['id' => $i, 'label' => $i, 'class' => ($i == $current) ? 'current' : ''];
        }

        if ($showLast && $end < $total) {
            $out[] = ['id' => $total, 'label' => '... ' . $total, 'class' => 'last'];
        }

        if ($current < $total) {
            $out[] = ['id' => $current + 1, 'label' => 'Page suivante' . ' »', 'class' => 'next', 'accesskey' => 'z'];
        }

        return $out;
    }

    static public function transliterateToAscii($str, $charset='UTF-8')
    {
        // Don't process empty strings
        if (!trim($str))
            return $str;

        // We only process non-ascii strings







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







296
297
298
299
300
301
302








































































303
304
305
306
307
308
309

        if (!isset($list[$code]))
            return false;

        return $list[$code];
    }









































































    static public function transliterateToAscii($str, $charset='UTF-8')
    {
        // Don't process empty strings
        if (!trim($str))
            return $str;

        // We only process non-ascii strings
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464

        $str = preg_replace('#&[^;]+;#', '', $str); // supprime les autres caractères
        $str = preg_replace('![^[:ascii:]]+!', '', $str);

        return $str;
    }

    /**
     * Transforme un texte SkrivML en HTML
     * @param  string $str Texte SkrivML
     * @return string      Texte HTML
     */
    static public function SkrivToHTML($str)
    {
        if (!self::$skriv)
        {
            self::$skriv = new \KD2\SkrivLite;
            self::$skriv->registerExtension('fichier', ['\\Garradin\\Fichiers', 'SkrivFichier']);
            self::$skriv->registerExtension('image', ['\\Garradin\\Fichiers', 'SkrivImage']);

            // Enregistrer d'autres extensions éventuellement
            Plugin::fireSignal('skriv.init', ['skriv' => self::$skriv]);
        }

        $skriv =& self::$skriv;

        $str = preg_replace_callback('/(fichier|image):\/\/(\d+)/', function ($match) use ($skriv) {
            try {
                $file = new Fichiers((int)$match[2]);
            }
            catch (\InvalidArgumentException $e)
            {
                return $skriv->parseError('/!\ Lien fichier : ' . $e->getMessage());
            }

            return $file->getURL();
        }, $str);

        $str = self::$skriv->render($str);

        return $str;
    }

    /**
     * Transforme les tags de base SPIP en tags SkrivML
     * @param  string $str Texte d'entrée
     * @return string      Texte transformé
     */
    static public function SpipToSkriv($str)
    {
        $str = preg_replace('/(?<!\\\\)\{{3}(\V*)\}{3}/', '=== $1 ===', $str);
        $str = preg_replace('/(?<!\\\\)\{{2}(\V*)\}{2}/', '**$1**', $str);
        $str = preg_replace('/(?<!\\\\)\{(\V*)\}/', '\'\'$1\'\'', $str);
        $str = preg_replace('/(?<!\\\\)\[(.+?)->(.+?)\]/', '[[$1 | $2]]', $str);
        $str = preg_replace('/(?<!\[)\[([^\[\]]+?)\]/', '[[$1]]', $str);
        return $str;
    }

    /**
     * Transforme les tags HTML basiques en tags SkrivML
     * @param  string $str Texte d'entrée
     * @return string      Texte transformé
     */
    static public function HTMLToSkriv($str)
    {
        $str = preg_replace('/<h3>(\V*?)<\/h3>/', '=== $1 ===', $str);
        $str = preg_replace('/<b>(\V*)<\/b>/', '**$1**', $str);
        $str = preg_replace('/<strong>(\V*?)<\/strong>/', '**$1**', $str);
        $str = preg_replace('/<i>(\V*?)<\/i>/', '\'\'$1\'\'', $str);
        $str = preg_replace('/<em>(\V*?)<\/em>/', '\'\'$1\'\'', $str);
        $str = preg_replace('/<li>(\V*?)<\/li>/', '* $1', $str);
        $str = preg_replace('/<ul>|<\/ul>/', '', $str);
        $str = preg_replace('/<a href="([^"]*?)">(\V*?)<\/a>/', '[[$2 | $1]]', $str);
        return $str;
    }

    static public function clearCaches($path = false)
    {
        if (!$path)
        {
            self::clearCaches('compiled');
            self::clearCaches('static');
            return true;
        }

        $path = CACHE_ROOT . '/' . $path;
        $dir = dir($path);

        while ($file = $dir->read())
        {
            if ($file[0] != '.')
            {
                self::safe_unlink($path . DIRECTORY_SEPARATOR . $file);
            }
        }

        $dir->close();
        return true;
    }

    static public function safe_unlink($path)
    {
        if (!@unlink($path))
        {
            return true;
        }








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


















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







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

        $str = preg_replace('#&[^;]+;#', '', $str); // supprime les autres caractères
        $str = preg_replace('![^[:ascii:]]+!', '', $str);

        return $str;
    }




















































    /**
     * Transforme les tags HTML basiques en tags SkrivML
     * @param  string $str Texte d'entrée
     * @return string      Texte transformé
     */
    static public function HTMLToSkriv($str)
    {
        $str = preg_replace('/<h3>(\V*?)<\/h3>/', '=== $1 ===', $str);
        $str = preg_replace('/<b>(\V*)<\/b>/', '**$1**', $str);
        $str = preg_replace('/<strong>(\V*?)<\/strong>/', '**$1**', $str);
        $str = preg_replace('/<i>(\V*?)<\/i>/', '\'\'$1\'\'', $str);
        $str = preg_replace('/<em>(\V*?)<\/em>/', '\'\'$1\'\'', $str);
        $str = preg_replace('/<li>(\V*?)<\/li>/', '* $1', $str);
        $str = preg_replace('/<ul>|<\/ul>/', '', $str);
        $str = preg_replace('/<a href="([^"]*?)">(\V*?)<\/a>/', '[[$2 | $1]]', $str);
        return $str;
    }

























    static public function safe_unlink($path)
    {
        if (!@unlink($path))
        {
            return true;
        }

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
599
600
601
602
603
604
605
606
607
            case 'K': case 'k': return (int)$size_str * 1024;
            default: return $size_str;
        }
    }

    static public function format_bytes($size)
    {
        if ($size > (1024 * 1024))





            return number_format(round($size / 1024 / 1024, 2), 2, ',', '') . ' Mo';



        elseif ($size > 1024)
            return round($size / 1024) . ' Ko';

        else
            return $size . ' o';
    }








































    static public function deleteRecursive($path)
    {
        if (!file_exists($path))
            return false;

        $dir = dir($path);
        if (!$dir) return false;

        while ($file = $dir->read())
        {
            if ($file == '.' || $file == '..')
                continue;

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

        $dir->close();
        rmdir($path);

        return true;







|
>
>
>
>
>
|
>
>
>
|

>




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












|

|




|







449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
            case 'K': case 'k': return (int)$size_str * 1024;
            default: return $size_str;
        }
    }

    static public function format_bytes($size)
    {
        if ($size > (1024 * 1024 * 1024)) {
            $size = round($size / 1024 / 1024 / 1024, 2);
            $decimals = $size == (int) $size ? 0 : 2;
            return number_format($size, $decimals, ',', '') . ' Go';
        }
        elseif ($size > (1024 * 1024)) {
            $size = round($size / 1024 / 1024, 2);
            $decimals = $size == (int) $size ? 0 : 2;
            return number_format($size, $decimals, ',', '') . ' Mo';
        }
        elseif ($size > 1024) {
            return round($size / 1024) . ' Ko';
        }
        else
            return $size . ' o';
    }

    static public function createEmptyDirectory(string $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>');
    }

    static public function resetCache(string $path): void
    {
        if (!file_exists($path)) {
            self::createEmptyDirectory($path);
            return;
        }

        $dir = dir($path);

        while ($file = $dir->read()) {
            if (substr($file, 0, 1) == '.' || is_dir($path . DIRECTORY_SEPARATOR . $file)) {
                continue;
            }

            self::safe_unlink($path . DIRECTORY_SEPARATOR . $file);
        }

        $dir->close();
    }

    static public function deleteRecursive(string $path, bool $delete_self = false): bool
    {
        if (!file_exists($path))
            return false;

        $dir = dir($path);
        if (!$dir) return false;

        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;
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865


866


867
868
869
870
871
872
873
            }
            $h /= 6;
        }

        return array($h * 360, $s, $v);
    }

    static public function HTTPCache(string $hash, int $last_change): bool
    {
        $etag = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : null;
        $last_modified = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : null;

        if ($etag === $hash && $last_modified >= $last_change) {
            header('HTTP/1.1 304 Not Modified', true, 304);
            exit;
        }

        header(sprintf('Last-Modified: %s GMT', gmdate('D, d M Y H:i:s', $last_change)));


        header(sprintf('Etag: %s', $hash));


        header('Cache-Control: private');

        return false;
    }

    static public function getLatestVersion(): ?string
    {







|










>
>
|
>
>







780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
            }
            $h /= 6;
        }

        return array($h * 360, $s, $v);
    }

    static public function HTTPCache(?string $hash, int $last_change): bool
    {
        $etag = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : null;
        $last_modified = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : null;

        if ($etag === $hash && $last_modified >= $last_change) {
            header('HTTP/1.1 304 Not Modified', true, 304);
            exit;
        }

        header(sprintf('Last-Modified: %s GMT', gmdate('D, d M Y H:i:s', $last_change)));

        if ($etag) {
            header(sprintf('Etag: %s', $hash));
        }

        header('Cache-Control: private');

        return false;
    }

    static public function getLatestVersion(): ?string
    {
914
915
916
917
918
919
920
921























































        }

        $config->set('last_version_check', json_encode($last));
        $config->save();

        return $last->version;
    }
}






























































|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
        }

        $config->set('last_version_check', json_encode($last));
        $config->save();

        return $last->version;
    }

    static public function transformTitleToURI($str)
    {
        $str = Utils::transliterateToAscii($str);

        $str = preg_replace('![^\w\d_-]!i', '-', $str);
        $str = preg_replace('!-{2,}!', '-', $str);
        $str = trim($str, '-');

        return $str;
    }

    /**
     * dirname may have undefined behaviour depending on the locale!
     */
    static public function dirname(string $str): string
    {
        $str = str_replace(DIRECTORY_SEPARATOR, '/', $str);
        return substr($str, 0, strrpos($str, '/'));
    }

    /**
     * basename may have undefined behaviour depending on the locale!
     */
    static public function basename(string $str): string
    {
        $str = str_replace(DIRECTORY_SEPARATOR, '/', $str);
        $str = trim($str, '/');
        $str = substr($str, strrpos($str, '/'));
        $str = trim($str, '/');
        return $str;
    }

    static public function unicodeCaseComparison($a, $b): int
    {
        if (!isset(self::$collator) && function_exists('collator_create')) {
            self::$collator = \Collator::create('fr_FR');
            self::$collator->setAttribute(\Collator::NUMERIC_COLLATION, \Collator::ON);
        }

        if (isset(self::$collator)) {
            return self::$collator->compare($a, $b);
        }

        $a = strtoupper(self::transliterateToAscii($a));
        $b = strtoupper(self::transliterateToAscii($b));

        return strcmp($a, $b);
    }

    static public function knatcasesort(array $array)
    {
        uksort($array, [self::class, 'unicodeCaseComparison']);
        return $array;
    }
}

Added src/include/lib/Garradin/Web/Render/EncryptedSkriv.php version [8b803e3b49].







































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

namespace Garradin\Web\Render;

use Garradin\Entities\Files\File;
use Garradin\Template;
use const Garradin\ADMIN_URL;

class EncryptedSkriv
{
	static public function render(File $file, ?string $content = null): string
	{
		$tpl = Template::getInstance();
		$content = $content ?? $file->fetch();
		$tpl->assign('admin_url', ADMIN_URL);
		$tpl->assign(compact('file', 'content'));
		return $tpl->fetch('common/files/_file_render_encrypted.tpl');
	}
}

Added src/include/lib/Garradin/Web/Render/HTML.php version [e2b502a15f].













































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

namespace Garradin\Files\Render;

use Garradin\Entities\Files\File;

use KD2\Garbage2xhtml;

class HTML
{
	static protected $g2x;

	static public function render(File $file, ?string $content = null): string
	{
		if (null === self::$g2x) {
			$g2x = self::$g2x = new Garbage2xhtml;
			$g2x->auto_br = false;
		}

		return self::$g2x->process($content ?? $file->fetch());
	}
}

Added src/include/lib/Garradin/Web/Render/Skriv.php version [f000051146].















































































































































































































































































































































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

namespace Garradin\Web\Render;

use Garradin\Entities\Files\File;

use Garradin\Squelette_Filtres;
use Garradin\Plugin;
use Garradin\Utils;
use Garradin\Files\Files;
use Garradin\UserTemplate\CommonModifiers;

use KD2\SkrivLite;

use const Garradin\{ADMIN_URL, WWW_URL};

class Skriv
{
	static protected $skriv;

	static protected $current_path;
	static protected $context;
	static protected $link_prefix;
	static protected $link_suffix;

	static protected function resolveAttachment(string $uri) {
		$prefix = self::$current_path;
		$pos = strpos($uri, '/');

		// "Image.jpg"
		if ($pos === false) {
			return WWW_URL . $prefix . '/' . $uri;
		}
		// "bla/Image.jpg" outside of web context
		elseif (self::$context !== File::CONTEXT_WEB && $pos !== 0) {
			return WWW_URL . '/' . self::$context . '/' . $uri;
		}
		// "bla/Image.jpg" in web context or absolute link, eg. "/transactions/2442/42.jpg"
		else {
			return WWW_URL . '/' . ltrim($uri, '/');
		}
	}

	static public function resolveLink(string $uri) {
		if (strpos(Utils::basename($uri), '.') === false) {
			$uri .= self::$link_suffix;
		}

		return self::$link_prefix . $uri;
	}

	static public function render(?File $file, ?string $content = null, array $options = []): string
	{
		if (!self::$skriv)
		{
			self::$skriv = new \KD2\SkrivLite;
			self::$skriv->registerExtension('file', [self::class, 'SkrivFile']);
			self::$skriv->registerExtension('image', [self::class, 'SkrivImage']);

			// Enregistrer d'autres extensions éventuellement
			Plugin::fireSignal('skriv.init', ['skriv' => self::$skriv]);
		}

		$skriv =& self::$skriv;

		if ($file) {
			self::$current_path = Utils::dirname($file->path);
			self::$context = strtok(self::$current_path, '/');
			self::$link_suffix = '';

			if (self::$context === File::CONTEXT_WEB) {
				self::$link_prefix = WWW_URL . '/';
				self::$current_path = Utils::basename(Utils::dirname($file->path));
			}
			else {
				self::$link_prefix = $options['prefix'] ?? sprintf(ADMIN_URL . 'common/files/preview.php?p=%s/', self::$context);
				self::$link_suffix = '.skriv';
			}
		}

		$str = $content ?? $file->fetch();

		$str = preg_replace_callback('/#file:\[([^\]\h]+)\]/', function ($match) {
			return self::resolveAttachment($match[1]);
		}, $str);

		$str = self::$skriv->render($str);

		$str = CommonModifiers::typo($str);

		$str = preg_replace_callback(';<a href="((?!https?://|\w+:).+)">;i', function ($matches) {
			return sprintf('<a href="%s" target="_parent">', self::resolveLink($matches[1]));
		}, $str);

		return sprintf('<div class="web-content">%s</div>', $str);
	}

	/**
	 * Callback utilisé pour l'extension <<file>> dans le wiki-texte
	 * @param array $args    Arguments passés à l'extension
	 * @param string $content Contenu éventuel (en mode bloc)
	 * @param SkrivLite $skriv   Objet SkrivLite
	 */
	static public function SkrivFile(array $args, ?string $content, SkrivLite $skriv): string
	{
		$name = $args[0] ?? null;
		$caption = $args[1] ?? null;

		if (!$name || !self::$current_path)
		{
			return $skriv->parseError('/!\ Tag file : aucun nom de fichier indiqué.');
		}

		if (empty($caption))
		{
			$caption = $name;
		}

		$url = self::resolveAttachment($name);
		$ext = substr($name, strrpos($name, '.')+1);

		return sprintf(
			'<aside class="file" data-type="%s"><a href="%s" class="internal-file">%s</a> <small>(%s)</small></aside>',
			htmlspecialchars($ext), htmlspecialchars($url), htmlspecialchars($caption), htmlspecialchars(strtoupper($ext))
		);
	}

	/**
	 * Callback utilisé pour l'extension <<image>> dans le wiki-texte
	 * @param array $args    Arguments passés à l'extension
	 * @param string $content Contenu éventuel (en mode bloc)
	 * @param SkrivLite $skriv   Objet SkrivLite
	 */
	static public function SkrivImage(array $args, ?string $content, SkrivLite $skriv): string
	{
		static $align_values = ['left', 'right', 'center'];

		$name = $args[0] ?? null;
		$align = $args[1] ?? null;
		$caption = $args[2] ?? null;

		if (!$name || !self::$current_path)
		{
			return $skriv->parseError('/!\ Tag image : aucun nom de fichier indiqué.');
		}

		$url = self::resolveAttachment($name);
		$thumb_url = sprintf('%s?%dpx', $url, $align == 'center' ? 500 : 200);

		$out = sprintf('<a href="%s" class="internal-image" target="_image"><img src="%s" alt="%s" loading="lazy" /></a>',
			htmlspecialchars($url),
			htmlspecialchars($thumb_url),
			htmlspecialchars($caption ?? $name)
		);

		if (!empty($align))
		{
			if ($caption) {
				$caption = sprintf('<figcaption>%s</figcaption>', htmlspecialchars($caption));
			}

			$out = sprintf('<figure class="image img-%s">%s%s</figure>', $align, $out, $caption);
		}

		return $out;
	}
}

Added src/include/lib/Garradin/Web/Skeleton.php version [0353cf768c].







































































































































































































































































































































































































































































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

namespace Garradin\Web;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\UserException;
use Garradin\UserTemplate\UserTemplate;

use KD2\Brindille_Exception;
use KD2\DB\EntityManager as EM;

use const Garradin\ROOT;

class Skeleton
{
	const TEMPLATE_TYPES = '!^(?:text/(?:html|plain)|\w+/(?:\w+\+)?xml)$!';

	protected $name;
	protected $file;

	public function __construct(string $tpl)
	{
		if (!preg_match('!^[\w\d_-]+(?:\.[\w\d_-]+)*$!i', $tpl)) {
			throw new \InvalidArgumentException('Invalid skeleton name');
		}

		$this->file = Files::get(File::CONTEXT_SKELETON . '/' . $tpl);

		$this->name = $tpl;
	}

	public function defaultPath(): ?string
	{
		$path = ROOT . '/www/skel-dist/' . $this->name;

		if (file_exists($path)) {
			return $path;
		}

		return null;
	}

	public function serve(array $params = []): bool
	{
		header('Content-Type: text/html;charset=utf-8', true);

		if (!$this->exists()) {
			header('HTTP/1.1 404 Not Found', true);
			$tpl = new self('404.html');

			if (!$tpl->serve()) {
				throw new UserException('Cette page n\'existe pas.');
			}
		}

		if (preg_match(self::TEMPLATE_TYPES, $this->type())) {
			$ut = new UserTemplate($this->file);

			if (!$this->file) {
				$ut->setSource($this->defaultPath());
			}

			header(sprintf('Content-Type: %s;charset=utf-8', $this->type()));

			try {
				$ut->assignArray($params);
				$ut->display();
			}
			catch (Brindille_Exception $e) {
				printf('<div style="border: 5px solid orange; padding: 10px; background: yellow;"><h2>Erreur dans le squelette</h2><p>%s</p></div>', nl2br(htmlspecialchars($e->getMessage())));
			}
		}
		elseif ($this->file) {
			$this->file->serve();
		}
		else {
			header(sprintf('Content-Type: %s;charset=utf-8', $this->type()));
			readfile($this->defaultPath());
		}


		return true;
	}

	public function fetch(array $params = []): string
	{
		if (!$this->exists()) {
			return '';
		}

		if (preg_match(self::TEMPLATE_TYPES, $this->type())) {
			$ut = new UserTemplate($this->file);

			if (!$this->file) {
				$ut->setSource($this->defaultPath());
			}

			$ut->assignArray($params);

			return $ut->fetch();
		}
		elseif ($this->file) {
			return $this->file->fetch();
		}
		else {
			return file_get_contents($this->defaultPath());
		}
	}

	public function display(array $params = []): void
	{
		if (!$this->exists()) {
			return;
		}

		if (preg_match(self::TEMPLATE_TYPES, $this->type())) {
			$ut = new UserTemplate($this->file);

			if (!$this->file) {
				$ut->setSource($this->defaultPath());
			}

			$ut->assignArray($params);

			$ut->display();
		}
		elseif ($this->file) {
			$this->file->display();
		}
		else {
			readfile($this->defaultPath());
		}
	}

	public function exists()
	{
		return $this->file ? true : ($this->defaultPath() ? true : false);
	}

	public function raw(): string
	{
		return $this->file ? $this->file->fetch() : file_get_contents($this->defaultPath());
	}

	public function edit(string $content)
	{
		$file = Files::get(File::CONTEXT_SKELETON . '/' . $this->name);

		if ($file) {
			$file->setContent($content);
		}
		else {
			File::createAndStore(File::CONTEXT_SKELETON, $this->name, null, $content);
		}
	}

	public function type(): string
	{
		$name = $this->file->name ?? $this->defaultPath();
		$ext = substr($name, strrpos($name, '.')+1);

		if ($ext == 'css') {
			return 'text/css';
		}
		elseif ($ext == 'html') {
			return 'text/html';
		}
		elseif ($ext == 'js') {
			return 'text/javascript';
		}

		if ($this->file) {
			return $this->file->type;
  		}

		$finfo = \finfo_open(\FILEINFO_MIME_TYPE);
		return finfo_file($finfo, $this->defaultPath());

	}

	public function reset()
	{
		if ($this->file) {
			$this->file->delete();
		}
	}

	static public function resetSelected(array $selected)
	{
		foreach ($selected as $file) {
			$f = new self($file);
			$f->reset();
		}
	}

	static public function list(): array
	{
		$sources = [];

		$dir = dir(ROOT . '/www/skel-dist/');

		while ($file = $dir->read())
		{
			if ($file[0] == '.')
				continue;

			$sources[$file] = null;
		}

		$dir->close();

		$list = Files::list(File::CONTEXT_SKELETON);

		foreach ($list as $file) {
			if ($file->type != $file::TYPE_FILE) {
				continue;
			}

			$sources[$file->name] = $file;
		}

		ksort($sources);

		return $sources;
	}
}

Added src/include/lib/Garradin/Web/Web.php version [a2f7a3c8e7].

















































































































































































































































































































































































































































































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

namespace Garradin\Web;

use Garradin\Entities\Web\Page;
use Garradin\Entities\Files\File;
use Garradin\Web\Skeleton;
use Garradin\Files\Files;
use Garradin\API;
use Garradin\Config;
use Garradin\DB;
use Garradin\Utils;
use Garradin\UserException;
use Garradin\Membres\Session;

use KD2\DB\EntityManager as EM;

use const Garradin\{WWW_URI, ADMIN_URL};

class Web
{
	static public function search(string $search): array
	{
		$results = Files::search($search, File::CONTEXT_WEB . '%');

		foreach ($results as &$result) {
			$result->uri = Utils::dirname(substr($result->path, strlen(File::CONTEXT_WEB) + 1));
			$result->breadcrumbs = [];
			$path = '';

			foreach (explode('/', $result->uri) as $part) {
				$path = trim($path . '/' . $part, '/');
				$result->breadcrumbs[$path] = $part;
			}
		}

		return $results;
	}

	static public function sync(?string $parent)
	{
		$path = trim(File::CONTEXT_WEB . '/' . $parent, '/');

		$exists = [];

		foreach (Files::callStorage('list', $path) as $file) {
			if ($file->type != File::TYPE_DIRECTORY) {
				continue;
			}

			$exists[$file->path] = null;
		}

		$db = DB::getInstance();

		$in_db = $db->getGrouped('SELECT dirname(file_path), file_path, path, modified FROM web_pages WHERE parent = ?;', $parent);

		$deleted = array_diff_key($in_db, $exists);
		$new = array_diff_key($exists, $in_db);

		if ($deleted) {
			$deleted = array_map(function ($page) {
				return $page->path;
			}, $deleted);

			$db->exec(sprintf('DELETE FROM web_pages WHERE %s;', $db->where('path', $deleted)));
		}

		foreach ($new as $file) {
			$f = Files::get($file . '/index.txt');

			if (!$f) {
				continue;
			}

			Page::fromFile($f)->save();
		}

		/*
		// There's no need for that sync as it is triggered when loading a Page entity!
		$intersection = array_intersect_key($in_db, $exists);
		foreach ($intersection as $page) {
			$file = Files::get($page->file_path);

			$modified = new \DateTime($page->modified);

			if ($modified == $file->modified) {
				continue;
			}

			$page = Web::get($page->path);
			$page->loadFromFile($file);
			$page->save();
		}
		 */
	}

	static public function listCategories(string $parent): array
	{
		$sql = 'SELECT * FROM @TABLE WHERE parent = ? AND type = ? ORDER BY title COLLATE NOCASE;';
		return EM::getInstance(Page::class)->all($sql, $parent, Page::TYPE_CATEGORY);
	}

	static public function listPages(string $parent, bool $order_by_date = true): array
	{
		$order = $order_by_date ? 'published DESC' : 'title COLLATE NOCASE';
		$sql = sprintf('SELECT * FROM @TABLE WHERE parent = ? AND type = %d ORDER BY %s;', Page::TYPE_PAGE, $order);
		return EM::getInstance(Page::class)->all($sql, $parent);
	}

	static public function get(string $path): ?Page
	{
		$page = EM::findOne(Page::class, 'SELECT * FROM @TABLE WHERE path = ?;', $path);

		if ($page && !$page->file()) {
			return null;
		}

		return $page;
	}

	static public function getByURI(string $uri): ?Page
	{
		$page = EM::findOne(Page::class, 'SELECT * FROM @TABLE WHERE uri = ?;', $uri);

		if ($page && !$page->file()) {
			return null;
		}

		return $page;
	}

	static public function getAttachmentFromURI(string $uri): ?File
	{
		if (strpos($uri, '/') === false) {
			return null;
		}

		$path = DB::getInstance()->firstColumn('SELECT path FROM web_pages WHERE uri = ?;', Utils::dirname($uri));

		if (!$path) {
			return null;
		}

		return Files::getFromURI(File::CONTEXT_WEB . '/' . $path . '/' . Utils::basename($uri));
	}

	static public function dispatchURI()
	{
		$uri = !empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';

		if ($pos = strpos($uri, '?')) {
			$uri = substr($uri, 0, $pos);
		}

		// WWW_URI inclus toujours le slash final, mais on veut le conserver ici
		$uri = substr($uri, strlen(WWW_URI) - 1);

		http_response_code(200);

		$uri = substr($uri, 1);

		// Redirect old URLs (pre-1.1)
		if ($uri == 'feed/atom/') {
			Utils::redirect('/atom.xml');
		}
		elseif (substr($uri, 0, 4) == 'api/') {
			API::dispatchURI(substr($uri, 4));
			exit;
		}
		elseif (substr($uri, 0, 6) === 'admin/') {
			http_response_code(404);
			throw new UserException('Cette page n\'existe pas.');
		}
		elseif (($file = Files::getFromURI($uri))
			|| ($file = self::getAttachmentFromURI($uri))) {
			$size = null;

			foreach ($_GET as $key => $value) {
				if (substr($key, -2) == 'px') {
					$size = (int)substr($key, 0, -2);
					break;
				}
			}

			$session = Session::getInstance();

			if ($size) {
				$file->serveThumbnail($session, $size);
			}
			else {
				$file->serve($session, isset($_GET['download']) ? true : false);
			}

			return;
		}

		if (Config::getInstance()->get('site_disabled')) {
			Utils::redirect(ADMIN_URL);
		}

		$page = null;

		if ($uri == '') {
			$skel = 'index.html';
		}
		elseif (($page = self::getByURI($uri)) && $page->status == Page::STATUS_ONLINE) {
			$skel = $page->template();
			$page = $page->asTemplateArray();
		}
		else {
			// Trying to see if a custom template with this name exists
			if (preg_match('!^[\w\d_-]+(?:\.[\w\d_-]+)*$!i', $uri)) {
				$s = new Skeleton($uri);

				if ($s->exists()) {
					$s->serve();
					return;
				}
			}
			elseif ($file = Files::getFromURI(File::CONTEXT_SKELETON . '/' . $uri)) {
				$file->serve();
				return;
			}

			$skel = '404.html';
		}

		$s = new Skeleton($skel);
		$s->serve(compact('uri', 'page', 'skel'));
	}
}

Deleted src/include/lib/Garradin/Wiki.php version [6ab9be5a8f].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
<?php

namespace Garradin;

class Wiki
{
    const LECTURE_PUBLIC = -1;
    const LECTURE_NORMAL = 0;
    const LECTURE_CATEGORIE = 1;

    const ECRITURE_NORMAL = 0;
    const ECRITURE_CATEGORIE = 1;

    const ITEMS_PER_PAGE = 25;

    protected $restriction_categorie = null;
    protected $restriction_droit = null;

    static public function transformTitleToURI($str)
    {
        $str = Utils::transliterateToAscii($str);

        $str = preg_replace('![^\w\d_-]!i', '-', $str);
        $str = preg_replace('!-{2,}!', '-', $str);
        $str = trim($str, '-');

        return $str;
    }

    // Gestion des données ///////////////////////////////////////////////////////

    public function _checkFields(&$data)
    {
        $db = DB::getInstance();

        if (array_key_exists('titre', $data) && !trim($data['titre']))
        {
            throw new UserException('Le titre ne peut rester vide.');
        }

        if (array_key_exists('uri', $data) && !trim($data['uri']))
        {
            throw new UserException('L\'adresse de la page ne peut rester vide.');
        }

        if (array_key_exists('droit_lecture', $data))
        {
            $data['droit_lecture'] = (int) $data['droit_lecture'];

            if ($data['droit_lecture'] < -1)
            {
                $data['droit_lecture'] = 0;
            }
        }

        if (array_key_exists('droit_ecriture', $data))
        {
            $data['droit_ecriture'] = (int) $data['droit_ecriture'];

            if ($data['droit_ecriture'] < 0)
            {
                $data['droit_ecriture'] = 0;
            }
        }

        if (array_key_exists('parent', $data))
        {
            $data['parent'] = (int) $data['parent'];

            if ($data['parent'] < 0)
            {
                $data['parent'] = 0;
            }

            if (!$db->firstColumn('SELECT 1 FROM wiki_pages WHERE id = ?;', $data['parent']))
            {
                $data['parent'] = 0;
            }
        }

        return true;
    }

    public function create($data = [])
    {
        $this->_checkFields($data);
        $db = DB::getInstance();

        if (!empty($data['uri']))
        {
            $data['uri'] = self::transformTitleToURI($data['uri']);

            if ($db->firstColumn('SELECT 1 FROM wiki_pages WHERE uri = ? LIMIT 1;', $data['uri']))
            {
                throw new UserException('Cette adresse de page est déjà utilisée pour une autre page, il faut en choisir une autre.');
            }
        }
        else
        {
            $data['uri'] = self::transformTitleToURI($data['titre']);

            if (!trim($data['uri']) || $db->firstColumn('SELECT 1 FROM wiki_pages WHERE uri = ? LIMIT 1;', $data['uri']))
            {
                $data['uri'] .= '_' . date('d-m-Y_H-i-s');
            }
        }

        $db->insert('wiki_pages', $data);
        $id = $db->lastInsertRowId();

        // On ne peut utiliser un trigger pour insérer dans la recherche
        // car les tables virtuelles font des opérations qui modifient
        // last_insert_rowid() et donc résultat incohérent
        $db->insert('wiki_recherche', ['id' => $id, 'titre' => $data['titre']]);

        return $id;
    }

    public function edit($id, $data = [])
    {
        $db = DB::getInstance();
        $this->_checkFields($data);

        // Modification de la date de création: vérification que le format est bien conforme SQLite
        if (isset($data['date_creation']))
        {
        	if (!Utils::checkDateTime($data['date_creation']))
	        {
	            throw new UserException('Date invalide: '.($data['date_creation'] ?: 'date non reconnue'));
	        }

	        // On stocke la date en UTC, pas dans le fuseau local
	        $data['date_creation'] = gmdate('Y-m-d H:i:s', strtotime($data['date_creation']));
	    }
        
        if (isset($data['uri']))
        {
            $data['uri'] = self::transformTitleToURI($data['uri']);

            if ($db->firstColumn('SELECT 1 FROM wiki_pages WHERE uri = ? AND id != ? LIMIT 1;', $data['uri'], (int)$id))
            {
                throw new UserException('Cette adresse de page est déjà utilisée pour une autre page, il faut en choisir une autre.');
            }
        }

        if (isset($data['droit_lecture']) && $data['droit_lecture'] >= self::LECTURE_CATEGORIE)
        {
            $data['droit_ecriture'] = $data['droit_lecture'];
        }

        if (isset($data['parent']) && (int)$data['parent'] == (int)$id)
        {
            $data['parent'] = 0;
        }

        $data['date_modification'] = gmdate('Y-m-d H:i:s');

        $db->update('wiki_pages', $data, 'id = :id', ['id' => (int)$id]);
        return true;
    }

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

        // Ne pas permettre de supprimer une page qui a des sous-pages
        if ($db->firstColumn('SELECT 1 FROM wiki_pages WHERE parent = ? LIMIT 1;', (int)$id))
        {
            return false;
        }

        // Suppression des fichiers liés
        $files = Fichiers::listLinkedFiles(Fichiers::LIEN_WIKI, $id, null);

        foreach ($files as $file)
        {
            $file = new Fichiers($file->id, $file);
            $file->remove();
        }

        $db->delete('wiki_revisions', 'id_page = ?', (int)$id);
        $db->delete('wiki_recherche', 'id = ?', (int)$id);
        $db->delete('wiki_pages', 'id = ?', (int)$id);

        return true;
    }

    public function get($id)
    {
        $db = DB::getInstance();
        return $db->first('SELECT *,
            strftime(\'%s\', date_creation) AS date_creation,
            strftime(\'%s\', date_modification) AS date_modification
            FROM wiki_pages WHERE id = ? LIMIT 1;', (int)$id);
    }

    public function getTitle($id)
    {
        $db = DB::getInstance();
        return $db->firstColumn('SELECT titre FROM wiki_pages WHERE id = ? LIMIT 1;', (int)$id);
    }

    public function getRevision($id, $rev)
    {
        $db = DB::getInstance();
        $champ_id = Config::getInstance()->get('champ_identite');

        return $db->first('SELECT r.revision, r.modification, r.id_auteur, r.contenu,
            strftime(\'%s\', r.date) AS date, LENGTH(r.contenu) AS taille, m.'.$champ_id.' AS nom_auteur,
            r.chiffrement
            FROM wiki_revisions AS r LEFT JOIN membres AS m ON m.id = r.id_auteur
            WHERE r.id_page = ? AND revision = ? LIMIT 1;', (int) $id, (int) $rev);
    }

    public function listRevisions($id)
    {
        $db = DB::getInstance();
        $champ_id = Config::getInstance()->get('champ_identite');

        // FIXME pagination au lieu de bloquer à 1000
        return $db->get('SELECT r.revision, r.modification, r.id_auteur,
            strftime(\'%s\', r.date) AS date, LENGTH(r.contenu) AS taille, m.'.$champ_id.' AS nom_auteur,
            LENGTH(r.contenu) - (SELECT LENGTH(contenu) FROM wiki_revisions WHERE id_page = r.id_page AND revision < r.revision ORDER BY revision DESC LIMIT 1)
            AS diff_taille, r.chiffrement
            FROM wiki_revisions AS r LEFT JOIN membres AS m ON m.id = r.id_auteur
            WHERE r.id_page = ? ORDER BY r.revision DESC LIMIT 1000;', (int) $id);
    }

    public function editRevision($id, $revision_edition = 0, $data)
    {
        $db = DB::getInstance();

        $revision = $db->firstColumn('SELECT revision FROM wiki_pages WHERE id = ?;', (int)$id);

        // ?! L'ID fournit ne correspond à rien ?
        if ($revision === false)
        {
            throw new \RuntimeException('La page demandée n\'existe pas.');
        }

        // Pas de révision
        if ($revision == 0 && !trim($data['contenu']))
        {
            return true;
        }

        // Il faut obligatoirement fournir un ID d'auteur
        if (empty($data['id_auteur']) && $data['id_auteur'] !== null)
        {
            throw new \BadMethodCallException('Aucun ID auteur de fourni.');
        }

        $contenu = $db->firstColumn('SELECT contenu FROM wiki_revisions WHERE revision = ? AND id_page = ?;', (int)$revision, (int)$id);

        // Pas de changement au contenu, pas la peine d'enregistrer une nouvelle révision
        if (trim($contenu) == trim($data['contenu']))
        {
            return true;
        }

        // Révision sur laquelle est basée la nouvelle révision
        // utilisé pour vérifier que le contenu n'a pas été modifié depuis qu'on
        // a chargé la page d'édition
        if ($revision > $revision_edition)
        {
            throw new UserException('La page a été modifiée depuis le début de votre modification.');
        }

        if (empty($data['chiffrement']))
            $data['chiffrement'] = 0;

        if (!isset($data['modification']) || !trim($data['modification']))
            $data['modification'] = null;

        // Incrémentons le numéro de révision
        $revision++;

        $data['id_page'] = $id;
        $data['revision'] = $revision;

        $db->insert('wiki_revisions', $data);
        $db->update('wiki_pages', [
            'revision'          =>  $revision,
            'date_modification' =>  gmdate('Y-m-d H:i:s'),
        ], 'id = :id', ['id' => (int)$id]);

        return true;
    }

    public function search($search)
    {
        if (strlen($search) > 100) {
            throw new UserException('Recherche trop longue : maximum 100 caractères');
        }

        $query = sprintf('SELECT
            p.uri, r.*, snippet(wiki_recherche, \'<b>\', \'</b>\', \'...\', -1, -50) AS snippet,
            rank(matchinfo(wiki_recherche), 0, 1.0, 1.0) AS points
            FROM wiki_recherche AS r INNER JOIN wiki_pages AS p ON p.id = r.id
            WHERE %s AND wiki_recherche MATCH ?
            ORDER BY points DESC LIMIT 0,50;', $this->_getLectureClause('p.'));

        return DB::getInstance()->get($query, $search);
    }

    public function setRestrictionCategorie($id, $droit_wiki)
    {
        $this->restriction_categorie = $id;
        $this->restriction_droit = $droit_wiki;
        return true;
    }

    protected function _getLectureClause($prefix = '')
    {
        if (is_null($this->restriction_categorie))
        {
            throw new \UnexpectedValueException('setRestrictionCategorie doit être appelé auparavant.');
        }

        if ($this->restriction_droit == Membres::DROIT_AUCUN)
        {
            throw new UserException('Vous n\'avez pas accès au wiki.');
        }

        if ($this->restriction_droit == Membres::DROIT_ADMIN)
            return '1';

        return '('.$prefix.'droit_lecture = '.self::LECTURE_NORMAL.' OR '.$prefix.'droit_lecture = '.self::LECTURE_PUBLIC.'
            OR '.$prefix.'droit_lecture = '.(int)$this->restriction_categorie.')';
    }

    public function canReadPage($lecture)
    {
        if (is_null($this->restriction_categorie))
        {
            throw new \UnexpectedValueException('setRestrictionCategorie doit être appelé auparavant.');
        }

        if ($this->restriction_droit < Membres::DROIT_ACCES)
        {
            return false;
        }

        if ($this->restriction_droit == Membres::DROIT_ADMIN
            || $lecture == self::LECTURE_NORMAL || $lecture == self::LECTURE_PUBLIC
            || $lecture == $this->restriction_categorie)
            return true;

        return false;
    }

    public function canWritePage($ecriture)
    {
        if (is_null($this->restriction_categorie))
        {
            throw new \UnexpectedValueException('setRestrictionCategorie doit être appelé auparavant.');
        }

        if ($this->restriction_droit < Membres::DROIT_ECRITURE)
        {
            return false;
        }

        if ($this->restriction_droit == Membres::DROIT_ADMIN
            || $ecriture == self::ECRITURE_NORMAL
            || $ecriture == $this->restriction_categorie)
            return true;

        return false;
    }

    public function getList($parent = 0, $order_by_date = false)
    {
        $order = ($order_by_date ? 'date_creation DESC' : 'transliterate_to_ascii(titre) COLLATE NOCASE');

        $query = sprintf('SELECT id, revision, uri, titre,
                strftime(\'%%s\', date_creation) AS date_creation,
                strftime(\'%%s\', date_modification) AS date_modification
                FROM wiki_pages
                WHERE parent = ? AND %s ORDER BY %s LIMIT 500;', $this->_getLectureClause(), $order);

        return DB::getInstance()->get($query, (int) $parent);
    }

    public function hasChildren($parent, $public_only = false)
    {
        $db = DB::getInstance();
        $public = !$public_only ? '' : ' AND ' . $db->where('droit_lecture', self::LECTURE_PUBLIC);
        return $db->test('wiki_pages', $db->where('parent', (int)$parent) . $public);
    }

    public function getById($id)
    {
        $db = DB::getInstance();
        $page = $db->first('SELECT *,
            strftime(\'%s\', date_creation) AS date_creation,
            strftime(\'%s\', date_modification) AS date_modification
            FROM wiki_pages
            WHERE id = ?;', (int)$id);

        if (!$page)
        {
            return false;
        }

        $page->contenu = false;

        if ($page->revision > 0)
        {
            $page->contenu = $db->first('SELECT * FROM wiki_revisions
                WHERE id_page = ? AND revision = ?;', (int)$page->id, (int)$page->revision);
        }

        return $page;
    }

    public function getByURI($uri)
    {
        $id = DB::getInstance()->firstColumn('SELECT id FROM wiki_pages WHERE uri = ?;', $uri);

        if (!$id)
        {
            return false;
        }

        return $this->getByID($id);
    }

    public function listRecentModifications($page = 1)
    {
        $begin = ($page - 1) * self::ITEMS_PER_PAGE;

        $db = DB::getInstance();

        return $db->get('SELECT *,
                strftime(\'%s\', date_creation) AS date_creation,
                strftime(\'%s\', date_modification) AS date_modification
                FROM wiki_pages
                WHERE '.$this->_getLectureClause().'
                ORDER BY date_modification DESC
                LIMIT ?,?;', $begin, self::ITEMS_PER_PAGE);
    }

    public function countRecentModifications()
    {
        $db = DB::getInstance();
        return $db->firstColumn('SELECT COUNT(*) FROM wiki_pages WHERE '.$this->_getLectureClause().';');
    }

    public function listBackBreadCrumbs($id)
    {
        if ($id == 0)
            return [];

        $db = DB::getInstance();
        $flat = [];
        $max = 0;

        while ($id > 0 && $max++ < 10)
        {
            $res = $db->first('SELECT parent, titre, uri
                FROM wiki_pages WHERE id = ? LIMIT 1;', (int)$id);

            $flat[] = [
                'id'        =>  $id,
                'titre'     =>  $res->titre,
                'uri'       =>  $res->uri,
            ];

            if ($id == $res->parent)
            {
                throw new \Exception('Parent! ' . $id . '/' . $res->parent);
            }

            $id = (int)$res->parent;
        }

        return array_reverse($flat);
    }

    public function listBackParentTree($id)
    {
        $db = DB::getInstance();
        $flat = [
            (object) [
                'id' => 0,
                'parent' => null,
                'titre' => 'Racine',
                'children' => $db->getGrouped('SELECT id, parent, titre FROM wiki_pages
                    WHERE parent = ? ORDER BY transliterate_to_ascii(titre) COLLATE NOCASE;',
                    0)
            ]
        ];

        $max = 0;

        do
        {
            $parent = $db->get('SELECT parent FROM wiki_pages WHERE id = ? LIMIT 1;', (int)$id);

            $flat[$id] = (object) [
                'id'        =>  $id,
                'parent'    =>  $id ? (int)$parent : null,
                'titre'     =>  $id ? $this->getTitle($id) : 'Racine',
                'children'  =>  $db->getGrouped('SELECT id, parent, titre FROM wiki_pages
                    WHERE parent = ? ORDER BY transliterate_to_ascii(titre) COLLATE NOCASE;',
                    (int)$id)
            ];

            $id = (int)$parent;
        }
        while ($id != 0 && $max++ < 20);

        $tree = [];
        foreach ($flat as $id=>&$node)
        {
            if (is_null($node->parent))
            {
                $tree[$id] = &$node;
            }
            else
            {
                if (!isset($flat[$node->parent]->children))
                {
                    $flat[$node->parent]->children = [];
                }

                $flat[$node->parent]->children[$id] = &$node;
            }
        }

        return $tree;
    }
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Modified src/include/lib/dependencies.list from [b716c7d0a7] to [9fc3eee5ea].

1
2
3
4
5

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
KD2/data/
KD2/DB/AbstractEntity.php
KD2/DB/DB.php
KD2/DB/EntityManager.php
KD2/DB/SQLite3.php

KD2/ErrorManager.php
KD2/FileInfo.php
KD2/Form.php
KD2/HTTP.php
KD2/Graphics/Image.php
KD2/Graphics/QRCode.php
KD2/Graphics/SVG/Pie.php
KD2/Graphics/SVG/Plot.php
KD2/MiniSkel.php
KD2/Office/Calc/Writer.php
KD2/Security.php
KD2/Security_OTP.php
KD2/SimpleDiff.php
KD2/SkrivLite.php
KD2/Smartyer.php
KD2/SMTP.php
KD2/Translate.php
KD2/UserSession.php
KD2/ZipWriter.php





>








<










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

15
16
17
18
19
20
21
22
23
24
KD2/data/
KD2/DB/AbstractEntity.php
KD2/DB/DB.php
KD2/DB/EntityManager.php
KD2/DB/SQLite3.php
KD2/Brindille.php
KD2/ErrorManager.php
KD2/FileInfo.php
KD2/Form.php
KD2/HTTP.php
KD2/Graphics/Image.php
KD2/Graphics/QRCode.php
KD2/Graphics/SVG/Pie.php
KD2/Graphics/SVG/Plot.php

KD2/Office/Calc/Writer.php
KD2/Security.php
KD2/Security_OTP.php
KD2/SimpleDiff.php
KD2/SkrivLite.php
KD2/Smartyer.php
KD2/SMTP.php
KD2/Translate.php
KD2/UserSession.php
KD2/ZipWriter.php

Modified src/include/test_required.php from [a96dd46521] to [3b6f01c207].

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
        echo "Pour plus d'informations consulter http://dev.kd2.org/garradin/Probl%C3%A8mes%20fr%C3%A9quents\n";
    }

    exit;
}

test_requis(
    version_compare(phpversion(), '7.2', '>='),
    'PHP 7.2 ou supérieur requis. PHP version ' . phpversion() . ' installée.'
);

test_requis(
    defined('CRYPT_BLOWFISH') && CRYPT_BLOWFISH,
    'L\'algorithme de hashage de mot de passe Blowfish n\'est pas présent (pas installé ou pas compilé).'
);








|
|







30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
        echo "Pour plus d'informations consulter http://dev.kd2.org/garradin/Probl%C3%A8mes%20fr%C3%A9quents\n";
    }

    exit;
}

test_requis(
    version_compare(phpversion(), '7.4', '>='),
    'PHP 7.4 ou supérieur requis. PHP version ' . phpversion() . ' installée.'
);

test_requis(
    defined('CRYPT_BLOWFISH') && CRYPT_BLOWFISH,
    'L\'algorithme de hashage de mot de passe Blowfish n\'est pas présent (pas installé ou pas compilé).'
);

Deleted src/plugins/index.html version [abe89f9bfb].

1
<!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>
<


Modified src/scripts/cron.php from [338658a83b] to [46784b92c3].

1
2
3
4
5
6
7
8
9


10
11
12
13
14
15
16
17
18
<?php

namespace Garradin;

use Garradin\Services\Reminders;

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

// Exécution des tâches automatiques



if (ENABLE_AUTOMATIC_BACKUPS && $config->get('frequence_sauvegardes') && $config->get('nombre_sauvegardes'))
{
	$s = new Sauvegarde;
	$s->auto();
}

// Exécution des rappels automatiques
Reminders::sendPending();









>
>









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

namespace Garradin;

use Garradin\Services\Reminders;

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

// Exécution des tâches automatiques

$config = Config::getInstance();

if (ENABLE_AUTOMATIC_BACKUPS && $config->get('frequence_sauvegardes') && $config->get('nombre_sauvegardes'))
{
	$s = new Sauvegarde;
	$s->auto();
}

// Exécution des rappels automatiques
Reminders::sendPending();

Modified src/templates/acc/accounts/deposit.tpl from [1de1606a11] to [42c0a571f4].

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
				</tr>
			</thead>
			<tbody>
				{foreach from=$journal item="line"}
				{if isset($line.sum)}
				<tr>
					<td colspan="5"></td>
					<td class="money">{if $line.sum > 0}-{/if}{$line.sum|abs|raw|html_money:false}</td>
					<th>Solde au {$line.date|date_short}</th>
					<td colspan="2"></td>
				</tr>
				{else}
				<tr>
					<td class="check">
						{input type="checkbox" name="deposit[%d]"|args:$line.id value="1" data-debit=$line.debit|abs data-credit=$line.credit default=$line.checked}
					</td>
					<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$line.id}">#{$line.id}</a></td>
					<td>{$line.date|date_short}</td>
					<td>{$line.reference}</td>
					<td>{$line.line_reference}</td>
					<th>{$line.label}</th>
					<td class="money">{$line.debit|raw|html_money}</td>
					<td class="money">{if $line.running_sum > 0}-{/if}{$line.running_sum|abs|raw|html_money:false}</td>
				</tr>
				{/if}
			{/foreach}
			</tbody>
		</table>

		<fieldset>







|






|






|
|







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
				</tr>
			</thead>
			<tbody>
				{foreach from=$journal item="line"}
				{if isset($line.sum)}
				<tr>
					<td colspan="5"></td>
					<td class="money">{if $line.sum > 0}-{/if}{$line.sum|abs|raw|money:false}</td>
					<th>Solde au {$line.date|date_short}</th>
					<td colspan="2"></td>
				</tr>
				{else}
				<tr>
					<td class="check">
						{input type="checkbox" name="deposit[%d]"|args:$line.id_line value="1" data-debit=$line.debit|abs data-credit=$line.credit default=$line.checked}
					</td>
					<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$line.id}">#{$line.id}</a></td>
					<td>{$line.date|date_short}</td>
					<td>{$line.reference}</td>
					<td>{$line.line_reference}</td>
					<th>{$line.label}</th>
					<td class="money">{$line.debit|raw|money}</td>
					<td class="money">{if $line.running_sum > 0}-{/if}{$line.running_sum|abs|raw|money:false}</td>
				</tr>
				{/if}
			{/foreach}
			</tbody>
		</table>

		<fieldset>

Modified src/templates/acc/accounts/index.tpl from [346db46cee] to [46d037e135].

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
{include file="admin/_head.tpl" title="Comptes favoris" current="acc/accounts"}

{include file="acc/_year_select.tpl"}

<nav class="tabs">
	<aside>
		{linkbutton shape="search" href="!acc/search.php?year=%d"|args:$current_year.id label="Recherche"}
	</aside>
	<ul>
		<li class="current"><a href="{$admin_url}acc/accounts/">Comptes favoris</a></li>
		<li><a href="{$admin_url}acc/reports/trial_balance.php?year={$current_year.id}">Balance générale (tous les comptes)</a></li>
		{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
			<li><a href="{$admin_url}acc/charts/accounts/?id={$chart_id}">Modifier les comptes</a></li>
			<li><a href="{$admin_url}acc/charts/accounts/all.php?id={$chart_id}">Plan comptable complet</a></li>
		{/if}
	</ul>
</nav>

{if isset($_GET['chart_change'])}
<p class="block error">
	L'exercice sélectionné utilise un plan comptable différent, merci de sélectionner un autre compte.
</p>
{/if}

{include file="acc/_simple_help.tpl" link="../reports/trial_balance.php?year=%d"|args:$current_year.id type=null}

{if !empty($grouped_accounts)}

	<table class="list">
		<thead>
			<tr>
				<td class="num">Numéro</td>
				<th>Compte</th>
				<td class="money">Solde</td>
				<td></td>











|















>







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
{include file="admin/_head.tpl" title="Comptes favoris" current="acc/accounts"}

{include file="acc/_year_select.tpl"}

<nav class="tabs">
	<aside>
		{linkbutton shape="search" href="!acc/search.php?year=%d"|args:$current_year.id label="Recherche"}
	</aside>
	<ul>
		<li class="current"><a href="{$admin_url}acc/accounts/">Comptes favoris</a></li>
		<li><a href="{$admin_url}acc/reports/trial_balance.php?year={$current_year.id}">Balance générale (tous les comptes)</a></li>
		{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
			<li><a href="{$admin_url}acc/charts/accounts/?id={$chart_id}">Modifier les comptes</a></li>
			<li><a href="{$admin_url}acc/charts/accounts/all.php?id={$chart_id}">Plan comptable complet</a></li>
		{/if}
	</ul>
</nav>

{if isset($_GET['chart_change'])}
<p class="block error">
	L'exercice sélectionné utilise un plan comptable différent, merci de sélectionner un autre compte.
</p>
{/if}

{include file="acc/_simple_help.tpl" link="../reports/trial_balance.php?year=%d"|args:$current_year.id type=null}

{if !empty($grouped_accounts)}
	<?php $has_accounts = false; ?>
	<table class="list">
		<thead>
			<tr>
				<td class="num">Numéro</td>
				<th>Compte</th>
				<td class="money">Solde</td>
				<td></td>
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
							{elseif $account.sum > 0}(Créance)
							{/if}
						</em>
						{/if}
					</td>
					<td class="actions">
						{linkbutton label="Journal" shape="menu" href="journal.php?id=%d&year=%d"|args:$account.id,$current_year.id}
						{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
							{if $account.type == Entities\Accounting\Account::TYPE_BANK}
								{linkbutton label="Rapprochement" shape="check" href="reconcile.php?id=%d"|args:$account.id}
							{elseif $account.type == Entities\Accounting\Account::TYPE_OUTSTANDING}
								{linkbutton label="Dépôt en banque" shape="check" href="deposit.php?id=%d"|args:$account.id}
							{/if}
						{/if}
					</td>
				</tr>
			{/foreach}
		</tbody>

		{/foreach}
	</table>









{/if}

<p class="help">
	Note : n'apparaissent ici que les comptes <strong>favoris</strong> qui ont été utilisés dans cet exercice (au moins une écriture).<br />
	Pour voir le solde de tous les comptes, se référer à la <a href="{$admin_url}acc/reports/trial_balance.php?year={$current_year.id}">balance générale de l'exercice</a>.<br />
	Pour voir la liste complète des comptes, même ceux qui n'ont pas été utilisés, se référer au <a href="{$admin_url}acc/charts/accounts/?id={$current_year.id_chart}">plan comptable</a>.
</p>

{include file="admin/_foot.tpl"}







|










>


>
>
>
>
>
>
>
>
>









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
							{elseif $account.sum > 0}(Créance)
							{/if}
						</em>
						{/if}
					</td>
					<td class="actions">
						{linkbutton label="Journal" shape="menu" href="journal.php?id=%d&year=%d"|args:$account.id,$current_year.id}
						{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
							{if $account.type == Entities\Accounting\Account::TYPE_BANK}
								{linkbutton label="Rapprochement" shape="check" href="reconcile.php?id=%d"|args:$account.id}
							{elseif $account.type == Entities\Accounting\Account::TYPE_OUTSTANDING}
								{linkbutton label="Dépôt en banque" shape="check" href="deposit.php?id=%d"|args:$account.id}
							{/if}
						{/if}
					</td>
				</tr>
			{/foreach}
		</tbody>
		<?php $has_accounts = true; ?>
		{/foreach}
	</table>

	{if !$has_accounts}
	<div class="alert block">
		<p>Aucun compte favori ne comporte d'écriture sur cet exercice.</p>
		<p>
			{linkbutton href="!acc/transactions/new.php" label="Saisir une écriture" shape="plus"}
		</p>
	</div>
	{/if}
{/if}

<p class="help">
	Note : n'apparaissent ici que les comptes <strong>favoris</strong> qui ont été utilisés dans cet exercice (au moins une écriture).<br />
	Pour voir le solde de tous les comptes, se référer à la <a href="{$admin_url}acc/reports/trial_balance.php?year={$current_year.id}">balance générale de l'exercice</a>.<br />
	Pour voir la liste complète des comptes, même ceux qui n'ont pas été utilisés, se référer au <a href="{$admin_url}acc/charts/accounts/?id={$current_year.id_chart}">plan comptable</a>.
</p>

{include file="admin/_foot.tpl"}

Modified src/templates/acc/accounts/journal.tpl from [6182c4c368] to [8864e5930b].

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
			<p class="alert block">Ce compte présente un solde négatif de <strong>{$sum|raw|money_currency}</strong>. Est-ce normal&nbsp;? Cette situation ne devrait se produire que si vous avez reçu des remboursements par exemple, et que ceux-ci couvrent des dépenses réglées sur un exercice précédent.</p>
		{/if}
	{/if}


	<nav class="tabs">
		<aside>
		{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
			{linkbutton href="%s&export=csv"|args:$self_url label="Export CSV" shape="export"}
			{linkbutton href="%s&export=ods"|args:$self_url label="Export tableur" shape="export"}
		{/if}
			{linkbutton shape="search" href="!acc/search.php?year=%d&account=%s"|args:$year.id,$account.code label="Recherche"}
		{if $year.id == CURRENT_YEAR_ID}
			{linkbutton href="!acc/transactions/new.php?account=%d"|args:$account.id label="Saisir une écriture dans ce compte" shape="plus"}
		{/if}







|







48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
			<p class="alert block">Ce compte présente un solde négatif de <strong>{$sum|raw|money_currency}</strong>. Est-ce normal&nbsp;? Cette situation ne devrait se produire que si vous avez reçu des remboursements par exemple, et que ceux-ci couvrent des dépenses réglées sur un exercice précédent.</p>
		{/if}
	{/if}


	<nav class="tabs">
		<aside>
		{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
			{linkbutton href="%s&export=csv"|args:$self_url label="Export CSV" shape="export"}
			{linkbutton href="%s&export=ods"|args:$self_url label="Export tableur" shape="export"}
		{/if}
			{linkbutton shape="search" href="!acc/search.php?year=%d&account=%s"|args:$year.id,$account.code label="Recherche"}
		{if $year.id == CURRENT_YEAR_ID}
			{linkbutton href="!acc/transactions/new.php?account=%d"|args:$account.id label="Saisir une écriture dans ce compte" shape="plus"}
		{/if}
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
			<td class="check">
				{input type="checkbox" name="check[%s]"|args:$line.id_line value=$line.id default=0}
			</td>
			{/if}
			<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$line.id}">#{$line.id}</a></td>
			<td>{$line.date|date_short}</td>
			{if $simple}
			<td class="money">{if $line.change > 0}+{else}-{/if}{$line.change|abs|raw|html_money}</td>
			{else}
			<td class="money">{$line.debit|raw|html_money}</td>
			<td class="money">{$line.credit|raw|html_money}</td>
			{/if}
			{if isset($line->sum)}
				<td class="money">{$line.sum|raw|html_money:false}</td>
			{/if}
			<td>{$line.reference}</td>
			<th>{$line.label}</th>
			{if !$simple}<td>{$line.line_label}</td>{/if}
			<td>{$line.line_reference}</td>
			<td class="num">{if $line.id_analytical}<a href="{$admin_url}acc/reports/statement.php?analytical={$line.id_analytical}">{$line.code_analytical}</a>{/if}</td>
			<td class="actions">







|

|
|


|







78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
			<td class="check">
				{input type="checkbox" name="check[%s]"|args:$line.id_line value=$line.id default=0}
			</td>
			{/if}
			<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$line.id}">#{$line.id}</a></td>
			<td>{$line.date|date_short}</td>
			{if $simple}
			<td class="money">{if $line.change > 0}+{else}-{/if}{$line.change|abs|raw|money}</td>
			{else}
			<td class="money">{$line.debit|raw|money}</td>
			<td class="money">{$line.credit|raw|money}</td>
			{/if}
			{if isset($line->sum)}
				<td class="money">{$line.sum|raw|money:false}</td>
			{/if}
			<td>{$line.reference}</td>
			<th>{$line.label}</th>
			{if !$simple}<td>{$line.line_label}</td>{/if}
			<td>{$line.line_reference}</td>
			<td class="num">{if $line.id_analytical}<a href="{$admin_url}acc/reports/statement.php?analytical={$line.id_analytical}">{$line.code_analytical}</a>{/if}</td>
			<td class="actions">
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
	<tfoot>
		<tr>
			{if $can_edit}
				<td class="check"><input type="checkbox" value="Tout cocher / décocher" id="f_all2" /><label for="f_all2"></label></td>
			{/if}
			{if !$simple}<td></td>{/if}
			<td colspan="3">Solde</td>
			<td class="money">{$sum|raw|html_money:false}</td>
			{if !$simple}<td></td>{/if}
			<td class="actions" colspan="5">
				{if $can_edit}
					<em>Pour les écritures cochées :</em>
					<input type="hidden" name="from" value="{$self_url}" />
					<input type="hidden" name="year" value="{$year.id}" />
					{csrf_field key="projects_action"}







|







112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
	<tfoot>
		<tr>
			{if $can_edit}
				<td class="check"><input type="checkbox" value="Tout cocher / décocher" id="f_all2" /><label for="f_all2"></label></td>
			{/if}
			{if !$simple}<td></td>{/if}
			<td colspan="3">Solde</td>
			<td class="money">{$sum|raw|money:false}</td>
			{if !$simple}<td></td>{/if}
			<td class="actions" colspan="5">
				{if $can_edit}
					<em>Pour les écritures cochées :</em>
					<input type="hidden" name="from" value="{$self_url}" />
					<input type="hidden" name="year" value="{$year.id}" />
					{csrf_field key="projects_action"}

Modified src/templates/acc/accounts/reconcile.tpl from [cc53da36ae] to [aa2066a69f].

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

<form method="get" action="{$self_url_no_qs}">
	{if $prev || $next}
	<fieldset class="shortFormRight">
		<legend>Rapprochement par mois</legend>
		<p>
			{if $prev}
				{linkbutton shape="left" href=$prev.url label=$prev.date|date_fr:'F Y'}
			{/if}
			{if $next}
				{linkbutton shape="right" href=$next.url label=$next.date|date_fr:'F Y'}
			{/if}
		</p>
	</fieldset>
	{/if}
	<fieldset class="shortFormLeft">
		<legend>Période de rapprochement</legend>
		<p>







|


|







11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

<form method="get" action="{$self_url_no_qs}">
	{if $prev || $next}
	<fieldset class="shortFormRight">
		<legend>Rapprochement par mois</legend>
		<p>
			{if $prev}
				{linkbutton shape="left" href=$prev.url label=$prev.date|date:'F Y'}
			{/if}
			{if $next}
				{linkbutton shape="right" href=$next.url label=$next.date|date:'F Y'}
			{/if}
		</p>
	</fieldset>
	{/if}
	<fieldset class="shortFormLeft">
		<legend>Période de rapprochement</legend>
		<p>
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
			</tr>
		</thead>
		<tbody>
			{foreach from=$journal item="line"}
			{if isset($line->sum)}
			<tr>
				<td colspan="5"></td>
				<td class="money">{if $line.sum > 0}-{/if}{$line.sum|abs|raw|html_money:false}</td>
				<td class="money">{if $line.reconciled_sum > 0}-{/if}{$line.reconciled_sum|abs|raw|html_money}</td>
				<th>Solde au {$line.date|date_short}</th>
				<td colspan="2"></td>
			</tr>
			{else}
			<tr>
				<td class="check">
					{input type="checkbox" name="reconcile[%d]"|args:$line.id_line value="1" default=$line.reconciled}
				</td>
				<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$line.id}">#{$line.id}</a></td>
				<td>{$line.date|date_short}</td>
				<td class="money">{$line.credit|raw|html_money}</td>
				<td class="money">{$line.debit|raw|html_money}</td> {* Not a bug! Credit/debit is reversed here to reflect the bank statement *}
				<td class="money">{if $line.running_sum > 0}-{/if}{$line.running_sum|abs|raw|html_money:false}</td>
				<td class="money">{if $line.reconciled_sum > 0}-{/if}{$line.reconciled_sum|abs|raw|html_money:false}</td>
				<th>{$line.label}</th>
				<td>{$line.reference}</td>
				<td>{$line.line_reference}</td>
			</tr>
			{/if}
		{/foreach}
		</tbody>







|
|










|
|
|
|







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
			</tr>
		</thead>
		<tbody>
			{foreach from=$journal item="line"}
			{if isset($line->sum)}
			<tr>
				<td colspan="5"></td>
				<td class="money">{if $line.sum > 0}-{/if}{$line.sum|abs|raw|money:false}</td>
				<td class="money">{if $line.reconciled_sum > 0}-{/if}{$line.reconciled_sum|abs|raw|money}</td>
				<th>Solde au {$line.date|date_short}</th>
				<td colspan="2"></td>
			</tr>
			{else}
			<tr>
				<td class="check">
					{input type="checkbox" name="reconcile[%d]"|args:$line.id_line value="1" default=$line.reconciled}
				</td>
				<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$line.id}">#{$line.id}</a></td>
				<td>{$line.date|date_short}</td>
				<td class="money">{$line.credit|raw|money}</td>
				<td class="money">{$line.debit|raw|money}</td> {* Not a bug! Credit/debit is reversed here to reflect the bank statement *}
				<td class="money">{if $line.running_sum > 0}-{/if}{$line.running_sum|abs|raw|money:false}</td>
				<td class="money">{if $line.reconciled_sum > 0}-{/if}{$line.reconciled_sum|abs|raw|money:false}</td>
				<th>{$line.label}</th>
				<td>{$line.reference}</td>
				<td>{$line.line_reference}</td>
			</tr>
			{/if}
		{/foreach}
		</tbody>

Modified src/templates/acc/accounts/reconcile_assist.tpl from [4e7ccd5117] to [80420a98b7].

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
				</tr>
			</thead>
			<tbody>
				{foreach from=$lines key="line_id" item="line"}
				{if isset($line->journal->sum)}
				<tr>
					<td colspan="4"></td>
					<td class="money">{if $line.journal.sum > 0}-{/if}{$line.journal.sum|abs|raw|html_money:false}</td>
					<th style="text-align: right">Solde au {$line.journal.date|date_short}</th>
					<td class="separator"></td>
					<td class="separator"></td>
					<td colspan="3"></td>
				</tr>
				{else}
				<tr>
					{if isset($line->journal)}
						<td class="check">
							{input type="checkbox" name="reconcile[%d]"|args:$line.journal.id_line value="1" default=$line.journal.reconciled}
						</td>
						<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$line.journal.id}">#{$line.journal.id}</a></td>
						<td>{$line.journal.date|date_short}</td>
						<td class="money">
							{if $line.journal.credit}
								{* Not a bug! Credit/debit is reversed here to reflect the bank statement *}
								-{$line.journal.credit|raw|html_money}
							{else}
								{$line.journal.debit|raw|html_money}
							{/if}
						</td>
						<td class="money">{if $line.journal.running_sum > 0}-{/if}{$line.journal.running_sum|abs|raw|html_money:false}</td>
						<th style="text-align: right">{$line.journal.label}</th>
					{else}
						<td colspan="5"></td>
						<td style="text-align: right">
							{if $line.add}
							{* FIXME later add ability to pre-fill multi-line transactions in new.php
								{linkbutton label="Créer cette écriture" target="_blank" href="%s&create=%s"|args:$self_url,$line_id shape="plus"}







|
















|

|


|







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
				</tr>
			</thead>
			<tbody>
				{foreach from=$lines key="line_id" item="line"}
				{if isset($line->journal->sum)}
				<tr>
					<td colspan="4"></td>
					<td class="money">{if $line.journal.sum > 0}-{/if}{$line.journal.sum|abs|raw|money:false}</td>
					<th style="text-align: right">Solde au {$line.journal.date|date_short}</th>
					<td class="separator"></td>
					<td class="separator"></td>
					<td colspan="3"></td>
				</tr>
				{else}
				<tr>
					{if isset($line->journal)}
						<td class="check">
							{input type="checkbox" name="reconcile[%d]"|args:$line.journal.id_line value="1" default=$line.journal.reconciled}
						</td>
						<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$line.journal.id}">#{$line.journal.id}</a></td>
						<td>{$line.journal.date|date_short}</td>
						<td class="money">
							{if $line.journal.credit}
								{* Not a bug! Credit/debit is reversed here to reflect the bank statement *}
								-{$line.journal.credit|raw|money}
							{else}
								{$line.journal.debit|raw|money}
							{/if}
						</td>
						<td class="money">{if $line.journal.running_sum > 0}-{/if}{$line.journal.running_sum|abs|raw|money:false}</td>
						<th style="text-align: right">{$line.journal.label}</th>
					{else}
						<td colspan="5"></td>
						<td style="text-align: right">
							{if $line.add}
							{* FIXME later add ability to pre-fill multi-line transactions in new.php
								{linkbutton label="Créer cette écriture" target="_blank" href="%s&create=%s"|args:$self_url,$line_id shape="plus"}
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
						{else}
							<b class="icn">⚠</b>
						{/if}
						</td>
					{if isset($line->csv)}
						<th class="separator">{$line.csv.label}</th>
						<td class="money">
							{$line.csv.amount|raw|html_money}
						</td>
						<td class="money">{$line.csv.running_sum|raw|html_money}</td>
						<td>{$line.csv.date|date_short}</td>
					{else}
						<td colspan="4" class="separator"></td>
					{/if}
				</tr>
				{/if}
			{/foreach}







|

|







132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
						{else}
							<b class="icn">⚠</b>
						{/if}
						</td>
					{if isset($line->csv)}
						<th class="separator">{$line.csv.label}</th>
						<td class="money">
							{$line.csv.amount|raw|money}
						</td>
						<td class="money">{$line.csv.running_sum|raw|money}</td>
						<td>{$line.csv.date|date_short}</td>
					{else}
						<td colspan="4" class="separator"></td>
					{/if}
				</tr>
				{/if}
			{/foreach}

Modified src/templates/acc/accounts/simple.tpl from [a83a75f997] to [7717c0c7db].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{include file="admin/_head.tpl" title="Suivi : %s"|args:$types[$type] current="acc/simple"}

{include file="acc/_year_select.tpl"}

<nav class="tabs">
	<aside>
	{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
		{linkbutton href="?type=%d&export=csv"|args:$type label="Export CSV" shape="export"}
		{linkbutton href="?type=%d&export=ods"|args:$type label="Export tableur" shape="export"}
	{/if}
		{linkbutton shape="search" href="!acc/search.php?year=%d&type=%d"|args:$year.id,$type label="Recherche"}
	</aside>
	<ul>
		{foreach from=$types key="key" item="label"}






|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
{include file="admin/_head.tpl" title="Suivi : %s"|args:$types[$type] current="acc/simple"}

{include file="acc/_year_select.tpl"}

<nav class="tabs">
	<aside>
	{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
		{linkbutton href="?type=%d&export=csv"|args:$type label="Export CSV" shape="export"}
		{linkbutton href="?type=%d&export=ods"|args:$type label="Export tableur" shape="export"}
	{/if}
		{linkbutton shape="search" href="!acc/search.php?year=%d&type=%d"|args:$year.id,$type label="Recherche"}
	</aside>
	<ul>
		{foreach from=$types key="key" item="label"}
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
				{if $can_edit}
				<td class="check">
					{input type="checkbox" name="check[%s]"|args:$line.id_line value=$line.id default=0}
				</td>
				{/if}
				<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$line.id}">#{$line.id}</a></td>
				<td>{$line.date|date_short}</td>
				<td class="money">{$line.change|abs|raw|html_money}</td>
				<td>{$line.reference}</td>
				<th>{$line.label}</th>
				<td>{$line.line_reference}</td>
				<td class="num">{foreach from=$line.code_analytical item="code" key="id"}<a href="{$admin_url}acc/reports/statement.php?analytical={$id}">{$code}</a> {/foreach}</td>
				<td class="actions">
					{if $line.type == Entities\Accounting\Transaction::TYPE_DEBT && ($line.status & Entities\Accounting\Transaction::STATUS_WAITING)}
						{linkbutton shape="check" label="Régler cette dette" href="!acc/transactions/new.php?payoff_for=%d"|args:$line.id}







|







31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
				{if $can_edit}
				<td class="check">
					{input type="checkbox" name="check[%s]"|args:$line.id_line value=$line.id default=0}
				</td>
				{/if}
				<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$line.id}">#{$line.id}</a></td>
				<td>{$line.date|date_short}</td>
				<td class="money">{$line.change|abs|raw|money}</td>
				<td>{$line.reference}</td>
				<th>{$line.label}</th>
				<td>{$line.line_reference}</td>
				<td class="num">{foreach from=$line.code_analytical item="code" key="id"}<a href="{$admin_url}acc/reports/statement.php?analytical={$id}">{$code}</a> {/foreach}</td>
				<td class="actions">
					{if $line.type == Entities\Accounting\Transaction::TYPE_DEBT && ($line.status & Entities\Accounting\Transaction::STATUS_WAITING)}
						{linkbutton shape="check" label="Régler cette dette" href="!acc/transactions/new.php?payoff_for=%d"|args:$line.id}

Modified src/templates/acc/charts/accounts/_nav.tpl from [ec091420e5] to [982004d151].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<nav class="tabs">
	<ul>
		<li class="current"><a href="{$admin_url}acc/charts/">Plans comptables</a></li>
		{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
		<li><a href="{$admin_url}acc/charts/import.php">Importer un plan comptable</a></li>
		{/if}
	</ul>
	<ul class="sub">
		<li class="title">{$chart.label}</li>
		<li{if $current == 'favorites'} class="current"{/if}><a href="{$admin_url}acc/charts/accounts/?id={$chart.id}">Comptes favoris</a></li>
		<li{if $current == 'all'} class="current"{/if}><a href="{$admin_url}acc/charts/accounts/all.php?id={$chart.id}">Tous les comptes</a></li>
		{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
			<li{if $current == 'new'} class="current"{/if}><a href="{$admin_url}acc/charts/accounts/new.php?id={$chart.id}"><strong>Ajouter un compte</strong></a></li>
		{/if}
	</ul>
</nav>



|







|




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<nav class="tabs">
	<ul>
		<li class="current"><a href="{$admin_url}acc/charts/">Plans comptables</a></li>
		{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
		<li><a href="{$admin_url}acc/charts/import.php">Importer un plan comptable</a></li>
		{/if}
	</ul>
	<ul class="sub">
		<li class="title">{$chart.label}</li>
		<li{if $current == 'favorites'} class="current"{/if}><a href="{$admin_url}acc/charts/accounts/?id={$chart.id}">Comptes favoris</a></li>
		<li{if $current == 'all'} class="current"{/if}><a href="{$admin_url}acc/charts/accounts/all.php?id={$chart.id}">Tous les comptes</a></li>
		{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
			<li{if $current == 'new'} class="current"{/if}><a href="{$admin_url}acc/charts/accounts/new.php?id={$chart.id}"><strong>Ajouter un compte</strong></a></li>
		{/if}
	</ul>
</nav>

Modified src/templates/acc/charts/accounts/all.tpl from [532b7dcf92] to [ff6fa9acdc].

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
					{icon shape="star"} <?=Entities\Accounting\Account::TYPES_NAMES[$account->type]?>
				{/if}
			</td>
			<td>
				{if $account.user}<em>Ajouté</em>{/if}
			</td>
			<td class="actions">
				{if $session->canAccess('compta', Membres::DROIT_ADMIN) && !$chart.archived}
					{if $account.user || !$chart.code}
						{linkbutton shape="delete" label="Supprimer" href="!acc/charts/accounts/delete.php?id=%d"|args:$account.id}
					{/if}
					{linkbutton shape="edit" label="Modifier" href="!acc/charts/accounts/edit.php?id=%d"|args:$account.id}
				{/if}
			</td>
		</tr>
	{/foreach}
	</tbody>
</table>


{include file="admin/_foot.tpl"}







|













17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
					{icon shape="star"} <?=Entities\Accounting\Account::TYPES_NAMES[$account->type]?>
				{/if}
			</td>
			<td>
				{if $account.user}<em>Ajouté</em>{/if}
			</td>
			<td class="actions">
				{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN) && !$chart.archived}
					{if $account.user || !$chart.code}
						{linkbutton shape="delete" label="Supprimer" href="!acc/charts/accounts/delete.php?id=%d"|args:$account.id}
					{/if}
					{linkbutton shape="edit" label="Modifier" href="!acc/charts/accounts/edit.php?id=%d"|args:$account.id}
				{/if}
			</td>
		</tr>
	{/foreach}
	</tbody>
</table>


{include file="admin/_foot.tpl"}

Modified src/templates/acc/charts/accounts/index.tpl from [d986fd5237] to [1453ceb936].

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

	{foreach from=$group.accounts item="account"}
		<tr>
			<td class="num">{$account.code}</td>
			<th>{$account.label}</th>
			<td class="desc">{$account.description}</td>
			<td class="actions">
				{if $session->canAccess('compta', Membres::DROIT_ADMIN) && !$chart.archived}
					{if $account.user || !$chart.code}
						{linkbutton shape="delete" label="Supprimer" href="!acc/charts/accounts/delete.php?id=%d"|args:$account.id}
					{/if}
					{linkbutton shape="edit" label="Modifier" href="!acc/charts/accounts/edit.php?id=%d"|args:$account.id}
				{/if}
			</td>
		</tr>
	{/foreach}
	</tbody>
{/foreach}
</table>

{include file="admin/_foot.tpl"}







|













16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

	{foreach from=$group.accounts item="account"}
		<tr>
			<td class="num">{$account.code}</td>
			<th>{$account.label}</th>
			<td class="desc">{$account.description}</td>
			<td class="actions">
				{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN) && !$chart.archived}
					{if $account.user || !$chart.code}
						{linkbutton shape="delete" label="Supprimer" href="!acc/charts/accounts/delete.php?id=%d"|args:$account.id}
					{/if}
					{linkbutton shape="edit" label="Modifier" href="!acc/charts/accounts/edit.php?id=%d"|args:$account.id}
				{/if}
			</td>
		</tr>
	{/foreach}
	</tbody>
{/foreach}
</table>

{include file="admin/_foot.tpl"}

Modified src/templates/acc/charts/accounts/selector.tpl from [6cbc945144] to [4fc94408d5].

1
2
3
4
5
6
7
8
{include file="admin/_head.tpl" title="Sélectionner un compte" body_id="popup" is_popup=true}

{if empty($grouped_accounts) && empty($accounts)}
	<p class="block alert">Le plan comptable ne comporte aucun compte de ce type. Pour afficher des comptes ici, les <a href="{$www_url}admin/acc/charts/accounts/all.php?id={$chart.id}" target="_blank">modifier dans le plan comptable</a> en sélectionnant le type de compte favori voulu.</td>

{elseif isset($grouped_accounts)}

	<?php $index = 1; ?>
|







1
2
3
4
5
6
7
8
{include file="admin/_head.tpl" title="Sélectionner un compte"}

{if empty($grouped_accounts) && empty($accounts)}
	<p class="block alert">Le plan comptable ne comporte aucun compte de ce type. Pour afficher des comptes ici, les <a href="{$www_url}admin/acc/charts/accounts/all.php?id={$chart.id}" target="_blank">modifier dans le plan comptable</a> en sélectionnant le type de compte favori voulu.</td>

{elseif isset($grouped_accounts)}

	<?php $index = 1; ?>

Modified src/templates/acc/charts/index.tpl from [edc5b4d9b1] to [0e0aa6ffba].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{include file="admin/_head.tpl" title="Gestion des plans comptables" current="acc/charts"}

<nav class="tabs">
	<ul>
		<li class="current"><a href="{$admin_url}acc/charts/">Plans comptables</a></li>
		{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
			<li><a href="{$admin_url}acc/charts/import.php">Importer un plan comptable</a></li>
		{/if}
	</ul>
</nav>

{if $_GET.msg == 'OPEN'}
<p class="block alert">
	Il n'existe aucun exercice ouvert.
	{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
		Merci d'en <a href="{$admin_url}acc/years/new.php">créer un nouveau</a> pour pouvoir saisir des écritures.
	{/if}
</p>
{/if}

{if count($list)}
	<table class="list">





|








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{include file="admin/_head.tpl" title="Gestion des plans comptables" current="acc/charts"}

<nav class="tabs">
	<ul>
		<li class="current"><a href="{$admin_url}acc/charts/">Plans comptables</a></li>
		{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
			<li><a href="{$admin_url}acc/charts/import.php">Importer un plan comptable</a></li>
		{/if}
	</ul>
</nav>

{if $_GET.msg == 'OPEN'}
<p class="block alert">
	Il n'existe aucun exercice ouvert.
	{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
		Merci d'en <a href="{$admin_url}acc/years/new.php">créer un nouveau</a> pour pouvoir saisir des écritures.
	{/if}
</p>
{/if}

{if count($list)}
	<table class="list">
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
					<td>{$item.country|get_country_name}</td>
					<th><a href="{$admin_url}acc/charts/accounts/?id={$item.id}">{$item.label}</a></th>
					<td>{if $item.code}Officiel{else}Personnel{/if}</td>
					<td>{if $item.archived}<em>Archivé</em>{/if}</td>
					<td class="actions">
						{linkbutton shape="star" label="Comptes favoris" href="!acc/charts/accounts/?id=%d"|args:$item.id}
						{linkbutton shape="menu" label="Tous les comptes" href="!acc/charts/accounts/all.php?id=%d"|args:$item.id}
						{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
							{linkbutton shape="edit" label="Modifier" href="!acc/charts/edit.php?id=%d"|args:$item.id}
							{linkbutton shape="export" label="Export CSV" href="!acc/charts/export.php?id=%d"|args:$item.id}
							{linkbutton shape="export" label="Export tableur" href="!acc/charts/export.php?id=%d&ods"|args:$item.id}
							{if !$item.code && !$item.archived}
								{linkbutton shape="delete" label="Supprimer" href="!acc/charts/delete.php?id=%d"|args:$item.id}
							{/if}
						{/if}
					</td>
				</tr>
			{/foreach}
		</tbody>
	</table>
{/if}

{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
	<form method="post" action="{$self_url_no_qs}">
		<fieldset>
			<legend>Créer un nouveau plan comptable</legend>
			<dl>
				{input type="select_groups" name="copy" options=$charts_groupped label="Recopier depuis" required=1 default=$from}
				{input type="text" name="label" label="Libellé" required=1}
				{input type="select" name="country" label="Pays" required=1 options=$country_list default=$config.pays}







|














|







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
					<td>{$item.country|get_country_name}</td>
					<th><a href="{$admin_url}acc/charts/accounts/?id={$item.id}">{$item.label}</a></th>
					<td>{if $item.code}Officiel{else}Personnel{/if}</td>
					<td>{if $item.archived}<em>Archivé</em>{/if}</td>
					<td class="actions">
						{linkbutton shape="star" label="Comptes favoris" href="!acc/charts/accounts/?id=%d"|args:$item.id}
						{linkbutton shape="menu" label="Tous les comptes" href="!acc/charts/accounts/all.php?id=%d"|args:$item.id}
						{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
							{linkbutton shape="edit" label="Modifier" href="!acc/charts/edit.php?id=%d"|args:$item.id}
							{linkbutton shape="export" label="Export CSV" href="!acc/charts/export.php?id=%d"|args:$item.id}
							{linkbutton shape="export" label="Export tableur" href="!acc/charts/export.php?id=%d&ods"|args:$item.id}
							{if !$item.code && !$item.archived}
								{linkbutton shape="delete" label="Supprimer" href="!acc/charts/delete.php?id=%d"|args:$item.id}
							{/if}
						{/if}
					</td>
				</tr>
			{/foreach}
		</tbody>
	</table>
{/if}

{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
	<form method="post" action="{$self_url_no_qs}">
		<fieldset>
			<legend>Créer un nouveau plan comptable</legend>
			<dl>
				{input type="select_groups" name="copy" options=$charts_groupped label="Recopier depuis" required=1 default=$from}
				{input type="text" name="label" label="Libellé" required=1}
				{input type="select" name="country" label="Pays" required=1 options=$country_list default=$config.pays}

Modified src/templates/acc/index.tpl from [10bfa27777] to [63dacb5997].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{include file="admin/_head.tpl" title="Comptabilité" current="acc"}

{foreach from=$years item="year"}
<section class="year-infos">
	<h2 class="ruler">{$year.label} —
		Du {$year.start_date|date_short} au {$year.end_date|date_short}</h2>

	<nav class="tabs">
		<aside>
			{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
				{linkbutton shape="upload" href="!acc/years/import.php?id=%d"|args:$year.id label="Import & export"}
			{/if}
			{linkbutton shape="search" href="!acc/search.php?year=%d"|args:$year.id label="Recherche"}
		</aside>
		<ul>
			<li><a href="{$admin_url}acc/reports/graphs.php?year={$year.id}">Graphiques</a></li>
			<li><a href="{$admin_url}acc/reports/trial_balance.php?year={$year.id}">Balance générale</a></li>









|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{include file="admin/_head.tpl" title="Comptabilité" current="acc"}

{foreach from=$years item="year"}
<section class="year-infos">
	<h2 class="ruler">{$year.label} —
		Du {$year.start_date|date_short} au {$year.end_date|date_short}</h2>

	<nav class="tabs">
		<aside>
			{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
				{linkbutton shape="upload" href="!acc/years/import.php?id=%d"|args:$year.id label="Import & export"}
			{/if}
			{linkbutton shape="search" href="!acc/search.php?year=%d"|args:$year.id label="Recherche"}
		</aside>
		<ul>
			<li><a href="{$admin_url}acc/reports/graphs.php?year={$year.id}">Graphiques</a></li>
			<li><a href="{$admin_url}acc/reports/trial_balance.php?year={$year.id}">Balance générale</a></li>

Modified src/templates/acc/reports/_journal.tpl from [4ecba1da68] to [ae9d01ba2d].

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
		<tr>
			<td rowspan="{$transaction.lines|count}" class="num"><a href="{$admin_url}acc/transactions/details.php?id={$transaction.id}">#{$transaction.id}</a></td>
			<td rowspan="{$transaction.lines|count}">{$transaction.reference}</td>
			<td rowspan="{$transaction.lines|count}">{$transaction.date|date_short}</td>
			<th rowspan="{$transaction.lines|count}">{$transaction.label}</th>
		{foreach from=$transaction.lines item="line"}
			<td>{$line.account_code} - {$line.account_label}</td>
			<td class="money">{$line.debit|raw|html_money}</td>
			<td class="money">{$line.credit|raw|html_money}</td>
			<td>{$line.label}</td>
			<td>{$line.reference}</td>
		</tr>
		<tr>
		{/foreach}
		</tr>
	</tbody>
	{/foreach}
</table>







|
|









17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
		<tr>
			<td rowspan="{$transaction.lines|count}" class="num"><a href="{$admin_url}acc/transactions/details.php?id={$transaction.id}">#{$transaction.id}</a></td>
			<td rowspan="{$transaction.lines|count}">{$transaction.reference}</td>
			<td rowspan="{$transaction.lines|count}">{$transaction.date|date_short}</td>
			<th rowspan="{$transaction.lines|count}">{$transaction.label}</th>
		{foreach from=$transaction.lines item="line"}
			<td>{$line.account_code} - {$line.account_label}</td>
			<td class="money">{$line.debit|raw|money}</td>
			<td class="money">{$line.credit|raw|money}</td>
			<td>{$line.label}</td>
			<td>{$line.reference}</td>
		</tr>
		<tr>
		{/foreach}
		</tr>
	</tbody>
	{/foreach}
</table>

Modified src/templates/acc/reports/_statement.tpl from [2408ac0c3b] to [674c33b3c6].

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
	<tfoot>
		<tr>
			<td>
				<table>
					<tfoot>
						<tr>
							<th>Total</th>
							<td class="money">{$statement.expense_sum|raw|html_money:false}</td>
						</tr>
					</tfoot>
				</table>
			</td>
			<td>
				<table>
					<tfoot>
						<tr>
							<th>Total</th>
							<td class="money">{$statement.revenue_sum|raw|html_money:false}</td>
						</tr>
					</tfoot>
				</table>
			</td>
		</tr>
		{if $statement.result}
		<tr>
			<td>
			{if ($statement.result < 0)}
				<table>
					<tfoot>
						<tr>
							<th>Résultat (perte)</th>
							<td class="money">{$statement.result|raw|html_money:false}</td>
						</tr>
					</tfoot>
				</table>
			{/if}
			</td>
			<td>
			{if ($statement.result >= 0)}
				<table>
					<tfoot>
						<tr>
							<th>Résultat (excédent)</th>
							<td class="money">{$statement.result|raw|html_money:false}</td>
						</tr>
					</tfoot>
				</table>
			{/if}
			</td>
		</tr>
		{/if}
	</tfoot>
</table>







|









|













|











|









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
	<tfoot>
		<tr>
			<td>
				<table>
					<tfoot>
						<tr>
							<th>Total</th>
							<td class="money">{$statement.expense_sum|raw|money:false}</td>
						</tr>
					</tfoot>
				</table>
			</td>
			<td>
				<table>
					<tfoot>
						<tr>
							<th>Total</th>
							<td class="money">{$statement.revenue_sum|raw|money:false}</td>
						</tr>
					</tfoot>
				</table>
			</td>
		</tr>
		{if $statement.result}
		<tr>
			<td>
			{if ($statement.result < 0)}
				<table>
					<tfoot>
						<tr>
							<th>Résultat (perte)</th>
							<td class="money">{$statement.result|raw|money:false}</td>
						</tr>
					</tfoot>
				</table>
			{/if}
			</td>
			<td>
			{if ($statement.result >= 0)}
				<table>
					<tfoot>
						<tr>
							<th>Résultat (excédent)</th>
							<td class="money">{$statement.result|raw|money:false}</td>
						</tr>
					</tfoot>
				</table>
			{/if}
			</td>
		</tr>
		{/if}
	</tfoot>
</table>

Modified src/templates/acc/reports/_statement_table.tpl from [59dd236cd8] to [cb39c0e999].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<table class="list">
	{if !empty($caption)}
		<caption><h3>{$caption}</h3></caption>
	{/if}
	<tbody>
	{foreach from=$accounts item="account"}
		<tr class="compte">
			<td class="num">
				{if !empty($year)}<a href="{$admin_url}acc/accounts/journal.php?id={$account.id}&amp;year={$year.id}">{$account.code}</a>
				{else}{$account.code}
				{/if}
			</td>
			<th>{$account.label}</th>
			<td class="money">{$account.sum|raw|html_money}</td>
		</tr>
	{/foreach}
	</tbody>
</table>













|




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<table class="list">
	{if !empty($caption)}
		<caption><h3>{$caption}</h3></caption>
	{/if}
	<tbody>
	{foreach from=$accounts item="account"}
		<tr class="compte">
			<td class="num">
				{if !empty($year)}<a href="{$admin_url}acc/accounts/journal.php?id={$account.id}&amp;year={$year.id}">{$account.code}</a>
				{else}{$account.code}
				{/if}
			</td>
			<th>{$account.label}</th>
			<td class="money">{$account.sum|raw|money}</td>
		</tr>
	{/foreach}
	</tbody>
</table>

Modified src/templates/acc/reports/balance_sheet.tpl from [a7a5928f43] to [dc88e4cf11].

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
	<tfoot>
		<tr>
			<td>
				<table>
					<tfoot>
						<tr>
							<th>Total actif</th>
							<td class="money">{$asset_sum|raw|html_money:false}</td>
						</tr>
					</tfoot>
				</table>
			</td>
			<td>
				<table>
					<tfoot>
						<tr>
							<th>Total passif</th>
							<td class="money">{$liability_sum|raw|html_money:false}</td>
						</tr>
					</tfoot>
				</table>
			</td>
		</tr>
	</tfoot>
</table>

<p class="help">Toutes les écritures sont libellées en {$config.monnaie}.</p>

{include file="admin/_foot.tpl"}







|









|











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
	<tfoot>
		<tr>
			<td>
				<table>
					<tfoot>
						<tr>
							<th>Total actif</th>
							<td class="money">{$asset_sum|raw|money:false}</td>
						</tr>
					</tfoot>
				</table>
			</td>
			<td>
				<table>
					<tfoot>
						<tr>
							<th>Total passif</th>
							<td class="money">{$liability_sum|raw|money:false}</td>
						</tr>
					</tfoot>
				</table>
			</td>
		</tr>
	</tfoot>
</table>

<p class="help">Toutes les écritures sont libellées en {$config.monnaie}.</p>

{include file="admin/_foot.tpl"}

Modified src/templates/acc/reports/ledger.tpl from [a06ebc88ec] to [2309772ddd].

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
		{foreach from=$account.lines item="line"}
			<tr>
				<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$line.id}">#{$line.id}</a></td>
				<td>{$line.reference}</td>
				<td>{$line.line_reference}</td>
				<td>{$line.date|date_short}</td>
				<th>{$line.label}{if $line.line_label} <em>({$line.line_label})</em>{/if}</th>
				<td class="money">{$line.debit|raw|html_money}</td>
				<td class="money">{$line.credit|raw|html_money}</td>
				<td class="money">{$line.running_sum|raw|html_money:false}</td>
			</tr>
		{/foreach}
		</tbody>
		<tfoot>
			<tr>
				<td colspan="4"></td>
				<th>Solde final</th>
				<td class="money">{$account.debit|raw|html_money}</td>
				<td class="money">{$account.credit|raw|html_money}</td>
				<td class="money">{$account.sum|raw|html_money:false}</td>
			</tr>
		</tfoot>
	</table>

</details>

{if isset($account->all_debit)}
	<table class="list">
		<colgroup>
			<col width="70%" />
			<col width="10%" />
			<col width="10%" />
			<col width="10%" />
		</colgroup>
		<tfoot>
			<tr>
				<td><strong>Totaux</strong></td>
				<td class="money">{$account.all_debit|raw|html_money:false}</td>
				<td class="money">{$account.all_credit|raw|html_money:false}</td>
				<td></td>
			</tr>
		</tfoot>
	</table>
{/if}

{/foreach}







|
|
|







|
|
|

















|
|







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
		{foreach from=$account.lines item="line"}
			<tr>
				<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$line.id}">#{$line.id}</a></td>
				<td>{$line.reference}</td>
				<td>{$line.line_reference}</td>
				<td>{$line.date|date_short}</td>
				<th>{$line.label}{if $line.line_label} <em>({$line.line_label})</em>{/if}</th>
				<td class="money">{$line.debit|raw|money}</td>
				<td class="money">{$line.credit|raw|money}</td>
				<td class="money">{$line.running_sum|raw|money:false}</td>
			</tr>
		{/foreach}
		</tbody>
		<tfoot>
			<tr>
				<td colspan="4"></td>
				<th>Solde final</th>
				<td class="money">{$account.debit|raw|money}</td>
				<td class="money">{$account.credit|raw|money}</td>
				<td class="money">{$account.sum|raw|money:false}</td>
			</tr>
		</tfoot>
	</table>

</details>

{if isset($account->all_debit)}
	<table class="list">
		<colgroup>
			<col width="70%" />
			<col width="10%" />
			<col width="10%" />
			<col width="10%" />
		</colgroup>
		<tfoot>
			<tr>
				<td><strong>Totaux</strong></td>
				<td class="money">{$account.all_debit|raw|money:false}</td>
				<td class="money">{$account.all_credit|raw|money:false}</td>
				<td></td>
			</tr>
		</tfoot>
	</table>
{/if}

{/foreach}

Modified src/templates/acc/reports/projects.tpl from [c1c139c152] to [4800025ba6].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{include file="admin/_head.tpl" title="Projets" current="acc/years"}

<nav class="tabs">
	{if CURRENT_YEAR_ID}
	<aside>
		{linkbutton label="Créer un nouveau compte de projet" href="!acc/charts/accounts/new.php?id=%d&type=%d"|args:$current_year.id_chart,$analytical_type shape="plus"}
	</aside>
	{/if}

	<ul>
		<li><a href="{$admin_url}acc/years/">Exercices</a></li>
		{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
		<li><a href="{$admin_url}acc/years/new.php">Nouvel exercice</a></li>
		{/if}
		<li class="current"><a href="{$admin_url}acc/reports/projects.php">Projets <em>(compta analytique)</em></a></li>
	</ul>

	<ul class="sub">
		<li{if !$by_year} class="current"{/if}><a href="{$self_url_no_qs}">Par projet</a></li>











|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{include file="admin/_head.tpl" title="Projets" current="acc/years"}

<nav class="tabs">
	{if CURRENT_YEAR_ID}
	<aside>
		{linkbutton label="Créer un nouveau compte de projet" href="!acc/charts/accounts/new.php?id=%d&type=%d"|args:$current_year.id_chart,$analytical_type shape="plus"}
	</aside>
	{/if}

	<ul>
		<li><a href="{$admin_url}acc/years/">Exercices</a></li>
		{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
		<li><a href="{$admin_url}acc/years/new.php">Nouvel exercice</a></li>
		{/if}
		<li class="current"><a href="{$admin_url}acc/reports/projects.php">Projets <em>(compta analytique)</em></a></li>
	</ul>

	<ul class="sub">
		<li{if !$by_year} class="current"{/if}><a href="{$self_url_no_qs}">Par projet</a></li>
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
						| <a href="{$admin_url}acc/reports/trial_balance.php?analytical={$item.id_account}&year={$item.id_year}">Balance générale</a>
						| <a href="{$admin_url}acc/reports/journal.php?analytical={$item.id_account}&year={$item.id_year}">Journal général</a>
						| <a href="{$admin_url}acc/reports/ledger.php?analytical={$item.id_account}&year={$item.id_year}">Grand livre</a>
						| <a href="{$admin_url}acc/reports/statement.php?analytical={$item.id_account}&year={$item.id_year}">Compte de résultat</a>
						| <a href="{$admin_url}acc/reports/balance_sheet.php?analytical={$item.id_account}&year={$item.id_year}">Bilan</a>
					</span>
					</td>
					<td class="money">{$item.sum_expense|raw|html_money}</td>
					<td class="money">{$item.sum_revenue|raw|html_money}</td>
					<td class="money">{$item.debit|raw|html_money:false}</td>
					<td class="money">{$item.credit|raw|html_money:false}</td>
					<td class="money">{$item.sum|raw|html_money:false}</td>
				</tr>
			{/foreach}
			</tbody>
		{/foreach}
	</table>

{else}







|
|
|
|
|







61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
						| <a href="{$admin_url}acc/reports/trial_balance.php?analytical={$item.id_account}&year={$item.id_year}">Balance générale</a>
						| <a href="{$admin_url}acc/reports/journal.php?analytical={$item.id_account}&year={$item.id_year}">Journal général</a>
						| <a href="{$admin_url}acc/reports/ledger.php?analytical={$item.id_account}&year={$item.id_year}">Grand livre</a>
						| <a href="{$admin_url}acc/reports/statement.php?analytical={$item.id_account}&year={$item.id_year}">Compte de résultat</a>
						| <a href="{$admin_url}acc/reports/balance_sheet.php?analytical={$item.id_account}&year={$item.id_year}">Bilan</a>
					</span>
					</td>
					<td class="money">{$item.sum_expense|raw|money}</td>
					<td class="money">{$item.sum_revenue|raw|money}</td>
					<td class="money">{$item.debit|raw|money:false}</td>
					<td class="money">{$item.credit|raw|money:false}</td>
					<td class="money">{$item.sum|raw|money:false}</td>
				</tr>
			{/foreach}
			</tbody>
		{/foreach}
	</table>

{else}

Modified src/templates/acc/reports/trial_balance.tpl from [98a27d9282] to [14933bb3ab].

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
		<tr>
			<td class="num">
				{if !empty($year)}<a href="{$admin_url}acc/accounts/journal.php?id={$account.id}&amp;year={$year.id}">{$account.code}</a>
				{else}{$account.code}
				{/if}
			</td>
			<th>{$account.label}</th>
			<td class="money">{$account.debit|raw|html_money}</td>
			<td class="money">{$account.credit|raw|html_money}</td>
			<td class="money">{if $account.sum < 0}{$account.sum|abs|escape|html_money}{/if}</td>
			<td class="money">{if $account.sum > 0}{$account.sum|abs|escape|html_money}{/if}</td>
		</tr>
	{/foreach}
	</tbody>
</table>

<p class="help">Toutes les écritures sont libellées en {$config.monnaie}.</p>

{include file="admin/_foot.tpl"}







|
|
|
|








18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
		<tr>
			<td class="num">
				{if !empty($year)}<a href="{$admin_url}acc/accounts/journal.php?id={$account.id}&amp;year={$year.id}">{$account.code}</a>
				{else}{$account.code}
				{/if}
			</td>
			<th>{$account.label}</th>
			<td class="money">{$account.debit|raw|money}</td>
			<td class="money">{$account.credit|raw|money}</td>
			<td class="money">{if $account.sum < 0}{$account.sum|abs|escape|money}{/if}</td>
			<td class="money">{if $account.sum > 0}{$account.sum|abs|escape|money}{/if}</td>
		</tr>
	{/foreach}
	</tbody>
</table>

<p class="help">Toutes les écritures sont libellées en {$config.monnaie}.</p>

{include file="admin/_foot.tpl"}

Modified src/templates/acc/search.tpl from [8068c4405e] to [f2a1ec386b].

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
{include file="admin/_head.tpl" title="Recherche" current="acc" custom_js=['query_builder.min.js']}

<nav class="tabs">
	<ul>
		<li class="current"><a href="{$self_url}">Recherche</a></li>
		<li><a href="saved_searches.php">Recherches enregistrées</a></li>
	</ul>
</nav>

{include file="common/search/advanced.tpl" action_url=$self_url}

{if !empty($result)}
	{*if $session->canAccess('compta', Membres::DROIT_ECRITURE)}
		<form method="post" action="{$admin_url}membres/action.php" class="memberList">
	{/if*}

	<p class="help">{$result|count} écritures trouvées pour cette recherche.</p>
	<table class="list search">
		<thead>
			<tr>
				{*if $session->canAccess('membres', Membres::DROIT_ADMIN)}<td class="check"><input type="checkbox" value="Tout cocher / décocher" /></td>{/if*}
				{foreach from=$result_header item="label"}
					<td>{$label}</td>
				{/foreach}
				<td></td>
			</tr>
		</thead>
		<tbody>
			{foreach from=$result item="row"}
				<tr>
					{*if $session->canAccess('membres', Membres::DROIT_ADMIN)}<td class="check"><input type="checkbox" name="selected[]" value="{$row.id}" /></td>{/if*}
					{foreach from=$row key="key" item="value"}
						{if $key == 'transaction_id'}
						<td class="num">
							<a href="{$admin_url}acc/transactions/details.php?id={$value}">{$value}</a>
						</td>
						{else}
						<td>
							{if $key == 'credit' || $key == 'debit'}
								{$value|raw|html_money:false}
							{elseif $key == 'date'}
								{$value|date_short}
							{elseif null == $value}
								<em>(nul)</em>
							{else}
								{$value}
							{/if}
						</td>
						{/if}
					{/foreach}
					<td class="actions">
						{if $row.transaction_id}
						{linkbutton shape="search" label="Détails" href="!acc/transactions/details.php?id=%d"|args:$row.transaction_id}
						{/if}
					</td>
				</tr>
			{/foreach}
		</tbody>
	{*if $session->canAccess('membres', Membres::DROIT_ADMIN)}
		{include file="admin/membres/_list_actions.tpl" colspan=count($result_header)+1}
	{/if*}
	</table>

	{*if $session->canAccess('membres', Membres::DROIT_ECRITURE)}
		</form>
	{/if*}

{elseif $result !== null}

	<p class="block alert">
		Aucun résultat trouvé.












|







|









|








|


















|




|







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
{include file="admin/_head.tpl" title="Recherche" current="acc" custom_js=['query_builder.min.js']}

<nav class="tabs">
	<ul>
		<li class="current"><a href="{$self_url}">Recherche</a></li>
		<li><a href="saved_searches.php">Recherches enregistrées</a></li>
	</ul>
</nav>

{include file="common/search/advanced.tpl" action_url=$self_url}

{if !empty($result)}
	{*if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_WRITE)}
		<form method="post" action="{$admin_url}membres/action.php" class="memberList">
	{/if*}

	<p class="help">{$result|count} écritures trouvées pour cette recherche.</p>
	<table class="list search">
		<thead>
			<tr>
				{*if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}<td class="check"><input type="checkbox" value="Tout cocher / décocher" /></td>{/if*}
				{foreach from=$result_header item="label"}
					<td>{$label}</td>
				{/foreach}
				<td></td>
			</tr>
		</thead>
		<tbody>
			{foreach from=$result item="row"}
				<tr>
					{*if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}<td class="check"><input type="checkbox" name="selected[]" value="{$row.id}" /></td>{/if*}
					{foreach from=$row key="key" item="value"}
						{if $key == 'transaction_id'}
						<td class="num">
							<a href="{$admin_url}acc/transactions/details.php?id={$value}">{$value}</a>
						</td>
						{else}
						<td>
							{if $key == 'credit' || $key == 'debit'}
								{$value|raw|money:false}
							{elseif $key == 'date'}
								{$value|date_short}
							{elseif null == $value}
								<em>(nul)</em>
							{else}
								{$value}
							{/if}
						</td>
						{/if}
					{/foreach}
					<td class="actions">
						{if $row.transaction_id}
						{linkbutton shape="search" label="Détails" href="!acc/transactions/details.php?id=%d"|args:$row.transaction_id}
						{/if}
					</td>
				</tr>
			{/foreach}
		</tbody>
	{*if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
		{include file="admin/membres/_list_actions.tpl" colspan=count($result_header)+1}
	{/if*}
	</table>

	{*if $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)}
		</form>
	{/if*}

{elseif $result !== null}

	<p class="block alert">
		Aucun résultat trouvé.

Modified src/templates/acc/transactions/details.tpl from [42225313b2] to [799aae9d5a].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{include file="admin/_head.tpl" title="Écriture n°%d"|args:$transaction.id current="acc"}

{if $session->canAccess('compta', Membres::DROIT_ADMIN) && !$transaction->validated && !$tr_year->closed}
<nav class="tabs">
	<ul>
		<li><a href="edit.php?id={$transaction.id}">Modifier cette écriture</a></li>
		<li><a href="delete.php?id={$transaction.id}">Supprimer cette écriture</a></li>
	</ul>
</nav>
{/if}

{if $session->canAccess('compta', Membres::DROIT_ECRITURE) && $transaction.status & $transaction::STATUS_WAITING}
<div class="block alert">
	<form method="post" action="{$self_url}">
	{if $transaction.type == $transaction::TYPE_DEBT}
		<h3>Dette en attente</h3>
		{linkbutton shape="check" label="Enregistrer le règlement de cette dette" href="!acc/transactions/new.php?payoff_for=%d"|args:$transaction.id}
	{else}
		<h3>Créance en attente</h3>


|








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{include file="admin/_head.tpl" title="Écriture n°%d"|args:$transaction.id current="acc"}

{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN) && !$transaction->validated && !$tr_year->closed}
<nav class="tabs">
	<ul>
		<li><a href="edit.php?id={$transaction.id}">Modifier cette écriture</a></li>
		<li><a href="delete.php?id={$transaction.id}">Supprimer cette écriture</a></li>
	</ul>
</nav>
{/if}

{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_WRITE) && $transaction.status & $transaction::STATUS_WAITING}
<div class="block alert">
	<form method="post" action="{$self_url}">
	{if $transaction.type == $transaction::TYPE_DEBT}
		<h3>Dette en attente</h3>
		{linkbutton shape="check" label="Enregistrer le règlement de cette dette" href="!acc/transactions/new.php?payoff_for=%d"|args:$transaction.id}
	{else}
		<h3>Créance en attente</h3>
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
	<dt>Type</dt>
	<dd>
		{$transaction->getTypeName()}
	</dd>
	<dt>Libellé</dt>
	<dd><h2>{$transaction.label}</h2></dd>
	<dt>Date</dt>
	<dd>{$transaction.date|date_fr:'l j F Y (d/m/Y)'}</dd>
	<dt>Numéro pièce comptable</dt>
	<dd>{if trim($transaction.reference)}{$transaction.reference}{else}-{/if}</dd>

	<dt>Exercice</dt>
	<dd>
		<a href="{$admin_url}acc/reports/ledger.php?year={$transaction.id_year}">{$tr_year.label}</a>
		| Du {$tr_year.start_date|date_short} au {$tr_year.end_date|date_short}
		| <strong>{if $tr_year.closed}Clôturé{else}En cours{/if}</strong>
	</dd>

	<dt>Écriture créée par</dt>
	<dd>
		{if $transaction.id_creator}
			{if $session->canAccess('compta', Membres::DROIT_ACCES)}
				<a href="{$admin_url}membres/fiche.php?id={$transaction.id_creator}">{$creator_name}</a>
			{else}
				{$creator_name}
			{/if}
		{else}
			<em>membre supprimé</em>
		{/if}







|













|







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
	<dt>Type</dt>
	<dd>
		{$transaction->getTypeName()}
	</dd>
	<dt>Libellé</dt>
	<dd><h2>{$transaction.label}</h2></dd>
	<dt>Date</dt>
	<dd>{$transaction.date|date:'l j F Y (d/m/Y)'}</dd>
	<dt>Numéro pièce comptable</dt>
	<dd>{if trim($transaction.reference)}{$transaction.reference}{else}-{/if}</dd>

	<dt>Exercice</dt>
	<dd>
		<a href="{$admin_url}acc/reports/ledger.php?year={$transaction.id_year}">{$tr_year.label}</a>
		| Du {$tr_year.start_date|date_short} au {$tr_year.end_date|date_short}
		| <strong>{if $tr_year.closed}Clôturé{else}En cours{/if}</strong>
	</dd>

	<dt>Écriture créée par</dt>
	<dd>
		{if $transaction.id_creator}
			{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ)}
				<a href="{$admin_url}membres/fiche.php?id={$transaction.id_creator}">{$creator_name}</a>
			{else}
				{$creator_name}
			{/if}
		{else}
			<em>membre supprimé</em>
		{/if}
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
				{if $u.id_service_user}— en règlement d'une <a href="{$admin_url}services/user.php?id={$u.id}&amp;only={$u.id_service_user}">activité</a>{/if}
			</dd>
		{/foreach}
	{/if}

	<dt>Remarques</dt>
	<dd>{if trim($transaction.notes)}{$transaction.notes|escape|nl2br}{else}-{/if}</dd>

	<dt>Fichiers joints</dt>
	{foreach from=$files item="file"}
	<dd>
		<aside class="file">
			<a target="_blank" href="{$file.url}">{$file.nom}</a>
			<small>({$file.type}, {$file.taille|format_bytes})</small>
			{linkbutton shape="download" href=$file.url target="_blank" label="Télécharger"}
			{linkbutton shape="delete" href="!acc/transactions/delete_file.php?id=%d&from=%d"|args:$file.id,$transaction.id label="Supprimer"}
		</aside>
	</dd>
	{foreachelse}
	<dd>-</dd>
	{/foreach}
</dl>

<table class="list">
	<thead>
		<tr>
			<td class="num">N° compte</td>
			<th>Compte</th>
			<td class="money">Débit</td>
			<td class="money">Crédit</td>
			<td>Libellé</td>
			<td>Référence</td>
			<td>Projet</td>
		</tr>
	</thead>
	<tbody>
		{foreach from=$transaction->getLinesWithAccounts(false) item="line"}
		<tr>
			<td class="num"><a href="{$admin_url}acc/accounts/journal.php?id={$line.id_account}&amp;year={$transaction.id_year}">{$line.account_code}</a></td>
			<td>{$line.account_name}</td>
			<td class="money">{if $line.debit}{$line.debit|escape|html_money}{/if}</td>
			<td class="money">{if $line.credit}{$line.credit|escape|html_money}{/if}</td>
			<td>{$line.label}</td>
			<td>{$line.reference}</td>
			<td>
				{if $line.id_analytical}
					<a href="{$admin_url}acc/reports/statement.php?analytical={$line.id_analytical}">{$line.analytical_name}</a>
				{/if}
			</td>
		</tr>
		{/foreach}
	</tbody>
</table>








{include file="admin/_foot.tpl"}







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



















|
|












>
>
>
>
>
>
>

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
				{if $u.id_service_user}— en règlement d'une <a href="{$admin_url}services/user.php?id={$u.id}&amp;only={$u.id_service_user}">activité</a>{/if}
			</dd>
		{/foreach}
	{/if}

	<dt>Remarques</dt>
	<dd>{if trim($transaction.notes)}{$transaction.notes|escape|nl2br}{else}-{/if}</dd>














</dl>

<table class="list">
	<thead>
		<tr>
			<td class="num">N° compte</td>
			<th>Compte</th>
			<td class="money">Débit</td>
			<td class="money">Crédit</td>
			<td>Libellé</td>
			<td>Référence</td>
			<td>Projet</td>
		</tr>
	</thead>
	<tbody>
		{foreach from=$transaction->getLinesWithAccounts(false) item="line"}
		<tr>
			<td class="num"><a href="{$admin_url}acc/accounts/journal.php?id={$line.id_account}&amp;year={$transaction.id_year}">{$line.account_code}</a></td>
			<td>{$line.account_name}</td>
			<td class="money">{if $line.debit}{$line.debit|escape|money}{/if}</td>
			<td class="money">{if $line.credit}{$line.credit|escape|money}{/if}</td>
			<td>{$line.label}</td>
			<td>{$line.reference}</td>
			<td>
				{if $line.id_analytical}
					<a href="{$admin_url}acc/reports/statement.php?analytical={$line.id_analytical}">{$line.analytical_name}</a>
				{/if}
			</td>
		</tr>
		{/foreach}
	</tbody>
</table>

{if $can_upload || count($files)}
<div class="attachments">
	<h3 class="ruler">Fichiers joints</h3>
	{include file="common/files/_context_list.tpl" files=$files can_upload=$can_upload path=$file_parent}
</div>
{/if}

{include file="admin/_foot.tpl"}

Modified src/templates/acc/transactions/edit.tpl from [9472a8358a] to [e2fa247466].

1
2
3
4
5
6
7
8
9
10
{include file="admin/_head.tpl" title="Modification d'une écriture" current="acc/simple"}

<form method="post" action="{$self_url}" enctype="multipart/form-data" data-focus="#f_date">
	{form_errors}

	{if $has_reconciled_lines}
	<p class="alert block">
		Attention, cette écriture contient des lignes qui ont été rapprochées. La modification de cette écriture entraînera la perte du rapprochement.
	</p>
	{/if}


|







1
2
3
4
5
6
7
8
9
10
{include file="admin/_head.tpl" title="Modification d'une écriture" current="acc/simple"}

<form method="post" action="{$self_url}" data-focus="#f_date">
	{form_errors}

	{if $has_reconciled_lines}
	<p class="alert block">
		Attention, cette écriture contient des lignes qui ont été rapprochées. La modification de cette écriture entraînera la perte du rapprochement.
	</p>
	{/if}
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
		<legend>Détails facultatifs</legend>
		<dl data-types="t{$transaction::TYPE_REVENUE} t{$transaction::TYPE_EXPENSE} t{$transaction::TYPE_TRANSFER}">
			{input type="text" name="payment_reference" label="Référence de paiement" help="Numéro de chèque, numéro de transaction CB, etc." default=$first_line.reference}
		</dl>
		<dl>
			{input type="list" multiple=true name="users" label="Membres associés" target="membres/selector.php" default=$linked_users}
			{input type="textarea" name="notes" label="Remarques" rows=4 cols=30 source=$transaction}

			{input type="file" name="file" label="Ajouter un fichier joint"}
		</dl>
		<dl data-types="all-but-advanced">
			{if count($analytical_accounts) > 1}
				{input type="select" name="id_analytical" label="Projet (compte analytique)" options=$analytical_accounts default=$first_line.id_analytical}
			{/if}
		</dl>
	</fieldset>







<
<







61
62
63
64
65
66
67


68
69
70
71
72
73
74
		<legend>Détails facultatifs</legend>
		<dl data-types="t{$transaction::TYPE_REVENUE} t{$transaction::TYPE_EXPENSE} t{$transaction::TYPE_TRANSFER}">
			{input type="text" name="payment_reference" label="Référence de paiement" help="Numéro de chèque, numéro de transaction CB, etc." default=$first_line.reference}
		</dl>
		<dl>
			{input type="list" multiple=true name="users" label="Membres associés" target="membres/selector.php" default=$linked_users}
			{input type="textarea" name="notes" label="Remarques" rows=4 cols=30 source=$transaction}


		</dl>
		<dl data-types="all-but-advanced">
			{if count($analytical_accounts) > 1}
				{input type="select" name="id_analytical" label="Projet (compte analytique)" options=$analytical_accounts default=$first_line.id_analytical}
			{/if}
		</dl>
	</fieldset>

Modified src/templates/acc/transactions/new.tpl from [46f9d6e317] to [49e96a9c33].

1
2
3
4
5
6
7
8
9
10
11
12
{include file="admin/_head.tpl" title="Saisie d'une écriture" current="acc/new"}

{include file="acc/_year_select.tpl"}

<form method="post" action="{$self_url}" enctype="multipart/form-data" data-focus="1">
	{form_errors}

	{if $ok}
		<p class="block confirm">
			L'écriture numéro <a href="details.php?id={$ok}">{$ok}</a> a été ajoutée.
			(<a href="details.php?id={$ok}">Voir l'écriture</a>)
		</p>




|







1
2
3
4
5
6
7
8
9
10
11
12
{include file="admin/_head.tpl" title="Saisie d'une écriture" current="acc/new"}

{include file="acc/_year_select.tpl"}

<form method="post" action="{$self_url}" data-focus="1">
	{form_errors}

	{if $ok}
		<p class="block confirm">
			L'écriture numéro <a href="details.php?id={$ok}">{$ok}</a> a été ajoutée.
			(<a href="details.php?id={$ok}">Voir l'écriture</a>)
		</p>
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
		<legend>Détails facultatifs</legend>
		<dl data-types="t{$transaction::TYPE_REVENUE} t{$transaction::TYPE_EXPENSE} t{$transaction::TYPE_TRANSFER}">
			{input type="text" name="payment_reference" label="Référence de paiement" help="Numéro de chèque, numéro de transaction CB, etc." source=$transaction}
		</dl>
		<dl>
			{input type="list" multiple=true name="users" label="Membres associés" target="membres/selector.php"}
			{input type="textarea" name="notes" label="Remarques" rows=4 cols=30}

			{input type="file" name="file" label="Fichier joint"}
		</dl>
		<dl data-types="all-but-advanced">
			{if count($analytical_accounts) > 1}
				{input type="select" name="id_analytical" label="Projet (compte analytique)" options=$analytical_accounts}
			{/if}
		</dl>
	</fieldset>







<
<







80
81
82
83
84
85
86


87
88
89
90
91
92
93
		<legend>Détails facultatifs</legend>
		<dl data-types="t{$transaction::TYPE_REVENUE} t{$transaction::TYPE_EXPENSE} t{$transaction::TYPE_TRANSFER}">
			{input type="text" name="payment_reference" label="Référence de paiement" help="Numéro de chèque, numéro de transaction CB, etc." source=$transaction}
		</dl>
		<dl>
			{input type="list" multiple=true name="users" label="Membres associés" target="membres/selector.php"}
			{input type="textarea" name="notes" label="Remarques" rows=4 cols=30}


		</dl>
		<dl data-types="all-but-advanced">
			{if count($analytical_accounts) > 1}
				{input type="select" name="id_analytical" label="Projet (compte analytique)" options=$analytical_accounts}
			{/if}
		</dl>
	</fieldset>

Modified src/templates/acc/transactions/service_user.tpl from [a8761edf6b] to [31416dfe77].

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
		</tr>
	</thead>
	<tbody>
	{foreach from=$balance item="account"}
		<tr>
			<td class="num"><a href="{$admin_url}acc/accounts/journal.php?id={$account.id}">{$account.code}</a></td>
			<th>{$account.label}</th>
			<td class="money">{if $account.sum < 0}{$account.sum|raw|html_money}{/if}</td>
			<td class="money">{if $account.sum > 0}{$account.sum|raw|html_money}{/if}</td>
		</tr>
	{/foreach}
	</tbody>
</table>

{include file="admin/_foot.tpl"}







|
|






18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
		</tr>
	</thead>
	<tbody>
	{foreach from=$balance item="account"}
		<tr>
			<td class="num"><a href="{$admin_url}acc/accounts/journal.php?id={$account.id}">{$account.code}</a></td>
			<th>{$account.label}</th>
			<td class="money">{if $account.sum < 0}{$account.sum|raw|money}{/if}</td>
			<td class="money">{if $account.sum > 0}{$account.sum|raw|money}{/if}</td>
		</tr>
	{/foreach}
	</tbody>
</table>

{include file="admin/_foot.tpl"}

Modified src/templates/acc/transactions/user.tpl from [fca819aadf] to [4c90bde47d].

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
		</tr>
	</thead>
	<tbody>
	{foreach from=$balance item="account"}
		<tr>
			<td class="num"><a href="{$admin_url}acc/accounts/journal.php?id={$account.id}">{$account.code}</a></td>
			<th>{$account.label}</th>
			<td class="money">{if $account.sum < 0}{$account.sum|raw|html_money}{/if}</td>
			<td class="money">{if $account.sum > 0}{$account.sum|raw|html_money}{/if}</td>
		</tr>
	{/foreach}
	</tbody>
</table>

{include file="admin/_foot.tpl"}







|
|






33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
		</tr>
	</thead>
	<tbody>
	{foreach from=$balance item="account"}
		<tr>
			<td class="num"><a href="{$admin_url}acc/accounts/journal.php?id={$account.id}">{$account.code}</a></td>
			<th>{$account.label}</th>
			<td class="money">{if $account.sum < 0}{$account.sum|raw|money}{/if}</td>
			<td class="money">{if $account.sum > 0}{$account.sum|raw|money}{/if}</td>
		</tr>
	{/foreach}
	</tbody>
</table>

{include file="admin/_foot.tpl"}

Modified src/templates/acc/years/index.tpl from [fd39c3ba37] to [b7ac0ffc9e].

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
{include file="admin/_head.tpl" title="Exercices" current="acc/years"}

<nav class="tabs">
	<aside>
		{linkbutton shape="search" href="!acc/search.php" label="Recherche"}
	</aside>
	<ul>
		<li class="current"><a href="{$self_url}">Exercices</a></li>
		{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
		<li><a href="{$admin_url}acc/years/new.php">Nouvel exercice</a></li>
		{/if}
		<li><a href="{$admin_url}acc/reports/projects.php">Projets <em>(compta analytique)</em></a></li>
	</ul>
</nav>

{if $_GET.msg == 'OPEN'}
<p class="block error">
	Il n'existe aucun exercice ouvert.
	{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
		Merci d'en <a href="{$admin_url}acc/years/new.php">créer un nouveau</a> pour pouvoir saisir des écritures.
	{/if}
</p>
{/if}

{if $_GET.msg == 'UPDATE_FEES'}
<p class="block error">








|









|







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
{include file="admin/_head.tpl" title="Exercices" current="acc/years"}

<nav class="tabs">
	<aside>
		{linkbutton shape="search" href="!acc/search.php" label="Recherche"}
	</aside>
	<ul>
		<li class="current"><a href="{$self_url}">Exercices</a></li>
		{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
		<li><a href="{$admin_url}acc/years/new.php">Nouvel exercice</a></li>
		{/if}
		<li><a href="{$admin_url}acc/reports/projects.php">Projets <em>(compta analytique)</em></a></li>
	</ul>
</nav>

{if $_GET.msg == 'OPEN'}
<p class="block error">
	Il n'existe aucun exercice ouvert.
	{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
		Merci d'en <a href="{$admin_url}acc/years/new.php">créer un nouveau</a> pour pouvoir saisir des écritures.
	{/if}
</p>
{/if}

{if $_GET.msg == 'UPDATE_FEES'}
<p class="block error">
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
					| <a href="{$admin_url}acc/reports/statement.php?year={$year.id}">Compte de résultat</a>
					| <a href="{$admin_url}acc/reports/balance_sheet.php?year={$year.id}">Bilan</a>
				</td>
			</tr>
			<tr>
				<td><em>{if $year.closed}Clôturé{else}En cours{/if}</em></td>
				<td>
				{if $session->canAccess('compta', Membres::DROIT_ADMIN)}
					{linkbutton label="Export CSV" shape="export" href="import.php?id=%d&export=csv"|args:$year.id}
					{linkbutton label="Export tableur" shape="export" href="import.php?id=%d&export=ods"|args:$year.id}
					{if !$year.closed}
						{linkbutton label="Import" shape="upload" href="import.php?id=%d"|args:$year.id}
						{linkbutton label="Balance d'ouverture" shape="reset" href="balance.php?id=%d"|args:$year.id}
						{linkbutton label="Modifier" shape="edit" href="edit.php?id=%d"|args:$year.id}
						{linkbutton label="Clôturer" shape="lock" href="close.php?id=%d"|args:$year.id}







|







60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
					| <a href="{$admin_url}acc/reports/statement.php?year={$year.id}">Compte de résultat</a>
					| <a href="{$admin_url}acc/reports/balance_sheet.php?year={$year.id}">Bilan</a>
				</td>
			</tr>
			<tr>
				<td><em>{if $year.closed}Clôturé{else}En cours{/if}</em></td>
				<td>
				{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
					{linkbutton label="Export CSV" shape="export" href="import.php?id=%d&export=csv"|args:$year.id}
					{linkbutton label="Export tableur" shape="export" href="import.php?id=%d&export=ods"|args:$year.id}
					{if !$year.closed}
						{linkbutton label="Import" shape="upload" href="import.php?id=%d"|args:$year.id}
						{linkbutton label="Balance d'ouverture" shape="reset" href="balance.php?id=%d"|args:$year.id}
						{linkbutton label="Modifier" shape="edit" href="edit.php?id=%d"|args:$year.id}
						{linkbutton label="Clôturer" shape="lock" href="close.php?id=%d"|args:$year.id}

Modified src/templates/admin/_head.tpl from [b134b1fcd2] to [c710e6cf26].

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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
    <meta charset="utf-8" />
    <title>{$title}</title>
    <link rel="icon" type="image/png" href="{$admin_url}static/icon.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=device-dpi" />
    <link rel="stylesheet" type="text/css" href="{$admin_url}static/admin.css?{$version_hash}" media="all" />
    <script type="text/javascript" src="{$admin_url}static/scripts/global.js?{$version_hash}"></script>
    {if isset($custom_js)}
        {foreach from=$custom_js item="js"}
            <script type="text/javascript" src="{$admin_url}static/scripts/{$js}?{$version_hash}"></script>
        {/foreach}
    {/if}
    {if isset($custom_css)}
        {foreach from=$custom_css item="css"}
            <link rel="stylesheet" type="text/css" href="{$admin_url}static/{$css}?{$version_hash}" media="all" />
        {/foreach}
    {/if}
    {if isset($plugin_css)}
        {foreach from=$plugin_css item="css"}
            <link rel="stylesheet" type="text/css" href="{plugin_url file=$css}?{$version_hash}" />
        {/foreach}
    {/if}
    {if isset($plugin_js)}
        {foreach from=$plugin_js item="js"}
            <script type="text/javascript" src="{plugin_url file=$js}?{$version_hash}"></script>
        {/foreach}
    {/if}
    <link rel="stylesheet" type="text/css" href="{$admin_url}static/print.css?{$version_hash}" media="print" />
    <link rel="stylesheet" type="text/css" href="{$admin_url}static/handheld.css?{$version_hash}" media="handheld,screen and (max-width:981px)" />
    {if isset($config)}
        {custom_colors config=$config}
    {/if}
</head>

<body{if !empty($body_id)} id="{$body_id}"{/if}>

{if empty($is_popup)}
<header class="header">
    <nav class="menu">
    <ul>
    {if !$is_logged}
        <li><a href="{$www_url}">&larr; Retour au site</a></li>
        <li><a href="{$admin_url}">Connexion</a>
            <ul>

|













|
|



















|

|







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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr"{if array_key_exists('_dialog', $_GET)} class="dialog"{/if}>
<head>
    <meta charset="utf-8" />
    <title>{$title}</title>
    <link rel="icon" type="image/png" href="{$admin_url}static/icon.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=device-dpi" />
    <link rel="stylesheet" type="text/css" href="{$admin_url}static/admin.css?{$version_hash}" media="all" />
    <script type="text/javascript" src="{$admin_url}static/scripts/global.js?{$version_hash}"></script>
    {if isset($custom_js)}
        {foreach from=$custom_js item="js"}
            <script type="text/javascript" src="{$admin_url}static/scripts/{$js}?{$version_hash}"></script>
        {/foreach}
    {/if}
    {if isset($custom_css)}
        {foreach from=$custom_css item="css_url"}
            <link rel="stylesheet" type="text/css" href="{$css_url|local_url:"!static/styles/"}?{$version_hash}" media="all" />
        {/foreach}
    {/if}
    {if isset($plugin_css)}
        {foreach from=$plugin_css item="css"}
            <link rel="stylesheet" type="text/css" href="{plugin_url file=$css}?{$version_hash}" />
        {/foreach}
    {/if}
    {if isset($plugin_js)}
        {foreach from=$plugin_js item="js"}
            <script type="text/javascript" src="{plugin_url file=$js}?{$version_hash}"></script>
        {/foreach}
    {/if}
    <link rel="stylesheet" type="text/css" href="{$admin_url}static/print.css?{$version_hash}" media="print" />
    <link rel="stylesheet" type="text/css" href="{$admin_url}static/handheld.css?{$version_hash}" media="handheld,screen and (max-width:981px)" />
    {if isset($config)}
        {custom_colors config=$config}
    {/if}
</head>

<body{if isset($transparent)} class="transparent"{/if}>

{if !array_key_exists('_dialog', $_GET) && !isset($transparent)}
<header class="header">
    <nav class="menu">
    <ul>
    {if !$is_logged}
        <li><a href="{$www_url}">&larr; Retour au site</a></li>
        <li><a href="{$admin_url}">Connexion</a>
            <ul>
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
                <ul>
                {foreach from=$plugins_menu key="plugin_id" item="name"}
                    <li class="plugins {if $current == sprintf("plugin_%s", $plugin_id)} current{/if}"><a href="{plugin_url id=$plugin_id}">{$name}</a></li>
                {/foreach}
                </ul>
            {/if}
        </li>
        {if $session->canAccess('membres', Membres::DROIT_ACCES)}
            <li class="member list{if $current == 'membres'} current{elseif $current_parent == 'membres'} current_parent{/if}"><a href="{$admin_url}membres/"><b class="icn">👪</b><i> Membres</i></a>
            <ul>
            {if $session->canAccess('membres', Membres::DROIT_ECRITURE)}
                <li class="member new{if $current == 'membres/ajouter'} current{/if}"><a href="{$admin_url}membres/ajouter.php">Ajouter</a></li>
            {/if}
                <li class="{if $current == 'membres/services'} current{/if}"><a href="{$admin_url}services/">Activités &amp; cotisations</a></li>
            {if $session->canAccess('membres', Membres::DROIT_ECRITURE)}
                <li class="member message{if $current == 'membres/message'} current{/if}"><a href="{$admin_url}membres/message_collectif.php">Message collectif</a></li>
            {/if}
            </ul>
            </li>
        {/if}
        {if $session->canAccess('compta', Membres::DROIT_ACCES)}
            <li class="{if $current == 'acc'} current{elseif $current_parent == 'acc'} current_parent{/if}"><a href="{$admin_url}acc/"><b>€</b><i> Comptabilité</i></a>
            <ul>
            {if $session->canAccess('compta', Membres::DROIT_ECRITURE)}
                <li class="{if $current == 'acc/new'} current{/if}"><a href="{$admin_url}acc/transactions/new.php">Saisie</a></li>
            {/if}
                <li class="{if $current == 'acc/accounts'} current{/if}"><a href="{$admin_url}acc/accounts/">Comptes</a></li>
                <li class="{if $current == 'acc/simple'} current{/if}"><a href="{$admin_url}acc/accounts/simple.php">Suivi des écritures</a></li>
                <li class="{if $current == 'acc/years'} current{/if}"><a href="{$admin_url}acc/years/">Exercices &amp; rapports</a></li>
            {if $session->canAccess('compta', Membres::DROIT_ECRITURE)}
                <li class="{if $current == 'acc/charts'} current{/if}"><a href="{$admin_url}acc/charts/">Plans comptables</a></li>
            {/if}
            </ul>
            </li>
        {/if}

        {if $session->canAccess('wiki', Membres::DROIT_ACCES)}
            <li class="wiki{if $current == 'wiki'} current{elseif $current_parent == 'wiki'} current_parent{/if}"><a href="{$admin_url}wiki/"><b class="icn"></b><i> Wiki</i></a>
            <ul>

                <li class="wiki list{if $current == 'wiki/recent'} current{/if}"><a href="{$admin_url}wiki/recent.php">Dernières modifications</a>

                <li class="wiki search{if $current == 'wiki/chercher'} current{/if}"><a href="{$admin_url}wiki/chercher.php">Recherche</a>
            </ul>
            </li>
        {/if}

        {if $session->canAccess('config', Membres::DROIT_ADMIN)}
            <li class="main config{if $current == 'config'} current{elseif $current_parent == 'config'} current_parent{/if}"><a href="{$admin_url}config/"><b class="icn">☸</b><i> Configuration</i></a>
        {/if}

        <li class="{if $current == 'mes_infos'} current{elseif $current_parent == 'mes_infos'} current_parent{/if}">
            <a href="{$admin_url}mes_infos.php"><b class="icn">👤</b><i> Mes infos personnelles</i></a>
            <ul>
                <li{if $current == 'my_services'}  class="current"{/if}><a href="{$admin_url}my_services.php">Mes activités &amp; cotisations</a></li>
            </ul>
        </li>

        {if !defined('Garradin\LOCAL_LOGIN') || !LOCAL_LOGIN}
        <li class="logout"><a href="{$admin_url}logout.php"><b class="icn">⤝</b><i> Déconnexion</i></a></li>
        {/if}
    {/if}
    </ul>
    </nav>

    <h1>{$title}</h1>
</header>
{/if}

<main>







|


|



|





|


|





|





>
|
|
|
>
|
>
|
<


>
|


>






>

|










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
                <ul>
                {foreach from=$plugins_menu key="plugin_id" item="name"}
                    <li class="plugins {if $current == sprintf("plugin_%s", $plugin_id)} current{/if}"><a href="{plugin_url id=$plugin_id}">{$name}</a></li>
                {/foreach}
                </ul>
            {/if}
        </li>
        {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_READ)}
            <li class="member list{if $current == 'membres'} current{elseif $current_parent == 'membres'} current_parent{/if}"><a href="{$admin_url}membres/"><b class="icn">👪</b><i> Membres</i></a>
            <ul>
            {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)}
                <li class="member new{if $current == 'membres/ajouter'} current{/if}"><a href="{$admin_url}membres/ajouter.php">Ajouter</a></li>
            {/if}
                <li class="{if $current == 'membres/services'} current{/if}"><a href="{$admin_url}services/">Activités &amp; cotisations</a></li>
            {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)}
                <li class="member message{if $current == 'membres/message'} current{/if}"><a href="{$admin_url}membres/message_collectif.php">Message collectif</a></li>
            {/if}
            </ul>
            </li>
        {/if}
        {if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ)}
            <li class="{if $current == 'acc'} current{elseif $current_parent == 'acc'} current_parent{/if}"><a href="{$admin_url}acc/"><b>€</b><i> Comptabilité</i></a>
            <ul>
            {if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_WRITE)}
                <li class="{if $current == 'acc/new'} current{/if}"><a href="{$admin_url}acc/transactions/new.php">Saisie</a></li>
            {/if}
                <li class="{if $current == 'acc/accounts'} current{/if}"><a href="{$admin_url}acc/accounts/">Comptes</a></li>
                <li class="{if $current == 'acc/simple'} current{/if}"><a href="{$admin_url}acc/accounts/simple.php">Suivi des écritures</a></li>
                <li class="{if $current == 'acc/years'} current{/if}"><a href="{$admin_url}acc/years/">Exercices &amp; rapports</a></li>
            {if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_WRITE)}
                <li class="{if $current == 'acc/charts'} current{/if}"><a href="{$admin_url}acc/charts/">Plans comptables</a></li>
            {/if}
            </ul>
            </li>
        {/if}

        {if $session->canAccess($session::SECTION_DOCUMENTS, $session::ACCESS_READ)}
            <li class="{if $current == 'docs'} current{elseif $current_parent == 'docs'} current_parent{/if}"><a href="{$admin_url}docs/"><b class="icn">🗀</b><i> Documents</i></a>
            </li>
        {/if}

        {if $session->canAccess($session::SECTION_WEB, $session::ACCESS_READ)}
            <li class="{if $current == 'web'} current{elseif $current_parent == 'web'} current_parent{/if}"><a href="{$admin_url}web/"><b class="icn">🖻</b><i> Site web</i></a>

            </li>
        {/if}

        {if $session->canAccess($session::SECTION_CONFIG, $session::ACCESS_ADMIN)}
            <li class="main config{if $current == 'config'} current{elseif $current_parent == 'config'} current_parent{/if}"><a href="{$admin_url}config/"><b class="icn">☸</b><i> Configuration</i></a>
        {/if}

        <li class="{if $current == 'mes_infos'} current{elseif $current_parent == 'mes_infos'} current_parent{/if}">
            <a href="{$admin_url}mes_infos.php"><b class="icn">👤</b><i> Mes infos personnelles</i></a>
            <ul>
                <li{if $current == 'my_services'}  class="current"{/if}><a href="{$admin_url}my_services.php">Mes activités &amp; cotisations</a></li>
            </ul>
        </li>

        {if !defined('Garradin\LOCAL_LOGIN') || !LOCAL_LOGIN}
            <li class="logout"><a href="{$admin_url}logout.php"><b class="icn">⤝</b><i> Déconnexion</i></a></li>
        {/if}
    {/if}
    </ul>
    </nav>

    <h1>{$title}</h1>
</header>
{/if}

<main>

Modified src/templates/admin/config/_menu.tpl from [1062a04378] to [91dfe799a4].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<nav class="tabs">
	<ul>
		<li{if $current == 'index'} class="current"{/if}><a href="{$admin_url}config/">Général</a></li>
		<li{if $current == 'categories'} class="current"{/if}><a href="{$admin_url}config/categories/">Catégories de membres</a></li>
		<li{if $current == 'fiches_membres'} class="current"{/if}><a href="{$admin_url}config/membres.php">Fiche des membres</a></li>
		<li{if $current == 'site'} class="current"{/if}><a href="{$admin_url}config/site.php">Site public</a></li>
		<li{if $current == 'donnees'} class="current"{/if}><a href="{$admin_url}config/donnees/">Sauvegardes</a></li>
		<li{if $current == 'plugins'} class="current"{/if}><a href="{$admin_url}config/plugins.php">Extensions</a></li>
		<li{if $current == 'advanced'} class="current"{/if}><a href="{$admin_url}config/advanced/">Fonctions avancées</a></li>
	</ul>

	{if $current == 'advanced'}
	<ul class="sub">
		<li{if !$sub_current} class="current"{/if}><a href="{$admin_url}config/advanced/">Fonctions avancées</a></li>





|
<







1
2
3
4
5
6

7
8
9
10
11
12
13
<nav class="tabs">
	<ul>
		<li{if $current == 'index'} class="current"{/if}><a href="{$admin_url}config/">Général</a></li>
		<li{if $current == 'categories'} class="current"{/if}><a href="{$admin_url}config/categories/">Catégories de membres</a></li>
		<li{if $current == 'fiches_membres'} class="current"{/if}><a href="{$admin_url}config/membres.php">Fiche des membres</a></li>
		<li{if $current == 'backup'} class="current"{/if}><a href="{$admin_url}config/backup/">Sauvegardes</a></li>

		<li{if $current == 'plugins'} class="current"{/if}><a href="{$admin_url}config/plugins.php">Extensions</a></li>
		<li{if $current == 'advanced'} class="current"{/if}><a href="{$admin_url}config/advanced/">Fonctions avancées</a></li>
	</ul>

	{if $current == 'advanced'}
	<ul class="sub">
		<li{if !$sub_current} class="current"{/if}><a href="{$admin_url}config/advanced/">Fonctions avancées</a></li>

Modified src/templates/admin/config/advanced/errors.tpl from [db5622e3ef] to [39b2ff6b31].

1
2
3
4
5
6
7
8
{include file="admin/_head.tpl" title="Journaux" current="config" custom_css=["styles/config.css"]}

{include file="admin/config/_menu.tpl" current="advanced" sub_current="errors"}

{if isset($reports) && isset($id)}
	<section class="error">
		{foreach from=$main.errors item="error"}
			<h2 class="ruler">{$error.type}: {$error.message} [Code: {$error.errorCode}]</h2>
|







1
2
3
4
5
6
7
8
{include file="admin/_head.tpl" title="Journaux" current="config" custom_css=["config.css"]}

{include file="admin/config/_menu.tpl" current="advanced" sub_current="errors"}

{if isset($reports) && isset($id)}
	<section class="error">
		{foreach from=$main.errors item="error"}
			<h2 class="ruler">{$error.type}: {$error.message} [Code: {$error.errorCode}]</h2>
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
				</article>
				{/foreach}
			{/if}
		{/foreach}

		{foreach from=$reports item=report}
		<article class="event">
			<h2 class="ruler">Occurence du {$report.context.date|date_fr}</h2>
			<table class="list">
				{foreach from=$report.context key="k" item="v"}
				<tr>
					<th>{$k}</th>
					<td>{if $k == 'date'}{$v|date_fr}{else}{$v}{/if}</td>
				</tr>
				{/foreach}
			</table>
		</article>
		{/foreach}
	</section>
{elseif isset($errors)}







|




|







31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
				</article>
				{/foreach}
			{/if}
		{/foreach}

		{foreach from=$reports item=report}
		<article class="event">
			<h2 class="ruler">Occurence du {$report.context.date|date}</h2>
			<table class="list">
				{foreach from=$report.context key="k" item="v"}
				<tr>
					<th>{$k}</th>
					<td>{if $k == 'date'}{$v|date}{else}{$v}{/if}</td>
				</tr>
				{/foreach}
			</table>
		</article>
		{/foreach}
	</section>
{elseif isset($errors)}
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
				<tr>
					<th><a href="?type=errors&id={$ref}">{$ref}</a></th>
					<td>
						{$error.message}<br />
						<tt>{$error.source}</tt>
					</td>
					<td>{$error.count}</td>
					<td>{$error.last_seen|date_fr}</td>
					<td class="actions">
						{linkbutton shape="menu" label="Voir les détails" href="%s?type=errors&id=%s"|args:$self_url_no_qs,$ref}
					</td>
				</tr>
				{/foreach}
			</tbody>
		</table>
	{/if}
{/if}

{include file="admin/_foot.tpl"}







|











71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
				<tr>
					<th><a href="?type=errors&id={$ref}">{$ref}</a></th>
					<td>
						{$error.message}<br />
						<tt>{$error.source}</tt>
					</td>
					<td>{$error.count}</td>
					<td>{$error.last_seen|date}</td>
					<td class="actions">
						{linkbutton shape="menu" label="Voir les détails" href="%s?type=errors&id=%s"|args:$self_url_no_qs,$ref}
					</td>
				</tr>
				{/foreach}
			</tbody>
		</table>
	{/if}
{/if}

{include file="admin/_foot.tpl"}

Modified src/templates/admin/config/advanced/index.tpl from [96b57f6bc4] to [fc7d4690cb].

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
{include file="admin/_head.tpl" title="Fonctions avancées" current="config" custom_css=["styles/config.css"]}

{include file="admin/config/_menu.tpl" current="advanced" sub_current=null}

<p class="help block">
	Attention, les fonctions avancées peuvent permettre de supprimer des données ou rendre votre instance inutilisable&nbsp;!
</p>

{form_errors}

{if $_GET.msg == 'RESET'}
	<p class="block confirm">
		La remise à zéro a été effectuée. Une sauvegarde a également été créée.</p>
	</p>
{else if $_GET.msg == 'REOPEN'}
	<p class="block confirm">
		L'exercice sélectionné a été réouvert.
	</p>
{/if}

{if count($closed_years)}
<form method="post" action="{$self_url_no_qs}">


<fieldset>
	<legend>Réouvrir un exercice clôturé</legend>
	<p class="help">
		À utiliser si vous avez clôturé un exercice par erreur. Attention, en comptabilité cette action est normalement exceptionnelle.
	</p>
	<p class="alert block">
		L'exercice sera réouvert, mais une écriture sera ajoutée au journal général indiquant que celui-ci a été réouvert après clôture. Cette écriture ne peut pas être supprimée.
	</p>
	<dl>
		{input type="select" options=$closed_years label="Exercicer à réouvrir" name="year"}
	</dl>
	<p>
		{csrf_field key="reopen_year"}
		{button type="submit" name="reopen_ok" label="Réouvrir l'exercice sélectionné" shape="reset"}
	</p>
</fieldset>









</form>





















{/if}



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

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

<fieldset>
	<legend>Remise à zéro</legend>
|



















<

>

















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







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
{include file="admin/_head.tpl" title="Fonctions avancées" current="config" custom_css=["config.css"]}

{include file="admin/config/_menu.tpl" current="advanced" sub_current=null}

<p class="help block">
	Attention, les fonctions avancées peuvent permettre de supprimer des données ou rendre votre instance inutilisable&nbsp;!
</p>

{form_errors}

{if $_GET.msg == 'RESET'}
	<p class="block confirm">
		La remise à zéro a été effectuée. Une sauvegarde a également été créée.</p>
	</p>
{else if $_GET.msg == 'REOPEN'}
	<p class="block confirm">
		L'exercice sélectionné a été réouvert.
	</p>
{/if}


<form method="post" action="{$self_url_no_qs}">
{if count($closed_years)}

<fieldset>
	<legend>Réouvrir un exercice clôturé</legend>
	<p class="help">
		À utiliser si vous avez clôturé un exercice par erreur. Attention, en comptabilité cette action est normalement exceptionnelle.
	</p>
	<p class="alert block">
		L'exercice sera réouvert, mais une écriture sera ajoutée au journal général indiquant que celui-ci a été réouvert après clôture. Cette écriture ne peut pas être supprimée.
	</p>
	<dl>
		{input type="select" options=$closed_years label="Exercicer à réouvrir" name="year"}
	</dl>
	<p>
		{csrf_field key="reopen_year"}
		{button type="submit" name="reopen_ok" label="Réouvrir l'exercice sélectionné" shape="reset"}
	</p>
</fieldset>
{/if}

{if ENABLE_TECH_DETAILS && $storage_backend != 'SQLite'}
	<h2 class="ruler">Stockage des fichiers</h2>
	{if !$quota_used}
	<fieldset>
		<legend>Migration de stockage de fichiers</legend>
		<p class="alert block">
			Les fichiers seront <strong>supprimés</strong> de la base de données après avoir été recopiés vers '{$storage_backend}'.
		</p>
		<p class="error block">
			Sauvegarde fortement recommandée avant de procéder à cette opération !
		</p>
		<p class="help">Cette opération peut prendre quelques minutes.</p>
		<p>
			{csrf_field key="migrate_backend"}
			{button type="submit" name="migrate_backend_ok" label="Copier tous les fichiers vers %s et les supprimer de la base de données"|args:$storage_backend shape="right"}
		</p>
	</fieldset>
	{else}
	<fieldset>
		<legend>Recopier les fichiers dans la base de données</legend>
		<p class="alert block">
			Les fichiers ne seront pas effacés de {$storage_backend} mais simplement recopiés dans la base de données.
		</p>
		<p class="help">Cette opération peut prendre quelques minutes. Elle est utile pour migrer entre deux systèmes de fichiers différents.</p>
		<p>
			{csrf_field key="migrate_back"}
			{button type="submit" name="migrate_back_ok" label="Copier tous les fichiers de %s vers la base de données"|args:$storage_backend shape="right"}
		</p>
	</fieldset>
	{/if}
{/if}
</form>

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

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

<fieldset>
	<legend>Remise à zéro</legend>

Modified src/templates/admin/config/advanced/sql.tpl from [a5a49b987e] to [61d73a5581].

1
2
3
4
5
6
7
8
{include file="admin/_head.tpl" title="SQL" current="config" custom_css=["styles/config.css"]}

{include file="admin/config/_menu.tpl" current="advanced" sub_current="sql"}

{form_errors}

{if $query}
	<h2 class="ruler">Requête SQL</h2>
|







1
2
3
4
5
6
7
8
{include file="admin/_head.tpl" title="SQL" current="config" custom_css=["config.css"]}

{include file="admin/config/_menu.tpl" current="advanced" sub_current="sql"}

{form_errors}

{if $query}
	<h2 class="ruler">Requête SQL</h2>

Added src/templates/admin/config/backup/_menu.tpl version [6843e6c837].















>
>
>
>
>
>
>
1
2
3
4
5
6
7
<nav class="tabs">
	<ul class="sub">
		<li{if $current == 'index'} class="current"{/if}><a href="{$admin_url}config/backup/">Informations</a></li>
		<li{if $current == 'save'} class="current"{/if}><a href="{$admin_url}config/backup/save.php">Sauvegarder</a></li>
		<li{if $current == 'restore'} class="current"{/if}><a href="{$admin_url}config/backup/restore.php">Restaurer</a></li>
	</ul>
</nav>

Added src/templates/admin/config/backup/automatique.tpl version [f0d729ff37].















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title="Sauvegarde et restauration" current="config"}

{include file="admin/config/_menu.tpl" current="donnees"}

{include file="admin/config/donnees/_menu.tpl" current="automatique"}

{form_errors}

{if $ok == 'config'}
	<p class="block confirm">La configuration a bien été enregistrée.</p>
{/if}

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

<fieldset>
	<legend>Configuration de la sauvegarde automatique</legend>
	<p class="help">
		En activant cette option une sauvegarde sera automatiquement créée à chaque intervalle donné.
		Par exemple en activant une sauvegarde hebdomadaire, une copie des données sera réalisée
		une fois par semaine, sauf si aucune modification n'a été effectuée sur les données
		ou que personne ne s'est connecté.
	</p>
	<dl>
		<dt><label for="f_frequency">Intervalle de sauvegarde</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
		<dd>
			<select name="frequence_sauvegardes" required="required" id="f_frequency">
				<option value="0"{form_field name=frequence_sauvegardes data=$config selected=0}>Aucun — les sauvegardes automatiques sont désactivées</option>
				<option value="1"{form_field name=frequence_sauvegardes data=$config selected=1}>Quotidien, tous les jours</option>
				<option value="7"{form_field name=frequence_sauvegardes data=$config selected=7}>Hebdomadaire, tous les 7 jours</option>
				<option value="15"{form_field name=frequence_sauvegardes data=$config selected=15}>Bimensuel, tous les 15 jours</option>
				<option value="30"{form_field name=frequence_sauvegardes data=$config selected=30}>Mensuel</option>
				<option value="90"{form_field name=frequence_sauvegardes data=$config selected=90}>Trimestriel</option>
				<option value="365{form_field name=frequence_sauvegardes data=$config selected=365}">Annuel</option>
			</select>
		</dd>
		<dt><label for="f_max_backups">Nombre de sauvegardes conservées</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
		<dd class="help">
			Par exemple avec l'intervalle mensuel, en indiquant de conserver 12 sauvegardes,
			vous pourrez garder un an d'historique de sauvegardes.
		</dd>
		<dd class="help">
			<strong>Attention :</strong> si vous choisissez un nombre important et un intervalle réduit,
			l'espace disque occupé par vos sauvegardes va rapidement augmenter.
		</dd>
		<dd><input type="number" name="nombre_sauvegardes" value="{form_field name=nombre_sauvegardes data=$config}" if="f_max_backups" min="1" max="90" required="required" /></dd>
	</dl>
	<p>
		{csrf_field key="backup_config"}
		<input type="submit" name="config" value="Enregistrer &rarr;" />
	</p>
</fieldset>

</form>

{include file="admin/_foot.tpl"}

Added src/templates/admin/config/backup/index.tpl version [d594e3f550].















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title="Sauvegardes" current="config"}

{include file="admin/config/_menu.tpl" current="backup"}

{include file="admin/config/backup/_menu.tpl" current="index"}

<fieldset>
	<legend>Politique de sauvegardes</legend>
	{if ENABLE_AUTOMATIC_BACKUPS && !$config.frequence_sauvegardes}
	<p class="help block">
		Les <a href="save.php">sauvegardes automatiques</a> sont désactivées. Il est recommandé de les activer pour pouvoir revenir en arrière en cas de problème majeur. Attention, cela ne dispense pas de réaliser des sauvegardes régulières sur votre ordinateur.
	</p>
	{/if}

	<p class="help">
		En cas de problème sur le serveur (plantage, dysfonctionnement du disque dur, incendie, etc.) vous pourriez perdre vos données.<br />
		<strong>Il est donc recommandé de réaliser régulièrement des sauvegardes et de les conserver sur votre ordinateur personnel&nbsp;!</strong><br /><br />
		Pour cela il convient de se rendre dans la section <a href="save.php">Sauvegarder</a> et de cliquer sur le bouton <em>«&nbsp;Télécharger une copie de la base de données sur mon ordinateur&nbsp;»</em>.
	</p>
</fieldset>

<fieldset>
	<legend>Import et export</legend>
	<p class="help">
		Il est possible d'exporter et importer des données afin d'interagir avec des logiciels tiers. Cette liste regroupe les imports et exports les plus courants. Il est également possible d'exporter la plupart des listes qui comportent un bouton "Exporter".
	</p>
	<dl>
		<dt><strong>Membres</strong></dt>
		<dd><a href="{$admin_url}membres/import.php">Import de la liste des membres</a></dd>
		<dd><a href="{$admin_url}membres/import.php?export=ods">Export de la liste des membres au format tableur LibreOffice Calc / Excel</a></dd>
		<dd><a href="{$admin_url}membres/import.php?export=csv">Export de la liste des membres au format CSV</a></dd>
		<dt><strong>Comptabilité</strong> (pour l'exercice courant)</dt>
		<dd><a href="{$admin_url}acc/years/import.php">Import des données comptables</a></dd>
		<dd><a href="{$admin_url}acc/years/import.php?export=ods">Export des données comptables au format tableur LibreOffice Calc / Excel</a></dd>
		<dd><a href="{$admin_url}acc/years/import.php?export=csv">Export des données comptables au format CSV</a></dd>
	</dl>
</fieldset>

{include file="admin/_foot.tpl"}

Added src/templates/admin/config/backup/restore.tpl version [79ea96c80e].























































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title="Restaurer" current="config"}

{include file="admin/config/_menu.tpl" current="backup"}

{include file="admin/config/backup/_menu.tpl" current="restore"}

{form_errors}

{if $code == Sauvegarde::INTEGRITY_FAIL && ALLOW_MODIFIED_IMPORT}
	<p class="block alert">Pour passer outre, renvoyez le fichier en cochant la case «&nbsp;Ignorer les erreurs&nbsp;».
	Attention, si vous avez effectué des modifications dans la base de données, cela peut créer des bugs&nbsp;!</p>
{/if}

{if $ok}
	<p class="block confirm">
		{if $ok == 'restore'}La restauration a bien été effectuée.
			{if $ok_code & Sauvegarde::NOT_AN_ADMIN}
			</p>
			<p class="block alert">
				<strong>Vous n'êtes pas administrateur dans cette sauvegarde.</strong> Garradin a donné les droits d'administration à toutes les catégories afin d'empêcher de ne plus pouvoir se connecter.
				Merci de corriger les droits des catégories maintenant.
			{/if}
		{elseif $ok == 'remove'}La sauvegarde a été supprimée.
		{/if}
	</p>
{/if}


<form method="post" action="{$self_url_no_qs}" enctype="multipart/form-data">

<fieldset>
	<legend><label for="f_file">Restaurer depuis un fichier de sauvegarde</label></legend>
	<p class="block alert">
		Attention, l'intégralité des données courantes seront effacées et remplacées par celles
		contenues dans le fichier fourni.
	</p>
	<p class="help">
		Une sauvegarde des données courantes sera effectuée avant le remplacement,
		en cas de besoin d'annuler cette restauration.
	</p>
	<dl>
		{input type="file" name="file" required=true}
	</dl>
	<p class="submit">
		{csrf_field key="backup_restore"}
		{button type="submit" name="restore_file" label="Restaurer depuis le fichier sélectionné" shape="upload" class="main"}
	</p>
	{if $code && ($code == Sauvegarde::INTEGRITY_FAIL && ALLOW_MODIFIED_IMPORT)}
	<p>
		{input type="checkbox" name="force_import" value="1" label="Ignorer les erreurs, je sais ce que je fait"}
	</p>
	{/if}
</fieldset>

</form>

{if ENABLE_AUTOMATIC_BACKUPS}

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

<fieldset>
	<legend>Sauvegardes disponibles</legend>
	{if empty($list)}
		<p class="help">Aucune copie de sauvegarde disponible.</p>
	{else}
		<table class="list">
			<tbody>
				<thead>
					<tr>
						<td></td>
						<th>Nom</th>
						<td>Taille</td>
						<td>Date</td>
						<td>Version</td>
						<td></td>
					</tr>
				</thead>
			{foreach from=$list item="backup"}
				<tr>
					<td class="check">{input type="radio" name="selected" value=$backup.filename}</td>
					<th><label for="f_selected_{$backup.filename}">{$backup.name}</label></th>
					<td>{$backup.size|size_in_bytes}</td>
					<td>{$backup.date|date_short:true}</td>
					<td>{$backup.version}{if !$backup.can_restore} — <span class="alert">Version trop ancienne pour pouvoir être restaurée</span>{/if}</td>
					<td class="actions">
						{linkbutton href="?download=%s"|args:$backup.filename label="Télécharger" shape="download"}
					</td>
				</tr>
			{/foreach}
			</tbody>
		</table>
		<p class="alert block">
			Attention, en cas de restauration, l'intégralité des données courantes seront effacées et remplacées par celles contenues dans la sauvegarde sélectionnée.
		</p>
		<p class="submit">
			{csrf_field key="backup_manage"}
			{button type="submit" name="restore" label="Restaurer cette sauvegarde" shape="reset" class="main"}
			{button type="submit" name="remove" label="Supprimer cette sauvegarde" shape="delete"}
		</p>
	{/if}
</fieldset>

</form>

{/if}

{include file="admin/_foot.tpl"}

Added src/templates/admin/config/backup/save.tpl version [6d87a6ea39].





















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title="Sauvegarder" current="config"}

{include file="admin/config/_menu.tpl" current="backup"}

{include file="admin/config/backup/_menu.tpl" current="save"}

{form_errors}

{if $ok}
	<p class="block confirm">
		{if $ok == 'create'}Une nouvelle sauvegarde a été créée.
		{elseif $ok == 'config'}La configuration a bien été enregistrée.
		{/if}
	</p>
{/if}

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

<fieldset>
	<legend>Téléchargement d'une sauvegarde</legend>
	<p class="help">
		Info : la base de données fait actuellement {$db_size|size_in_bytes}.
		{if FILE_STORAGE_BACKEND == 'SQLite'} (Dont {$files_size|size_in_bytes} pour les documents.){/if}
	</p>
	<p class="submit">
		{csrf_field key="backup_download"}
		{button type="submit" name="download" label="Télécharger une copie de la base de données sur mon ordinateur" shape="download" class="main"}
	</p>
</fieldset>

<fieldset>
	<legend>Téléchargement des fichiers</legend>
	<p class="help">
		Les documents font {$files_size|size_in_bytes}.
	</p>
	{if $files_size > 0}
	<p class="submit">
		{csrf_field key="files_download"}
		{button type="submit" name="download_files" label="Télécharger une archive ZIP des documents sur mon ordinateur" shape="download" class="main"}
	</p>
	{/if}
</fieldset>

</form>

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

<fieldset>
	<legend>Sauvegarde manuelle de la base de données</legend>
	<p class="help">
		Cette sauvegarde sera enregistrée sur le serveur et pourra être restaurée plus tard.
	</p>
	<p class="submit">
		{csrf_field key="backup_create"}
		{button type="submit" name="create" label="Créer une nouvelle sauvegarde" shape="right" class="main"}
	</p>
</fieldset>

</form>

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

<fieldset>
	<legend>Configuration de la sauvegarde automatique</legend>
	<p class="help">
		En activant cette option une sauvegarde sera automatiquement créée à chaque intervalle donné.
		Par exemple en activant une sauvegarde hebdomadaire, une copie des données sera réalisée
		une fois par semaine, sauf si aucune modification n'a été effectuée sur les données
		ou que personne ne s'est connecté.
	</p>
	<p class="alert block">
		Attention, la sauvegarde automatique permet uniquement de revenir à un état antérieur, mais ne prévient pas de la perte des données&nbsp;! Pour cela, il est recommandé de faire des sauvegardes manuelles en téléchargeant une copie des données sur votre ordinateur.
	</p>
	<dl>
		<dt><label for="f_frequency">Intervalle de sauvegarde</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
		<dd>
			<select name="frequence_sauvegardes" required="required" id="f_frequency">
				<option value="0"{form_field name=frequence_sauvegardes data=$config selected=0}>Aucun — les sauvegardes automatiques sont désactivées</option>
				<option value="1"{form_field name=frequence_sauvegardes data=$config selected=1}>Quotidien, tous les jours</option>
				<option value="7"{form_field name=frequence_sauvegardes data=$config selected=7}>Hebdomadaire, tous les 7 jours</option>
				<option value="15"{form_field name=frequence_sauvegardes data=$config selected=15}>Bimensuel, tous les 15 jours</option>
				<option value="30"{form_field name=frequence_sauvegardes data=$config selected=30}>Mensuel</option>
				<option value="90"{form_field name=frequence_sauvegardes data=$config selected=90}>Trimestriel</option>
				<option value="365{form_field name=frequence_sauvegardes data=$config selected=365}">Annuel</option>
			</select>
		</dd>
		<dt><label for="f_max_backups">Nombre de sauvegardes conservées</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
		<dd class="help">
			Par exemple avec l'intervalle mensuel, en indiquant de conserver 12 sauvegardes,
			vous pourrez garder un an d'historique de sauvegardes.
		</dd>
		<dd class="help">
			<strong>Attention :</strong> si vous choisissez un nombre important et un intervalle réduit,
			l'espace disque occupé par vos sauvegardes va rapidement augmenter.
		</dd>
		<dd><input type="number" name="nombre_sauvegardes" value="{form_field name=nombre_sauvegardes data=$config}" if="f_max_backups" min="1" max="50" required="required" /></dd>
	</dl>
	<p class="submit">
		{csrf_field key="backup_config"}
		{button type="submit" name="config" label="Enregistrer" shape="right" class="main"}
	</p>
</fieldset>

</form>

{include file="admin/_foot.tpl"}

Modified src/templates/admin/config/categories/index.tpl from [b1e9086f4b] to [7b5889b61d].

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
{include file="admin/_head.tpl" title="Catégories de membres" current="config"}

{include file="admin/config/_menu.tpl" current="categories"}

<table class="list">
    <thead>
        <th>Nom</th>
        <td class="num">Membres</td>
        <td>Droits</td>
        <td></td>
    </thead>
    <tbody>
        {foreach from=$liste item="cat"}
            <tr>
                <th>{$cat.nom}</th>
                <td class="num">{$cat.nombre}</td>
                <td class="droits">
                    {format_droits droits=$cat}
                </td>
                <td class="actions">
                    {if $cat.id != $user.id_categorie}
                        {linkbutton shape="delete" label="Supprimer" href="supprimer.php?id=%d"|args:$cat.id}
                    {/if}
                    {linkbutton shape="edit" label="Modifier" href="modifier.php?id=%d"|args:$cat.id}
                    {linkbutton shape="users" label="Liste des membres" href="!membres/?cat=%d"|args:$cat.id}
                </td>
            </tr>
        {/foreach}
    </tbody>
</table>

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

    <fieldset>
        <legend>Ajouter une catégorie</legend>
        <dl>
            <dt><label for="f_nom">Nom</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd><input type="text" name="nom" id="f_nom" value="{form_field name=nom}" required="required" /></dd>
        </dl>
    </fieldset>

    <p class="submit">
        {csrf_field key="new_cat"}
        {button type="submit" name="save" label="Ajouter" shape="right" class="main"}
    </p>


</form>


{include file="admin/_foot.tpl"}





|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|




|
|
|
<
|
|
<

|
|
|
|
>





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
{include file="admin/_head.tpl" title="Catégories de membres" current="config"}

{include file="admin/config/_menu.tpl" current="categories"}

<table class="list">
	<thead>
		<th>Nom</th>
		<td class="num">Membres</td>
		<td>Droits</td>
		<td></td>
	</thead>
	<tbody>
		{foreach from=$list item="cat"}
			<tr>
				<th>{$cat.name}</th>
				<td class="num">{$cat.count}</td>
				<td class="permissions">
					{display_permissions permissions=$cat}
				</td>
				<td class="actions">
					{if $cat.id != $user.id_category}
						{linkbutton shape="delete" label="Supprimer" href="supprimer.php?id=%d"|args:$cat.id}
					{/if}
					{linkbutton shape="edit" label="Modifier" href="modifier.php?id=%d"|args:$cat.id}
					{linkbutton shape="users" label="Liste des membres" href="!membres/?cat=%d"|args:$cat.id}
				</td>
			</tr>
		{/foreach}
	</tbody>
</table>

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

	<fieldset>
		<legend>Ajouter une catégorie</legend>
		<dl>

			{input type="text" name="name" label="Nom" required=true}
		</dl>


		<p class="submit">
			{csrf_field key=$csrf_key}
			{button type="submit" name="save" label="Ajouter" shape="right" class="main"}
		</p>
	</fieldset>

</form>


{include file="admin/_foot.tpl"}

Modified src/templates/admin/config/categories/modifier.tpl from [4bc679901e] to [abe451d3d1].

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
{include file="admin/_head.tpl" title="Modifier une catégorie de membre" current="config"}

{include file="admin/config/_menu.tpl" current="categories"}

{form_errors}

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

    <fieldset>
        <legend>Informations générales</legend>
        <dl>
            <dt><label for="f_nom">Nom</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd><input type="text" name="nom" id="f_nom" value="{form_field data=$cat name=nom}" required="required" /></dd>
            <dt>
                <input type="checkbox" name="cacher" value="1" id="f_cacher" {if $cat.cacher}checked="checked"{/if} />
                <label for="f_cacher">Catégorie cachée</label>
            </dt>
            <dd class="help">
                Si coché cette catégorie ne sera visible qu'aux administrateurs et ne recevra pas
                de messages collectifs ou de rappels.
            </dd>
        </dl>
    </fieldset>

    <fieldset>
        <legend>Droits</legend>
        <dl class="droits">

            <dt><label for="f_droit_connexion_aucun">Les membres de cette catégorie peuvent-ils se connecter ?</label></dt>
            {if $readonly}
                <dd class="help">
                    Il n'est pas possible de désactiver ce droit pour votre propre catégorie.
                </dd>
            {/if}
            <dd>
                <input type="radio" name="droit_connexion" value="{$membres::DROIT_AUCUN}" id="f_droit_connexion_aucun" {if $cat.droit_connexion == $membres::DROIT_AUCUN}checked="checked"{/if} {$readonly} />
                <label for="f_droit_connexion_aucun"><b class="aucun">C</b> Non</label>
            </dd>
            <dd>
                <input type="radio" name="droit_connexion" value="{$membres::DROIT_ACCES}" id="f_droit_connexion_acces" {if $cat.droit_connexion == $membres::DROIT_ACCES}checked="checked"{/if} {$readonly} />
                <label for="f_droit_connexion_acces"><b class="acces">C</b> Oui</label>
            </dd>
        </dl>
        {* TODO pas d'inscription pour le moment
        <dl class="droits">
            <dt><label for="f_droit_inscription_aucun">Les membres de cette catégorie peuvent-ils s'inscrire d'eux-même ?</label></dt>
            <dd>
                <input type="radio" name="droit_inscription" value="{$membres::DROIT_AUCUN}" id="f_droit_inscription_aucun" {if $cat.droit_inscription == $membres::DROIT_AUCUN}checked="checked"{/if} />
                <label for="f_droit_inscription_aucun"><b class="aucun">I</b> Non</label>
            </dd>
            <dd>
                <input type="radio" name="droit_inscription" value="{$membres::DROIT_ACCES}" id="f_droit_inscription_acces" {if $cat.droit_inscription == $membres::DROIT_ACCES}checked="checked"{/if} />
                <label for="f_droit_inscription_acces"><b class="acces">I</b> Oui</label>
            </dd>
        </dl>
        *}
        <dl class="droits">
            <dt><label for="f_droit_membres_aucun">Gestion des membres :</label></dt>
            <dd>
                <input type="radio" name="droit_membres" value="{$membres::DROIT_AUCUN}" id="f_droit_membres_aucun" {if $cat.droit_membres == $membres::DROIT_AUCUN}checked="checked"{/if} />
                <label for="f_droit_membres_aucun"><b class="aucun">M</b> Pas d'accès</label>
            </dd>
            <dd>
                <input type="radio" name="droit_membres" value="{$membres::DROIT_ACCES}" id="f_droit_membres_acces" {if $cat.droit_membres == $membres::DROIT_ACCES}checked="checked"{/if} />
                <label for="f_droit_membres_acces"><b class="acces">M</b> Lecture uniquement <em>(peut voir les informations personnelles de tous les membres, y compris leurs inscriptions à des activités)</em></label>
            </dd>
            <dd>
                <input type="radio" name="droit_membres" value="{$membres::DROIT_ECRITURE}" id="f_droit_membres_ecriture" {if $cat.droit_membres == $membres::DROIT_ECRITURE}checked="checked"{/if} />
                <label for="f_droit_membres_ecriture"><b class="ecriture">M</b> Lecture &amp; écriture <em>(peut ajouter et modifier des membres, mais pas les supprimer ni les changer de catégorie, peut inscrire des membres à des activités)</em></label>
            </dd>
            <dd>
                <input type="radio" name="droit_membres" value="{$membres::DROIT_ADMIN}" id="f_droit_membres_admin" {if $cat.droit_membres == $membres::DROIT_ADMIN}checked="checked"{/if} />
                <label for="f_droit_membres_admin"><b class="admin">M</b> Administration <em>(peut tout faire)</em></label>
            </dd>
        </dl>
        <dl class="droits">
            <dt><label for="f_droit_compta_aucun">Comptabilité :</label></dt>
            <dd>
                <input type="radio" name="droit_compta" value="{$membres::DROIT_AUCUN}" id="f_droit_compta_aucun" {if $cat.droit_compta == $membres::DROIT_AUCUN}checked="checked"{/if} />
                <label for="f_droit_compta_aucun"><b class="aucun">€</b> Pas d'accès</label>
            </dd>
            <dd>
                <input type="radio" name="droit_compta" value="{$membres::DROIT_ACCES}" id="f_droit_compta_acces" {if $cat.droit_compta == $membres::DROIT_ACCES}checked="checked"{/if} />
                <label for="f_droit_compta_acces"><b class="acces">€</b> Lecture uniquement <em>(peut lire toutes les informations de tous les exercices)</em></label>
            </dd>
            <dd>
                <input type="radio" name="droit_compta" value="{$membres::DROIT_ECRITURE}" id="f_droit_compta_ecriture" {if $cat.droit_compta == $membres::DROIT_ECRITURE}checked="checked"{/if} />
                <label for="f_droit_compta_ecriture"><b class="ecriture">€</b> Lecture &amp; écriture <em>(peut ajouter des écritures, mais pas les modifier ni les supprimer)</em></label>
            </dd>
            <dd>
                <input type="radio" name="droit_compta" value="{$membres::DROIT_ADMIN}" id="f_droit_compta_admin" {if $cat.droit_compta == $membres::DROIT_ADMIN}checked="checked"{/if} />
                <label for="f_droit_compta_admin"><b class="admin">€</b> Administration <em>(peut modifier et supprimer des écritures, gérer les comptes, les exercices, etc.)</em></label>
            </dd>
        </dl>
        <dl class="droits">
            <dt><label for="f_droit_wiki_aucun">Wiki :</label></dt>
            <dd>
                <input type="radio" name="droit_wiki" value="{$membres::DROIT_AUCUN}" id="f_droit_wiki_aucun" {if $cat.droit_wiki == $membres::DROIT_AUCUN}checked="checked"{/if} />
                <label for="f_droit_wiki_aucun"><b class="aucun">W</b> Pas d'accès</label>
            </dd>
            <dd>
                <input type="radio" name="droit_wiki" value="{$membres::DROIT_ACCES}" id="f_droit_wiki_acces" {if $cat.droit_wiki == $membres::DROIT_ACCES}checked="checked"{/if} />
                <label for="f_droit_wiki_acces"><b class="acces">W</b> Lecture uniquement <em>(peut lire les pages auquel il a le droit d'accéder)</em></label>
            </dd>
            <dd>
                <input type="radio" name="droit_wiki" value="{$membres::DROIT_ECRITURE}" id="f_droit_wiki_ecriture" {if $cat.droit_wiki == $membres::DROIT_ECRITURE}checked="checked"{/if} />
                <label for="f_droit_wiki_ecriture"><b class="ecriture">W</b> Lecture &amp; écriture <em>(peut modifier ou ajouter des pages, mais pas les supprimer)</em></label>
            </dd>
            <dd>
                <input type="radio" name="droit_wiki" value="{$membres::DROIT_ADMIN}" id="f_droit_wiki_admin" {if $cat.droit_wiki == $membres::DROIT_ADMIN}checked="checked"{/if} />
                <label for="f_droit_wiki_admin"><b class="admin">W</b> Administration <em>(peut tout faire)</em></label>
            </dd>
        </dl>
        <dl class="droits">
            <dt><label for="f_droit_config_aucun">Les membres de cette catégorie peuvent-ils modifier la configuration ?</label></dt>
            {if $readonly}
                <dd class="help">
                    Il n'est pas possible de désactiver ce droit pour votre propre catégorie.
                </dd>
            {/if}
            <dd>
                <input type="radio" name="droit_config" value="{$membres::DROIT_AUCUN}" id="f_droit_config_aucun" {if $cat.droit_config == $membres::DROIT_AUCUN}checked="checked"{/if} {$readonly} />
                <label for="f_droit_config_aucun"><b class="aucun">&#x2611;</b> Non</label>
            </dd>
            <dd>
                <input type="radio" name="droit_config" value="{$membres::DROIT_ADMIN}" id="f_droit_config_admin" {if $cat.droit_config == $membres::DROIT_ADMIN}checked="checked"{/if} {$readonly} />
                <label for="f_droit_config_admin"><b class="admin">&#x2611;</b> Oui</label>
            </dd>
        </dl>
    </fieldset>

    <p class="submit">
        {csrf_field key="edit_cat_"|cat:$cat.id}
        {button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
    </p>

</form>

{include file="admin/_foot.tpl"}








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

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

|
|
|
|




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
{include file="admin/_head.tpl" title="Modifier une catégorie de membre" current="config"}

{include file="admin/config/_menu.tpl" current="categories"}

{form_errors}

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

	<fieldset>
		<legend>Informations générales</legend>
		<dl>

			{input type="text" name="name" label="Nom" required=true source=$cat}



			<dt>Configuration</dt>

			{input type="checkbox" name="hidden" label="Catégorie cachée" source=$cat value=1 help="Si coché cette catégorie ne sera visible qu'aux administrateurs et ne recevra pas de messages collectifs ou de rappels"}


		</dl>
	</fieldset>

	<fieldset>
		<legend>Droits</legend>
		<dl class="permissions">
		{foreach from=$permissions key="type" item="perm"}
			<dt><label for="f_perm_{$type}_0">{$perm.label}</label></dt>
			{if $perm.disabled}
				<dd class="help">
					Il n'est pas possible de désactiver ce droit pour votre propre catégorie.
				</dd>
			{/if}

			{foreach from=$perm.options key="level" item="label"}













































			<dd>
				<input type="radio" name="perm_{$type}" value="{$level}" id="f_perm_{$type}_{$level}" {if $cat->{'perm_' . $type} == $level}checked="checked"{/if} {if $perm.disabled}disabled="disabled"{/if} />












				<label for="f_perm_{$type}_{$level}"><b class="access_{$level}">{$perm.shape}</b> {$label}</label>



			</dd>















			{/foreach}



		{/foreach}








		</dl>
	</fieldset>

	<p class="submit">
		{csrf_field key=$csrf_key}
		{button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
	</p>

</form>

{include file="admin/_foot.tpl"}

Modified src/templates/admin/config/categories/supprimer.tpl from [f56242fa31] to [b8906b9dfd].

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
{include file="admin/_head.tpl" title="Supprimer une catégorie de membre" current="config"}

{include file="admin/config/_menu.tpl" current="categories"}

{form_errors}

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

    <fieldset>
        <legend>Supprimer la catégorie de membres ?</legend>
        <h3 class="warning">
            Êtes-vous sûr de vouloir supprimer la catégorie «&nbsp;{$cat.nom}&nbsp;» ?
        </h3>
        <p class="help">
            Attention, la catégorie ne doit plus contenir de membres pour pouvoir
            être supprimée.
        </p>
        <p class="help">
            Notez que si des pages du wiki étaient restreintes à la lecture ou à l'écriture
            aux seuls membres de ce groupe, elles redeviendront lisibles et modifiables
            par tous les membres ayant accès au wiki !
        </p>
    </fieldset>

    <p class="submit">
        {csrf_field key="delete_cat_"|cat:$cat.id}
        {button type="submit" name="delete" label="Supprimer" shape="delete" class="main"}
    </p>

</form>

{include file="admin/_foot.tpl"}




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

<
<

1
2
3
4

5



6

7


8








9




10


11
{include file="admin/_head.tpl" title="Supprimer une catégorie de membre" current="config"}

{include file="admin/config/_menu.tpl" current="categories"}


{include file="common/delete_form.tpl"



	legend="Supprimer cette catégorie de membres ?"

	warning="Êtes-vous sûr de vouloir supprimer la catégorie « %s » ?"|args:$cat.name


	alert="Attention, la catégorie ne doit plus contenir de membres pour pouvoir être supprimée."








	info="Les écritures comptables liées à l'historique des membres inscrits à cette activité ne seront pas supprimées, et la comptabilité demeurera inchangée."}







{include file="admin/_foot.tpl"}

Deleted src/templates/admin/config/donnees/_menu.tpl version [34eb7c69e1].

1
2
3
4
5
6
7
8
9
10
<nav class="tabs">
	<ul class="sub">
		<li{if $current == 'index'} class="current"{/if}><a href="{$admin_url}config/donnees/">Sauvegarder et restaurer</a></li>
		<li{if $current == 'import'} class="current"{/if}><a href="{$admin_url}config/donnees/import.php">Import et export</a></li>
		<li{if $current == 'local'} class="current"{/if}><a href="{$admin_url}config/donnees/local.php">Gestion des sauvegardes</a></li>
		{if ENABLE_AUTOMATIC_BACKUPS}
		<li{if $current == 'automatique'} class="current"{/if}><a href="{$admin_url}config/donnees/automatique.php">Configuration de la sauvegarde automatique</a></li>
		{/if}
	</ul>
</nav>
<
<
<
<
<
<
<
<
<
<




















Deleted src/templates/admin/config/donnees/automatique.tpl version [f0d729ff37].

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
{include file="admin/_head.tpl" title="Sauvegarde et restauration" current="config"}

{include file="admin/config/_menu.tpl" current="donnees"}

{include file="admin/config/donnees/_menu.tpl" current="automatique"}

{form_errors}

{if $ok == 'config'}
	<p class="block confirm">La configuration a bien été enregistrée.</p>
{/if}

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

<fieldset>
	<legend>Configuration de la sauvegarde automatique</legend>
	<p class="help">
		En activant cette option une sauvegarde sera automatiquement créée à chaque intervalle donné.
		Par exemple en activant une sauvegarde hebdomadaire, une copie des données sera réalisée
		une fois par semaine, sauf si aucune modification n'a été effectuée sur les données
		ou que personne ne s'est connecté.
	</p>
	<dl>
		<dt><label for="f_frequency">Intervalle de sauvegarde</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
		<dd>
			<select name="frequence_sauvegardes" required="required" id="f_frequency">
				<option value="0"{form_field name=frequence_sauvegardes data=$config selected=0}>Aucun — les sauvegardes automatiques sont désactivées</option>
				<option value="1"{form_field name=frequence_sauvegardes data=$config selected=1}>Quotidien, tous les jours</option>
				<option value="7"{form_field name=frequence_sauvegardes data=$config selected=7}>Hebdomadaire, tous les 7 jours</option>
				<option value="15"{form_field name=frequence_sauvegardes data=$config selected=15}>Bimensuel, tous les 15 jours</option>
				<option value="30"{form_field name=frequence_sauvegardes data=$config selected=30}>Mensuel</option>
				<option value="90"{form_field name=frequence_sauvegardes data=$config selected=90}>Trimestriel</option>
				<option value="365{form_field name=frequence_sauvegardes data=$config selected=365}">Annuel</option>
			</select>
		</dd>
		<dt><label for="f_max_backups">Nombre de sauvegardes conservées</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
		<dd class="help">
			Par exemple avec l'intervalle mensuel, en indiquant de conserver 12 sauvegardes,
			vous pourrez garder un an d'historique de sauvegardes.
		</dd>
		<dd class="help">
			<strong>Attention :</strong> si vous choisissez un nombre important et un intervalle réduit,
			l'espace disque occupé par vos sauvegardes va rapidement augmenter.
		</dd>
		<dd><input type="number" name="nombre_sauvegardes" value="{form_field name=nombre_sauvegardes data=$config}" if="f_max_backups" min="1" max="90" required="required" /></dd>
	</dl>
	<p>
		{csrf_field key="backup_config"}
		<input type="submit" name="config" value="Enregistrer &rarr;" />
	</p>
</fieldset>

</form>

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































Deleted src/templates/admin/config/donnees/import.tpl version [19ab1e4db0].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{include file="admin/_head.tpl" title="Import & export" current="config"}

{include file="admin/config/_menu.tpl" current="donnees"}

{include file="admin/config/donnees/_menu.tpl" current="import"}

<fieldset>
<dl>
	<dt>Membres</dt>
	<dd><a href="{$admin_url}membres/import.php">Import de la liste des membres</a></dd>
	<dd><a href="{$admin_url}membres/import.php?export=ods">Export de la liste des membres au format tableur Calc / Excel</a></dd>
	<dd><a href="{$admin_url}membres/import.php?export=csv">Export de la liste des membres au format CSV</a></dd>
	<dt>Comptabilité</dt>
	<dd><a href="{$admin_url}acc/years/import.php">Import des données comptables</a></dd>
	<dd><a href="{$admin_url}acc/years/import.php?export=ods">Export des données comptables au format tableur Calc / Excel</a></dd>
	<dd><a href="{$admin_url}acc/years/import.php?export=csv">Export des données comptables au format CSV</a></dd>
</dl>
</fieldset>

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































Deleted src/templates/admin/config/donnees/index.tpl version [8251f0824b].

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
{include file="admin/_head.tpl" title="Sauvegarde et restauration" current="config"}

{include file="admin/config/_menu.tpl" current="donnees"}

{include file="admin/config/donnees/_menu.tpl" current="index"}

{form_errors}

{if $code == Sauvegarde::INTEGRITY_FAIL && ALLOW_MODIFIED_IMPORT}
    <p class="block alert">Pour passer outre, renvoyez le fichier en cochant la case «&nbsp;Ignorer les erreurs&nbsp;».
    Attention, si vous avez effectué des modifications dans la base de données, cela peut créer des bugs&nbsp;!</p>
{/if}

{if $ok}
    <p class="block confirm">
        {if $ok == 'restore'}La restauration a bien été effectuée.
            {if $ok_code & Sauvegarde::NOT_AN_ADMIN}
            </p>
            <p class="block alert">
                <strong>Vous n'êtes pas administrateur dans cette sauvegarde.</strong> Garradin a donné les droits d'administration à toutes les catégories afin d'empêcher de ne plus pouvoir se connecter.
                Merci de corriger les droits des catégories maintenant.
            {/if}
        {elseif $ok == 'remove'}La sauvegarde a été supprimée.
        {/if}
    </p>
{/if}


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

<fieldset>
    <legend>Téléchargement d'une sauvegarde</legend>
	<p class="help">
		Info : la base de données fait actuellement {$db_size|format_bytes} (dont {$files_size|format_bytes} pour les documents et images).
	</p>
    <p class="submit">
        {csrf_field key="backup_download"}
        {button type="submit" name="download" label="Télécharger une copie de la base de données sur mon ordinateur" shape="download" class="main"}
    </p>
</fieldset>

</form>

<form method="post" action="{$self_url_no_qs}" enctype="multipart/form-data">

<fieldset>
    <legend><label for="f_file">Restaurer depuis un fichier de sauvegarde</label></legend>
    <p class="block alert">
        Attention, l'intégralité des données courantes seront effacées et remplacées par celles
        contenues dans le fichier fourni.
    </p>
    <p class="help">
        Une sauvegarde des données courantes sera effectuée avant le remplacement,
        en cas de besoin d'annuler cette restauration.
    </p>
    <p>
        {csrf_field key="backup_restore"}
        <input type="hidden" name="MAX_FILE_SIZE" value="{$max_file_size}" />
        <input type="file" name="file" id="f_file" required="required" />
        (maximum {$max_file_size|format_bytes})
    </p>
    <p class="submit">
        {button type="submit" name="restore_file" label="Restaurer depuis le fichier sélectionné" shape="upload" class="main"}
    </p>
    {if $code && ($code == Sauvegarde::INTEGRITY_FAIL && ALLOW_MODIFIED_IMPORT)}
    <p>
        {input type="checkbox" name="force_import" value="1" label="Ignorer les erreurs, je sais ce que je fait"}
    </p>
    {/if}
</fieldset>

</form>

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































Deleted src/templates/admin/config/donnees/local.tpl version [c86c4163a9].

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
{include file="admin/_head.tpl" title="Gestion des sauvegardes" current="config"}

{include file="admin/config/_menu.tpl" current="donnees"}

{include file="admin/config/donnees/_menu.tpl" current="local"}

{form_errors}

{if $ok}
    <p class="block confirm">
        {if $ok == 'create'}Une nouvelle sauvegarde a été créée.
        {elseif $ok == 'restore'}La restauration a bien été effectuée. Si vous désirez revenir en arrière, vous pouvez utiliser la sauvegarde automatique nommée <em>date-du-jour.avant_restauration.sqlite</em>, sinon vous pouvez l'effacer.
            {if $ok_code & Sauvegarde::NOT_AN_ADMIN}
            </p>
            <p class="block alert">
                <strong>Vous n'êtes pas administrateur dans cette sauvegarde.</strong> Garradin a donné les droits d'administration à toutes les catégories afin d'empêcher de ne plus pouvoir se connecter.
                Merci de corriger les droits des catégories maintenant.
            {/if}
        {elseif $ok == 'remove'}La sauvegarde a été supprimée.
        {/if}
    </p>
{/if}


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

<fieldset>
    <legend>Sauvegarde manuelle</legend>
    <p class="submit">
        {csrf_field key="backup_create"}
        {button type="submit" name="create" label="Créer une nouvelle sauvegarde manuelle" shape="right" class="main"}
    </p>
</fieldset>

</form>

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

<fieldset>
    <legend>Sauvegardes disponibles</legend>
    {if empty($list)}
        <p class="help">Aucune copie de sauvegarde disponible.</p>
    {else}
        <table class="list">
            <tbody>
            {foreach from=$list item="backup"}
                <tr>
                    <td class="check">{input type="radio" name="selected" value=$backup.filename}</td>
                    <th><label for="f_selected_{$backup.filename}">{$backup.name}</label></th>
                    <td>{$backup.size|format_bytes}</td>
                    <td>{$backup.date|date_long}</td>
                    <td>{if !$backup.can_restore}<span class="alert">Version {$backup.version} trop ancienne pour pouvoir être restaurée</span>{/if}</td>
                    <td class="actions">
                        {linkbutton href="?download=%s"|args:$backup.filename label="Télécharger" shape="download"}
                    </td>
                </tr>
            {/foreach}
            </tbody>
        </table>
        <p class="alert block">
            Attention, en cas de restauration, l'intégralité des données courantes seront effacées et remplacées par celles contenues dans la sauvegarde sélectionnée.
        </p>
        <p>
            {csrf_field key="backup_manage"}
            {button type="submit" name="restore" label="Restaurer cette sauvegarde" shape="reset"}
            {button type="submit" name="remove" label="Supprimer cette sauvegarde" shape="delete"}
        </p>
    {/if}
</fieldset>

</form>

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































Modified src/templates/admin/config/index.tpl from [8115cb5714] to [7910ad85ee].

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
{include file="admin/_head.tpl" title="Configuration" current="config"}

{include file="admin/config/_menu.tpl" current="index"}

{if $ok && !$form->hasErrors()}
    <p class="block confirm">
        La configuration a bien été enregistrée.
    </p>
{/if}

{form_errors}

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

    <fieldset>
        <legend>Garradin</legend>
        <dl>
            <dt>Version installée</dt>
            <dd class="help">{$garradin_version}</dd>
            {if $new_version}
            <dd><p class="block alert">
                Une nouvelle version <strong>{$new_version}</strong> est disponible !<br />
                <a href="{$garradin_website}" target="_blank">Aller télécharger la nouvelle version</a>
            </p></dd>
            {/if}
            {if ENABLE_TECH_DETAILS}
            <dt>Informations système</dt>
            <dd class="help">
                Version PHP&nbsp;: {$php_version}<br />
                Version SQLite&nbsp;: {$sqlite_version}<br />
                Heure du serveur&nbsp;: {$server_time|date_fr}<br />
                Chiffrement GnuPG&nbsp;: {if $has_gpg_support}disponible, module activé{else}non, module PHP gnupg non installé&nbsp;?{/if}<br />
            </dd>
            {/if}
        </dl>
    </fieldset>

    <fieldset>
        <legend>Informations sur l'association</legend>
        <dl>
            <dt><label for="f_nom_asso">Nom</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd><input type="text" name="nom_asso" id="f_nom_asso" required="required" value="{form_field data=$config name=nom_asso}" /></dd>
            <dt><label for="f_email_asso">Adresse E-Mail</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd><input type="email" name="email_asso" id="f_email_asso" required="required" value="{form_field data=$config name=email_asso}" /></dd>
            <dt><label for="f_adresse_asso">Adresse postale</label></dt>
            <dd><textarea cols="30" rows="5" name="adresse_asso" id="f_adresse_asso">{form_field data=$config name=adresse_asso}</textarea></dd>
            <dt><label for="f_site_asso">Site web</label></dt>

            <dd><input type="url" name="site_asso" id="f_site_asso" value="{form_field name=site_asso data=$config}" /></dd>
        </dl>
    </fieldset>

    <fieldset>
        <legend>Localisation</legend>
        <dl>
            <dt><label for="f_monnaie">Monnaie</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd><input type="text" name="monnaie" id="f_monnaie" required="required" value="{form_field name=monnaie data=$config}" size="5" /></dd>
            <dt><label for="f_pays">Pays</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd>
                <select name="pays" id="f_pays" required="required">
                {foreach from=$pays key="cc" item="nom"}
                    <option value="{$cc}"{if $cc == $config.pays} selected="selected"{/if}>{$nom}</option>
                {/foreach}
                </select>
            </dd>
        </dl>
    </fieldset>

    <fieldset>
        <legend>Wiki</legend>
        <dl>
            <dt><label for="f_accueil_wiki">Page d'accueil du wiki</label> 
                <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd>Indiquer ici l'adresse unique de la page qui sera utilisée comme page d'accueil du wiki.</dd>
            <dd><input type="text" name="accueil_wiki" id="f_accueil_wiki" required="required" value="{form_field data=$config name=accueil_wiki}" /></dd>
            <dt><label for="f_accueil_connexion">Page d'accueil à la connexion</label> 
                <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd>Indiquer ici l'adresse unique de la page qui sera affichée à la connexion d'un membre.</dd>
            <dd><input type="text" name="accueil_connexion" id="f_accueil_connexion" required="required" value="{form_field data=$config name=accueil_connexion}" /></dd>
        </dl>
    </fieldset>

    <fieldset>
        <legend>Membres</legend>
        <dl>
            <dt><label for="f_categorie_membres">Catégorie par défaut des nouveaux membres</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd>
                <select name="categorie_membres" required="required" id="f_categorie_membres">
                {foreach from=$membres_cats key="id" item="nom"}
                    <option value="{$id}"{if $config.categorie_membres == $id} selected="selected"{/if}>{$nom}</option>
                {/foreach}
                </select>
            </dd>
            <dt><label for="f_champ_identite">Champ utilisé pour définir l'identité des membres</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd class="help">Ce champ des fiches membres sera utilisé comme identité du membre dans les emails, les fiches, les pages, etc.</dd>
            <dd>
                <select name="champ_identite" required="required" id="f_champ_identite">
                    {foreach from=$champs key="c" item="champ"}
                        <option value="{$c}" {form_field selected=$c name="champ_identite" data=$config}>{$champ.title}</option>
                    {/foreach}
                </select>
            </dd>
            <dt><label for="f_champ_identifiant">Champ utilisé comme identifiant de connexion</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd class="help">Ce champ des fiches membres sera utilisé en guise d'identifiant pour se connecter à Garradin. Pour cela le champ doit être unique (pas de doublons).</dd>
            <dd>
                <select name="champ_identifiant" required="required" id="f_champ_identifiant">
                    {foreach from=$champs key="c" item="champ"}
                        <option value="{$c}" {form_field selected=$c name="champ_identifiant" data=$config}>{$champ.title}</option>
                    {/foreach}
                </select>
            </dd>

        </dl>
    </fieldset>

    <fieldset id="couleurs">
        <legend>Personnalisation de l'interface</legend>
        <dl>









            {input type="color" pattern="#[a-f0-9]{6}" title="Couleur au format hexadécimal" default=$couleur1 name="couleur1" label="Couleur primaire" placeholder=$couleurs_defaut[0]}
            {input type="color" pattern="#[a-f0-9]{6}" title="Couleur au format hexadécimal" default=$couleur2 name="couleur2" label="Couleur secondaire" placeholder=$couleurs_defaut[1]}
            {input type="file" label="Image de fond" name="background" help="Il est conseillé d'utiliser une image en noir et blanc avec un fond blanc pour un meilleur rendu. Dimensions recommandées : 380x200" accept="image/*,*.jpeg,*.jpg,*.png,*.gif"}
        </dl>
        <input type="hidden" name="image_fond" id="f_image_fond" data-source="{$background_image_source}" data-default="{$background_image_default}" value="{form_field name=image_fond}" />
    </fieldset>

    <p class="submit">
        {csrf_field key="config"}
        {button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
    </p>

</form>

{include file="admin/_foot.tpl"}




|
|
|
|






|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

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

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

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

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

|
|
|
|




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
{include file="admin/_head.tpl" title="Configuration" current="config"}

{include file="admin/config/_menu.tpl" current="index"}

{if isset($_GET['ok']) && !$form->hasErrors()}
	<p class="block confirm">
		La configuration a bien été enregistrée.
	</p>
{/if}

{form_errors}

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

	<fieldset>
		<legend>Garradin</legend>
		<dl>
			<dt>Version installée</dt>
			<dd class="help">{$garradin_version}</dd>
			{if $new_version}
			<dd><p class="block alert">
				Une nouvelle version <strong>{$new_version}</strong> est disponible !<br />
				<a href="{$garradin_website}" target="_blank">Aller télécharger la nouvelle version</a>
			</p></dd>
			{/if}
			{if ENABLE_TECH_DETAILS}
			<dt>Informations système</dt>
			<dd class="help">
				Version PHP&nbsp;: {$php_version}<br />
				Version SQLite&nbsp;: {$sqlite_version}<br />
				Heure du serveur&nbsp;: {$server_time|date}<br />
				Chiffrement GnuPG&nbsp;: {if $has_gpg_support}disponible, module activé{else}non, module PHP gnupg non installé&nbsp;?{/if}<br />
			</dd>
			{/if}
		</dl>
	</fieldset>

	<fieldset>
		<legend>Informations sur l'association</legend>
		<dl>

			{input type="text" name="nom_asso" required=true source=$config label="Nom"}

			{input type="email" name="email_asso" required=true source=$config label="Adresse e-mail de contact"}
			{input type="textarea" name="adresse_asso" source=$config label="Adresse postale"}


			{input type="tel" name="telephone_asso" source=$config label="Numéro de téléphone"}
			{input type="url" name="site_asso" source=$config label="Site web" help="Si vous n'utilisez pas la fonctionnalité site web de Garradin"}
		</dl>
	</fieldset>

	<fieldset>
		<legend>Localisation</legend>
		<dl>

			{input type="text" name="monnaie" required=true source=$config label="Monnaie" help="Inscrire ici la devise utilisée : €, CHF, XPF, etc." size="3"}










			{input type="select" name="pays" required=true source=$config label="Pays" options=$countries}











		</dl>
	</fieldset>

	<fieldset>
		<legend>Membres</legend>
		<dl>
			{input type="select" name="categorie_membres" source=$config options=$membres_cats required=true label="Catégorie par défaut des nouveaux membres"}







			{input type="select" name="champ_identite" source=$config options=$champs required=true label="Champ utilisé pour définir l'identité des membres" help="Ce champ des fiches membres sera utilisé comme identité du membre dans les emails, les fiches, les pages, etc."}

















			{input type="select" name="champ_identifiant" source=$config options=$champs required=true label="Champ utilisé comme identifiant de connexion" help="Ce champ des fiches membres sera utilisé comme identifiant pour se connecter à Garradin. Ce champ doit être unique (il ne peut pas contenir deux membres ayant la même valeur dans ce champ)."}
		</dl>
	</fieldset>

	<fieldset>
		<legend>Personnalisation</legend>
		<dl>
		{if $config.admin_homepage}
			<dt>Texte de la page d'accueil</dt>
			<dd>
				{linkbutton href="!common/files/edit.php?p=%s"|args:$config.admin_homepage label="Modifier" shape="edit" target="_dialog" data-dialog-height="90%"}
			</dd>
			<dd class="help">
				Ce contenu sera affiché à la connexion d'un membre, ou en cliquant sur l'onglet 'Accueil' du menu de gauche.
			</dd>
		{/if}
			{input type="color" pattern="#[a-f0-9]{6}" title="Couleur au format hexadécimal" default=$color1 source=$config name="couleur1" label="Couleur primaire" placeholder=$color1}
			{input type="color" pattern="#[a-f0-9]{6}" title="Couleur au format hexadécimal" default=$color2 source=$config name="couleur2" label="Couleur secondaire" placeholder=$color2}
			{input type="file" label="Image de fond" name="background" help="Il est conseillé d'utiliser une image en noir et blanc avec un fond blanc pour un meilleur rendu. Dimensions recommandées : 380x200" accept="image/*,*.jpeg,*.jpg,*.png,*.gif"}
		</dl>
		<input type="hidden" name="admin_background" id="f_admin_background" data-current="{$background_image_current}" data-default="{$background_image_default}" value="{$_POST.admin_background}" />
	</fieldset>

	<p class="submit">
		{csrf_field key="config"}
		{button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
	</p>

</form>

{include file="admin/_foot.tpl"}

Modified src/templates/admin/config/membres.tpl from [5a8266eee1] to [d986be9230].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{include file="admin/_head.tpl" current="config" custom_css=['styles/config.css']}

{include file="admin/config/_menu.tpl" current="fiches_membres"}

{if isset($status) && $status == 'OK'}
    <p class="block confirm">
        La configuration a bien été enregistrée.
    </p>
{elseif isset($status) && $status == 'ADDED'}
    <p class="block alert">
        Le champ a été ajouté à la fin de la liste. Pour sauvegarder les modifications de la fiche membre cliquer sur le bouton «&nbsp;Enregistrer&nbsp;» en base de page.
    </p>
{/if}

{form_errors}

{if $review}
    <p class="help">
|









|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{include file="admin/_head.tpl" current="config" custom_css=['config.css']}

{include file="admin/config/_menu.tpl" current="fiches_membres"}

{if isset($status) && $status == 'OK'}
    <p class="block confirm">
        La configuration a bien été enregistrée.
    </p>
{elseif isset($status) && $status == 'ADDED'}
    <p class="block alert">
        Le champ a été ajouté à la fin de la liste. Pour vérifier et sauvegarder les modifications de la fiche membre cliquer sur le bouton «&nbsp;rifier les changements&nbsp;» en base de page.
    </p>
{/if}

{form_errors}

{if $review}
    <p class="help">

Deleted src/templates/admin/config/site.tpl version [2454b9048e].

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
{include file="admin/_head.tpl" title="Configuration — Site public" current="config"}

{form_errors}

{include file="admin/config/_menu.tpl" current="site"}

{if $config.desactiver_site}
    <div class="block alert">
        <h3>Site public désactivé</h3>
        <p>Le site public est désactivé, les visiteurs sont redirigés automatiquement vers la page de connexion.</p>
        <form method="post" action="{$self_url}">
            <p class="submit">
                {csrf_field key="config_site"}
                {button type="submit" name="activer_site" label="Réactiver le site public" shape="right" class="main"}
            </p>
        </form>
    </div>
{elseif isset($edit)}
    <form method="post" action="{$self_url}">
        <h3>Éditer un squelette</h3>

        {if $ok}
        <p class="block confirm">
            Modifications enregistrées.
        </p>
        {/if}

        <fieldset class="skelEdit">
            <legend>{$edit.file}</legend>
            <p>
                <textarea name="content" cols="90" rows="50" id="f_content">{form_field name=content data=$edit}</textarea>
            </p>
        </fieldset>

        <p class="submit">
            {csrf_field key=$csrf_key}
            {button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
        </p>

    </form>

    <script type="text/javascript">
    var doc_url = "{$admin_url}doc/skel/";
    var skel_list = {$sources|escape:json};
    var skel_current = "{$edit.file|escape:'js'}";
    g.script("scripts/skel_editor.js");
    </script>
{else}

    <fieldset>
        <legend>Activation du site public</legend>
        <dl>
            <dt>
                <form method="post" action="{$self_url}">
                    <p class="submit">
                        {button type="submit" name="desactiver_site" label="Désactiver le site public" shape="right" class="main"}
                        {csrf_field key="config_site"}
                    </p>
                </form>
            </dt>
            <dd class="help">
                En désactivant le site public, les visiteurs seront automatiquement redirigés vers la page de connexion.<br />
                Cette option est utile si vous avez déjà un site web et ne souhaitez pas utiliser la fonctionnalité site web de Garradin.
            </dd>
        </dl>
    </fieldset>

    <fieldset>
        <legend>Gérer le contenu du site public</legend>
        <p class="help">
            Le contenu affiché sur le site est celui présent dans le wiki, il suffit de sélectionner «&nbsp;Cette page est visible sur le site de l'association&nbsp;» à l'édition d'une page wiki. Il est également possible de <a href="{$admin_url}wiki/creer.php?public">créer une nouvelle page publique sur le wiki</a>.
        </p>
    </fieldset>

    <form method="post" action="{$self_url}">
    <fieldset class="templatesList">
        <legend>Squelettes du site</legend>

        {if $reset_ok}
        <p class="block confirm">
            Réinitialisation effectuée. Les squelettes ont été remis à jour
        </p>
        {/if}

        <table class="list">
            <thead>
                <tr>
                    <td class="check"></td>
                    <th>Fichier</th>
                    <td>Dernière modification</td>
                    <td></td>
                </tr>
            </thead>
            <tbody>
            {foreach from=$sources key="source" item="local"}
                <tr>
                    <td>{if $local && $local.dist}<input type="checkbox" name="select[]" value="{$source}" id="f_source_{$iteration}" /><label for="f_source_{$iteration}"></label>{/if}</td>
                    <th><a href="{$admin_url}config/site.php?edit={$source|escape:'url'}" title="Éditer">{$source}</a></th>
                    <td>{if $local}{$local.mtime|date_fr:'d/m/Y à H:i:s'}{else}<em>(fichier non modifié)</em>{/if}</td>
                    <td class="actions">
                        {linkbutton shape="edit" label="Éditer" href="?edit=%s"|args:$source}
                    </td>
                </tr>
            {/foreach}
            </tbody>
        </table>

        <p class="actions">
            Pour les squelettes sélectionnés&nbsp;:
            <input type="submit" name="reset" value="Réinitialiser" onclick="return confirm('Effacer toute modification locale et restaurer les squelettes d\'installation ?');" />
            {csrf_field key="squelettes"}
        </p>
    </fieldset>
    </form>
{/if}

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































Modified src/templates/admin/index.tpl from [8ad9228981] to [8fc4b88474].

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
{include file="admin/_head.tpl" title="Bonjour %s !"|args:$user.identite current="home"}

{$banniere|raw}

<nav class="tabs">
    <ul>
        <li><a href="{$admin_url}mes_infos.php">Modifier mes informations personnelles</a></li>
        <li><a href="{$admin_url}my_services.php">Suivi de mes activités et cotisations</a></li>
    </ul>
</nav>

<aside class="describe">
    <h3>{$config.nom_asso}</h3>
    {if !empty($config.adresse_asso)}
    <p>
        {$config.adresse_asso|escape|nl2br}
    </p>
    {/if}





    {if !empty($config.email_asso)}
    <p>
        E-Mail : <a href="mailto:{$config.email_asso}">{$config.email_asso}</a>
    </p>
    {/if}
    {if !empty($config.site_asso)}
    <p>
        Web : <a href="{$config.site_asso}" target="_blank">{$config.site_asso}</a>
    </p>
    {/if}
</aside>


<div class="wikiContent">
    {$page.contenu.contenu|raw|format_wiki|liens_wiki:'wiki/?'}
</div>


{include file="admin/_foot.tpl"}


|


|
|
|
|



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


>
|
|
|
>


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
{include file="admin/_head.tpl" title="Bonjour %s !"|args:$user.identite current="home"}

{$banner|raw}

<nav class="tabs">
	<ul>
		<li><a href="{$admin_url}mes_infos.php">Modifier mes informations personnelles</a></li>
		<li><a href="{$admin_url}my_services.php">Suivi de mes activités et cotisations</a></li>
	</ul>
</nav>

<aside class="describe">
	<h3>{$config.nom_asso}</h3>
	{if !empty($config.adresse_asso)}
	<p>
		{$config.adresse_asso|escape|nl2br}
	</p>
	{/if}
	{if !empty($config.telephone_asso)}
	<p>
		Tél. : <a href="tel:{$config.telephone_asso}">{$config.telephone_asso}</a>
	</p>
	{/if}
	{if !empty($config.email_asso)}
	<p>
		E-Mail : <a href="mailto:{$config.email_asso}">{$config.email_asso}</a>
	</p>
	{/if}
	{if !empty($config.site_asso)}
	<p>
		Web : <a href="{$config.site_asso}" target="_blank">{$config.site_asso}</a>
	</p>
	{/if}
</aside>

{if $homepage}
	<article class="web-content">
		{$homepage|raw}
	</article>
{/if}

{include file="admin/_foot.tpl"}

Modified src/templates/admin/install.tpl from [e0d35a0a40] to [57684a4a9c].

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
{include file="admin/_head.tpl" title="Garradin - Installation"}

{if $disabled}
    <p class="block error">Garradin est déjà installé.</p>
{else}
    <p class="help">
        Bienvenue dans Garradin !
        Veuillez remplir les quelques informations suivantes pour terminer
        l'installation.
    </p>

    {form_errors}

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

    <fieldset>
        <legend>Informations sur l'association</legend>
        <dl>
            <dt><label for="f_nom_asso">Nom</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd><input type="text" name="nom_asso" id="f_nom_asso" required="required" value="{form_field name=nom_asso}" /></dd>
        </dl>
    </fieldset>

    <fieldset>
        <legend>Création du compte administrateur</legend>
        <dl>
            <dt><label for="f_nom_membre">Nom et prénom</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd><input type="text" name="nom_membre" id="f_nom_membre" required="required" value="{form_field name=nom_membre}" /></dd>
            <dt><label for="f_email_membre">Adresse E-Mail</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd><input type="email" name="email_membre" id="f_email_membre" required="required" value="{form_field name=email_membre}" /></dd>
            <dt><label for="f_passe_membre">Mot de passe</label> (minimum {$password_length} caractères) <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd class="help">
                Astuce : un mot de passe de quatre mots choisis au hasard dans le dictionnaire est plus sûr
                et plus simple à retenir qu'un mot de passe composé de 10 lettres et chiffres.
            </dd>
            <dd class="help">
                Pas d'idée&nbsp;? Voici une suggestion choisie au hasard :
                <input type="text" readonly="readonly" title="Cliquer pour utiliser cette suggestion comme mot de passe" id="pw_suggest" value="{$passphrase}" autocomplete="off" />
            </dd>
            <dd><input type="password" name="passe" id="f_passe_membre" value="{form_field name=passe}" pattern="{$password_pattern}" required="required" autocomplete="off" /></dd>
            <dt><label for="f_repasse_membre">Encore le mot de passe</label> (vérification) <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd><input type="password" name="passe_confirmed" id="f_repasse_membre" value="{form_field name=passe_confirmed}" pattern="{$password_pattern}" required="required" autocomplete="off" /></dd>
        </dl>
    </fieldset>

    <p class="submit">
        {csrf_field key="install"}
        {button type="submit" name="save" label="Terminer l'installation" shape="right" class="main"}
    </p>

    <script type="text/javascript" src="{$admin_url}static/scripts/loader.js"></script>

    <script type="text/javascript">
    {literal}
    g.script('scripts/password.js', () => {
        initPasswordField('pw_suggest', 'f_passe_membre', 'f_repasse_membre');
    });

    var form = $('form')[0];
    form.onsubmit = function () {
        $('#f_submit').style.opacity = 0;
        var loader = document.createElement('div');
        loader.className = 'loader install';
        loader.innerHTML = '<b>Garradin est en cours d\'installation…</b>';
        $('#f_submit').parentNode.appendChild(loader);
        animatedLoader(loader, 5);
    };
    {/literal}
    </script>

    </form>
{/if}

{include file="admin/_foot.tpl"}
|

<
<
<
|
|
|
|
|

|

|

|
|
|
<
|
|
|

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

|
|
|
|

|

|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|

|
|


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
{include file="admin/_head.tpl" title="Garradin - Installation" menu=false}




<p class="help">
    Bienvenue dans Garradin !
    Veuillez remplir les quelques informations suivantes pour terminer
    l'installation.
</p>

{form_errors}

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

<fieldset>
    <legend>Informations sur l'association</legend>
    <dl>

        {input type="text" label="Nom de l'association" required=true name="name"}
    </dl>
</fieldset>

<fieldset>
    <legend>Création du compte administrateur</legend>
    <dl>

        {input type="text" label="Nom et prénom" required=true name="user_name"}

        {input type="email" label="Adresse E-Mail" required=true name="user_email"}



        {password_change label="Mot de passe" required=true name="user_password"}








    </dl>
</fieldset>

<p class="submit">
    {csrf_field key="install"}
    {button type="submit" name="save" label="Terminer l'installation" shape="right" class="main"}
</p>

<script type="text/javascript" src="{$admin_url}static/scripts/loader.js"></script>

<script type="text/javascript">
{literal}
g.script('scripts/password.js', () => {
    initPasswordField('user_password');
});

var form = $('form')[0];
form.onsubmit = function () {
    $('#f_submit').style.opacity = 0;
    var loader = document.createElement('div');
    loader.className = 'loader install';
    loader.innerHTML = '<b>Garradin est en cours d\'installation…</b>';
    $('#f_submit').parentNode.appendChild(loader);
    animatedLoader(loader, 5);
};
{/literal}
</script>

</form>


{include file="admin/_foot.tpl"}

Modified src/templates/admin/membres/_list_actions.tpl from [143fb71a16] to [158163abdd].

1
2
3
4
5
6
7
8
9
10
		<tfoot>
			<tr>
				{if $session->canAccess('membres', Membres::DROIT_ADMIN)}<td class="check"><input type="checkbox" value="Tout cocher / décocher" id="f_all2" /><label for="f_all2"></label></td>{/if}
				<td class="actions" colspan="{$colspan}">
					<em>Pour les membres cochés :</em>
					{csrf_field key="membres_action"}
					<select name="action">
						<option value="">— Choisir une action à effectuer —</option>
						<option value="move">Changer de catégorie</option>
						<option value="csv">Exporter en tableau CSV</option>


|







1
2
3
4
5
6
7
8
9
10
		<tfoot>
			<tr>
				{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}<td class="check"><input type="checkbox" value="Tout cocher / décocher" id="f_all2" /><label for="f_all2"></label></td>{/if}
				<td class="actions" colspan="{$colspan}">
					<em>Pour les membres cochés :</em>
					{csrf_field key="membres_action"}
					<select name="action">
						<option value="">— Choisir une action à effectuer —</option>
						<option value="move">Changer de catégorie</option>
						<option value="csv">Exporter en tableau CSV</option>

Modified src/templates/admin/membres/_nav.tpl from [419563ac94] to [bb7c40e577].

1
2
3
4
5
6
7
8
9
10
<nav class="tabs">
	<ul>
		<li{if $current == 'index'} class="current"{/if}><a href="{$admin_url}membres/">Liste des membres</a></li>
		<li{if $current == 'recherche'} class="current"{/if}><a href="{$admin_url}membres/recherche.php">Recherche avancée</a></li>
		<li{if $current == 'recherches'} class="current"{/if}><a href="{$admin_url}membres/recherches.php">Recherches enregistrées</a></li>
		{if $session->canAccess('membres', Membres::DROIT_ADMIN)}
			<li{if $current == 'import'} class="current"{/if}><a href="{$admin_url}membres/import.php">Import &amp; export</a></li>
		{/if}
	</ul>
</nav>





|




1
2
3
4
5
6
7
8
9
10
<nav class="tabs">
	<ul>
		<li{if $current == 'index'} class="current"{/if}><a href="{$admin_url}membres/">Liste des membres</a></li>
		<li{if $current == 'recherche'} class="current"{/if}><a href="{$admin_url}membres/recherche.php">Recherche avancée</a></li>
		<li{if $current == 'recherches'} class="current"{/if}><a href="{$admin_url}membres/recherches.php">Recherches enregistrées</a></li>
		{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
			<li{if $current == 'import'} class="current"{/if}><a href="{$admin_url}membres/import.php">Import &amp; export</a></li>
		{/if}
	</ul>
</nav>

Modified src/templates/admin/membres/ajouter.tpl from [e4d16e8863] to [8e6270090a].

1
2
3
4
5
6
7
8
9
10
11
12
{include file="admin/_head.tpl" title="Ajouter un membre" current="membres/ajouter"}

{form_errors}

<form method="post" action="{$self_url}">
    <!-- This is to avoid chrome autofill, Chrome developers you suck -->
    <input type="text" style="display: none;" name="email" />
    {if $id_field_name != 'email'}<input type="text" style="display: none;" name="{$id_field_name}" />{/if}
    <input type="password" style="display: none;" name="password" />

    <fieldset>
        <legend>Informations personnelles</legend>




|







1
2
3
4
5
6
7
8
9
10
11
12
{include file="admin/_head.tpl" title="Ajouter un membre" current="membres/ajouter"}

{form_errors}

<form method="post" action="{$self_url}" enctype="multipart/form-data">
    <!-- This is to avoid chrome autofill, Chrome developers you suck -->
    <input type="text" style="display: none;" name="email" />
    {if $id_field_name != 'email'}<input type="text" style="display: none;" name="{$id_field_name}" />{/if}
    <input type="password" style="display: none;" name="password" />

    <fieldset>
        <legend>Informations personnelles</legend>
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
            </dd>
            <dd><input type="password" name="passe" id="f_passe" value="{form_field name=passe}" pattern="{$password_pattern}" autocomplete="new-password" /></dd>
            <dt><label for="f_repasse">Encore le mot de passe</label> (vérification)</dt>
            <dd><input type="password" name="passe_confirmed" id="f_repasse" value="{form_field name=passe_confirmed}" pattern="{$password_pattern}" autocomplete="new-password" /></dd>
        </dl>
    </fieldset>

    {if $session->canAccess('membres', Membres::DROIT_ADMIN)}
    <fieldset>
        <legend>Général</legend>
        <dl>
            <dt><label for="f_cat">Catégorie du membre</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd>
                <select name="id_categorie" id="f_cat">
                {foreach from=$membres_cats key="id" item="nom"}
                    <option value="{$id}"{if $current_cat == $id} selected="selected"{/if}>{$nom}</option>
                {/foreach}
                </select>
            </dd>
        </dl>
    </fieldset>







|





|







31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
            </dd>
            <dd><input type="password" name="passe" id="f_passe" value="{form_field name=passe}" pattern="{$password_pattern}" autocomplete="new-password" /></dd>
            <dt><label for="f_repasse">Encore le mot de passe</label> (vérification)</dt>
            <dd><input type="password" name="passe_confirmed" id="f_repasse" value="{form_field name=passe_confirmed}" pattern="{$password_pattern}" autocomplete="new-password" /></dd>
        </dl>
    </fieldset>

    {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
    <fieldset>
        <legend>Général</legend>
        <dl>
            <dt><label for="f_cat">Catégorie du membre</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd>
                <select name="id_category" id="f_cat">
                {foreach from=$membres_cats key="id" item="nom"}
                    <option value="{$id}"{if $current_cat == $id} selected="selected"{/if}>{$nom}</option>
                {/foreach}
                </select>
            </dd>
        </dl>
    </fieldset>

Modified src/templates/admin/membres/fiche.tpl from [4cc42f5c24] to [cd708e950f].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{include file="admin/_head.tpl" title="%s (%s)"|args:$membre.identite:$categorie.nom current="membres"}

<nav class="tabs">
    <ul>
        <li class="current"><a href="{$admin_url}membres/fiche.php?id={$membre.id}">{$membre.identite}</a></li>
        {if $session->canAccess('membres', Membres::DROIT_ECRITURE)}<li><a href="{$admin_url}membres/modifier.php?id={$membre.id}">Modifier</a></li>{/if}
        {if $session->canAccess('membres', Membres::DROIT_ADMIN) && $user.id != $membre.id}
            <li><a href="{$admin_url}membres/supprimer.php?id={$membre.id}">Supprimer</a></li>
        {/if}
    </ul>
</nav>

<dl class="cotisation">
    <dt>Activités et cotisations</dt>
|




|
|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
{include file="admin/_head.tpl" title="%s (%s)"|args:$membre.identite:$category.name current="membres"}

<nav class="tabs">
    <ul>
        <li class="current"><a href="{$admin_url}membres/fiche.php?id={$membre.id}">{$membre.identite}</a></li>
        {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)}<li><a href="{$admin_url}membres/modifier.php?id={$membre.id}">Modifier</a></li>{/if}
        {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN) && $user.id != $membre.id}
            <li><a href="{$admin_url}membres/supprimer.php?id={$membre.id}">Supprimer</a></li>
        {/if}
    </ul>
</nav>

<dl class="cotisation">
    <dt>Activités et cotisations</dt>
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
        Ce membre n'est inscrit à aucune activité ou cotisation.
    </dd>
    {/foreach}
    <dd>
        {if count($services)}
            {linkbutton href="!services/user.php?id=%d"|args:$membre.id label="Liste des inscriptions aux activités" shape="menu"}
        {/if}
        {if $session->canAccess('membres', Membres::DROIT_ECRITURE)}
            {linkbutton href="!services/save.php?user=%d"|args:$membre.id label="Inscrire à une activité" shape="plus"}
        {/if}
    </dd>
    {if $session->canAccess('membres', Membres::DROIT_ACCES)}
        {if !empty($transactions_linked)}
            <dt>Écritures comptables liées</dt>
            <dd><a href="{$admin_url}acc/transactions/user.php?id={$membre.id}">{$transactions_linked} écritures comptables liées à ce membre</a></dd>
        {/if}
        {if !empty($transactions_created)}
            <dt>Écritures comptables créées</dt>
            <dd><a href="{$admin_url}acc/transactions/creator.php?id={$membre.id}">{$transactions_created} écritures comptables créées par ce membre</a></dd>
        {/if}
    {/if}
</dl>

<aside class="describe">
	<dl class="describe">
		<dt>Catégorie</dt>
		<dd>{$categorie.nom} <span class="droits">{format_droits droits=$categorie}</span></dd>
		<dt>Inscription</dt>
		<dd>{$membre.date_inscription|date_short}</dd>
		<dt>Dernière connexion</dt>
		<dd>{if empty($membre.date_connexion)}Jamais{else}{$membre.date_connexion|date_long}{/if}</dd>
		<dt>Mot de passe</dt>
		<dd>
			{if empty($membre.passe)}
				Pas de mot de passe configuré
			{else}
				<b class="icn">☑</b> Oui
				{if !empty($membre.secret_otp)}







|



|














|



|







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
        Ce membre n'est inscrit à aucune activité ou cotisation.
    </dd>
    {/foreach}
    <dd>
        {if count($services)}
            {linkbutton href="!services/user.php?id=%d"|args:$membre.id label="Liste des inscriptions aux activités" shape="menu"}
        {/if}
        {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)}
            {linkbutton href="!services/save.php?user=%d"|args:$membre.id label="Inscrire à une activité" shape="plus"}
        {/if}
    </dd>
    {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_READ)}
        {if !empty($transactions_linked)}
            <dt>Écritures comptables liées</dt>
            <dd><a href="{$admin_url}acc/transactions/user.php?id={$membre.id}">{$transactions_linked} écritures comptables liées à ce membre</a></dd>
        {/if}
        {if !empty($transactions_created)}
            <dt>Écritures comptables créées</dt>
            <dd><a href="{$admin_url}acc/transactions/creator.php?id={$membre.id}">{$transactions_created} écritures comptables créées par ce membre</a></dd>
        {/if}
    {/if}
</dl>

<aside class="describe">
	<dl class="describe">
		<dt>Catégorie</dt>
		<dd>{$category.name} <span class="permissions">{display_permissions permissions=$category}</span></dd>
		<dt>Inscription</dt>
		<dd>{$membre.date_inscription|date_short}</dd>
		<dt>Dernière connexion</dt>
		<dd>{if empty($membre.date_connexion)}Jamais{else}{$membre.date_connexion|date_short:true}{/if}</dd>
		<dt>Mot de passe</dt>
		<dd>
			{if empty($membre.passe)}
				Pas de mot de passe configuré
			{else}
				<b class="icn">☑</b> Oui
				{if !empty($membre.secret_otp)}
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

<dl class="describe">
    {foreach from=$champs key="c" item="c_config"}
    <dt>{$c_config.title}</dt>
    <dd>
        {if $c_config.type == 'checkbox'}
            {if $membre->$c}Oui{else}Non{/if}


        {elseif empty($membre->$c)}
            <em>(Non renseigné)</em>
        {elseif $c == $c_config.champ_identite}
            <strong>{$membre->$c}</strong>
        {elseif $c_config.type == 'email'}
            <a href="mailto:{$membre->$c|escape:'url'}">{$membre->$c}</a>
            {if $c == 'email'}
                {linkbutton href="!membres/message.php?id=%d"|args:$membre.id label="Envoyer un message" shape="mail"}
            {/if}
        {elseif $c_config.type == 'tel'}
            <a href="tel:{$membre->$c}">{$membre->$c|format_tel}</a>
        {elseif $c_config.type == 'country'}
            {$membre->$c|get_country_name}
        {elseif $c_config.type == 'date'}
            {$membre->$c|date_short}
        {elseif $c_config.type == 'datetime'}
            {$membre->$c|date_fr}
        {elseif $c_config.type == 'password'}
            *******
        {elseif $c_config.type == 'multiple'}
            <ul>
            {foreach from=$c_config.options key="b" item="name"}
                {if $membre->$c & (0x01 << $b)}
                    <li>{$name}</li>







>
>
















|







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

<dl class="describe">
    {foreach from=$champs key="c" item="c_config"}
    <dt>{$c_config.title}</dt>
    <dd>
        {if $c_config.type == 'checkbox'}
            {if $membre->$c}Oui{else}Non{/if}
        {elseif $c_config.type == 'file'}
            {include file="common/files/_context_list.tpl" limit=1 path="%s/%s"|args:$user_files_path,$c}
        {elseif empty($membre->$c)}
            <em>(Non renseigné)</em>
        {elseif $c == $c_config.champ_identite}
            <strong>{$membre->$c}</strong>
        {elseif $c_config.type == 'email'}
            <a href="mailto:{$membre->$c|escape:'url'}">{$membre->$c}</a>
            {if $c == 'email'}
                {linkbutton href="!membres/message.php?id=%d"|args:$membre.id label="Envoyer un message" shape="mail"}
            {/if}
        {elseif $c_config.type == 'tel'}
            <a href="tel:{$membre->$c}">{$membre->$c|format_tel}</a>
        {elseif $c_config.type == 'country'}
            {$membre->$c|get_country_name}
        {elseif $c_config.type == 'date'}
            {$membre->$c|date_short}
        {elseif $c_config.type == 'datetime'}
            {$membre->$c|date}
        {elseif $c_config.type == 'password'}
            *******
        {elseif $c_config.type == 'multiple'}
            <ul>
            {foreach from=$c_config.options key="b" item="name"}
                {if $membre->$c & (0x01 << $b)}
                    <li>{$name}</li>

Modified src/templates/admin/membres/import.tpl from [203c781562] to [dc72822dd3].

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

    {else}

    <fieldset>
        <legend>Importer depuis un fichier</legend>
        <dl>
            <dt><label for="f_file">Fichier à importer</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd class="help">La taille maximale du fichier est de {$max_upload_size|format_bytes}.</dd>
            <dd><input type="file" name="upload" id="f_file" required="required" /></dd>
            <dt><label for="f_type">Type de fichier</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd>
                <input type="radio" name="type" id="f_type" value="garradin" {form_field name=type checked="garradin" default="garradin"} />
                <label for="f_type">Fichier CSV de Garradin</label>
            </dd>
            <dd class="help">







|







26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

    {else}

    <fieldset>
        <legend>Importer depuis un fichier</legend>
        <dl>
            <dt><label for="f_file">Fichier à importer</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd class="help">La taille maximale du fichier est de {$max_upload_size|size_in_bytes}.</dd>
            <dd><input type="file" name="upload" id="f_file" required="required" /></dd>
            <dt><label for="f_type">Type de fichier</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd>
                <input type="radio" name="type" id="f_type" value="garradin" {form_field name=type checked="garradin" default="garradin"} />
                <label for="f_type">Fichier CSV de Garradin</label>
            </dd>
            <dd class="help">

Modified src/templates/admin/membres/index.tpl from [5aaf76eac9] to [ea21066fdc].

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{if !empty($categories)}
<form method="get" action="{$self_url}" class="shortFormRight">
    <fieldset>
        <legend>Filtrer par catégorie</legend>
        <select name="cat" id="f_cat" onchange="this.form.submit();">
            <option value="0" {if $current_cat == 0} selected="selected"{/if}>-- Toutes</option>
        {foreach from=$categories key="id" item="nom"}
            {if $session->canAccess('membres', Membres::DROIT_ECRITURE)
                || !array_key_exists($id, $hidden_categories)}
            <option value="{$id}"{if $current_cat == $id} selected="selected"{/if}>{$nom}</option>
            {/if}
        {/foreach}
        </select>
        <noscript><input type="submit" value="Filtrer &rarr;" /></noscript>
    </fieldset>







|







9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{if !empty($categories)}
<form method="get" action="{$self_url}" class="shortFormRight">
    <fieldset>
        <legend>Filtrer par catégorie</legend>
        <select name="cat" id="f_cat" onchange="this.form.submit();">
            <option value="0" {if $current_cat == 0} selected="selected"{/if}>-- Toutes</option>
        {foreach from=$categories key="id" item="nom"}
            {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)
                || !array_key_exists($id, $hidden_categories)}
            <option value="{$id}"{if $current_cat == $id} selected="selected"{/if}>{$nom}</option>
            {/if}
        {/foreach}
        </select>
        <noscript><input type="submit" value="Filtrer &rarr;" /></noscript>
    </fieldset>
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
                    {if $key == $id_field}</a>{/if}
                </td>
                {/if}
            {/foreach}

            <td class="actions">
                {linkbutton label="Fiche membre" shape="user" href="!membres/fiche.php?id=%d"|args:$row._user_id}
                {if $session->canAccess('membres', Membres::DROIT_ECRITURE)}
                    {linkbutton label="Modifier" shape="edit" href="!membres/modifier.php?id=%d"|args:$row._user_id}
                {/if}
            </td>
        </tr>
    {/foreach}

    </tbody>

    {if $session->canAccess('membres', Membres::DROIT_ADMIN)}
        {include file="admin/membres/_list_actions.tpl" colspan=count($list->getHeaderColumns())+$can_edit+1}
    {/if}

    </table>

    {pagination url=$list->paginationURL() page=$list.page bypage=$list.per_page total=$list->count()}
{else}







|








|







57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
                    {if $key == $id_field}</a>{/if}
                </td>
                {/if}
            {/foreach}

            <td class="actions">
                {linkbutton label="Fiche membre" shape="user" href="!membres/fiche.php?id=%d"|args:$row._user_id}
                {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)}
                    {linkbutton label="Modifier" shape="edit" href="!membres/modifier.php?id=%d"|args:$row._user_id}
                {/if}
            </td>
        </tr>
    {/foreach}

    </tbody>

    {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
        {include file="admin/membres/_list_actions.tpl" colspan=count($list->getHeaderColumns())+$can_edit+1}
    {/if}

    </table>

    {pagination url=$list->paginationURL() page=$list.page bypage=$list.per_page total=$list->count()}
{else}

Modified src/templates/admin/membres/modifier.tpl from [be24573e1c] to [4ea936740e].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{include file="admin/_head.tpl" title="Modifier un membre" current="membres"}

<nav class="tabs">
    <ul>
        <li><a href="{$admin_url}membres/fiche.php?id={$membre.id}">{$membre.identite}</a></li>
        <li class="current"><a href="{$admin_url}membres/modifier.php?id={$membre.id}">Modifier</a></li>
        {if $session->canAccess('membres', Membres::DROIT_ADMIN) && $user.id != $membre.id}
            <li><a href="{$admin_url}membres/supprimer.php?id={$membre.id}">Supprimer</a></li>
        {/if}
    </ul>
</nav>

{form_errors}







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
{include file="admin/_head.tpl" title="Modifier un membre" current="membres"}

<nav class="tabs">
    <ul>
        <li><a href="{$admin_url}membres/fiche.php?id={$membre.id}">{$membre.identite}</a></li>
        <li class="current"><a href="{$admin_url}membres/modifier.php?id={$membre.id}">Modifier</a></li>
        {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN) && $user.id != $membre.id}
            <li><a href="{$admin_url}membres/supprimer.php?id={$membre.id}">Supprimer</a></li>
        {/if}
    </ul>
</nav>

{form_errors}

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
        {if $membre.clef_pgp}
            {input type="checkbox" name="clear_pgp" value="1" label="Supprimer la clé PGP associée au membre"}
        {/if}
        </dl>
    </fieldset>
    {/if}

    {if $session->canAccess('membres', Membres::DROIT_ADMIN) && $user.id != $membre.id}
    <fieldset>
        <legend>Général</legend>
        <dl>
            <dt><label for="f_cat">Catégorie du membre</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd>
                <select name="id_categorie" id="f_cat">
                {foreach from=$membres_cats key="id" item="nom"}
                    <option value="{$id}"{if $current_cat == $id} selected="selected"{/if}>{$nom}</option>
                {/foreach}
                </select>
            </dd>
        </dl>
    </fieldset>







|





|







60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
        {if $membre.clef_pgp}
            {input type="checkbox" name="clear_pgp" value="1" label="Supprimer la clé PGP associée au membre"}
        {/if}
        </dl>
    </fieldset>
    {/if}

    {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN) && $user.id != $membre.id}
    <fieldset>
        <legend>Général</legend>
        <dl>
            <dt><label for="f_cat">Catégorie du membre</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd>
                <select name="id_category" id="f_cat">
                {foreach from=$membres_cats key="id" item="nom"}
                    <option value="{$id}"{if $current_cat == $id} selected="selected"{/if}>{$nom}</option>
                {/foreach}
                </select>
            </dd>
        </dl>
    </fieldset>

Modified src/templates/admin/membres/recherche.tpl from [5a5c80b31f] to [7ed26a1626].

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
{include file="admin/_head.tpl" title="Recherche de membre" current="membres" custom_js=['query_builder.min.js']}

{include file="admin/membres/_nav.tpl" current="recherche"}

{include file="common/search/advanced.tpl" action_url=$self_url}

{if !empty($result)}
	{if $session->canAccess('membres', Membres::DROIT_ECRITURE)}
		<form method="post" action="{$admin_url}membres/action.php" class="memberList">
	{/if}

	<p class="help">{$result|count} membres trouvés pour cette recherche.</p>
	<table class="list search">
		<thead>
			<tr>
				{if $session->canAccess('membres', Membres::DROIT_ADMIN)}<td class="check"><input type="checkbox" value="Tout cocher / décocher" id="f_all" /><label for="f_all"></label></td>{/if}
				{foreach from=$result_header item="label"}
					<td>{$label}</td>
				{/foreach}
				<td></td>
			</tr>
		</thead>
		<tbody>
			{foreach from=$result item="row"}
				<tr>
					{if $session->canAccess('membres', Membres::DROIT_ADMIN)}<td class="check">{if $row._user_id}{input type="checkbox" name="selected[]" value=$row._user_id}{/if}</td>{/if}
					{foreach from=$row key="key" item="value"}
						<?php $link = false; ?>
						{if isset($result_header[$key])}
							<td>
							{if !$link && $row._user_id}
								<a href="{$admin_url}membres/fiche.php?id={$row._user_id}">
							{/if}







|







|









|







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
{include file="admin/_head.tpl" title="Recherche de membre" current="membres" custom_js=['query_builder.min.js']}

{include file="admin/membres/_nav.tpl" current="recherche"}

{include file="common/search/advanced.tpl" action_url=$self_url}

{if !empty($result)}
	{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)}
		<form method="post" action="{$admin_url}membres/action.php" class="memberList">
	{/if}

	<p class="help">{$result|count} membres trouvés pour cette recherche.</p>
	<table class="list search">
		<thead>
			<tr>
				{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}<td class="check"><input type="checkbox" value="Tout cocher / décocher" id="f_all" /><label for="f_all"></label></td>{/if}
				{foreach from=$result_header item="label"}
					<td>{$label}</td>
				{/foreach}
				<td></td>
			</tr>
		</thead>
		<tbody>
			{foreach from=$result item="row"}
				<tr>
					{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}<td class="check">{if $row._user_id}{input type="checkbox" name="selected[]" value=$row._user_id}{/if}</td>{/if}
					{foreach from=$row key="key" item="value"}
						<?php $link = false; ?>
						{if isset($result_header[$key])}
							<td>
							{if !$link && $row._user_id}
								<a href="{$admin_url}membres/fiche.php?id={$row._user_id}">
							{/if}
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
						{elseif substr($key, 0, 1) != '_'}
							<td>{$value}</td>
						{/if}
					{/foreach}
					<td class="actions">
						{if $row._user_id}
							{linkbutton shape="user" label="Fiche membre" href="!membres/fiche.php?id=%d"|args:$row._user_id}
							{if $session->canAccess('membres', Membres::DROIT_ECRITURE)}
								{linkbutton shape="edit" label="Modifier" href="!membres/modifier.php?id=%d"|args:$row._user_id}
							{/if}
						{/if}
					</td>
				</tr>
			{/foreach}
		</tbody>
	{if $session->canAccess('membres', Membres::DROIT_ADMIN) && $row._user_id}
		{include file="admin/membres/_list_actions.tpl" colspan=count($result_header)+1}
	{/if}
	</table>

	{if $session->canAccess('membres', Membres::DROIT_ECRITURE)}
		</form>
	{/if}

{elseif $result !== null}

	<p class="block alert">
		Aucun membre trouvé.







|







|




|







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
						{elseif substr($key, 0, 1) != '_'}
							<td>{$value}</td>
						{/if}
					{/foreach}
					<td class="actions">
						{if $row._user_id}
							{linkbutton shape="user" label="Fiche membre" href="!membres/fiche.php?id=%d"|args:$row._user_id}
							{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)}
								{linkbutton shape="edit" label="Modifier" href="!membres/modifier.php?id=%d"|args:$row._user_id}
							{/if}
						{/if}
					</td>
				</tr>
			{/foreach}
		</tbody>
	{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN) && $row._user_id}
		{include file="admin/membres/_list_actions.tpl" colspan=count($result_header)+1}
	{/if}
	</table>

	{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)}
		</form>
	{/if}

{elseif $result !== null}

	<p class="block alert">
		Aucun membre trouvé.

Modified src/templates/admin/membres/selector.tpl from [6df59fc8ca] to [d560c1b60a].

1
2
3
4
5
6
7
8
9
10
{include file="admin/_head.tpl" title="Sélectionner un compte" body_id="popup" is_popup=true}

<form method="get" action="{$self_url_no_qs}">
	<h2 class="ruler">
		<input type="text" placeholder="Recherche rapide de membre" value="{$query}" name="q" />
		<input type="submit" value="Chercher &rarr;" />
	</h2>
</form>

<table class="list">
|

|







1
2
3
4
5
6
7
8
9
10
{include file="admin/_head.tpl" title="Sélectionner un compte"}

<form method="post" action="{$self_url}">
	<h2 class="ruler">
		<input type="text" placeholder="Recherche rapide de membre" value="{$query}" name="q" />
		<input type="submit" value="Chercher &rarr;" />
	</h2>
</form>

<table class="list">

Modified src/templates/admin/membres/supprimer.tpl from [82816cbfa7] to [9188bf5497].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{include file="admin/_head.tpl" title="Supprimer un membre" current="membres"}

<nav class="tabs">
    <ul>
        <li><a href="{$admin_url}membres/fiche.php?id={$membre.id}">{$membre.identite}</a></li>
        <li><a href="{$admin_url}membres/modifier.php?id={$membre.id}">Modifier</a></li>
        {if $session->canAccess('membres', Membres::DROIT_ADMIN)}
            <li class="current"><a href="{$admin_url}membres/supprimer.php?id={$membre.id}">Supprimer</a></li>
        {/if}
    </ul>
</nav>

{form_errors}







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
{include file="admin/_head.tpl" title="Supprimer un membre" current="membres"}

<nav class="tabs">
    <ul>
        <li><a href="{$admin_url}membres/fiche.php?id={$membre.id}">{$membre.identite}</a></li>
        <li><a href="{$admin_url}membres/modifier.php?id={$membre.id}">Modifier</a></li>
        {if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
            <li class="current"><a href="{$admin_url}membres/supprimer.php?id={$membre.id}">Supprimer</a></li>
        {/if}
    </ul>
</nav>

{form_errors}

Modified src/templates/admin/mes_infos_securite.tpl from [99becf7d6d] to [f732fceed2].

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    </form>
{else}

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

        <fieldset>
            <legend>Changer mon mot de passe</legend>
            {if $user.droit_membres < Membres::DROIT_ADMIN && (!empty($champs.passe.private) || empty($champs.passe.editable))}
                <p class="help">Vous devez contacter un administrateur pour changer votre mot de passe.</p>
            {else}
                <dl>
                    <dd>Vous avez déjà un mot de passe, ne remplissez les champs suivants que si vous souhaitez en changer.</dd>
                    <dt><label for="f_passe">Nouveau mot de passe</label> (minimum {$password_length} caractères)</dt>
                    <dd class="help">
                        Astuce : un mot de passe de quatre mots choisis au hasard dans le dictionnaire est plus sûr 







|







65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    </form>
{else}

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

        <fieldset>
            <legend>Changer mon mot de passe</legend>
            {if $user.droit_membres < $session::ACCESS_ADMIN && (!empty($champs.passe.private) || empty($champs.passe.editable))}
                <p class="help">Vous devez contacter un administrateur pour changer votre mot de passe.</p>
            {else}
                <dl>
                    <dd>Vous avez déjà un mot de passe, ne remplissez les champs suivants que si vous souhaitez en changer.</dd>
                    <dt><label for="f_passe">Nouveau mot de passe</label> (minimum {$password_length} caractères)</dt>
                    <dd class="help">
                        Astuce : un mot de passe de quatre mots choisis au hasard dans le dictionnaire est plus sûr 

Deleted src/templates/admin/wiki/_chercher_parent.tpl version [8f5769baca].

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
{include file="admin/_head.tpl" title="Choisir la page parent" current="wiki" body_id="popup" is_popup=true}

<div class="wikiTree">
    <p class="choice">
        <input type="button" onclick="chooseParent();" value="Choisir la page sélectionnée" />
    </p>

    {display_tree tree=$list}

</div>

{literal}
<script type="text/javascript">
(function() {
    window.chooseParent = function()
    {
        var elm = document.getElementsByClassName("current")[0].getElementsByTagName("a")[0];

        if (match = elm.href.match(/=(\d+)$/))
        {
            var id = parseInt(match[1], 10);
            var titre = (id == 0 ? 'la racine du site' : elm.innerHTML);

            if (window.opener.changeParent(id, titre))
            {
                self.close();
            }
            else
            {
                alert("Impossible de choisir la page comme parent d'elle-même !");
            }

            return false;
        }
    };
}());
</script>
{/literal}

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































Deleted src/templates/admin/wiki/_fichiers.tpl version [528fa66749].

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
{include file="admin/_head.tpl" title="Inclure un fichier" current="wiki" body_id="transparent" is_popup=true}

{form_errors}

<form method="post" enctype="multipart/form-data" action="{$self_url}" id="f_upload">
    <fieldset>
        <legend>Téléverser un fichier</legend>
        <input type="hidden" name="MAX_FILE_SIZE" value="{$max_size}" id="f_maxsize" />
        <dl>
            <dd class="help">Taille maximale : {$max_size|format_bytes}</dd>
            <dd class="fileUpload"><input type="file" name="fichier" id="f_fichier" data-hash-check /></dd>
        </dl>
        <p class="submit">
            {csrf_field key=$csrf_id}
            {button type="submit" name="upload" label="Envoyer le fichier" shape="upload" class="main" id="f_submit"}
        </p>
    </fieldset>
</form>

<form method="get" action="#" style="display: none;" id="insertImage">
    <fieldset>
        <h3>Insérer une image dans le texte</h3>
        <dl>
            <dd class="image"></dd>
            <dt>Légende <i>(facultatif)</i></dt>
            <dd class="caption">
                <input type="text" name="f_caption" size="50" />
            </dd>
            <dt>Alignement&nbsp;:</dt>
            <dd class="align">
                <input type="button" name="gauche" value="À gauche" />
                <input type="button" name="centre" value="Au centre" />
                <input type="button" name="droite" value="À droite" />
            </dd>
            <dd class="cancel">
                <input type="reset" value="Annuler" />
            </dd>
        </dl>
    </fieldset>
</form>

{if !empty($images)}
<ul class="gallery">
{foreach from=$images item="file"}
    <li>
        <figure>
            <a href="{$file.url}" data-id="{$file.id}"><img src="{$file.thumb}" alt="" title="{$file.nom}" /></a>
            <form class="actions" method="post" action="{$self_url}">
                {linkbutton shape="download" label="Télécharger" href=$file.url target="_blank"}
                {csrf_field key=$csrf_id}
                <input type="hidden" name="delete" value="{$file.id}" />
                <noscript><input type="submit" value="Supprimer" /></noscript>
            </form>
        </figure>
    </li>
{/foreach}
</ul>
{/if}

{if !empty($fichiers)}
<table class="list">
    <tbody>
    {foreach from=$fichiers item="file"}
        <tr>
            <th>{$file.nom}</th>
            <td>{if $file.type}{$file.type}{/if}</td>
            <td class="actions">
                <form class="actions" method="post" action="{$self_url}">
                    {linkbutton shape="download" label="Télécharger" href=$file.url target="_blank"}
                    {csrf_field key=$csrf_id}
                    <input type="hidden" name="delete" value="{$file.id}" />
                    <noscript><input type="submit" value="Supprimer" /></noscript>
                </form>
            </td>
        </tr>
    {/foreach}
    </tbody>
</table>
{/if}

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































Deleted src/templates/admin/wiki/_preview.tpl version [1c9551975d].

1
2
3
4
5
6
7
{include file="admin/_head.tpl" title="Wiki" current="wiki" is_popup=1 body_id="transparent"}

<div class="wikiContent">
{$contenu|raw|format_wiki|liens_wiki:'#'}
</div>

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<














Deleted src/templates/admin/wiki/chercher.tpl version [b5b27035db].

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
{include file="admin/_head.tpl" title="Recherche" current="wiki/chercher"}

<form method="get" action="{$admin_url}wiki/chercher.php" class="wikiSearch">
    <fieldset>
        <legend>Rechercher une page</legend>
        <p class="submit">
            <input type="text" name="q" value="{$recherche}" size="25" />
            {button type="submit" name="search" label="Chercher" shape="search" class="main"}
        </p>
    </fieldset>
</form>


{if !$recherche}
    <p class="block alert">
        Aucun terme recherché.
    </p>
{else}
    <p class="block alert">
        <strong>{$nb_resultats}</strong> pages trouvées pour «&nbsp;{$recherche}&nbsp;»
    </p>

    <div class="wikiResults">
    {foreach from=$resultats item="page"}
        <h3><a href="./?{$page.uri}">{$page.titre}</a></h3>
        <p>{$page.snippet|escape|clean_snippet}</p>
    {/foreach}
    </div>
{/if}

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































Deleted src/templates/admin/wiki/creer.tpl version [e927f05760].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{include file="admin/_head.tpl" title="Créer une page" current="wiki"}

{form_errors}

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

    <fieldset>
        <legend>Informations</legend>
        <dl>
            <dt><label for="f_titre">Titre</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd><input type="text" name="titre" id="f_titre" value="{form_field name=titre}" /></dd>
        </dl>
    </fieldset>

    <p class="submit">
        {csrf_field key="wiki_create"}
        {button type="submit" name="create" label="Créer cette page" shape="right" class="main"}
    </p>

</form>


{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































Deleted src/templates/admin/wiki/editer.tpl version [fa476c25ad].

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
{include file="admin/_head.tpl" title="Éditer une page" current="wiki"}

{form_errors}

<form method="post" action="{$self_url}" id="f_form">

    <fieldset class="wikiMain">
        <legend>Informations générales</legend>
        <dl>
            <dt><label for="f_titre">Titre</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd><input type="text" name="titre" id="f_titre" value="{form_field data=$page name=titre}" required="required" /></dd>
            <dt><label for="f_uri">Adresse unique</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd class="help">
                Ne peut comporter que des lettres, des chiffres, des tirets et des tirets bas.
            </dd>
            <dd><input type="text" name="uri" id="f_uri" value="{form_field data=$page name=uri}" required="required" /></dd>
            <dt><label for="f_browse_parent">Cette page est une sous-rubrique de...</label></dt>
            <dd>
                <input type="hidden" name="parent" id="f_parent" value="{form_field data=$page name=parent}" />
                {if $page.parent == 0}
                    <samp id="current_parent_name">la racine du site</samp>
                {else}
                    <samp id="current_parent_name">{$parent}</samp>
                {/if}
                <input type="button" id="f_browse_parent" onclick="browseWikiForParent();" value="Changer" />
            </dd>
            <dt><label for="f_date">Date</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
            <dd>
                <input type="date" size="10" name="date" id="f_date" value="{$date|date_fr:'Y-m-d'}" pattern="{literal}^\d{4}-\d{2}-\d{2}${/literal}" required="required" />
                <input type="text" class="time" size="2" name="date_h" value="{$date|date_fr:'H'}" pattern="^{literal}\d{1,2}${/literal}" required="required" /> h
                <input type="text" class="time" size="2" name="date_min" value="{$date|date_fr:'i'}" pattern="{literal}^\d{1,2}${/literal}" required="required" />
            </dd>
        </dl>
    </fieldset>

    <fieldset class="wikiRights">
        <legend>Droits d'accès</legend>
        <dl>
            <dt><label for="f_droit_lecture_public">Cette page est visible :</label></dt>
            <dd>
                <input type="radio" name="droit_lecture" id="f_droit_lecture_public" value="{$wiki::LECTURE_PUBLIC}" {form_field data=$page name="droit_lecture" checked=$wiki::LECTURE_PUBLIC} />
                <label for="f_droit_lecture_public"><strong>Sur le site de l'association</strong></label>
                &mdash; cette page apparaîtra sur le site public de l'association, accessible à tous les visiteurs
            </dd>
            <dd>
                <input type="radio" name="droit_lecture" id="f_droit_lecture_normal" value="{$wiki::LECTURE_NORMAL}"  {form_field data=$page name="droit_lecture" checked=$wiki::LECTURE_NORMAL} />
                <label for="f_droit_lecture_normal"><strong>Sur le wiki uniquement</strong></label>
                &mdash; seuls les membres ayant accès au wiki pourront la voir
            </dd>
            <dd>
                <input type="radio" name="droit_lecture" id="f_droit_lecture_categorie" value="{$user.id_categorie}"  {if $page.droit_lecture >= $wiki::LECTURE_CATEGORIE}checked="checked"{/if} />
                <label for="f_droit_lecture_categorie"><strong>Aux membres de ma catégorie</strong></label>
                &mdash; seuls les membres de la même catégorie que moi pourront voir cette page
            </dd>
            <dt><label for="f_droit_ecriture_normal">Cette page peut être modifiée par :</label></dt>
            <dd>
                <input type="radio" name="droit_ecriture" id="f_droit_ecriture_normal" value="{$wiki::ECRITURE_NORMAL}" {form_field data=$page name="droit_ecriture" checked=$wiki::ECRITURE_NORMAL} {if $page.droit_lecture >= $wiki::LECTURE_CATEGORIE}disabled="disabled"{/if} />
                <label for="f_droit_ecriture_normal">Les membres qui ont accès au wiki en écriture</label>
            </dd>
            <dd>
                <input type="radio" name="droit_ecriture" id="f_droit_ecriture_categorie" value="{$user.id_categorie}" {if $page.droit_ecriture >= $wiki::ECRITURE_CATEGORIE || $page.droit_lecture >= $wiki::LECTURE_CATEGORIE}checked="checked"{/if} {if $page.droit_lecture >= $wiki::LECTURE_CATEGORIE}disabled="disabled"{/if} />
                <label for="f_droit_ecriture_categorie">Les membres de ma catégorie</label>
            </dd>
        </dl>
    </fieldset>

    <fieldset class="wikiEncrypt">
        <dl>
            <dt>
                <input type="checkbox" name="chiffrement" id="f_chiffrement" {form_field name=chiffrement data=$page default=0 checked=1} value="1" onchange="checkEncryption(this);" />
                <label for="f_chiffrement">Chiffrer le contenu</label> <i>(facultatif)</i>
            </dt>
            <noscript>
            <dd>Nécessite JavaScript activé pour fonctionner !</dd>
            </noscript>
            <dd>Mot de passe : <i id="encryptPasswordDisplay" title="Chiffrement désactivé">désactivé</i></dd>
            <dd class="help">Le mot de passe n'est ni transmis ni enregistré, vous seul le connaissez,
                il n'est pas possible de retrouver le contenu si vous l'oubliez.</dd>
        </dl>
    </fieldset>


    <fieldset class="wikiText">
        <div class="textEditor">
            <textarea name="contenu" id="f_contenu" cols="70" rows="35">{form_field data=$page name=contenu}</textarea>
        </div>
    </fieldset>

    <fieldset class="wikiRevision">
        <dl>
            <dt><label for="f_modification">Résumé des modifications</label>  <i>(facultatif)</i></dt>
            <dd><input type="text" name="modification" id="f_modification" value="{form_field data=$page name=modification}" /></dd>
            {* FIXME
            <dt>
                <input type="checkbox" name="suivi" value="1" id="f_suivi" />
                <label for="f_suivi">Suivre les modifications de cette page</label>
            </dt>
            *}
        </dl>
    </fieldset>

    <p class="submit">
        {csrf_field key="wiki_edit_%d"|args:$page.id}
        <input type="hidden" name="revision_edition" value="{form_field name=revision_edition default=$page.revision}" />
        <input type="hidden" name="debut_edition" value="{form_field name=debut_edition default=$time}" />
        <input id="f_id" value="{$page.id}" type="hidden" />
        {button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
    </p>

</form>

<script type="text/javascript">
var page_id = '{$page.id}';
{literal}
(function() {
    $('#f_droit_lecture_categorie').onchange = function()
    {
        $('#f_droit_ecriture_normal').checked = false;
        $('#f_droit_ecriture_normal').disabled = true;

        $('#f_droit_ecriture_categorie').checked = true;
        $('#f_droit_ecriture_categorie').disabled = true;
    };

    $('#f_droit_lecture_normal').onchange = function() {
        $('#f_droit_ecriture_normal').disabled = false;
        $('#f_droit_ecriture_categorie').disabled = false;
    };

    $('#f_droit_lecture_public').onchange = function() {
        $('#f_droit_ecriture_normal').disabled = false;
        $('#f_droit_ecriture_categorie').disabled = false;
    };

    window.changeParent = function(parent, title)
    {
        if (parent == page_id)
        {
            return false;
        }

        $('#f_parent').value = parent;
        $('#current_parent_name').innerHTML = title;
        return true;
    };

    window.browseWikiForParent = function()
    {
        window.open('_chercher_parent.php?parent=' + $('#f_parent').value, 'browseParent',
            'width=500,height=600,top=150,left=150,scrollbars=1,location=false');
    };

    if ($('#f_chiffrement').checked)
    {
        wikiDecrypt(true);
    }
}());
</script>
{/literal}

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































































































Deleted src/templates/admin/wiki/historique.tpl version [ad74fa04e5].

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
{include file="admin/_head.tpl" title="Historique : %s"|args:$page.titre current="wiki"}

<nav class="tabs">
    <ul>
        <li><a href="{$admin_url}wiki/?{$page.uri}">Retour à la page</a></li>
    </ul>
</nav>

{if !empty($revisions)}
    <table class="list wikiRevisions">
    {foreach from=$revisions item="rev"}
        <tr>
            <td>
                {if $rev.chiffrement}
                    <del title="Contenu chiffré">chiffré</del>
                {else}
                    {if $rev.revision == $page.revision}
                        actu
                    {else}
                        <a href="?id={$page.id}&amp;diff={$rev.revision}.{$page.revision}">actu</a>
                    {/if}
                    |
                    {if $rev.revision == 1}
                        diff
                    {else}
                        <a href="?id={$page.id}&amp;diff={$rev.revision-1}.{$rev.revision}">diff</a>
                    {/if}
                {/if}
            </td>
            <th>{$rev.date|date_long}</th>
            <td>
                {if $session->canAccess('membres', Membres::DROIT_ACCES)}
                <a href="{$admin_url}membres/fiche.php?id={$rev.id_auteur}">{$rev.nom_auteur}</a>
                {/if}
            </td>
            <td class="length">
                {$rev.taille} octets
                {if $rev.revision > 1 && !$rev.chiffrement}
                    {if $rev.diff_taille > 0}
                        <ins>(+{$rev.diff_taille})</ins>
                    {elseif $rev.diff_taille < 0}
                        <del>({$rev.diff_taille})</del>
                    {else}
                        <i>({$rev.diff_taille})</i>
                    {/if}
                {/if}
            </td>
            <td>
            {if $rev.modification}
                <em>{$rev.modification}</em>
            {/if}
            </td>
        </tr>
    {/foreach}
    </table>
{elseif !empty($diff)}
    <div class="wikiRevision revisionLeft">
        <h3>Version du {$rev1.date|date_long}</h3>
        {if $session->canAccess('membres', Membres::DROIT_ACCES)}
            <h4>De <a href="{$admin_url}membres/fiche.php?id={$rev1.id_auteur}">{$rev1.nom_auteur}</a></h4>
        {/if}
        {if $rev1.modification}
            <p><em>{$rev1.modification}</em></p>
        {/if}
    </div>
    <div class="wikiRevision revisionRight">
        <h3>Version {if $rev2.revision == $page.revision}actuelle en date{/if} du {$rev2.date|date_long}</h3>
        {if $session->canAccess('membres', Membres::DROIT_ACCES)}
            <h4>De <a href="{$admin_url}membres/fiche.php?id={$rev2.id_auteur}">{$rev2.nom_auteur}</a></h4>
        {/if}
        {if $rev2.modification}
            <p><em>{$rev2.modification}</em></p>
        {/if}
    </div>
    {diff old=$rev1.contenu new=$rev2.contenu}
{else}
    <p class="block alert">
        Cette page n'a pas d'historique.
    </p>
{/if}


{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































































Deleted src/templates/admin/wiki/page.tpl version [fc2fcb0602].

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
{if !empty($page.titre) && $can_read}
    {include file="admin/_head.tpl" title=$page.titre current="wiki"}
{else}
    {include file="admin/_head.tpl" title="Wiki" current="wiki"}
{/if}

<nav class="tabs">
    <ul>
        {if $session->canAccess('wiki', Membres::DROIT_ECRITURE)}
            <li><a href="{$admin_url}wiki/creer.php?parent={if $page && $config.accueil_wiki != $page.uri}{$page.id}{else}0{/if}"><strong>Créer une nouvelle page</strong></a></li>
        {/if}
        {if $can_edit}
            <li><a href="{$admin_url}wiki/editer.php?id={$page.id}">Éditer</a></li>
        {/if}
        {if $can_read && $page && $page.contenu}
            <li><a href="{$admin_url}wiki/historique.php?id={$page.id}">Historique</a></li>
            {if $page.droit_lecture == Wiki::LECTURE_PUBLIC}
                <li><a href="{$www_url}{$page.uri}{if $has_public_children}/{/if}">Voir sur le site</a></li>
            {/if}
        {/if}
        {if $can_edit && $session->canAccess('wiki', Membres::DROIT_ADMIN)}
            <li><a href="{$admin_url}wiki/supprimer.php?id={$page.id}">Supprimer</a></li>
        {/if}
    </ul>
</nav>

{if !$can_read}
    <p class="block alert">Vous n'avez pas le droit de lire cette page.</p>
{else}
    <div class="breadCrumbs">
        <ul>
            <li><a href="./">Wiki</a></li>
            {if !empty($breadcrumbs)}
            {foreach from=$breadcrumbs item="crumb"}
            <li><a href="?{$crumb.uri}">{$crumb.titre}</a></li>
            {/foreach}
            {/if}
        </ul>
    </div>

    {if !$page}
        <p class="block error">
            Cette page n'existe pas.
        </p>

        {if $can_edit}
        <form method="post" action="{$admin_url}wiki/creer.php">
            <p class="submit">
                {csrf_field key="wiki_create"}
                <input type="hidden" name="titre" value="{$uri}" />
                {button type="submit" name="create" label="Créer cette page" shape="right" class="main"}
            </p>
        </form>
        {/if}
    {else}

        {if !empty($children)}
        <div class="wikiChildren">
            <h4>Dans cette rubrique</h4>
            <ul>
            {foreach from=$children item="child"}
                <li><a href="?{$child.uri}">{$child.titre}</a></li>
            {/foreach}
            </ul>
        </div>
        {/if}

        {if !$page.contenu}
            <p class="block alert">Cette page est vide, cliquez sur « Éditer » pour la modifier.</p>
        {else}

            {if $page.contenu.chiffrement}
                <noscript>
                    <div class="error">
                        Vous dever activer javascript pour pouvoir déchiffrer cette page.
                    </div>
                </noscript>
                <script type="text/javascript" src="{$admin_url}static/scripts/wiki-encryption.js"></script>
                <div id="wikiEncryptedMessage">
                    <p class="block alert">Cette page est chiffrée.
                        <input type="button" onclick="return wikiDecrypt(false);" value="Entrer le mot de passe" />
                    </p>
                </div>
                <div class="wikiContent" style="display: none;" id="wikiEncryptedContent">
                    {$page.contenu.contenu}
                </div>
            {else}
                <div class="wikiContent">
                    {$page.contenu.contenu|raw|format_wiki|liens_wiki:'?'}
                </div>
            {/if}


            {if !empty($images) || !empty($fichiers)}
            <div class="wikiFiles">
                <h3>Fichiers liés à cette page</h3>

                {if !empty($images)}
                <ul class="gallery">
                    {foreach from=$images item="file"}
                        <li>
                            <figure>
                                <a class="internal-image" href="{$file.url}"><img src="{$file.thumb}" alt="" title="{$file.nom}" /></a>
                            </figure>
                        </li>
                    {/foreach}
                </ul>
                {/if}

                {if !empty($fichiers)}
                <ul class="files">
                    {foreach from=$fichiers item="file"}
                        <li>
                            <aside class="fichier" class="internal-file"><a href="{$file.url}">{$file.nom}</a>
                            <small>({$file.type}, {$file.taille|format_bytes})</small></aside>
                       </li>
                    {/foreach}
                </ul>
                {/if}
            </div>
            {/if}

            <p class="wikiFooter">
                Dernière modification le {$page.date_modification|date_long}
                {if $session->canAccess('membres', Membres::DROIT_ACCES)}
                par <a href="{$admin_url}membres/fiche.php?id={$page.contenu.id_auteur}">{$auteur}</a>
                {/if}
            </p>
        {/if}
    {/if}
{/if}


{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































Deleted src/templates/admin/wiki/recent.tpl version [b616432b4b].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{include file="admin/_head.tpl" title="Pages modifiées récemment" current="wiki/recent"}

{if !empty($list)}
    <table class="list">
        <tbody>
        {foreach from=$list item="page"}
        <tr>
            <th><a href="{$admin_url}wiki/?{$page.uri}">{$page.titre}</a></th>
            <td>{$page.date_modification|date_long}</td>
        </tr>
        {/foreach}
        </tbody>
    </table>

    {pagination url="?p=[ID]" page=$current_page bypage=$bypage total=$total}
{else}
    <p class="block alert">Pas de modification récente.</p>
{/if}

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































Deleted src/templates/admin/wiki/supprimer.tpl version [0d139503af].

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
{include file="admin/_head.tpl" title="Supprimer : %s"|args:$page.titre current="wiki"}

<nav class="tabs">
    <ul>
        <li><a href="{$admin_url}wiki/"><strong>Wiki</strong></a></li>
        <li><a href="{$admin_url}wiki/chercher.php">Rechercher</a></li>
        <li><a href="{$admin_url}wiki/?{$page.uri}">Voir la page</a></li>
        <li><a href="{$admin_url}wiki/editer.php?id={$page.id}">Éditer</a></li>
    </ul>
</nav>

{form_errors}

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

    <fieldset>
        <legend>Supprimer cette page du wiki ?</legend>
        <h3 class="warning">
            Êtes-vous sûr de vouloir supprimer la page «&nbsp;{$page.titre}&nbsp;» ?
        </h3>
        <p class="help">
            La page ne pourra pas être supprimée si d'autres pages l'utilisent comme rubrique
            parente.
        </p>
    </fieldset>

    <p class="submit">
        {csrf_field key="delete_wiki_"|cat:$page.id}
        {button type="submit" name="delete" label="Supprimer" shape="right" class="main"}
    </p>

</form>

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































Deleted src/templates/common/delete_file.tpl version [42a5f97ba7].

1
2
3
4
5
6
7
8
{include file="admin/_head.tpl" title="Supprimer un fichier" current=null}

{include file="common/delete_form.tpl"
	legend="Supprimer ce fichier ?"
	warning="Êtes-vous sûr de vouloir supprimer le fichier « %s » ?"|args:$file.nom
}

{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
















Modified src/templates/common/delete_form.tpl from [089a0cfbe1] to [1a5247d599].

1
2
3
4
5
6
7
8
9
10
{form_errors}

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

	<fieldset>
		<legend>{$legend}</legend>
		<h3 class="warning">
			{$warning}
		</h3>
		{if isset($alert)}


|







1
2
3
4
5
6
7
8
9
10
{form_errors}

<form method="post" action="{$self_url}" data-focus="1">

	<fieldset>
		<legend>{$legend}</legend>
		<h3 class="warning">
			{$warning}
		</h3>
		{if isset($alert)}

Added src/templates/common/files/_context_list.tpl version [7492d35a51].

















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
assert(isset($path) || isset($can_upload, $files, $path));

if (!isset($files, $can_upload)) {
	$files = Files\Files::list($path);
	$can_upload = (!isset($limit) || count($files) < $limit) && Entities\Files\File::checkCreateAccess($path, $session);
}
?>

{if $can_upload}
<p class="actions">
	{linkbutton shape="upload" href="!common/files/upload.php?p=%s"|args:$path target="_dialog" label="Ajouter un fichier"}
</p>
{/if}

<div class="files-list">
{foreach from=$files item="file"}
	{if !$file->checkReadAccess($session)}
		<?php break; ?>
	{/if}
	<aside class="file">
		{if $file.image}
			<figure>
				<a target="_blank" href="{$file->url()}"><img src="{$file->thumb_url()}" alt="" /></a>
				<figcaption>
					<a target="_blank" href="{$file->url()}">{$file.name}</a>
					<small>({$file.mime}, {$file.size|size_in_bytes})</small>
				</figcaption>
			</figure>
		{else}
			<a target="_blank" href="{$file->url()}">{$file.name}</a>
			<small>({$file.mime}, {$file.size|size_in_bytes})</small>
		{/if}
		{linkbutton shape="download" href=$file->url(true) target="_blank" label="Télécharger"}
		{if $file->checkDeleteAccess($session)}
			{linkbutton shape="delete" target="_dialog" href="!common/files/delete.php?p=%s"|args:$file.path label="Supprimer"}
		{/if}
	</aside>
{/foreach}
</div>

Added src/templates/common/files/_file_render_encrypted.tpl version [b283e35b3f].





























>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<noscript>
	<div class="error">
		Vous dever activer javascript pour pouvoir déchiffrer cette page.
	</div>
</noscript>
<script type="text/javascript" src="{$admin_url}static/scripts/wiki-encryption.js"></script>
<div id="wikiEncryptedMessage">
	<p class="block alert">Cette page est chiffrée.
		<input type="button" onclick="return wikiDecrypt(false);" value="Entrer le mot de passe" />
	</p>
</div>
<div class="web-content" style="display: none;" id="wikiEncryptedContent">
	{$content}
</div>

Added src/templates/common/files/_preview.tpl version [d04060e5dd].











>
>
>
>
>
1
2
3
4
5
{include file="admin/_head.tpl" title=$file.name custom_css=['/content.css'] transparent=true}

{$content|raw}

{include file="admin/_foot.tpl"}

Added src/templates/common/files/delete.tpl version [6b7ff711ef].

































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{include file="admin/_head.tpl" title="Supprimer un fichier" current=null}

{if $file.type == $file::TYPE_DIRECTORY}
	{include file="common/delete_form.tpl"
		legend="Supprimer ce répertoire ?"
		warning="Êtes-vous sûr de vouloir supprimer le répertoire « %s » ?"|args:$file.name
		alert="Tous les sous-répertoires et fichiers de ce répertoire seront supprimés !"
	}
{else}
	{include file="common/delete_form.tpl"
		legend="Supprimer ce fichier ?"
		warning="Êtes-vous sûr de vouloir supprimer le fichier « %s » ?"|args:$file.name
	}
{/if}

{include file="admin/_foot.tpl"}

Added src/templates/common/files/edit_code.tpl version [bf7571f93a].



































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{include file="admin/_head.tpl" title="Édition de fichier"}

<form method="post" action="{$self_url}">
	<p>
		{input type="textarea" name="content" cols="90" rows="50" default=$content}
	</p>

	<p class="submit">
		{csrf_field key=$csrf_key}
		{button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
	</p>

</form>

<script type="text/javascript" src="{$admin_url}static/scripts/code_editor.js"></script>

{include file="admin/_foot.tpl"}

Added src/templates/common/files/edit_web.tpl version [1178627620].































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{include file="admin/_head.tpl" title="Édition de fichier" custom_js=['wiki_editor.js']}

<form method="post" action="{$self_url}">
	<p class="textEditor">
		{input type="textarea" name="content" cols="70" rows="30" default=$content data-preview-url="!common/files/_preview.php?f=%s"|local_url|args:$file.parent data-fullscreen="1" data-attachments="0" data-savebtn="1"}
	</p>

	<p class="submit">
		{csrf_field key=$csrf_key}
		{button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
	</p>

</form>

{include file="admin/_foot.tpl"}

Added src/templates/common/files/upload.tpl version [7265a3906f].





































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{include file="admin/_head.tpl" title="Envoi de fichier"}

{form_errors}

<form method="post" action="{$self_url}" enctype="multipart/form-data" data-focus="1">
	<fieldset>
		<legend>Téléverser un fichier</legend>
		<dl>
			{input type="file" name="file" required="required" label="Fichier à envoyer"}
		</dl>
		<p class="submit">
			{csrf_field key=$csrf_key}
			{button type="submit" name="upload" label="Envoyer le fichier" shape="upload" class="main"}
		</p>
	</fieldset>
</form>

{include file="admin/_foot.tpl"}

Modified src/templates/common/search/advanced.tpl from [8f33333af3] to [4a40d92d55].

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
<?php
assert(isset($columns));
assert(isset($action_url));
assert(isset($query));
assert(isset($is_admin));
$sql_disabled = !$is_admin || (!$session->canAccess('config', Membres::DROIT_ADMIN) && $is_unprotected);
?>

{form_errors}

<form method="post" action="{$action_url}" id="queryBuilderForm">
	<fieldset>
	{if $sql_query && !$sql_disabled}
		<legend>Recherche SQL</legend>
		<dl>
			{input type="textarea" name="sql_query" cols="100" rows="10" required=1 label="Requête SQL" help="Si aucune limite n'est précisée, une limite de 100 résultats sera appliquée." default=$sql_query}
			{if $session->canAccess('config', Membres::DROIT_ADMIN)}
				{input type="checkbox" name="unprotected" value=1 label="Autoriser l'accès à toutes les tables de la base de données" default=$is_unprotected}
				<dd class="help">Attention : en cochant cette case vous autorisez la requête à lire toutes les données de toutes les tables de la base de données&nbsp;!</dd>
			{/if}

			<dd class="help">
				<details>
					<summary class="block help">Schéma SQL des tables</summary>
					<pre class="block help">{foreach from=$schema item="table"}{$table}<br />{/foreach}</pre>
				</details>
			</dd>
		</dl>
		<p class="submit">
			{button type="submit" name="run" label="Exécuter" shape="search" class="main"}
			<input type="hidden" name="id" value="{$search.id}" />
			{if $search.id}
				{button name="save" value=1 type="submit" label="Enregistrer : %s"|args:$search.intitule|truncate:40:"…":true shape="upload"}
				{button name="save_new" value=1 type="submit" label="Enregistrer nouvelle recherche" shape="plus"}
			{else}
				{button name="save" value=1 type="submit" label="Enregistrer cette recherche" shape="upload"}
			{/if}
			{if $session->canAccess('config', Membres::DROIT_ADMIN)}
				{linkbutton href="!config/advanced/sql.php" target="_blank" shape="menu" label="Voir le schéma SQL complet"}
			{/if}
		</p>
	{elseif !$sql_query}
		<legend>Rechercher</legend>
		<div class="queryBuilder" id="queryBuilder"></div>
		<p class="actions">





|










|




















|







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
<?php
assert(isset($columns));
assert(isset($action_url));
assert(isset($query));
assert(isset($is_admin));
$sql_disabled = !$is_admin || (!$session->canAccess($session::SECTION_CONFIG, $session::ACCESS_ADMIN) && $is_unprotected);
?>

{form_errors}

<form method="post" action="{$action_url}" id="queryBuilderForm">
	<fieldset>
	{if $sql_query && !$sql_disabled}
		<legend>Recherche SQL</legend>
		<dl>
			{input type="textarea" name="sql_query" cols="100" rows="10" required=1 label="Requête SQL" help="Si aucune limite n'est précisée, une limite de 100 résultats sera appliquée." default=$sql_query}
			{if $session->canAccess($session::SECTION_CONFIG, $session::ACCESS_ADMIN)}
				{input type="checkbox" name="unprotected" value=1 label="Autoriser l'accès à toutes les tables de la base de données" default=$is_unprotected}
				<dd class="help">Attention : en cochant cette case vous autorisez la requête à lire toutes les données de toutes les tables de la base de données&nbsp;!</dd>
			{/if}

			<dd class="help">
				<details>
					<summary class="block help">Schéma SQL des tables</summary>
					<pre class="block help">{foreach from=$schema item="table"}{$table}<br />{/foreach}</pre>
				</details>
			</dd>
		</dl>
		<p class="submit">
			{button type="submit" name="run" label="Exécuter" shape="search" class="main"}
			<input type="hidden" name="id" value="{$search.id}" />
			{if $search.id}
				{button name="save" value=1 type="submit" label="Enregistrer : %s"|args:$search.intitule|truncate:40:"…":true shape="upload"}
				{button name="save_new" value=1 type="submit" label="Enregistrer nouvelle recherche" shape="plus"}
			{else}
				{button name="save" value=1 type="submit" label="Enregistrer cette recherche" shape="upload"}
			{/if}
			{if $session->canAccess($session::SECTION_CONFIG, $session::ACCESS_ADMIN)}
				{linkbutton href="!config/advanced/sql.php" target="_blank" shape="menu" label="Voir le schéma SQL complet"}
			{/if}
		</p>
	{elseif !$sql_query}
		<legend>Rechercher</legend>
		<div class="queryBuilder" id="queryBuilder"></div>
		<p class="actions">

Modified src/templates/common/search/saved_searches.tpl from [4474b6655d] to [c5426cd9d9].

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
			{foreach from=$liste item="recherche"}
			<tr>
				<th><a href="{$search_url}?id={$recherche.id}">{$recherche.intitule}</a></th>
				<td>{if $recherche.type == Recherche::TYPE_JSON}Avancée{else}SQL{/if}</td>
				<td>{if !$recherche.id_membre}Publique{else}Privée{/if}</td>
				<td class="actions">
					{linkbutton href="%s?id=%d"|args:$search_url,$recherche.id shape="search" label="Rechercher"}
					{if $recherche.id_membre || $session->canAccess($target, Membres::DROIT_ADMIN)}
						{linkbutton href="?edit=%d"|args:$recherche.id shape="edit" label="Modifier"}
						{linkbutton href="?delete=%d"|args:$recherche.id shape="delete" label="Supprimer"}
					{/if}
				</td>
			</tr>
			{/foreach}
		</tbody>
	</table>
{/if}

{include file="admin/_foot.tpl"}







|











66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
			{foreach from=$liste item="recherche"}
			<tr>
				<th><a href="{$search_url}?id={$recherche.id}">{$recherche.intitule}</a></th>
				<td>{if $recherche.type == Recherche::TYPE_JSON}Avancée{else}SQL{/if}</td>
				<td>{if !$recherche.id_membre}Publique{else}Privée{/if}</td>
				<td class="actions">
					{linkbutton href="%s?id=%d"|args:$search_url,$recherche.id shape="search" label="Rechercher"}
					{if $recherche.id_membre || $session->canAccess($access_section, $session::ACCESS_ADMIN)}
						{linkbutton href="?edit=%d"|args:$recherche.id shape="edit" label="Modifier"}
						{linkbutton href="?delete=%d"|args:$recherche.id shape="delete" label="Supprimer"}
					{/if}
				</td>
			</tr>
			{/foreach}
		</tbody>
	</table>
{/if}

{include file="admin/_foot.tpl"}

Added src/templates/docs/action_delete.tpl version [987d942776].























>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
{include file="admin/_head.tpl" title="Supprimer %d fichiers"|args:$count current="docs"}

{include file="common/delete_form.tpl"
	legend="Supprimer ces fichiers ?"
	warning="Êtes-vous sûr de vouloir supprimer %d fichiers ?"|args:$count
	confirm="Cocher cette case pour confirmer la suppression"
	csrf_key=$csrf_key
	extra=$extra
}

{include file="admin/_foot.tpl"}

Added src/templates/docs/action_move.tpl version [6596a8e5e5].

















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title="Ajouter/supprimer des écritures à un projet" current="acc/accounts"}

{form_errors}

<form method="post" action="{$self_url}">
	<fieldset>
		<legend>Déplacer {$count} fichiers vers…</legend>

		<table class="tree-selector list">
			<tbody>
				<?php $last = 0; ?>
				{foreach from=$breadcrumbs item="_title" key="_path"}
				<tr>
					<td class="check">{input type="radio" name="select" value=$_path}</td>
					<th><?=str_repeat('<i>&nbsp;</i>', $last)?> <b class="icn">&rarr;</b>
						<button type="submit" name="current" value="{$_path}">{$_title}</button></th>
					<?php $last = $iteration; ?>
				</tr>
				{/foreach}
				{foreach from=$directories item="dir"}
				<tr>
					<td class="check">{input type="radio" name="select" value=$dir.path}</td>
					<th><?=str_repeat('<i>&nbsp;</i>', $last)?> <b class="icn">&rarr;</b>
						<button type="submit" name="current" value="{$dir.path}">{$dir.name}</button></th>
				</tr>
				{foreachelse}
				<tr>
					<td class="check"></td>
					<th><?=str_repeat('<i>&nbsp;</i>', $last+1)?> <b class="icn">&rarr;</b> <em>Pas de sous-répertoire</em></th>
				</tr>
				{/foreach}
			</tbody>
		</table>

	</fieldset>

	<p class="submit">
		{csrf_field key=$csrf_key}
		{button type="submit" name="move" label="Déplacer les fichiers" shape="right" class="main"}

		{if isset($extra)}
			{foreach from=$extra key="key" item="value"}
				{if is_array($value)}
					{foreach from=$value key="subkey" item="subvalue"}
						<input type="hidden" name="{$key}[{$subkey}]" value="{$subvalue}" />
					{/foreach}
				{else}
					<input type="hidden" name="{$key}" value="{$value}" />
				{/if}
			{/foreach}
		{/if}
	</p>

</form>

{include file="admin/_foot.tpl"}

Added src/templates/docs/index.tpl version [34d64a62ee].



























































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
use Garradin\Entities\Files\File;
?>
{include file="admin/_head.tpl" title="Documents" current="docs"}

<nav class="tabs">
	<aside>
	{if $context == File::CONTEXT_DOCUMENTS}
		{linkbutton shape="search" label="Rechercher" href="search.php" target="_dialog"}
	{/if}
	{if $can_mkdir}
		{linkbutton shape="plus" label="Nouveau répertoire" target="_dialog" href="!docs/new_dir.php?p=%s"|args:$path}
	{/if}
	{if $can_upload}
		{linkbutton shape="plus" label="Nouveau fichier texte" target="_dialog" href="!docs/new_file.php?p=%s"|args:$path}
		{linkbutton shape="upload" label="Ajouter un fichier" target="_dialog" href="!common/files/upload.php?p=%s"|args:$path}
	{/if}
	</aside>
	<ul>
		<li{if $context == File::CONTEXT_DOCUMENTS} class="current"{/if}><a href="./">Documents</a></li>
		{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)}
			<li{if $context == File::CONTEXT_TRANSACTION} class="current"{/if}><a href="./?p=<?=File::CONTEXT_TRANSACTION?>">Fichiers des écritures</a></li>
		{/if}
		{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
			<li{if $context == File::CONTEXT_USER} class="current"{/if}><a href="./?p=<?=File::CONTEXT_USER?>">Fichiers des membres</a></li>
		{/if}
		{if $session->canAccess($session::SECTION_WEB, $session::ACCESS_ADMIN)}
			<li{if $context == File::CONTEXT_SKELETON} class="current"{/if}><a href="./?p=<?=File::CONTEXT_SKELETON?>">Squelettes du site web</a></li>
		{/if}
	</ul>

</nav>

<nav class="breadcrumbs">
	<ul>
	{foreach from=$breadcrumbs item="name" key="bc_path"}
		<li><a href="?p={$bc_path}">{$name}</a></li>
	{/foreach}
	</ul>

	{if $context == File::CONTEXT_USER && $context_ref}
		{linkbutton href="!membres/fiche.php?id=%d"|args:$context_ref|local_url label="Fiche du membre" shape="user"}
	{elseif $context == File::CONTEXT_TRANSACTION && $context_ref}
		{linkbutton href="!acc/transactions/details.php?id=%d"|args:$context_ref|local_url label="Détails de l'écriture" shape="menu"}
	{/if}

	{if count($breadcrumbs) > 1}
		{linkbutton href="?p=%s"|args:$parent_path label="Retour au répertoire parent" shape="left"}
	{/if}

	<aside class="quota">
		<h4><b>{$quota_left|size_in_bytes}</b> libres sur <i>{$quota_max|size_in_bytes}</i></h4>
		<span class="meter"><span style="width: {$quota_percent}%"></span></span>
	</aside>
</nav>

{if !$can_mkdir && !$context_ref}
<p class="block alert">
	Il n'est pas possible de créer de répertoire ici.
	{if $context == File::CONTEXT_USER}
		Utiliser le <a href="{"!membres/ajouter.php"|local_url}">formulaire de création</a> pour enregistrer un membre.
	{else}
		Utiliser le <a href="{"!acc/transactions/new.php"|local_url}">formulaire de saisie</a> pour créer une nouvelle écriture.
	{/if}
</p>
{/if}

{if count($files)}
<form method="post" action="{"!docs/action.php"|local_url}" target="_dialog">
<table class="list">
	<thead>
		<tr>
			<td class="check"><input type="checkbox" value="Tout cocher / décocher" id="f_all" /><label for="f_all"></label></td>
			<th>Nom</th>
			<td>Modifié</td>
			<td>Type</td>
			<td>Taille</td>
			<td></td>
		</tr>
	</thead>

	<tbody>

	{foreach from=$files item="file"}
		{if $file.type == $file::TYPE_DIRECTORY}
		<tr>
			{if $can_delete}
			<td class="check">
				{input type="checkbox" name="check[]" value=$file.path}
			</td>
			{/if}
			<th><a href="?p={$file.path}">{$file.name}</a></th>
			<td></td>
			<td>Répertoire</td>
			<td></td>
			<td class="actions">{linkbutton href="!common/files/delete.php?p=%s"|args:$file.path label="Supprimer" shape="delete" target="_dialog"}</td>
		</tr>
		{else}
		</tr>
			{if $can_delete}
			<td class="check">
				{input type="checkbox" name="check[]" value=$file.path}
			</td>
			{/if}
			<td>
				{if $file->canPreview()}
					<a href="{"!common/files/preview.php?p=%s"|local_url|args:$file.path}" target="_dialog" data-mime="{$file.mime}">{$file.name}</a>
				{else}
					<a href="{$file->url(true)}" target="_blank">{$file.name}</a>
				{/if}
			</td>
			<td>{$file.modified|date}</td>
			<td>{$file.mime}</td>
			<td>{$file.size|size_in_bytes}</td>
			<td class="actions">
				{if $can_write && $file->getEditor()}
					{linkbutton href="!common/files/edit.php?p=%s"|args:$file.path label="Modifier" shape="edit" target="_dialog" data-dialog-height="90%"}
				{/if}
				{if $file->canPreview()}
					{linkbutton href="!common/files/preview.php?p=%s"|args:$file.path label="Voir" shape="eye" target="_dialog" data-mime=$file.mime}
				{/if}
				{linkbutton href=$file->url(true) label="Télécharger" shape="download"}
				{linkbutton href="!common/files/delete.php?p=%s"|args:$file.path label="Supprimer" shape="delete" target="_dialog"}
			</td>
		</tr>
		{/if}
	{/foreach}

	</tbody>
	{if $can_delete}
	<tfoot>
		<tr>
			<td class="check"><input type="checkbox" value="Tout cocher / décocher" id="f_all2" /><label for="f_all2"></label></td>
			<td class="actions" colspan="5">
				<em>Pour les fichiers cochés :</em>
					<input type="hidden" name="parent" value="{$path}" />
					<select name="action">
						<option value="">— Choisir une action à effectuer —</option>
						{if $context == File::CONTEXT_DOCUMENTS}
						<option value="move">Déplacer</option>
						{/if}
						<option value="delete">Supprimer</option>
					</select>
					<noscript>
						{button type="submit" value="OK" shape="right" label="Valider"}
					</noscript>
				{/if}
			</td>
		</tr>
	</tfoot>
</table>
</form>
{else}
	<p class="alert block">Il n'y a aucun fichier dans ce répertoire.</p>
{/if}

{include file="admin/_foot.tpl"}

Added src/templates/docs/new_dir.tpl version [7609c1ea55].





































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{include file="admin/_head.tpl" title="Créer un répertoire"}

{form_errors}

<form method="post" action="{$self_url}" data-focus="1">
	<fieldset>
		<legend>Créer un répertoire</legend>
		<dl>
			{input type="text" minlength="1" size="60" name="name" required="required" label="Nom du répertoire à créer"}
		</dl>
		<p class="submit">
			{csrf_field key=$csrf_key}
			{button type="submit" name="create" label="Créer le répertoire" shape="plus" class="main"}
		</p>
	</fieldset>
</form>

{include file="admin/_foot.tpl"}

Added src/templates/docs/new_file.tpl version [77d65a65c8].





































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{include file="admin/_head.tpl" title="Créer un répertoire"}

{form_errors}

<form method="post" action="{$self_url}" data-focus="1">
	<fieldset>
		<legend>Créer un fichier texte</legend>
		<dl>
			{input type="text" minlength="1" size="60" name="name" required="required" label="Nom du fichier à créer"}
		</dl>
		<p class="submit">
			{csrf_field key=$csrf_key}
			{button type="submit" name="create" label="Créer le fichier" shape="plus" class="main"}
		</p>
	</fieldset>
</form>

{include file="admin/_foot.tpl"}

Added src/templates/docs/search.tpl version [ae804588a5].



























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title="Rechercher dans les fichiers" current="docs"}

<form method="post" action="{$self_url}" data-focus="1">
	<fieldset>
		<legend>Rechercher un fichier</legend>
		<p class="submit">
			<input type="text" name="q" value="{$query}" size="25" />
			{button type="submit" name="search" label="Chercher" shape="search" class="main"}
		</p>
	</fieldset>
</form>

{if $query}
	<p class="block alert">
		<strong>{$results_count}</strong> fichiers trouvés pour «&nbsp;{$query}&nbsp;»
	</p>

	<section class="search-results">
	{foreach from=$results item="result"}
		<article>
			<h4><a href="{"!docs/?parent=%s"|local_url|args:$result.parent}" target="_parent">{$result.path}</a></h4>
			<h3><a href="{"!docs/?parent=%s"|local_url|args:$result.parent}" target="_parent">{$result.title}</a></h3>
			<p>{$result.snippet|escape|clean_snippet}</p>
		</article>
	{/foreach}
	</section>
{/if}

{include file="admin/_foot.tpl"}

Modified src/templates/services/_nav.tpl from [002aae664e] to [a20e52a2d4].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<nav class="tabs">
	<ul>
		<li{if $current == 'index'} class="current"{/if}><a href="{$admin_url}services/">Activités et cotisations</a></li>
		{if $session->canAccess('membres', Membres::DROIT_ECRITURE)}
			<li{if $current == 'save'} class="current"{/if}><a href="{$admin_url}services/save.php">Inscrire à une activité</a></li>
		{/if}
		{if $session->canAccess('membres', Membres::DROIT_ADMIN)}
			<li{if $current == 'reminders'} class="current"{/if}><a href="{$admin_url}services/reminders/">Gestion des rappels automatiques</a></li>
		{/if}
	</ul>

	{if isset($current_service)}
	<ul class="sub">
		<li class="title">



|


|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
<nav class="tabs">
	<ul>
		<li{if $current == 'index'} class="current"{/if}><a href="{$admin_url}services/">Activités et cotisations</a></li>
		{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)}
			<li{if $current == 'save'} class="current"{/if}><a href="{$admin_url}services/save.php">Inscrire à une activité</a></li>
		{/if}
		{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
			<li{if $current == 'reminders'} class="current"{/if}><a href="{$admin_url}services/reminders/">Gestion des rappels automatiques</a></li>
		{/if}
	</ul>

	{if isset($current_service)}
	<ul class="sub">
		<li class="title">

Modified src/templates/services/details.tpl from [61301fabc6] to [d4fb23f692].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{include file="admin/_head.tpl" title="%s — Liste des membres inscrits"|args:$service.label current="membres/services"}

{include file="services/_nav.tpl" current="index" current_service=$service service_page=$type}

<dl class="cotisation">
	<dt>Nombre de membres trouvés</dt>
	<dd>
		{$list->count()}
		<em class="help">(N'apparaît ici que l'inscription la plus récente de chaque membre.)</em>
		{if $session->canAccess('membres', Membres::DROIT_ADMIN)}
		{linkbutton href="%s&export=csv"|args:$self_url shape="export" label="Export CSV"}
		{linkbutton href="%s&export=ods"|args:$self_url shape="export" label="Export tableur"}
		{/if}
	</dd>
</dl>

{include file="common/dynamic_list_head.tpl"}









|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{include file="admin/_head.tpl" title="%s — Liste des membres inscrits"|args:$service.label current="membres/services"}

{include file="services/_nav.tpl" current="index" current_service=$service service_page=$type}

<dl class="cotisation">
	<dt>Nombre de membres trouvés</dt>
	<dd>
		{$list->count()}
		<em class="help">(N'apparaît ici que l'inscription la plus récente de chaque membre.)</em>
		{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
		{linkbutton href="%s&export=csv"|args:$self_url shape="export" label="Export CSV"}
		{linkbutton href="%s&export=ods"|args:$self_url shape="export" label="Export tableur"}
		{/if}
	</dd>
</dl>

{include file="common/dynamic_list_head.tpl"}

Modified src/templates/services/fees/details.tpl from [bab86fda03] to [238f21a2af].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{include file="admin/_head.tpl" title="Tarif : %s — Liste des membres inscrits"|args:$fee.label current="membres/services"}

{include file="services/_nav.tpl" current="index" current_service=$service service_page="index" current_fee=$fee fee_page=$type}

<dl class="cotisation">
	<dt>Nombre de membres trouvés</dt>
	<dd>
		{$list->count()}
		<em class="help">(N'apparaît ici que l'inscription la plus récente de chaque membre.)</em>
		{if $session->canAccess('membres', Membres::DROIT_ADMIN)}
			{linkbutton href="%s&export=csv"|args:$self_url shape="export" label="Export CSV"}
			{linkbutton href="%s&export=ods"|args:$self_url shape="export" label="Export tableur"}
		{/if}
	</dd>
</dl>

{include file="common/dynamic_list_head.tpl"}









|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{include file="admin/_head.tpl" title="Tarif : %s — Liste des membres inscrits"|args:$fee.label current="membres/services"}

{include file="services/_nav.tpl" current="index" current_service=$service service_page="index" current_fee=$fee fee_page=$type}

<dl class="cotisation">
	<dt>Nombre de membres trouvés</dt>
	<dd>
		{$list->count()}
		<em class="help">(N'apparaît ici que l'inscription la plus récente de chaque membre.)</em>
		{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
			{linkbutton href="%s&export=csv"|args:$self_url shape="export" label="Export CSV"}
			{linkbutton href="%s&export=ods"|args:$self_url shape="export" label="Export tableur"}
		{/if}
	</dd>
</dl>

{include file="common/dynamic_list_head.tpl"}

Modified src/templates/services/fees/index.tpl from [da9ebe99b8] to [829d080cff].

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
						{/if}
					</td>
					<td class="num"><a href="details.php?id={$row.id}">{$row.nb_users_ok}</a></td>
					<td class="num"><a href="details.php?id={$row.id}&amp;type=expired">{$row.nb_users_expired}</a></td>
					<td class="num"><a href="details.php?id={$row.id}&amp;type=unpaid">{$row.nb_users_unpaid}</td>
					<td class="actions">
						{linkbutton shape="users" label="Liste des inscrits" href="!services/fees/details.php?id=%d"|args:$row.id}
						{if $session->canAccess('membres', Membres::DROIT_ADMIN)}
							{linkbutton shape="edit" label="Modifier" href="!services/fees/edit.php?id=%d"|args:$row.id}
							{linkbutton shape="delete" label="Supprimer" href="!services/fees/delete.php?id=%d"|args:$row.id}
						{/if}
					</td>
				</tr>
			{/foreach}
		</tbody>
	</table>
{else}
	<p class="block alert">
		Il n'y a aucun tarif enregistré. Créez un premier tarif pour l'activité «&nbsp;{$service.label}&nbsp;» pour pouvoir y inscrire des membres.
	</p>
{/if}

{if $session->canAccess('membres', Membres::DROIT_ADMIN)}
	{include file="services/fees/_fee_form.tpl" legend="Ajouter un tarif" submit_label="Ajouter" csrf_key="fee_add" fee=null amount_type=0 account=null}
{/if}

{include file="admin/_foot.tpl"}







|














|




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
						{/if}
					</td>
					<td class="num"><a href="details.php?id={$row.id}">{$row.nb_users_ok}</a></td>
					<td class="num"><a href="details.php?id={$row.id}&amp;type=expired">{$row.nb_users_expired}</a></td>
					<td class="num"><a href="details.php?id={$row.id}&amp;type=unpaid">{$row.nb_users_unpaid}</td>
					<td class="actions">
						{linkbutton shape="users" label="Liste des inscrits" href="!services/fees/details.php?id=%d"|args:$row.id}
						{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
							{linkbutton shape="edit" label="Modifier" href="!services/fees/edit.php?id=%d"|args:$row.id}
							{linkbutton shape="delete" label="Supprimer" href="!services/fees/delete.php?id=%d"|args:$row.id}
						{/if}
					</td>
				</tr>
			{/foreach}
		</tbody>
	</table>
{else}
	<p class="block alert">
		Il n'y a aucun tarif enregistré. Créez un premier tarif pour l'activité «&nbsp;{$service.label}&nbsp;» pour pouvoir y inscrire des membres.
	</p>
{/if}

{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
	{include file="services/fees/_fee_form.tpl" legend="Ajouter un tarif" submit_label="Ajouter" csrf_key="fee_add" fee=null amount_type=0 account=null}
{/if}

{include file="admin/_foot.tpl"}

Modified src/templates/services/index.tpl from [c030049f17] to [e96f0904c2].

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
					</td>
					<td class="num"><a href="details.php?id={$row.id}">{$row.nb_users_ok}</a></td>
					<td class="num"><a href="details.php?id={$row.id}&amp;type=expired">{$row.nb_users_expired}</a></td>
					<td class="num"><a href="details.php?id={$row.id}&amp;type=unpaid">{$row.nb_users_unpaid}</a></td>
					<td class="actions">
						{linkbutton shape="menu" label="Tarifs" href="!services/fees/?id=%d"|args:$row.id}
						{linkbutton shape="users" label="Liste des inscrits" href="!services/details.php?id=%d"|args:$row.id}
						{if $session->canAccess('membres', Membres::DROIT_ADMIN)}
							{linkbutton shape="edit" label="Modifier" href="!services/edit.php?id=%d"|args:$row.id}
							{linkbutton shape="delete" label="Supprimer" href="!services/delete.php?id=%d"|args:$row.id}
						{/if}
					</td>
				</tr>
			{/foreach}
		</tbody>
	</table>
{else}
	<p class="block alert">Il n'y a aucune activité enregistrée.</p>
{/if}

{if $session->canAccess('membres', Membres::DROIT_ADMIN)}
	{include file="services/_service_form.tpl" legend="Ajouter une activité" service=null period=0}
{/if}

{include file="admin/_foot.tpl"}







|












|




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
					</td>
					<td class="num"><a href="details.php?id={$row.id}">{$row.nb_users_ok}</a></td>
					<td class="num"><a href="details.php?id={$row.id}&amp;type=expired">{$row.nb_users_expired}</a></td>
					<td class="num"><a href="details.php?id={$row.id}&amp;type=unpaid">{$row.nb_users_unpaid}</a></td>
					<td class="actions">
						{linkbutton shape="menu" label="Tarifs" href="!services/fees/?id=%d"|args:$row.id}
						{linkbutton shape="users" label="Liste des inscrits" href="!services/details.php?id=%d"|args:$row.id}
						{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
							{linkbutton shape="edit" label="Modifier" href="!services/edit.php?id=%d"|args:$row.id}
							{linkbutton shape="delete" label="Supprimer" href="!services/delete.php?id=%d"|args:$row.id}
						{/if}
					</td>
				</tr>
			{/foreach}
		</tbody>
	</table>
{else}
	<p class="block alert">Il n'y a aucune activité enregistrée.</p>
{/if}

{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
	{include file="services/_service_form.tpl" legend="Ajouter une activité" service=null period=0}
{/if}

{include file="admin/_foot.tpl"}

Modified src/templates/services/user.tpl from [dbd53507fd] to [d3b73b33b5].

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
	<dd>
		Aucune inscription.
	</dd>
	{/foreach}
	<dt>Nombre d'inscriptions pour ce membre</dt>
	<dd>
		{$list->count()}
		{if $session->canAccess('membres', Membres::DROIT_ADMIN)}
			{linkbutton href="?export=csv" shape="export" label="Export CSV"}
			{linkbutton href="?export=ods" shape="export" label="Export tableur"}
		{/if}
	</dd>
</dl>

{include file="common/dynamic_list_head.tpl"}

	{foreach from=$list->iterate() item="row"}
		<tr>
			<th>{$row.label}</th>
			<td>{$row.date|date_short}</td>
			<td>{$row.expiry|date_short}</td>
			<td>{$row.fee}</td>
			<td>{if $row.paid}<b class="confirm">Oui</b>{else}<b class="error">Non</b>{/if}</td>
			<td>{$row.amount|raw|money_currency}</td>
			<td class="actions">
				{if $session->canAccess('membres', Membres::DROIT_ECRITURE)}
					{if $row.paid}
						{linkbutton shape="reset" label="Marquer comme non payé" href="?id=%d&su_id=%d&paid=0"|args:$user.id,$row.id}
					{else}
						{linkbutton shape="check" label="Marquer comme payé" href="?id=%d&su_id=%d&paid=1"|args:$user.id,$row.id}
					{/if}
					{linkbutton shape="delete" label="Supprimer" href="user_delete.php?id=%d"|args:$row.id}
				{/if}
				{if $session->canAccess('compta', Membres::DROIT_ACCES) && $row.id_account}
					{linkbutton shape="menu" label="Liste des écritures" href="!acc/transactions/service_user.php?id=%d&user=%d"|args:$row.id,$user.id}
				{/if}
				{if $session->canAccess('compta', Membres::DROIT_ECRITURE) && $row.id_account}
					{linkbutton shape="plus" label="Nouveau règlement" href="payment.php?id=%d"|args:$row.id}
				{/if}
			</td>
		</tr>
	{/foreach}

	</tbody>
</table>

{pagination url=$list->paginationURL() page=$list.page bypage=$list.per_page total=$list->count()}


{include file="admin/_foot.tpl"}







|

















|







|


|













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
	<dd>
		Aucune inscription.
	</dd>
	{/foreach}
	<dt>Nombre d'inscriptions pour ce membre</dt>
	<dd>
		{$list->count()}
		{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN)}
			{linkbutton href="?export=csv" shape="export" label="Export CSV"}
			{linkbutton href="?export=ods" shape="export" label="Export tableur"}
		{/if}
	</dd>
</dl>

{include file="common/dynamic_list_head.tpl"}

	{foreach from=$list->iterate() item="row"}
		<tr>
			<th>{$row.label}</th>
			<td>{$row.date|date_short}</td>
			<td>{$row.expiry|date_short}</td>
			<td>{$row.fee}</td>
			<td>{if $row.paid}<b class="confirm">Oui</b>{else}<b class="error">Non</b>{/if}</td>
			<td>{$row.amount|raw|money_currency}</td>
			<td class="actions">
				{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE)}
					{if $row.paid}
						{linkbutton shape="reset" label="Marquer comme non payé" href="?id=%d&su_id=%d&paid=0"|args:$user.id,$row.id}
					{else}
						{linkbutton shape="check" label="Marquer comme payé" href="?id=%d&su_id=%d&paid=1"|args:$user.id,$row.id}
					{/if}
					{linkbutton shape="delete" label="Supprimer" href="user_delete.php?id=%d"|args:$row.id}
				{/if}
				{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ) && $row.id_account}
					{linkbutton shape="menu" label="Liste des écritures" href="!acc/transactions/service_user.php?id=%d&user=%d"|args:$row.id,$user.id}
				{/if}
				{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_WRITE) && $row.id_account}
					{linkbutton shape="plus" label="Nouveau règlement" href="payment.php?id=%d"|args:$row.id}
				{/if}
			</td>
		</tr>
	{/foreach}

	</tbody>
</table>

{pagination url=$list->paginationURL() page=$list.page bypage=$list.per_page total=$list->count()}


{include file="admin/_foot.tpl"}

Added src/templates/web/_attach.tpl version [d9dde30b66].



































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title="Inclure un fichier"}

{form_errors}

<form method="post" enctype="multipart/form-data" action="{$self_url}" id="f_upload">
	<fieldset>
		<legend>Téléverser un fichier</legend>
		<dl>
			{input type="file" name="file" label="Fichier" required=true}
		</dl>
		<p class="submit">
			{csrf_field key=$csrf_key}
			{button type="submit" name="upload" label="Envoyer le fichier" shape="upload" class="main" id="f_submit"}
		</p>
	</fieldset>
</form>

<form method="get" action="#" style="display: none;" id="insertImage">
	<fieldset>
		<h3>Insérer une image dans le texte</h3>
		<dl>
			<dd class="image"></dd>
			<dt>Légende <i>(facultatif)</i></dt>
			<dd class="caption">
				<input type="text" name="f_caption" size="50" />
			</dd>
			<dt>Alignement&nbsp;:</dt>
			<dd class="align">
				<input type="button" name="left" value="À gauche" />
				<input type="button" name="center" value="Au centre" />
				<input type="button" name="right" value="À droite" />
			</dd>
			<dd class="cancel">
				<input type="reset" value="Annuler" />
			</dd>
		</dl>
	</fieldset>
</form>

{if !empty($images)}
<ul class="gallery">
{foreach from=$images item="file"}
	<li>
		<figure>
			<a href="{$file->url()}" data-name="{$file.name}" data-insert="image" data-thumb="{$file->thumb_url()}"><img src="{$file->thumb_url()}" alt="" title="{$file.name}" /></a>
			<form class="actions" method="post" action="{$self_url}">
				{linkbutton shape="download" label="Télécharger" href=$file->url() target="_blank"}
				{linkbutton shape="plus" label="Insérer" href=$file->url() data-name=$file.name data-insert="image" data-thumb=$file->thumb_url()}
				{csrf_field key=$csrf_key}
				<input type="hidden" name="delete" value="{$file.name}" />
				<noscript><input type="submit" value="Supprimer" /></noscript>
			</form>
		</figure>
	</li>
{/foreach}
</ul>
{/if}

{if !empty($files)}
<table class="list">
	<tbody>
	{foreach from=$files item="file"}
		<tr>
			<th>{$file.name}</th>
			<td>{$file.type}, {$file.size|size_in_bytes}</td>
			<td class="actions">
				<form class="actions" method="post" action="{$self_url}">
					{linkbutton shape="plus" label="Insérer" href=$file->url() data-name=$file.name data-insert="file"}
					{linkbutton shape="download" label="Télécharger" href=$file->url() target="_blank"}
					{csrf_field key=$csrf_key}
					<input type="hidden" name="delete" value="{$file.name}" />
					<noscript><input type="submit" value="Supprimer" /></noscript>
				</form>
			</td>
		</tr>
	{/foreach}
	</tbody>
</table>
{/if}

{include file="admin/_foot.tpl"}

Added src/templates/web/_selector.tpl version [b84b0a915e].























































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title="Choisir la page parent" current="web"}

<table class="tree-selector list">
	<tbody>
		<tr{if !$parent} class="focused"{/if}>
			<td><input type="button" value="Choisir" data-path="" data-label="Racine du site" /></td>
			<th><h3><a href="?current={$selected}">Racine du site</a></h3></th>
		</tr>
		<?php $last = 1; ?>
		{foreach from=$breadcrumbs item="_title" key="_path"}
		<tr{if $_path == $parent} class="focused"{/if}>
			<td><input type="button" value="Choisir" data-path="{$_path}" data-label="{$_title}" /></td>
			<th><?=str_repeat('<i>&nbsp;</i>', $last)?> <b class="icn">&rarr;</b> <a href="?parent={$_path}&amp;current={$selected}">{$_title}</a></th>
			<?php $last = $iteration; ?>
		</tr>
		{/foreach}
		{foreach from=$categories item="cat"}
		<tr{if $cat.path == $parent} class="focused"{/if}>
			<td><input type="button" value="Choisir" data-path="{$cat.path}" data-label="{$cat.title}" /></td>
			<th><?=str_repeat('<i>&nbsp;</i>', $last)?> <b class="icn">&rarr;</b> <a href="?parent={$cat.path}&amp;current={$selected}">{$cat.title}</a></th>
		</tr>
		{foreachelse}
		<tr>
			<td></td>
			<th><?=str_repeat('<i>&nbsp;</i>', $last+1)?> <b class="icn">&rarr;</b> <em>Pas de sous-catégorie…</em></th>
		</tr>
		{/foreach}
	</tbody>
</table>

{literal}
<script type="text/javascript">
var buttons = document.querySelectorAll('input');

buttons.forEach((e) => {
	e.onclick = () => {
		window.parent.g.inputListSelected(e.dataset.path, e.dataset.label);
	};
});
</script>
{/literal}

{include file="admin/_foot.tpl"}

Added src/templates/web/config.tpl version [8397b3f71c].





































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title="Configuration" current="web"}

<nav class="tabs">
	<ul>
		<li><a href="./">Gestion du site web</a></li>
		{if $session->canAccess($session::SECTION_WEB, $session::ACCESS_ADMIN)}
			{*<li><a href="theme.php">Thèmes</a></li>*}
			<li class="current"><a href="config.php">Configuration</a></li>
		{/if}
		{if !$config.site_disabled}
			<li><a href="{$www_url}" target="_blank">Voir le site en ligne</a></li>
		{/if}
	</ul>
</nav>

{form_errors}

{if isset($edit)}
	<form method="post" action="{$self_url}">
		<h3>Éditer un squelette</h3>

		{if $ok}
		<p class="block confirm">
			Modifications enregistrées.
		</p>
		{/if}

		<fieldset class="skelEdit">
			<legend>{$edit.file}</legend>
			<p>
				<textarea name="content" cols="90" rows="50" id="f_content">{form_field name=content data=$edit}</textarea>
			</p>
		</fieldset>

		<p class="submit">
			{csrf_field key=$csrf_key}
			{button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
		</p>

	</form>

	<script type="text/javascript">
	g.script("scripts/code_editor.js");
	</script>
{else}


	{if $config.site_disabled}

	<div class="block alert">
		<h3>Site public désactivé</h3>
		<p>Le site public est désactivé, les visiteurs sont redirigés automatiquement vers la page de connexion.</p>
		<form method="post" action="{$self_url}">
			<p class="submit">
				{csrf_field key="config_site"}
				{button type="submit" name="enable_site" label="Activer le site public" shape="right" class="main"}
			</p>
		</form>
	</div>

	{else}

	<fieldset>
		<legend>Activation du site public</legend>
		<dl>
			<dt>
				<form method="post" action="{$self_url}">
					<p class="submit">
						{button type="submit" name="disable_site" label="Désactiver le site public" shape="right" class="main"}
						{csrf_field key="config_site"}
					</p>
				</form>
			</dt>
			<dd class="help">
				En désactivant le site public, les visiteurs seront automatiquement redirigés vers la page de connexion.<br />
				Cette option est utile si vous avez déjà un site web et ne souhaitez pas utiliser la fonctionnalité site web de Garradin.
			</dd>
		</dl>
	</fieldset>

	{/if}

	<form method="post" action="{$self_url}">
	<fieldset class="templatesList">
		<legend>Squelettes du site</legend>

		{if $reset_ok}
		<p class="block confirm">
			Réinitialisation effectuée. Les squelettes ont été remis à jour
		</p>
		{/if}

		<table class="list">
			<thead>
				<tr>
					<td class="check"></td>
					<th>Fichier</th>
					<td>Dernière modification</td>
					<td></td>
				</tr>
			</thead>
			<tbody>
			{foreach from=$sources key="source" item="local"}
				<tr>
					<td>{if $local.modified}<input type="checkbox" name="select[]" value="{$source}" id="f_source_{$iteration}" /><label for="f_source_{$iteration}"></label>{/if}</td>
					<th><a href="?edit={$source|escape:'url'}" title="Éditer">{$source}</a></th>
					<td>{if $local.modified}{$local.modified|date}{else}<em>(fichier non modifié)</em>{/if}</td>
					<td class="actions">
						{linkbutton shape="edit" label="Éditer" href="?edit=%s"|args:$source}
					</td>
				</tr>
			{/foreach}
			</tbody>
		</table>

		<p class="actions">
			Pour les squelettes sélectionnés&nbsp;:
			<input type="submit" name="reset" value="Réinitialiser" onclick="return confirm('Effacer toute modification locale et restaurer les squelettes d\'installation ?');" />
			{csrf_field key="squelettes"}
		</p>

		<p>
			{linkbutton href="!docs/?p=skel" label="Gérer les fichiers de squelettes" shape="folder"}
		</p>
	</fieldset>
	</form>

{/if}

{include file="admin/_foot.tpl"}

Added src/templates/web/delete.tpl version [4069827d96].



















>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
{include file="admin/_head.tpl" title=$title current="web"}

{include file="common/delete_form.tpl"
	legend=$title
	warning="Êtes-vous sûr de vouloir supprimer « %s » ?"|args:$page.title
	alert=$alert
}

{include file="admin/_foot.tpl"}

Added src/templates/web/edit.tpl version [a716c2cf03].















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title="Édition : %s"|args:$page.title current="web"}

{form_errors}

{if $show_diff}
	<h3>Modifications entre votre version et la nouvelle version</h3>
	{diff old=$old_content new=$new_content}
{/if}

<form method="post" action="{$self_url}" class="web-edit" data-focus="#f_content">

	<fieldset class="wikiMain">
		<legend>Informations générales</legend>
		<dl>
			{input type="text" name="title" source=$page required=true label="Titre"}
			{input type="text" name="uri" default=$page.uri required=true label="Adresse unique URI" help="Utilisée pour désigner l'adresse de la page sur le site. Ne peut comporter que des lettres, des chiffres, des tirets et des tirets bas." pattern="[A-Za-z0-9_-]+"}
			{input type="list" name="parent" label="Catégorie" default=$parent target="web/_selector.php?current=%s"|args:$page.path required=true}
			{input type="datetime" name="date" label="Date" required=true default=$page.published}
			<dt>Statut</dt>
			{input type="radio" name="status" value=$page::STATUS_ONLINE label="En ligne" source=$page}
			{input type="radio" name="status" value=$page::STATUS_DRAFT label="Brouillon" source=$page help="ne sera pas visible sur le site"}
		</dl>
	</fieldset>

	<fieldset class="wikiEncrypt">
		<dl>
			<dt>
				<input type="checkbox" name="encryption" id="f_encryption" {if $encrypted} checked="checked"{/if} value="1" onchange="checkEncryption(this);" />
				<label for="f_encryption">Chiffrer le contenu</label> <i>(facultatif)</i>
			</dt>
			<noscript>
			<dd>Nécessite JavaScript activé pour fonctionner !</dd>
			</noscript>
			<dd>Mot de passe : <i id="encryptPasswordDisplay" title="Chiffrement désactivé">désactivé</i></dd>
			<dd class="help">Le mot de passe n'est ni transmis ni enregistré,
				il n'est pas possible de retrouver le contenu si vous perdez le mot de passe.</dd>
		</dl>
	</fieldset>


	<fieldset class="wikiText">
		<div class="textEditor">
			{input type="textarea" name="content" cols="70" rows="35" default=$new_content data-attachments=1 data-savebtn=2 data-preview-url="!common/files/_preview.php?w=%s"|local_url|args:$page.path}
		</div>
	</fieldset>

	<p class="submit">
		{csrf_field key=$csrf_key}
		<input type="hidden" name="editing_started" value="{$editing_started}" />
		{button type="submit" name="save" label="Enregistrer et fermer" shape="upload" class="main"}
	</p>

</form>

{include file="admin/_foot.tpl"}

Added src/templates/web/index.tpl version [ecc94b7c86].





































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title=$title current="web"}

<nav class="tabs">
	<aside>
		{linkbutton shape="search" label="Rechercher" target="_dialog" href="search.php"}
		{linkbutton shape="plus" label="Nouvelle page" target="_dialog" href="new.php?type=%d&parent=%s"|args:$type_page,$current_path}
		{linkbutton shape="plus" label="Nouvelle catégorie" target="_dialog" href="new.php?type=%d&parent=%s"|args:$type_category,$current_path}
	</aside>
	<ul>
		<li class="current"><a href="./">Gestion du site web</a></li>
		{if $session->canAccess($session::SECTION_WEB, $session::ACCESS_ADMIN)}
			{*<li><a href="theme.php">Thèmes</a></li>*}
			<li><a href="config.php">Configuration</a></li>
		{/if}
		{if !$config.site_disabled}
			<li><a href="{if $cat}{$cat->url()}{else}{$www_url}{/if}" target="_blank">Voir le site en ligne</a></li>
		{/if}
	</ul>
</nav>

<nav class="breadcrumbs">
	<ul>
		<li><a href="?p=">Racine du site</a></li>
		{foreach from=$breadcrumbs key="id" item="title"}
			<li><a href="?p={$id}">{$title}</a></li>
		{/foreach}
	</ul>

	{if $current_path}
		{linkbutton href="?p=%s"|args:$parent label="Retour à la catégorie parente" shape="left"}
		{linkbutton href="page.php?p=%s"|args:$current_path label="Prévisualiser cette catégorie" shape="image"}
		{linkbutton href="edit.php?p=%s"|args:$current_path label="Éditer cette catégorie" shape="edit"}
	{/if}

</nav>

{if $config.site_disabled}
	<p class="block alert">
		Le site public est désactivé. <a href="{"!web/config.php"|local_url}">Activer le site dans la configuration.</a>
	</p>
{/if}

{if count($categories)}
	<h2 class="ruler">Catégories</h2>
	<table class="list">
		<tbody>
			{foreach from=$categories item="p"}
			<tr>
				<th><a href="?p={$p.path}">{$p.title}</a></th>
				<td>{if $p.status == $p::STATUS_ONLINE}En ligne{else}<em>Brouillon</em>{/if}</td>
				<td class="actions">
					{if $p.status == $p::STATUS_ONLINE && !$config.site_disabled}
						{linkbutton shape="eye" label="Voir sur le site" href=$p->url() target="_blank"}
					{/if}
					{linkbutton shape="menu" label="Sous-catégories et pages" href="?p=%s"|args:$p.path}
					{linkbutton shape="image" label="Prévisualiser" href="page.php?p=%s"|args:$p.path}
					{linkbutton shape="edit" label="Éditer" href="edit.php?p=%s"|args:$p.path}
					{linkbutton shape="delete" label="Supprimer" target="_dialog" href="delete.php?p=%s"|args:$p.path}
				</td>
			</tr>
			{/foreach}
		</tbody>
	</table>
{/if}

{if count($pages)}
	<h2 class="ruler">Pages</h2>
	<p>
		{if !$order_date}
			{linkbutton shape="down" label="Trier par date" href="?p=%s"|args:$current_path}
		{else}
			{linkbutton shape="up" label="Trier par titre" href="?p=%s&order_title"|args:$current_path}
		{/if}
	</p>
	<table class="list">
		<tbody>
			{foreach from=$pages item="p"}
			<tr>
				<th>{$p.title}</th>
				<td>{if $p.status == $p::STATUS_ONLINE}En ligne{else}<em>Brouillon</em>{/if}</td>
				<td>{$p.created|date_short}</td>
				<td>Modifié {$p.modified|relative_date:true}</td>
				<td class="actions">
					{if $p.status == $p::STATUS_ONLINE}
						{linkbutton shape="eye" label="Voir sur le site" href=$p->url() target="_blank"}
					{/if}
					{linkbutton shape="image" label="Prévisualiser" href="page.php?p=%s"|args:$p.path}
					{linkbutton shape="edit" label="Éditer" href="edit.php?p=%s"|args:$p.path}
					{linkbutton shape="delete" label="Supprimer" target="_dialog" href="delete.php?p=%s"|args:$p.path}
				</td>
			</tr>
			{/foreach}
		</tbody>
	</table>
{/if}


{include file="admin/_foot.tpl"}

Added src/templates/web/new.tpl version [8e6a2cf2b1].













































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{include file="admin/_head.tpl" title=$title current="web"}

{form_errors}

<form method="post" action="{$self_url}" data-focus="1">

	<fieldset>
		<legend>Informations générales</legend>
		<dl>
			{input type="text" name="title" required=true label="Titre"}
		</dl>
	</fieldset>

	<p class="submit">
		{csrf_field key=$csrf_key}
		{button type="submit" name="create" label="Créer" shape="plus" class="main"}
	</p>

</form>


{include file="admin/_foot.tpl"}

Added src/templates/web/page.tpl version [a3e822ccef].

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title=$page.title current="web"}

<nav class="tabs">
	{if $page.type == $page::TYPE_CATEGORY}
	<aside>
		{linkbutton shape="plus" label="Nouvelle page" href="new.php?type=%d&parent=%d"|args:$type_page,$page.path}
		{linkbutton shape="plus" label="Nouvelle catégorie" href="new.php?type=%d&parent=%d"|args:$type_category,$page.path}
	</aside>
	{/if}
	<ul>
		<li><a href="{$admin_url}web/?p={$page.parent}">Retour à la liste</a></li>
		{if $session->canAccess($session::SECTION_WEB, $session::ACCESS_WRITE)}
			<li><a href="{$admin_url}web/edit.php?p={$page.path}">Modifier</a></li>
		{/if}
		{if $page.status == $page::STATUS_ONLINE && !$config.site_disabled}
			<li><a href="{$page->url()}" target="_blank">Voir sur le site</a></li>
		{/if}
		{if $session->canAccess($session::SECTION_WEB, $session::ACCESS_ADMIN)}
			<li><a href="{$admin_url}web/delete.php?p={$page.path}">Supprimer</a></li>
		{/if}
	</ul>
</nav>

{if !empty($breadcrumbs)}
<nav class="breadcrumbs">
	<ul>
		<li><a href="{"!web/"|local_url}">Racine du site</a></li>
		{foreach from=$breadcrumbs key="id" item="title"}
			<li><a href="?p={$id}">{$title}</a></li>
		{/foreach}
	</ul>
</nav>
{/if}


{if !$content}
	<p class="block alert">Cette page est vide, cliquez sur « Modifier » pour commencer à rédiger son contenu.</p>
{else}
	{$content|raw}

	{if count($images) || count($files)}
	<div class="wikiFiles">
		<h3>Fichiers liés à cette page</h3>

		{if count($images)}
		<ul class="gallery">
			{foreach from=$images item="file"}
				<li>
					<figure>
						<a class="internal-image" href="{$file->url()}"><img src="{$file->thumb_url()}" alt="" title="{$file.name}" /></a>
					</figure>
				</li>
			{/foreach}
		</ul>
		{/if}

		{if count($files)}
		<ul class="files">
			{foreach from=$files item="file"}
				<li>
					<aside class="fichier" class="internal-file"><a href="{$file->url()}">{$file.name}</a>
					<small>({$file.mime}, {$file.size|size_in_bytes})</small></aside>
			   </li>
			{/foreach}
		</ul>
		{/if}
	</div>
	{/if}

	<p class="wikiFooter">
		Dernière modification le {$page.modified|date_long:true}
	</p>
{/if}


{include file="admin/_foot.tpl"}

Added src/templates/web/search.tpl version [8a727d1b73].











































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title="Rechercher dans le site web" current="web"}

<form method="post" action="{$self_url}" data-focus="1">
	<fieldset>
		<legend>Rechercher une page ou catégorie</legend>
		<p class="submit">
			<input type="text" name="q" value="{$query}" size="25" />
			{button type="submit" name="search" label="Chercher" shape="search" class="main"}
		</p>
	</fieldset>
</form>

{if $query}
	<p class="block alert">
		<strong>{$results_count}</strong> pages trouvées pour «&nbsp;{$query}&nbsp;»
	</p>

	<section class="search-results">
	{foreach from=$results item="result"}
		<article>
			<h4>
				<nav class="breadcrumbs">
					<ul>
						{foreach from=$result.breadcrumbs key="id" item="title"}
							<li><a href="{"!web/page.php?p=%s"|local_url|args:$id}" target="_parent">{$title}</a></li>
						{/foreach}
					</ul>
				</nav>
			</h4>
			<h3><a href="{"!web/page.php?p=%s"|local_url|args:$result.path}" target="_parent">{$result.title}</a></h3>
			<p>{$result.snippet|escape|clean_snippet}</p>
		</article>
	{/foreach}
	</section>
{/if}

{include file="admin/_foot.tpl"}

Modified src/www/_route.php from [d7347d2841] to [044eb9e8fb].

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
}
elseif (preg_match('!/admin/plugin/(.+?)/(.*)!', $uri, $match))
{
	$_GET['_p'] = $match[1];
	$_GET['_u'] = $match[2];
	require __DIR__ . '/admin/plugin.php';
}
elseif (preg_match('!/f/([\d\w]+)/(.+)!', $uri, $match))
{
	$_GET['id'] = $match[1];
	$_GET['file'] = $match[2];
	require __DIR__ . '/file.php';
}
elseif (preg_match('!/admin/!', $uri, $match))
{
	require __DIR__ . '/_inc.php';
	http_response_code(404);
	throw new UserException('Cette page n\'existe pas.');
}
else
{
	require __DIR__ . '/index.php';
}







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




37
38
39
40
41
42
43












44
45
46
47
}
elseif (preg_match('!/admin/plugin/(.+?)/(.*)!', $uri, $match))
{
	$_GET['_p'] = $match[1];
	$_GET['_u'] = $match[2];
	require __DIR__ . '/admin/plugin.php';
}












else
{
	require __DIR__ . '/index.php';
}

Modified src/www/admin/_inc.php from [d6f6a6d40f] to [0d408179d6].

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

namespace Garradin;

use Garradin\Membres\Session;

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

// Redirection automatique en HTTPS si nécessaire
if (PREFER_HTTPS !== true && PREFER_HTTPS >= 2 && empty($_SERVER['HTTPS']) && empty($_POST))
{
    utils::redirect(str_replace('http://', 'https://', utils::getSelfURL()));
    exit;
}

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











|







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

namespace Garradin;

use Garradin\Membres\Session;

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

// Redirection automatique en HTTPS si nécessaire
if (PREFER_HTTPS !== true && PREFER_HTTPS >= 2 && empty($_SERVER['HTTPS']) && empty($_POST))
{
    Utils::redirect(str_replace('http://', 'https://', Utils::getSelfURL()));
    exit;
}

function f($key)
{
    return \KD2\Form::get($key);
}
41
42
43
44
45
46
47
48

49
50
51
52
53
54
55
56
57
58

$tpl = Template::getInstance();
$tpl->assign('admin_url', ADMIN_URL);

$form = new Form;
$tpl->assign_by_ref('form', $form);

$session = new Session;


$tpl->assign('session', $session);
$tpl->assign('config', Config::getInstance()->getConfig());

if (!defined('Garradin\LOGIN_PROCESS'))
{
    if (!$session->isLogged())
    {
        if ($session->isOTPRequired())
        {







|
>


|







41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

$tpl = Template::getInstance();
$tpl->assign('admin_url', ADMIN_URL);

$form = new Form;
$tpl->assign_by_ref('form', $form);

$session = Session::getInstance();
$config = Config::getInstance();

$tpl->assign('session', $session);
$tpl->assign('config', $config);

if (!defined('Garradin\LOGIN_PROCESS'))
{
    if (!$session->isLogged())
    {
        if ($session->isOTPRequired())
        {
71
72
73
74
75
76
77
78
79
80
81
82






    $tpl->assign('current', '');

    if ($session->get('plugins_menu') === null)
    {
        // Construction de la liste de plugins pour le menu
        // et stockage en session pour ne pas la recalculer à chaque page
        $session->set('plugins_menu', Plugin::listMenu($user));
    }

    $tpl->assign('plugins_menu', $session->get('plugins_menu'));
}












|




>
>
>
>
>
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

    $tpl->assign('current', '');

    if ($session->get('plugins_menu') === null)
    {
        // Construction de la liste de plugins pour le menu
        // et stockage en session pour ne pas la recalculer à chaque page
        $session->set('plugins_menu', Plugin::listMenu($session));
    }

    $tpl->assign('plugins_menu', $session->get('plugins_menu'));
}

// Make sure we allow frames to work
if (array_key_exists('_dialog', $_GET)) {
    header('X-Frame-Options: SAMEORIGIN', true);
}

Modified src/www/admin/acc/_inc.php from [734ee883db] to [b6e3c3f264].

1
2
3
4
5
6
7
8
9
10
11

12
13
14
15
16
17
18
<?php

namespace Garradin;

use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ACCES);

$current_year_id = $session->get('acc_year');


if ($current_year_id) {
	// Check that the year is still valid
	$current_year = Years::get($current_year_id);

	if (!$current_year || $current_year->closed) {
		$current_year_id = null;








|


>







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

namespace Garradin;

use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ);

$current_year_id = $session->get('acc_year');
$current_year = null;

if ($current_year_id) {
	// Check that the year is still valid
	$current_year = Years::get($current_year_id);

	if (!$current_year || $current_year->closed) {
		$current_year_id = null;

Modified src/www/admin/acc/accounts/deposit.php from [ceabbe5204] to [0f05ff8022].

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
<?php
namespace Garradin;

use Garradin\Accounting\Accounts;
use Garradin\Accounting\Transactions;
use Garradin\Entities\Accounting\Transaction;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

if (!CURRENT_YEAR_ID) {
	Utils::redirect(ADMIN_URL . 'acc/years/?msg=OPEN');
}

$account = Accounts::get((int)qg('id'));

if (!$account) {
	throw new UserException("Le compte demandé n'existe pas.");
}

$checked = f('deposit') ?: [];

$journal = $account->getDepositJournal(CURRENT_YEAR_ID, $checked);
$transaction = new Transaction;
$transaction->id_year = CURRENT_YEAR_ID;
$transaction->id_creator = $session->getUser()->id;

$form->runIf('save', function () use ($account, $checked, $transaction, $journal) {
	if (!count($checked)) {
		throw new UserException('Aucune ligne n\'a été cochée, impossible de créer un dépôt. Peut-être vouliez-vous saisir un virement ?');
	}

	$transaction->importFromDepositForm();
	Transactions::saveDeposit($transaction, $journal, $checked);










|


















|







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
<?php
namespace Garradin;

use Garradin\Accounting\Accounts;
use Garradin\Accounting\Transactions;
use Garradin\Entities\Accounting\Transaction;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

if (!CURRENT_YEAR_ID) {
	Utils::redirect(ADMIN_URL . 'acc/years/?msg=OPEN');
}

$account = Accounts::get((int)qg('id'));

if (!$account) {
	throw new UserException("Le compte demandé n'existe pas.");
}

$checked = f('deposit') ?: [];

$journal = $account->getDepositJournal(CURRENT_YEAR_ID, $checked);
$transaction = new Transaction;
$transaction->id_year = CURRENT_YEAR_ID;
$transaction->id_creator = $session->getUser()->id;

$form->runIf('save', function () use ($checked, $transaction, $journal) {
	if (!count($checked)) {
		throw new UserException('Aucune ligne n\'a été cochée, impossible de créer un dépôt. Peut-être vouliez-vous saisir un virement ?');
	}

	$transaction->importFromDepositForm();
	Transactions::saveDeposit($transaction, $journal, $checked);

Modified src/www/admin/acc/accounts/journal.php from [90c7758145] to [da00ba6416].

33
34
35
36
37
38
39






40
41
42
43
44
45
46
47

// The account has a different chart after changing the current year:
// get back to the list of accounts to select a new account!
if ($account->id_chart != $year->id_chart) {
	Utils::redirect(ADMIN_URL . 'acc/accounts/?chart_change');
}







$can_edit = $session->canAccess('compta', Membres::DROIT_ADMIN) && !$year->closed;
$simple = qg('simple');

// Use simplified view for favourite accounts
if (null === $simple) {
	$simple = (bool) $account->type;
}








>
>
>
>
>
>
|







33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

// The account has a different chart after changing the current year:
// get back to the list of accounts to select a new account!
if ($account->id_chart != $year->id_chart) {
	Utils::redirect(ADMIN_URL . 'acc/accounts/?chart_change');
}

// The account has a different chart after changing the current year:
// get back to the list of accounts to select a new account!
if ($account->id_chart != $year->id_chart) {
	Utils::redirect(ADMIN_URL . 'acc/accounts/?chart_change');
}

$can_edit = $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN) && !$year->closed;
$simple = qg('simple');

// Use simplified view for favourite accounts
if (null === $simple) {
	$simple = (bool) $account->type;
}

Modified src/www/admin/acc/accounts/reconcile.php from [a1470d0cad] to [f870477b9e].

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

use Garradin\Accounting\Accounts;
use Garradin\Accounting\Transactions;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

if (!CURRENT_YEAR_ID) {
	Utils::redirect(ADMIN_URL . 'acc/years/?msg=OPEN');
}

$account = Accounts::get((int)qg('id'));









|







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

use Garradin\Accounting\Accounts;
use Garradin\Accounting\Transactions;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

if (!CURRENT_YEAR_ID) {
	Utils::redirect(ADMIN_URL . 'acc/years/?msg=OPEN');
}

$account = Accounts::get((int)qg('id'));

Modified src/www/admin/acc/accounts/reconcile_assist.php from [393b54f6c1] to [b1a074fbc8].

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

use Garradin\Accounting\Accounts;
use Garradin\Accounting\Transactions;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

if (!CURRENT_YEAR_ID) {
	Utils::redirect(ADMIN_URL . 'acc/years/?msg=OPEN');
}

$account = Accounts::get((int)qg('id'));









|







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

use Garradin\Accounting\Accounts;
use Garradin\Accounting\Transactions;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

if (!CURRENT_YEAR_ID) {
	Utils::redirect(ADMIN_URL . 'acc/years/?msg=OPEN');
}

$account = Accounts::get((int)qg('id'));

Modified src/www/admin/acc/accounts/simple.php from [50a686e3e9] to [e1797be0df].

27
28
29
30
31
32
33
34
35
36
37
38
	$type = key($types);
}

$list = Transactions::listByType(CURRENT_YEAR_ID, $type);
$list->setTitle(sprintf('Suivi - %s', $types[$type]));
$list->loadFromQueryString();

$can_edit = $session->canAccess('compta', Membres::DROIT_ADMIN) && !$year->closed;

$tpl->assign(compact('type', 'list', 'types', 'can_edit', 'year'));

$tpl->display('acc/accounts/simple.tpl');







|




27
28
29
30
31
32
33
34
35
36
37
38
	$type = key($types);
}

$list = Transactions::listByType(CURRENT_YEAR_ID, $type);
$list->setTitle(sprintf('Suivi - %s', $types[$type]));
$list->loadFromQueryString();

$can_edit = $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN) && !$year->closed;

$tpl->assign(compact('type', 'list', 'types', 'can_edit', 'year'));

$tpl->display('acc/accounts/simple.tpl');

Modified src/www/admin/acc/charts/accounts/delete.php from [6c837a3adc] to [7053ee989f].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Accounts;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$account = Accounts::get((int) qg('id'));

if (!$account) {
	throw new UserException("Le compte demandé n'existe pas.");
}








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Accounts;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$account = Accounts::get((int) qg('id'));

if (!$account) {
	throw new UserException("Le compte demandé n'existe pas.");
}

Modified src/www/admin/acc/charts/accounts/edit.php from [cd87e2dec4] to [1dfbc47d52].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Accounts;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$account = Accounts::get((int) qg('id'));

if (!$account) {
	throw new UserException("Le compte demandé n'existe pas.");
}








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Accounts;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$account = Accounts::get((int) qg('id'));

if (!$account) {
	throw new UserException("Le compte demandé n'existe pas.");
}

Modified src/www/admin/acc/charts/accounts/new.php from [9b98b97dd0] to [3f258f32a4].

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

use Garradin\Entities\Accounting\Account;
use Garradin\Accounting\Accounts;
use Garradin\Accounting\Charts;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$chart = Charts::get((int)qg('id'));

if (!$chart) {
	throw new UserException('Ce plan comptable n\'existe pas');
}










|







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

use Garradin\Entities\Accounting\Account;
use Garradin\Accounting\Accounts;
use Garradin\Accounting\Charts;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$chart = Charts::get((int)qg('id'));

if (!$chart) {
	throw new UserException('Ce plan comptable n\'existe pas');
}

Modified src/www/admin/acc/charts/accounts/selector.php from [695773dc6d] to [fb856540e1].

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

namespace Garradin;

use Garradin\Entities\Accounting\Account;
use Garradin\Accounting\Charts;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../../_inc.php';

header('X-Frame-Options: SAMEORIGIN', true);

$targets = qg('targets');
$chart = qg('chart');








if ($chart) {
	$chart = Charts::get((int)qg('chart'));
}
elseif (qg('year')) {
	$year = Years::get((int)qg('year'));

	if ($year) {
		$chart = $year->chart();
	}
}
elseif ($current_year) {
	$chart = $current_year->chart();
}

if (!$chart) {
	throw new UserException('Aucun exercice ouvert disponible');
}

// Cache the page until the charts have changed
$hash = sha1($targets . $chart->id());
$last_change = Config::getInstance()->get('last_chart_change') ?: time();

// Exit if there's no need to reload
Utils::HTTPCache($hash, $last_change);

$accounts = $chart->accounts();

$tpl->assign(compact('chart', 'targets'));

$all = (bool) qg('all');

if (!$targets) {










<
<


>
>
>
>
>
>
>



















<
<
<
<
<
<
<







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

namespace Garradin;

use Garradin\Entities\Accounting\Account;
use Garradin\Accounting\Charts;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../../_inc.php';



$targets = qg('targets');
$chart = qg('chart');

// Cache the page until the charts have changed
$hash = sha1($targets . $chart);
$last_change = Config::getInstance()->get('last_chart_change') ?: time();

// Exit if there's no need to reload
Utils::HTTPCache($hash, $last_change);

if ($chart) {
	$chart = Charts::get((int)qg('chart'));
}
elseif (qg('year')) {
	$year = Years::get((int)qg('year'));

	if ($year) {
		$chart = $year->chart();
	}
}
elseif ($current_year) {
	$chart = $current_year->chart();
}

if (!$chart) {
	throw new UserException('Aucun exercice ouvert disponible');
}








$accounts = $chart->accounts();

$tpl->assign(compact('chart', 'targets'));

$all = (bool) qg('all');

if (!$targets) {

Modified src/www/admin/acc/charts/delete.php from [35b792e76d] to [7b80471a02].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Charts;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$chart = Charts::get((int) qg('id'));

if (!$chart) {
	throw new UserException("Le plan comptable demandé n'existe pas.");
}








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Charts;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$chart = Charts::get((int) qg('id'));

if (!$chart) {
	throw new UserException("Le plan comptable demandé n'existe pas.");
}

Modified src/www/admin/acc/charts/edit.php from [e0ba778302] to [012860281d].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Charts;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$chart = Charts::get((int) qg('id'));

if (!$chart) {
	throw new UserException("Le plan comptable demandé n'existe pas.");
}








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Charts;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$chart = Charts::get((int) qg('id'));

if (!$chart) {
	throw new UserException("Le plan comptable demandé n'existe pas.");
}

Modified src/www/admin/acc/charts/export.php from [34dc474779] to [4305b4133c].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace Garradin;

use Garradin\Accounting\Charts;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$chart = Charts::get((int) qg('id'));

if (!$chart) {
	throw new UserException("Le plan comptable demandé n'existe pas.");
}

CSV::export(
	null !== qg('ods') ? 'ods' : 'csv',
	sprintf('Plan comptable - %s - %s', Config::getInstance()->get('nom_asso'), $chart->label),
	$chart->accounts()->export()
);







|












1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace Garradin;

use Garradin\Accounting\Charts;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$chart = Charts::get((int) qg('id'));

if (!$chart) {
	throw new UserException("Le plan comptable demandé n'existe pas.");
}

CSV::export(
	null !== qg('ods') ? 'ods' : 'csv',
	sprintf('Plan comptable - %s - %s', Config::getInstance()->get('nom_asso'), $chart->label),
	$chart->accounts()->export()
);

Modified src/www/admin/acc/charts/import.php from [db18f89e13] to [105414a37d].

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

use Garradin\Accounting\Accounts;
use Garradin\Accounting\Charts;
use Garradin\Entities\Accounting\Chart;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

if (f('import') && $form->check('acc_charts_import', ['file' => 'file|required'])) {
	try {
		$chart = new Chart;
		$chart->importForm();
		$chart->save();
		$chart->accounts()->importUpload($_FILES['file']); // This will save everything









|







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

use Garradin\Accounting\Accounts;
use Garradin\Accounting\Charts;
use Garradin\Entities\Accounting\Chart;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

if (f('import') && $form->check('acc_charts_import', ['file' => 'file|required'])) {
	try {
		$chart = new Chart;
		$chart->importForm();
		$chart->save();
		$chart->accounts()->importUpload($_FILES['file']); // This will save everything

Modified src/www/admin/acc/charts/index.php from [78edbd5354] to [3348c1ac3a].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace Garradin;

use Garradin\Entities\Accounting\Chart;
use Garradin\Accounting\Charts;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ACCES);

$tpl->assign('list', Charts::list());

if ($session->canAccess('compta', Membres::DROIT_ADMIN)) {
	if (f('new') && $form->check('acc_charts_new')) {
		try {
			$chart = new Chart;
			$chart->importForm();
			$chart->save();

			if (f('copy')) {








|



|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace Garradin;

use Garradin\Entities\Accounting\Chart;
use Garradin\Accounting\Charts;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ);

$tpl->assign('list', Charts::list());

if ($session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN)) {
	if (f('new') && $form->check('acc_charts_new')) {
		try {
			$chart = new Chart;
			$chart->importForm();
			$chart->save();

			if (f('copy')) {

Modified src/www/admin/acc/index.php from [f7d3653bb9] to [e3b75e427f].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Years;
use Garradin\Accounting\Graph;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ACCES);

$tpl->assign('graphs', Graph::URL_LIST);

$tpl->assign('years', Years::listOpen(true));

$tpl->display('acc/index.tpl');








|






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Years;
use Garradin\Accounting\Graph;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ);

$tpl->assign('graphs', Graph::URL_LIST);

$tpl->assign('years', Years::listOpen(true));

$tpl->display('acc/index.tpl');

Modified src/www/admin/acc/reports/_inc.php from [461ecc0cc6] to [923715a8c5].

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

namespace Garradin;

use Garradin\Accounting\Years;
use Garradin\Accounting\Accounts;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ACCES);

$criterias = [];

if (qg('analytical'))
{
	$account = Accounts::get((int) qg('analytical'));










|







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

namespace Garradin;

use Garradin\Accounting\Years;
use Garradin\Accounting\Accounts;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ);

$criterias = [];

if (qg('analytical'))
{
	$account = Accounts::get((int) qg('analytical'));

Modified src/www/admin/acc/reports/graphs.php from [fc9df953bc] to [25629cf275].

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

use Garradin\Accounting\Years;
use Garradin\Accounting\Graph;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('compta', Membres::DROIT_ACCES);

$year = Years::get((int)qg('year'));

$tpl->assign('graphs', Graph::URL_LIST);
$tpl->assign('year', $year);

$tpl->display('acc/reports/graphs.tpl');








|







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

use Garradin\Accounting\Years;
use Garradin\Accounting\Graph;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ);

$year = Years::get((int)qg('year'));

$tpl->assign('graphs', Graph::URL_LIST);
$tpl->assign('year', $year);

$tpl->display('acc/reports/graphs.tpl');

Modified src/www/admin/acc/reports/projects.php from [ebc0bf8009] to [a9751b3536].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace Garradin;

use Garradin\Accounting\Accounts;
use Garradin\Accounting\Reports;
use Garradin\Entities\Accounting\Account;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ACCES);

$by_year = (bool)qg('by_year');

$tpl->assign(compact('by_year'));
$tpl->assign('list', Reports::getAnalyticalSums($by_year));

$tpl->assign('analytical_type', Account::TYPE_ANALYTICAL);
$tpl->assign('analytical_accounts_count', CURRENT_YEAR_ID ? $current_year->accounts()->countByType(Account::TYPE_ANALYTICAL) : null);

$tpl->display('acc/reports/projects.tpl');









|










1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace Garradin;

use Garradin\Accounting\Accounts;
use Garradin\Accounting\Reports;
use Garradin\Entities\Accounting\Account;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ);

$by_year = (bool)qg('by_year');

$tpl->assign(compact('by_year'));
$tpl->assign('list', Reports::getAnalyticalSums($by_year));

$tpl->assign('analytical_type', Account::TYPE_ANALYTICAL);
$tpl->assign('analytical_accounts_count', CURRENT_YEAR_ID ? $current_year->accounts()->countByType(Account::TYPE_ANALYTICAL) : null);

$tpl->display('acc/reports/projects.tpl');

Modified src/www/admin/acc/transactions/actions.php from [d994046118] to [56b1e90e1d].

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

namespace Garradin;

use Garradin\Accounting\Transactions;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$check = f('check');

if (!$check || !is_array($check)) {
	throw new UserException('Aucune écriture n\'a été sélectionnée.');
}










|







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

namespace Garradin;

use Garradin\Accounting\Transactions;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$check = f('check');

if (!$check || !is_array($check)) {
	throw new UserException('Aucune écriture n\'a été sélectionnée.');
}

Modified src/www/admin/acc/transactions/creator.php from [5ea9d63a0d] to [9941809933].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
namespace Garradin;

use Garradin\Accounting\Reports;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ACCES);

$u = (new Membres)->get((int)qg('id'));

if (!$u) {
	throw new UserException('Ce membre n\'existe pas');
}

$criterias = ['creator' => $u->id];

$tpl->assign('journal', Reports::getJournal($criterias));
$tpl->assign('transaction_creator', $u);

$tpl->display('acc/transactions/creator.tpl');







|













1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
namespace Garradin;

use Garradin\Accounting\Reports;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ);

$u = (new Membres)->get((int)qg('id'));

if (!$u) {
	throw new UserException('Ce membre n\'existe pas');
}

$criterias = ['creator' => $u->id];

$tpl->assign('journal', Reports::getJournal($criterias));
$tpl->assign('transaction_creator', $u);

$tpl->display('acc/transactions/creator.tpl');

Modified src/www/admin/acc/transactions/delete.php from [f22c7ed0fd] to [517085aced].

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

namespace Garradin;

use Garradin\Accounting\Transactions;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$transaction = Transactions::get((int) qg('id'));

if (!$transaction) {
	throw new UserException('Cette écriture n\'existe pas');
}









|







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

namespace Garradin;

use Garradin\Accounting\Transactions;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$transaction = Transactions::get((int) qg('id'));

if (!$transaction) {
	throw new UserException('Cette écriture n\'existe pas');
}

Deleted src/www/admin/acc/transactions/delete_file.php version [19275e53c5].

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

namespace Garradin;

use Garradin\Accounting\Transactions;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$csrf_key = sprintf('acc_delete_file_%d', qg('id'));
$redirect = sprintf(ADMIN_URL . 'acc/transactions/details.php?id=%d', qg('from'));

require __DIR__ . '/../../common/delete_file.php';
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























Modified src/www/admin/acc/transactions/details.php from [2e3f27db39] to [392d0a8bfa].

20
21
22
23
24
25
26


27
28
29

$tpl->assign(compact('transaction', 'csrf_key'));

$tpl->assign('files', $transaction->listFiles());
$tpl->assign('tr_year', $transaction->year());
$tpl->assign('creator_name', $transaction->id_creator ? (new Membres)->getNom($transaction->id_creator) : null);



$tpl->assign('related_users', $transaction->listLinkedUsers());

$tpl->display('acc/transactions/details.tpl');







>
>



20
21
22
23
24
25
26
27
28
29
30
31

$tpl->assign(compact('transaction', 'csrf_key'));

$tpl->assign('files', $transaction->listFiles());
$tpl->assign('tr_year', $transaction->year());
$tpl->assign('creator_name', $transaction->id_creator ? (new Membres)->getNom($transaction->id_creator) : null);

$tpl->assign('can_upload', $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_WRITE));
$tpl->assign('file_parent', $transaction->getAttachementsDirectory());
$tpl->assign('related_users', $transaction->listLinkedUsers());

$tpl->display('acc/transactions/details.tpl');

Modified src/www/admin/acc/transactions/edit.php from [d3ba5816a5] to [b0a077e022].

1
2
3
4
5

6
7
8
9
10
11
12
13
14
15
16
17
18
<?php

namespace Garradin;

use Garradin\Entities\Accounting\Transaction;

use Garradin\Accounting\Transactions;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$transaction = Transactions::get((int) qg('id'));

if (!$transaction) {
	throw new UserException('Cette écriture n\'existe pas');
}






>





|







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

namespace Garradin;

use Garradin\Entities\Accounting\Transaction;
use Garradin\Entities\Files\File;
use Garradin\Accounting\Transactions;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$transaction = Transactions::get((int) qg('id'));

if (!$transaction) {
	throw new UserException('Cette écriture n\'existe pas');
}

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
];

if (f('save') && $form->check('acc_edit_' . $transaction->id(), $rules)) {
	try {
		$transaction->importFromEditForm();
		$transaction->save();

		// Append file
		if (!empty($_FILES['file']['name'])) {
			$file = Fichiers::upload($_FILES['file']);
			$file->linkTo(Fichiers::LIEN_COMPTA, $transaction->id());
		}

		// Link members
		if (null !== f('users') && is_array(f('users'))) {
			$transaction->updateLinkedUsers(array_keys(f('users')));
		}
		else {
			// Remove all
			$transaction->updateLinkedUsers([]);







<
<
<
<
<
<







37
38
39
40
41
42
43






44
45
46
47
48
49
50
];

if (f('save') && $form->check('acc_edit_' . $transaction->id(), $rules)) {
	try {
		$transaction->importFromEditForm();
		$transaction->save();







		// Link members
		if (null !== f('users') && is_array(f('users'))) {
			$transaction->updateLinkedUsers(array_keys(f('users')));
		}
		else {
			// Remove all
			$transaction->updateLinkedUsers([]);

Modified src/www/admin/acc/transactions/new.php from [4ff3b2387c] to [d8191985b4].

1
2
3
4
5

6
7
8
9
10
11
12
13
14
15
16
17
<?php
namespace Garradin;

use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Transaction;

use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ECRITURE);

if (!CURRENT_YEAR_ID) {
	Utils::redirect(ADMIN_URL . 'acc/years/?msg=OPEN');
}

$chart = $current_year->chart();
$accounts = $chart->accounts();





>




|







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

use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Transaction;
use Garradin\Entities\Files\File;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_WRITE);

if (!CURRENT_YEAR_ID) {
	Utils::redirect(ADMIN_URL . 'acc/years/?msg=OPEN');
}

$chart = $current_year->chart();
$accounts = $chart->accounts();
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
if (f('save') && $form->check('acc_transaction_new')) {
	try {
		$transaction->id_year = $current_year->id();
		$transaction->importFromNewForm();
		$transaction->id_creator = $session->getUser()->id;
		$transaction->save();

		// Append fileTYPE_ANALYTICAL
		if (!empty($_FILES['file']['name'])) {
			$file = Fichiers::upload($_FILES['file']);
			$file->linkTo(Fichiers::LIEN_COMPTA, $transaction->id());
		}

		 // Link members
		if (null !== f('users') && is_array(f('users'))) {
			$transaction->updateLinkedUsers(array_keys(f('users')));
		}

		$session->set('acc_last_date', f('date'));








<
<
<
<
<
<







72
73
74
75
76
77
78






79
80
81
82
83
84
85
if (f('save') && $form->check('acc_transaction_new')) {
	try {
		$transaction->id_year = $current_year->id();
		$transaction->importFromNewForm();
		$transaction->id_creator = $session->getUser()->id;
		$transaction->save();







		 // Link members
		if (null !== f('users') && is_array(f('users'))) {
			$transaction->updateLinkedUsers(array_keys(f('users')));
		}

		$session->set('acc_last_date', f('date'));

Modified src/www/admin/acc/transactions/service_user.php from [0473be53b7] to [fb13cfe6c3].

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

use Garradin\Accounting\Reports;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ACCES);

$criterias = ['service_user' => (int)qg('id')];

$tpl->assign('balance', Reports::getClosingSumsWithAccounts($criterias));
$tpl->assign('journal', Reports::getJournal($criterias));
$tpl->assign('user_id', qg('user'));

$tpl->display('acc/transactions/service_user.tpl');








|








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

use Garradin\Accounting\Reports;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ);

$criterias = ['service_user' => (int)qg('id')];

$tpl->assign('balance', Reports::getClosingSumsWithAccounts($criterias));
$tpl->assign('journal', Reports::getJournal($criterias));
$tpl->assign('user_id', qg('user'));

$tpl->display('acc/transactions/service_user.tpl');

Modified src/www/admin/acc/transactions/user.php from [698de7ba96] to [4b78a375e7].

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

use Garradin\Accounting\Reports;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ACCES);

$u = (new Membres)->get((int)qg('id'));

if (!$u) {
	throw new UserException('Ce membre n\'existe pas');
}









|







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

use Garradin\Accounting\Reports;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ);

$u = (new Membres)->get((int)qg('id'));

if (!$u) {
	throw new UserException('Ce membre n\'existe pas');
}

Modified src/www/admin/acc/years/balance.php from [a4edefccf4] to [3a08646ae0].

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

use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Transaction;
use Garradin\Accounting\Reports;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$year = Years::get((int)qg('id'));

if (!$year) {
	throw new UserException('Exercice inconnu.');
}











|







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

use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Transaction;
use Garradin\Accounting\Reports;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$year = Years::get((int)qg('id'));

if (!$year) {
	throw new UserException('Exercice inconnu.');
}

Modified src/www/admin/acc/years/close.php from [440db77f6b] to [124836d0d2].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$year = Years::get((int)qg('id'));

if (!$year) {
	throw new UserException('Exercice inconnu.');
}








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$year = Years::get((int)qg('id'));

if (!$year) {
	throw new UserException('Exercice inconnu.');
}

Modified src/www/admin/acc/years/delete.php from [1f309cbc2f] to [112d142c77].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$year = Years::get((int)qg('id'));

if (!$year) {
	throw new UserException('Exercice inconnu.');
}








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$year = Years::get((int)qg('id'));

if (!$year) {
	throw new UserException('Exercice inconnu.');
}

Modified src/www/admin/acc/years/edit.php from [1f8f1a8a07] to [b69940ea09].

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

use Garradin\Accounting\Years;
use Garradin\Entities\Accounting\Year;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$year = Years::get((int)qg('id'));

if (!$year) {
	throw new UserException('Exercice inconnu.');
}









|







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

use Garradin\Accounting\Years;
use Garradin\Entities\Accounting\Year;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$year = Years::get((int)qg('id'));

if (!$year) {
	throw new UserException('Exercice inconnu.');
}

Modified src/www/admin/acc/years/import.php from [4878b9a097] to [2d7d375a16].

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

use Garradin\Accounting\Transactions;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$year_id = (int) qg('id') ?: CURRENT_YEAR_ID;

if ($year_id === CURRENT_YEAR_ID) {
	$year = $current_year;
}
else {








|







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

use Garradin\Accounting\Transactions;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$year_id = (int) qg('id') ?: CURRENT_YEAR_ID;

if ($year_id === CURRENT_YEAR_ID) {
	$year = $current_year;
}
else {

Modified src/www/admin/acc/years/index.php from [9f9b364525] to [6ddabc3291].

1
2
3
4
5
6
7
8
9
10
11
12
<?php
namespace Garradin;

use Garradin\Accounting\Years;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ACCES);

$tpl->assign('list', Years::list(true));

$tpl->display('acc/years/index.tpl');







|




1
2
3
4
5
6
7
8
9
10
11
12
<?php
namespace Garradin;

use Garradin\Accounting\Years;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ);

$tpl->assign('list', Years::list(true));

$tpl->display('acc/years/index.tpl');

Modified src/www/admin/acc/years/new.php from [e19c3a9787] to [089708c6e5].

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

use Garradin\Accounting\Years;
use Garradin\Accounting\Charts;
use Garradin\Services\Fees;
use Garradin\Entities\Accounting\Year;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

$form->runIf('new', function () {
	$year = new Year;
	$year->importForm();
	$year->save();

	if ($old_id = qg('from')) {










|







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

use Garradin\Accounting\Years;
use Garradin\Accounting\Charts;
use Garradin\Services\Fees;
use Garradin\Entities\Accounting\Year;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN);

$form->runIf('new', function () {
	$year = new Year;
	$year->importForm();
	$year->save();

	if ($old_id = qg('from')) {

Deleted src/www/admin/common/delete_file.php version [dbcb7d7cc0].

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
<?php
namespace Garradin;

use Garradin\Services\Services;

if (!defined('Garradin\ROOT')) {
	die('Access denied.');
}

if (!isset($csrf_key, $redirect)) {
	throw new \InvalidArgumentException('Missing params');
}

try {
	$file = new Fichiers(qg('id'));
}
catch (\InvalidArgumentException $e) {
	throw new UserException($e->getMessage());
}

if (!$file->checkAccess($session))
{
    throw new UserException('Vous n\'avez pas accès à ce fichier.');
}

$form->runIf('delete', function () use ($file) {
	$file->remove();
}, $csrf_key, $redirect);

$tpl->assign(compact('file', 'csrf_key'));

$tpl->display('common/delete_file.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































Added src/www/admin/common/files/_preview.php version [cc05638664].





















































































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

namespace Garradin;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\Web\Render\Skriv;
use Garradin\Web\Web;

require_once __DIR__ . '/../../_inc.php';

$page = null;

if ($path = qg('f')) {
	$file = Files::get($path);

	if (!$file || !$file->checkReadAccess($session)) {
		throw new UserException('Vous n\'avez pas le droit de lire ce fichier.');
	}
}
elseif ($web = qg('w')) {
	$page = Web::get($web);

	if (!$page || !$page->file() || !$page->file()->checkReadAccess($session)) {
		throw new UserException('Vous n\'avez pas le droit de lire ce fichier.');
	}

	$file = $page->file();
}
else {
	throw new UserException('Fichier inconnu');
}

$prefix = $page ? 'web/page.php?uri=' : 'common/files/_preview.php?p=' . File::CONTEXT_DOCUMENTS . '/';

$content = Skriv::render($file, f('content'), ['prefix' => ADMIN_URL . $prefix]);

$tpl->assign(compact('file', 'content'));

$tpl->assign('custom_css', ['!web/css.php']);

$tpl->display('common/files/_preview.tpl');

Added src/www/admin/common/files/delete.php version [f68ffe55ca].



































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

use Garradin\Entities\Files\File;
use Garradin\Files\Files;

require __DIR__ . '/../../_inc.php';

$file = Files::get(qg('p'));

if (!$file) {
	throw new UserException('Fichier inconnu');
}

if (!$file->checkDeleteAccess($session)) {
    throw new UserException('Vous n\'avez pas le droit de supprimer ce fichier.');
}

$context = $file->context();

if ($context == File::CONTEXT_CONFIG || $context == File::CONTEXT_WEB) {
	throw new UserException('Vous n\'avez pas le droit de supprimer ce fichier.');
}

$csrf_key = 'file_delete_' . $file->pathHash();

$form->runIf('delete', function () use ($file) {
	$file->delete();
}, $csrf_key, '!');

$tpl->assign(compact('file', 'csrf_key'));

$tpl->display('common/files/delete.tpl');

Added src/www/admin/common/files/edit.php version [9d117de49a].



















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

use Garradin\Entities\Files\File;
use Garradin\Files\Files;

require __DIR__ . '/../../_inc.php';

$file = Files::get(qg('p'));

if (!$file) {
	throw new UserException('Fichier inconnu');
}

if (!$file->checkWriteAccess($session)) {
	throw new UserException('Vous n\'avez pas le droit de modifier ce fichier.');
}

$editor = $file->getEditor();
$csrf_key = 'edit_file_' . $file->pathHash();

$form->runIf('content', function () use ($file) {
	$file->setContent(f('content'));

	if (qg('js') !== null) {
		die('{"success":true}');
	}

}, $csrf_key, Utils::getSelfURI());

$tpl->assign('file', $file);

if (!$editor) {
	$tpl->assign('file', $file);
	$tpl->display('common/file_upload.tpl');
}
else {
	$content = $file->fetch();
	$tpl->assign(compact('csrf_key', 'content'));
	$tpl->display(sprintf('common/files/edit_%s.tpl', $editor));
}

Added src/www/admin/common/files/preview.php version [a192851b45].





















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

use Garradin\Entities\Files\File;
use Garradin\Files\Files;

require __DIR__ . '/../../_inc.php';

$file = Files::get(qg('p'));

if (!$file) {
	throw new UserException('Ce fichier est introuvable.');
}

if (!$file->checkReadAccess($session)) {
	throw new UserException('Vous n\'avez pas le droit de lire ce fichier.');
}

try {
	$tpl->assign('content', $file->render());
	$tpl->assign('file', $file);
	$tpl->display('common/files/_preview.tpl');
}
catch (\LogicException $e) {
	$file->serve($session);
}

Added src/www/admin/common/files/upload.php version [873b74e7d4].















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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;

use Garradin\Entities\Files\File;
use Garradin\Files\Files;

require __DIR__ . '/../../_inc.php';

$parent = qg('p');

if (!File::checkCreateAccess($parent, $session)) {
	throw new UserException('Vous n\'avez pas le droit d\'ajouter de fichier.');
}

$csrf_key = 'upload_file_' . md5($parent);

$form->runIf('upload', function () use ($parent) {
	File::upload($parent, 'file');
}, $csrf_key, Utils::getSelfURI());

$tpl->assign(compact('parent', 'csrf_key'));

$tpl->display('common/files/upload.tpl');

Modified src/www/admin/common/saved_searches.php from [08209d1978] to [b986545306].

1
2
3
4
5
6
7
8
9






10
11
12
13
14
15
16
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

if (empty($target) || !in_array($target, Recherche::TARGETS)) {
    throw new UserException('Cible inconnue');
}







$recherche = new Recherche;
$mode = null;

if (qg('edit') || qg('delete'))
{
	$r = $recherche->get(qg('edit') ?: qg('delete'));










>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

if (empty($target) || !in_array($target, Recherche::TARGETS)) {
    throw new UserException('Cible inconnue');
}

if (empty($search_url)) {
	throw new \LogicException('Missing $search_url');
}

$access_section = $target == 'compta' ? $session::SECTION_ACCOUNTING : $session::SECTION_USERS;

$recherche = new Recherche;
$mode = null;

if (qg('edit') || qg('delete'))
{
	$r = $recherche->get(qg('edit') ?: qg('delete'));

50
51
52
53
54
55
56
57
58
59
}

if (!$mode)
{
	$tpl->assign('liste', $recherche->getList($user->id, $target));
}

$tpl->assign(compact('mode', 'target', 'search_url'));

$tpl->display('common/search/saved_searches.tpl');







|


56
57
58
59
60
61
62
63
64
65
}

if (!$mode)
{
	$tpl->assign('liste', $recherche->getList($user->id, $target));
}

$tpl->assign(compact('mode', 'target', 'search_url', 'access_section'));

$tpl->display('common/search/saved_searches.tpl');

Modified src/www/admin/common/search.php from [42043bbc1a] to [f310a1310c].

1
2
3
4
5
6
7
8
9
10
11


12
13
14
15
16
17
18
<?php
namespace Garradin;

use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

if (empty($target) || !in_array($target, Recherche::TARGETS)) {
	throw new UserException('Cible inconnue');
}



$recherche = new Recherche;

$query = (object) [
	'query' => f('q') ? json_decode(f('q'), true) : null,
	'order' => f('order') ?: $recherche->getDefaultOrder($target),
	'limit' => f('limit') ?: 100,
	'desc'  => $recherche->getDefaultDesc($target),











>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace Garradin;

use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

if (empty($target) || !in_array($target, Recherche::TARGETS)) {
	throw new UserException('Cible inconnue');
}

$access_section = $target == 'compta' ? $session::SECTION_ACCOUNTING : $session::SECTION_USERS;

$recherche = new Recherche;

$query = (object) [
	'query' => f('q') ? json_decode(f('q'), true) : null,
	'order' => f('order') ?: $recherche->getDefaultOrder($target),
	'limit' => f('limit') ?: 100,
	'desc'  => $recherche->getDefaultDesc($target),
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
		$query->limit = (int) f('limit') ?: $query->limit;
	}
}

// Recherche SQL
if (f('sql_query')) {
	// Only admins can run custom queries, others can only run saved queries
	$session->requireAccess($target, Membres::DROIT_ADMIN);
	$sql_query = f('sql_query');

	if ($session->canAccess('config', Membres::DROIT_ADMIN)) {
		$is_unprotected = (bool) f('unprotected');
	}
	else {
		$is_unprotected = false;
	}
}








|


|







56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
		$query->limit = (int) f('limit') ?: $query->limit;
	}
}

// Recherche SQL
if (f('sql_query')) {
	// Only admins can run custom queries, others can only run saved queries
	$session->requireAccess($access_section, $session::ACCESS_ADMIN);
	$sql_query = f('sql_query');

	if ($session->canAccess($session::SECTION_CONFIG, $session::ACCESS_ADMIN)) {
		$is_unprotected = (bool) f('unprotected');
	}
	else {
		$is_unprotected = false;
	}
}

182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
	}

	$query->desc = true;
	$result = null;
}

$columns = $recherche->getColumns($target);
$is_admin = $session->canAccess($target, Membres::DROIT_ADMIN);
$schema = $recherche->schema($target);

$tpl->assign(compact('query', 'sql_query', 'result', 'columns', 'is_admin', 'schema', 'search', 'target', 'is_unprotected'));

if ($target == 'compta') {
	$tpl->display('acc/search.tpl');
}
else {
	$tpl->display('admin/membres/recherche.tpl');
}







|










184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
	}

	$query->desc = true;
	$result = null;
}

$columns = $recherche->getColumns($target);
$is_admin = $session->canAccess($access_section, $session::ACCESS_ADMIN);
$schema = $recherche->schema($target);

$tpl->assign(compact('query', 'sql_query', 'result', 'columns', 'is_admin', 'schema', 'search', 'target', 'is_unprotected'));

if ($target == 'compta') {
	$tpl->display('acc/search.tpl');
}
else {
	$tpl->display('admin/membres/recherche.tpl');
}

Modified src/www/admin/config/_inc.php from [b18c881300] to [807fafd5a8].

1
2
3
4
5
6
7
8
9
<?php

namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('config', Membres::DROIT_ADMIN);

$tpl->assign('garradin_website', WEBSITE);






|

<
1
2
3
4
5
6
7
8

<?php

namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_CONFIG, $session::ACCESS_ADMIN);


Modified src/www/admin/config/advanced/index.php from [2748d571f1] to [68a26e2219].

1
2
3
4

5
6


7
8
9
10
11
12
13
14
15
16











17


18
19
<?php
namespace Garradin;

use Garradin\Accounting\Years;


require_once __DIR__ . '/../_inc.php';



$form->runIf('reset_ok', function () use ($session) {
	Install::reset($session, f('passe_verif'));
}, 'reset', Utils::getSelfURI(['msg' => 'RESET']));

$form->runIf('reopen_ok', function () use ($session) {
	$year = Years::get((int) f('year'));
	$year->reopen($session->getUser()->id);
}, 'reopen_year', Utils::getSelfURI(['msg' => 'REOPEN']));












$tpl->assign('closed_years', Years::listClosedAssoc());



$tpl->display('admin/config/advanced/index.tpl');




>


>
>










>
>
>
>
>
>
>
>
>
>
>

>
>


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
<?php
namespace Garradin;

use Garradin\Accounting\Years;
use Garradin\Files\Files;

require_once __DIR__ . '/../_inc.php';

$quota_used = Files::getUsedQuota();

$form->runIf('reset_ok', function () use ($session) {
	Install::reset($session, f('passe_verif'));
}, 'reset', Utils::getSelfURI(['msg' => 'RESET']));

$form->runIf('reopen_ok', function () use ($session) {
	$year = Years::get((int) f('year'));
	$year->reopen($session->getUser()->id);
}, 'reopen_year', Utils::getSelfURI(['msg' => 'REOPEN']));

if (FILE_STORAGE_BACKEND !== 'SQLite' && ENABLE_TECH_DETAILS) {
	$form->runIf('migrate_backend_ok', function () {
		Files::migrateStorage('SQLite', FILE_STORAGE_BACKEND, null, FILE_STORAGE_CONFIG);
		Files::truncateStorage('SQLite');
	}, 'migrate_backend', Utils::getSelfURI(['msg' => 'MIGRATION_OK']));

	$form->runIf('migrate_back_ok', function () {
		Files::migrateStorage(FILE_STORAGE_BACKEND, 'SQLite', FILE_STORAGE_CONFIG, null);
	}, 'migrate_back', Utils::getSelfURI(['msg' => 'MIGRATION_OK']));
}

$tpl->assign('closed_years', Years::listClosedAssoc());
$tpl->assign('quota_used', $quota_used);
$tpl->assign('storage_backend', FILE_STORAGE_BACKEND);

$tpl->display('admin/config/advanced/index.tpl');

Added src/www/admin/config/backup/automatique.php version [05a939d15b].





































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

if (!ENABLE_AUTOMATIC_BACKUPS)
{
    throw new UserException('Les sauvegardes automatiques sont désactivées.');
}

if (f('config'))
{
    $form->check('backup_config', [
        'frequence_sauvegardes' => 'present|numeric|min:0|max:365',
        'nombre_sauvegardes' => 'present|numeric|min:1|max:90',
    ]);

    if (!$form->hasErrors())
    {
        try {
            $config->set('frequence_sauvegardes', f('frequence_sauvegardes'));
            $config->set('nombre_sauvegardes', f('nombre_sauvegardes'));
            $config->save();

            Utils::redirect(ADMIN_URL . 'config/donnees/automatique.php?ok=config');
        } catch (UserException $e) {
            $form->addError($e->getMessage());
        }
    }
}

$tpl->assign('ok', qg('ok'));

$tpl->display('admin/config/donnees/automatique.tpl');

Added src/www/admin/config/backup/index.php version [2160415827].













>
>
>
>
>
>
1
2
3
4
5
6
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$tpl->display('admin/config/backup/index.tpl');

Added src/www/admin/config/backup/restore.php version [6ef87fa07a].































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$s = new Sauvegarde;
$code = null; // error code

$form->runIf('restore', function () use ($s) {
	if (!f('selected')) {
		throw new UserException('Aucune sauvegarde sélectionnée');
	}

	$r = $s->restoreFromLocal(f('selected'));
	Utils::redirect(Utils::getSelfURI(['ok' => 'restore', 'code' => (int)$r]));
}, 'backup_manage');

$form->runIf('remove', function () use ($s) {
	if (!f('selected')) {
		throw new UserException('Aucune sauvegarde sélectionnée');
	}

	$s->remove(f('selected'));
}, 'backup_manage', Utils::getSelfURI(['ok' => 'remove']));


$form->runIf('restore_file', function () use ($s, &$code, $session) {
	// Ignorer la vérification d'intégrité si autorisé et demandé
	$check = (ALLOW_MODIFIED_IMPORT && f('force_import')) ? false : true;

	try {
		$r = $s->restoreFromUpload($_FILES['file'], $session->getUser()->id, $check);
		Utils::redirect(ADMIN_URL . 'config/donnees/?ok=restore&code=' . (int)$r);
	} catch (UserException $e) {
		$code = $e->getCode();
	}
}, 'backup_restore');


$ok_code = qg('code'); // return code
$ok = qg('ok'); // return message

$list = $s->getList();

$tpl->assign(compact('code', 'list', 'ok', 'ok_code'));

$tpl->display('admin/config/backup/restore.tpl');

Added src/www/admin/config/backup/save.php version [0defc760cc].



















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

use Garradin\Files\Files;

require_once __DIR__ . '/../_inc.php';

$s = new Sauvegarde;

// Download database
$form->runIf('download', function () use ($s) {
	$s->dump();
	exit;
}, 'backup_download');

// Download all files as ZIP
$form->runIf('download_files', function () use ($s) {
	$s->dumpFilesZip();
	exit;
}, 'files_download');

// Create local backup
$form->runIf('create', function () use ($s) {
	$s->create();
}, 'backup_create', Utils::getSelfURI(['ok' => 'create']));

$form->runIf('config', function () {
	if (!ENABLE_AUTOMATIC_BACKUPS) {
		return;
	}

	$frequency = (int) f('frequence_sauvegardes');

	if ($frequency < 0 || $frequency > 365) {
		throw new UserException('Fréquence invalide');
	}

	$number = (int) f('nombre_sauvegardes');

	if ($number < 0 || $number > 50) {
		throw new UserException('Nombre de sauvegardes invalide. Le maximum est de 50 sauvegardes.');
	}

	$config = Config::getInstance();
	$config->set('frequence_sauvegardes', $frequency);
	$config->set('nombre_sauvegardes', $number);
	$config->save();
}, 'backup_config', Utils::getSelfURI(['ok' => 'config']));

$db_size = $s->getDBSize();
$files_size = Files::getUsedQuota();

$ok = qg('ok'); // return message

$tpl->assign(compact('ok', 'db_size', 'files_size'));

$tpl->display('admin/config/backup/save.tpl');

Modified src/www/admin/config/categories/index.php from [c7ce3325e0] to [5f595523cd].

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
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$cats = new Membres\Categories;


if (f('save'))
{
    $form->check('new_cat', [
        'nom' => 'required',
    ]);

    if (!$form->hasErrors())

    {
        $cats->add([
            'nom' => f('nom'),

        ]);

        Utils::redirect(ADMIN_URL . 'config/categories/');
    }


}


$tpl->assign('liste', $cats->listCompleteWithStats());

$tpl->display('admin/config/categories/index.tpl');



<
|
|
>

|
|
|
<
<

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

|


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\Entities\Users\Category;
use Garradin\Users\Categories;
use Garradin\Membres\Session;

require_once __DIR__ . '/../_inc.php';

$csrf_key = 'cat_create';



$form->runIf('save', function() {
	$cat = new Category;

	$cat->importForm([
		'name'   => f('name'),
		'hidden' => 0,
	]);
	$cat->setAllPermissions(Session::ACCESS_NONE);


	$cat->save();
}, $csrf_key, Utils::getSelfURI());

$list =  Categories::listWithStats();

$tpl->assign(compact('list', 'csrf_key'));

$tpl->display('admin/config/categories/index.tpl');

Modified src/www/admin/config/categories/modifier.php from [79f85734c9] to [fc55af1c22].

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
<?php
namespace Garradin;





require_once __DIR__ . '/../_inc.php';

$cats = new Membres\Categories;

qv(['id' => 'required|numeric']);

$id = (int) qg('id');

$cat = $cats->get($id);

if (!$cat)
{
    throw new UserException("Cette catégorie n'existe pas.");
}


if (f('save'))

{

    $droits = implode(',', [
        Membres::DROIT_AUCUN,
        Membres::DROIT_ACCES,
        Membres::DROIT_ECRITURE,
        Membres::DROIT_ADMIN,
    ]);




    $form->check('edit_cat_' . $id, [
        'nom'                       => 'required',
        'droit_wiki'                => 'in:' . $droits,
        'droit_compta'              => 'in:' . $droits,
        'droit_membres'             => 'in:' . $droits,

        'droit_config'              => sprintf('in:%s,%s', Membres::DROIT_ADMIN, Membres::DROIT_AUCUN),
        'droit_connexion'           => sprintf('in:%s,%s', Membres::DROIT_ACCES, Membres::DROIT_AUCUN),
        'droit_inscription'         => sprintf('in:%s,%s', Membres::DROIT_ACCES, Membres::DROIT_AUCUN),
        'cacher'                    => 'boolean',
    ]);

    if (!$form->hasErrors())
    {
        $data = [
            'nom'           =>  f('nom'),
            'droit_wiki'    =>  (int) f('droit_wiki'),
            'droit_compta'  =>  (int) f('droit_compta'),
            'droit_config'  =>  (int) f('droit_config'),
            'droit_membres' =>  (int) f('droit_membres'),
            'droit_connexion' => (int) f('droit_connexion'),
            'droit_inscription' => (int) f('droit_inscription'),
            'cacher'        =>  (int) f('cacher'),
        ];

        // Ne pas permettre de modifier la connexion, l'accès à la config et à la gestion des membres
        // pour la catégorie du membre qui édite les catégories, sinon il pourrait s'empêcher
        // de se connecter ou n'avoir aucune catégorie avec le droit de modifier les catégories !
        if ($cat->id == $user->id_categorie)
        {
            $data['droit_connexion'] = Membres::DROIT_ACCES;
            $data['droit_config'] = Membres::DROIT_ADMIN;
        }

        try {
            $cats->edit($id, $data);

            if ($id == $user->id_categorie)
            {
                // Mise à jour de la session courante
                $session->refresh();
            }

            Utils::redirect(ADMIN_URL . 'config/categories/');
        }
        catch (UserException $e)
        {
            $form->addError($e->getMessage());

        }



    }
}

$tpl->assign('cat', $cat);

$tpl->assign('readonly', $cat->id == $user->id_categorie ? 'disabled="disabled"' : '');

$tpl->assign('membres', new Membres);

$tpl->display('admin/config/categories/modifier.tpl');


>
>
>
>



<
<
<
<
|

<
<
|
<
|


>
|
>
|
>
|
<
<
<
<
|

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

<
<
<
<
<
<
<
<
|
<
<

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


<
|
<

|


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
<?php
namespace Garradin;

use Garradin\Entities\Users\Category;
use Garradin\Users\Categories;
use Garradin\Membres\Session;

require_once __DIR__ . '/../_inc.php';





$cat = Categories::get((int) qg('id'));



if (!$cat) {

	throw new UserException("Cette catégorie n'existe pas.");
}

$user = $session->getUser();

$csrf_key = 'cat_edit_' . $cat->id();

$form->runIf('save', function () use ($cat, $session) {
	$user = $session->getUser();




	$cat->importForm();

	// Ne pas permettre de modifier la connexion, l'accès à la config et à la gestion des membres
	// pour la catégorie du membre qui édite les catégories, sinon il pourrait s'empêcher
	// de se connecter ou n'avoir aucune catégorie avec le droit de modifier les catégories !
	if ($cat->id() == $user->id_category) {




		$cat->set('perm_connect', Session::ACCESS_READ);
		$cat->set('perm_config', Session::ACCESS_ADMIN);




	}





















	$cat->save();



	if ($cat->id() == $user->id_category) {


		$session->refresh();
	}

}, $csrf_key, '!config/categories/');




$permissions = Category::PERMISSIONS;

foreach ($permissions as $key => &$config) {
	if ($cat->id() == $user->id_category && in_array($key, [Session::SECTION_CONFIG, Session::SECTION_CONNECT])) {
		$config['disabled'] = true;
	}
}


unset($config);


$tpl->assign(compact('csrf_key', 'cat', 'permissions'));

$tpl->display('admin/config/categories/modifier.tpl');

Modified src/www/admin/config/categories/supprimer.php from [93c453e7a7] to [b94b2508bb].

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
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$cats = new Membres\Categories;

qv(['id' => 'required|numeric']);

$id = (int) qg('id');

$cat = $cats->get($id);

if (!$cat)
{
    throw new UserException("Cette catégorie n'existe pas.");
}


if ($cat->id == $user->id_categorie)

{

    throw new UserException("Vous ne pouvez pas supprimer votre catégorie.");
}

if (f('delete'))
{
    $form->check('delete_cat_' . $id);

    if (!$form->hasErrors())
    {
        try {
            $cats->remove($id);
            Utils::redirect(ADMIN_URL . 'config/categories/');
        }
        catch (UserException $e)
        {
            $form->addError($e->getMessage());
        }
    }
}

$tpl->assign('cat', $cat);

$tpl->display('admin/config/categories/supprimer.tpl');



<
<
|

|

|

<
<
|
<
|


>
|
>
|
>
|


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


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\Users\Categories;

require_once __DIR__ . '/../_inc.php';

$cat = Categories::get((int) qg('id'));



if (!$cat) {

	throw new UserException("Cette catégorie n'existe pas.");
}

$user = $session->getUser();

$csrf_key = 'cat_delete_' . $cat->id();

if ($cat->id() == $user->id_category) {
	throw new UserException("Vous ne pouvez pas supprimer votre catégorie.");
}

$form->runIf('delete', function () use($cat) {


	$cat->delete();




}, $csrf_key, '!config/categories/');








$tpl->assign(compact('cat', 'csrf_key'));

$tpl->display('admin/config/categories/supprimer.tpl');

Deleted src/www/admin/config/donnees/automatique.php version [05a939d15b].

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
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

if (!ENABLE_AUTOMATIC_BACKUPS)
{
    throw new UserException('Les sauvegardes automatiques sont désactivées.');
}

if (f('config'))
{
    $form->check('backup_config', [
        'frequence_sauvegardes' => 'present|numeric|min:0|max:365',
        'nombre_sauvegardes' => 'present|numeric|min:1|max:90',
    ]);

    if (!$form->hasErrors())
    {
        try {
            $config->set('frequence_sauvegardes', f('frequence_sauvegardes'));
            $config->set('nombre_sauvegardes', f('nombre_sauvegardes'));
            $config->save();

            Utils::redirect(ADMIN_URL . 'config/donnees/automatique.php?ok=config');
        } catch (UserException $e) {
            $form->addError($e->getMessage());
        }
    }
}

$tpl->assign('ok', qg('ok'));

$tpl->display('admin/config/donnees/automatique.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































Deleted src/www/admin/config/donnees/index.php version [d6ee96dc35].

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
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$s = new Sauvegarde;

$tpl->assign('code', null);

$form->runIf('download', function () use ($s) {
    $s->dump();
    exit;
}, 'backup_download');

$form->runIf('restore_file', function () use ($s, $tpl, $session) {
    // Ignorer la vérification d'intégrité si autorisé et demandé
    $check = (ALLOW_MODIFIED_IMPORT && f('force_import')) ? false : true;

    try {
        $r = $s->restoreFromUpload($_FILES['file'], $session->getUser()->id, $check);
        Utils::redirect(ADMIN_URL . 'config/donnees/?ok=restore&code=' . (int)$r);
    } catch (UserException $e) {
        $tpl->assign('code', $e->getCode());
    }
}, 'backup_restore');

$tpl->assign('db_size', $s->getDBSize());
$tpl->assign('files_size', $s->getDBFilesSize());

$tpl->assign('ok_code', qg('code'));
$tpl->assign('ok', qg('ok'));
$tpl->assign('now_date', date('Y-m-d'));

$tpl->assign('max_file_size', Utils::getMaxUploadSize());

$tpl->display('admin/config/donnees/index.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































Deleted src/www/admin/config/donnees/local.php version [9914dfe2ec].

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
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$s = new Sauvegarde;

if (qg('download')) {
	$s->dump(qg('download'));
	exit;
}

$form->runIf('create', function () use ($s) {
	$s->create();
}, 'backup_create', Utils::getSelfURI(['ok' => 'create']));

$form->runIf('restore', function () use ($s) {
	if (!f('selected')) {
		throw new UserException('Aucune sauvegarde sélectionnée');
	}

	$r = $s->restoreFromLocal(f('selected'));
	Utils::redirect(Utils::getSelfURI(['ok' => 'restore', 'code' => (int)$r]));
}, 'backup_manage');

$form->runIf('remove', function () use ($s) {
	if (!f('selected')) {
		throw new UserException('Aucune sauvegarde sélectionnée');
	}

	$s->remove(f('selected'));
}, 'backup_manage', Utils::getSelfURI(['ok' => 'remove']));

$tpl->assign('ok_code', qg('code'));
$tpl->assign('ok', qg('ok'));
$tpl->assign('list', $s->getList());

$tpl->display('admin/config/donnees/local.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































Modified src/www/admin/config/index.php from [d2afe0f99d] to [b8ee1564e9].

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
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

if (f('save') && $form->check('config'))
{
    try {
        $config->set('nom_asso', f('nom_asso'));
        $config->set('email_asso', f('email_asso'));
        $config->set('adresse_asso', f('adresse_asso'));
        $config->set('site_asso', f('site_asso'));
        $config->set('accueil_wiki', f('accueil_wiki'));
        $config->set('accueil_connexion', f('accueil_connexion'));
        $config->set('categorie_membres', f('categorie_membres'));

        $config->set('champ_identite', f('champ_identite'));
        $config->set('champ_identifiant', f('champ_identifiant'));

        $config->set('pays', f('pays'));
        $config->set('monnaie', f('monnaie'));

        // N'enregistrer les couleurs que si ce ne sont pas les couleurs par défaut
        if (f('couleur1') != ADMIN_COLOR1 || f('couleur2') != ADMIN_COLOR2)
        {
            $config->set('couleur1', f('couleur1'));
            $config->set('couleur2', f('couleur2'));
        }
        else
        {
            $config->set('couleur1', null);
            $config->set('couleur2', null);
        }

        if (trim(f('image_fond')) != '') {
            $config->set('image_fond', f('image_fond'));
        }
        elseif (!f('image_fond') && !$config->get('couleur1') && !$config->get('couleur2')) {
            $config->set('image_fond', null);
        }

        $config->save();

        Utils::redirect(ADMIN_URL . 'config/?ok');
    }
    catch (UserException $e)
    {
        $form->addError($e->getMessage());
    }
}

$tpl->assign('ok', qg('ok') !== null);

$server_time = time();

$tpl->assign('garradin_version', garradin_version() . ' [' . (garradin_manifest() ?: 'release') . ']');

$tpl->assign('new_version', ENABLE_TECH_DETAILS ? Utils::getLatestVersion() : null);
$tpl->assign('php_version', phpversion());
$tpl->assign('has_gpg_support', \KD2\Security::canUseEncryption());
$tpl->assign('server_time', $server_time);

$v = \SQLite3::version();
$tpl->assign('sqlite_version', $v['versionString']);

$tpl->assign('pays', Utils::getCountryList());

$cats = new Membres\Categories;
$tpl->assign('membres_cats', $cats->listSimple());

$tpl->assign('champs', $config->get('champs_membres')->getList());

$tpl->assign('couleur1', $config->get('couleur1') ?: ADMIN_COLOR1);
$tpl->assign('couleur2', $config->get('couleur2') ?: ADMIN_COLOR2);

$image_fond = ADMIN_BACKGROUND_IMAGE;

if ($config->get('image_fond'))
{
    try {
        $f = new Fichiers($config->get('image_fond'));
        $image_fond = $f->getURL();
    }
    catch (\InvalidArgumentException $e)
    {
        // Fichier qui n'existe pas/plus


    }
}


$tpl->assign('background_image_source', $image_fond);
$tpl->assign('background_image_default', ADMIN_BACKGROUND_IMAGE);
$tpl->assign('couleurs_defaut', [ADMIN_COLOR1, ADMIN_COLOR2]);

$tpl->assign('custom_js', ['color_helper.js']);
$tpl->display('admin/config/index.tpl');



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

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

|

<



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
<?php
namespace Garradin;

use Garradin\Users\Categories;
use Garradin\Files\Files;










use Garradin\Entities\Files\File;





require_once __DIR__ . '/_inc.php';








$config = Config::getInstance();


$form->runIf('save', function () use ($config) {




	$config->importForm();


	$config->save();
}, 'config', Utils::getSelfURI(['ok' => '']));








$tpl->assign([



	'garradin_version' => garradin_version() . ' [' . (garradin_manifest() ?: 'release') . ']',

	'new_version'      => ENABLE_TECH_DETAILS ? Utils::getLatestVersion() : null,
	'php_version'      => phpversion(),
	'has_gpg_support'  => \KD2\Security::canUseEncryption(),
	'server_time'      => time(),

	'sqlite_version'   => \SQLite3::version()['versionString'],


	'countries'        => Utils::getCountryList(),
	'membres_cats'     => Categories::listSimple(),



	'champs'           => $config->get('champs_membres')->listAssocNames(),
	'color1'           => ADMIN_COLOR1,

	'color2'           => ADMIN_COLOR2,
	'garradin_website' => WEBSITE,

]);



$homepage = $config->admin_homepage;





if ($homepage && !Files::get($homepage)) {
	File::createAndStore(Utils::dirname($homepage), Utils::basename($homepage), null, '');
}

$admin_background = $config->get('admin_background');

$tpl->assign('background_image_current', $admin_background ? WWW_URL . $admin_background : null);
$tpl->assign('background_image_default', ADMIN_BACKGROUND_IMAGE);


$tpl->assign('custom_js', ['color_helper.js']);
$tpl->display('admin/config/index.tpl');

Modified src/www/admin/config/plugins.php from [3d32d903c2] to [b0c3c722c2].

51
52
53
54
55
56
57
58


59
    $tpl->assign('delete', true);
}
else
{
    $tpl->assign('liste_telecharges', Plugin::listDownloaded());
    $tpl->assign('liste_installes', Plugin::listInstalled());
}



$tpl->display('admin/config/plugins.tpl');








>
>

51
52
53
54
55
56
57
58
59
60
61
    $tpl->assign('delete', true);
}
else
{
    $tpl->assign('liste_telecharges', Plugin::listDownloaded());
    $tpl->assign('liste_installes', Plugin::listInstalled());
}

$tpl->assign('garradin_website', WEBSITE);

$tpl->display('admin/config/plugins.tpl');

Deleted src/www/admin/config/site.php version [4b2ceec322].

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
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

if (f('desactiver_site') && $form->check('config_site'))
{
    $config->set('desactiver_site', true);
    $config->save();
    Utils::redirect(ADMIN_URL . 'config/site.php');
}
elseif (f('activer_site') && $form->check('config_site'))
{
    $config->set('desactiver_site', false);
    $config->save();
    Utils::redirect(ADMIN_URL . 'config/site.php');
}

if (f('select') && f('reset') && $form->check('squelettes'))
{
    try {
        foreach (f('select') as $source)
        {
            if (!Squelette::resetSource($source))
            {
                throw new UserException('Impossible de réinitialiser le squelette.');
            }
        }
    
        Utils::redirect(ADMIN_URL . 'config/site.php?reset_ok');
    }
    catch (UserException $e)
    {
        $form->addError($e->getMessage());
    }
}


if (qg('edit'))
{
    $source = Squelette::getSource(qg('edit'));

    if (null === $source)
    {
        throw new UserException("Ce squelette n'existe pas.");
    }

    $csrf_key = 'edit_skel_' . md5(qg('edit'));

    if (f('save') && $form->check($csrf_key))
    {
        if (Squelette::editSource(qg('edit'), f('content')))
        {
            $fullscreen = null !== qg('fullscreen') ? '#fullscreen' : '';
            Utils::redirect(ADMIN_URL . 'config/site.php?edit='.rawurlencode(qg('edit')).'&ok'.$fullscreen);
        }
        else
        {
            $form->addError("Impossible d'enregistrer le squelette.");
        }
    }

    $tpl->assign('edit', ['file' => trim(qg('edit')), 'content' => $source]);
    $tpl->assign('csrf_key', $csrf_key);
}

$tpl->assign('sources', Squelette::listSources());

$tpl->assign('reset_ok', qg('reset_ok') !== null);
$tpl->assign('ok', qg('ok') !== null);
$tpl->display('admin/config/site.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































Added src/www/admin/docs/_inc.php version [f36ddb9ac0].



















>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
<?php

namespace Garradin;

use Garradin\Membres\Session;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess(Session::SECTION_DOCUMENTS, Session::ACCESS_READ);

Added src/www/admin/docs/action.php version [a63ecf9df6].













































































































































































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

namespace Garradin;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;

require_once __DIR__ . '/_inc.php';

$check = f('check');
$action = f('action');
$parent = f('parent');

$actions = ['move', 'delete'];

if (!is_array($check) || !count($check) || !in_array($action, $actions)) {
	throw new UserException('Action invalide');
}

$csrf_key = 'action_' . $action;

$form->runIf('confirm_delete', function () use ($check, $session) {
	foreach ($check as &$file) {
		$file = Files::get($file);

		if (!$file || !$file->checkDeleteAccess($session)) {
			throw new UserException('Impossible de supprimer un fichier car vous n\'avez pas le droit de le supprimer');
		}
	}

	unset($file);

	foreach ($check as $file) {
		$file->delete();
	}
}, $csrf_key, '!docs/?p=' . $parent);

$form->runIf(f('move') && f('select'), function () use ($check, $session) {
	foreach ($check as &$file) {
		$file = Files::get($file);

		if (!$file || !$file->checkWriteAccess($session) || $file->context() != File::CONTEXT_DOCUMENTS) {
			throw new UserException('Impossible de déplacer un fichier car vous n\'avez pas le droit de le modifier');
		}
	}

	$target = f('select');
	unset($file);

	foreach ($check as $file) {
		$file->move($target);
	}
}, $csrf_key, '!docs/?p=' . $parent);

$count = count($check);

$extra = compact('parent', 'action', 'check');
$tpl->assign(compact('csrf_key', 'extra', 'action', 'count'));

if ($action == 'delete') {
	$tpl->display('docs/action_delete.tpl');
}
else {
	$parent = f('current') ?? f('parent');

	if (!$parent) {
		$first_file = Files::get(current($check));

		if (!$first_file) {
			throw new UserException('Fichier introuvable');
		}

		$parent = $first_file->parent;
	}

	$directories = Files::list($parent);
	$directories = array_filter($directories, function (File $file) {
		return $file->type == File::TYPE_DIRECTORY;
	});

	$breadcrumbs = Files::getBreadcrumbs($parent);

	$tpl->assign(compact('directories', 'breadcrumbs', 'parent'));

	$tpl->display('docs/action_move.tpl');
}

Added src/www/admin/docs/index.php version [c2e76c334f].

































































































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

namespace Garradin;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;

require_once __DIR__ . '/_inc.php';

$path = trim(qg('p')) ?: File::CONTEXT_DOCUMENTS;

$files = Files::list($path);

// We consider that the first file has the same rights as the others
if (count($files)) {
	$first = current($files);

	if (!$first->checkReadAccess($session)) {
		throw new UserException('Vous n\'avez pas accès à ce répertoire');
	}

	$can_delete = $first->checkDeleteAccess($session);
	$can_write = $first->checkWriteAccess($session);
}
else {
	$can_delete = $can_write = false;
}

$context = Files::getContext($path);
$context_ref = Files::getContextRef($path);

$can_create = File::checkCreateAccess($path, $session);
$can_upload = $can_create && (($context == File::CONTEXT_DOCUMENTS || $context == File::CONTEXT_SKELETON)
	|| (($context == File::CONTEXT_USER || $context == File::CONTEXT_TRANSACTION) && $context_ref));
$can_mkdir = $can_create && ($context == File::CONTEXT_DOCUMENTS || $context == File::CONTEXT_SKELETON);

$breadcrumbs = Files::getBreadcrumbs($path);

$parent_path = Utils::dirname($path);

$quota_used = Files::getUsedQuota();
$quota_max = Files::getQuota();
$quota_left = Files::getRemainingQuota();
$quota_percent = round(($quota_used / $quota_max) * 100);

$tpl->assign(compact('path', 'files', 'can_write', 'can_delete', 'can_mkdir', 'can_upload', 'context', 'context_ref', 'breadcrumbs', 'parent_path', 'quota_used', 'quota_max', 'quota_percent', 'quota_left'));

$tpl->display('docs/index.tpl');

Added src/www/admin/docs/new_dir.php version [e00667d877].





















































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

namespace Garradin;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;

require_once __DIR__ . '/_inc.php';

$parent = trim(qg('p'));

if (!File::checkCreateAccess(File::CONTEXT_DOCUMENTS, $session)) {
	throw new UserException('Vous n\'avez pas le droit de créer de répertoire ici.');
}

$csrf_key = 'create_dir';

$form->runIf('create', function () use ($parent) {
	$name = trim(f('name'));
	File::validatePath($parent . '/' . $name);
	File::createDirectory($parent, $name);
}, $csrf_key, '!docs/?p=' . $parent);

$tpl->assign(compact('csrf_key'));

$tpl->display('docs/new_dir.tpl');

Added src/www/admin/docs/new_file.php version [ad63719729].



































































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

namespace Garradin;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;

require_once __DIR__ . '/_inc.php';

$parent = trim(qg('p'));

if (!File::checkCreateAccess(File::CONTEXT_DOCUMENTS, $session)) {
	throw new UserException('Vous n\'avez pas le droit de créer de répertoire ici.');
}

$csrf_key = 'create_file';

$form->runIf('create', function () use ($parent) {
	$name = trim(f('name'));

	if (!strpos($name, '.')) {
		$name .= '.skriv';
	}

	File::validatePath($parent . '/' . $name);
	$name = File::filterName($name);

	$file = File::createAndStore($parent, $name, null, '');
}, $csrf_key, '!docs/?p=' . $parent);

$tpl->assign(compact('csrf_key'));

$tpl->display('docs/new_file.tpl');

Added src/www/admin/docs/search.php version [553721a33e].



















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;

require_once __DIR__ . '/_inc.php';

$q = trim(f('q'));

$tpl->assign('query', $q);

if ($q) {
	$r = Files::search($q, File::CONTEXT_DOCUMENTS . '%');
	$tpl->assign('results', $r);
	$tpl->assign('results_count', count($r));
}

function tpl_clean_snippet($str) {
	return preg_replace('!&lt;(/?b)&gt;!', '<$1>', $str);
}

$tpl->register_modifier('clean_snippet', 'Garradin\tpl_clean_snippet');

$tpl->display('docs/search.tpl');

Modified src/www/admin/index.php from [7e32fa08cc] to [bf52e33fdb].

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

namespace Garradin;

require_once __DIR__ . '/_inc.php';

$cats = new Membres\Categories;
$categorie = $cats->get($user->id_categorie);

$tpl->assign('categorie', $categorie);

$wiki = new Wiki;
$page = $wiki->getByURI($config->get('accueil_connexion'));
$tpl->assign('page', $page);

$tpl->assign('custom_css', ['wiki.css']);


$banner = null;
Plugin::fireSignal('accueil.banniere', ['user' => $user, 'session' => $session], $banner);










$tpl->assign('banniere', $banner);

$tpl->display('admin/index.tpl');
flush();

// Si pas de cron on réalise les tâches automatisées à ce moment-là
// c'est pas idéal mais mieux que rien
if (!USE_CRON)
{
	require_once ROOT . '/scripts/cron.php';
}




|
|
|
<

<
|
<
<
<

<
>



>
>
>
>
>
>
>
>
>
>
|










1
2
3
4
5
6
7

8

9



10

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php

namespace Garradin;

use Garradin\Web\Web;
use Garradin\Files\Files;
use Garradin\Entities\Files\File;



require_once __DIR__ . '/_inc.php';





$homepage = Config::getInstance()->get('admin_homepage');

$banner = null;
Plugin::fireSignal('accueil.banniere', ['user' => $user, 'session' => $session], $banner);

if ($homepage && ($file = Files::get($homepage))) {
	$homepage = $file->render(['prefix' => ADMIN_URL . 'common/files/preview.php?p=' . File::CONTEXT_DOCUMENTS . '/']);
}
else {
	$homepage = null;
}

$tpl->assign(compact('homepage', 'banner'));

$tpl->assign('custom_css', ['!web/css.php']);

$tpl->display('admin/index.tpl');
flush();

// Si pas de cron on réalise les tâches automatisées à ce moment-là
// c'est pas idéal mais mieux que rien
if (!USE_CRON)
{
	require_once ROOT . '/scripts/cron.php';
}

Modified src/www/admin/install.php from [23c948e5c1] to [f605686443].

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
<?php
namespace Garradin;



const INSTALL_PROCESS = true;

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






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

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

$tpl = Template::getInstance();
$tpl->assign('admin_url', ADMIN_URL);

$form = new Form;
$tpl->assign_by_ref('form', $form);

if (file_exists(DB_FILE))
{
    $tpl->assign('disabled', true);
}
else
{
    $tpl->assign('disabled', false);

    if (f('save'))
    {
        $form->check('install', [
            'nom_membre'   => 'required',
            'email_membre' => 'required|email',
            'passe'        => 'confirmed|required',
        ]);

        if (!$form->hasErrors())
        {
            try {
            	Install::install(f('nom_asso'), f('nom_membre'), f('email_membre'), f('passe'));

            	Utils::redirect(ADMIN_URL . 'login.php');
            }
            catch (UserException $e)
            {
                @unlink(DB_FILE);

                $form->addError($e->getMessage());
            }
        }
    }
}

$tpl->assign('passphrase', Utils::suggestPassword());
$tpl->display('admin/install.tpl');



>
>




>
>
>
>
>




















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

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
<?php
namespace Garradin;

use Garradin\Membres\Session;

const INSTALL_PROCESS = true;

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

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

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

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

$tpl = Template::getInstance();
$tpl->assign('admin_url', ADMIN_URL);

$form = new Form;
$tpl->assign_by_ref('form', $form);








$form->runIf('save', function () {











    Install::installFromForm();
    Session::getInstance()->forceLogin(1);





}, 'install', ADMIN_URL);







$tpl->display('admin/install.tpl');

Modified src/www/admin/login.php from [7cddf916d3] to [a530e4030b].

41
42
43
44
45
46
47
48
49
50
51
52
53
    if (!$session->login(f('_id'), f('password'), (bool) f('permanent'))) {
        throw new UserException(sprintf("Connexion impossible.\nVérifiez votre identifiant (%s) et votre mot de passe.", $id_field_name));
    }
}, 'login', ADMIN_URL);

$tpl->assign('ssl_enabled', empty($_SERVER['HTTPS']) ? false : true);
$tpl->assign('prefer_ssl', (bool)PREFER_HTTPS);
$tpl->assign('own_https_url', str_replace('http://', 'https://', utils::getSelfURI()));

$tpl->assign(compact('id_field_name'));
$tpl->assign('changed', qg('changed') !== null);

$tpl->display('admin/login.tpl');







|





41
42
43
44
45
46
47
48
49
50
51
52
53
    if (!$session->login(f('_id'), f('password'), (bool) f('permanent'))) {
        throw new UserException(sprintf("Connexion impossible.\nVérifiez votre identifiant (%s) et votre mot de passe.", $id_field_name));
    }
}, 'login', ADMIN_URL);

$tpl->assign('ssl_enabled', empty($_SERVER['HTTPS']) ? false : true);
$tpl->assign('prefer_ssl', (bool)PREFER_HTTPS);
$tpl->assign('own_https_url', str_replace('http://', 'https://', Utils::getSelfURI()));

$tpl->assign(compact('id_field_name'));
$tpl->assign('changed', qg('changed') !== null);

$tpl->display('admin/login.tpl');

Modified src/www/admin/logout.php from [2dab3d0640] to [89dde98700].

1
2
3
4
5
6
7
8
<?php
namespace Garradin;

const LOGIN_PROCESS = true;
require_once __DIR__ . '/_inc.php';

$session->logout();
Utils::redirect('/');







|
1
2
3
4
5
6
7
8
<?php
namespace Garradin;

const LOGIN_PROCESS = true;
require_once __DIR__ . '/_inc.php';

$session->logout();
Utils::redirect(WWW_URL);

Modified src/www/admin/membres/_inc.php from [def8326778] to [c16003df62].

1
2
3
4
5
6
7
8
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('membres', Membres::DROIT_ACCES);

$membres = new Membres;





|


1
2
3
4
5
6
7
8
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_READ);

$membres = new Membres;

Modified src/www/admin/membres/action.php from [d0b4b091d1] to [f19e35588b].

1
2


3
4
5
6
7
8
9
10
11
12
13
<?php
namespace Garradin;



require_once __DIR__ . '/_inc.php';

$session->requireAccess('membres', Membres::DROIT_ADMIN);

if (!f('selected') || !is_array(f('selected')) || !count(f('selected')))
{
    throw new UserException("Aucun membre sélectionné.");
}

$action = f('action');


>
>



|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Users\Categories;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);

if (!f('selected') || !is_array(f('selected')) || !count(f('selected')))
{
    throw new UserException("Aucun membre sélectionné.");
}

$action = f('action');
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
    }
}

if ($action == 'move' && f('confirm'))
{
    $form->check('membres_action', [
        'selected' => 'required|array',
        'id_categorie' => 'required|numeric',
    ]);

    if (!$form->hasErrors())
    {
        $membres->changeCategorie(f('id_categorie'), f('selected'));
        Utils::redirect(ADMIN_URL . 'membres/');
    }
}
elseif ($action == 'delete' && f('confirm'))
{
    $form->check('membres_action', [
        'selected' => 'required|array',







|




|







50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
    }
}

if ($action == 'move' && f('confirm'))
{
    $form->check('membres_action', [
        'selected' => 'required|array',
        'id_category' => 'required|numeric',
    ]);

    if (!$form->hasErrors())
    {
        $membres->changeCategorie(f('id_category'), f('selected'));
        Utils::redirect(ADMIN_URL . 'membres/');
    }
}
elseif ($action == 'delete' && f('confirm'))
{
    $form->check('membres_action', [
        'selected' => 'required|array',
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
}

$tpl->assign('selected', $list);
$tpl->assign('nb_selected', count($list));

if ($action == 'move')
{
    $cats = new Membres\Categories;

    $tpl->assign('membres_cats', $cats->listSimple());
}

$tpl->assign('action', $action);

$tpl->display('admin/membres/action.tpl');







<
<
|





77
78
79
80
81
82
83


84
85
86
87
88
89
}

$tpl->assign('selected', $list);
$tpl->assign('nb_selected', count($list));

if ($action == 'move')
{


    $tpl->assign('membres_cats', Categories::listSimple());
}

$tpl->assign('action', $action);

$tpl->display('admin/membres/action.tpl');

Modified src/www/admin/membres/ajouter.php from [9c63eece10] to [d3cc735a21].

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
<?php
namespace Garradin;



require_once __DIR__ . '/_inc.php';

$session->requireAccess('membres', Membres::DROIT_ECRITURE);

$cats = new Membres\Categories;
$champs = $config->get('champs_membres');

if (f('save'))
{
    $form->check('new_member', [
        'passe' => 'confirmed',
        // FIXME: ajouter les règles pour les champs membres
    ]);

    if (!$form->hasErrors())
    {
        try
        {
            if ($session->canAccess('membres', Membres::DROIT_ADMIN))
            {
                $id_categorie = f('id_categorie');
            }
            else
            {
                $id_categorie = $config->get('categorie_membres');
            }

            $data = ['id_categorie' => $id_categorie];

            foreach ($champs->getAll() as $key=>$dismiss)
            {
                $data[$key] = f($key);
            }

            $id = $membres->add($data);

            Utils::redirect(ADMIN_URL . 'membres/fiche.php?id='.(int)$id);
        }
        catch (UserException $e)
        {
            $form->addError($e->getMessage());
        }
    }
}

$tpl->assign('id_field_name', $config->get('champ_identifiant'));



$tpl->assign('passphrase', Utils::suggestPassword());
$tpl->assign('champs', $champs->getAll());

$tpl->assign('membres_cats', $cats->listSimple());
$tpl->assign('current_cat', f('id_categorie') ?: $config->get('categorie_membres'));

$tpl->display('admin/membres/ajouter.tpl');


>
>



|

<













|

|



|


|



















>
>



|
|


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
<?php
namespace Garradin;

use Garradin\Users\Categories;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_WRITE);


$champs = $config->get('champs_membres');

if (f('save'))
{
    $form->check('new_member', [
        'passe' => 'confirmed',
        // FIXME: ajouter les règles pour les champs membres
    ]);

    if (!$form->hasErrors())
    {
        try
        {
            if ($session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN))
            {
                $id_category = f('id_category');
            }
            else
            {
                $id_category = $config->get('categorie_membres');
            }

            $data = ['id_category' => $id_category];

            foreach ($champs->getAll() as $key=>$dismiss)
            {
                $data[$key] = f($key);
            }

            $id = $membres->add($data);

            Utils::redirect(ADMIN_URL . 'membres/fiche.php?id='.(int)$id);
        }
        catch (UserException $e)
        {
            $form->addError($e->getMessage());
        }
    }
}

$tpl->assign('id_field_name', $config->get('champ_identifiant'));

$tpl->assign('id_field_name', $config->get('champ_identifiant'));

$tpl->assign('passphrase', Utils::suggestPassword());
$tpl->assign('champs', $champs->getAll());

$tpl->assign('membres_cats', Categories::listSimple());
$tpl->assign('current_cat', f('id_category') ?: $config->get('categorie_membres'));

$tpl->display('admin/membres/ajouter.tpl');

Modified src/www/admin/membres/fiche.php from [1ec254fd3b] to [143e0f77e2].

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
<?php
namespace Garradin;

use Garradin\Accounting\Transactions;
use Garradin\Services\Services_User;


require_once __DIR__ . '/_inc.php';

qv(['id' => 'required|numeric']);

$id = (int) qg('id');

$membre = $membres->get($id);

if (!$membre)
{
    throw new UserException("Ce membre n'existe pas.");
}

$champs = $config->get('champs_membres');
$tpl->assign('champs', $champs->getList());

$cats = new Membres\Categories;

$categorie = $cats->get($membre->id_categorie);
$tpl->assign('categorie', $categorie);

$tpl->assign('services', Services_User::listDistinctForUser($membre->id));

if ($session->canAccess('compta', Membres::DROIT_ACCES)) {
	$tpl->assign('transactions_linked', Transactions::countForUser($membre->id));
	$tpl->assign('transactions_created', Transactions::countForCreator($membre->id));
}

$tpl->assign('membre', $membre);


$tpl->display('admin/membres/fiche.tpl');





>

















<
<
|
|



|





>


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
<?php
namespace Garradin;

use Garradin\Accounting\Transactions;
use Garradin\Services\Services_User;
use Garradin\Users\Categories;

require_once __DIR__ . '/_inc.php';

qv(['id' => 'required|numeric']);

$id = (int) qg('id');

$membre = $membres->get($id);

if (!$membre)
{
    throw new UserException("Ce membre n'existe pas.");
}

$champs = $config->get('champs_membres');
$tpl->assign('champs', $champs->getList());



$category = Categories::get($membre->id_category);
$tpl->assign('category', $category);

$tpl->assign('services', Services_User::listDistinctForUser($membre->id));

if ($session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ)) {
	$tpl->assign('transactions_linked', Transactions::countForUser($membre->id));
	$tpl->assign('transactions_created', Transactions::countForCreator($membre->id));
}

$tpl->assign('membre', $membre);
$tpl->assign('user_files_path', $membres->getAttachementsDirectory($membre->id));

$tpl->display('admin/membres/fiche.tpl');

Modified src/www/admin/membres/import.php from [9914c40830] to [ec0f7e7826].

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('membres', Membres::DROIT_ADMIN);

$import = new Membres\Import;

$tpl->assign('tab', null !== qg('export') ? 'export' : 'import');

if (qg('export') == 'csv')
{





|







1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);

$import = new Membres\Import;

$tpl->assign('tab', null !== qg('export') ? 'export' : 'import');

if (qg('export') == 'csv')
{

Modified src/www/admin/membres/index.php from [5989b9495b] to [a64439f1c2].

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;



require_once __DIR__ . '/_inc.php';

$cats = new Membres\Categories;

$categories = $cats->listSimple();
$hidden_categories = $cats->listHidden();

$current_cat = (int) qg('cat') ?: null;

// Deny access to hidden categories to users that are not admins
if ($current_cat && !$session->canAccess('membres', Membres::DROIT_ADMIN) && array_key_exists($current_cat, $hidden_categories)) {
	$current_cat = null;
}

$can_edit = $session->canAccess('membres', Membres::DROIT_ADMIN);

$list = $membres->listByCategory($current_cat);
$list->loadFromQueryString();

$tpl->assign('sent', null !== qg('sent'));

$id_field = Config::getInstance()->get('champ_identite');

$tpl->assign(compact('can_edit', 'list', 'current_cat', 'hidden_categories', 'categories', 'id_field'));

$tpl->display('admin/membres/index.tpl');


>
>



<
<
|
|




|



|











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\Users\Categories;

require_once __DIR__ . '/_inc.php';



$categories = Categories::listSimple();
$hidden_categories = Categories::listHidden();

$current_cat = (int) qg('cat') ?: null;

// Deny access to hidden categories to users that are not admins
if ($current_cat && !$session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN) && array_key_exists($current_cat, $hidden_categories)) {
	$current_cat = null;
}

$can_edit = $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);

$list = $membres->listByCategory($current_cat);
$list->loadFromQueryString();

$tpl->assign('sent', null !== qg('sent'));

$id_field = Config::getInstance()->get('champ_identite');

$tpl->assign(compact('can_edit', 'list', 'current_cat', 'hidden_categories', 'categories', 'id_field'));

$tpl->display('admin/membres/index.tpl');

Modified src/www/admin/membres/message.php from [7c97469c92] to [d30f1f2d16].

1
2


3
4
5
6
7
8
9
<?php
namespace Garradin;



require_once __DIR__ . '/_inc.php';

if (empty($user->email))
{
    throw new UserException("Vous devez renseigner l'adresse e-mail dans vos informations pour pouvoir contacter les autres membres.");
}


>
>







1
2
3
4
5
6
7
8
9
10
11
<?php
namespace Garradin;

use Garradin\Users\Categories;

require_once __DIR__ . '/_inc.php';

if (empty($user->email))
{
    throw new UserException("Vous devez renseigner l'adresse e-mail dans vos informations pour pouvoir contacter les autres membres.");
}
42
43
44
45
46
47
48
49
50
51
52
53
54
        catch (UserException $e)
        {
            $form->addError($e->getMessage());
        }
    }
}

$cats = new Membres\Categories;

$tpl->assign('categorie', $cats->get($membre->id_categorie));
$tpl->assign('membre', $membre);

$tpl->display('admin/membres/message.tpl');







<
<
|



44
45
46
47
48
49
50


51
52
53
54
        catch (UserException $e)
        {
            $form->addError($e->getMessage());
        }
    }
}



$tpl->assign('categorie', Categories::get($membre->id_category));
$tpl->assign('membre', $membre);

$tpl->display('admin/membres/message.tpl');

Modified src/www/admin/membres/message_collectif.php from [1fb0ba4034] to [040e680ac0].

1
2


3
4
5
6
7
8
9
10
11
12
13
<?php
namespace Garradin;



require_once __DIR__ . '/_inc.php';

$cats = new Membres\Categories;
$recherche = new Recherche;

if (f('send'))
{
    $form->check('send_message_co', [
        'sujet'      => 'required|string',
        'message'    => 'required|string',


>
>



<







1
2
3
4
5
6
7

8
9
10
11
12
13
14
<?php
namespace Garradin;

use Garradin\Users\Categories;

require_once __DIR__ . '/_inc.php';


$recherche = new Recherche;

if (f('send'))
{
    $form->check('send_message_co', [
        'sujet'      => 'required|string',
        'message'    => 'required|string',
51
52
53
54
55
56
57
58
59
60
61
        catch (UserException $e)
        {
            $form->addError($e->getMessage());
        }
    }
}

$tpl->assign('categories', $cats->listNotHidden());
$tpl->assign('recherches', $recherche->getList($user->id, 'membres'));

$tpl->display('admin/membres/message_collectif.tpl');







|



52
53
54
55
56
57
58
59
60
61
62
        catch (UserException $e)
        {
            $form->addError($e->getMessage());
        }
    }
}

$tpl->assign('categories', Categories::listNotHidden());
$tpl->assign('recherches', $recherche->getList($user->id, 'membres'));

$tpl->display('admin/membres/message_collectif.tpl');

Modified src/www/admin/membres/modifier.php from [a765c3047e] to [82d245779d].

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
<?php
namespace Garradin;



require_once __DIR__ . '/_inc.php';

$session->requireAccess('membres', Membres::DROIT_ECRITURE);

qv(['id' => 'required|numeric']);

$id = (int) qg('id');

$membre = $membres->get($id);

if (!$membre)
{
    throw new UserException("Ce membre n'existe pas.");
}

// Ne pas modifier le membre courant, on risque de se tirer une balle dans le pied
if ($membre->id == $user->id) {
    throw new UserException("Vous ne pouvez pas modifier votre propre profil, la modification doit être faite par un autre membre.");
}

$cats = new Membres\Categories;
$champs = $config->get('champs_membres');

// Protection contre la modification des admins par des membres moins puissants
$membre_cat = $cats->get($membre->id_categorie);

if (($membre_cat->droit_membres == Membres::DROIT_ADMIN)
    && ($user->droit_membres < Membres::DROIT_ADMIN))
{
    throw new UserException("Seul un membre admin peut modifier un autre membre admin.");
}

if (f('save'))
{
    $form->check('edit_member_' . $id, [


>
>



|

















<



|

|
|







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
<?php
namespace Garradin;

use Garradin\Users\Categories;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_WRITE);

qv(['id' => 'required|numeric']);

$id = (int) qg('id');

$membre = $membres->get($id);

if (!$membre)
{
    throw new UserException("Ce membre n'existe pas.");
}

// Ne pas modifier le membre courant, on risque de se tirer une balle dans le pied
if ($membre->id == $user->id) {
    throw new UserException("Vous ne pouvez pas modifier votre propre profil, la modification doit être faite par un autre membre.");
}


$champs = $config->get('champs_membres');

// Protection contre la modification des admins par des membres moins puissants
$membre_cat = Categories::get($membre->id_category);

if (($membre_cat->perm_users == $session::ACCESS_ADMIN)
    && ($user->perm_users < $session::ACCESS_ADMIN))
{
    throw new UserException("Seul un membre admin peut modifier un autre membre admin.");
}

if (f('save'))
{
    $form->check('edit_member_' . $id, [
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
            $data = [];

            foreach ($champs->getAll() as $key=>$config)
            {
                $data[$key] = f($key);
            }

            if ($session->canAccess('membres', Membres::DROIT_ADMIN) && $user->id != $membre->id)
            {
                $data['id_categorie'] = f('id_categorie');
                $data['id'] = f('id');
            }

            if (f('clear_otp')) {
                $data['secret_otp'] = null;
            }








|

|







47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
            $data = [];

            foreach ($champs->getAll() as $key=>$config)
            {
                $data[$key] = f($key);
            }

            if ($session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN) && $user->id != $membre->id)
            {
                $data['id_category'] = f('id_category');
                $data['id'] = f('id');
            }

            if (f('clear_otp')) {
                $data['secret_otp'] = null;
            }

81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
}

$config = Config::getInstance();
$tpl->assign('id_field_name', $config->get('champ_identifiant'));
$tpl->assign('passphrase', Utils::suggestPassword());
$tpl->assign('champs', $champs->getAll());

$tpl->assign('membres_cats', $cats->listSimple());
$tpl->assign('current_cat', f('id_categorie') ?: $membre->id_categorie);

$tpl->assign('can_change_id', $session->canAccess('membres', Membres::DROIT_ADMIN));

$tpl->assign('membre', $membre);

$tpl->display('admin/membres/modifier.tpl');







|
|

|




82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
}

$config = Config::getInstance();
$tpl->assign('id_field_name', $config->get('champ_identifiant'));
$tpl->assign('passphrase', Utils::suggestPassword());
$tpl->assign('champs', $champs->getAll());

$tpl->assign('membres_cats', Categories::listSimple());
$tpl->assign('current_cat', f('id_category') ?: $membre->id_category);

$tpl->assign('can_change_id', $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN));

$tpl->assign('membre', $membre);

$tpl->display('admin/membres/modifier.tpl');

Modified src/www/admin/membres/selector.php from [88f3f59197] to [325272ec6c].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

header('X-Frame-Options: SAMEORIGIN', true);

$text_query = trim(qg('q'));

$tpl->assign('list', []);

// Recherche simple
if ($text_query !== '')
{
    $tpl->assign('list', (new Membres)->quickSearch($text_query));
}

$tpl->assign('query', $text_query);

$tpl->display('admin/membres/selector.tpl');





<
<
|












1
2
3
4
5


6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';



$text_query = trim(qg('q') ?? f('q'));

$tpl->assign('list', []);

// Recherche simple
if ($text_query !== '')
{
    $tpl->assign('list', (new Membres)->quickSearch($text_query));
}

$tpl->assign('query', $text_query);

$tpl->display('admin/membres/selector.tpl');

Modified src/www/admin/membres/supprimer.php from [628b9e4ac1] to [a2b788e91d].

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('membres', Membres::DROIT_ADMIN);

qv(['id' => 'required|numeric']);

$membre = $membres->get(qg('id'));

if (!$membre)
{





|







1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);

qv(['id' => 'required|numeric']);

$membre = $membres->get(qg('id'));

if (!$membre)
{

Modified src/www/admin/mes_infos.php from [dd87b3ed86] to [3bfc6b66d5].

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
            {
                if (!empty($c->editable))
                {
                    $data[$key] = f($key);
                }
            }

            if (isset($data[$config->get('champ_identifiant')]) && !trim($data[$config->get('champ_identifiant')]) && $session->canAccess('config', Membres::DROIT_ADMIN)) {
                throw new UserException("Le champ identifiant ne peut être vide pour un administrateur, sinon vous ne pourriez plus vous connecter.");
            }

            $session->editUser($data);

            Utils::redirect(ADMIN_URL);
        }







|







18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
            {
                if (!empty($c->editable))
                {
                    $data[$key] = f($key);
                }
            }

            if (isset($data[$config->get('champ_identifiant')]) && !trim($data[$config->get('champ_identifiant')]) && $session->canAccess($session::SECTION_CONFIG, $session::ACCESS_ADMIN)) {
                throw new UserException("Le champ identifiant ne peut être vide pour un administrateur, sinon vous ne pourriez plus vous connecter.");
            }

            $session->editUser($data);

            Utils::redirect(ADMIN_URL);
        }

Modified src/www/admin/services/_inc.php from [b575a08455] to [75fb2e78ae].

1
2
3
4
5
6
7
<?php

namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('membres', Membres::DROIT_ACCES);






|
1
2
3
4
5
6
7
<?php

namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_READ);

Modified src/www/admin/services/delete.php from [d664c15fa3] to [42c04a5c1f].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Services\Services;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('membres', Membres::DROIT_ADMIN);

$service = Services::get((int) qg('id'));

if (!$service) {
	throw new UserException("Cette activité n'existe pas");
}








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Services\Services;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);

$service = Services::get((int) qg('id'));

if (!$service) {
	throw new UserException("Cette activité n'existe pas");
}

Modified src/www/admin/services/details.php from [c951b03a28] to [f51df3fd9b].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
namespace Garradin;
use Garradin\Services\Services;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('membres', Membres::DROIT_ACCES);

$service = Services::get((int) qg('id'));

if (!$service) {
	throw new UserException("Cette activité n'existe pas");
}







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
namespace Garradin;
use Garradin\Services\Services;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_READ);

$service = Services::get((int) qg('id'));

if (!$service) {
	throw new UserException("Cette activité n'existe pas");
}

Modified src/www/admin/services/edit.php from [2bc2174d1a] to [8093b3572e].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Services\Services;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('membres', Membres::DROIT_ADMIN);

$service = Services::get((int) qg('id'));

if (!$service) {
	throw new UserException("Cette activité n'existe pas");
}








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Services\Services;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);

$service = Services::get((int) qg('id'));

if (!$service) {
	throw new UserException("Cette activité n'existe pas");
}

Modified src/www/admin/services/fees/delete.php from [810abad666] to [95c719e952].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Services\Fees;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('membres', Membres::DROIT_ADMIN);

$fee = Fees::get((int) qg('id'));

if (!$fee) {
	throw new UserException("Ce tarif n'existe pas");
}








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Services\Fees;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);

$fee = Fees::get((int) qg('id'));

if (!$fee) {
	throw new UserException("Ce tarif n'existe pas");
}

Modified src/www/admin/services/fees/details.php from [fb9b7b8df1] to [81bc52a6fd].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
namespace Garradin;
use Garradin\Services\Fees;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('membres', Membres::DROIT_ACCES);

$fee = Fees::get((int) qg('id'));

if (!$fee) {
	throw new UserException("Ce tarif n'existe pas");
}







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
namespace Garradin;
use Garradin\Services\Fees;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_READ);

$fee = Fees::get((int) qg('id'));

if (!$fee) {
	throw new UserException("Ce tarif n'existe pas");
}

Modified src/www/admin/services/fees/edit.php from [30c90681af] to [545ab428a4].

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

use Garradin\Services\Fees;
use Garradin\Accounting\Accounts;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('membres', Membres::DROIT_ADMIN);

$fee = Fees::get((int) qg('id'));

if (!$fee) {
	throw new UserException("Ce tarif n'existe pas");
}










|







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

use Garradin\Services\Fees;
use Garradin\Accounting\Accounts;
use Garradin\Accounting\Years;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);

$fee = Fees::get((int) qg('id'));

if (!$fee) {
	throw new UserException("Ce tarif n'existe pas");
}

Modified src/www/admin/services/fees/index.php from [85376d6574] to [853d7be879].

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

if (!$service) {
	throw new UserException("Cette activité n'existe pas");
}

$fees = $service->fees();

$form->runIf($session->canAccess('membres', Membres::DROIT_ADMIN) && f('save'), function () use ($service) {
	$fee = new Fee;
	$fee->id_service = $service->id();
	$fee->importForm();
	$fee->save();
}, 'fee_add', ADMIN_URL . 'services/fees/?id=' . $service->id());

$targets = Account::TYPE_REVENUE;







|







12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

if (!$service) {
	throw new UserException("Cette activité n'existe pas");
}

$fees = $service->fees();

$form->runIf($session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN) && f('save'), function () use ($service) {
	$fee = new Fee;
	$fee->id_service = $service->id();
	$fee->importForm();
	$fee->save();
}, 'fee_add', ADMIN_URL . 'services/fees/?id=' . $service->id());

$targets = Account::TYPE_REVENUE;

Modified src/www/admin/services/index.php from [8524cc3af6] to [2d0dd515b1].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
namespace Garradin;

use Garradin\Entities\Services\Service;
use Garradin\Services\Services;

require_once __DIR__ . '/_inc.php';

$csrf_key = 'service_add';

$form->runIf($session->canAccess('membres', Membres::DROIT_ADMIN) && f('save'), function () {
	$service = new Service;
	$service->importForm();
	$service->save();
	Utils::redirect(ADMIN_URL . 'services/fees/?id=' . $service->id());
}, $csrf_key);

$tpl->assign(compact('csrf_key'));
$tpl->assign('list', Services::listWithStats());

$tpl->display('services/index.tpl');










|










1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
namespace Garradin;

use Garradin\Entities\Services\Service;
use Garradin\Services\Services;

require_once __DIR__ . '/_inc.php';

$csrf_key = 'service_add';

$form->runIf($session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN) && f('save'), function () {
	$service = new Service;
	$service->importForm();
	$service->save();
	Utils::redirect(ADMIN_URL . 'services/fees/?id=' . $service->id());
}, $csrf_key);

$tpl->assign(compact('csrf_key'));
$tpl->assign('list', Services::listWithStats());

$tpl->display('services/index.tpl');

Modified src/www/admin/services/payment.php from [a8ad0d0fc0] to [abbfbc0faf].

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

use Garradin\Services\Services_User;
use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Transaction;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('membres', Membres::DROIT_ECRITURE);

$su = Services_User::get((int)qg('id'));

if (!$su) {
	throw new UserException("Cette inscription n'existe pas");
}










|







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

use Garradin\Services\Services_User;
use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Transaction;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_WRITE);

$su = Services_User::get((int)qg('id'));

if (!$su) {
	throw new UserException("Cette inscription n'existe pas");
}

Modified src/www/admin/services/reminders/delete.php from [6e29e0f367] to [6d93826b49].

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

use Garradin\Entities\Services\Reminder;
use Garradin\Services\Reminders;
use Garradin\Services\Services;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('membres', Membres::DROIT_ADMIN);

$reminder = Reminders::get((int) qg('id'));

if (!$reminder) {
	throw new UserException("Ce rappel n'existe pas");
}










|







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

use Garradin\Entities\Services\Reminder;
use Garradin\Services\Reminders;
use Garradin\Services\Services;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);

$reminder = Reminders::get((int) qg('id'));

if (!$reminder) {
	throw new UserException("Ce rappel n'existe pas");
}

Modified src/www/admin/services/reminders/details.php from [160d90cac6] to [a59c1bc0dd].

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

use Garradin\Entities\Services\Reminder;
use Garradin\Services\Reminders;
use Garradin\Services\Services;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('membres', Membres::DROIT_ADMIN);

$reminder = Reminders::get((int) qg('id'));

if (!$reminder) {
	throw new UserException("Ce rappel n'existe pas");
}










|







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

use Garradin\Entities\Services\Reminder;
use Garradin\Services\Reminders;
use Garradin\Services\Services;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);

$reminder = Reminders::get((int) qg('id'));

if (!$reminder) {
	throw new UserException("Ce rappel n'existe pas");
}

Modified src/www/admin/services/reminders/edit.php from [30e7c419dc] to [7b4713a4cc].

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

use Garradin\Entities\Services\Reminder;
use Garradin\Services\Reminders;
use Garradin\Services\Services;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('membres', Membres::DROIT_ADMIN);

$reminder = Reminders::get((int) qg('id'));

if (!$reminder) {
	throw new UserException("Ce rappel n'existe pas");
}










|







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

use Garradin\Entities\Services\Reminder;
use Garradin\Services\Reminders;
use Garradin\Services\Services;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);

$reminder = Reminders::get((int) qg('id'));

if (!$reminder) {
	throw new UserException("Ce rappel n'existe pas");
}

Modified src/www/admin/services/reminders/index.php from [78ba4100aa] to [afd86fb166].

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

use Garradin\Entities\Services\Reminder;
use Garradin\Services\Reminders;
use Garradin\Services\Services;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('membres', Membres::DROIT_ADMIN);

$services_list = Services::listAssoc();

if (!count($services_list)) {
	Utils::redirect(ADMIN_URL . 'services/?CREATE');
}










|







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

use Garradin\Entities\Services\Reminder;
use Garradin\Services\Reminders;
use Garradin\Services\Services;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);

$services_list = Services::listAssoc();

if (!count($services_list)) {
	Utils::redirect(ADMIN_URL . 'services/?CREATE');
}

Modified src/www/admin/services/save.php from [0bec8e59c8] to [0acb3f484c].

1
2
3
4
5
6
7
8
9
10
11






12
13
14
15
16
17
18
<?php
namespace Garradin;

use Garradin\Services\Services;
use Garradin\Entities\Services\Service_User;
use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Transaction;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('membres', Membres::DROIT_ECRITURE);







$count_all = Services::count();

if (!$count_all) {
	Utils::redirect(ADMIN_URL . 'services/?CREATE');
}











|
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
namespace Garradin;

use Garradin\Services\Services;
use Garradin\Entities\Services\Service_User;
use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Transaction;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_WRITE);

$count_all = Services::count();

if (!$count_all) {
	Utils::redirect(ADMIN_URL . 'services/?CREATE');
}

$count_all = Services::count();

if (!$count_all) {
	Utils::redirect(ADMIN_URL . 'services/?CREATE');
}

Modified src/www/admin/services/user.php from [e3055067d1] to [64386e9e96].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
namespace Garradin;
use Garradin\Services\Services_User;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('membres', Membres::DROIT_ACCES);

$user = (new Membres)->get((int) qg('id'));

if (!$user) {
	throw new UserException("Cet utilisateur est introuvable");
}

$form->runIf($session->canAccess('membres', Membres::DROIT_ECRITURE) && null !== qg('paid') && qg('su_id'), function () use ($user) {
	$su = Services_User::get((int) qg('su_id'));

	if (!$su) {
		throw new UserException("Cette inscription est introuvable");
	}

	$su->paid = (bool)qg('paid');






|







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
namespace Garradin;
use Garradin\Services\Services_User;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_READ);

$user = (new Membres)->get((int) qg('id'));

if (!$user) {
	throw new UserException("Cet utilisateur est introuvable");
}

$form->runIf($session->canAccess($session::SECTION_USERS, $session::ACCESS_WRITE) && null !== qg('paid') && qg('su_id'), function () {
	$su = Services_User::get((int) qg('su_id'));

	if (!$su) {
		throw new UserException("Cette inscription est introuvable");
	}

	$su->paid = (bool)qg('paid');

Modified src/www/admin/services/user_delete.php from [c5d8584c97] to [aee9cb435e].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Services\Services_User;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('membres', Membres::DROIT_ECRITURE);

$su = Services_User::get((int) qg('id'));

if (!$su) {
	throw new UserException("Cette inscription n'existe pas");
}








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Services\Services_User;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_USERS, $session::ACCESS_WRITE);

$su = Services_User::get((int) qg('id'));

if (!$su) {
	throw new UserException("Cette inscription n'existe pas");
}

Added src/www/admin/static/scripts/code_editor.css version [7c23f5ec10].























































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
.codeEditor {
	width: 100%;
	height: 600px;
	border: 1px solid #999;
	background: #eee;
	position: relative;
	display: block;
}

.codeEditor .sk_help {
	background: #ccc;
	border-top: 2px solid #999;
	position: absolute;
	left: 0;
	right: 0;
	bottom: 0;
	height: 15px;
	padding: 5px 1em 0;
	font-family: "Deja Vu Sans Mono", "Droid Sans Mono", "Courier New", Courier, monospace;
	font-size: 12px;
}

.codeEditor .sk_toolbar {
	background: #ccc;
	border-bottom: 2px solid #999;
	height: 32px;
}

.codeEditor .sk_toolbar select {
	float: right;
	border: none;
	border-radius: .2em;
	height: 24px;
	padding: 1px;
	padding-left: 24px;
	margin: 4px .5em;
	background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAMFBMVEUAAACZm4leYFyOkX1RU09MTkp9f2+ys6KwsZrn5+KanIz///+6u6vGxryDhXtVV1Otpz1oAAAAA3RSTlMA+7omiqY6AAAAgklEQVQI12NI+f9fgQEEfO7e+QBm/BGU+P8fJPrd2LgLCD4AGSCBLCDD8Pfu3bu9QCK/Z86e/esDw4/Hv+/euf0ZyEj7PXPnbCDDI+33kZDQkE8M/11D1969e9eEwRNIlpe332f421Ne0dHRcYnh75k7Z8/cudPEoOIS4uriAlQMAwDpN0taA/g97gAAAABJRU5ErkJggg==") no-repeat 5px center;
	cursor: pointer;
}

.codeEditor .sk_toolbar select:hover {
	background-color: #fff;
}

.codeEditor .sk_toolbar p {
	display: inline;
	padding: .3em .5em;
	border-radius: .5em;
	font-size: .9em;
	margin-left: 2em;
}

.codeEditor .sk_toolbar input {
	margin: 4px .5em;
	padding: 0;
	width: 24px;
	height: 24px;
	border: none;
	border-radius: .2em;
	cursor: pointer;
	text-indent: -70em;
	overflow: hidden;
	background: transparent no-repeat center center;
}

.codeEditor .sk_toolbar input:hover { background-color: #fff; }

.codeEditor .sk_toolbar .save { margin-left: 2em; background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAMFBMVEU6XIthfJfOXAD8rz6PpsDe3t7+/v6YrsZhe5NVV1Py8vL09PTMzc6+0upyn88gSod8oq0HAAAAAXRSTlOZyTXzhgAAAGxJREFUCNdj4P+kBAT6Hxj+XjYGAtv7DH+fbQOCfSBGKBDkgRi7gQAschQoAmbsXrVq1ToQIw0IQGregQGQ8bCjo6OvDsQ4czS04jmQ8eLMzJiDUMYZkMj3ilAIg/9h6PEjJ4AMhp8zgeD/BwBY4VdD5HZlvAAAAABJRU5ErkJggg=="); }
.codeEditor .sk_toolbar .reset { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QAAAAAAAD5Q7t/AAABCklEQVR42p2TsUrDUBSGv4RM2qlLXXwBHdoncG3u5tpZx059gojgZAtC3bqqa7cQKH2FWiFZHUSIg5lChi7Xpak312Ma/eHA5Zzz/5fzHw5UMQZ0wxgDOCb5fnQ8Glxe0AR31zdcPW0mpoDOkoDPJKRI41rywdEpRRrTHeZ4drFIY15nh5w/f4jkea/D2aPafeJKTVuyI4Ut7G0NkVDmnbpxXMAHyJJgl1xPW+XT32emC0SA3z75FugO85Ic8Qf0jR33a/p0lgR6PW1pQJtbiPbNK8GzDLPhNBVAKVUphGGIJD7vdWQBi1SBuSGA/P1FFvgNb8vbH7nFaoO5Ja2Uki6Ommt8ME36t4lfRLtlZDAJ4ScAAAAASUVORK5CYII="); }
.codeEditor .sk_toolbar .search { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAABGdBTUEAAK/INwWK6QAAADBQTFRF////epWwPGiTdYKPdHqB1tbWWW6Hp6enR2yQc6b/dqncME9tmcz/i5CX5e32w9PmM3gGSwAAAAd0Uk5TAAAAQoTswgXk1s4AAABySURBVAjXYxA0v+4syAAEIqXvQh1BDPN3J88Vgxj3/r07EwtmnDw58y2YcebMHLBI6p/358NADN/3Z75eFhQUZFC5/i4WqIaRwcjtdsrWa0AGEDByr2oAM5i4V82AMBh2nGmCMIBCEAbDrhVghpKS9jYA43soYFw0gPcAAAAASUVORK5CYII="); }
.codeEditor .sk_toolbar .search_replace { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAMFBMVEUAAABnVEEAAACEhoVsaWX4liHmz2/8/Pzf398uNDawrKfn5+fOXADj4+P+/v6IioXFYmG9AAAAAnRSTlMAWv0tddIAAACKSURBVAjXY2Dg/w8EAgwMDP/evSuvWwhi7N69Y8UrATDjxurbC4CMn/P3rv9vwMDw3+/J31s9BxkYOl/vm3vjaCiEsSc0hoGhxe+J7dHUgwxckz0nAwUCGDotO3qPph4zYJg8q+P20Zg+AwbJ9rt3VE60f2BgML+76VgHiPH93bt3z8uBjP9g8AEArPJMCYP5JmIAAAAASUVORK5CYII="); }
.codeEditor .sk_toolbar .gotoline { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAMFBMVEX///9BQUEVFRWysrREREQ4ODhVVVX7+/vu7u7q6uqcnJy+vr/m5ub19fXc3Nz///89lwBDAAAAB3RSTlMAAILOakNmMhUGwgAAAHtJREFUCNdjYIABQbE0EEhkEMx793r37tdmDILZu1fv3rVqEYNgfv3/u/X/vwEZu4/Xl5eXARnbd96trS1hcPNaWdd7924Jg+///7UdHR1XGIK01lSfnDmzhUFQY8W6N2fOABl+q/a8OXfmCYOg3jugwJlJDIJKEMCAAQCfIDck8YzyWAAAAABJRU5ErkJggg=="); }
.codeEditor .sk_toolbar .fullscreen { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAADFBMVEUAAABMTFFOTlBOTlCQ1uMHAAAAA3RSTlMAOcKBmOr4AAAAQUlEQVQI12P4/4D7P8N/B0Yo8XsC23+GZw+4pzM4TmBzYsAGgBKODNcecM9m+D+B7T3DPwfG/Qz/G5iABlzg+g8ANzMax/3kkQoAAAAASUVORK5CYII="); }
.codeEditor.fullscreen .sk_toolbar .fullscreen { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAADFBMVEUAAABNTVFOTlBOTlBLB/faAAAAA3RSTlMAOsPdsomtAAAAQElEQVQI12NIEWCRZNi5gTePIe8D/08G6Q/8Txj0P/B/YVj/gf8fAzawHyQhD1ICJvI/8O9k2FnAl8eQosAiCQCgixb13aKGIwAAAABJRU5ErkJggg=="); }

.codeEditor .lineCount, .codeEditor textarea {
	font-family: "Deja Vu Sans Mono", "Droid Sans Mono", "Courier New", Courier, monospace;
	font-size: 11pt;
	line-height: 11pt;
}

.codeEditor .lineCount {
	position: absolute;
	top: 34px;
	left: 0;
	bottom: 22px;
	width: 46px;
	text-align: right;
	border-right: 2px solid #999;
	overflow: hidden;
}

.codeEditor .lineCount i {
	display: block;
	padding-right: 2px;
	font-weight: normal;
}	

.codeEditor .lineCount b {
	display: block;
	padding-right: 2px;
	font-weight: normal;
}

.codeEditor .lineCount b.current {
	background: #ccc;
}

.codeEditor .container {
	position: absolute;
	right: 4px;
	top: 34px;
	bottom: 22px;
	left: 50px;
	margin: 0;
	padding: 0;
}

.codeEditor textarea {
	height: 100%;
	width: 100%;
	padding: 0 0 0 2px;
	margin: 0;
	background: transparent;
	border: none;
	overflow: auto;
	resize: none;
}

.codeEditor.fullscreen {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	width: 100%;
	height: 100%;
	z-index: 100000;
}

Added src/www/admin/static/scripts/code_editor.js version [a3a35cf3cc].

































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
(function (){
	g.style('scripts/code_editor.css');
	g.script('scripts/lib/code_editor.min.js', function ()
	{
		var save_btn = document.querySelector('[name=save]');
		save_btn.type = 'hidden';

		var code = new codeEditor('f_content');

		code.params.lang = {
			search: "Texte à chercher ?\n(expression régulière autorisée, pour cela commencer par un slash '/')",
			replace: "Texte pour le remplacement ?\n(utiliser $1, $2... pour les captures d'expression régulière)",
			search_selection: "Texte à chercher dans la sélection ?\n(expression régulière autorisée, pour cela commencer par un slash '/')",
			replace_result: "%d occurences trouvées et remplacées.",
			goto: "Aller à la ligne :",
			no_search_result: "Aucun résultat trouvé."
		};

		code.origValue = code.textarea.value;
		code.saved = true;

		code.saveFile = function ()
		{
			this.textarea.form.submit();
		};

		code.resetFile = function (e)
		{
			if (this.textarea.value == this.origValue) return;
			if (!window.confirm("Le fichier a été modifié, abandonner les modifications ?")) return;
			this.textarea.form.reset();
		};

		var help = document.createElement('div');
		help.className = 'sk_help';

		code.parent.appendChild(help);

		var toolbar = document.createElement('nav');
		toolbar.className = 'sk_toolbar';

		var appendButton = function (name, title, action)
		{
			var btn = document.createElement('input');
			btn.type = 'button';
			btn.value = btn.title = title;
			btn.className = name;
			btn.onclick = function () { action.call(code); return false; };

			toolbar.appendChild(btn);
		};

		appendButton('save', 'Enregistrer les modifications', code.saveFile);
		appendButton('reset', 'Recharger le fichier (effacer les modifications)', code.resetFile);

		appendButton('search', 'Chercher', code.search);
		appendButton('search_replace', 'Chercher et remplacer', code.searchAndReplace);
		appendButton('gotoline', 'Aller à la ligne', code.goToLine);

		code.parent.insertBefore(toolbar, code.parent.firstChild);

		code.shortcuts.push({ctrl: true, key: 's', callback: code.saveFile});

		// Cancel Escape to close
		if (window.parent && window.parent.g.dialog) {
			// Always fullscreen in dialogs
			code.toggleFullscreen();

			// Display error message in editor
			if (msg = document.querySelector('p.error, p.confirm'))
			{
				var m = document.createElement('p');
				m.innerHTML = msg.innerHTML;
				m.className = msg.className;
				toolbar.appendChild(m);
				msg.parentNode.removeChild(msg);
			}

			window.parent.g.dialog.preventClose = () => {
				if (code.textarea.value == code.textarea.defaultValue) {
					return false;
				}

				if (window.confirm('Sauvegarder avant de fermer ?')) {
					code.saveFile();
					return false;
				}

				return true;
			};
		}
		else {
			appendButton('fullscreen', 'Plein écran', code.toggleFullscreen);
		}
	});
}());

Deleted src/www/admin/static/scripts/code_editor.min.js version [f838117490].

1
2
window.textEditor=function(t){if(!document.getElementById(t))throw new Error("Invalid ID parameter: "+t);return this.id=t,this.textarea=document.getElementById(t),this.shortcuts=[],"selectionStart"in this.textarea&&(this.textarea.addEventListener("keydown",this.keyEvent.bind(this),!0),this.textarea.addEventListener("keypress",this.keyEvent.bind(this),!0),!0)},textEditor.prototype.keyEvent=function(t){for(var e in t=t||window.event,this.shortcuts){var r=this.shortcuts[e];if(!t.metaKey&&!(t.ctrlKey&&!r.ctrl||r.ctrl&&!t.ctrlKey)&&!(t.shiftKey&&!r.shift||r.shift&&!t.shiftKey)&&!(t.altKey&&!r.alt||r.alt&&!t.altKey)&&(e=this.matchKeyPress(r.key,t))){if("function"==typeof r.callback)return!r.callback.call(this,t,e)||this.preventDefault(t);var n=(r.ctrl?"Ctrl-":"")+(r.alt?"Alt-":"");throw n+=(r.shift?"Shift-":"")+r,new Error("Invalid callback type for shortcut "+n)}}return!0},textEditor.prototype.matchKeyPress=function(t,e){return!(e.defaultPrevented||!e.key)&&(t=t.toLowerCase(),e.key.toLowerCase()==t&&t)},textEditor.prototype.preventDefault=function(t){return t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation(),t.stopImmediatePropagation&&t.stopImmediatePropagation(),t.returnValue=!1,!(t.cancelBubble=!0)},textEditor.prototype.getSelection=function(){var t=this.textarea,e=t.selectionEnd-t.selectionStart;return{start:t.selectionStart,end:t.selectionEnd,length:e,text:t.value.substr(t.selectionStart,e)}},textEditor.prototype.replaceSelection=function(t,e){var r=this.textarea,n=t.start,o=n+e.length;return r.value=r.value.substr(0,n)+e+r.value.substr(t.end,r.value.length),this.setSelection(n,o),{start:n,end:o,length:e.length,text:e}},textEditor.prototype.insertAtPosition=function(t,e,r){var n=t+e.length,o=this.textarea;return o.value=o.value.substr(0,t)+e+o.value.substr(t,o.value.length-t),r||(r=n),this.setSelection(r,r)},textEditor.prototype.setSelection=function(t,e){var r=this.textarea;return r.focus(),r.selectionStart=t,r.selectionEnd=e,this.getSelection()},textEditor.prototype.scrollToSelection=function(t){var e=this.textarea,r=e.value.substr(t.end);e.value=e.value.substr(0,t.end),e.scrollTop=1e5;var n=e.scrollTop;e.value+=r,e.scrollTop=n,this.setSelection(t.start,t.end)},textEditor.prototype.wrapSelection=function(t,e,r){var n=this.textarea,o=n.scrollTop,a=t.text;return t=this.replaceSelection(t,e+a+r),""==a&&(t=this.setSelection(t.start+e.length,t.start+e.length)),n.scrollTop=o,t};
String.prototype.repeat=function(t){return new Array(t+1).join(this)},window.codeEditor=function(t){if(!textEditor.call(this,t))return!1;this.onlinechange=null,this.onlinenumberchange=null,this.fullscreen=!1,this.nb_lines=0,this.current_line=0,this.search_str=null,this.search_pos=0,this.params={indent_size:4,tab_size:4,convert_tabs:!0,lang:{search:"Text to search?\n(regexps allowed, begin them with '/')",replace:"Text for replacement?\n(use $1, $2... for regexp replacement)",search_selection:"Text to replace in selection?\n(regexps allowed, begin them with '/')",replace_result:"%d occurence found and replaced.",goto:"Line to go to:",no_search_result:"No search result found."}},(that=this).init(),this.textarea.spellcheck=!1,this.shortcuts.push({shift:!0,key:"tab",callback:this.indent}),this.shortcuts.push({key:"tab",callback:this.indent}),this.shortcuts.push({ctrl:!0,key:"f",callback:this.search}),this.shortcuts.push({ctrl:!0,key:"h",callback:this.searchAndReplace}),this.shortcuts.push({ctrl:!0,key:"g",callback:this.goToLine}),this.shortcuts.push({key:"F3",callback:this.searchNext}),this.shortcuts.push({key:"backspace",callback:this.backspace}),this.shortcuts.push({key:"enter",callback:this.enter}),this.shortcuts.push({key:'"',callback:this.insertBrackets}),this.shortcuts.push({key:"[",callback:this.insertBrackets}),this.shortcuts.push({key:"{",callback:this.insertBrackets}),this.shortcuts.push({key:"(",callback:this.insertBrackets}),this.shortcuts.push({key:"F11",callback:this.toggleFullscreen}),this.textarea.addEventListener("keypress",this.keyEvent.bind(this),!0),this.textarea.addEventListener("keydown",this.keyEvent.bind(this),!0)},codeEditor.prototype=function(t){function e(){}return e.prototype=t,new e}(textEditor.prototype),codeEditor.prototype.init=function(){var t=this;for(this.nb_lines=this.countLines(),this.parent=document.createElement("div"),this.parent.className="codeEditor",this.lineCounter=document.createElement("span"),this.lineCounter.className="lineCount",i=1;i<=this.nb_lines;i++)this.lineCounter.innerHTML+="<b>"+i+"</b>";this.lineCounter.innerHTML+="<i>---</i>",this.parent.appendChild(this.lineCounter);var e=document.createElement("div");e.className="container",e.appendChild(this.textarea.cloneNode(!0)),this.parent.appendChild(e);var s=this.textarea.parentNode;s.appendChild(this.parent),s.removeChild(this.textarea),this.textarea=this.parent.getElementsByTagName("textarea")[0],this.textarea.wrap="off",this.params.convert_tabs&&(this.textarea.value=this.textarea.value.replace(/[ ]{1,7}\t/g," ".repeat(this.params.tab_size)),this.textarea.value=this.textarea.value.replace(/\t/g," ".repeat(this.params.tab_size))),this.textarea.addEventListener("focus",function(){t.update()},!1),this.textarea.addEventListener("keyup",function(){t.update()},!1),this.textarea.addEventListener("click",function(){t.update()},!1),this.textarea.addEventListener("scroll",function(){t.lineCounter.scrollTop=t.textarea.scrollTop},!1)},codeEditor.prototype.update=function(){var t=this.getSelection(),e=this.getLineNumberFromPosition(t),s=this.countLines();if(this.search_pos=t.end,s!=this.nb_lines){for(var r=this.lineCounter.getElementsByTagName("b"),i=this.nb_lines;s<i;i--)this.lineCounter.removeChild(r[i-1]);var n=this.lineCounter.lastChild;for(i=r.length;i<s;i++){var a=document.createElement("b");a.innerHTML=i+1,this.lineCounter.insertBefore(a,n)}this.nb_lines=s,"function"==typeof this.onlinenumberchange&&this.onlinenumberchange.call(this)}if(e!=this.current_line){for(r=this.lineCounter.getElementsByTagName("b"),i=0;i<this.nb_lines;i++)r[i].className="";r[e].className="current",this.current_line=e,"function"==typeof this.onlinechange&&this.onlinechange.call(this)}},codeEditor.prototype.countLines=function(){var t=this.textarea.value.match(/(\r?\n)/g);return t?t.length+1:1},codeEditor.prototype.getLineNumberFromPosition=function(t){if(0==(t=t||this.getSelection()).start)return 0;var e=this.textarea.value.substr(0,t.start).match(/(\r?\n)/g);return e?e.length:0},codeEditor.prototype.getLines=function(){return this.textarea.value.split("\n")},codeEditor.prototype.getLine=function(t){return this.textarea.value.split("\n",t+1)[t]},codeEditor.prototype.getLinePosition=function(t,e){var s=0;for(i=0;i<t.length;i++){if(i==e)return{start:s+i,end:s+t[i].length,length:t[i].length,text:t[i]};s+=t[i].length}return!1},codeEditor.prototype.selectLines=function(t){for(var e=t.start;0<e;e--)if("\n"==this.textarea.value.substr(e,1)){t.start=e+1;break}for(e=t.end-1;e<this.textarea.length;e++)if("\n"==this.textarea.value.substr(e,1)){t.end=e-1;break}return this.setSelection(t.start,t.end),t},codeEditor.prototype.goToLine=function(t){var e=window.prompt(that.params.lang.goto);if(e){var s=this.textarea.value.split("\n",parseInt(e,10)).join("\n").length;return this.scrollToSelection(this.setSelection(s,s)),!0}},codeEditor.prototype.indent=function(t,e){var s=this.getSelection(),r=t.shiftKey,i=this.getLines(),n=this.getLineNumberFromPosition(s),a=this.getLinePosition(i,n),h=s.end>a.end;if((0==s.length||!h)&&s.start!=a.start)return this.insertAtPosition(s.start," ".repeat(this.params.indent_size)),!0;if(0==s.length&&s.start==a.start){var o=n-1 in i&&i[n-1].match(/^(\s+)/);if(o&&0==a.length)c=" ".repeat(o[1].length);else var c=" ".repeat(this.params.indent_size);return this.insertAtPosition(s.start,c),!0}s=this.selectLines(s);var l=this.textarea.value.substr(s.start,s.end-s.start);if(i=l.split("\n"),r)for(var p=new RegExp("^[ ]{1,"+this.params.indent_size+"}"),u=0;u<i.length;u++)i[u]=i[u].replace(p,"");else for(u=0;u<i.length;u++)i[u]=" ".repeat(this.params.indent_size)+i[u];return l=i.join("\n"),this.replaceSelection(s,l),!0},codeEditor.prototype.search=function(){if(this.search_str=window.prompt(this.params.lang.search,this.search_str))return this.search_pos=0,this.searchNext()},codeEditor.prototype.searchNext=function(){if(!this.search_str)return!0;var t=this.getSelection(),e=t.end>=this.search_pos?this.search_pos:t.start,s=this.textarea.value.substr(e),r=this.getSearchRegexp(this.search_str),i=s.search(r);if(-1==i)return window.alert(this.params.lang.no_search_result);var n=s.match(r);return t.start=e+i,t.end=t.start+n[0].length,t.length=n[0].length,t.text=n[0],this.setSelection(t.start,t.end),this.search_pos=t.end,this.scrollToSelection(t),!0},codeEditor.prototype.getSearchRegexp=function(t,e){var s,r;if("/"==t.substr(0,1)){var i=t.lastIndexOf("/");s=t.substr(1,i-1),r=t.substr(i+1).replace(/g/,"")}else s=t.replace(/([\/$^.?()[\]{}\\])/,"\\$1"),r="i";return e&&(r+="g"),new RegExp(s,r)},codeEditor.prototype.searchAndReplace=function(t){var e=this.getSelection(),i=0!=e.length?this.params.lang.search_selection:this.params.lang.search;if(!(s=window.prompt(i,this.search_str))||!(r=window.prompt(that.params.lang.replace)))return!0;var n=this.getSearchRegexp(s,!0);if(0==e.length){var a=this.textarea.value.match(n).length;this.textarea.value=this.textarea.value.replace(n,r)}else a=e.text.match(n).length,this.replaceSelection(e,e.text.replace(n,r));return window.alert(this.params.lang.replace_result.replace(/%d/g,a)),!0},codeEditor.prototype.enter=function(t){var e=this.getSelection(),s=this.getLineNumberFromPosition(e),r="";return s=this.getLine(s),"{"==this.textarea.value.substr(e.start-1,1)&&(r+=" ".repeat(this.params.indent_size)),(match=s.match(/^(\s+)/))&&(r+=match[1]),!!r&&(this.insertAtPosition(e.start,"\n"+r),!0)},codeEditor.prototype.backspace=function(t){var e=this.getSelection();if(0<e.length)return!1;if('""'==(s=this.textarea.value.substr(e.start-2,2))||"''"==s||"{}"==s||"()"==s||"[]"==s)return e.start-=2,this.replaceSelection(e,""),!0;var s=this.textarea.value.substr(e.start-20,20);return-1!=(pos=s.search(/^(\s+)$/m))&&(e.start-=this.params.indent_size,this.replaceSelection(e,""),!0)},codeEditor.prototype.insertBrackets=function(t,e){var s=this.getSelection(),r=e,i=r;switch(r){case"(":i=")";break;case"[":i="]";break;case"{":i="}"}return 0==s.length?this.insertAtPosition(s.start,r+i,s.start+1):this.wrapSelection(s,r,i),!0},codeEditor.prototype.toggleFullscreen=function(t){for(var e=this.parent.className.split(" "),s=0;s<e.length;s++)if("fullscreen"==e[s])return e.splice(s,1),this.parent.className=e.join(" "),!(this.fullscreen=!1);return e.push("fullscreen"),this.parent.className=e.join(" "),this.fullscreen=!0};
<
<




Modified src/www/admin/static/scripts/color_helper.js from [97e321468f] to [02c441126c].

34
35
36
37
38
39
40
41


42
43
44
45
46
47
48
		applyColors();
		return new_color;
	}

	function applyColors()
	{
		let input = $('#f_couleur2');
		var color = colorToRGB(input.value, 'gSecondColor');



		var img = new Image;
		img.crossOrigin = "Anonymous";

		img.onload = function() {
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');







|
>
>







34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
		applyColors();
		return new_color;
	}

	function applyColors()
	{
		let input = $('#f_couleur2');
		let color = colorToRGB(input.value, 'gSecondColor');
		let color1 = $('#f_couleur1'), color2 = $('#f_couleur2');
		let default_colors = color1.value == color1.placeholder && color2.value == color2.placeholder;

		var img = new Image;
		img.crossOrigin = "Anonymous";

		img.onload = function() {
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
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

			ctx.putImageData(imgData, 0, 0);

			var i = canvas.toDataURL('image/png');

			// Prévisualisation
			document.documentElement.style.setProperty('--gBgImage', 'url("' + i + '")');
			$('#f_image_fond').value = i.substr(i.indexOf(',')+1);

			delete canvas2;
			delete canvas;
			delete ctx;
			delete img;
		};

		var bg = $('#f_image_fond');







		if (bg.value) {
			img.src = 'data:image/png;base64,' + bg.value;
		}
		else if (bg.dataset.source) {
			img.src = 'data:image/png;base64,' + bg.dataset.source;
		}
		else {
			img.src = bg.dataset.default;
		}
	}

	/**







|







|

>
>
>
>
>
>
|


|
|







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

			ctx.putImageData(imgData, 0, 0);

			var i = canvas.toDataURL('image/png');

			// Prévisualisation
			document.documentElement.style.setProperty('--gBgImage', 'url("' + i + '")');
			$('#f_admin_background').value = i.substr(i.indexOf(',')+1);

			delete canvas2;
			delete canvas;
			delete ctx;
			delete img;
		};

		var bg = $('#f_admin_background');

		if (bg.value == 'RESET' && default_colors) {
			document.documentElement.style.setProperty('--gBgImage', 'url("' + bg.dataset.default + '")');
		}
		else if (bg.value == 'RESET') {
			img.src = bg.dataset.default;
		}
		else if (bg.value) {
			img.src = 'data:image/png;base64,' + bg.value;
		}
		else if (bg.dataset.current) {
			img.src = bg.dataset.current;
		}
		else {
			img.src = bg.dataset.default;
		}
	}

	/**
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
				}
			}

			ctx.putImageData(imgData, 0, 0);

			var i = canvas.toDataURL('image/png');

			$('#f_image_fond').value = i.substr(i.indexOf(',')+1);

			delete canvas2;
			delete canvas;
			delete ctx;
			delete img;

			callback();







|







143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
				}
			}

			ctx.putImageData(imgData, 0, 0);

			var i = canvas.toDataURL('image/png');

			$('#f_admin_background').value = i.substr(i.indexOf(',')+1);

			delete canvas2;
			delete canvas;
			delete ctx;
			delete img;

			callback();
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213

		var reset_btn = document.createElement('button');
		reset_btn.className = 'resetButton icn-btn';
		reset_btn.type = 'button';
		reset_btn.innerHTML = 'RàZ';

		reset_btn.onclick = () => {
			$('#f_image_fond').dataset.source = '';
			$('#f_image_fond').value = '';
			bg.disabled = false;

			applyColors();
		};

		bg.parentNode.insertBefore(reset_btn, bg.nextSibling);
	});
})();







|
|








205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221

		var reset_btn = document.createElement('button');
		reset_btn.className = 'resetButton icn-btn';
		reset_btn.type = 'button';
		reset_btn.innerHTML = 'RàZ';

		reset_btn.onclick = () => {
			$('#f_admin_background').dataset.current = '';
			$('#f_admin_background').value = 'RESET';
			bg.disabled = false;

			applyColors();
		};

		bg.parentNode.insertBefore(reset_btn, bg.nextSibling);
	});
})();

Modified src/www/admin/static/scripts/global.js from [a4e04fc8bc] to [b78bac285f].

1


2
3
4
5
6
7
8
9
10
11
12
13
(function () {


	window.g = window.garradin = {
		url: window.location.href.replace(/\/admin\/.*?$/, ''),
		admin_url: window.location.href.replace(/\/admin\/.*?$/, '/admin/'),
		static_url: window.location.href.replace(/\/admin\/.*?$/, '/admin/static/'),
		version: document.head.querySelector('script').src.match(/\?(.*)$/)[1],
		loaded: {}
	};

	window.$ = function(selector) {
		if (!selector.match(/^[.#]?[a-z0-9_-]+$/i))
		{
			return document.querySelectorAll(selector);

>
>




|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(function () {
	let s = document.head.querySelector('script');

	window.g = window.garradin = {
		url: window.location.href.replace(/\/admin\/.*?$/, ''),
		admin_url: window.location.href.replace(/\/admin\/.*?$/, '/admin/'),
		static_url: window.location.href.replace(/\/admin\/.*?$/, '/admin/static/'),
		version: s ? s.src.match(/\?(.*)$/)[1] : null,
		loaded: {}
	};

	window.$ = function(selector) {
		if (!selector.match(/^[.#]?[a-z0-9_-]+$/i))
		{
			return document.querySelectorAll(selector);
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
			var container = document.createElement('div');
			container.appendChild(content.cloneNode(true));
			content = container;
		}

		g.dialog.appendChild(content);

		content.style.opacity = g.dialog.style.opacity = 0;
		g.dialog.onclick = (e) => { if (e.target == g.dialog) g.closeDialog(); };
		window.onkeyup = (e) => { if (e.key == 'Escape') g.closeDialog(); };

















		document.body.appendChild(g.dialog);

		// Restore CSS defaults
		window.setTimeout(() => { g.dialog.style.opacity = ''; }, 50);
		window.setTimeout(() => { content.style.opacity = ''; }, 100);

		return content;
	}

	g.openFrameDialog = function (url) {
		var iframe = document.createElement('iframe');
		iframe.src = url;
		iframe.name = 'dialog';

		iframe.frameborder = '0';
		iframe.scrolling = 'yes';
		iframe.width = iframe.height = 0;

		iframe.onload = () => { iframe.contentWindow.onkeyup = (e) => { if (e.key == 'Escape') g.closeDialog(); };}



		g.openDialog(iframe);

	};

	g.closeDialog = function () {
		if (null === g.dialog) {
			return;
		}





		var d = g.dialog;
		d.style.opacity = 0;
		window.onkeyup = g.dialog = null;

		window.setTimeout(() => { d.parentNode.removeChild(d); }, 500);
	}

	// From KD2fw/js/xhr.js
	g.load = function(b,d,f,e){var a=new XMLHttpRequest();if(!a||!b)return false;if(a.overrideMimeType)a.overrideMimeType('text/xml');b+=(b.indexOf('?')+1?'&':'?')+(+(new Date));a.onreadystatechange=function(){if(a.readyState!=4)return;if((s=a.status)==200){if(!d)return true;var c=a.responseText;if(f=='json'){return((j=window.JSON)&&j.parse)?j.parse(c):eval('('+c.replace(/[\n\r]/g,'')+')')}d(c)}else if(e){e(s)}};a.open('GET',b,true);a.send(null)};

	g.checkUncheck = function()
	{
		var checked = this.checked;
		this.form.querySelectorAll('tbody input[type=checkbox]').forEach((elm) => {
			elm.checked = checked;
			elm.dispatchEvent(new Event("change"));







|


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





<




|



>



>
|
>
>

|
>






>
>
>
>






|
<
<
<







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
			var container = document.createElement('div');
			container.appendChild(content.cloneNode(true));
			content = container;
		}

		g.dialog.appendChild(content);

		g.dialog.style.opacity = 0;
		g.dialog.onclick = (e) => { if (e.target == g.dialog) g.closeDialog(); };
		window.onkeyup = (e) => { if (e.key == 'Escape') g.closeDialog(); };

		let tag = content.tagName.toLowerCase();

		if (tag == 'img' || tag == 'iframe') {
			event = 'load';
		}
		else if (tag == 'audio' || tag == 'video') {
			event = 'canplaythrough';
		}

		if (event) {
			content.addEventListener(event, () => g.dialog.classList.add('loaded'));
		}
		else {
			g.dialog.classList.add('loaded');
		}

		document.body.appendChild(g.dialog);

		// Restore CSS defaults
		window.setTimeout(() => { g.dialog.style.opacity = ''; }, 50);


		return content;
	}

	g.openFrameDialog = function (url, height = '90%', callback) {
		var iframe = document.createElement('iframe');
		iframe.src = url;
		iframe.name = 'dialog';
		iframe.id = 'frameDialog';
		iframe.frameborder = '0';
		iframe.scrolling = 'yes';
		iframe.width = iframe.height = 0;
		iframe.addEventListener('load', () => {
			iframe.contentWindow.onkeyup = (e) => { if (e.key == 'Escape') g.closeDialog(); };
			iframe.style.height = height == 'auto' ? iframe.contentWindow.document.body.offsetHeight + 'px' : height;
		});

		g.openDialog(iframe, callback);
		return iframe;
	};

	g.closeDialog = function () {
		if (null === g.dialog) {
			return;
		}

		if (g.dialog.preventClose && g.dialog.preventClose()) {
			return false;
		}

		var d = g.dialog;
		d.style.opacity = 0;
		window.onkeyup = g.dialog = null;

		window.setTimeout(() => { d.parentNode.removeChild(d); }, 500);
	};




	g.checkUncheck = function()
	{
		var checked = this.checked;
		this.form.querySelectorAll('tbody input[type=checkbox]').forEach((elm) => {
			elm.checked = checked;
			elm.dispatchEvent(new Event("change"));
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
		if (!document.activeElement || document.activeElement.tagName.toLowerCase() == 'body') {
			let form = document.querySelector('form[data-focus]');

			if (!form) {
				return;
			}

			var i = form.querySelector(form.dataset.focus == 1 ? '[name]' : form.dataset.focus);
			i.focus();
		}
	}, 'dom');

	// Sélecteurs de listes
	g.onload(() => {
		var inputs = $('form .input-list > button');

		inputs.forEach((i) => {
			i.onclick = () => {
				g.current_list_input = i.parentNode;

				g.openFrameDialog(i.value);
				return false;
			};
		});

		var multiples = $('form .input-list span button');

		multiples.forEach((btn) => {
			btn.onclick = () => btn.parentNode.parentNode.removeChild(btn.parentNode);
		});




















































	});

	g.onload(() => {
		document.querySelectorAll('input[data-input="date"]').forEach((e) => {
			g.enhanceDateField(e);
		});
	});

	// 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++)
		{
			tableActions[i].onchange = function () {
				if (!this.form.querySelector('table tbody input[type=checkbox]:checked'))
				{
					return !window.alert("Aucune ligne sélectionnée !");
				}


				this.form.submit();
			};
		}

		// Ajouter action check/uncheck sur les checkbox de raccourci dans les tableaux
		document.querySelectorAll('table thead input[type=checkbox], table tfoot input[type=checkbox]').forEach((elm) => {
			elm.addEventListener('change', g.checkUncheck);







|











>
|









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




















>







331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
		if (!document.activeElement || document.activeElement.tagName.toLowerCase() == 'body') {
			let form = document.querySelector('form[data-focus]');

			if (!form) {
				return;
			}

			var i = form.querySelector(form.dataset.focus == 1 ? '[name]:not([type="hidden"])' : form.dataset.focus);
			i.focus();
		}
	}, 'dom');

	// Sélecteurs de listes
	g.onload(() => {
		var inputs = $('form .input-list > button');

		inputs.forEach((i) => {
			i.onclick = () => {
				g.current_list_input = i.parentNode;
				let url = i.value + (i.value.indexOf('?') > 0 ? '&' : '?') + '_dialog';
				g.openFrameDialog(url);
				return false;
			};
		});

		var multiples = $('form .input-list span button');

		multiples.forEach((btn) => {
			btn.onclick = () => btn.parentNode.parentNode.removeChild(btn.parentNode);
		});

		// Open links in dialog
		$('a[target="_dialog"]').forEach((e) => {
			e.onclick = () => {
				let type = e.getAttribute('data-mime');

				if (!type) {
					let url = e.href + (e.href.indexOf('?') > 0 ? '&' : '?') + '_dialog';
					g.openFrameDialog(url, e.getAttribute('data-dialog-height') ? '90%' : 'auto');
					return false;
				}

				if (type.match(/^image\//)) {
					var i = document.createElement('img');
					i.src = e.href;
				}
				else if (type.match(/^audio\//)) {
					var i = document.createElement('audio');
					i.autoplay = true;
					i.controls = true;
					i.src = e.href;
				}
				else if (type.match(/^video\/|^application\/ogg$/)) {
					var i = document.createElement('video');
					i.autoplay = true;
					i.controls = true;
					i.src = e.href;
				}
				else {
					let url = e.href + (e.href.indexOf('?') > 0 ? '&' : '?') + '_dialog';
					g.openFrameDialog(url, '90%');
					return false;
				}

				g.openDialog(i);

				return false;
			};
		});

		$('form[target="_dialog"]').forEach((e) => {
			e.addEventListener('submit', () => {
				let url = e.getAttribute('action');
				url = url + (url.indexOf('?') > 0 ? '&' : '?') + '_dialog';
				e.setAttribute('action', url);
				e.target = 'dialog';

				g.openFrameDialog('about:blank', e.getAttribute('data-dialog-height') ? '90%' : 'auto');
				e.submit();
				return false;
			});
		});
	});

	g.onload(() => {
		document.querySelectorAll('input[data-input="date"]').forEach((e) => {
			g.enhanceDateField(e);
		});
	});

	// 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++)
		{
			tableActions[i].onchange = function () {
				if (!this.form.querySelector('table tbody input[type=checkbox]:checked'))
				{
					return !window.alert("Aucune ligne sélectionnée !");
				}

				this.form.dispatchEvent(new Event('submit'));
				this.form.submit();
			};
		}

		// Ajouter action check/uncheck sur les checkbox de raccourci dans les tableaux
		document.querySelectorAll('table thead input[type=checkbox], table tfoot input[type=checkbox]').forEach((elm) => {
			elm.addEventListener('change', g.checkUncheck);

Added src/www/admin/static/scripts/lib/code_editor.min.js version [b81debcc16].





>
>
1
2
window.textEditor=function(t){if(!document.getElementById(t))throw new Error("Invalid ID parameter: "+t);return this.id=t,this.textarea=document.getElementById(t),this.shortcuts=[],"selectionStart"in this.textarea&&(this.textarea.addEventListener("keydown",this.keyEvent.bind(this),!0),this.textarea.addEventListener("keypress",this.keyEvent.bind(this),!0),!0)},textEditor.prototype.keyEvent=function(t){for(var e in t=t||window.event,this.shortcuts){var r=this.shortcuts[e];if(!t.metaKey&&!(t.ctrlKey&&!r.ctrl||r.ctrl&&!t.ctrlKey)&&!(t.shiftKey&&!r.shift||r.shift&&!t.shiftKey)&&!(t.altKey&&!r.alt||r.alt&&!t.altKey)&&(e=this.matchKeyPress(r.key,t))){if("function"==typeof r.callback)return!r.callback.call(this,t,e)||this.preventDefault(t);var n=(r.ctrl?"Ctrl-":"")+(r.alt?"Alt-":"");throw n+=(r.shift?"Shift-":"")+r,new Error("Invalid callback type for shortcut "+n)}}return!0},textEditor.prototype.matchKeyPress=function(t,e){return!(e.defaultPrevented||!e.key)&&(t=t.toLowerCase(),e.key.toLowerCase()==t&&t)},textEditor.prototype.preventDefault=function(t){return t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation(),t.stopImmediatePropagation&&t.stopImmediatePropagation(),t.returnValue=!1,!(t.cancelBubble=!0)},textEditor.prototype.getSelection=function(){var t=this.textarea,e=t.selectionEnd-t.selectionStart;return{start:t.selectionStart,end:t.selectionEnd,length:e,text:t.value.substr(t.selectionStart,e)}},textEditor.prototype.replaceSelection=function(t,e){var r=this.textarea,n=t.start,o=n+e.length;return r.value=r.value.substr(0,n)+e+r.value.substr(t.end,r.value.length),this.setSelection(n,o),{start:n,end:o,length:e.length,text:e}},textEditor.prototype.insertAtPosition=function(t,e,r){var n=t+e.length,o=this.textarea;return o.value=o.value.substr(0,t)+e+o.value.substr(t,o.value.length-t),r||(r=n),this.setSelection(r,r)},textEditor.prototype.setSelection=function(t,e){var r=this.textarea;return r.focus(),r.selectionStart=t,r.selectionEnd=e,this.getSelection()},textEditor.prototype.scrollToSelection=function(t){var e=this.textarea,r=e.value.substr(t.end);e.value=e.value.substr(0,t.end),e.scrollTop=1e5;var n=e.scrollTop;e.value+=r,e.scrollTop=n,this.setSelection(t.start,t.end)},textEditor.prototype.wrapSelection=function(t,e,r){var n=this.textarea,o=n.scrollTop,a=t.text;return t=this.replaceSelection(t,e+a+r),""==a&&(t=this.setSelection(t.start+e.length,t.start+e.length)),n.scrollTop=o,t};
String.prototype.repeat=function(t){return new Array(t+1).join(this)},window.codeEditor=function(t){if(!textEditor.call(this,t))return!1;this.onlinechange=null,this.onlinenumberchange=null,this.fullscreen=!1,this.nb_lines=0,this.current_line=0,this.search_str=null,this.search_pos=0,this.params={indent_size:4,tab_size:4,convert_tabs:!0,lang:{search:"Text to search?\n(regexps allowed, begin them with '/')",replace:"Text for replacement?\n(use $1, $2... for regexp replacement)",search_selection:"Text to replace in selection?\n(regexps allowed, begin them with '/')",replace_result:"%d occurence found and replaced.",goto:"Line to go to:",no_search_result:"No search result found."}},(that=this).init(),this.textarea.spellcheck=!1,this.shortcuts.push({shift:!0,key:"tab",callback:this.indent}),this.shortcuts.push({key:"tab",callback:this.indent}),this.shortcuts.push({ctrl:!0,key:"f",callback:this.search}),this.shortcuts.push({ctrl:!0,key:"h",callback:this.searchAndReplace}),this.shortcuts.push({ctrl:!0,key:"g",callback:this.goToLine}),this.shortcuts.push({key:"F3",callback:this.searchNext}),this.shortcuts.push({key:"backspace",callback:this.backspace}),this.shortcuts.push({key:"enter",callback:this.enter}),this.shortcuts.push({key:'"',callback:this.insertBrackets}),this.shortcuts.push({key:"[",callback:this.insertBrackets}),this.shortcuts.push({key:"{",callback:this.insertBrackets}),this.shortcuts.push({key:"(",callback:this.insertBrackets}),this.shortcuts.push({key:"F11",callback:this.toggleFullscreen}),this.textarea.addEventListener("keypress",this.keyEvent.bind(this),!0),this.textarea.addEventListener("keydown",this.keyEvent.bind(this),!0)},codeEditor.prototype=function(t){function e(){}return e.prototype=t,new e}(textEditor.prototype),codeEditor.prototype.init=function(){var t=this;for(this.nb_lines=this.countLines(),this.parent=document.createElement("div"),this.parent.className="codeEditor",this.lineCounter=document.createElement("span"),this.lineCounter.className="lineCount",i=1;i<=this.nb_lines;i++)this.lineCounter.innerHTML+="<b>"+i+"</b>";this.lineCounter.innerHTML+="<i>---</i>",this.parent.appendChild(this.lineCounter);var e=document.createElement("div");e.className="container",e.appendChild(this.textarea.cloneNode(!0)),this.parent.appendChild(e);var s=this.textarea.parentNode;s.appendChild(this.parent),s.removeChild(this.textarea),this.textarea=this.parent.getElementsByTagName("textarea")[0],this.textarea.wrap="off",this.params.convert_tabs&&(this.textarea.value=this.textarea.value.replace(/[ ]{1,7}\t/g," ".repeat(this.params.tab_size)),this.textarea.value=this.textarea.value.replace(/\t/g," ".repeat(this.params.tab_size))),this.textarea.addEventListener("focus",function(){t.update()},!1),this.textarea.addEventListener("keyup",function(){t.update()},!1),this.textarea.addEventListener("click",function(){t.update()},!1),this.textarea.addEventListener("scroll",function(){t.lineCounter.scrollTop=t.textarea.scrollTop},!1)},codeEditor.prototype.update=function(){var t=this.getSelection(),e=this.getLineNumberFromPosition(t),s=this.countLines();if(this.search_pos=t.end,s!=this.nb_lines){for(var r=this.lineCounter.getElementsByTagName("b"),i=this.nb_lines;s<i;i--)this.lineCounter.removeChild(r[i-1]);var n=this.lineCounter.lastChild;for(i=r.length;i<s;i++){var a=document.createElement("b");a.innerHTML=i+1,this.lineCounter.insertBefore(a,n)}this.nb_lines=s,"function"==typeof this.onlinenumberchange&&this.onlinenumberchange.call(this)}if(e!=this.current_line){for(r=this.lineCounter.getElementsByTagName("b"),i=0;i<this.nb_lines;i++)r[i].className="";r[e].className="current",this.current_line=e,"function"==typeof this.onlinechange&&this.onlinechange.call(this)}},codeEditor.prototype.countLines=function(){var t=this.textarea.value.match(/(\r?\n)/g);return t?t.length+1:1},codeEditor.prototype.getLineNumberFromPosition=function(t){if(0==(t=t||this.getSelection()).start)return 0;var e=this.textarea.value.substr(0,t.start).match(/(\r?\n)/g);return e?e.length:0},codeEditor.prototype.getLines=function(){return this.textarea.value.split("\n")},codeEditor.prototype.getLine=function(t){return this.textarea.value.split("\n",t+1)[t]},codeEditor.prototype.getLinePosition=function(t,e){var s=0;for(i=0;i<t.length;i++){if(i==e)return{start:s+i,end:s+t[i].length,length:t[i].length,text:t[i]};s+=t[i].length}return!1},codeEditor.prototype.selectLines=function(t){for(var e=t.start;0<e;e--)if("\n"==this.textarea.value.substr(e,1)){t.start=e+1;break}for(e=t.end-1;e<this.textarea.length;e++)if("\n"==this.textarea.value.substr(e,1)){t.end=e-1;break}return this.setSelection(t.start,t.end),t},codeEditor.prototype.goToLine=function(t){var e=window.prompt(that.params.lang.goto);if(e){var s=this.textarea.value.split("\n",parseInt(e,10)).join("\n").length;return this.scrollToSelection(this.setSelection(s,s)),!0}},codeEditor.prototype.indent=function(t,e){var s=this.getSelection(),r=t.shiftKey,i=this.getLines(),n=this.getLineNumberFromPosition(s),a=this.getLinePosition(i,n),h=s.end>a.end;if((0==s.length||!h)&&s.start!=a.start)return this.insertAtPosition(s.start," ".repeat(this.params.indent_size)),!0;if(0==s.length&&s.start==a.start){var o=n-1 in i&&i[n-1].match(/^(\s+)/);if(o&&0==a.length)c=" ".repeat(o[1].length);else var c=" ".repeat(this.params.indent_size);return this.insertAtPosition(s.start,c),!0}s=this.selectLines(s);var l=this.textarea.value.substr(s.start,s.end-s.start);if(i=l.split("\n"),r)for(var p=new RegExp("^[ ]{1,"+this.params.indent_size+"}"),u=0;u<i.length;u++)i[u]=i[u].replace(p,"");else for(u=0;u<i.length;u++)i[u]=" ".repeat(this.params.indent_size)+i[u];return l=i.join("\n"),this.replaceSelection(s,l),!0},codeEditor.prototype.search=function(){if(this.search_str=window.prompt(this.params.lang.search,this.search_str?this.search_str:""))return this.search_pos=0,this.searchNext()},codeEditor.prototype.searchNext=function(){if(!this.search_str)return!0;var t=this.getSelection(),e=t.end>=this.search_pos?this.search_pos:t.start,s=this.textarea.value.substr(e),r=this.getSearchRegexp(this.search_str),i=s.search(r);if(-1==i)return window.alert(this.params.lang.no_search_result);var n=s.match(r);return t.start=e+i,t.end=t.start+n[0].length,t.length=n[0].length,t.text=n[0],this.setSelection(t.start,t.end),this.search_pos=t.end,this.scrollToSelection(t),!0},codeEditor.prototype.getSearchRegexp=function(t,e){var s,r;if("/"==t.substr(0,1)){var i=t.lastIndexOf("/");s=t.substr(1,i-1),r=t.substr(i+1).replace(/g/,"")}else s=t.replace(/([\/$^.?()[\]{}\\])/,"\\$1"),r="i";return e&&(r+="g"),new RegExp(s,r)},codeEditor.prototype.searchAndReplace=function(t){var e=this.getSelection(),i=0!=e.length?this.params.lang.search_selection:this.params.lang.search;if(!(s=window.prompt(i,this.search_str?this.search_str:""))||!(r=window.prompt(that.params.lang.replace)))return!0;var n=this.getSearchRegexp(s,!0);if(0==e.length){var a=this.textarea.value.match(n).length;this.textarea.value=this.textarea.value.replace(n,r)}else a=e.text.match(n).length,this.replaceSelection(e,e.text.replace(n,r));return window.alert(this.params.lang.replace_result.replace(/%d/g,a)),!0},codeEditor.prototype.enter=function(t){var e=this.getSelection(),s=this.getLineNumberFromPosition(e),r="";return s=this.getLine(s),"{"==this.textarea.value.substr(e.start-1,1)&&(r+=" ".repeat(this.params.indent_size)),(match=s.match(/^(\s+)/))&&(r+=match[1]),!!r&&(this.insertAtPosition(e.start,"\n"+r),!0)},codeEditor.prototype.backspace=function(t){var e=this.getSelection();if(0<e.length)return!1;if('""'==(s=this.textarea.value.substr(e.start-2,2))||"''"==s||"{}"==s||"()"==s||"[]"==s)return e.start-=2,this.replaceSelection(e,""),!0;var s=this.textarea.value.substr(e.start-20,20);return-1!=(pos=s.search(/^(\s+)$/m))&&(e.start-=this.params.indent_size,this.replaceSelection(e,""),!0)},codeEditor.prototype.insertBrackets=function(t,e){var s=this.getSelection(),r=e,i=r;switch(r){case"(":i=")";break;case"[":i="]";break;case"{":i="}"}return 0==s.length?this.insertAtPosition(s.start,r+i,s.start+1):this.wrapSelection(s,r,i),!0},codeEditor.prototype.toggleFullscreen=function(t){for(var e=this.parent.className.split(" "),s=0;s<e.length;s++)if("fullscreen"==e[s])return e.splice(s,1),this.parent.className=e.join(" "),!(this.fullscreen=!1);return e.push("fullscreen"),this.parent.className=e.join(" "),this.fullscreen=!0};

Added src/www/admin/static/scripts/lib/text_editor.min.js version [83bda3f0af].



>
1
window.textEditor=function(t){if(!document.getElementById(t))throw new Error("Invalid ID parameter: "+t);return this.id=t,this.textarea=document.getElementById(t),this.shortcuts=[],"selectionStart"in this.textarea&&(this.textarea.addEventListener("keydown",this.keyEvent.bind(this),!0),this.textarea.addEventListener("keypress",this.keyEvent.bind(this),!0),!0)},textEditor.prototype.keyEvent=function(t){for(var e in t=t||window.event,this.shortcuts){var r=this.shortcuts[e];if(!t.metaKey&&!(t.ctrlKey&&!r.ctrl||r.ctrl&&!t.ctrlKey)&&!(t.shiftKey&&!r.shift||r.shift&&!t.shiftKey)&&!(t.altKey&&!r.alt||r.alt&&!t.altKey)&&(e=this.matchKeyPress(r.key,t))){if("function"==typeof r.callback)return!r.callback.call(this,t,e)||this.preventDefault(t);var n=(r.ctrl?"Ctrl-":"")+(r.alt?"Alt-":"");throw n+=(r.shift?"Shift-":"")+r,new Error("Invalid callback type for shortcut "+n)}}return!0},textEditor.prototype.matchKeyPress=function(t,e){return!(e.defaultPrevented||!e.key)&&(t=t.toLowerCase(),e.key.toLowerCase()==t&&t)},textEditor.prototype.preventDefault=function(t){return t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation(),t.stopImmediatePropagation&&t.stopImmediatePropagation(),t.returnValue=!1,!(t.cancelBubble=!0)},textEditor.prototype.getSelection=function(){var t=this.textarea,e=t.selectionEnd-t.selectionStart;return{start:t.selectionStart,end:t.selectionEnd,length:e,text:t.value.substr(t.selectionStart,e)}},textEditor.prototype.replaceSelection=function(t,e){var r=this.textarea,n=t.start,o=n+e.length;return r.value=r.value.substr(0,n)+e+r.value.substr(t.end,r.value.length),this.setSelection(n,o),{start:n,end:o,length:e.length,text:e}},textEditor.prototype.insertAtPosition=function(t,e,r){var n=t+e.length,o=this.textarea;return o.value=o.value.substr(0,t)+e+o.value.substr(t,o.value.length-t),r||(r=n),this.setSelection(r,r)},textEditor.prototype.setSelection=function(t,e){var r=this.textarea;return r.focus(),r.selectionStart=t,r.selectionEnd=e,this.getSelection()},textEditor.prototype.scrollToSelection=function(t){var e=this.textarea,r=e.value.substr(t.end);e.value=e.value.substr(0,t.end),e.scrollTop=1e5;var n=e.scrollTop;e.value+=r,e.scrollTop=n,this.setSelection(t.start,t.end)},textEditor.prototype.wrapSelection=function(t,e,r){var n=this.textarea,o=n.scrollTop,a=t.text;return t=this.replaceSelection(t,e+a+r),""==a&&(t=this.setSelection(t.start+e.length,t.start+e.length)),n.scrollTop=o,t};

Modified src/www/admin/static/scripts/password.js from [3ab672a055] to [424f2fa176].

1
2
3
4
5
6
7
8
9






10
11
12
13
14
15
16
(function () {
	var strength_elm, match_elm, pw_elm, pw2_elm, suggest_elm;

	RegExp.quote = function(str) {
	    return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
	};

	window.initPasswordField = function(suggest, password, password2)
	{






		pw_elm = (typeof password == 'string') ? document.getElementById(password) : password;
		pw2_elm = (typeof password2 == 'string') ? document.getElementById(password2) : password2;
		suggest_elm = (typeof suggest == 'string') ? document.getElementById(suggest) : suggest;

		g.enhancePasswordField(pw_elm, pw2_elm);

		suggest_elm.style.width = suggest_elm.value.length + 'ch';









>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
(function () {
	var strength_elm, match_elm, pw_elm, pw2_elm, suggest_elm;

	RegExp.quote = function(str) {
	    return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
	};

	window.initPasswordField = function(suggest, password, password2)
	{
		if (typeof password == 'undefined') {
			password = 'f_' + suggest;
			password2 = password + '_confirm';
			suggest = password + '_suggest';
		}

		pw_elm = (typeof password == 'string') ? document.getElementById(password) : password;
		pw2_elm = (typeof password2 == 'string') ? document.getElementById(password2) : password2;
		suggest_elm = (typeof suggest == 'string') ? document.getElementById(suggest) : suggest;

		g.enhancePasswordField(pw_elm, pw2_elm);

		suggest_elm.style.width = suggest_elm.value.length + 'ch';
119
120
121
122
123
124
125
126






127
128
129
130
131
132
133
	    if (pw_elm.value == '')
	    {
	    	strength_elm.className = strength_elm.className.split(' ')[0];
	        strength_elm.innerHTML = '';
	        return true;
	    }

	    if (!pw_elm.value.match(new RegExp(pw_elm.getAttribute('pattern'))))






	    {
	    	strength_elm.className = strength_elm.className.split(' ')[0] + ' fail';
	        strength_elm.innerHTML = 'Trop court&nbsp;!';
	        return true;
	    }

	    var score = scorePassword(pw_elm.value);







|
>
>
>
>
>
>







125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
	    if (pw_elm.value == '')
	    {
	    	strength_elm.className = strength_elm.className.split(' ')[0];
	        strength_elm.innerHTML = '';
	        return true;
	    }

	    if (pw_elm.hasAttribute('pattern') && !pw_elm.value.match(new RegExp(pw_elm.getAttribute('pattern')))) // FIXME deprecated
	    {
	    	strength_elm.className = strength_elm.className.split(' ')[0] + ' fail';
	        strength_elm.innerHTML = 'Trop court&nbsp;!';
	        return true;
	    }
	    else if (pw_elm.hasAttribute('minlength') && pw_elm.value.length < pw_elm.getAttribute('minlength'))
	    {
	    	strength_elm.className = strength_elm.className.split(' ')[0] + ' fail';
	        strength_elm.innerHTML = 'Trop court&nbsp;!';
	        return true;
	    }

	    var score = scorePassword(pw_elm.value);

Deleted src/www/admin/static/scripts/skel_editor.css version [f204b32def].

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
.codeEditor {
	width: 100%;
	height: 600px;
	border: 1px solid #999;
	background: #eee;
	position: relative;
	display: block;
}

.codeEditor .sk_help {
	background: #ccc;
	border-top: 2px solid #999;
	position: absolute;
	left: 0;
	right: 0;
	bottom: 0;
	height: 15px;
	padding: 5px 1em 0;
	font-family: "Deja Vu Sans Mono", "Droid Sans Mono", "Courier New", Courier, monospace;
	font-size: 12px;
}

.codeEditor .sk_toolbar {
	background: #ccc;
	border-bottom: 2px solid #999;
	height: 32px;
}

.codeEditor .sk_toolbar select {
	float: right;
	border: none;
	border-radius: .2em;
	height: 24px;
	padding-left: 24px;
	margin: 4px .5em;
	background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAMFBMVEUAAACZm4leYFyOkX1RU09MTkp9f2+ys6KwsZrn5+KanIz///+6u6vGxryDhXtVV1Otpz1oAAAAA3RSTlMA+7omiqY6AAAAgklEQVQI12NI+f9fgQEEfO7e+QBm/BGU+P8fJPrd2LgLCD4AGSCBLCDD8Pfu3bu9QCK/Z86e/esDw4/Hv+/euf0ZyEj7PXPnbCDDI+33kZDQkE8M/11D1969e9eEwRNIlpe332f421Ne0dHRcYnh75k7Z8/cudPEoOIS4uriAlQMAwDpN0taA/g97gAAAABJRU5ErkJggg==") no-repeat 5px center;
	cursor: pointer;
}

.codeEditor .sk_toolbar select:hover {
	background-color: #fff;
}

.codeEditor .sk_toolbar p {
	display: inline;
	padding: .3em .5em;
	border-radius: .5em;
	font-size: .9em;
	margin-left: 2em;
}

.codeEditor .sk_toolbar input {
	margin: 4px .5em;
	padding: 0;
	width: 24px;
	height: 24px;
	border: none;
	border-radius: .2em;
	cursor: pointer;
	text-indent: -70em;
	overflow: hidden;
	background: transparent no-repeat center center;
}

.codeEditor .sk_toolbar input:hover { background-color: #fff; }

.codeEditor .sk_toolbar .save { margin-left: 2em; background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAMFBMVEU6XIthfJfOXAD8rz6PpsDe3t7+/v6YrsZhe5NVV1Py8vL09PTMzc6+0upyn88gSod8oq0HAAAAAXRSTlOZyTXzhgAAAGxJREFUCNdj4P+kBAT6Hxj+XjYGAtv7DH+fbQOCfSBGKBDkgRi7gQAschQoAmbsXrVq1ToQIw0IQGregQGQ8bCjo6OvDsQ4czS04jmQ8eLMzJiDUMYZkMj3ilAIg/9h6PEjJ4AMhp8zgeD/BwBY4VdD5HZlvAAAAABJRU5ErkJggg=="); }
.codeEditor .sk_toolbar .reset { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QAAAAAAAD5Q7t/AAABCklEQVR42p2TsUrDUBSGv4RM2qlLXXwBHdoncG3u5tpZx059gojgZAtC3bqqa7cQKH2FWiFZHUSIg5lChi7Xpak312Ma/eHA5Zzz/5fzHw5UMQZ0wxgDOCb5fnQ8Glxe0AR31zdcPW0mpoDOkoDPJKRI41rywdEpRRrTHeZ4drFIY15nh5w/f4jkea/D2aPafeJKTVuyI4Ut7G0NkVDmnbpxXMAHyJJgl1xPW+XT32emC0SA3z75FugO85Ic8Qf0jR33a/p0lgR6PW1pQJtbiPbNK8GzDLPhNBVAKVUphGGIJD7vdWQBi1SBuSGA/P1FFvgNb8vbH7nFaoO5Ja2Uki6Ommt8ME36t4lfRLtlZDAJ4ScAAAAASUVORK5CYII="); }
.codeEditor .sk_toolbar .search { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAABGdBTUEAAK/INwWK6QAAADBQTFRF////epWwPGiTdYKPdHqB1tbWWW6Hp6enR2yQc6b/dqncME9tmcz/i5CX5e32w9PmM3gGSwAAAAd0Uk5TAAAAQoTswgXk1s4AAABySURBVAjXYxA0v+4syAAEIqXvQh1BDPN3J88Vgxj3/r07EwtmnDw58y2YcebMHLBI6p/358NADN/3Z75eFhQUZFC5/i4WqIaRwcjtdsrWa0AGEDByr2oAM5i4V82AMBh2nGmCMIBCEAbDrhVghpKS9jYA43soYFw0gPcAAAAASUVORK5CYII="); }
.codeEditor .sk_toolbar .search_replace { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAMFBMVEUAAABnVEEAAACEhoVsaWX4liHmz2/8/Pzf398uNDawrKfn5+fOXADj4+P+/v6IioXFYmG9AAAAAnRSTlMAWv0tddIAAACKSURBVAjXY2Dg/w8EAgwMDP/evSuvWwhi7N69Y8UrATDjxurbC4CMn/P3rv9vwMDw3+/J31s9BxkYOl/vm3vjaCiEsSc0hoGhxe+J7dHUgwxckz0nAwUCGDotO3qPph4zYJg8q+P20Zg+AwbJ9rt3VE60f2BgML+76VgHiPH93bt3z8uBjP9g8AEArPJMCYP5JmIAAAAASUVORK5CYII="); }
.codeEditor .sk_toolbar .gotoline { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAMFBMVEX///9BQUEVFRWysrREREQ4ODhVVVX7+/vu7u7q6uqcnJy+vr/m5ub19fXc3Nz///89lwBDAAAAB3RSTlMAAILOakNmMhUGwgAAAHtJREFUCNdjYIABQbE0EEhkEMx793r37tdmDILZu1fv3rVqEYNgfv3/u/X/vwEZu4/Xl5eXARnbd96trS1hcPNaWdd7924Jg+///7UdHR1XGIK01lSfnDmzhUFQY8W6N2fOABl+q/a8OXfmCYOg3jugwJlJDIJKEMCAAQCfIDck8YzyWAAAAABJRU5ErkJggg=="); }
.codeEditor .sk_toolbar .fullscreen { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAADFBMVEUAAABMTFFOTlBOTlCQ1uMHAAAAA3RSTlMAOcKBmOr4AAAAQUlEQVQI12P4/4D7P8N/B0Yo8XsC23+GZw+4pzM4TmBzYsAGgBKODNcecM9m+D+B7T3DPwfG/Qz/G5iABlzg+g8ANzMax/3kkQoAAAAASUVORK5CYII="); }
.codeEditor.fullscreen .sk_toolbar .fullscreen { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAADFBMVEUAAABNTVFOTlBOTlBLB/faAAAAA3RSTlMAOsPdsomtAAAAQElEQVQI12NIEWCRZNi5gTePIe8D/08G6Q/8Txj0P/B/YVj/gf8fAzawHyQhD1ICJvI/8O9k2FnAl8eQosAiCQCgixb13aKGIwAAAABJRU5ErkJggg=="); }

.codeEditor .lineCount, .codeEditor textarea {
	font-family: "Deja Vu Sans Mono", "Droid Sans Mono", "Courier New", Courier, monospace;
	font-size: 11pt;
	line-height: 11pt;
}

.codeEditor .lineCount {
	position: absolute;
	top: 34px;
	left: 0;
	bottom: 22px;
	width: 46px;
	text-align: right;
	border-right: 2px solid #999;
	overflow: hidden;
}

.codeEditor .lineCount i {
	display: block;
	padding-right: 2px;
	font-weight: normal;
}	

.codeEditor .lineCount b {
	display: block;
	padding-right: 2px;
	font-weight: normal;
}

.codeEditor .lineCount b.current {
	background: #ccc;
}

.codeEditor .container {
	position: absolute;
	right: 4px;
	top: 34px;
	bottom: 22px;
	left: 50px;
	margin: 0;
	padding: 0;
}

.codeEditor textarea {
	height: 100%;
	width: 100%;
	padding: 0 0 0 2px;
	margin: 0;
	background: transparent;
	border: none;
	overflow: auto;
	resize: none;
}

.codeEditor.fullscreen {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	width: 100%;
	height: 100%;
	z-index: 100000;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































































































































Deleted src/www/admin/static/scripts/skel_editor.js version [6b35de296d].

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
(function (){
	g.style('scripts/skel_editor.css');
	g.script('scripts/code_editor.min.js', function ()
	{
		var save_btn = document.querySelector('[name=save]');
		save_btn.type = 'hidden';

		var code = new codeEditor('f_content');

		code.params.lang = {
			search: "Texte à chercher ?\n(expression régulière autorisée, pour cela commencer par un slash '/')",
			replace: "Texte pour le remplacement ?\n(utiliser $1, $2... pour les captures d'expression régulière)",
			search_selection: "Texte à chercher dans la sélection ?\n(expression régulière autorisée, pour cela commencer par un slash '/')",
			replace_result: "%d occurences trouvées et remplacées.",
			goto: "Aller à la ligne :",
			no_search_result: "Aucun résultat trouvé."
		};

		code.origValue = code.textarea.value;
		code.saved = true;

		code.onlinechange = function () {
			if ((p = this.parent.querySelector('nav p')) && this.origValue != code.textarea.value)
			{
				toolbar.removeChild(p);
			}

			var line = this.getLine(this.current_line);
			var doc = [];

			if (match = line.match(/<BOUCLE(\d+|_[a-zA-Z0-9_-]+)\(([A-Z]+)\)(.*?)>/))
			{
				doc.push({link: 'Boucles', title: 'BOUCLE'});
				doc.push({link: 'Boucle-'+match[2], title: match[2]});

				if (match[3])
				{
					if (match[3].match(/\{".*"\}/))
						doc.push({link: 'Critere-inter', title: 'Critère inter-résultat {"..."}'});
					if (match[3].match(/\{\d+(,\d+)?\}/))
						doc.push({link: 'Critere-de-nombre', title: 'Critère de nombre {X,Y}'});
					if (match[3].match(/\{par\s+.*\}/))
						doc.push({link: 'Critere-d-ordre', title: 'Critère d\'ordre {par champ}'});
					if (match[3].match(/\{inverse\}/))
						doc.push({link: 'Critere-inverse', title: 'Critère {inverse}'});
				}
			}

			if (match = line.match(/<INCLURE\{(.*?)\}>/))
			{
				doc.push({link: 'Inclure', title: 'Inclusion du fichier ' + match[1]});
			}

			if (match = line.match(/#[A-Z0-9_]+(\*?(\|.*?)?\).*?\])?/g))
			{
				for (var i = 0; i < match.length; i++)
				{
					var tag = match[i].match(/(#[A-Z0-9_]+)(\*?(\|(.*?))?\).*?\])?/);
					doc.push({title: 'Balise ' + tag[1]});
					
					if (typeof tag[4] != 'undefined')
					{
						var tag = tag[4].split('|');
						for (var j = 0; j < tag.length; j++)
						{
							var end = tag[j].indexOf('{');
							end = (end == -1) ? tag[j].length : end;
							var f = tag[j].substr(0, end);
							doc.push({link: 'Filtre-'+f, title: 'Filtre '+f});
						}
					}
				}
			}

			help.innerHTML = '';

			for (var i = 0; i < doc.length; i++)
			{
				help.innerHTML += ' | ';

				if (doc[i].link)
					help.innerHTML += '<a href="' + doc_url + '#' + doc[i].link + '" onclick="return !window.open(this.href);">' + doc[i].title + '</a>';
				else if (doc[i].tag)
					help.innerHTML += '<' + tag + '>' + doc[i].title + '</' + tag + '>';
				else
					help.innerHTML += doc[i].title;
			}		return false;

		};

		code.saveFile = function (e)
		{
			if (this.fullscreen)
				this.textarea.form.action += '&fullscreen';

			this.textarea.form.submit();
		};

		code.loadFile = function (e)
		{
			var file = e.target.value;

			if (file == skel_current) return;

			if (code.textarea.value != code.origValue &&
				!window.confirm("Le fichier a été modifié, abandonner les modifications ?"))
			{
				for (var i = 0; i < e.target.options.length; i++)
				{
					e.target.options[i].selected = false;

					if (e.target.options[i].value == skel_current)
					{
						e.target.options[i].selected = true;
					}
				}

				return false;
			}

			var url = garradin.admin_url + 'config/site.php?edit=' + encodeURIComponent(file);

			window.location.href = url + (code.fullscreen ? '#fullscreen' : '');

			return true;
		};

		code.resetFile = function (e)
		{
			if (this.textarea.value == this.origValue) return;
			if (!window.confirm("Le fichier a été modifié, abandonner les modifications ?")) return;
			this.textarea.form.reset();
		};

		var help = document.createElement('div');
		help.className = 'sk_help';

		code.parent.appendChild(help);

		var toolbar = document.createElement('nav');
		toolbar.className = 'sk_toolbar';

		var appendButton = function (name, title, action)
		{
			var btn = document.createElement('input');
			btn.type = 'button';
			btn.value = btn.title = title;
			btn.className = name;
			btn.onclick = function () { action.call(code); return false; };

			toolbar.appendChild(btn);
		};

		appendButton('save', 'Enregistrer les modifications', code.saveFile);
		appendButton('reset', 'Recharger le fichier (effacer les modifications)', code.resetFile);

		appendButton('search', 'Chercher', code.search);
		appendButton('search_replace', 'Chercher et remplacer', code.searchAndReplace);
		appendButton('gotoline', 'Aller à la ligne', code.goToLine);
		appendButton('fullscreen', 'Plein écran', code.toggleFullscreen);
		
		var sel = document.createElement('select');
		sel.title = 'Charger un autre fichier';
		sel.onchange = code.loadFile;

		for (var i in skel_list)
		{
			if (!skel_list.hasOwnProperty(i))
				continue;

			var skel = i;
			var opt = document.createElement('option');
			opt.value = skel;
			opt.innerHTML = skel;
			opt.selected = (skel == skel_current) ? true : false;
			sel.appendChild(opt);
		}

		toolbar.appendChild(sel);

		code.parent.insertBefore(toolbar, code.parent.firstChild);

		if (window.location.hash.match(/fullscreen/))
		{
			code.toggleFullscreen();

			if (msg = document.querySelector('p.error, p.confirm'))
			{
				var m = document.createElement('p');
				m.innerHTML = msg.innerHTML;
				m.className = msg.className;
				toolbar.appendChild(m);
				msg.parentNode.removeChild(msg);
			}

			window.location.hash = '';
		}
	});
}());
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































































Deleted src/www/admin/static/scripts/text_editor.min.js version [83bda3f0af].

1
window.textEditor=function(t){if(!document.getElementById(t))throw new Error("Invalid ID parameter: "+t);return this.id=t,this.textarea=document.getElementById(t),this.shortcuts=[],"selectionStart"in this.textarea&&(this.textarea.addEventListener("keydown",this.keyEvent.bind(this),!0),this.textarea.addEventListener("keypress",this.keyEvent.bind(this),!0),!0)},textEditor.prototype.keyEvent=function(t){for(var e in t=t||window.event,this.shortcuts){var r=this.shortcuts[e];if(!t.metaKey&&!(t.ctrlKey&&!r.ctrl||r.ctrl&&!t.ctrlKey)&&!(t.shiftKey&&!r.shift||r.shift&&!t.shiftKey)&&!(t.altKey&&!r.alt||r.alt&&!t.altKey)&&(e=this.matchKeyPress(r.key,t))){if("function"==typeof r.callback)return!r.callback.call(this,t,e)||this.preventDefault(t);var n=(r.ctrl?"Ctrl-":"")+(r.alt?"Alt-":"");throw n+=(r.shift?"Shift-":"")+r,new Error("Invalid callback type for shortcut "+n)}}return!0},textEditor.prototype.matchKeyPress=function(t,e){return!(e.defaultPrevented||!e.key)&&(t=t.toLowerCase(),e.key.toLowerCase()==t&&t)},textEditor.prototype.preventDefault=function(t){return t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation(),t.stopImmediatePropagation&&t.stopImmediatePropagation(),t.returnValue=!1,!(t.cancelBubble=!0)},textEditor.prototype.getSelection=function(){var t=this.textarea,e=t.selectionEnd-t.selectionStart;return{start:t.selectionStart,end:t.selectionEnd,length:e,text:t.value.substr(t.selectionStart,e)}},textEditor.prototype.replaceSelection=function(t,e){var r=this.textarea,n=t.start,o=n+e.length;return r.value=r.value.substr(0,n)+e+r.value.substr(t.end,r.value.length),this.setSelection(n,o),{start:n,end:o,length:e.length,text:e}},textEditor.prototype.insertAtPosition=function(t,e,r){var n=t+e.length,o=this.textarea;return o.value=o.value.substr(0,t)+e+o.value.substr(t,o.value.length-t),r||(r=n),this.setSelection(r,r)},textEditor.prototype.setSelection=function(t,e){var r=this.textarea;return r.focus(),r.selectionStart=t,r.selectionEnd=e,this.getSelection()},textEditor.prototype.scrollToSelection=function(t){var e=this.textarea,r=e.value.substr(t.end);e.value=e.value.substr(0,t.end),e.scrollTop=1e5;var n=e.scrollTop;e.value+=r,e.scrollTop=n,this.setSelection(t.start,t.end)},textEditor.prototype.wrapSelection=function(t,e,r){var n=this.textarea,o=n.scrollTop,a=t.text;return t=this.replaceSelection(t,e+a+r),""==a&&(t=this.setSelection(t.start+e.length,t.start+e.length)),n.scrollTop=o,t};
<


Modified src/www/admin/static/scripts/wiki-encryption.js from [2f0eae2745] to [0a4baa4a5c].

1
2
3


4
5

6







7
8
9
10



11
12
13
14




15






16
17
18
19
20
21
22
(function () {
	var aesEnabled = false;
	var iteration = 0;


	var encryptPassword = null;
	var www_url = location.href.replace(/admin\/.*$/, 'admin/');









	function loadAESlib()
	{
		if (aesEnabled)
		{



			return;
		}

		g.script('scripts/gibberish-aes.min.js');




		aesEnabled = true;






	}

	function formatContent(content)
	{
		// htmlspecialchars ENT_QUOTES
		content = content.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
			.replace(/'/g, '&#039;').replace(/"/g, '&quot');

|

>
>

|
>

>
>
>
>
>
>
>
|

|
<
>
>
>



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







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
(function () {
	var aes_loaded = false;
	var iteration = 0;
	var self_path_match = /static\/scripts\/wiki-encryption\.js/;
	var www_url;
	var encryptPassword = null;

	var scripts = document.getElementsByTagName('script');

	for (var i = 0; i < scripts.length; i++) {
		if (scripts[i].src.match(self_path_match)) {
			www_url = scripts[i].src.replace(/\/admin\/.*$/, '/');
			break;
		}
	}

	function load_aes(callback)
	{
		if (aes_loaded) {

			if (callback) {
				callback();
			}
			return;
		}

		var url = www_url + 'admin/static/scripts/gibberish-aes.min.js';
		var s = document.createElement('script');
		s.src = url;
		s.type = 'text/javascript';
		s.onload = function () {
			aes_loaded = true;
			if (callback) {
				callback();
			}
		};

		document.head.appendChild(s);
	}

	function formatContent(content)
	{
		// htmlspecialchars ENT_QUOTES
		content = content.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
			.replace(/'/g, '&#039;').replace(/"/g, '&quot');
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
		content = content.replace(/\r/g, '').replace(/\n/g, '<br />');

		return content;
	}

	window.wikiDecrypt = function ()
	{
		loadAESlib();

		encryptPassword = window.prompt('Mot de passe ?');

		if (!encryptPassword)
		{
			encryptPassword = null;

			if (document.getElementById('f_contenu'))
			{
				if (window.confirm("Aucun mot de passe entré.\nDésactiver le chiffrement et effacer le contenu ?"))
				{
					document.getElementById('f_contenu').value = '';
					document.getElementById('f_chiffrement').checked = false;
					checkEncryption(document.getElementById('f_chiffrement'));
				}
				else
				{
					wikiDecrypt();
				}
			}








|







|



|
|
|







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
		content = content.replace(/\r/g, '').replace(/\n/g, '<br />');

		return content;
	}

	window.wikiDecrypt = function ()
	{
		load_aes();

		encryptPassword = window.prompt('Mot de passe ?');

		if (!encryptPassword)
		{
			encryptPassword = null;

			if (document.getElementById('f_content'))
			{
				if (window.confirm("Aucun mot de passe entré.\nDésactiver le chiffrement et effacer le contenu ?"))
				{
					document.getElementById('f_content').value = '';
					document.getElementById('f_encryption').checked = false;
					checkEncryption(document.getElementById('f_encryption'));
				}
				else
				{
					wikiDecrypt();
				}
			}

108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
			}

			iteration++;
			window.setTimeout(decrypt, 500);
			return;
		}

		var content = document.getElementById('f_contenu');
		var edit = true;

		if (!content) {
		 	content = document.getElementById('wikiEncryptedContent');
		 	edit = false;
		}








|







130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
			}

			iteration++;
			window.setTimeout(decrypt, 500);
			return;
		}

		var content = document.getElementById('f_content');
		var edit = true;

		if (!content) {
		 	content = document.getElementById('wikiEncryptedContent');
		 	edit = false;
		}

144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
			content.style.display = 'block';
			document.getElementById('wikiEncryptedMessage').style.display = 'none';
			content.innerHTML = formatContent(wikiContent);
		}
		else
		{
			content.value = wikiContent;
			checkEncryption(document.getElementById('f_chiffrement'));
		}
	};

	window.checkEncryption = function(elm)
	{
		String.prototype.repeat = function(num)
		{







|







166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
			content.style.display = 'block';
			document.getElementById('wikiEncryptedMessage').style.display = 'none';
			content.innerHTML = formatContent(wikiContent);
		}
		else
		{
			content.value = wikiContent;
			checkEncryption(document.getElementById('f_encryption'));
		}
	};

	window.checkEncryption = function(elm)
	{
		String.prototype.repeat = function(num)
		{
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
			if (!encryptPassword)
			{
				elm.checked = false;
				encryptPassword = null;
				return;
			}

			loadAESlib();

			var hidden = true;
			var d = document.getElementById('encryptPasswordDisplay');
			d.innerHTML = '&bull;'.repeat(encryptPassword.length);
			d.title = 'Cliquer pour voir le mot de passe';
			d.onclick = function () {
				if (hidden)
				{
					this.innerHTML = encryptPassword;
					this.title = 'Cliquer pour cacher le mot de passe.';
				}
				else
				{
					this.innerHTML = '&bull;'.repeat(encryptPassword.length);
					this.title = 'Cliquer pour voir le mot de passe';
				}
				hidden = !hidden;
			};

			document.getElementById('f_form').onsubmit = function ()
			{
				if (typeof GibberishAES == 'undefined')
				{
					alert("Le chargement de la bibliothèque AES n'est pas terminé.\nLe chiffrement est impossible pour le moment, recommencez dans quelques instants ou désactivez le chiffrement.");
					return false;
				}

				var content = document.getElementById('f_contenu');
				content.value = GibberishAES.enc(content.value, encryptPassword);
				content.readOnly = true;
				return true;
			};

		}
		else
		{
			encryptPassword = null;
			var d = document.getElementById('encryptPasswordDisplay');
			d.innerHTML = 'désactivé';
			d.title = 'Chiffrement désactivé';
			d.onclick = null;
			document.getElementById('f_form').onsubmit = null;
		}
	};






} ());







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

|
|
|
|
|
|
|

|
|
|
|
|
>








|


>
>
>
>
>
>

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
			if (!encryptPassword)
			{
				elm.checked = false;
				encryptPassword = null;
				return;
			}


			load_aes(function () {
				var hidden = true;
				var d = document.getElementById('encryptPasswordDisplay');
				d.innerHTML = '&bull;'.repeat(encryptPassword.length);
				d.title = 'Cliquer pour voir le mot de passe';
				d.onclick = function () {
					if (hidden)
					{
						this.innerHTML = encryptPassword;
						this.title = 'Cliquer pour cacher le mot de passe.';
					}
					else
					{
						this.innerHTML = '&bull;'.repeat(encryptPassword.length);
						this.title = 'Cliquer pour voir le mot de passe';
					}
					hidden = !hidden;
				};

				elm.form.onsubmit = function ()
				{
					if (typeof GibberishAES == 'undefined')
					{
						alert("Le chargement de la bibliothèque AES n'est pas terminé.\nLe chiffrement est impossible pour le moment, recommencez dans quelques instants ou désactivez le chiffrement.");
						return false;
					}

					var content = document.getElementById('f_content');
					content.value = GibberishAES.enc(content.value, encryptPassword);
					content.readOnly = true;
					return true;
				};
			});
		}
		else
		{
			encryptPassword = null;
			var d = document.getElementById('encryptPasswordDisplay');
			d.innerHTML = 'désactivé';
			d.title = 'Chiffrement désactivé';
			d.onclick = null;
			elm.form.onsubmit = null;
		}
	};

	document.addEventListener('DOMContentLoaded', () => {
		if (e = document.getElementById('f_encryption')) {
			checkEncryption(e);
		}
	});
} ());

Modified src/www/admin/static/scripts/wiki_editor.css from [30c3c98262] to [531ffd0eea].

54
55
56
57
58
59
60






61
62
63
64
65
66
67
    line-height: 5px;
    overflow: hidden;
}

nav.te .file {
    margin-left: 2em;
}







nav.te .fullscreen {
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAADFBMVEUAAABMTFFOTlBOTlCQ1uMHAAAAA3RSTlMAOcKBmOr4AAAAQUlEQVQI12P4/4D7P8N/B0Yo8XsC23+GZw+4pzM4TmBzYsAGgBKODNcecM9m+D+B7T3DPwfG/Qz/G5iABlzg+g8ANzMax/3kkQoAAAAASUVORK5CYII=");
    float: right;
}

nav.te .preview {







>
>
>
>
>
>







54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
    line-height: 5px;
    overflow: hidden;
}

nav.te .file {
    margin-left: 2em;
}

nav.te .save {
    float: right;
    font-weight: bold;
    margin-right: 2em;
}

nav.te .fullscreen {
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAADFBMVEUAAABMTFFOTlBOTlCQ1uMHAAAAA3RSTlMAOcKBmOr4AAAAQUlEQVQI12P4/4D7P8N/B0Yo8XsC23+GZw+4pzM4TmBzYsAGgBKODNcecM9m+D+B7T3DPwfG/Qz/G5iABlzg+g8ANzMax/3kkQoAAAAASUVORK5CYII=");
    float: right;
}

nav.te .preview {
122
123
124
125
126
127
128































































































.textEditor iframe.hidden {
    visibility: hidden;
    width: 0px;
    height: 0px;
    position: absolute;
    top: -1000px;
}






































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
.textEditor iframe.hidden {
    visibility: hidden;
    width: 0px;
    height: 0px;
    position: absolute;
    top: -1000px;
}


form .fileUpload .uploadHelper_progress {
    position: absolute;
    bottom: 1em;
    left: 1em;
    right: 1em;
    text-align: center;
    padding: 1em;
    background: #ddd;
    box-shadow: 0px 0px 5px #999;
    border-radius: .5em;
}

form .fileUpload progress {
    width: 50%;
}

form#insertImage {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 10000;
    background: rgb(0, 0, 0);
    background: rgba(0, 0, 0, 0.75);
}

form#insertImage fieldset {
    box-shadow: 5px 5px 10px #000;
    margin: 1em;
    padding: 1em;
    background: #ddd;
    border-radius: .5em;
    text-align: center;
}

form#insertImage dt {
    margin: .2em 0;
}

form#insertImage .align input {
    font-size: 1.2em;
    line-height: 32px;
    background: #fff;
    background-position: 5px center;
    background-repeat: no-repeat;
    padding: 5px;
    padding-left: 42px;
    border: 1px solid #999;
    border-radius: 5px;
    margin: .5em;
}

form#insertImage .align input[name=""] {
    background-image: url("../pics/img_flow.png");
}

form#insertImage .align input[name="left"] {
    background-image: url("../pics/img_left.png");
}

form#insertImage .align input[name="right"] {
    background-image: url("../pics/img_right.png");
}

form#insertImage .align input[name="center"] {
    background-image: url("../pics/img_center.png");
}

form#insertImage .cancel input {
    font-size: 0.8em;
    background: transparent;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin: .5em;
    color: #666;
    cursor: pointer;
}

form#insertImage .align input:hover, form#insertImage .cancel input:hover  {
    cursor: pointer;
    background-color: #eee;
    color: darkred;
}

#confirm_saved {
    position: absolute;
    top: .5em;
    right: 10em;
    text-align: center;
    transition: all .5s, opacity 2s;
}

Modified src/www/admin/static/scripts/wiki_editor.js from [2d8c9cc5c3] to [1882f41586].

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
(function () {

	var wiki_id = window.location.search.match(/id=(\d+)/)[1];








	g.onload(function () {



		g.style('scripts/wiki_editor.css');









		g.script('scripts/text_editor.min.js', function () {
			var t = new textEditor('f_contenu');
			t.parent = t.textarea.parentNode;



























			var toolbar = document.createElement('nav');
			toolbar.className = 'te';

			var toggleFullscreen = function (e)
			{
				var classes = t.parent.className.split(' ');

				for (var i = 0; i < classes.length; i++)
				{
					if (classes[i] == 'fullscreen')
					{
						classes.splice(i, 1);
						t.parent.className = classes.join(' ');
						t.fullscreen = false;
						return true;
					}
				}


				
				classes.push('fullscreen');
				t.parent.className = classes.join(' ');
				t.fullscreen = true;
				return true;
			};

			var openPreview = function ()
			{
				openIFrame('');
				var form = document.createElement('form');
				form.appendChild(t.textarea.cloneNode(true));
				form.firstChild.value = t.textarea.value;
				form.target = 'editorFrame';
				form.action = g.admin_url + 'wiki/_preview.php?id=' + wiki_id;
				form.style.display = 'none';
				form.method = 'post';
				document.body.appendChild(form);
				form.submit();
				//document.body.removeChild(form);
			};

			var openSyntaxHelp = function ()
			{
				openIFrame(g.admin_url + 'wiki/_syntaxe.html');

			};

			var openFileInsert = function ()
			{


				openIFrame(g.admin_url + 'wiki/_fichiers.php?page=' + wiki_id);

			};

			window.te_insertFile = function (file)
			{
				var tag = '<<fichier|'+file+'>>';
				
				t.insertAtPosition(t.getSelection().start, tag);
				
				closeIFrame();
			};

			window.te_insertImage = function (file, position, caption)
			{
				var tag = '<<image|' + file;

				if (position)
					tag += '|' + position;

				if (caption)
					tag += '|' + caption;
				
				tag += '>>';
				
				t.insertAtPosition(t.getSelection().start, tag);
				





				closeIFrame();



			};

			var openIFrame = function(url)
			{
				if (t.iframe && t.iframe.src == t.base_url + url)
				{
					t.iframe.className = '';
					t.parent.className += ' iframe';
					return true;
				}
				else if (t.iframe)
				{
					t.parent.removeChild(t.iframe);
					t.iframe = null;
				}

				var w = t.textarea.offsetWidth,
					h = t.textarea.offsetHeight;

				var iframe = document.createElement('iframe');
				iframe.width = w;
				iframe.height = h;
				iframe.src = url;
				iframe.name = 'editorFrame';
				iframe.frameborder = '0';
				iframe.scrolling = 'yes';

				t.parent.appendChild(iframe);
				t.parent.className += ' iframe';
				t.iframe = iframe;


			};

			var closeIFrame = function ()
			{





				t.parent.className = t.parent.className.replace(/ iframe$/, '');
				t.iframe.className = 'hidden';
			};


			var appendButton = function (name, title, action, altTitle)
			{
				var btn = document.createElement('button');
				btn.type = 'button';
				btn.title = altTitle ? altTitle : title;
				if (title.length == 1) {
					btn.dataset.icon = title;
				}
				else {
					btn.innerText = title;
				}
				btn.className = 'icn-btn ' +name;
				btn.onclick = function () { action.call(); return false; };

				toolbar.appendChild(btn);
				return btn;
			};

			var wrapTags = function (left, right)
			{
				t.wrapSelection(t.getSelection(), left, right);
				return true;
			};





























			appendButton('title', "== Titre", function () { wrapTags("== ", ""); } );
			appendButton('bold', '**gras**', function () { wrapTags('**', '**'); } );
			appendButton('italic', "''italique''", function () { wrapTags("''", "''"); } );
			appendButton('link', "[[lien|http://]]", function () { 


				if (url = window.prompt('Adresse URL ?')) 
					wrapTags("[[", "|" + url + ']]'); 
			} );

			appendButton('file', "📎", openFileInsert, 'Insérer fichier / image');


			appendButton('ext preview', '⎙', openPreview, 'Prévisualiser');

			appendButton('ext help', '❓', openSyntaxHelp, 'Aide sur la syntaxe');

			appendButton('ext fullscreen', 'Plein écran', toggleFullscreen, 'Plein écran');









			appendButton('ext close', 'Fermer', closeIFrame);
			
			t.parent.insertBefore(toolbar, t.parent.firstChild);

			t.shortcuts.push({key: 'F11', callback: toggleFullscreen});
			t.shortcuts.push({ctrl: true, key: 'b', callback: function () { return wrapTags('**', '**'); } });
			t.shortcuts.push({ctrl: true, key: 'g', callback: function () { return wrapTags('**', '**'); } });
			t.shortcuts.push({ctrl: true, key: 'i', callback: function () { return wrapTags("''", "''"); } });

			if (window.location.hash.match(/fullscreen/))
			{
				t.toggleFullscreen();
				window.location.hash = '';
			}
		});
	});
}());

>
|
>
>
>
>
>
>

>
|
>
>
>
|
>
>
>

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

|
|

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

|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
>
|

|
|
>
>
|
>
|

|
|
|
|
|
|
|
|

|
|
|

|
|

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

>
>
>
|

|
|
|
|
|
|
|
|
|
|
|
|
|

|
|

|
|
|
|
|
|
|

|
|
|
>
>
|

|
|
>
>
>
>
>
|
|
|


|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|

|
|
|
|
|

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

<
>

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

|
|
|
|
|
|
|
|
<
<
|


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
(function () {
	g.style('scripts/wiki_editor.css');

	function showSaved() {
		let c = document.createElement('p');
		c.className = 'block confirm';
		c.id = 'confirm_saved';
		c.innerText = 'Enregistré';
		c.style.right = '-10em';

		document.querySelector('#f_content').parentNode.appendChild(c);

		window.setTimeout(() => {
			c.style.right = '';
		}, 200);

		window.setTimeout(() => {
			c.style.opacity = 0;
		}, 3000);

		window.setTimeout(() => {
			c.remove();
		}, 5000);
	}

	g.script('scripts/lib/text_editor.min.js', function () {
		var t = new textEditor('f_content');
		t.parent = t.textarea.parentNode;

		var config = {
			fullscreen: t.textarea.getAttribute('data-fullscreen') == 1,
			attachments: t.textarea.getAttribute('data-attachments') == 1,
			savebtn: t.textarea.getAttribute('data-savebtn'),
			preview_url: t.textarea.getAttribute('data-preview-url')
		};

		// Cancel Escape to close.value
		if (window.parent && window.parent.g.dialog) {
			// Always fullscreen in dialogs
			config.fullscreen = true;

			window.parent.g.dialog.preventClose = () => {
				if (t.textarea.value == t.textarea.defaultValue) {
					return false;
				}

				if (window.confirm('Sauvegarder avant de fermer ?')) {
					save();
					return false;
				}

				return true;
			};
		}

		var toolbar = document.createElement('nav');
		toolbar.className = 'te';

		var toggleFullscreen = function (e)
		{




			t.parent.classList.toggle('fullscreen');



			t.fullscreen = true;
			return true;
		};

		if (config.fullscreen) {
			toggleFullscreen();
		}






		var openPreview = function ()
		{
			openIFrame('');
			var form = document.createElement('form');
			form.appendChild(t.textarea.cloneNode(true));
			form.firstChild.value = t.textarea.value;
			form.target = 'editorFrame';
			form.action = config.preview_url;
			form.style.display = 'none';
			form.method = 'post';
			document.body.appendChild(form);
			form.submit();
			return true;
		};

		var openSyntaxHelp = function ()
		{
			openIFrame(g.admin_url + 'web/_syntaxe.html');
			return true;
		};

		var openFileInsert = function ()
		{
			let args = new URLSearchParams(window.location.search);
			var wiki_id = args.get('p');
			g.openFrameDialog(g.admin_url + 'web/_attach.php?_dialog&p=' + wiki_id);
			return true;
		};

		window.te_insertFile = function (file)
		{
			var tag = '<<file|'+file+'>>';

			t.insertAtPosition(t.getSelection().start, tag);

			g.closeDialog();
		};

		window.te_insertImage = function (file, position, caption)
		{
			var tag = '<<image|' + file;

			if (position)
				tag += '|' + position;

			if (caption)
				tag += '|' + caption;

			tag += '>>';

			t.insertAtPosition(t.getSelection().start, tag);

			g.closeDialog();
		};

		var EscapeEvent = function (e) {
			if (e.key == 'Escape') {
				closeIFrame();
				e.preventDefault();
				return false;
			}
		};

		var openIFrame = function(url)
		{
			if (t.iframe && t.iframe.src == t.base_url + url)
			{
				t.iframe.className = '';
				t.parent.className += ' iframe';
				return true;
			}
			else if (t.iframe)
			{
				t.parent.removeChild(t.iframe);
				t.iframe = null;
			}

			var w = t.textarea.offsetWidth,
				h = t.textarea.offsetHeight;

			var iframe = document.createElement('iframe');
			iframe.width = w;
			iframe.height = h;
			iframe.src = url;
			iframe.name = 'editorFrame';
			iframe.frameborder = '0';
			iframe.scrolling = 'yes';

			t.parent.appendChild(iframe);
			t.parent.className += ' iframe';
			t.iframe = iframe;

			document.addEventListener('keydown', EscapeEvent);
		};

		var closeIFrame = function ()
		{
			document.removeEventListener('keydown', EscapeEvent);

			if (!t.iframe) {
				return true;
			}
			t.parent.className = t.parent.className.replace(/ iframe$/, '');
			t.iframe.className = 'hidden';
		};


		var appendButton = function (name, title, action, altTitle)
		{
			var btn = document.createElement('button');
			btn.type = 'button';
			btn.title = altTitle ? altTitle : title;
			if (title.length == 1) {
				btn.dataset.icon = title;
			}
			else {
				btn.innerText = title;
			}
			btn.className = 'icn-btn ' +name;
			btn.onclick = function () { action.call(); return false; };

			toolbar.appendChild(btn);
			return btn;
		};

		var wrapTags = function (left, right)
		{
			t.wrapSelection(t.getSelection(), left, right);
			return true;
		};

		let insertURL = function () {
			if (url = window.prompt('Adresse URL ?'))
				wrapTags("[[", "|" + url + ']]');
			return true;
		};

		let save = function () {
			const data = new URLSearchParams();

			for (const pair of new FormData(t.textarea.form)) {
				data.append(pair[0], pair[1]);
			}

			data.append('save', 1);

			fetch(t.textarea.form.action + '&js', {
				method: 'post',
				body: data,
			}).then((response) => {
				if (!response.ok) {
					throw response;
				}
				showSaved();
				t.textarea.defaultValue = t.textarea.value;
			}).catch(e => t.textarea.form.querySelector('[type=submit]').click() );
			return true;
		};

		appendButton('title', "== Titre", function () { wrapTags("== ", ""); } );
		appendButton('bold', '**gras**', function () { wrapTags('**', '**'); } );
		appendButton('italic', "''italique''", function () { wrapTags("''", "''"); } );
		appendButton('link', "[[lien|http://]]", insertURL);
		appendButton('ext preview', '👁', openPreview, 'Prévisualiser');
		appendButton('ext help', '❓', openSyntaxHelp, 'Aide sur la syntaxe');



		if (config.attachments) {
			appendButton('file', "📎 Fichiers", openFileInsert, 'Insérer fichier / image');
			t.shortcuts.push({ctrl: true, shift: true, key: 'i', callback: openFileInsert});
		}



		if (!config.fullscreen) {
			appendButton('ext fullscreen', 'Plein écran', toggleFullscreen, 'Plein écran');
		}

		if (config.savebtn == 1) {
			appendButton('ext save', 'Enregistrer', save, 'Enregistrer');
		}
		else if (config.savebtn == 2) {
			appendButton('ext save', '⇑', save, 'Enregistrer sans fermer');
		}

		appendButton('ext close', 'Fermer', closeIFrame);

		t.parent.insertBefore(toolbar, t.parent.firstChild);

		t.shortcuts.push({key: 'F11', callback: toggleFullscreen});
		t.shortcuts.push({ctrl: true, key: 'b', callback: function () { return wrapTags('**', '**'); } });
		t.shortcuts.push({ctrl: true, key: 'g', callback: function () { return wrapTags('**', '**'); } });
		t.shortcuts.push({ctrl: true, key: 'i', callback: function () { return wrapTags("''", "''"); } });
		t.shortcuts.push({ctrl: true, key: 't', callback: function () { return wrapTags("\n== ", "\n"); } });
		t.shortcuts.push({ctrl: true, key: 'l', callback: insertURL});
		t.shortcuts.push({ctrl: true, key: 's', callback: save});
		t.shortcuts.push({ctrl: true, shift: true, key: 'p', callback: openPreview});


		t.shortcuts.push({key: 'F1', callback: openSyntaxHelp});
	});
}());

Modified src/www/admin/static/scripts/wiki_fichiers.js from [0dc8ddc2bb] to [1bc10af361].

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
(function () {
    g.onload(function () {
        uploadHelper($('#f_fichier'), {
            width: 1920,
            height: null,
            resize: true,
            bytes: 'o',
            size_error_msg: 'Le fichier %file fait %size, soit plus que la taille maximale autorisée de %max_size.'
        });

        function insertImageHelper(file, from_upload) {
            if (!document.querySelectorAll)
            {
                window.parent.te_insertImage(file.id, 'centre');
                return true;
            }

            var f = document.getElementById('insertImage');
            f.style.display = 'block';

            var inputs = f.querySelectorAll('input[type=button]');

            for (var i = 0; i < inputs.length; i++)
            {
                inputs[i].onclick = function(e) {
                    window.parent.te_insertImage(file.id, e.target.name, f.f_caption.value);
                };
            }

            f.querySelector('dd.image').innerHTML = '';
            var img = document.createElement('img');
            img.src = file.thumb;
            img.alt = '';


|










|











|







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
(function () {
    g.onload(function () {
        uploadHelper($('#f_file'), {
            width: 1920,
            height: null,
            resize: true,
            bytes: 'o',
            size_error_msg: 'Le fichier %file fait %size, soit plus que la taille maximale autorisée de %max_size.'
        });

        function insertImageHelper(file, from_upload) {
            if (!document.querySelectorAll)
            {
                window.parent.te_insertImage(file.name, 'center');
                return true;
            }

            var f = document.getElementById('insertImage');
            f.style.display = 'block';

            var inputs = f.querySelectorAll('input[type=button]');

            for (var i = 0; i < inputs.length; i++)
            {
                inputs[i].onclick = function(e) {
                    window.parent.te_insertImage(file.name, e.target.name, f.f_caption.value);
                };
            }

            f.querySelector('dd.image').innerHTML = '';
            var img = document.createElement('img');
            img.src = file.thumb;
            img.alt = '';
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

            if (file.image)
            {
                insertImageHelper(file, true);
            }
            else
            {
                window.parent.te_insertFile(data.file.id);
            }

            return true;
        }

        var gallery = document.getElementsByClassName('gallery');

        if (gallery.length == 1 && document.querySelector)
        {
            var items = gallery[0].getElementsByTagName('li');

            for (var i = 0; i < items.length; i++)
            {
                var a = items[i].querySelector('figure > a');
                a.onclick= function (e) {
                    insertImageHelper({
                        id: this.getAttribute('data-id'),

                        thumb: this.firstChild.src
                    });
                    return false;
                };
            }
        }

        var a = document.createElement('button');
        a.className = 'icn-btn';
        a.innerText = 'Supprimer';
        a.dataset.icon = '✘';
        a.type = 'button';
        a.onclick = function() { if (confirm('Supprimer ce fichier ?')) this.parentNode.submit(); };







|





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







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

            if (file.image)
            {
                insertImageHelper(file, true);
            }
            else
            {
                window.parent.te_insertFile(file.name);
            }

            return true;
        }



        document.querySelectorAll('a[data-insert]').forEach((a) => {






            a.onclick = function (e) {
               insertHelper({
                    name: this.dataset.name,
                    image: this.dataset.insert == 'image',
                    thumb: this.dataset.thumb
                });
                return false;
            };
        });


        var a = document.createElement('button');
        a.className = 'icn-btn';
        a.innerText = 'Supprimer';
        a.dataset.icon = '✘';
        a.type = 'button';
        a.onclick = function() { if (confirm('Supprimer ce fichier ?')) this.parentNode.submit(); };

Modified src/www/admin/static/scripts/wiki_gallery.js from [4fb5f1eccd] to [b3da297b33].

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
(function () {

    var enableGallery = function () {

        if (!document.querySelectorAll)

        {

            return false;
        }

        var items = document.querySelectorAll('a.internal-image');

        for (var i = 0; i < items.length; i++)
        {
            var a = items[i];
            a.setAttribute('data-pos', i);
            a.onclick= function (e) {
                e.preventDefault();
                openImageBrowser(items, this.getAttribute('data-pos'));
                return false;
            };
        }
    };

    if (document.addEventListener)
        document.addEventListener('DOMContentLoaded', enableGallery, false);
    else
        document.attachEvent('onDOMContentLoaded', callback);

    function openImageBrowser(items, pos)
    {
        var div = document.createElement('div');
        div.className = 'imageBrowser';

        var img = document.createElement('img');
        img.pos = pos-1;

        img.onclick = function (e) {
            e.stopPropagation();
            openImage(img, items);
        };

        var fig = document.createElement('figure');
        fig.style.opacity = 0;

        div.onclick = function (e) {
            div.style.opacity = 0;
            window.setTimeout(function() { div.parentNode.removeChild(div); }, 500);
        };

















        fig.appendChild(img);
        div.appendChild(fig);
        document.body.appendChild(div);

        openImage(img, items);
    }

    function openImage(img, items)
    {
        // Pour animation

        img.parentNode.style.opacity = 0;




        if (++img.pos == items.length)
        {
            var div = img.parentNode.parentNode;
            div.style.opacity = 0;
            window.setTimeout(function() { div.parentNode.removeChild(div); }, 500);
            return;
        }

        var newImg = new Image;
        newImg.onload = function (e) {
            var new_src = e.target.src;
            window.setTimeout(function() {
                img.src = new_src;
                img.parentNode.style.opacity = 1;
            }, img.src ? 250 : 0);
        };

        newImg.src = items[img.pos].href;
        return false;   
    }

}());

>
|
>
|
>
|
>









|







<
<
<
<
<


|


<
<
<
<
<
<
<
<

<





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





|





>
|

>
>
>
|







|
|
<
<
|
<
<
<
|
<
<



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
(function () {
    var div, fig;

    document.addEventListener('DOMContentLoaded', enableGallery, false);

    function enableGallery()
    {
        if (!document.querySelectorAll) {
            return false;
        }

        var items = document.querySelectorAll('a.internal-image');

        for (var i = 0; i < items.length; i++)
        {
            var a = items[i];
            a.setAttribute('data-pos', i);
            a.onclick = function (e) {
                e.preventDefault();
                openImageBrowser(items, this.getAttribute('data-pos'));
                return false;
            };
        }
    };






    function openImageBrowser(items, pos)
    {
        div = document.createElement('div');
        div.className = 'imageBrowser';









        var fig = document.createElement('figure');


        div.onclick = function (e) {
            div.style.opacity = 0;
            window.setTimeout(function() { div.parentNode.removeChild(div); }, 500);
        };

        var img = document.createElement('img');
        img.title = 'Cliquer sur l\'image pour aller à la suivante, ou à côté pour fermer';
        img.pos = pos || 0;

        img.onload = function () {
            fig.style.opacity = 1;
            img.style.width = 'initial';
            img.style.height = 'initial';
        };

        img.onclick = function (e) {
            e.stopPropagation();
            img.pos++;
            openImage(img, items);
        };

        fig.appendChild(img);
        div.appendChild(fig);
        document.body.appendChild(div);

        openImage(img, items, div);
    }

    function openImage(img, items)
    {
        // Pour animation
        var fig = img.parentNode;
        fig.style.opacity = 0;

        console.log(img);
        var pos = img.pos;

        if (pos >= items.length)
        {
            var div = img.parentNode.parentNode;
            div.style.opacity = 0;
            window.setTimeout(function() { div.parentNode.removeChild(div); }, 500);
            return;
        }

        img.style.width = 0;
        img.style.height = 0;


        img.src = items[pos].href;



        img.pos = pos;


    }

}());

Modified src/www/admin/static/styles/01-layout.css from [91d3f8d7aa] to [00233b0391].

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    margin-left: 180px;
    margin-bottom: 0.4em;
}

.header .menu {
    position: fixed;
    overflow: auto;
    z-index: 10000;
    width: 170px;
    top: 0;
    bottom: 0;
    padding-top: 100px;
    background: rgb(var(--gMainColor)) var(--gBgImage) no-repeat 0px 0px;
}








|







39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    margin-left: 180px;
    margin-bottom: 0.4em;
}

.header .menu {
    position: fixed;
    overflow: auto;
    z-index: 1000;
    width: 170px;
    top: 0;
    bottom: 0;
    padding-top: 100px;
    background: rgb(var(--gMainColor)) var(--gBgImage) no-repeat 0px 0px;
}

Modified src/www/admin/static/styles/02-common.css from [8cf9202305] to [96523462ef].

78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    color: #666;
}

.help {
    color: #666;
}

p.help {
    margin: 1em;
}

.help ul li {
    list-style-type: disc;
    margin: .5em;
    margin-left: 2em;







|







78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    color: #666;
}

.help {
    color: #666;
}

p.help:not(.block) {
    margin: 1em;
}

.help ul li {
    list-style-type: disc;
    margin: .5em;
    margin-left: 2em;
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
}

.error ul, .alert ul, .confirm ul {
    margin-left: 1.5em;
    list-style: disc;
}

h2.ruler {
    margin: .5em;
    text-align: center;
    color: #333;
    overflow: hidden;
}

h2.ruler:before, h2.ruler:after {
    background-color: #000;
    content: "";
    display: inline-block;
    height: 1px;
    position: relative;
    vertical-align: middle;
    width: 50%;
}

h2.ruler:before {
    right: 0.5em;
    margin-left: -50%;
}

h2.ruler:after {
    left: 0.5em;
    margin-right: -50%;
}

.num a, a.num {
    text-decoration: none;
    border-radius: .5rem;
    display: inline-block;
    text-align: center;
    padding: 0 .3rem;
    background: rgba(var(--gMainColor), 0.7);
    color: #fff;
    white-space: pre;
}

.droits b {
    border: 2px solid #999;
    border-radius: 1em;
    color: #000;
    background: #ccc;
    width: 16px;
    display: inline-block;
    text-align: center;
    font-size: 0.8em;
    cursor: help;
    vertical-align: middle;
    position: relative;
    z-index: 10;
    font-family: "gicon", "Trebuchet MS", Arial, Helvetica, sans-serif;
}

.droits b.aucun {
    border-color: #ccc;
    background: #eee;
    color: #999;
}

.droits b.acces {
    border-color: #cc9;
    color: #660;
    background: #ffe;
}

.droits b.ecriture {
    border-color: #9c9;
    color: #060;
    background: #efe;
}

.droits b.aucun:before {
    content: "X";
    position: absolute;
    left: 0;
    right: 0;
    top: -3px;
    color: #ccc;
    z-index: -1;
    font-size: 1.5em;
    overflow: hidden;
}

.droits b.admin {
    color: #900;
    border-color: #c99;
    background: #fee;
}

.infos {
    margin-bottom: 1em;







|






|









|




|















|















|





|





|





|











|







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
}

.error ul, .alert ul, .confirm ul {
    margin-left: 1.5em;
    list-style: disc;
}

.ruler {
    margin: .5em;
    text-align: center;
    color: #333;
    overflow: hidden;
}

.ruler:before, .ruler:after {
    background-color: #000;
    content: "";
    display: inline-block;
    height: 1px;
    position: relative;
    vertical-align: middle;
    width: 50%;
}

.ruler:before {
    right: 0.5em;
    margin-left: -50%;
}

.ruler:after {
    left: 0.5em;
    margin-right: -50%;
}

.num a, a.num {
    text-decoration: none;
    border-radius: .5rem;
    display: inline-block;
    text-align: center;
    padding: 0 .3rem;
    background: rgba(var(--gMainColor), 0.7);
    color: #fff;
    white-space: pre;
}

.permissions b {
    border: 2px solid #999;
    border-radius: 1em;
    color: #000;
    background: #ccc;
    width: 16px;
    display: inline-block;
    text-align: center;
    font-size: 0.8em;
    cursor: help;
    vertical-align: middle;
    position: relative;
    z-index: 10;
    font-family: "gicon", "Trebuchet MS", Arial, Helvetica, sans-serif;
}

.permissions b.access_0 {
    border-color: #ccc;
    background: #eee;
    color: #999;
}

.permissions b.access_1 {
    border-color: #cc9;
    color: #660;
    background: #ffe;
}

.permissions b.access_2 {
    border-color: #9c9;
    color: #060;
    background: #efe;
}

.permissions b.access_0:before {
    content: "X";
    position: absolute;
    left: 0;
    right: 0;
    top: -3px;
    color: #ccc;
    z-index: -1;
    font-size: 1.5em;
    overflow: hidden;
}

.permissions b.access_9 {
    color: #900;
    border-color: #c99;
    background: #fee;
}

.infos {
    margin-bottom: 1em;
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
}

dl.describe > dt {
    grid-column: 1;
    margin: .2rem .5rem;
    text-align: right;
    color: #666;
    align-self: center;
}

dl.describe > dd {
    grid-column: 2;
    margin: .2rem .5rem;
    align-self: center;
}







|







284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
}

dl.describe > dt {
    grid-column: 1;
    margin: .2rem .5rem;
    text-align: right;
    color: #666;
    align-self: start;
}

dl.describe > dd {
    grid-column: 2;
    margin: .2rem .5rem;
    align-self: center;
}
400
401
402
403
404
405
406

































































































    padding-right: 4em !important;
}

details summary.block::after {
    right: 0;
    left: inherit;
}








































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
    padding-right: 4em !important;
}

details summary.block::after {
    right: 0;
    left: inherit;
}
.files-list {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
}

.files-list aside.file {
    border-radius: .5rem;
    background: rgba(var(--gSecondColor), 0.1);
    text-align: center;
    padding: .5rem;
    margin: .5rem;
}

.files-list aside small {
    display: block;
    color: #666;
}

nav.breadcrumbs {
    margin: .5em 0;
    color: #999;
}

nav.breadcrumbs a {
    color: #333;
}

nav.breadcrumbs ul, nav.breadcrumbs li {
    list-style-type: none;
    display: inline;
}

nav.breadcrumbs li:before {
    content: "> ";
}

nav.breadcrumbs li:last-child a {
    font-weight: bold;
}

nav.breadcrumbs aside {
    float: right;
}

aside.quota {
    background: rgba(var(--gMainColor), 0.1);
    border-radius: .5rem;
    padding: .2rem .5rem;
    color: #000;
}

aside.quota i {
    font-style: normal;
}

aside.quota h4 {
    display: inline-block;
}

.meter {
    min-width: 20rem;
    height: 1rem;
    background: rgba(var(--gSecondColor), 0.5);
    border-radius: .2rem;
    display: inline-flex;
    padding: 0;
    vertical-align: middle;
    margin-left: 1rem;
}

.meter span {
    border-radius: .2rem;
    background: rgb(var(--gMainColor));
    display: inline-block;
    height: 1rem;
    vertical-align: middle;
}

.search-results article {
    margin: 2em 1em;
}

.search-results h4 a {
    font-weight: normal !important;
    font-size: .9em;
    color: #999;
}

.search-results h3 {
    margin: .3em 0;
}

.search-results h3 a {
    color: darkblue;
    font-weight: normal;
}

Modified src/www/admin/static/styles/03-forms.css from [211fa0b520] to [c5c1f73efc].

527
528
529
530
531
532
533





































534
535
536
537
538
539
540
#queryBuilder table .values label {
    margin: 0 .3em;
}

#queryBuilderForm input[type=number] {
    width: 4em;
}






































@media screen and (max-width: 1279px) {
    #queryBuilder table tr {
        display: flex;
        flex-wrap: wrap;
        padding: .5em 0;
        margin-left: 6rem;







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







527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
#queryBuilder table .values label {
    margin: 0 .3em;
}

#queryBuilderForm input[type=number] {
    width: 4em;
}

.tree-selector a {
    color: #666;
}

.tree-selector td {
    width: 15%;
    text-align: right;
}

.tree-selector th {
    width: 85%;
}

.tree-selector i {
    display: inline-block;
    padding: 0 .5em;
}

.tree-selector b {
    display: inline-block;
    padding: 0 .5em;
    color: #999;
}

.tree-selector em {
    font-weight: normal;
}

.tree-selector h3 {
    display: inline-block;
}

.tree-selector .current > a {
    font-weight: bold;
    color: #000;
}

@media screen and (max-width: 1279px) {
    #queryBuilder table tr {
        display: flex;
        flex-wrap: wrap;
        padding: .5em 0;
        margin-left: 6rem;

Modified src/www/admin/static/styles/04-dialogs.css from [9ade8c8089] to [58a19139b9].

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
body#popup {
    background-position: -170px 0px;
}

body#transparent {
    background: transparent;

}

body#popup main {


    margin: 1em 1em 1em 2.5em;
}

body#transparent main {
    margin: 0;
    padding: .2em;
}

/** Dialogs pop-ins */
#dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;

    background: rgba(0, 0, 0, 0.7);
    position: fixed;
    opacity: 1;
    transition: opacity .5s;
    z-index: 100000;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: none;
}





#dialog > iframe {
    width: 90%;


    height: 90%;

    border: none;


    box-shadow: 0px 0px 5px #000;








}

#dialog > button.closeBtn {
    background: unset;
    border: unset;
    box-shadow: unset;
    color: #fff;
|
|


|

>


|
>
>
|
<
|
<

<












>
|











>
>
>
>
|
|
>
>

>

>
>
|
>
>
>
>
>
>
>
>







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
body.transparent {
    background: none;
}

html.dialog body {
    background: transparent;
    overflow: auto;
}

html.dialog main {
    background: #fff;
    border-radius: .5em;
    padding: .5em;

    box-shadow: 0px 0px 5px #000;

    margin: 0;

}

/** Dialogs pop-ins */
#dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: transparent url("data:image/svg+xml;base64,PCEtLSBCeSBTYW0gSGVyYmVydCAoQHNoZXJiKSwgZm9yIGV2ZXJ5b25lLiBNb3JlIEAgaHR0cDovL2dvby5nbC83QUp6YkwgLS0+Cjxzdmcgd2lkdGg9IjM4IiBoZWlnaHQ9IjM4IiB2aWV3Qm94PSIwIDAgMzggMzgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgc3Ryb2tlPSIjZmZmIj4KICAgIDxnIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+CiAgICAgICAgPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMSAxKSIgc3Ryb2tlLXdpZHRoPSIyIj4KICAgICAgICAgICAgPGNpcmNsZSBzdHJva2Utb3BhY2l0eT0iLjUiIGN4PSIxOCIgY3k9IjE4IiByPSIxOCIvPgogICAgICAgICAgICA8cGF0aCBkPSJNMzYgMThjMC05Ljk0LTguMDYtMTgtMTgtMTgiPgogICAgICAgICAgICAgICAgPGFuaW1hdGVUcmFuc2Zvcm0gYXR0cmlidXRlTmFtZT0idHJhbnNmb3JtIiB0eXBlPSJyb3RhdGUiIGZyb209IjAgMTggMTgiIHRvPSIzNjAgMTggMTgiIGR1cj0iMXMiIHJlcGVhdENvdW50PSJpbmRlZmluaXRlIi8+CiAgICAgICAgICAgIDwvcGF0aD4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPg==") no-repeat center center;
    background-color: rgba(0, 0, 0, 0.7);
    position: fixed;
    opacity: 1;
    transition: opacity .5s;
    z-index: 100000;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: none;
}

#dialog.loaded {
    background-image: none;
}

#dialog > iframe, #dialog > img, #dialog > audio, #dialog > video {
    max-width: 90%;
    max-height: 90%;
    min-height: 3em;
    height: 90%;
    transition: opacity .2s, height .2s;
    border: none;
    opacity: 0;
}

#dialog.loaded > img, #dialog.loaded > audio, #dialog.loaded > video {
    opacity: 1;
    height: initial;
}

#dialog.loaded > iframe {
    width: 90%;
    opacity: 1;
}

#dialog > button.closeBtn {
    background: unset;
    border: unset;
    box-shadow: unset;
    color: #fff;

Modified src/www/admin/static/styles/10-accounting.css from [c404c68c91] to [d4efb6cfa3].

100
101
102
103
104
105
106

107

108





table.accounts th { font-weight: normal; }
table.accounts .account-level-1 th { font-size: 1.6em; }
table.accounts .account-level-2 th { padding-left: 1em; font-size: 1.3em; }
table.accounts .account-level-3 th { padding-left: 2em; }
table.accounts .account-level-4 th { padding-left: 3em; }
table.accounts .account-level-5 th { padding-left: 4em; }
table.accounts .account-level-6 th { padding-left: 5em; }



table.projects tr.title p.help { font-weight: normal; text-align: center; }












>

>
|
>
>
>
>
>
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
table.accounts th { font-weight: normal; }
table.accounts .account-level-1 th { font-size: 1.6em; }
table.accounts .account-level-2 th { padding-left: 1em; font-size: 1.3em; }
table.accounts .account-level-3 th { padding-left: 2em; }
table.accounts .account-level-4 th { padding-left: 3em; }
table.accounts .account-level-5 th { padding-left: 4em; }
table.accounts .account-level-6 th { padding-left: 5em; }
table.projects tr.title p.help { font-weight: normal; text-align: center; }

.attachments {
    text-align: center;
}

.attachments .files-list {
    justify-content: center;
}

Added src/www/admin/static/styles/wiki.css version [5b5f5a2486].





























































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
.web-edit {
    display: grid;
    grid-template-columns: 1fr 30%;
    grid-template-rows: .3fr .3fr .3fr;
    grid-gap: 2em;
}

fieldset.wikiText {
    grid-column: 1;
    grid-row: 1/3;
    border: none;
    padding: 0;
}

.web-edit input[type=text] {
    min-width: 0;
}

@media screen and (max-width: 980px) {
    .web-edit {
        display: block;
    }
}

#encryptPasswordDisplay {
    cursor: help;
    background: #ddd;
}

fieldset.wikiEncrypt, fieldset.wikiMain, .web-edit p.submit {
    grid-column: 2;
}

.web-edit dd.help {
    font-size: .9em;
}

fieldset.wikiMain #f_title {
    width: 90%;
    font-size: 14pt;
}

fieldset.wikiMain #f_uri {
    width: 90%;
}


.wikiFiles {
    text-align: center;
}

.wikiFooter, .wikiFiles {
    font-size: 0.8em;
    color: #666;
    border-top: 0.1em solid #ccc;
    clear: both;
}

.wikiMain samp {
    background: #eee;
    padding: 0.2em 0.3em;
}

.wikiChildren {
    margin: 1em 0 1em 1em;
    border: .1em solid #999;
    border-radius: .5em;
    padding: 1em;
    background: rgba(255, 255, 255, 0.5);
    float: right;
    clear: right;
    width: 25%;
}

.wikiChildren ul {
    color: #ccc;
    list-style-type: square;
    margin-left: 1em;
}

form#f_upload fieldset {
    position: relative;
}

.diff {
    margin: 1em;
}

.diff .ins {diff
    background: #cfc;
    width: 45%;
}

.diff .del {
    background: #fcc;
    width: 45%;
}

.diff .line {
    width: 2%;
    padding: 0.2em;
    text-align: right;
    font-family: Mono;
    font-size: 90%;
    color: #666;
}

.diff .leftChange, .diff .rightChange {
    text-align: center;
    vertical-align: middle;
}

.diff ins { background: #9f9; }
.diff del { background: #f99; }

.diff hr {
    background: none;
    border: none;
    border-top: 5px dotted #fff;
    color: #fff;
    margin: .2em .4em;
}

.diff .separator {
    background: #ccc;
}

.diff {
    border-collapse: collapse;
    width: 100%;
    font-size: 0.9em;
}

.diff tr {
    border: 1px solid #ccc;
    vertical-align: top;
}

.diff .leftChange b, .diff .rightChange b {
    text-shadow: 1px 1px 1px #ccc;
    color: #666;
}

Deleted src/www/admin/static/wiki.css version [c1552b949b].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
.wikiContent p, .wikiContent h3, .wikiContent h4, .wikiContent h5, .wikiContent h6,
.wikiContent ul, .wikiContent ol, .wikiContent table, .wikiContent blockquote {
    margin-bottom: 8pt;
}

.wikiContent ul, .wikiContent ol, .wikiContent dd {
    margin-left: 2em;
}

.wikiContent ul {
    list-style-type: disc;
}

.wikiContent ol {
    list-style-type: decimal;
}

aside.fichier {
    margin: 1em;
}

aside.fichier small {
    opacity: 0.7;
}

aside.fichier a {
    display: inline-block;
    margin-right: 1em;
    padding: .5em;
    padding-left: 1.8em;
    border: 1px solid #999;
    background: #eee;
    border-radius: .5em;
    background-repeat: no-repeat;
    background-position: .5em center;
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAAQCAYAAADAvYV+AAAAd0lEQVQoz2NgQAVNQDwDCTcw4AF3gPg/Er4xSBWnAXEHFL9HU/wWSS4FpFgZiJ+jKULHT4BYAWa6LhC/w6HwNRBrojvHEoi/oCn8BMQmuDzoBsQ/oQq/A7E9AwEQDMQ/gNiHgUggx0AN8IVI/AGkeA+ReCdJTgAAgMhKhf6mzTIAAAAASUVORK5CYII=");
    transition: background-color .2s, color .2s;
}

aside.fichier a:hover {
    background-color: #ccc;
    color: darkred;
}

.wikiContent figure.image {
    text-align: center;
}

.wikiContent figure.image figcaption {
    font-style: italic;
    color: #666;
    margin-top: 2pt;
}

.wikiContent figure.image.centre {
    max-width: 500px;
    margin: 0 auto 8pt auto;
}

.wikiContent figure.image.gauche {
    max-width: 200px;
    float: left;
    margin: 0 8pt 4pt 0;
    clear: left;
}

.wikiContent figure.image.droite {
    max-width: 200px;
    float: right;
    margin: 0 0 4pt 8pt;
    clear: right;
}

.wikiContent figure.image.gauche figcaption, .wikiContent figure.image.droite figcaption {
    font-size: .8em;
}

.imageBrowser {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    background: url("data:image/svg+xml;base64,PCEtLSBCeSBTYW0gSGVyYmVydCAoQHNoZXJiKSwgZm9yIGV2ZXJ5b25lLiBNb3JlIEAgaHR0cDovL2dvby5nbC83QUp6YkwgLS0+Cjxzdmcgd2lkdGg9IjM4IiBoZWlnaHQ9IjM4IiB2aWV3Qm94PSIwIDAgMzggMzgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgc3Ryb2tlPSIjZmZmIj4KICAgIDxnIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+CiAgICAgICAgPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMSAxKSIgc3Ryb2tlLXdpZHRoPSIyIj4KICAgICAgICAgICAgPGNpcmNsZSBzdHJva2Utb3BhY2l0eT0iLjUiIGN4PSIxOCIgY3k9IjE4IiByPSIxOCIvPgogICAgICAgICAgICA8cGF0aCBkPSJNMzYgMThjMC05Ljk0LTguMDYtMTgtMTgtMTgiPgogICAgICAgICAgICAgICAgPGFuaW1hdGVUcmFuc2Zvcm0gYXR0cmlidXRlTmFtZT0idHJhbnNmb3JtIiB0eXBlPSJyb3RhdGUiIGZyb209IjAgMTggMTgiIHRvPSIzNjAgMTggMTgiIGR1cj0iMXMiIHJlcGVhdENvdW50PSJpbmRlZmluaXRlIi8+CiAgICAgICAgICAgIDwvcGF0aD4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPg==") no-repeat center center;
    background-color: rgb(0, 0, 0);
    background-color: rgba(0, 0, 0, 0.75);
    text-align: center;
    transition: opacity .5s;
    cursor: zoom-out;
}

.imageBrowser figure {
    position: fixed;
    top: 1em;
    left: 1em;
    right: 1em;
    bottom: 1em;
    transition: all .5s;
}

.imageBrowser figure img {
    top: 50%;
    transform: translateY(-50%);
    position: relative;
    max-width: 100%;
    width: auto;
    height: auto;
    background: #fff;
    padding: 1em;
    max-height: 90%;
    max-width: 90%;
    border-radius: .5em;
    cursor: e-resize;
}

fieldset.wikiText {
    border: none;
    padding: 0;
}

fieldset.wikiMain, fieldset.wikiRights, fieldset.wikiEncrypt {
    float: right;
    width: 35%;
    margin-left: 3%;
    clear: right;
}

fieldset.wikiMain input[type=text] {
    min-width: 0;
}

#encryptPasswordDisplay {
    cursor: help;
    background: #ddd;
}

fieldset.wikiEncrypt .help {
    font-size: .9em;
}

fieldset.wikiMain #f_titre {
    width: 90%;
    font-size: 14pt;
}

fieldset.wikiMain #f_uri {
    width: 90%;
}

fieldset.wikiRights dl {
    font-size: 10pt;
}

fieldset.wikiRevision  {
    clear: both;
}

fieldset.wikiRevision #f_modification {
    width: 90%;
}

.wikiFiles {
    text-align: center;
}

.wikiFooter, .wikiFiles {
    font-size: 0.8em;
    color: #666;
    border-top: 0.1em solid #ccc;
    clear: both;
}

.wikiMain samp {
    background: #eee;
    padding: 0.2em 0.3em;
}

.wikiChildren {
    margin: 1em 0 1em 1em;
    border: .1em solid #999;
    border-radius: .5em;
    padding: 1em;
    background: rgba(255, 255, 255, 0.5);
    float: right;
    clear: right;
    width: 25%;
}

.wikiChildren ul {
    color: #ccc;
    list-style-type: square;
    margin-left: 1em;
}

.wikiTree ul {
    margin-left: 1em;
    list-style-type: none;
}

.wikiTree ul ul {
    margin-left: 2em;
}

.wikiTree a {
    color: #666;
}

.wikiTree h3:before {
    content: "▸";
    display: inline;
    margin-right: .5em;
}

.wikiTree li {
    margin: 0.2em 0;
}

.wikiTree h3 {
    font-size: 1em;
    font-weight: normal;
}

.wikiTree .current > h3 a {
    font-weight: bold;
    color: #000;
}

.wikiTree .choice {
    text-align: center;
    margin-bottom: 1em;
}

.breadCrumbs {
    margin-bottom: .8em;
    font-size: .9em;
    color: #999;
}

.breadCrumbs ul, .breadCrumbs li {
    list-style-type: none;
    display: inline;
}

.breadCrumbs li:before {
    content: "> ";
}

.breadCrumbs li a {
    color: #333;
}

.wikiSearch {
}

.wikiSearch fieldset {
    padding: .3em;
}

.wikiSearch input[type=text] {
    padding: .3em;
}

.wikiResults h3 {
    font-weight: normal;
    margin-bottom: .3em;
}

.wikiResults p {
    margin-bottom: .8em;
    font-size: .9em;
}

.wikiRevisions .length ins {
    text-decoration: none;
    color: green;
}

.wikiRevisions .length del {
    text-decoration: none;
    color: red;
}

.wikiRevisions .length i {
    font-style: normal;
    color: gray;
}

div.wikiRevision {
    width: 48%;
    margin: 1em 1%;
    text-align: center;
    float: left;
}

div.wikiRevision h3 {
    font-size: 1em;
}

div.wikiRevision h4 {
    font-weight: normal;
    font-size: .9em;
}

.diff .ins {
    background: #cfc;
    width: 45%;
}

.diff .del {
    background: #fcc;
    width: 45%;
}

.diff .line {
    width: 2%;
    padding: 0.2em;
    text-align: right;
    font-family: Mono;
    font-size: 90%;
    color: #666;
}

.diff .leftChange, .diff .rightChange {
    text-align: center;
    vertical-align: middle;
}

.diff ins { background: #9f9; }
.diff del { background: #f99; }

.diff hr {
    background: none;
    border: none;
    border-top: 5px dotted #fff;
    color: #fff;
    margin: .2em .4em;
}

.diff .separator {
    background: #ccc;
}

.diff {
    border-collapse: collapse;
    width: 100%;
    font-size: 0.9em;
}

.diff tr {
    border: 1px solid #ccc;
    vertical-align: top;
}

.diff .leftChange b, .diff .rightChange b {
    text-shadow: 1px 1px 1px #ccc;
    color: #666;
}

form#f_upload fieldset {
    position: relative;
}

form .fileUpload .uploadHelper_progress {
    position: absolute;
    bottom: 1em;
    left: 1em;
    right: 1em;
    text-align: center;
    padding: 1em;
    background: #ddd;
    box-shadow: 0px 0px 5px #999;
    border-radius: .5em;
}

form .fileUpload progress {
    width: 50%;
}

form#insertImage {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 10000;
    background: rgb(0, 0, 0);
    background: rgba(0, 0, 0, 0.75);
}

form#insertImage fieldset {
    box-shadow: 5px 5px 10px #000;
    margin: 1em;
    padding: 1em;
    background: #ddd;
    border-radius: .5em;
    text-align: center;
}

form#insertImage dt {
    margin: .2em 0;
}

form#insertImage .align input {
    font-size: 1.2em;
    line-height: 32px;
    background: #fff;
    background-position: 5px center;
    background-repeat: no-repeat;
    padding: 5px;
    padding-left: 42px;
    border: 1px solid #999;
    border-radius: 5px;
    margin: .5em;
}

form#insertImage .align input[name=""] {
    background-image: url("pics/img_flow.png");
}

form#insertImage .align input[name="gauche"] {
    background-image: url("pics/img_left.png");
}

form#insertImage .align input[name="droite"] {
    background-image: url("pics/img_right.png");
}

form#insertImage .align input[name="centre"] {
    background-image: url("pics/img_center.png");
}

form#insertImage .cancel input {
    font-size: 0.8em;
    background: transparent;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin: .5em;
    color: #666;
    cursor: pointer;
}

form#insertImage .align input:hover, form#insertImage .cancel input:hover  {
    cursor: pointer;
    background-color: #eee;
    color: darkred;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































































































































































































































































































































































































































































Modified src/www/admin/upgrade.php from [0bcf1f55dd] to [f17b581907].

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

namespace Garradin;

const UPGRADE_PROCESS = true;

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

$config = Config::getInstance();

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 '.$config->getVersion().' 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>';










<
<
















|







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
<?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>';

Added src/www/admin/web/_attach.php version [a59c3eef8c].

















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

use Garradin\Web\Web;
use Garradin\Entities\Web\Page;
use Garradin\Entities\Files\File;
use Garradin\Files\Files;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_WEB, $session::ACCESS_WRITE);

$page = Web::get(qg('p') ?: '');

if (!$page) {
	throw new UserException('Page inconnue');
}

$csrf_key = 'attach_' . $page->id();

$form->runIf('delete', function () use ($session) {
	$file = Files::get(f('delete'));

	if (!$file || !$file->checkDeleteAccess($session)) {
		throw new UserException('Vous ne pouvez pas supprimer ce fichier');
	}

	$file->delete();
}, $csrf_key, Utils::getSelfURI());


$form->runIf(f('upload') || f('uploadHelper_mode'), function () use ($page) {
	if (f('uploadHelper_status') > 0) {
		throw new UserException('Un seul fichier peut être envoyé en même temps.');
	}

	$new_file = File::upload(Utils::dirname($page->file_path), 'file');

	if (f('uploadHelper_status') !== null)
	{
		$uri = Utils::getSelfURI() . '&sent';
		echo json_encode([
			'redirect'  =>  $uri,
			'callback'  =>  'insertHelper',
			'file'      =>  [
				'image' =>  $new_file->image,
				'name'  =>  $new_file->name,
				'thumb' =>  $new_file->image ? $new_file->thumb_url() : false
			],
		]);
		exit;
	}
}, $csrf_key, Utils::getSelfURI() . '&sent');

if (f('uploadHelper_mode') !== null && $form->hasErrors()) {
	echo json_encode(['error' => implode(PHP_EOL, $form->getErrorMessages())]);
	exit;
}

$files = $page->getAttachmentsGallery(true);
$images = $page->getImageGallery(true);
$max_size = Utils::getMaxUploadSize();

$tpl->assign(compact('page', 'files', 'images', 'max_size', 'csrf_key'));
$tpl->assign('sent', (bool)qg('sent'));

$tpl->assign('custom_js', ['upload_helper.min.js', 'wiki_fichiers.js']);
$tpl->assign('custom_css', ['!static/scripts/wiki_editor.css']);

$tpl->display('web/_attach.tpl');

Added src/www/admin/web/_inc.php version [d0802763b9].























>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
<?php

namespace Garradin;

use Garradin\Membres\Session;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess(Session::SECTION_WEB, $session::ACCESS_READ);

$tpl->assign('custom_css', ['wiki.css']);

Added src/www/admin/web/_selector.php version [1082df8ea7].











































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

use Garradin\Web\Web;
use Garradin\Entities\Web\Page;

require_once __DIR__ . '/_inc.php';

// Force dialog mode
$_GET['_dialog'] = true;

$current = qg('current') ?? '';
$parent = qg('parent') ?? '';

$breadcrumbs = [];

if ($parent) {
	$page = Web::get($parent);

	if (!$page) {
		throw new UserException('Page inconnue');
	}

	$tpl->assign('page', $page);
	$breadcrumbs = $page->getBreadcrumbs();
}

$categories = Web::listCategories($parent);

$categories = array_filter($categories, function ($cat) use ($current) {
	return ($cat->path == $current) ? false : true;
});

$tpl->assign('selected', $current);
$tpl->assign(compact('breadcrumbs', 'parent', 'categories'));

$tpl->display('web/_selector.tpl');

Added src/www/admin/web/_syntaxe.html version [1b5e7a5287].





































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>Syntaxe SkrivML</title>
	<style type="text/css">
	body, form, p, div, hr, fieldset, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6 {
	    margin: 0;
	    padding: 0;
	}
	h1  { font-size: 2em; }
	h2  { font-size: 1.5em; }
	h3  { font-size: 1.2em; }
	h4  { font-size: 1em; }
	h5  { font-size: 0.9em; }
	h6  { font-size: 0.8em; }
	article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; }

	body {
		font-family: "Trebuchet MS", Arial, Helvetica, Sans-serif;
		padding: .8em;
	}
	pre, samp {
		display: block;
		background: #ccc;
		color: #000;
		border-radius: .5em;
		padding: .4em;
		white-space: normal;
	}

	samp {
		background: #999;
		font-family: "Trebuchet MS", Arial, Helvetica, Sans-serif;
	}

	p, header, article {
		margin: .8em 0;
		clear: both;
	}

	h1, h2, h3, h4, samp, pre {
		margin: .4em 0;
	}

	ul, ol {
		margin-left: 1.5em;
	}

	table {
		border-collapse: collapse;
	}
	table td, table th {
		border: 1px solid #666;
		padding: .3em;
	}

	a {
		color: blue;
		text-decoration: underline;
		cursor: pointer;
	}

	</style>
</head>

<body>

<section>
	<h1>Raccourcis clavier</h1>
	<table>
		<tbody>
			<tr>
				<th><kbd>Ctrl</kbd> + <kbd>G</kbd></th>
				<td>Mettre en gras</td>
			</tr>
			<tr>
				<th><kbd>Ctrl</kbd> + <kbd>I</kbd></th>
				<td>Mettre en italique</td>
			</tr>
			<tr>
				<th><kbd>Ctrl</kbd> + <kbd>T</kbd></th>
				<td>Mettre en titre</td>
			</tr>
			<tr>
				<th><kbd>Ctrl</kbd> + <kbd>L</kbd></th>
				<td>Mettre en lien</td>
			</tr>
			<tr>
				<th><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>I</kbd></th>
				<td>Insérer un fichier ou image</td>
			</tr>
			<tr>
				<th><kbd>Ctrl</kbd> + <kbd>P</kbd></th>
				<td>Prévisualiser</td>
			</tr>
			<tr>
				<th><kbd>Ctrl</kbd> + <kbd>S</kbd></th>
				<td>Enregistrer</td>
			</tr>
			<tr>
				<th><kbd>Echap</kbd></th>
				<td>Fermer l'aide, la prévisualisation ou l'insertion de fichier</td>
			</tr>
			<tr>
				<th><kbd>F11</kbd></th>
				<td>Activer ou désactiver l'édition plein écran</td>
			</tr>
			<tr>
				<th><kbd>F11</kbd></th>
				<td>Afficher l'aide</td>
			</tr>
		</tbody>
	</table>
</section>

<header>
	<h1>Syntaxe</h1>
	<p>Garradin utilise la syntaxe <a href="http://markup.skriv.org/language/syntax">SkrivML</a> pour 
		le formatage du texte dans le wiki.</p>
</header>

<section>
	<h2>Styles de base</h2>
	<article>
		<h3>Gras</h3>
		<pre>Utiliser **deux astérisques**.</pre>
		<samp>Utiliser <b>deux astérisques</b>.</samp>
	</article>

	<article>
		<h3>Italique</h3>
		<pre>Pourquoi pas des ''guillemets''.</pre>
		<samp>Pourquoi pas des <i>guillemets</i>.</samp>
	</article>

	<article>
		<h3>Souligné</h3>
		<pre>Il faut des __tirets bas__ pour souligner.</pre>
		<samp>Il faut des <u>tirets bas</u> pour souligner.</samp>
	</article>

	<article>
		<h3>Barré</h3>
		<pre>--Tirets hauts-- pour barrer.</pre>
		<samp><s>Tirets hauts</s> pour barrer.</samp>
	</article>

	<article>
		<h3>Exposant</h3>
		<pre>XXI^^ème^^ siècle</pre>
		<samp>XXI<sup>ème</sup> siècle.</samp>
	</article>


	<article>
		<h3>Indice</h3>
		<pre>CO,,2,,</pre>
		<samp>CO<sub>2</sub></samp>
	</article>

	<article>
		<p>Attention, ces styles ne fonctionnent que si le code entoure des mots complets, ça ne fonctionne pas au milieu de mots.</p>
		<pre>Un **mot** en gras. Mais on ne peut pas cou**per** un mot avec du gras.</pre>
		<samp>Un <b>mot</b> en gras. Mais on ne peut pas cou**per** un mot avec du gras.</samp>
	</article>
</section>

<section>
	<h2>Titres</h2>
	<article>
		<p>Doivent être précédé d'un ou plusieurs signe égal. Peuvent aussi être suivi du même nombre de signe égal.</p>
		<pre>= Titre niveau 1<br />== Titre niveau 2<br />=== Titre niveau 3 ===<br />==== Titre de niveau 4 ====</pre>
		<samp><h1>Titre niveau 1</h1><h2>Titre niveau 2</h2><h3>Titre niveau 3</h3><h4>Titre de niveau 4</h4></samp>
	</article>
</section>


<section>
	<h2>Listes</h2>
	<article>
		<h3>Listes non ordonnées</h3>
		<pre>* Item 1<br />* Item 2<br />** Sub-item 2.1<br />** Sub-item 2.2<br />*** Sub-item 2.2.1</pre>
		<samp><ul><li>Item 1</li><li>Item 2<ul><li>Sub-item 2.1</li><li>Sub-item 2.2<ul><li>Sub-item 2.2.1</li></ul></li></ul></li></ul></samp>
	</article>
	<article>
		<h3>Listes ordonnées</h3>
		<pre># Item 1<br /># Item 2<br />## Sub-item 2.1<br />## Sub-item 2.2<br />### Sub-item 2.2.1</pre>
		<samp><ol><li>Item 1</li><li>Item 2<ol><li>Sub-item 2.1</li><li>Sub-item 2.2<ol><li>Sub-item 2.2.1</li></ol></li></ol></li></ol></samp>
	</article>
</section>

<section>
	<h2>Liens</h2>
	<article>
		<h3>Lien wiki</h3>
		<pre>[[Autre page du wiki]]</pre>
		<samp><a title="Autre_page_du_wiki">Autre page du wiki</a></samp>
	</article>
	<article>
		<h3>Lien wiki avec libellé différent</h3>
		<pre>Voir [[cette page|Autre page du wiki]]</pre>
		<samp>Voir <a title="Autre_page_du_wiki">cette page</a></samp>
	</article>
	<article>
		<h3>Lien externe</h3>
		<pre>[[http://garradin.eu/]]</pre>
		<samp><a>http://garradin.eu/</a></samp>
	</article>
</section>

<section>
	<h2>Tableaux</h2>
	<article>
		<pre>!! Colonne 1 !! Colonne 2<br />|| Cellule 1 || Cellule 2<br />|| Cellule 3 || Cellule 4</pre>
		<samp><table><thead><tr><th>Colonne 1</th><th>Colonne 2</th></tr></thead><tbody><tr><td>Cellule 1</td><td>Cellule 2</td></tr><tr><td>Cellule 3</td><td>Cellule 4</td></tr></tbody></table></samp>
	</article>
</section>

<section>
	<h3>Autres</h3>
	<p>Consulter la documentation de <a href="http://markup.skriv.org/language/syntax">SkrivML</a>.</p>
</section>

</body>
</html>

Added src/www/admin/web/config.php version [ce640ecdba].































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

use Garradin\Web\Skeleton;

require_once __DIR__ . '/_inc.php';

$config = Config::getInstance();

if (f('disable_site') && $form->check('config_site'))
{
	$config->set('site_disabled', true);
	$config->save();
	Utils::redirect(Utils::getSelfURI());
}
elseif (f('enable_site') && $form->check('config_site'))
{
	$config->set('site_disabled', false);
	$config->save();
	Utils::redirect(Utils::getSelfURI());
}

$form->runIf('reset', function () {
	Skeleton::resetSelected(f('select'));
}, 'squelettes', Utils::getSelfURI('reset_ok'));

if (qg('edit')) {
	$source = trim(qg('edit'));
	$csrf_key = 'edit_skel_' . md5($source);

	$form->runIf('save', function () use ($source) {
		$tpl = new Skeleton($source);
		$tpl->edit(f('content'));
		$fullscreen = null !== qg('fullscreen') ? '#fullscreen' : '';
		Utils::redirect(Utils::getSelfURI(sprintf('edit=%s&ok%s', rawurlencode($source), $fullscreen)));
	}, $csrf_key);

	$tpl->assign('edit', ['file' => $source, 'content' => (new Skeleton($source))->raw()]);
	$tpl->assign('csrf_key', $csrf_key);
}

$tpl->assign('sources', Skeleton::list());

$tpl->assign('reset_ok', qg('reset_ok') !== null);
$tpl->assign('ok', qg('ok') !== null);

$tpl->display('web/config.tpl');

Added src/www/admin/web/css.php version [31cfe203b8].































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

/**
 * This file is an alias to /content.css basically,
 * but it is required for when WWW_URL is on a different domain than ADMIN_URL
 */

namespace Garradin;

use Garradin\Web\Skeleton;

require_once __DIR__ . '/_inc.php';

$s = new Skeleton('content.css');
$s->serve();

Added src/www/admin/web/delete.php version [cee4b59d69].



















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

use Garradin\Web\Web;
use Garradin\Entities\Web\Page;

require_once __DIR__ . '/_inc.php';

$page = Web::get(qg('p'));

if (!$page) {
	throw new UserException('Page inconnue');
}

$csrf_key = 'web_delete_' . $page->id();

$form->runIf('delete', function () use ($page) {
	$page->delete();
}, $csrf_key, ADMIN_URL . 'web/?parent=' . $page->parent);

$tpl->assign(compact('page', 'csrf_key'));
$tpl->assign('title', $page->type == Page::TYPE_CATEGORY ? 'Supprimer une catégorie' : 'Supprimer une page');
$tpl->assign('alert', $page->type == Page::TYPE_CATEGORY ? 'Attention ceci supprimera toutes les sous-catégories, pages et fichiers dans cette catégorie.' : 'Attention ceci supprimera tous les fichiers liés dans cette page.');

$tpl->display('web/delete.tpl');

Added src/www/admin/web/edit.php version [93999963a2].



























































































































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

namespace Garradin;

use Garradin\Web\Web;
use Garradin\Entities\Web\Page;
use Garradin\Entities\Files\File;
use KD2\SimpleDiff;

require_once __DIR__ . '/_inc.php';

$page = Web::get(qg('p'));

if (!$page) {
	throw new UserException('Page inconnue');
}

if (qg('new') !== null && empty($_POST)) {
	$page->set('status', Page::STATUS_ONLINE);
}

$csrf_key = 'web_edit_' . $page->id();

$editing_started = f('editing_started') ?: $page->modified->getTimestamp();

if (f('cancel')) {
	Utils::redirect(ADMIN_URL . 'web/?parent=' . $page->parent);
}

$show_diff = false;

$form->runIf('save', function () use ($page, $editing_started, &$show_diff) {
	if ($editing_started < $page->modified->getTimestamp()) {
		$show_diff = true;
		http_response_code(400);
		throw new UserException('La page a été modifiée par quelqu\'un d\'autre pendant que vous éditiez le contenu.');
	}

	$page->importForm();

	$page->save();

	if (qg('js') !== null) {
		die('{"success":true}');
	}

	Utils::redirect('!web/?p=' . $page->parent);
}, $csrf_key);

$parent = $page->parent ? [$page->parent => Web::get($page->parent)->title] : ['' => 'Racine du site'];
$encrypted = f('encrypted') || $page->format == Page::FORMAT_ENCRYPTED;

$old_content = f('content');
$new_content = $page->content;

$tpl->assign(compact('page', 'parent', 'editing_started', 'encrypted', 'csrf_key', 'old_content', 'new_content', 'show_diff'));

$tpl->assign('custom_js', ['wiki_editor.js', 'wiki-encryption.js']);
$tpl->assign('custom_css', ['wiki.css']);

$tpl->display('web/edit.tpl');

Added src/www/admin/web/index.php version [5baaa10463].









































































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

namespace Garradin;

use Garradin\Web\Web;
use Garradin\Entities\Web\Page;

require_once __DIR__ . '/_inc.php';

$current_path = qg('p') ?: '';
$cat = null;

Web::sync($current_path);

if ($current_path) {
	$cat = Web::get($current_path);

	if (!$cat) {
		throw new UserException('Catégorie inconnue');
	}
}

$order_date = qg('order_title') === null;

$categories = Web::listCategories($cat ? $cat->path : '');
$pages = Web::listPages($cat ? $cat->path : '', $order_date);
$title = $cat ? sprintf('Gestion du site web : %s', $cat->title) : 'Gestion du site web';
$type_page = Page::TYPE_PAGE;
$type_category = Page::TYPE_CATEGORY;
$breadcrumbs = $cat ? $cat->getBreadcrumbs() : [];

$parent = $cat ? $cat->parent : null;

$tpl->assign(compact('categories', 'pages', 'title', 'current_path', 'parent', 'type_page', 'type_category', 'order_date', 'breadcrumbs', 'cat'));

$tpl->display('web/index.tpl');

Added src/www/admin/web/new.php version [edfbf26682].





































































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

namespace Garradin;

use Garradin\Web\Web;
use Garradin\Entities\Web\Page;
use Garradin\Entities\Files\File;
use KD2\SimpleDiff;

require_once __DIR__ . '/_inc.php';

$csrf_key = 'web_page_new';

$parent = qg('parent') ?: null;

$form->runIf('create', function () use ($parent) {
	$page = Page::create((int) qg('type'), $parent, f('title'), Page::STATUS_DRAFT);
	$page->save();

	$url = ADMIN_URL . 'web/edit.php?new&p=' . $page->path;

	if (null !== qg('_dialog')) {
		Utils::reloadParentFrame($url);
	}
	else {
		Utils::redirect($url);
	}
}, $csrf_key);

$title = qg('type') == Page::TYPE_CATEGORY ? 'Nouvelle catégorie' : 'Nouvelle page';

$tpl->assign(compact('title', 'csrf_key'));

$tpl->display('web/new.tpl');

Added src/www/admin/web/page.php version [c7ad7078d0].



































































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

namespace Garradin;

use Garradin\Web\Web;
use Garradin\Entities\Web\Page;

require_once __DIR__ . '/_inc.php';

$page = Web::get(qg('p'));

if (!$page) {
	throw new UserException('Page inconnue');
}

$membres = new Membres;

$tpl->assign('breadcrumbs', $page->getBreadcrumbs());

$images = $page->getImageGallery(true);
$files = $page->getAttachmentsGallery(true);

$content = $page->render(['prefix' => ADMIN_URL . 'web/page.php?p=']);

$type_page = Page::TYPE_PAGE;
$type_category = Page::TYPE_CATEGORY;

$tpl->assign(compact('page', 'images', 'files', 'content', 'type_page', 'type_category'));

$tpl->assign('custom_js', ['wiki_gallery.js']);
$tpl->assign('custom_css', ['wiki.css', '!web/css.php']);

$tpl->display('web/page.tpl');

Added src/www/admin/web/search.php version [7ffb84ef47].



















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

use Garradin\Web\Web;
use Garradin\Entities\Web\Page;

require_once __DIR__ . '/_inc.php';

$q = trim(f('q'));

$tpl->assign('query', $q);

if ($q) {
	$r = Web::search($q);
	$tpl->assign('results', $r);
	$tpl->assign('results_count', count($r));
}

function tpl_clean_snippet($str) {
	return preg_replace('!&lt;(/?b)&gt;!', '<$1>', $str);
}

$tpl->register_modifier('clean_snippet', 'Garradin\tpl_clean_snippet');

$tpl->display('web/search.tpl');

Deleted src/www/admin/wiki/_chercher_parent.php version [4ec2c6e487].

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
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

qv(['parent' => 'required|numeric']);

$parent = (int) qg('parent');

$tpl->assign('parent', $parent);
$tpl->assign('list', $wiki->listBackParentTree($parent));

function tpl_display_tree($params)
{
    if (isset($params['tree']))
        $tree = $params['tree'];
    else
        $tree = $params;

    $out = '<ul>';

    foreach ($tree as $node)
    {
        $out .= '<li'.(qg('parent') == $node->id ? ' class="current"' : '').'><h3><a href="?parent='.(int)$node->id.'">'.htmlspecialchars($node->titre, ENT_QUOTES, 'UTF-8', false).'</a></h3>';

        if (!empty($node->children))
        {
            $out .= tpl_display_tree($node->children);
        }

        $out .= '</li>';
    }

    $out .= '</ul>';

    return $out;
}

$tpl->register_function('display_tree', 'Garradin\tpl_display_tree');

$tpl->display('admin/wiki/_chercher_parent.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































Deleted src/www/admin/wiki/_fichiers.php version [aec8dcbc2d].

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
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

qv(['page' => 'required|numeric']);

$page = $wiki->getById(qg('page'));
$csrf_id = 'wiki_files_' . $page->id;

if (!$page)
{
    throw new UserException('Page introuvable.');
}

// Vérification des hash avant upload
if ($hash_check = f('uploadHelper_hashCheck'))
{
    echo json_encode(Fichiers::checkHashList($hash_check));
    exit;
}
elseif (f('delete'))
{
    if ($form->check($csrf_id))
    {
        try {
            $fichier = new Fichiers(f('delete'));
            
            if (!$fichier->checkAccess($session, true))
            {
                throw new UserException('Vous n\'avez pas accès à ce fichier.');
            }

            $fichier->remove();
            Utils::redirect(ADMIN_URL . 'wiki/_fichiers.php?page=' . $page->id);
        }
        catch (UserException $e)
        {
            $form->addError($e->getMessage());
        }
    }
}
elseif (f('upload') || f('uploadHelper_mode'))
{
    $validate = ['fichier' => 'file|required'];

    if (f('uploadHelper_mode') == 'hash_only')
    {
        $validate = [
            'uploadHelper_fileHash' => 'required',
            'uploadHelper_fileName' => 'required',
        ];
    }

    $form->check($csrf_id, $validate);

    if (f('uploadHelper_status') > 0)
    {
        $form->addError('Un seul fichier peut être envoyé en même temps.');
    }
    
    if (!$form->hasErrors())
    {
        try {
            if (f('uploadHelper_mode') == 'hash_only' && f('uploadHelper_fileHash') && f('uploadHelper_fileName'))
            {
                $fichier = Fichiers::uploadExistingHash(f('uploadHelper_fileName'), f('uploadHelper_fileHash'));
            }
            else
            {
                $fichier = Fichiers::upload($_FILES['fichier']);
            }

            // Lier le fichier à la page wiki
            $fichier->linkTo(Fichiers::LIEN_WIKI, $page->id);
            $uri = ADMIN_URL . 'wiki/_fichiers.php?page=' . $page->id . '&sent';

            if (f('uploadHelper_status') !== null)
            {
                echo json_encode([
                    'redirect'  =>  $uri,
                    'callback'  =>  'insertHelper',
                    'file'      =>  [
                        'image' =>  (int)$fichier->image,
                        'id'    =>  (int)$fichier->id,
                        'nom'   =>  $fichier->nom,
                        'thumb' =>  $fichier->image ? $fichier->getURL(200) : false
                    ],
                ]);
                exit;
            }

            Utils::redirect($uri);
        }
        catch (UserException $e)
        {
            $form->addError($e->getMessage());
        }
    }

    if (f('uploadHelper_mode') !== null)
    {
        echo json_encode(['error' => implode(PHP_EOL, $form->getErrorMessages())]);
        exit;
    }
}

$tpl->assign('fichiers', Fichiers::listLinkedFiles(Fichiers::LIEN_WIKI, $page->id, false));
$tpl->assign('images', Fichiers::listLinkedFiles(Fichiers::LIEN_WIKI, $page->id, true));

$tpl->assign('max_size', Utils::getMaxUploadSize());
$tpl->assign('page', $page);
$tpl->assign('sent', (bool)qg('sent'));
$tpl->assign('csrf_id', $csrf_id);

$tpl->assign('custom_js', ['upload_helper.min.js', 'wiki_fichiers.js']);

$tpl->display('admin/wiki/_fichiers.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































Deleted src/www/admin/wiki/_inc.php version [7e46f0d30d].

1
2
3
4
5
6
7
8
9
10
11
12
<?php

namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$session->requireAccess('wiki', Membres::DROIT_ACCES);

$wiki = new Wiki;
$wiki->setRestrictionCategorie($user->id_categorie, $user->droit_wiki);

$tpl->assign('custom_css', ['wiki.css']);
<
<
<
<
<
<
<
<
<
<
<
<
























Deleted src/www/admin/wiki/_preview.php version [d803765203].

1
2
3
4
5
6
7
8
9
10
11
<?php

namespace Garradin;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('wiki', Membres::DROIT_ECRITURE);

$tpl->assign('contenu', f('contenu'));

$tpl->display('admin/wiki/_preview.tpl');
<
<
<
<
<
<
<
<
<
<
<






















Deleted src/www/admin/wiki/_syntaxe.html version [4f5b72c0af].

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
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>Syntaxe SkrivML</title>
	<style type="text/css">
	body, form, p, div, hr, fieldset, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6 {
	    margin: 0;
	    padding: 0;
	}
	h1  { font-size: 2em; }
	h2  { font-size: 1.5em; }
	h3  { font-size: 1.2em; }
	h4  { font-size: 1em; }
	h5  { font-size: 0.9em; }
	h6  { font-size: 0.8em; }
	article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; }

	body {
		font-family: "Trebuchet MS", Arial, Helvetica, Sans-serif;
		padding: .8em;
	}
	pre, samp {
		display: block;
		background: #ccc;
		color: #000;
		border-radius: .5em;
		padding: .4em;
		white-space: normal;
	}

	samp {
		background: #999;
		font-family: "Trebuchet MS", Arial, Helvetica, Sans-serif;
	}

	p, header, article {
		margin: .8em 0;
		clear: both;
	}

	h1, h2, h3, h4, samp, pre {
		margin: .4em 0;
	}

	ul, ol {
		margin-left: 1.5em;
	}

	table {
		border-collapse: collapse;
	}
	table td, table th {
		border: 1px solid #666;
		padding: .3em;
	}

	a {
		color: blue;
		text-decoration: underline;
		cursor: pointer;
	}

	</style>
</head>

<body>

<header>
	<p>Garradin utilise la syntaxe <a href="http://markup.skriv.org/language/syntax">SkrivML</a> pour 
		le formatage du texte dans le wiki.</p>
</header>

<section>
	<h2>Styles de base</h2>
	<article>
		<h3>Gras</h3>
		<pre>Utiliser **deux astérisques**.</pre>
		<samp>Utiliser <b>deux astérisques</b>.</samp>
	</article>

	<article>
		<h3>Italique</h3>
		<pre>Pourquoi pas des ''guillemets''.</pre>
		<samp>Pourquoi pas des <i>guillemets</i>.</samp>
	</article>

	<article>
		<h3>Souligné</h3>
		<pre>Il faut des __tirets bas__ pour souligner.</pre>
		<samp>Il faut des <u>tirets bas</u> pour souligner.</samp>
	</article>

	<article>
		<h3>Barré</h3>
		<pre>--Tirets hauts-- pour barrer.</pre>
		<samp><s>Tirets hauts</s> pour barrer.</samp>
	</article>

	<article>
		<h3>Exposant</h3>
		<pre>XXI^^ème^^ siècle</pre>
		<samp>XXI<sup>ème</sup> siècle.</samp>
	</article>


	<article>
		<h3>Indice</h3>
		<pre>CO,,2,,</pre>
		<samp>CO<sub>2</sub></samp>
	</article>

	<article>
		<p>Attention, ces styles ne fonctionnent que si le code entoure des mots complets, ça ne fonctionne pas au milieu de mots.</p>
		<pre>Un **mot** en gras. Mais on ne peut pas cou**per** un mot avec du gras.</pre>
		<samp>Un <b>mot</b> en gras. Mais on ne peut pas cou**per** un mot avec du gras.</samp>
	</article>
</section>

<section>
	<h2>Titres</h2>
	<article>
		<p>Doivent être précédé d'un ou plusieurs signe égal. Peuvent aussi être suivi du même nombre de signe égal.</p>
		<pre>= Titre niveau 1<br />== Titre niveau 2<br />=== Titre niveau 3 ===<br />==== Titre de niveau 4 ====</pre>
		<samp><h1>Titre niveau 1</h1><h2>Titre niveau 2</h2><h3>Titre niveau 3</h3><h4>Titre de niveau 4</h4></samp>
	</article>
</section>


<section>
	<h2>Listes</h2>
	<article>
		<h3>Listes non ordonnées</h3>
		<pre>* Item 1<br />* Item 2<br />** Sub-item 2.1<br />** Sub-item 2.2<br />*** Sub-item 2.2.1</pre>
		<samp><ul><li>Item 1</li><li>Item 2<ul><li>Sub-item 2.1</li><li>Sub-item 2.2<ul><li>Sub-item 2.2.1</li></ul></li></ul></li></ul></samp>
	</article>
	<article>
		<h3>Listes ordonnées</h3>
		<pre># Item 1<br /># Item 2<br />## Sub-item 2.1<br />## Sub-item 2.2<br />### Sub-item 2.2.1</pre>
		<samp><ol><li>Item 1</li><li>Item 2<ol><li>Sub-item 2.1</li><li>Sub-item 2.2<ol><li>Sub-item 2.2.1</li></ol></li></ol></li></ol></samp>
	</article>
</section>

<section>
	<h2>Liens</h2>
	<article>
		<h3>Lien wiki</h3>
		<pre>[[Autre page du wiki]]</pre>
		<samp><a title="Autre_page_du_wiki">Autre page du wiki</a></samp>
	</article>
	<article>
		<h3>Lien wiki avec libellé différent</h3>
		<pre>Voir [[cette page|Autre page du wiki]]</pre>
		<samp>Voir <a title="Autre_page_du_wiki">cette page</a></samp>
	</article>
	<article>
		<h3>Lien externe</h3>
		<pre>[[http://garradin.eu/]]</pre>
		<samp><a>http://garradin.eu/</a></samp>
	</article>
</section>

<section>
	<h2>Tableaux</h2>
	<article>
		<pre>!! Colonne 1 !! Colonne 2<br />|| Cellule 1 || Cellule 2<br />|| Cellule 3 || Cellule 4</pre>
		<samp><table><thead><tr><th>Colonne 1</th><th>Colonne 2</th></tr></thead><tbody><tr><td>Cellule 1</td><td>Cellule 2</td></tr><tr><td>Cellule 3</td><td>Cellule 4</td></tr></tbody></table></samp>
	</article>
</section>

<section>
	<h3>Autres</h3>
	<p>Consulter la documentation de <a href="http://markup.skriv.org/language/syntax">SkrivML</a>.</p>
</section>

</body>
</html>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































































































































Deleted src/www/admin/wiki/chercher.php version [6cce625794].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

$q = trim(qg('q'));

$tpl->assign('recherche', $q);

if ($q)
{
    $r = $wiki->search($q);
    $tpl->assign('resultats', $r);
    $tpl->assign('nb_resultats', count($r));
}

function tpl_clean_snippet($str)
{
    return preg_replace('!&lt;(/?b)&gt;!', '<$1>', $str);
}

$tpl->register_modifier('clean_snippet', 'Garradin\tpl_clean_snippet');

$tpl->display('admin/wiki/chercher.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































Deleted src/www/admin/wiki/creer.php version [fcf6294705].

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
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

$parent = (int) qg('parent');

if (f('create'))
{
    $form->check('wiki_create', [
        'titre' => 'required',
        'parent'=> 'required|integer'
    ]);

    try {
        $id = $wiki->create([
            'titre'  => f('titre'),
            'parent' => $parent,
            'droit_lecture' => qg('public') !== null ? Wiki::LECTURE_PUBLIC : Wiki::LECTURE_NORMAL,
        ]);

        Utils::redirect(ADMIN_URL . 'wiki/editer.php?id='.$id);
    }
    catch (UserException $e)
    {
        $form->addError($e->getMessage());
    }
}

$tpl->display('admin/wiki/creer.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































Deleted src/www/admin/wiki/editer.php version [85c2033cca].

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
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('wiki', Membres::DROIT_ECRITURE);

qv(['id' => 'required|numeric']);

$page = $wiki->getById(qg('id'));
$date = false;

if (!$page)
{
    throw new UserException('Page introuvable.');
}

if (!empty($page->contenu))
{
    $page->chiffrement = $page->contenu->chiffrement;
    $page->contenu = $page->contenu->contenu;
}

if (f('date'))
{
    $date = f('date') . ' ' . sprintf('%02d:%02d', f('date_h'), f('date_min'));
}

if (f('save'))
{
    $form->check('wiki_edit_' . $page->id, [
        'titre'          => 'required',
        'uri'            => 'required',
        'parent'         => 'numeric',
        'droit_lecture'  => 'numeric',
        'droit_ecriture' => 'numeric',
    ]);
    
    if ($page->date_modification > (int) f('debut_edition'))
    {
        $form->addError('La page a été modifiée par quelqu\'un d\'autre depuis que vous avez commencé l\'édition.');
    }

    if (!$form->hasErrors())
    {
        try {
            $wiki->edit($page->id, [
                'titre'         =>  f('titre'),
                'uri'           =>  f('uri'),
                'parent'        =>  f('parent'),
                'droit_lecture' =>  f('droit_lecture'),
                'droit_ecriture'=>  f('droit_ecriture'),
                'date_creation' =>  $date,
            ]);

            $wiki->editRevision($page->id, (int) f('revision_edition'), [
                'contenu'      =>  f('contenu'),
                'modification' =>  f('modification'),
                'id_auteur'    =>  $user->id,
                'chiffrement'  =>  f('chiffrement'),
            ]);

            $page = $wiki->getById($page->id);

            Utils::redirect(ADMIN_URL . 'wiki/?'.$page->uri);
        }
        catch (UserException $e)
        {
            $form->addError($e->getMessage());
        }
    }
}

$parent = (int) f('parent') ?: (int) $page->parent;
$tpl->assign('parent', $parent ? $wiki->getTitle($parent) : 0);

$tpl->assign('page', $page);

$tpl->assign('wiki', $wiki);

$tpl->assign('time', time());
$tpl->assign('date', $date ? strtotime($date) : $page->date_creation);

$tpl->assign('custom_js', ['wiki_editor.js', 'wiki-encryption.js']);

$tpl->display('admin/wiki/editer.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































Deleted src/www/admin/wiki/historique.php version [0c8cd47a0e].

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
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

qv(['id' => 'required|numeric']);

$page = $wiki->getByID(qg('id'));

if (!$page)
{
    throw new UserException("Cette page n'existe pas.");
}

if (!$wiki->canReadPage($page->droit_lecture))
{
    throw new UserException("Vous n'avez pas le droit de voir cette page.");
}

if (qg('diff'))
{
    $revs = explode('.', qg('diff'));

    if (count($revs) != 2)
    {
        throw new UserException("Erreur de paramètre.");
    }

    $rev1 = $wiki->getRevision($page->id, (int)$revs[0]);
    $rev2 = $wiki->getRevision($page->id, (int)$revs[1]);

    if ($rev1->chiffrement)
    {
        $rev1->contenu = 'Contenu chiffré';
    }

    if ($rev2->chiffrement)
    {
        $rev2->contenu = 'Contenu chiffré';
    }

    $tpl->assign('rev1', $rev1);
    $tpl->assign('rev2', $rev2);
    $tpl->assign('diff', true);
}
else
{
    $tpl->assign('revisions', $wiki->listRevisions($page->id));
}

$tpl->assign('can_edit', $wiki->canWritePage($page->droit_ecriture));
$tpl->assign('page', $page);

$tpl->display('admin/wiki/historique.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































Deleted src/www/admin/wiki/index.php version [373b4cc240].

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

namespace Garradin;
require_once __DIR__ . '/_inc.php';

if (!empty($_SERVER['QUERY_STRING']))
{
    $page_uri = Wiki::transformTitleToURI(rawurldecode($_SERVER['QUERY_STRING']));
    $page = $wiki->getByURI($page_uri);
}
else
{
    $page = $wiki->getByURI($config->get('accueil_wiki'));
    $page_uri = '';
}

if (!$page)
{
    $tpl->assign('uri', $page_uri);
    $tpl->assign('can_edit', false);
    $tpl->assign('can_read', true);
}
else
{
    $membres = new Membres;
    $tpl->assign('can_read', $wiki->canReadPage($page->droit_lecture));
    $tpl->assign('can_edit', $wiki->canWritePage($page->droit_ecriture));
    $tpl->assign('children', $wiki->getList($page_uri == '' ? 0 : $page->id, true));
    $tpl->assign('has_public_children', $wiki->hasChildren($page_uri == '' ? 0 : $page->id, true));
    $tpl->assign('breadcrumbs', $wiki->listBackBreadCrumbs($page->id));
    $tpl->assign('auteur', $page->contenu ? $membres->getNom($page->contenu->id_auteur) : null);

    $images = Fichiers::listLinkedFiles(Fichiers::LIEN_WIKI, $page->id, true);

    if ($images && !empty($page->contenu->chiffrement))
    {
        $images = Fichiers::filterFilesUsedInText($images, $page->contenu->contenu);
    }

    $fichiers = Fichiers::listLinkedFiles(Fichiers::LIEN_WIKI, $page->id, false);

    if ($fichiers && !empty($page->contenu->chiffrement))
    {
        $fichiers = Fichiers::filterFilesUsedInText($fichiers, $page->contenu->contenu);
    }

    $tpl->assign('images', $images);
    $tpl->assign('fichiers', $fichiers);
}

$tpl->assign('page', $page);

$tpl->assign('custom_js', ['wiki_gallery.js']);

$tpl->display('admin/wiki/page.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































Deleted src/www/admin/wiki/recent.php version [8a00987ce2].

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

namespace Garradin;

require_once __DIR__ . '/_inc.php';

$page = (int) qg('p') ?: 1;

$tpl->assign('current_page', $page);
$tpl->assign('bypage', Wiki::ITEMS_PER_PAGE);
$tpl->assign('total', $wiki->countRecentModifications());
$tpl->assign('list', $wiki->listRecentModifications($page));

$tpl->display('admin/wiki/recent.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























Deleted src/www/admin/wiki/supprimer.php version [cc76953c4e].

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
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

qv(['id' => 'required|numeric']);

$session->requireAccess('wiki', Membres::DROIT_ADMIN);

$page = $wiki->getByID(qg('id'));

if (!$page)
{
    throw new UserException("Cette page n'existe pas.");
}

if (f('delete'))
{
    if ($form->check('delete_wiki_' . $page->id))
    {
        if ($wiki->delete($page->id))
        {
            Utils::redirect(ADMIN_URL . 'wiki/');
        }
        else
        {
            $form->addError('D\'autres pages utilisent cette page comme rubrique parente.');
        }
    }
}

$tpl->assign('page', $page);

$tpl->display('admin/wiki/supprimer.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































Deleted src/www/file.php version [a75fe87ff3].

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

namespace Garradin;

require __DIR__ . '/_inc.php';

$id = isset($_GET['id']) ? $_GET['id'] : false;
$filename = !empty($_GET['file']) ? $_GET['file'] : false;
$size = false;

if (empty($id))
{
	throw new UserException('Fichier inconnu.');
}

foreach ($_GET as $key=>$value)
{
	if (substr($key, -2) == 'px')
	{
		$size = (int)substr($key, 0, -2);
		break;
	}
}

$id = base_convert($id, 36, 10);

try {
	$file = new Fichiers((int)$id);
}
catch (\InvalidArgumentException $e)
{
	throw new UserException('Ce fichier n\'existe pas.');
}

$session = new Membres\Session;

if (!$file->checkAccess($session))
{
	header('HTTP/1.1 403 Forbidden', true, 403);
	throw new UserException('Vous n\'avez pas accès à ce fichier.');
}

if ($size)
{
	$file->serveThumbnail($size);
}
else
{
	$file->serve();
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































Modified src/www/index.php from [1c65f87820] to [058717db8f].

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

namespace Garradin;

if (PHP_VERSION_ID < 70200) {
	die("PHP 7.2 ou supérieur est requis.");
}

require __DIR__ . '/_inc.php';

if (Config::getInstance()->get('desactiver_site'))
{
	Utils::redirect(ADMIN_URL);
}

$squelette = new Squelette;
$squelette->dispatchURI();




|
<
<



<
<
<
<
<
<
|
1
2
3
4
5


6
7
8






9
<?php

namespace Garradin;

use Garradin\Web\Web;



require __DIR__ . '/_inc.php';







Web::dispatchURI();

Added src/www/skel-dist/404.html version [24a08b71a2].

















>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
{{:http code=404}}
{{:include file="_head.html" title="Page non trouvée"}}

	<p class="error">
		Cette page n'existe pas.
	</p>

{{:include file="_foot.html"}}

Added src/www/skel-dist/_breadcrumbs.html version [0552416b60].

















>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
<nav class="breadcrumbs">
	<ul>
		<li><a href="{{ $root_url }}">Accueil</a></li>
		{{#breadcrumbs path=$parent}}
		<li><a href="{{ $url }}">{{ $title }}</a></li>
		{{/breadcrumbs}}
	</ul>
</nav>

Added src/www/skel-dist/_foot.html version [8e09fe42c0].

















>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
</section>

<footer class="main">
	Propulsé par <a href="https://garradin.eu/" id="garradin">Garradin</a> — logiciel libre de gestion associative
</footer>

</body>
</html>

Added src/www/skel-dist/_head.html version [785b737716].

















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<!DOCTYPE html>
<html lang="fr">
<head>
	<meta charset="utf-8" />
	<title>{{if $title}}{{$title}} — {{/if}}{{$config.nom_asso}}</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=device-dpi" />
	<link rel="stylesheet" type="text/css" href="{{$root_url}}default.css" media="screen,projection,handheld" />
	<link rel="stylesheet" type="text/css" href="{{$root_url}}content.css" media="all" />
	<link rel="alternate" type="application/atom+xml" title="{{$config.nom_asso}}" href="{{$root_url}}atom.xml" />
</head>

<body>

<header class="nav">
	<nav>
		<ul>
			<li class="current"><a href="{{$root_url}}">Accueil</a></li>
			<li><a href="{{$admin_url}}">Administration</a></li>
		</ul>
	</nav>
</header>

<header class="main">
	<h1><a href="{{$root_url}}">{{$config.nom_asso}}</a></h1>

{{if $config.adresse_asso || $config.telephone_asso || $config.email_asso}}
	<article class="contacts">
		{{if $config.adresse_asso}}
			<h4>{{$config.adresse_asso|escape}}</h4>
		{{/if}}
		{{if $config.telephone_asso}}
			<h5>{{$config.telephone_asso|raw|protect_contact}}</h5>
		{{/if}}
		{{if $config.email_asso}}
			<h5>{{$config.email_asso|raw|protect_contact}}</h5>
		{{/if}}
	</article>
{{/if}}

	<form method="get" action="{{ $root_url }}search.html" class="search-widget">
		<p>
			<input type="search" name="search" placeholder="Rechercher…" />
			<input type="submit" value="»" />
		</p>
	</form>

	<nav>
		<ul>
		{{#categories parent=null order="title"}}
			<li><a href="{{$url}}">{{ $title }}</a></li>
		{{/categories}}
		</ul>
	</nav>
</header>

<section class="page">

Added src/www/skel-dist/article.html version [0d3f6a0c3e].

































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{{:include file="_head.html" title=$page.title}}

{{:include file="_breadcrumbs.html" parent=$page.path}}

<article class="single">
	<h1>{{$page.title}}</h1>

	<h4>Publié le {{$page.published|date_long:true}}</h4>

	{{$page.html|raw}}

	{{:include file="gallery.html" parent=$page.path}}
	{{:include file="documents.html" parent=$page.path}}
</article>

{{:include file="_foot.html"}}

Added src/www/skel-dist/atom.xml version [821fe4fdaa].

































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{{:http type="application/atom+xml"}}
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="fr">

	<title type="html">{{$config.nom_asso|xml_escape}}</title>
	<link href="{{$root_url|xml_escape}}" rel="alternate" type="text/html" title="{{$config.nom_asso|xml_escape}}" />

	{{#articles order="published DESC" limit=1}}
	<updated>{{$created|atom_date}}</updated>
	{{/articles}}

	<author>
		<name>{{$config.nom_asso|xml_escape}}</name>
	</author>

	<id>{{$root_url|xml_escape}}</id>
	<generator uri="https://fossil.kd2.org/garradin/">Garradin</generator>

	{{#articles order="published DESC" limit=20}}
	<entry>
		<title>{{$title|xml_escape}}</title>
		<link href="{{$url|xml_escape}}" rel="alternate" type="text/html" title="{{$title|xml_escape}}" />
		<id>{{$url|xml_escape}}</id>
		<updated>{{$modified|atom_date}}</updated>
		<author><name>{{$config.nom_asso|xml_escape}}</name></author>
		<content type="html">
			{{$html|raw|xml_escape}}
		</content>
	</entry>
	{{/articles}}

</feed>

Added src/www/skel-dist/category.html version [21f3b64cc6].

































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{{:include file="_head.html" title=$page.title}}

{{:include file="_breadcrumbs.html" parent=$page.path}}

<section class="subcategories">
	{{#categories parent=$page.path order="title"}}
	<ul>
		<li><a href="{{$url}}">{{$title}}</a></li>
	</ul>
	{{/categories}}
</section>

<article class="single">
	<h1>{{$page.title}}</h1>

	{{$page.html|raw}}

	{{:include file="gallery.html" parent=$page.path}}
	{{:include file="documents.html" parent=$page.path}}
</article>

<section class="articles">
	{{#articles parent=$page.path order="published DESC" future=false}}
	<article>
		<h3><a href="{{$url}}">{{$title}}</a></h3>
		<h5>{{$published|date_long}}</h5>
		<p>{{$html|raw|strip_tags|truncate:200}}</p>
	</article>
	{{/articles}}
</section>

{{:include file="_foot.html"}}

Added src/www/skel-dist/content.css version [38f956b17f].







































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
.web-content p, .web-content h1, .web-content h2, .web-content h3, .web-content h4, .web-content h5, .web-content h6,
.web-content ul, .web-content ol, .web-content table, .web-content blockquote {
    margin-bottom: .8em;
}

.web-content ul, .web-content ol, .web-content dd {
    margin-left: 2em;
}

.web-content ul {
    list-style-type: disc;
}

.web-content ol {
    list-style-type: decimal;
}

.web-content table {
    border-collapse: collapse;
}

.web-content table th, .web-content table td {
    border: 1px solid #999;
    padding: .5rem;
    text-align: center;
}

.web-content table th {
    background: #eee;
    font-weight: bold;
}

.web-content aside.file {
    margin: 1em;
}

.web-content aside.file small {
    opacity: 0.7;
}

.web-content aside.file a {
    display: inline-block;
    margin-right: 1em;
    padding: .5em;
    padding-left: 1.8em;
    border: 1px solid #999;
    background: #eee;
    border-radius: .5em;
    background-repeat: no-repeat;
    background-position: .5em center;
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAAQCAYAAADAvYV+AAAAd0lEQVQoz2NgQAVNQDwDCTcw4AF3gPg/Er4xSBWnAXEHFL9HU/wWSS4FpFgZiJ+jKULHT4BYAWa6LhC/w6HwNRBrojvHEoi/oCn8BMQmuDzoBsQ/oQq/A7E9AwEQDMQ/gNiHgUggx0AN8IVI/AGkeA+ReCdJTgAAgMhKhf6mzTIAAAAASUVORK5CYII=");
    transition: background-color .2s, color .2s;
}

.web-content aside.file a:hover {
    background-color: #ccc;
    color: darkred;
}

.web-content figure.image {
    text-align: center;
}

.web-content figure.image figcaption {
    font-style: italic;
    color: #666;
    margin-top: 2pt;
}

.web-content figure.image.img-center {
    max-width: 500px;
    margin: 0 auto 8pt auto;
}

.web-content figure.image.img-left {
    max-width: 200px;
    float: left;
    margin: 0 8pt 4pt 0;
    clear: left;
}

.web-content figure.image.img-right {
    max-width: 200px;
    float: right;
    margin: 0 0 4pt 8pt;
    clear: right;
}

.web-content figure.image.img-left figcaption, .web-content figure.image.img-right figcaption {
    font-size: .8em;
}

.web-content a.internal-image {
    cursor: zoom-in;
}

.web-content img {
    max-width: 100%;
}

.imageBrowser {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    background: url("data:image/svg+xml;base64,PCEtLSBCeSBTYW0gSGVyYmVydCAoQHNoZXJiKSwgZm9yIGV2ZXJ5b25lLiBNb3JlIEAgaHR0cDovL2dvby5nbC83QUp6YkwgLS0+Cjxzdmcgd2lkdGg9IjM4IiBoZWlnaHQ9IjM4IiB2aWV3Qm94PSIwIDAgMzggMzgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgc3Ryb2tlPSIjZmZmIj4KICAgIDxnIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+CiAgICAgICAgPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMSAxKSIgc3Ryb2tlLXdpZHRoPSIyIj4KICAgICAgICAgICAgPGNpcmNsZSBzdHJva2Utb3BhY2l0eT0iLjUiIGN4PSIxOCIgY3k9IjE4IiByPSIxOCIvPgogICAgICAgICAgICA8cGF0aCBkPSJNMzYgMThjMC05Ljk0LTguMDYtMTgtMTgtMTgiPgogICAgICAgICAgICAgICAgPGFuaW1hdGVUcmFuc2Zvcm0gYXR0cmlidXRlTmFtZT0idHJhbnNmb3JtIiB0eXBlPSJyb3RhdGUiIGZyb209IjAgMTggMTgiIHRvPSIzNjAgMTggMTgiIGR1cj0iMXMiIHJlcGVhdENvdW50PSJpbmRlZmluaXRlIi8+CiAgICAgICAgICAgIDwvcGF0aD4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPg==") no-repeat center center;
    background-color: rgb(0, 0, 0);
    background-color: rgba(0, 0, 0, 0.75);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    transition: opacity .5s;
    cursor: zoom-out;
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}

.imageBrowser figure {
    max-height: 90%;
    max-width: 90%;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    transition: all .5s;
    margin: 0;
}

.imageBrowser figure img {
    background: #000;
    max-width: 100%;
    max-height: 100%;
    padding: .5rem;
    border-radius: .5em;
    cursor: pointer;
}

@media handheld, screen and (max-width: 980px) {
    .imageBrowser figure {
        max-width: 100%;
        max-height: 100%;
    }
}

Added src/www/skel-dist/default.css version [c5d9c9f441].



















































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
body, form, p, div, hr, fieldset, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6 {
    margin: 0;
    padding: 0;
}
h1  { font-size: 2em; }
h2  { font-size: 1.5em; }
h3  { font-size: 1.2em; }
h4  { font-size: 1em; }
h5  { font-size: 0.9em; }
h6  { font-size: 0.8em; }
ul, ol { list-style-type: none; }
article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; }

body {
    font-size: 100.01%;
    color: #000;
    font-family: "Trebuchet MS", Helvetica, Sans-serif;
    background: #fff;
}

header.nav {
    background: #ddd;
    border-bottom: 1px solid #999;
    border-top: .3em solid #666;
    text-align: center;
    padding-top: .3em;
}

header.nav li {
    display: inline-block;
    padding: .3em .5em;
    margin-bottom: -1px;
}

header.nav li a {
    padding: .3em .5em;
    text-transform: uppercase;
    color: #666;
    text-decoration: none;
}

header.nav li.current a {
    background: #fff;
    border: .1em solid #999;
    border-bottom: none;
    border-top-left-radius: .3em;
    border-top-right-radius: .3em;
}

header.nav li a:hover {
    color: #000;
}

header.main, footer.main, section.page {
    max-width: 950px;
    margin: 0 auto;
}

header.main h1 {
    color: #9c4f15;
    padding: .2em 0 .1em 0;
    font-size: 4em;
    font-family: Georgia, "Times New Roman", Times, serif;
    font-weight: normal;
}

header.main h1 a {
    color: #9c4f15;
    text-decoration: none;
}

header.main {
    margin-bottom: 1em;
    background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAXMAAADPAQMAAAA9C6NrAAAABlBMVEXx9PD+//zYDo7WAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gEIER05obn78wAACb1JREFUaN7V2TuOHLkZAGBSHKgmMEyFCgRRR1CoYD2lo+gI42wAyyoKCjbUEXZvshQUONwb2BwoULhcOHDJLhT9v/io6u7ZrXAFaKa76xsWi4+fP9kq13+K/+m84o8POUcN/+XTkU1UzculIS/o3+ecwC/i3alfypWEHmzCi54/tadeLk14I4N+htdYSqC7nvrE1cG/M6tCP/6c848WvTnjMxePv8gvavxcPtY7H7EJEhW/4l3Yu5j5/d7Ts8K9lby2K9xoVTZOWC2+2PvYtRk+hit+lMfCenaemsa0vx1XepAhQjuGrsPEr6q7J16fVgTgh9Lvrvdz/xneK5P3JppS1sbXoSBeV6+Lt73HKrwsnp6EfNB43XdliccPbqQMan746XCARh4etTHY0y1d4DZYqLLkk4rw2Xziqbfc0p59ZD/DUHN4d7iP7vzcjVh6k4t/jR8D8kp1PrYHyjz6sW9lZHyRB5yaD13v4h8P85TR06OXIdd5r65q79JI9ewz+bE8U/VQeB1RfDPxOHNwCKXSwVEGMDTAxq9T9WHgz2z1cDe9wHtqE+7OdfKW66aD5v5sPknlZ/I0m9axecX9OVQfpfKJnon8wh5LCnCtznjyQZ4eO5/LMosLVvoOu3guMziWkATyZyypeEt+IW9ljBcv0816iU9QV/H4x6/VEKZZHjEqKRHu7VSJDsrOhjzPRRPqjI+KBTx8fK5UHXuzjrbFgbjzz2nyPWvezSraOhJ1rBEiUpjkWz+jR0riX9gaUlWsMx59oq5Y1CtqYhLjLP05n/ER3ccEE96UGlTPa8LrGiHY67zYCH4ofkrd5C9+EB/AJwjyL+gTarvM/j91eem9h1ceOusFFdn7VILnpv54CZpUahhoqIgfpYE27U/R+3kpwdNQFD+UyNqNT3ikvyzQ+NIjnmqKfp1SjZ7d/IUm+zarp7237MdZhn4L9uT1fVJPSg3rEmwXN/OrbXyelfmAnSVF8H3IW5zUS188+8cwAF+c96asDW29TuraBPK6eBo3boZFVW+XX/QY/3xtsZUvkjeZb/m6xqbiW4fzakEeWtOXPKblMNhgQ2uClX+Tx2vunH/cBgj6MWCrOLq3PfFQ96vWg+ihIuynVFeFc36qycUCfgS/1FWh+TYAc/Nv2a+1Ic94XSegmW/wKeCGXu39uh2w4p+Lj7XlT32b4CZZ8XOdVcUvm/km4TPB+jR5SoFkDp3xU+e1R49RT+ZozSfn7nFjCbe0glC4DiVmnHgc6r2HWkxzrjFs3NfHQTEllaieWzn286tMuEyds0iqorBjpoUrkjb5SZDWT9VDU8Jrpf6+cDOkfr7LIoLVMeIn8XcrV3xW+/xBUdwa8i/V4+S6y+wXtckHsEo/4Yc2f+RE17O/nch9Xbbre82T3Dos1BOeMmjwHt2XvF3fWx6zDLz4iY8j9ew9VVjvPA6SmbzF15BxqzBiMIBurw3UeWrSgbNDTzGbvclxWvt4XjN6m+PALc5ee4gR6Mc6Ipqf8QM/cI96ytA1rqtQb8zIfFvvyuNqTJhpL4VXqQ6O3kZXcoDOc2aKfug8/kBfEqDmObQaegxqK4507Fe19yu+XclTbbX4gN7WLU/1Cye16POXr0EZ8dBAU7S8DPd+VjS7wet1+Fw87SUnWCYlKW0+cdJvqCHeB3pDjw71Ax8lvlYfuPXIWx8oGyUf0P+S9p5yvuIhwXDFJ/T/KDOgeqqf+OeyY+Aqov+8ygzYeHg4gxe+a9tOrCcsfJ/zztMyt75l/4rbrnnzKcseuN9vmuWO/a0q66jBhgEfqIE6P1OSKuW/4b6vfjGeElbTPG0I5lfsA3uc9F+LX0/9mNhrz2OXfCIPzRU4Inf73wm8Ri/BA/1nSmwe0eZw52FePKXyH7VMy3yYeebTrk01T1UWfyVzFRf+9zNPAiebkG5/DWP9mp9XYgF6vbC3uRxNVA9RoXmp42NcDsmvew+N5a+K11vvpfyxeu6gK4qyLVaqP6mJ/bD3dcC0pTiR9zSJB9nktPMBHsCmLB4fZVWZ0ML/f9GE6rzp/Zht2QlgChTV8DH2fuHRr6Se8NrKKjRiCgT++7T3U/OY3xc/U3Y88ETdlD9XD11tv4lf2eu19xSGm8f9wDdZWrPCJP0x54UnniOZg91yKj5g0HpMa33vTechsNjEi4r4K5oB1WN0+1+qHrdkxUcJdXSc0nn7a/W4HcGTouqzHHls/H0qSx3eFr2vnob73DzO6lA9Lic2up3npUm1Mwea87TU4QCWRegmcdA98dnH4mnLFGltUe8Shyla7zsP6csbbj4eeeixgLe3HKTV8AMtZSU/gYn1hmZc4D3LGGlTJR77agi9t83TCdEke7U78lCAwV1z87C2vKR5HmhHDN7QgLjjXSuesLzqfSavOeHEksTfvpTY+AgmJyyV7D3e/Al7KztcnnDxZduF7jxH4DDR4+eZj1niE2XrPr55U/195h3xzGlHYC9Z7Vg87oY47nzNvCNeNNXCP1Xt4KJ6Jd6WaOR+WhRHefF+58fOw3PejCu3q7pW3UGE23lXZv/dzTtVTh+6g4VLXvubqSTrctOd/1tqh6hY7LuxnNxIIeGcn5p3fqqZeDszrP6ve2/9VAptGYOt55m/thyf2mI1YdoeG8eNv48UN2dXvHpdNgqupSRD9Z8i7zHKkctKlZt7P/c+cEIRZDuk2S/dVwU5/7d57XkP5PXGrxvfnd+yd7wfFT+2o7lTL9FByXmfWesaf9Ybme1Ui87Hdi668Y/owCKf+PSQ1+Jl9zKWhe2MLxvsvV/bue6pt7LOe84xRuzth7zL3J68guHqT4n2RT/tfTA5bk8UNh7bWxLPkY5aPC6aFz0EQBdNOfxGjwd/lz3EKJs4uFLcpd5etycivYeczq5jacOAqYCi0HfBTzz6Kbn5hofF5MMlr3Pzw6d/Fx8vefg8lTPMP+uUxM/DBW87/8Skl+KXSx739a68M/GaRje8tRc8/p6ap9mAbf/xvG+P1bzfnS713p7xwZz3eTNL+VsOasvhss9n/OwuerPzu3F/4t32a0IblH7QT8e83n0N6X7D250fozIP+fGY93nnp6iGB/z3e58f9j/svD49KT33/Wxum6VjHnM9d8Bb+S7p93r3z9sDHkLPs6e7g9KH/dvvrs8Ozwtex1fqiMcvX/Uhf3vERzxSMId8OD98HvD2kPdHfMLU2h304xH/6KDfZQ2/4WelLgyHy14f9OagHw74ZbN8/D7vDvrxgF8vNv9ln495fcTni81/0Q8HvTvox0PeX2rOiz4f8+aYD8NB7w768ZiP0zF/n4/5rwd9/uP4/wOHV4ghb+WqVQAAAABJRU5ErkJggg==") no-repeat top right;
}

header.main nav, .subcategories {
    font-size: 1.2em;
    margin: 1em 0;
}

header.main nav ul li, .subcategories li {
    display: inline-block;
    margin: .1rem .2rem;
    padding: 0;
}

header.main nav ul li a, .subcategories li a {
    display: inline-block;
    margin: 0;
    padding: .2em .5em;
    color: #006;
    text-decoration: none;
    background: #ddd;
    border-radius: .5rem;
}

header.main nav ul li a:hover, .subcategories li a:hover {
    color: darkred;
    background: #eee;
}

footer.main {
    color: #999;
    margin-top: 1em;
    text-align: center;
}

footer.main a {
    text-decoration: none;
    font-weight: bold;
    color: #666;
}

footer.main a:hover {
    color: #006;
}

footer.main a#garradin {
    padding-left: 20px;
    background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAGFBMVEX///+qjnmcTxWgYzWeWyiysrGzs7Ozs7MzVhJAAAAAB3RSTlMAGtv2e9p5oKuvKgAAAH1JREFUCNcdzLEOwjAMBNCrFDoXEGK3zA906RoifwBLmpVUSrMTpf59DNM9nU4HYNhjzJNlUaUPAzddN54NKU5uJsGoL4CYce9vA3mUJiLEHrURiRUoXQLRM6N2F4jrajcXm9YDJ+Xwx5AegX/Addn82eA4tah6QPwYNe75C+4yHrwP6fqUAAAAAElFTkSuQmCC") no-repeat left top;
    min-height: 16px;
    display: inline-block;
}

.error {
    border-bottom: .2em solid #c00;
    border-radius: .5em;
    background: #fcc;
    padding: .5em;
    margin-bottom: 1em;
    font-size: 1.2em;
    color: #900;
}

.alert {
    border-bottom: .2em solid #cc0;
    border-radius: .5em;
    background: #ffc;
    padding: .5em;
    margin-bottom: 1em;
    font-size: 1.2em;
    color: #990;
}

section.articles article {
    clear: both;
    border-left: .2em solid #ccc;
    border-radius: .5em;
    padding-left: 1em;
}

section.articles article h3, section.articles article h1 {
    margin-bottom: .3em;
}

section.articles article h1 a {
    color: #000;
    text-decoration: none;
    font-weight: normal;
}

section.articles article h3 a {
    color: #009;
    font-weight: normal;
}

section.articles article h3 a:visited {
    color: #669;
}

section.articles article h5 {
    color: #666;
    font-weight: normal;
    font-size: .8em;
    margin-bottom: .3em;
}

section.articles.main aside {
    float: right;
    margin: 1em;
}

section.page article {
    margin-bottom: 1em;
}

article ul, article ol, article blockquote {
    margin-left: 2em;
}

article ul {
    list-style-type: disc;
}

article ol {
    list-style-type: decimal;
}

article dl dd {
    margin: .5em 0 .5em 2em;
}

article img {
    max-width: 100%;
}

article figure {
    text-align: center;
}

article figcaption {
    font-style: italic;
    color: #666;
    margin-top: 2pt;
    font-size: .8em;
}

section.gallery {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    grid-gap: 1.5rem;
    justify-content: center;
    align-items: center;
}

section.gallery figure {
    display: inline-flex;
    justify-content: center;
    align-items: center;
}

article > h1 {
    margin-bottom: 1rem;
}

.contacts * {
    font-size: 1rem;
    display: inline-block;
    font-weight: normal;
    margin: 0;
    margin-right: 1em;
}

.breadcrumbs {
    margin: 1em 0;
}

.breadcrumbs ul li {
    display: inline-block;
}

.breadcrumbs ul li::before {
    content: "»";
    color: #ccc;
    margin: .5em;
}

.breadcrumbs a {
    color: #999;
}

fieldset {
    border: 2px solid #ccc;
    border-radius: .5em;
    padding: 1em;
    margin: 1em;
}

fieldset legend {
    padding: 0 1em;
}

fieldset input {
    padding: .5rem;
    border: 1px solid #999;
    border-radius: .3rem;
    font-size: 1.2em;
}

fieldset input[type=submit] {
    background: #999;
    color: #fff;
    cursor: pointer;
}

input:focus {
    outline: none;
    box-shadow: 0px 0px 5px 2px orange;
}

.search article p b {
    background: #ff9;
    padding: .2em 0;
}

.search-widget {
    float: right;
    margin-top: -1rem;
}

.search-widget input {
    padding: .2em;
    border: 1px solid #999;
    border-radius: .3rem;
    line-height: 1rem;
    line-height: .8rem;
    display: inline-block;
    vertical-align: middle;
}

.search-widget input[type=submit] {
    background: #999;
    font-size: 1.2rem;
    line-height: .8rem;
    color: #fff;
    cursor: pointer;
}

@media handheld, screen and (max-width: 980px) {
    body {
        padding: 0;
    }

    header.nav {
        font-size: .9em;
        margin: 0;
    }

    header.main {
        padding: 0 .2em;
        background-position: center top;
        text-align: center;
    }

    header.main h1 {
        font-size: 2em;
    }

    header.main .contacts {
        text-align: center;
        margin: .5em 0;
    }

    header.main .contacts * {
        font-size: .8em;
        display: block;
        margin: 0;
    }

    .search-widget {
        float: none;
        margin: .5em;
    }

    header.main nav {
        font-size: 1em;
        background: none;
    }

    section.page {
        margin: 0 .3em;
    }

    section.page h1 { font-size: 1.5em; }
    section.page h2 { font-size: 1.3em; }
    section.page h3 { font-size: 1.2em; }
    section.page h4 { font-size: 1em; }
    section.page h5 { font-size: .9em; }
    section.page h6 { font-size: .8em; }

    footer.main {
        background: #eee;
        padding: .2em;
        font-size: .8em;
    }
}

Added src/www/skel-dist/documents.html version [b071506de9].















>
>
>
>
>
>
>
1
2
3
4
5
6
7
<section class="documents">
{{#documents order="name" parent=$parent except_in_text=true}}
	<aside class="fichier">
		<a href="{{$url}}">{{$name}} ({{$type}}, {{$size|size_in_bytes}})</a>
	</aside>
{{/documents}}
</section>

Added src/www/skel-dist/gallery.html version [3e079fae32].



















>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
<section class="gallery">
{{#images order="name" parent=$parent except_in_text=true}}
	<figure>
		<a href="{{$url}}" class="internal-image"><img src="{{$thumb_url}}" alt="{{$name}}" /></a>
	</figure>
{{/images}}
</section>

<script type="text/javascript" src="{{$admin_url}}static/scripts/wiki_gallery.js"></script>

Added src/www/skel-dist/index.html version [e346bb1e71].



























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{{:include file="_head.html"}}

{{#articles order="published DESC" future=false limit=1}}
<section class="articles main">
	<article>
		{{#images parent=$path limit=1}}
		<aside>
			<a href="{{$.url}}"><img src="{{$thumb_url}}" alt="" /></a>
		</aside>
		{{/images}}

		<h1><a href="{{ $url }}">{{ $title }}</a></h1>
		<h5>Posté : {{ $published|relative_date }}</h5>
		<p>{{ $html|raw|strip_tags|truncate:600 }}</p>
	</article>
</section>
{{/articles}}

{{#articles order="published DESC" future=false begin=1 limit=9}}
<section class="articles">
	<article>
		<h3><a href="{{ $url }}">{{ $title }}</a></h3>
		<h5>Posté : {{ $published|relative_date }}</h5>
		<p>{{ $html|raw|strip_tags|truncate:200 }}</p>
	</article>
</section>
{{/articles}}

{{:include file="_foot.html"}}

Added src/www/skel-dist/search.html version [e6cf225932].







































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{{:include file="_head.html" title="Recherche"}}

<section class="articles search">
	<form method="get" action="">
		<fieldset>
			<legend>Rechercher dans le site</legend>
			<p>
				<input type="search" name="search" value="{{ $_GET.search }}" />
				<input type="submit" value="Chercher" />
			</p>
		</fieldset>
	</form>

	{{#pages search=$_GET.search future=false count=true}}
		{{if !$count}}
			<p class="alert">Aucun résultat trouvé.</p>
		{{else}}
			<p class="alert">{{if $count == 1}}1 résultat trouvé{{else}}{{$count}} résultats trouvés{{/if}}.</p>

			{{#pages search=$_GET.search future=false}}
			<article>
				<h3><a href="{{$url}}">{{$title}}</a></h3>
				<h5>{{$published|date_long}}</h5>
				<p>{{$snippet|raw}}</p>
			</article>
			{{else}}
			<p class="alert">
				Aucun résultat trouvé.
			</p>
			{{/pages}}
		{{/if}}
	{{/pages}}
</section>

{{:include file="_foot.html"}}

Deleted src/www/squelettes-dist/article.html version [76fac266de].

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
<INCLURE{entete.html}>

<B_article>
	<article>
		<BOUCLE_article(ARTICLES){uri}>
		<h1>#TITRE</h1>
		<div class="corps">
			[(#TEXTE*|formatter_texte)]
		</div>
		<INCLURE{galerie.html}>
		<INCLURE{documents.html}>
		</BOUCLE_article>
	</article>

	<B_enfants>
	<section class="articles">
		<BOUCLE_enfants(PAGES){parent}{par uri}>
		<article>
			<h3><a href="#URL">#TITRE</a></h3>
			<p>[(#TEXTE|supprimer_skriv|couper{200})]</p>
		</article>
		</BOUCLE_enfants>
	</section>
	</B_enfants>
</B_article>
<p class="error">
	Cette page n'existe pas.
</p>
<//B_article>

<INCLURE{pied.html}>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































Deleted src/www/squelettes-dist/atom.xml version [7a395435ce].

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
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="fr">

	<title type="html">[(#NOM_ASSO|echapper_xml)]</title>
	<link href="[(#URL_ATOM|echapper_xml)]" rel="self"/>
	<link href="[(#URL_RACINE|echapper_xml)]" rel="alternate" type="text/html" title="[(#NOM_ASSO|echapper_xml)]" />

	<BOUCLE_derniere(PAGES){par date_creation}{inverse}{0,1}>
	<updated>[(#DATE_CREATION|date_atom)]</updated>
	</BOUCLE_derniere>

	<author>
		<name>[(#NOM_ASSO|echapper_xml)]</name>
	</author>

	<id>[(#URL_RACINE|echapper_xml)]</id>
	<generator uri="http://dev.kd2.org/garradin/">Garradin</generator>

	<BOUCLE_actu(PAGES){par date_creation}{inverse}{0,20}>
	<entry>
		<title>[(#TITRE|echapper_xml)]</title>
		<link href="[(#URL|echapper_xml)]" rel="alternate" type="text/html" title="[(#TITRE|echapper_xml)]" />
		<id>[(#URL|echapper_xml)]</id>
		<updated>[(#DATE_CREATION|date_atom)]</updated>
		<author><name>[(#NOM_ASSO|echapper_xml)]</name></author>
		<content type="html">
			[(#TEXTE*|formatter_texte|echapper_xml)]
		</content>
	</entry>
	</BOUCLE_actu>

</feed>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































Deleted src/www/squelettes-dist/default.css version [4d22b01b8b].

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
body, form, p, div, hr, fieldset, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6 {
    margin: 0;
    padding: 0;
}
h1  { font-size: 2em; }
h2  { font-size: 1.5em; }
h3  { font-size: 1.2em; }
h4  { font-size: 1em; }
h5  { font-size: 0.9em; }
h6  { font-size: 0.8em; }
ul, ol { list-style-type: none; }
article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; }

body {
    font-size: 100.01%;
    color: #000;
    font-family: "Trebuchet MS", Helvetica, Sans-serif;
    background: #fff;
}

header.nav {
    background: #ddd;
    border-bottom: 1px solid #999;
    border-top: .3em solid #666;
    text-align: center;
    padding-top: .3em;
    font-size: 1.1em;
}

header.nav li {
    display: inline-block;
    padding: .3em .5em;
    margin-bottom: -1px;
}

header.nav li a {
    padding: .3em .5em;
    text-transform: uppercase;
    color: #666;
}

header.nav li.current a {
    background: #fff;
    border: .1em solid #999;
    border-bottom: none;
    border-top-left-radius: .5em;
    border-top-right-radius: .5em;
}

header.nav li a:hover {
    color: #000;
}

header.main, footer.main, section.page {
    max-width: 950px;
    margin: 0 auto;
}

header.main h1 {
    color: #9c4f15;
    padding: .2em 0 .1em 0;
    font-size: 4em;
    font-family: Georgia, "Times New Roman", Times, serif;
    font-weight: normal;
}

header.main h1 a {
    color: #9c4f15;
    text-decoration: none;
}

header.main h4 {
    color: #666;
    font-family: Georgia, "Times New Roman", Times, serif;
    font-weight: normal;
    margin-bottom: 2em;
}

header.main {
    margin-bottom: 1em;
    background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAXMAAADPAQMAAAA9C6NrAAAABlBMVEXx9PD+//zYDo7WAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gEIER05obn78wAACb1JREFUaN7V2TuOHLkZAGBSHKgmMEyFCgRRR1CoYD2lo+gI42wAyyoKCjbUEXZvshQUONwb2BwoULhcOHDJLhT9v/io6u7ZrXAFaKa76xsWi4+fP9kq13+K/+m84o8POUcN/+XTkU1UzculIS/o3+ecwC/i3alfypWEHmzCi54/tadeLk14I4N+htdYSqC7nvrE1cG/M6tCP/6c848WvTnjMxePv8gvavxcPtY7H7EJEhW/4l3Yu5j5/d7Ts8K9lby2K9xoVTZOWC2+2PvYtRk+hit+lMfCenaemsa0vx1XepAhQjuGrsPEr6q7J16fVgTgh9Lvrvdz/xneK5P3JppS1sbXoSBeV6+Lt73HKrwsnp6EfNB43XdliccPbqQMan746XCARh4etTHY0y1d4DZYqLLkk4rw2Xziqbfc0p59ZD/DUHN4d7iP7vzcjVh6k4t/jR8D8kp1PrYHyjz6sW9lZHyRB5yaD13v4h8P85TR06OXIdd5r65q79JI9ewz+bE8U/VQeB1RfDPxOHNwCKXSwVEGMDTAxq9T9WHgz2z1cDe9wHtqE+7OdfKW66aD5v5sPknlZ/I0m9axecX9OVQfpfKJnon8wh5LCnCtznjyQZ4eO5/LMosLVvoOu3guMziWkATyZyypeEt+IW9ljBcv0816iU9QV/H4x6/VEKZZHjEqKRHu7VSJDsrOhjzPRRPqjI+KBTx8fK5UHXuzjrbFgbjzz2nyPWvezSraOhJ1rBEiUpjkWz+jR0riX9gaUlWsMx59oq5Y1CtqYhLjLP05n/ER3ccEE96UGlTPa8LrGiHY67zYCH4ofkrd5C9+EB/AJwjyL+gTarvM/j91eem9h1ceOusFFdn7VILnpv54CZpUahhoqIgfpYE27U/R+3kpwdNQFD+UyNqNT3ikvyzQ+NIjnmqKfp1SjZ7d/IUm+zarp7237MdZhn4L9uT1fVJPSg3rEmwXN/OrbXyelfmAnSVF8H3IW5zUS188+8cwAF+c96asDW29TuraBPK6eBo3boZFVW+XX/QY/3xtsZUvkjeZb/m6xqbiW4fzakEeWtOXPKblMNhgQ2uClX+Tx2vunH/cBgj6MWCrOLq3PfFQ96vWg+ihIuynVFeFc36qycUCfgS/1FWh+TYAc/Nv2a+1Ic94XSegmW/wKeCGXu39uh2w4p+Lj7XlT32b4CZZ8XOdVcUvm/km4TPB+jR5SoFkDp3xU+e1R49RT+ZozSfn7nFjCbe0glC4DiVmnHgc6r2HWkxzrjFs3NfHQTEllaieWzn286tMuEyds0iqorBjpoUrkjb5SZDWT9VDU8Jrpf6+cDOkfr7LIoLVMeIn8XcrV3xW+/xBUdwa8i/V4+S6y+wXtckHsEo/4Yc2f+RE17O/nch9Xbbre82T3Dos1BOeMmjwHt2XvF3fWx6zDLz4iY8j9ew9VVjvPA6SmbzF15BxqzBiMIBurw3UeWrSgbNDTzGbvclxWvt4XjN6m+PALc5ee4gR6Mc6Ipqf8QM/cI96ytA1rqtQb8zIfFvvyuNqTJhpL4VXqQ6O3kZXcoDOc2aKfug8/kBfEqDmObQaegxqK4507Fe19yu+XclTbbX4gN7WLU/1Cye16POXr0EZ8dBAU7S8DPd+VjS7wet1+Fw87SUnWCYlKW0+cdJvqCHeB3pDjw71Ax8lvlYfuPXIWx8oGyUf0P+S9p5yvuIhwXDFJ/T/KDOgeqqf+OeyY+Aqov+8ygzYeHg4gxe+a9tOrCcsfJ/zztMyt75l/4rbrnnzKcseuN9vmuWO/a0q66jBhgEfqIE6P1OSKuW/4b6vfjGeElbTPG0I5lfsA3uc9F+LX0/9mNhrz2OXfCIPzRU4Inf73wm8Ri/BA/1nSmwe0eZw52FePKXyH7VMy3yYeebTrk01T1UWfyVzFRf+9zNPAiebkG5/DWP9mp9XYgF6vbC3uRxNVA9RoXmp42NcDsmvew+N5a+K11vvpfyxeu6gK4qyLVaqP6mJ/bD3dcC0pTiR9zSJB9nktPMBHsCmLB4fZVWZ0ML/f9GE6rzp/Zht2QlgChTV8DH2fuHRr6Se8NrKKjRiCgT++7T3U/OY3xc/U3Y88ETdlD9XD11tv4lf2eu19xSGm8f9wDdZWrPCJP0x54UnniOZg91yKj5g0HpMa33vTechsNjEi4r4K5oB1WN0+1+qHrdkxUcJdXSc0nn7a/W4HcGTouqzHHls/H0qSx3eFr2vnob73DzO6lA9Lic2up3npUm1Mwea87TU4QCWRegmcdA98dnH4mnLFGltUe8Shyla7zsP6csbbj4eeeixgLe3HKTV8AMtZSU/gYn1hmZc4D3LGGlTJR77agi9t83TCdEke7U78lCAwV1z87C2vKR5HmhHDN7QgLjjXSuesLzqfSavOeHEksTfvpTY+AgmJyyV7D3e/Al7KztcnnDxZduF7jxH4DDR4+eZj1niE2XrPr55U/195h3xzGlHYC9Z7Vg87oY47nzNvCNeNNXCP1Xt4KJ6Jd6WaOR+WhRHefF+58fOw3PejCu3q7pW3UGE23lXZv/dzTtVTh+6g4VLXvubqSTrctOd/1tqh6hY7LuxnNxIIeGcn5p3fqqZeDszrP6ve2/9VAptGYOt55m/thyf2mI1YdoeG8eNv48UN2dXvHpdNgqupSRD9Z8i7zHKkctKlZt7P/c+cEIRZDuk2S/dVwU5/7d57XkP5PXGrxvfnd+yd7wfFT+2o7lTL9FByXmfWesaf9Ybme1Ui87Hdi668Y/owCKf+PSQ1+Jl9zKWhe2MLxvsvV/bue6pt7LOe84xRuzth7zL3J68guHqT4n2RT/tfTA5bk8UNh7bWxLPkY5aPC6aFz0EQBdNOfxGjwd/lz3EKJs4uFLcpd5etycivYeczq5jacOAqYCi0HfBTzz6Kbn5hofF5MMlr3Pzw6d/Fx8vefg8lTPMP+uUxM/DBW87/8Skl+KXSx739a68M/GaRje8tRc8/p6ap9mAbf/xvG+P1bzfnS713p7xwZz3eTNL+VsOasvhss9n/OwuerPzu3F/4t32a0IblH7QT8e83n0N6X7D250fozIP+fGY93nnp6iGB/z3e58f9j/svD49KT33/Wxum6VjHnM9d8Bb+S7p93r3z9sDHkLPs6e7g9KH/dvvrs8Ozwtex1fqiMcvX/Uhf3vERzxSMId8OD98HvD2kPdHfMLU2h304xH/6KDfZQ2/4WelLgyHy14f9OagHw74ZbN8/D7vDvrxgF8vNv9ln495fcTni81/0Q8HvTvox0PeX2rOiz4f8+aYD8NB7w768ZiP0zF/n4/5rwd9/uP4/wOHV4ghb+WqVQAAAABJRU5ErkJggg==") no-repeat top right;
}

header.main nav {
    font-size: 1.2em;
    margin: 1em 0;
    padding: 0 1em;
    background: #ddd;
    border-radius: .5em;
}

header.main nav ul li {
    display: inline-block;
    margin: -.3em .2em;
}

header.main nav ul li a {
    display: inline-block;
    border-radius: 25%;
    padding: .5em .5em .4em .5em;
    color: #006;
    text-decoration: none;
    background: #ddd;
    border-bottom: .1em solid #ddd;
}

header.main nav ul li a:hover {
    color: #00f;
    border-bottom: .1em solid #000;
}

footer.main {
    color: #999;
    margin-top: 1em;
    text-align: center;
}

footer.main a {
    text-decoration: none;
    font-weight: bold;
    color: #666;
}

footer.main a:hover {
    color: #006;
}

footer.main a#garradin {
    padding-left: 20px;
    background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAGFBMVEX///+qjnmcTxWgYzWeWyiysrGzs7Ozs7MzVhJAAAAAB3RSTlMAGtv2e9p5oKuvKgAAAH1JREFUCNcdzLEOwjAMBNCrFDoXEGK3zA906RoifwBLmpVUSrMTpf59DNM9nU4HYNhjzJNlUaUPAzddN54NKU5uJsGoL4CYce9vA3mUJiLEHrURiRUoXQLRM6N2F4jrajcXm9YDJ+Xwx5AegX/Addn82eA4tah6QPwYNe75C+4yHrwP6fqUAAAAAElFTkSuQmCC") no-repeat left top;
    min-height: 16px;
    display: inline-block;
}

.error {
    border-bottom: .2em solid #c00;
    border-radius: .5em;
    background: #fcc;
    padding: .5em;
    margin-bottom: 1em;
    font-size: 1.2em;
    color: #900;
}

section.articles article {
    border-left: .2em solid #ccc;
    border-radius: .5em;
    padding-left: 1em;
}

section.articles article h3, section.articles article h1 {
    margin-bottom: .3em;
}

section.articles article h1 a {
    color: #000;
    text-decoration: none;
    font-weight: normal;
}

section.articles article h3 a {
    color: #009;
    font-weight: normal;
}

section.articles article h3 a:visited {
    color: #669;
}

section.articles article h5 {
    color: #666;
    font-weight: normal;
    font-size: .8em;
    margin-bottom: .3em;
}

section.page article {
    margin-bottom: 1em;
}

article h1, article h2, article h3, article h4, article p {
    margin-bottom: .8em;
}

article ul, article ol, article blockquote {
    margin-left: 2em;
}

article ul {
    list-style-type: disc;
}

article ol {
    list-style-type: decimal;
}

article dl dd {
    margin: .5em 0 .5em 2em;
}

article img {
    max-width: 100%;
}

article figure {
    text-align: center;
}

article figcaption {
    font-style: italic;
    color: #666;
    margin-top: 2pt;
    font-size: .8em;
}

article figure.image.centre {
    max-width: 500px;
    margin: 0 auto 8pt auto;
}

article figure.image.gauche {
    max-width: 200px;
    float: left;
    margin: 0 8pt 4pt 0;
    clear: left;
}

article figure.image.droite {
    max-width: 200px;
    float: right;
    margin: 0 0 4pt 8pt;
    clear: right;
}

section.galerie {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    flex-direction: row;
}

section.galerie figure {
    display: inline-flex;
}

aside.fichier {
    margin: 1em;
}

aside.fichier small {
    opacity: 0.7;
}

aside.fichier a {
    display: inline-block;
    margin-right: 1em;
    padding: .5em;
    padding-left: 1.8em;
    border: 1px solid #999;
    background: #eee;
    border-radius: .5em;
    background-repeat: no-repeat;
    background-position: .5em center;
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAAQCAYAAADAvYV+AAAAd0lEQVQoz2NgQAVNQDwDCTcw4AF3gPg/Er4xSBWnAXEHFL9HU/wWSS4FpFgZiJ+jKULHT4BYAWa6LhC/w6HwNRBrojvHEoi/oCn8BMQmuDzoBsQ/oQq/A7E9AwEQDMQ/gNiHgUggx0AN8IVI/AGkeA+ReCdJTgAAgMhKhf6mzTIAAAAASUVORK5CYII=");
    transition: background-color .2s, color .2s;
}

.imageBrowser {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    background: rgb(0, 0, 0);
    background: rgba(0, 0, 0, 0.75);
    text-align: center;
    transition: opacity .5s;
}

.imageBrowser figure {
    margin: 5%;
    width: 90%;
    height: 90%;
    transition: all .5s;
}

.imageBrowser figure img {
    top: 50%;
    transform: translateY(-50%);
    position: relative;
    max-width: 100%;
    width: auto;
    height: auto;
    background: #fff;
    padding: 2%;
    max-height: 90%;
    max-width: 90%;
    border-radius: .5em;
    cursor: pointer;
}

@media handheld, screen and (max-width: 980px) {
    body {
        padding: 0;
    }

    header.nav {
        font-size: .9em;
        margin: 0;
    }

    header.main {
        padding: 0 .2em;
        background-position: center top;
        text-align: center;
    }

    header.main h1 {
        font-size: 2em;
    }

    header.main h4 {
        margin-bottom: 1em;
    }

    header.main nav {
        font-size: 1em;
        padding: 0;
    }

    section.page {
        margin: 0 .3em;
    }

    section.page h1 { font-size: 1.5em; }
    section.page h2 { font-size: 1.3em; }
    section.page h3 { font-size: 1.2em; }
    section.page h4 { font-size: 1em; }
    section.page h5 { font-size: .9em; }
    section.page h6 { font-size: .8em; }

    footer.main {
        background: #eee;
        padding: .2em;
        font-size: .8em;
    }
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































































































































































































































































































































































































































































Deleted src/www/squelettes-dist/documents.html version [3338b0694f].

1
2
3
4
5
6
7
8
9
<B_documents>
	<section class="documents">
	<BOUCLE_documents(DOCUMENTS){article}{par nom}{sauf_mention}>
		<aside class="fichier">
			<a href="#URL">#NOM (#TYPE, [(#TAILLE|taille_en_octets)])</a>
		</aside>
	</BOUCLE_documents>
	</section>
</B_documents>
<
<
<
<
<
<
<
<
<


















Deleted src/www/squelettes-dist/entete.html version [5a1592d699].

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
<!DOCTYPE html>
<html lang="fr">
<head>
	<meta charset="utf-8" />
	<title>[(#TITRE) - ]#NOM_ASSO</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=device-dpi" />
	<link rel="stylesheet" type="text/css" href="[(#URL_CSS_DEFAUT)]?2017" media="screen,projection,handheld" />
	<link rel="alternate" type="application/atom+xml" title="Actualité de #NOM_ASSO" href="#URL_ATOM" />
	<!--[if lte IE 8]>
	<script type="text/javascript">
	'article aside footer header nav section time'.replace(/\w+/g,function(n){document.createElement(n)})
	</script>
	<![endif]-->
</head>

<body>

<header class="nav">
	<nav>
		<ul>
			<li class="current"><a href="#URL_RACINE">Accueil</a></li>
			<li><a href="#URL_ADMIN">Administration</a></li>
		</ul>
	</nav>
</header>

<header class="main">
	<h1><a href="#URL_RACINE">#NOM_ASSO</a></h1>
	[<h4>(#ADRESSE_ASSO)</h4>]

	<B_menu>
	<nav>
		<ul>
		<BOUCLE_menu(RUBRIQUES){parent=0}{par titre}>
			<li><a href="#URL/">#TITRE</a></li>
		</BOUCLE_menu>
		</ul>
	</nav>
	</B_menu>
</header>

<section class="page">
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































Deleted src/www/squelettes-dist/galerie.html version [bedc2aaab8].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<B_galerie>
	<section class="galerie">
	<BOUCLE_galerie(IMAGES){article}{par nom}{sauf_mention}>
		<figure>
			<a href="#URL" class="internal-image"><img src="#MINIATURE" alt="#NOM" /></a>
		</figure>
	</BOUCLE_galerie>
	</section>
</B_galerie>

<BOUCLE_galerie_script(IMAGES){article}{0,1}>
	<!-- N'inclure le script de galerie que s'il y a au moins une image dans la page -->
	<script type="text/javascript" src="[(#URL_ADMIN)static/scripts/wiki_gallery.js"></script>
</BOUCLE_galerie_script>
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























Deleted src/www/squelettes-dist/index.html version [abe89f9bfb].

1
<!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>
<


Deleted src/www/squelettes-dist/pied.html version [25cd019401].

1
2
3
4
5
6
7
8
</section>

<footer class="main">
	Propulsé par <a href="http://garradin.eu/" id="garradin">Garradin</a> — logiciel libre de gestion associative
</footer>

</body>
</html>
<
<
<
<
<
<
<
<
















Deleted src/www/squelettes-dist/rubrique.html version [99a59756e7].

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
<BOUCLE_rubrique(RUBRIQUES){uri}>

	<INCLURE{entete.html}>

	<article class="rubrique">
		<h1>#TITRE</h1>
		<div class="corps">
			[(#TEXTE*|formatter_texte)]
		</div>
		<INCLURE{galerie.html}>
		<INCLURE{documents.html}>
	</article>

	<section class="articles">
	<BOUCLE_articles(ARTICLES){rubrique}{par uri}>
		<article>
		<h3><a href="#URL">#TITRE</a></h3>
		<p>[(#TEXTE|supprimer_skriv|couper{200})]</p>
		</article>
	</BOUCLE_articles>
	</section>

	<INCLURE{pied.html}>

</BOUCLE_rubrique>

	<INCLURE{entete.html}>
	<p class="error">
		Cette page n'existe pas.
	</p>
	<INCLURE{pied.html}>

<//B_rubrique>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































Deleted src/www/squelettes-dist/sommaire.html version [570a872763].

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
<INCLURE{entete.html}>

<BOUCLE_une(ARTICLES){par date}{inverse}{0,1}>
<section class="articles">
	<article>
	<h1><a href="#URL">#TITRE</a></h1>
	<h5>Posté : [(#DATE_CREATION|date_intelligente)]</h5>
	<p>[(#TEXTE|formatter_texte)]</p>
	</article>
</section>
</BOUCLE_une>

<B_derniers>
	<section class="articles">
	<BOUCLE_derniers(ARTICLES){par date}{inverse}{1,9}>
		<article>
		<h3><a href="#URL">#TITRE</a></h3>
		<h5>Posté : [(#DATE_CREATION|date_intelligente)]</h5>
		<p>[(#TEXTE|supprimer_skriv|couper{200})]</p>
		</article>
	</BOUCLE_derniers>
	</section>
</B_derniers>

<INCLURE{pied.html}>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































Deleted src/www/squelettes/index.html version [abe89f9bfb].

1
<!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>
<


Deleted tests/phantom/01-installation.js version [042769244d].

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
/*jshint strict:false*/
/*global CasperError, casper, console, phantom, require*/

casper.test.begin('Installation', 3, function suite(test) {
    casper.start("http://localhost:8080/", function() {
        test.assertTitle("Garradin - Installation", "Page installation");
        test.assertExists('form', "Formulaire présent");
        this.fillSelectors('form', {
            '#f_nom_asso':          "Garradin",
            '#f_email_asso':        "asso@demo.garradin.eu",
            '#f_adresse_asso':      "15 rue du Logiciel Libre\n21000 DIJON",
            '#f_nom_membre':        "Ada Lovelace",
            '#f_cat_membre':        "Bureau",
            '#f_email_membre':      "ada@demo.garradin.eu",
            '#f_passe_membre':      "Garradin c'est chouette",
            '#f_repasse_membre':    "Garradin c'est chouette"
        }, false);
        this.click('form input[type=submit]');
    });

    casper.then(function() {
        if (this.getCurrentUrl().match(/login\.php/))
        {
            test.pass("Installation réussie.");
        }
        else
        {
            test.error(this.fetchText('p.error'));
        }
    });

    casper.run(function () {
        test.done();
    });
});
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































Deleted tests/phantom/10-login.js version [9e07ca2ad5].

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
/*jshint strict:false*/
/*global CasperError, casper, console, phantom, require*/

casper.test.begin('Login', 3, function suite(test) {
    casper.start("http://localhost:8080/admin/login.php", function() {
        test.assertTitle("Connexion", "Page de connexion");
        test.assertExists('form', "Formulaire présent");
        this.fillSelectors('form', {
            '#f_id':                "ada@demo.garradin.eu",
            '#f_passe':             "Garradin c'est chouette",
        }, false);
        this.click('form input[type=submit]');
    });

    casper.then(function() {
        if (this.getCurrentUrl().match(/\/$/))
        {
            test.pass("Connexion réussie.");
        }
        else
        {
            test.error(this.fetchText('p.error'));
        }
    });

    casper.run(function () {
        test.done();
    });
});
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































Deleted tests/phantom/11-add-member.js version [d82bb90f60].

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
/*jshint strict:false*/
/*global CasperError, casper, console, phantom, require*/

casper.test.begin('Ajout membre', 3, function suite(test) {
    casper.start("http://localhost:8080/admin/membres/ajouter.php", function() {
        test.assertTitle("Ajouter un membre", "Page OK");
        test.assertExists('form', "Formulaire présent");
        this.fillSelectors('form', {
            '#f_nom':               "Gaston Lagaffe",
            '#f_email':             "gaston@demo.garradin.eu",
            '#f_adresse':           "42 rue Spirou",
            '#f_ville':             "Bruxelles",
            '#f_code_postal':       "3001",
            '#f_pays':              "BE",
            '#f_telephone':         "01 02 03 04 05",
        }, false);
        this.click('#password_suggest');
        this.click('form input[type=submit]');
    });

    casper.then(function() {
        if (this.getCurrentUrl().match(/fiche\.php\?id=/))
        {
            test.pass("Ajout réussi.");
        }
        else
        {
            test.error(this.fetchText('p.error'));
        }
    });

    casper.run(function () {
        test.done();
    });
});
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































Deleted tests/phantom/12-edit-member.js version [9ba6b617ca].

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
/*jshint strict:false*/
/*global CasperError, casper, console, phantom, require*/

casper.test.begin('Modif Membre', 3, function suite(test) {
    casper.start("http://localhost:8080/admin/membres/modifier.php?id=2", function() {
        test.assertTitle("Modifier un membre", "Page OK");
        test.assertExists('form', "Formulaire présent");
        this.fillSelectors('form', {
            '#f_nom':               "Pacôme De Champignac",
            '#f_email':             "comte@demo.garradin.eu",
            '#f_adresse':           "Château",
            '#f_ville':             "Champignac",
            '#f_code_postal':       "12070",
            '#f_pays':              "FR",
            '#f_telephone':         "+32777229929",
        }, false);
        this.click('#password_suggest');
        this.click('form input[type=submit]');
    });

    casper.then(function() {
        if (this.getCurrentUrl().match(/fiche\.php\?id=/))
        {
            test.pass("Modif réussie.");
        }
        else
        {
            test.error(this.fetchText('p.error'));
        }
    });

    casper.run(function () {
        test.done();
    });
});
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































Deleted tests/phantom/13-delete-member.js version [1ddf5215aa].

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
/*jshint strict:false*/
/*global CasperError, casper, console, phantom, require*/

casper.test.begin('Login', 3, function suite(test) {
    casper.start("http://localhost:8080/admin/membres/supprimer.php?id=2", function() {
        test.assertTitle("Supprimer un membre", "Page OK");
        test.assertExists('form', "Formulaire présent");
        this.click('form input[type=submit]');
    });

    casper.then(function() {
        if (this.getCurrentUrl().match(/\/membres\/$/))
        {
            test.pass("Suppression OK");
        }
        else
        {
            test.error(this.fetchText('p.error'));
        }
    });

    casper.run(function () {
        test.done();
    });
});
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































Deleted tests/phantom/14-add-cotisation.js version [4e5efdd1ce].

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
/*jshint strict:false*/
/*global CasperError, casper, console, phantom, require*/

casper.test.begin('Ajout cotise', 3, function suite(test) {
	casper.start("http://localhost:8080/admin/membres/cotisations/", function() {
		test.assertTitle("Cotisations", "Page OK");
		test.assertExists('form', "Formulaire présent");
		this.click('#f_periodicite_jours');
		this.click('#f_categorie');
		this.fillSelectors('form', {
			'#f_intitule':
				'Cotisation normale',
			'#f_montant':
				'15.00',
			'#f_id_categorie_compta':
				'18',
			'#f_duree':
				'300',
		}, false);
		this.click('form input[type=submit]');
	});

	casper.thenOpen('http://localhost:8080/admin/membres/cotisations/voir.php?id=1', function() {
		test.assertTitle("Membres ayant cotisé", "Cotisation OK");
	});

	casper.run(function () {
		test.done();
	});
});
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































Deleted tests/phantom/README version [00c8746857].

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
Les tests de Garradin sont écrits en Javascript à l'aide de CasperJS.

CasperJS peut utiliser Phantom.js pour émuler un navigateur webkit ou SlimeJS pour un navigateur Gecko.

=== Installer l'environnement de test ===

1. Installer Phantom.js
    - apt-get install phantomjs/unstable
    - ou depuis http://phantomjs.org/download.html
2. (si installation manuelle) mettre Phantom.js dans le $PATH
3. Installer CasperJS:
    $ git clone git://github.com/n1k0/casperjs.git
4. Mettre CasperJS dans le $PATH

=== Lancer un test ===

1. Lancer un serveur php sur localhost:8080 qui pointe sur le www/ de Garradin
2. Lancer le test avec par exemple :
    $ phantomjs test 02-login.js

=== Lancer tous les tests ===

 $ ./run-all.sh

Cela va :
- télécharger le trunk de Garradin dans /tmp/garradin
- télécharger les dépendances
- lancer chacun des tests JS avec CasperJS dans l'ordre indiqué par le numéro

Pour utiliser une version locale de Garradin plutôt que de laisser télécharger le trunk 
il suffit de faire un lien symbolique de /tmp/garradin vers le code local.
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































Deleted tests/phantom/run.sh version [c2ecdca281].

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
#!/bin/sh

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"

if [ -f $SCRIPTPATH/config.sh ]
then
    . $SCRIPTPATH/config.sh
fi

if [ "$1" = "--reset" ]
then
    rm -rf $TESTDIR
fi

if [ ! -d $TESTDIR ]
then
    mkdir -p $TESTDIR
    cd $TESTDIR
    fossil clone https://fossil.kd2.org/garradin/ garradin.fossil
    fossil open garradin.fossil
    sh tools/setup_dependencies.sh
    cd $SCRIPTPATH
fi

if [ "$1" != "--no-install" ]
then
	rm -rf $TESTDIR/src/cache
	rm -rf $TESTDIR/src/*.sqlite
fi

php -S localhost:8080 -t $TESTDIR/src/www &
PHP_PID=$!

if [ "$1" != "--no-install" ]
then
	$CASPERJS test 0*.js
fi

$CASPERJS --cookies-file=$TESTDIR/cookies.txt test 1*.js

kill $!
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































Deleted tests/phantom/syntax.sh version [9f1c94329e].

1
2
3
4
5
6
7
8
#!/bin/sh

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"

cd $SCRIPTPATH
cd ../src

find . -name '*.php' -exec php -l '{}' \; | fgrep -v 'No syntax error'
<
<
<
<
<
<
<
<
















Modified tests/phpstan.neon from [e5c89f56d6] to [9d90dee4cf].

10
11
12
13
14
15
16
17
18






    excludes_analyse:
      - ../src/include/lib/KD2
    reportUnmatchedIgnoredErrors: false
    ignoreErrors:
        - '#Access to protected property Garradin\\Entities#'
        - '#Access to an undefined property KD2\\DB\\AbstractEntity#'
        -
          message: '#Variable \$(tpl|form|session|user|session|wiki|config|membres) might not be defined#'
          path: ../src/www/*













|

>
>
>
>
>
>
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    excludes_analyse:
      - ../src/include/lib/KD2
    reportUnmatchedIgnoredErrors: false
    ignoreErrors:
        - '#Access to protected property Garradin\\Entities#'
        - '#Access to an undefined property KD2\\DB\\AbstractEntity#'
        -
          message: '#Variable \$(tpl|form|session|user|session|wiki|config|membres|current_year) might not be defined#'
          path: ../src/www/*
        -
          message: '#Constant CURRENT_YEAR_ID not found#'
          path: ../src/www/admin/acc/*

includes:
	- phar://phpstan.phar/conf/bleedingEdge.neon

Deleted tests/run.sh version [476c017c61].

1
2
3
4
5
#!/bin/bash

DIR="$(dirname "${BASH_SOURCE[0]}")"

find "$DIR" -type f -name '*.php' -exec php "{}" \;
<
<
<
<
<










Modified tests/unit_tests/01_basic/paths.php from [10b0dc1a36] to [819d6c04bf].

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

namespace Garradin;
use KD2\Test;

require_once INIT;

Test::assert(defined('Garradin\ROOT'));
Test::assert(is_readable(ROOT));

Test::assert(defined('Garradin\PLUGINS_ROOT'));
Test::assert(is_readable(PLUGINS_ROOT));

Test::assert(defined('Garradin\DATA_ROOT'));
Test::assert(is_readable(DATA_ROOT));
Test::assert(is_writeable(DATA_ROOT));

Test::assert(defined('Garradin\CACHE_ROOT'));
Test::assert(is_readable(CACHE_ROOT));
Test::assert(is_writeable(CACHE_ROOT));












<


<
<


<
<
<
1
2
3
4
5
6
7
8
9
10
11

12
13


14
15



<?php

namespace Garradin;
use KD2\Test;

require_once INIT;

Test::assert(defined('Garradin\ROOT'));
Test::assert(is_readable(ROOT));

Test::assert(defined('Garradin\PLUGINS_ROOT'));


Test::assert(defined('Garradin\DATA_ROOT'));



Test::assert(defined('Garradin\CACHE_ROOT'));