Overview
Comment:Merge trunk
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | templates
Files: files | file ages | folders
SHA3-256: 1621418cf07f40da6c3e5a7e29bc7bf2c4ec57002b65ab6c005dba88cadb0e4a
User & Date: bohwaz on 2021-10-28 02:02:39
Other Links: branch diff | manifest | tags
Context
2021-11-14
14:45
Merge trunk check-in: b74facc72e user: bohwaz tags: templates
2021-10-28
02:02
Merge trunk check-in: 1621418cf0 user: bohwaz tags: templates
00:56
New stable release check-in: 0a2988ef3f user: bohwaz tags: trunk, stable, 1.1.12
2021-01-14
13:36
Some ideas on documents templates check-in: 86ce8c926c user: bohwaz tags: templates
Changes

Modified archives/1.0.0_schema.sql from [4710567bc0] to [292ae06778].

262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    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);
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,








|







262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    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,

287
288
289
290
291
292
293

294
295
296
297
298
299
300

    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_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
(







>







287
288
289
290
291
292
293
294
295
296
297
298
299
300
301

    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
(

Modified debian/makedeb.sh from [e75e803576] to [0cffd3a1a4].

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
    echo "Generating ${CONTROL}..."
    cat <<EOF > ${CONTROL}
Package: ${PACKAGE_DEBNAME}
Section: web
Priority: optional
Maintainer: Garradin <garradin@kd2.org>
Architecture: ${DEB_ARCH_NAME}
Depends: dash | bash, php-cli (>=7.2), php-sqlite3
Version: ${PACKAGE_DEB_VERSION}
Suggests: www-browser, php-gd
Homepage: http://dev.kd2.org/garradin/
Description: Garradin is a tool to manage non-profit organizations.
 It's only available in french.
Description-fr: Gestionnaire d'association en interface web ou CLI.
 Garradin est un gestionnaire d'association à but non lucratif.
 Il permet de gérer les membres, leur adhésion et leurs contributions financières.
 Les membres peuvent se connecter eux-même et modifier leurs informations
 ou communiquer entre eux par e-mail. Une gestion précise des droits et
 autorisations est possible. Il est également possible de faire des
 envois de mails en groupe.
 .
 Un module de comptabilité à double entrée assure une gestion financière
 complète digne d'un vrai logiciel de comptabilité : suivi des opérations,
 graphiques, bilan annuel, compte de résultat, exercices, etc.
 .
 Un module wiki permet de prendre des notes de réunion, tenir à jour

 les informations internes à l'association (possibilité de chiffrer le
 contenu des pages) ou de publier des pages sur le site public intégré.
 L'aspect du site public peut être géré simplement avec ses squelettes
 SPIP.

EOF

}


true && {







|

|















|
>
|
<
<
<







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
    echo "Generating ${CONTROL}..."
    cat <<EOF > ${CONTROL}
Package: ${PACKAGE_DEBNAME}
Section: web
Priority: optional
Maintainer: Garradin <garradin@kd2.org>
Architecture: ${DEB_ARCH_NAME}
Depends: dash | bash, php-cli (>=7.4), php-sqlite3
Version: ${PACKAGE_DEB_VERSION}
Suggests: www-browser, php-gd, php-imagick, php-intl
Homepage: http://dev.kd2.org/garradin/
Description: Garradin is a tool to manage non-profit organizations.
 It's only available in french.
Description-fr: Gestionnaire d'association en interface web ou CLI.
 Garradin est un gestionnaire d'association à but non lucratif.
 Il permet de gérer les membres, leur adhésion et leurs contributions financières.
 Les membres peuvent se connecter eux-même et modifier leurs informations
 ou communiquer entre eux par e-mail. Une gestion précise des droits et
 autorisations est possible. Il est également possible de faire des
 envois de mails en groupe.
 .
 Un module de comptabilité à double entrée assure une gestion financière
 complète digne d'un vrai logiciel de comptabilité : suivi des opérations,
 graphiques, bilan annuel, compte de résultat, exercices, etc.
 .
 Il y a également la possibilité de publier un site web simple,
 et un gestionnaire de documents permettant de gérer les fichiers de
 l'association.




EOF

}


true && {

Modified doc/index.md from [af8aa07b41] to [1d3794b203].

103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
	r.json().then((list) => {
		let last;
		let selected;

		list.forEach((file) => {
			var v = file.name.match(/^garradin-(.*)\.tar\.bz2/);

			if (!v) {
				return;
			}

			if (!last || isNewerVersion(last, v[1])) {
				last = v[1];
				selected = file;
			}







|







103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
	r.json().then((list) => {
		let last;
		let selected;

		list.forEach((file) => {
			var v = file.name.match(/^garradin-(.*)\.tar\.bz2/);

			if (!v || v[1].match(/-(alpha|rc|beta)/)) {
				return;
			}

			if (!last || isNewerVersion(last, v[1])) {
				last = v[1];
				selected = file;
			}
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
*  la gestion des __adhérent⋅e⋅s__ : ajout, modification, suppression, possibilité de choisir les informations présentes sur les fiches adhérent, envoi de mails collectifs aux adhérent⋅e⋅s
*  la tenue de la __comptabilité__ : avoir une gestion comptable complète à même de satisfaire un expert-comptable tout en restant à la portée de celles et ceux qui ne savent pas ce qu'est la comptabilité à double entrée, permettre la production des rapports et bilans annuels et de suivre au jour le jour le budget de l'association
*  la gestion des __cotisations__ et __activités__ : suivi des cotisations à jour, inscriptions et paiement des activités, rappels automatiques par e-mail, etc.
*  le travail __collaboratif__ et __collectif__ : gestion fine des droits d'accès aux fonctions, échange de mails entre membres…
*  la __simplification administrative__ : prise de notes en réunion, archivage et partage de fichiers (afin d'éliminer le besoin d'archiver les documents papier), etc.
*  la publication d'un __site web__ pour l'association, simple mais suffisamment flexible pour pouvoir adapter le fonctionnement à la plupart des besoins
*  l'__autonomisation des adhérents__ : possibilité de mettre à jour leurs informations par eux-même, ou de s'inscrire seul depuis un ordinateur ou un smartphone
*  la possibilité d'adapter aux besoins spécifiques de chaque association via des __extensions__.

Tous ces objectifs ne sont pas encore réalisés, voir :

* [la liste des fonctionnalités disponibles](/wiki/?name=Fonctionnalités) pour ce qui est actuellement disponible ;
* [la feuille de route](/wiki/?name=Roadmap) pour la liste des fonctionnalités qu'il reste à implémenter.

Garradin est un logiciel libre disponible sous licence [AGPL v3](https://www.gnu.org/licenses/why-affero-gpl.fr.html).

Garradin signifie *argent* en *Wagiman*, un dialecte aborigène du nord de l'Australie.

## Documentation et entraide

*  D'abord lire la [documentation](/wiki/?name=Documentation) et notamment la [foire aux questions](/wiki/?name=FAQ)
*  La [liste de discussion d'entraide entre utilisateurs](https://admin.kd2.org/lists/aide@garradin.eu) est le meilleur moyen de vous faire aider :)
*  [Chat d'entraide en direct](https://kiwiirc.com/nextclient/#irc://irc.freenode.net/#garradin?nick=garradin%7C?), ou via IRC : salon `#garradin` sur `irc.freenode.net`

## Participer

Tout coup de main est le bienvenu, pas besoin d'avoir des connaissances techniques ! Nous avons un [guide de contribution](/wiki/?name=Contribuer) pour vous aider à voir comment vous pouvez participer à Garradin :)

### Développement

Garradin est un logiciel libre, développé en PHP, utilisant la base de données SQLite, et avec une interface utilisant HTML, CSS et un peu de Javascript.

Nous acceptons les contributions (plugins, patch, code, tickets, etc.) avec plaisir, consultez la [documentation développeur⋅euse](/wiki/?name=Documentation développeur) pour découvrir comment vous pouvez contribuer.







|












|
|
<










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
*  la gestion des __adhérent⋅e⋅s__ : ajout, modification, suppression, possibilité de choisir les informations présentes sur les fiches adhérent, envoi de mails collectifs aux adhérent⋅e⋅s
*  la tenue de la __comptabilité__ : avoir une gestion comptable complète à même de satisfaire un expert-comptable tout en restant à la portée de celles et ceux qui ne savent pas ce qu'est la comptabilité à double entrée, permettre la production des rapports et bilans annuels et de suivre au jour le jour le budget de l'association
*  la gestion des __cotisations__ et __activités__ : suivi des cotisations à jour, inscriptions et paiement des activités, rappels automatiques par e-mail, etc.
*  le travail __collaboratif__ et __collectif__ : gestion fine des droits d'accès aux fonctions, échange de mails entre membres…
*  la __simplification administrative__ : prise de notes en réunion, archivage et partage de fichiers (afin d'éliminer le besoin d'archiver les documents papier), etc.
*  la publication d'un __site web__ pour l'association, simple mais suffisamment flexible pour pouvoir adapter le fonctionnement à la plupart des besoins
*  l'__autonomisation des adhérents__ : possibilité de mettre à jour leurs informations par eux-même, ou de s'inscrire seul depuis un ordinateur ou un smartphone
*  la possibilité d'adapter aux besoins spécifiques de chaque association via des [__extensions__](/wiki/?name=Extensions).

Tous ces objectifs ne sont pas encore réalisés, voir :

* [la liste des fonctionnalités disponibles](/wiki/?name=Fonctionnalités) pour ce qui est actuellement disponible ;
* [la feuille de route](/wiki/?name=Roadmap) pour la liste des fonctionnalités qu'il reste à implémenter.

Garradin est un logiciel libre disponible sous licence [AGPL v3](https://www.gnu.org/licenses/why-affero-gpl.fr.html).

Garradin signifie *argent* en *Wagiman*, un dialecte aborigène du nord de l'Australie.

## Documentation et entraide

* D'abord lire la [documentation](/wiki/?name=Documentation) et notamment la [foire aux questions](/wiki/?name=FAQ)
* Voir la page [Entraide](/wiki/?name=Entraide) pour accéder aux listes de discussion et au salon de discussion IRC


## Participer

Tout coup de main est le bienvenu, pas besoin d'avoir des connaissances techniques ! Nous avons un [guide de contribution](/wiki/?name=Contribuer) pour vous aider à voir comment vous pouvez participer à Garradin :)

### Développement

Garradin est un logiciel libre, développé en PHP, utilisant la base de données SQLite, et avec une interface utilisant HTML, CSS et un peu de Javascript.

Nous acceptons les contributions (plugins, patch, code, tickets, etc.) avec plaisir, consultez la [documentation développeur⋅euse](/wiki/?name=Documentation développeur) pour découvrir comment vous pouvez contribuer.

Added doc/skrivml.html version [b749ec40a9].













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
<!DOCTYPE html>
<html lang="en">
<head>
	<title>Skriv Markup Language</title>
	<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.2.2/css/bootstrap.min.css" />
	<style type="text/css">
	/* text colors */
.red {
	color: brown;
}
.blue {
	color: blue;
}

/* titles */
h2 {
	margin-top: 2em;
	border-bottom: 1px solid #ddd;
}

/* grey alert box */
.alert-grey {
	border-color: #ccc;
	background-color: #eee;
	color: #888;
}

/* footer */
.footer {
	background-color: #F5F5F5;
	border-top: 1px solid #E5E5E5;
	margin-top: 70px;
	padding: 30px 0;
	text-align: center;
}
.footer p {
	color: #777;
	margin-bottom: 0;
}
</style>
</head>
<body style="padding-top: 50px;" >

<div class="navbar navbar-fixed-top">
	<div class="navbar-inner">
		<div class="container">
			<a class="brand" href="https://markup.skriv.org/">Skriv Markup Language</a>
		</div>
	</div>
</div>


<div class="container">
	<div class="row">
		<div class="span3">
			<div class="well" style="padding: 0; position: fixed;">
				<ul class="nav nav-list">
											<li><a href="https://markup.skriv.org/">Home</a></li>
						<li class="divider"></li>
										<li class="nav-header">Skriv Markup Language</li>
					<li ><a href="https://markup.skriv.org/language/intro">Introduction &amp; Rationale</a></li>
					<li class="active"><a href="https://markup.skriv.org/language/syntax">Official Syntax</a></li>
					<li ><a href="https://markup.skriv.org/language/extensions">Official Extensions</a></li>
					<li ><a href="https://markup.skriv.org/proposal/list">Extension Proposals</a></li>
					<li class="divider"></li>
					<li class="nav-header">Associated Services</li>
					<li ><a href="https://markup.skriv.org/online/try">Try Skriv<sup>ML</sup> Online</a></li>
					<li><a href="http://skriv.io">Webservice API</a></li>
					<li class="divider"></li>
					<li class="nav-header">PHP Implementation</li>
					<li ><a href="https://markup.skriv.org/php/project">Download &amp; Contribute</a></li>
					<li ><a href="https://markup.skriv.org/php/usage">Usage</a></li>
					<li ><a href="https://markup.skriv.org/php/configuration">Configuration &amp; Callbacks</a></li>
					<li class="muted">Extensions</li>
					<li class="divider"></li>
										<li ><a href="https://markup.skriv.org/skriv/use">Who uses Skriv Markup?</a></li>
					<li><a href="mailto:contact@skriv.org">Contact</a></li>
				</ul>
			</div>
		</div>
		<div class="span9" style="min-height: 32em;">

<h1>Official Syntax</h1>
<hr />
<div class="alert alert-grey">
	<ol>
		<li><a href="#introduction">Introduction</a>
			<ol>
				<li><a href="#version">Version</a></li>
				<li><a href="#escaping">Escaping</a></li>
				<li><a href="#note-about-spaces">Note about spaces</a></li>
			</ol>
		</li>
		<li><a href="#paragraphs">Paragraphs</a></li>
		<li><a href="#basic-styles">Basic styles</a>
			<ol>
				<li><a href="#italic">Italic</a></li>
				<li><a href="#strong">Strong</a></li>
				<li><a href="#underline">Underline</a></li>
				<li><a href="#strikeout">Strikeout</a></li>
				<li><a href="#monospace">Monospace</a></li>
				<li><a href="#superscript">Superscript</a></li>
				<li><a href="#subscript">Subscript</a></li>
			</ol>
		</li>
		<li><a href="#titles">Titles</a>
			<ol>
				<li><a href="#titles-main">Main syntax</a></li>
				<li><a href="#titles-identifiers">User-defined identifiers</a></li>
			</ol>
		</li>
		<li><a href="#lists">Lists</a>
			<ol>
				<li><a href="#unordered-lists">Unordered lists</a></li>
				<li><a href="#ordered-lists">Ordered lists</a></li>
				<li><a href="#mixed-lists">Mixed lists</a></li>
			</ol>
		</li>
		<li><a href="#links">Links</a></li>
		<li><a href="#images">Images</a></li>
		<li><a href="#tables">Tables</a></li>
		<li><a href="#horizontal-rules">Horizontal rules</a></li>
		<li><a href="#quotes">Quotes</a></li>
		<li><a href="#footnotes">Footnotes</a></li>
		<li><a href="#abbreviations">Abbreviations</a></li>
		<li><a href="#preformatted">Preformatted text</a></li>
		<li><a href="#verbatim">Verbatim text</a></li>
		<li><a href="#code">Code</a></li>
		<li><a href="#styled-paragraphs">Styled paragraphs</a></li>
		<li><a href="#smileys-symbols">Smileys &amp; Symbols</a>
			<ol>
				<li><a href="#smileys">Smileys</a></li>
				<li><a href="#symbols">Symbols</a></li>
			</ol>
		</li>
		<li><a href="#extensions">Extensions</a>
			<ol>
				<li><a href="#extensions-inline">Inline</a></li>
				<li><a href="#extensions-block">Block</a></li>
			</ol>
		</li>
	</ol>
</div>



<h2 id="introduction">1. Introduction</h2>
<p>Here is the official core of <strong>Skriv Markup</strong>'s syntax.</p>

<h3 id="version">1.1 Version</h3>
<p>The <strong>Skriv Markup</strong> syntax' current version is <b class="blue">alpha</b>.</p>

<h3 id="escaping">1.2 Escaping</h3>
<p>
	All special characters are escaped. For instance, less-than (<tt>&lt;</tt>), greatear-than (<tt>&gt;</tt>)
	and ampersand (<tt>&amp;</tt>) characters are transformed during HTML export (respectively to
	<tt>&amp;lt;</tt>, <tt>&amp;gt;</tt> and <tt>&amp;amp;</tt>).
</p>
<p>
	Sometimes, it's necessary to prevent some language interpretation, when you want to display something that
	should be used as a markup. To do so, you just have to put a backslash (<tt>\</tt>) character in front of the markup.
</p>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	The backslash character is commonly used to escape sequences in text streams, in many programming languages.
	More, this character is rarely used in normal texts, so in shouldn't conflict with any other typed characters.
</div>

<h3 id="note-about-spaces">1.3 Note about spaces</h3>
<p>
	You'll see that some markups can take several parameters; in this case, the parameters are separated with a
	pipe character (<b class="red">|</b>). You can add spaces before and/or after any parameter, they will be removed afterward.
</p>
<p>For example, these four lines produce the exact same link:</p>
<pre><b class="red">[[</b>Skriv<b class="red">|</b>http://skriv.org<b class="red">]]</b>
<b class="red">[[</b> Skriv <b class="red">|</b> http://skriv.org <b class="red">]]</b>
<b class="red">[[</b>Skriv <b class="red">|</b> http://skriv.org<b class="red">]]</b>
<b class="red">[[</b>Skriv <b class="red">|</b>http://skriv.org<b class="red">]]</b></pre>
<p>
	In fact, spaces are removed when they are obviously optional. These two lists produce the exact same result:
</p>
<pre><b class="red">*</b>AAA
<b class="red">*</b>BBB

<b class="red">*</b> AAA
<b class="red">*</b> BBB</pre>
<p>
	As well as these two titles:
</p>
<pre><b class="red">==</b>Level 2 title<b class="red">==</b>
<b class="red">==</b> Level 2 title <b class="red">==</b></pre>
<p>
	And for these tables:
</p>
<pre><b class="red">!!</b>Head 1<b class="red">!!</b>Head 2
<b class="red">||</b>Cell 1<b class="red">||</b>Cell 2

<b class="red">!!</b> Head 1 <b class="red">!!</b> Head 2
<b class="red">||</b> Cell 1 <b class="red">||</b> Cell 2</pre>
<p>
	On the other hand, inline markups without parameters don't remove spaces. So these two lines are different:
</p>
<pre><b class="red">**</b>bold text<b class="red">**</b> and <b class="red">''</b>italic text<b class="red">''</b>
<b class="red">**</b> bold text <b class="red">**</b> and <b class="red">''</b> italic text <b class="red">''</b></pre>



<h2 id="paragraphs">2. Paragraphs</h2>
<p>
Out of special blocks, any text is placed inside a paragraph. Paragraphs are separated by one or more blank line.
Inside a paragraph, line-breaks are kept as they are typed.
</p>

<div class="label">Skriv Markup</div>
<pre>Here is the first paragraph.
With two lines.

Here is the second paragraph, with
many
carriage-returns.</pre>

<div class="label">Result</div>
<div class="alert alert-grey">
	<p>
		Here is the first paragraph.<br />
		With two lines.
	</p>
	<p>
		Here is the second paragraph, with<br />
		many<br />
		carriage-returns.
	</p>
</div>

<div class="label">HTML</div>
<pre>&lt;p&gt;
    Here is the first paragraph.&lt;br /&gt;
    With two lines.
&lt;/p&gt;
&lt;p&gt;
    Here is the second paragraph, with&lt;br /&gt;
    many&lt;br /&gt;
    carriage-returns.
&lt;/p&gt;</pre>

<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>
		Paragraphs are so common that no explicit markup should be necessary to create them.
	</p>
	<p>
		Keep line-breaks seems the best way to ensure a result as close as possible from what
		the writer wants. This point of view is shared by <a href="http://github.github.com/github-flavored-markdown/" target="_blank">GitHub Flavored Markdown</a>.
	</p>
</div>



<h2 id="basic-styles">3. Basic styles</h2>
<p>
	Inline styles are marked up using tags before and after the affected text. These tags are constituted by two identical characters.<br />
	These markups can affect full-words only, they are not effective if they are written in the middle of a word.
</p>
<div class="label">Skriv Markup</div>
<pre>works on**ly on full** words</pre>
<div class="label">Output</div>
<div class="alert alert-grey">works on**ly on full** words</div>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	Most of the time, it's totally pointless to apply a style on a chuck of a word. Usually, that could lead to a misunderstanding of the writer's will.
	Here again, this point of view is shared by <a href="http://github.github.com/github-flavored-markdown/" target="_blank">GitHub Flavored Markdown</a>.</p>
</div>

<h3 id="italic">3.1 Italic</h3>
<div class="label">Skriv Markup</div>
<pre>two <b class="red">''</b>single quotes<b class="red">''</b> for italic</pre>
<div class="label">Output</div>
<div class="alert alert-grey">two <em>single quotes</em> for italic</div>
<div class="label">HTML</div>
<pre>two &lt;em&gt;single quotes&lt;/em&gt; for italic</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	For light emphasis, the doubled-single-quotes markup is widely used (MediaWiki). The doubled-slash characters (<tt>//</tt>),
	used by Creole, is pretty logical; the shape of the slash character reminds the slanted aspect of italic writing.
	But the visual impact on the text is overweening compared with the desired result.
</div>

<h3 id="strong">3.2 Strong</h3>
<div class="label">Skriv Markup</div>
<pre>two <b class="red">**</b>asterisks<b class="red">**</b> for bold</pre>
<div class="label">Output</div>
<div class="alert alert-grey">two <strong>asterisks</strong> for bold</div>
<div class="label">HTML</div>
<pre>two &lt;strong&gt;asterisks&lt;/strong&gt; for bold</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	Asterisks are commonly used for strong emphasis (Creole, Markdown, txt2tags, DokuWiki). They are also used in emails since the down of time.
</div>

<h3 id="underline">3.3 Underline</h3>
<div class="label">Skriv Markup</div>
<pre>two <b class="red">__</b>underscores<b class="red">__</b> for underline</pre>
<div class="label">Output</div>
<div class="alert alert-grey">two <u>underscores</u> for underline</div>
<div class="label">HTML</div>
<pre>two &lt;u&gt;underscores&lt;/u&gt; for underline</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>Adding underscores before and after is the perfect markup for underlining, as they are suggesting the beginning and the end of the under line.</p>
	<p>This syntax is already used by Creole and DokuWiki.</p>
</div>

<h3 id="strikeout">3.4 Strikeout</h3>
<div class="label">Skriv Markup</div>
<pre>two <b class="red">--</b>minus signs<b class="red">--</b> for striking out</pre>
<div class="label">Output</div>
<div class="alert alert-grey">two <s>minus signs</s> for striking out</div>
<div class="label">HTML</div>
<pre>two &lt;s&gt;minus signs&lt;/s&gt; for striking out</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	The minus signs are good for striked out text, for the same reason than the underscores for underlining.
</div>

<h3 id="monospace">3.5 Monospace</h3>
<div class="label">Skriv Markup</div>
<pre>two <b class="red">##</b>hash signs<b class="red">##</b> for monospace</pre>
<div class="label">Output</div>
<div class="alert alert-grey">two <tt>hash signs</tt> for monospace</div>
<div class="label">HTML</div>
<pre>two &lt;tt&gt;hash signs&lt;/tt&gt; for monospace</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>Hash signs have a very special shape. Their more-or-less squared look is a valid metaphor for monospaced fonts.</p>
	<p>This syntax is already used by Creole.</p>
</div>

<h3 id="superscript">3.6 Superscript</h3>
<div class="label">Skriv Markup</div>
<pre>two <b class="red">^^</b>caret characters<b class="red">^^</b> for exponent</pre>
<div class="label">Output</div>
<div class="alert alert-grey">two <sup>caret characters</sup> for exponent</div>
<div class="label">HTML</div>
<pre>two &lt;sup&gt;cart characters&lt;/sup&gt; for exponent</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>Caret characters are like little arrowheads indicating upside direction.</p>
	<p>This syntax is already used by Creole.</p>
</div>

<h3 id="subscript">3.7 Subscript</h3>
<div class="label">Skriv Markup</div>
<pre>two <b class="red">,,</b>commas<b class="red">,,</b> for subscript</pre>
<div class="label">Output</div>
<div class="alert alert-grey">two <sub>commas</sub> for subscript</div>
<div class="label">HTML</div>
<pre>two &lt;sub&gt;commas&lt;/sub&gt; for subscript</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>On the contrary, commas are going under the text's baseline, thus they are suggesting to push down the text.</p>
	<p>This syntax is already used by Creole.</p>
</div>



<h2 id="titles">4. Titles</h2>
<h3 id="titles-main">4.1 Main syntax</h3>
<p>
	Titles are written using one to six equal signs (<tt>=</tt>) at the beginning of the line. One equal sign for a first level heading;
	six equal signs for a sixth level heading.
</p>
<p>
	For esthetical reasons, it's possible to add as many equal signs at the end of the line than at the beginning. They will be removed.<br />
	Spaces are allowed between the markups and the title's text.
</p>
<p>
	On HTML output, DOM identifier should be added. It should be possible to prepend a given prefix at the beginning of these identifiers.
</p>

<div class="label">Skriv Markup</div>
<pre><b class="red">=</b>Level 1 heading
<b class="red">==</b> Level 2 heading<b class="red">==</b>
<b class="red">===</b>Level 3 heading <b class="red">===</b>
<b class="red">====</b> Level 4 heading</pre>

<div class="label">HTML</div>
<pre>&lt;h1 id="Level-1-heading"&gt;Level 1 heading&lt;h1&gt;
&lt;h2 id="Level-2-heading"&gt;Level 2 heading&lt;h2&gt;
&lt;h3 id="Level-3-heading"&gt;Level 3 heading&lt;h3&gt;
&lt;h4 id="Level-4-heading"&gt;Level 4 heading&lt;h4&gt;</pre>

<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>Equals signs are a very widespread mean to write headings among wiki syntaxes (MediaWiki, Creole, txt2tags, DokuWiki).</p>
	<p>It's a convenient writing, very fast to type. The visual impact is clear; with more equal signs at the beginning of the line, the title is more
	   indented, indicating a sub-header.</p>
	<p>Equals signs at the end of the line are optional, because some existing wiki syntaxes made it mandatory, some others avoid them.</p>
</div>

<h3 id="titles-identifiers">4.2 User-defined identifiers</h3>
<p>
	Because two titles may have the same text, two titles may have the same DOM identifier. It could be a real problem when creating
	links pointing to these titles (even for automatically created table of contents).
</p>
<p>
	To circumvent this problem, it is possible to override a title identifier by writing it at the end of the line, using the balanced markup.
</p>
<p>
	It's always possible to disable this feature, by using the usual escaping character (backslash) before the equal signs, or by using the balanced markup all the time.
</p>

<div class="label">Skriv Markup</div>
<pre><b class="red">===</b>Darth Vador
<b class="red">===</b>Darth Vador<b class="red">===</b>
<b class="red">===</b>Darth Vador<b class="red">===</b><b class="blue">your father</b>
<b class="red">=</b>Darth Vador \= your father
<b class="red">=</b>Darth Vador = your father<b class="red">=</b></pre>

<div class="label">HTML</div>
<pre>&lt;h3 id="Darth-Vador"&gt;Darth Vador&lt;/h3&gt;
&lt;h3 id="Darth-Vador"&gt;Darth Vador&lt;/h3&gt;
&lt;h3 id="your-father"&gt;Darth Vador&lt;/h3&gt;
&lt;h1 id="Darth-Vador-your-father"&gt;Darth Vador = your father&lt;h1&gt;
&lt;h1 id="Darth-Vador-your-father"&gt;Darth Vador = your father&lt;h1&gt;</pre>

<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	This syntax is the simplest way to define special identifiers, without any fancy addition.
</div>



<h2 id="lists">5. Lists</h2>
<h3 id="unordered-lists">5.1 Unordered lists</h3>
<p>
	Unordered lists are also known as “bulleted-lists”. They are written using asterisk characters (<tt>*</tt>), placed at the beginning of the lines.
	There must be no space before the asterisks.
</p>
<p>
	Sub-lists are created by typing more asterisks.
</p>
<div class="label">Skriv Markup</div>
<pre><b class="red">*</b> Item 1
<b class="red">*</b> Item 2
<b class="red">**</b> Sub-item 2.1
<b class="red">**</b> Sub-item 2.2
<b class="red">***</b> Sub-item 2.2.1</pre>
<div class="label">Output</div>
<div class="alert alert-grey">
	<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>
</div>
<div class="label">HTML</div>
<pre>&lt;ul&gt;
    &lt;li&gt;Item 1&lt;/li&gt;
    &lt;li&gt;Item 2
        &lt;ul&gt;
            &lt;li&gt;Sub-item 2.1&lt;/li&gt;
            &lt;li&gt;Sub-item 2.2
                &lt;ul&gt;
                    &lt;li&gt;Sub-item 2.2.1&lt;/li&gt;
                &lt;/ul&gt;
            &lt;/li&gt;
        &lt;/ul&gt;
    &lt;/li&gt;
&lt;/ul&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>Asterisks character are commonly used to create lists (MediaWiki, Creole, Markdown, reStructuredText, POD, Asciidoc, Textile, WikiWikiWeb, TWiki, MoinMoin, Redmine, ...).</p>
	<p>Adding more asterisks at the beginning of the line indent the text as a result. This indentation makes clear where the sublist is.</p>
</div>

<h3 id="ordered-lists">5.2 Ordered lists</h3>
<p>
	Items of ordered lists are displayed with an incremented number in front of them. They are written using hash signs (<tt>#</tt>),
	placed at the beginning of the lines. There must be no space before the hash signs.
</p>
<p>
	Sub-lists are created by typing more hash signs.
</p>
<div class="label">Skriv Markup</div>
<pre><b class="red">#</b> Item 1
<b class="red">#</b> Item 2
<b class="red">##</b> Sub-item 2.1
<b class="red">##</b> Sub-item 2.2
<b class="red">###</b> Sub-item 2.2.1</pre>
<div class="label">Output</div>
<div class="alert alert-grey">
	<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>
</div>
<div class="label">HTML</div>
<pre>&lt;ul&gt;
    &lt;li&gt;Item 1&lt;/li&gt;
    &lt;li&gt;Item 2
        &lt;ul&gt;
            &lt;li&gt;Sub-item 2.1&lt;/li&gt;
            &lt;li&gt;Sub-item 2.2
                &lt;ol&gt;
                    &lt;li&gt;Sub-item 2.2.1&lt;/li&gt;
                &lt;/ol&gt;
            &lt;/li&gt;
        &lt;/ul&gt;
    &lt;/li&gt;
&lt;/ul&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>
		The hash sign is a character used to represent numbers, so its usage is understandable for numbered lists.
		It's also used by many other languages (MediaWiki, Creole, Textile, Redmine, ...).
	</p>
	<p>The same mechanisms than for unordered lists are applied, to keep a coherent syntax.</p>
</div>

<h3 id="mixed-lists">5.3 Mixed lists</h3>
<p>
	It is possible to mix ordered and unordered lists. The last character used determines the list's type.
</p>
<div class="label">Skriv Markup</div>
<pre><b class="red">*</b> Item 1
<b class="red">**</b> Sub-item 1.1
<b class="red">**#</b> Sub-item 1.1.1
<b class="red">**#</b> Sub-item 1.1.2
<b class="red">**</b> Sub-item 1.2
<b class="red">*#</b> Sub-item 1.3
<b class="red">*</b> Item 2</pre>
<div class="label">Output</div>
<div class="alert alert-grey">
	<ul>
		<li>Item 1
			<ul>
				<li>Sub-item 1.1
					<ol>
						<li>Sub-item 1.1.1</li>
						<li>Sub-item 1.1.2</li>
					</ol>
				</li>
				<li>Sub-item 1.2</li>
			</ul>
			<ol>
				<li>Sub-item 1.3</li>
			</ol>
		</li>
		<li>Item 2</li>
	</ul>
</div>
<div class="label">HTML</div>
<pre>&lt;ul&gt;
    &lt;li&gt;Item 1
        &lt;ul&gt;
            &lt;li&gt;Sub-item 1.1
                &lt;ol&gt;
                    &lt;li&gt;Sub-item 1.1.1&lt;/li&gt;
                    &lt;li&gt;Sub-item 1.1.2&lt;/li&gt;
                &lt;/ol&gt;
            &lt;/li&gt;
            &lt;li&gt;Sub-item 1.2&lt;/li&gt;
        &lt;/ul&gt;
        &lt;ol&gt;
            &lt;li&gt;Sub-item 2.2.1&lt;/li&gt;
        &lt;/ol&gt;
    &lt;/li&gt;
    &lt;li&gt;Item 2&lt;/li&gt;
&lt;/ul&gt;</pre>



<h2 id="links">6. Links</h2>
<p>
	Links are explicitely defined using double-square brackets (<tt>[[&nbsp;]]</tt>). There must be at least the link destination, but it is also
	possible to define its title first, separated from the link address with a pipe character (<tt>|</tt>).
</p>
<p>
	When no title is given, the address is used as the title, shorten to 40 characters.
</p>
<p>
	By default, every outgoing links (those containing "<tt>://</tt>" or starting with "<tt>//</tt>") SHOULD be set with
	a <tt>target="_blank"</tt> and a <tt>rel="nofollow"</tt> attributes. This behaviour SHOULD be configurable.
</p>
<div class="label">Skriv Markup</div>
<pre><b class="red">[[</b>/language/intro<b class="red">]]</b>
<b class="red">[[</b>http://www.site.com/very/long/long/looong/url/as/you/never/saw<b class="red">]]</b>
<b class="red">[[</b>Skriv Markup <b class="red">|</b> http://markup.skriv.org<b class="red">]]</b>
<b class="red">[[</b>contact@skriv.org<b class="red">]]</b>
<b class="red">[[</b>Contact<b class="red">|</b>contact@skriv.org<b class="red">]]</b></pre>
<div class="label">Output</div>
<div class="alert alert-grey">
	<a href="https://markup.skriv.org/language/intro">/language/intro</a><br />
	<a href="http://www.site.com/very/long/long/looong/url/as/you/never/saw" target="_blank" rel="nofollow">http://site.com/very/long/long/looon...</a><br />
	<a href="http://markup.skriv.org">Skriv Markup</a><br />
	<a href="mailto:contact@skriv.org">contact@skriv.org</a><br />
	<a href="mailto:contact@skriv.org">Contact</a>
</div>
<div class="label">HTML</div>
<pre>&lt;a href="https://markup.skriv.org/language/intro"&gt;/language/intro&lt;/a&gt;
&lt;a href="http://www.site.com/very/long/long/looong/url/as/you/never/saw"
   target="_blank" rel="nofollow"&gt;http://site.com/very/long/long/looon...&lt;/a&gt;
&lt;a href="http://markup.skriv.org" target="_blank" rel="nofollow"&gt;Skriv Markup&lt;/a&gt;
&lt;a href="mailto:contact@skriv.org"&gt;contact@skriv.org&lt;/a&gt;
&lt;a href="mailto:contact@skriv.org"&gt;Contact&lt;/a&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>
		Square brackets are commonly used to represent some kind of reference (MediaWiki, Creole, Markdown, Asciidoc, DokuWiki, TWiki, MoinMoin, ...).
		They are doubled to follow the <a href="https://markup.skriv.org/language/intro#rationale">Skriv rationale</a>.
	</p>
	<p>
		When you read some text, the title of a link contains more direct information than its destination address.
		That's why the title is written first, before the address, when defined.
	</p>
</div>



<h2 id="images">7. Images</h2>
<p>
	Images' syntax follows the links' syntax. Double-curly brackets (<tt>{{&nbsp;}}</tt>) are used instead of double-square brackets,
	to define the image location. An optional text can be set as the image alternative representation.
</p>
<div class="label">Skriv Markup</div>

<pre><b class="red">{{</b>http://skriv.org/logo.png<b class="red">}}</b>
<b class="red">{{</b>Skriv logo<b class="red">|</b>http://skriv.org/logo.png<b class="red">}}</b></pre>

<div class="label">HTML</div>
<pre>&lt;img src="http://skriv.org/logo.png" alt="http://skriv.org/logo.png" /&gt;
&lt;img src="http://skriv.org/logo.png" alt="Skriv logo" /&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>
		Curly brackets are like square brackets, but with a more “artistic” shape. That's enough to distinguish images from regular links.
	</p>
	<p>
		Double-curly brackets are already used by DokuWiki.
	</p>
</div>



<h2 id="tables">8. Tables</h2>
<p>
	Skriv Markup helps you to create simple tables as quickly as possible. It is not intended to
	generate complex tables with merged cells.
</p>
<p>
	Each table row starts with a cell delimiter. There is two kinds of cell delimiter: double-pipe (<tt>||</tt>) for normal cells,
	and double-exclamation marks (<tt>!!</tt>) for header cells. Every cell begins with a delimiter.
</p>
<div class="label">Skriv Markup</div>
<pre><b class="red">!!</b> Header 1 <b class="red">!!</b> Header 2
<b class="red">||</b> Cell 1   <b class="red">||</b> Cell 2
<b class="red">||</b> Cell 3   <b class="red">||</b> Cell 4</pre>
<div class="label">Output</div>
<div class="alert alert-grey">
	<table border="1">
		<tr>
			<th>Header 1</th>
			<th>Header 2</th>
		</tr>
		<tr>
			<td>Cell 1</td>
			<td>Cell 2</td>
		</tr>
		<tr>
			<td>Cell 3</td>
			<td>Cell 4</td>
		</tr>
	</table>
</div>
<div class="label">HTML</div>
<pre>&lt;table&gt;
    &lt;tr&gt;
        &lt;th&gt;Header 1&lt;/th&gt;
        &lt;th&gt;Header 2&lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;Cell 1&lt;/td&gt;
        &lt;td&gt;Cell 2&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;Cell 3&lt;/td&gt;
        &lt;td&gt;Cell 4&lt;/td&gt;
    &lt;/tr&gt;
&lt;/table&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>
		The major goal with the table syntax was to provide a convenient way to create tables, without doing
		<a href="http://en.wikipedia.org/wiki/Ascii_art" target="_blank">ascii-art</a>. That's the reason why there is only two
		type of cells, no merged cells, and a very simple layout.
	</p>
	<p>
		Pipes are the natural characters to create vertical separations between elements. It's perfect for table representation.
		Exclamation marks have a similar shape, with a subtle difference to indicate headers.
	</p>
</div>



<h2 id="horizontal-rules">9. Horizontal rules</h2>
<p>
	Horizontal rules are done by putting at least four minus signs on the same line, without anything else
	on the line. There must be no space before the minus signs.
</p>
<div class="label">Skriv Markup</div>
<pre><b class="red">----</b></pre>
<div class="label">Output</div>
<div class="alert alert-grey">
	<hr />
</div>
<div class="label">HTML</div>
<pre>&lt;hr /&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	The four minus signs markup represent a line, like an horizontal separator in the page. It is used by a lot of other systems
	(Creole, Markdown, reStructuredText, WikiWikiWeb, TWiki,&nbsp;...).
</div>



<h2 id="quotes">10. Quotes</h2>
<p>
	To write a quote, add a right angle bracket (<tt>&gt;</tt>) at the beginning of each line.
	If you need many paragraphs inside the quote, just mark blank lines as well.
</p>
<div class="label">Skriv Markup</div>
<pre><b class="red">&gt;</b> Quotes use right angle brackets.
<b class="red">&gt;</b>
<b class="red">&gt;</b> Paragraphs are managed as usual.
<b class="red">&gt;</b> Line-breaks too.</pre>
<div class="label">Output</div>
<div class="alert alert-grey">
	<blockquote>
		<p>Quotes use right angle brackets.</p>
		<p>
			Paragraphs are managed as usual.<br />
			Line-breaks too.
		</p>
	</blockquote>
</div>
<div class="label">HTML</div>
<pre>&lt;blockquote&gt;
    &lt;p&gt;
        Quotes use right angle brackets.
    &lt;/p&gt;
    &lt;p&gt;
        Paragraphs are managed as usual.&lt;br /&gt;
        Line-breaks too.
    &lt;/p&gt;
&lt;/blockquote&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	The right angle bracket character is a convenient mean to separate a quote from the rest
	of the text (already used in Markdown).
</div>



<h2 id="footnotes">11. Footnotes</h2>
<p>
	Footnotes are used to add internal links inside a document, referencing some chunks of text that should
	be listed at the bottom of the page.
</p>
<p>
	They are defined using double-parenthesis (<tt>(( ))</tt>), where the footnote is referenced. Usually, footnotes
	are identified by an incremented number; if you want to use a label in place of that number, write it first,
	separated from the footnote's text by a pipe character (<tt>|</tt>).
</p>
<div class="label">Skriv Markup</div>
<pre>Arthur C. Clarke is one of the best SF author <b class="red">((</b>just after Issac Asimov<b class="red">))</b>.

The Ford T is the car of the century <b class="red">((</b>Source<b class="red">|</b>ahead Mini and Citroën DS, see
[[Wikipedia|http://en.wikipedia.org/wiki/Car_of_the_Century]]<b class="red">))</b>, but everybody knows
it should be the VW Beetle <b class="red">((</b>[[Wikipedia<b class="red">|</b>
http://en.wikipedia.org/wiki/Volkswagen_Beetle]]<b class="red">))</b>.</pre>
<div class="label">Output</div>
<div class="alert alert-grey">
	<p>
		Arthur C. Clarke is one of the best SF author <sup><a href="#cite_note-1" id="cite_ref-1">1</a></sup>.
	</p>
	<p>
		The Ford T is the car of the century <sup><a href="#cite_note-2" id="cite_ref-2">Source</a></sup>,
		but everybody knows it should be the VW Beetle <sup><a href="#cite_note-3" id="cite_ref-3">3</a></sup>.
	</p>
</div>
<div class="alert alert-grey">
	<div>
		<p><a href="cite_ref-1" id="cite_note-1">1</a>. juste after Isaac Asimov</p>
		<p><a href="cite_ref-2" id="cite_note-2">Source</a>. ahead Mini and Citroën DS, see <a href="http://en.wikipedia.org/wiki/Car_of_the_Century">Wikipedia</a></p>
		<p><a href="cite_ref-3" id="cite_note-3">3</a>. <a href="http://en.wikipedia.org/wiki/Volkswagen_Beetle">Wikipedia</a></p>
	</div>
</div>
<div class="label">HTML</div>
<pre>Arthur C. Clarke is one of the best SF author &lt;sup&gt;&lt;a href="#cite_note-1"
id="cite_ref-1"&gt;1&lt;/a&gt;&lt;/sup&gt;.

The Ford T is the car of the century &lt;sup&gt;&lt;a href="#cite_note-2"
id="cite_ref-2"&gt;Source&lt;/a&gt;&lt;/sup&gt;, but everybody knows it should be the VW Beetle
&lt;sup&gt;&lt;a href="#cite_note-3" id="cite_ref-3"&gt;3&lt;/a&gt;&lt;/sup&gt;.</pre>
<pre>&lt;div class="footnotes"&gt;
    &lt;p class="footnote"&gt;&lt;a href="cite_ref-1" id="cite_note-1"&gt;1&lt;/a&gt;. juste after
 Isaac Asimov&lt;/p&gt;
    &lt;p class="footnote"&gt;&lt;a href="cite_ref-2" id="cite_note-2"&gt;Source&lt;/a&gt;. ahead Mini
 and Citroën DS, see &lt;a href="http://en.wikipedia.org/wiki/Car_of_the_Century"&gt;Wiki
pedia&lt;/a&gt;&lt;/p&gt;
    &lt;p class="footnote"&gt;&lt;a href="cite_ref-3" id="cite_note-3"&gt;3&lt;/a&gt;. &lt;a
 href="http://en.wikipedia.org/wiki/Volkswagen_Beetle"&gt;Wikipedia&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>
		Parenthesis are used to write secondary content that it not crucial to the meaning of a text.
		Using double-parenthesis indicates that footnotes are like “tertiary content”, even less important
		so it can be put down at the end of the page.
	</p>
	<p>
		Double-parenthesis are already used by DokuWiki.
	</p>
</div>



<h2 id="abbreviations">12. Abbreviations</h2>
<p>
	Abbreviations are written using double-question marks (<tt>??</tt>). The abbreviation and its explaination
	are separated by a pipe character (<tt>|</tt>).
</p>
<div class="label">Skriv Markup</div>
<pre><b class="red">??</b>EFF<b class="red">|</b>Electronic Frontier Foundation<b class="red">??</b></pre>
<div class="label">Output</div>
<div class="alert alert-grey">
	<abbr title="Electronic Frontier foundation">EFF</abbr>
</div>
<div class="label">HTML</div>
<pre>&lt;abbr title="Electronic Frontier foundation"&gt;EFF&lt;/abbr&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	Question marks are the symbol for interrogation and help. The purpose of this markup is
	to provide some explaination about a term, so it fit very well.
</div>



<h2 id="preformatted">13. Preformatted text</h2>
<p>
	Preformatted texts are blocks of text rendered using monospace font. Line breaks are kept.
	Skriv syntax is still interpreted.
</p>
<p>
	To create a preformatted text block, just add a space character at the beginning of each line
	of the block. In fact, once space is enough, but you can put as many spaces as you want.
</p>
<div class="label">Skriv Markup</div>
<pre> At least one space at the beginning of each
 line is enough to create a preformatted paragraph.
 
 Skriv syntax **works**.</pre>
<div class="label">Output</div>
<div class="alert alert-grey">
	<pre style="background-color: #fff;">At least one space at the beginning of each
line is enough to create a preformatted paragraph.

Skriv syntax <strong>works</strong>.</pre>
</div>
<div class="label">HTML</div>
<pre>&lt;pre&gt;
At least one space at the beginning of each
line is enough to create a preformatted paragraph.

Skriv syntax &lt;strong&gt;works&lt;/strong&gt;.
&lt;/pre&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>
		Adding space characters at the beginning of the line is the fastest way to define a style
		on a block of text. By indenting it from regular text, it gives a special meaning to the text.
	</p>
	<p>
		MediaWiki already uses this writing to create preformatted text blocks.
	</p>
</div>



<h2 id="verbatim">14. Verbatim text</h2>
<p>
	Verbatim text are preformatted text blocks without any interpretation.
	They are written using triple-square brackets (<tt>[[[ ]]]</tt>).
</p>
<div class="label">Skriv Markup</div>
<pre><b class="red">[[[</b>
Triple square brackets also create
preformatted paragraphs.

**Skriv** syntax is __not__ interpreted.
<b class="red">]]]</b></pre>
<div class="label">Output</div>
<div class="alert alert-grey">
	<pre style="background-color: #fff;">Triple square brackets also create
preformatted paragraphs.

**Skriv** syntax is __not__ interpreted.</pre>
</div>
<div class="label">HTML</div>
<pre>&lt;pre&gt;
Triple square brackets also create
preformatted paragraphs.

**Skriv** syntax is __not__ interpreted.
&lt;/pre&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	The angular shape of square bracket characters is a good reminder of verbatim
	texts' aspect (separate block, monospace font). The usage of opening and closing
	square brackets is perfect to mark the block's boundaries.
</div>



<h2 id="code">15. Code</h2>
<p>
	As for verbatim text, Skriv syntax is not interpreted inside code blocks.
	The difference between a verbatim text block and a code block is the presence
	of the programming language's name after the three opening square brackets
	(there could be spaces between the brackets and the language's name, but it's
	not a mandatory).
</p>
<p>
	Syntax highlighting is let to the interpreter will.
</p>
<div class="label">Skriv Markup</div>

<pre><b class="red">[[[</b> <b class="blue">php</b>
class Foo {
    public function show() {
        print("bar\n");
    }
}
<b class="red">]]]</b></pre>

<div class="label">Output</div>

<pre class="prettyprint linenums"><code class="language-php">class Foo {
    public function show() {
        print("bar\n");
    }
}</code></pre>

<div class="label">HTML</div>

<pre>&lt;pre&gt;&lt;code class="language-php"&gt;
class Foo {
    public function show() {
        print("bar\n");
    }
}
&lt;/code&gt;&lt;/pre&gt;</pre>

<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	<p>
		Since code blocks content is not interpreted, they are only a special case of verbatim text blocks.
		So it's logical to keep usage of triple-square brackets.
	</p>
	<p>
		Code blocks are rendered as a <tt>&lt;code&gt;</tt> inside a <tt>&lt;pre&gt;</tt> tag, because it's the
		<a href="http://dev.w3.org/html5/spec-author-view/the-code-element.html#the-code-element" target="_blank">recommended
		method in HTML 5</a>. When syntax highlighting is activated, this markup is not a mandatory.
	</p>
</div>



<h2 id="styled-paragraphs">16. Styled paragraphs</h2>
<p>
	This syntax is a convenient way to apply some CSS styles to paragraphs. Styled blocks are
	written between triple-curly brackets (<tt>{{{ }}}</tt>). All paragraphs
	inside will inherit the specified styles. CSS classes are typed just after the opening brackets.
</p>
<p>
	It is possible to nest styled paragraphs. Just add triple-curly brackets-enclosed blocks inside
	existing ones. For a better readability, you can add any number of spaces and/or curly brackets
	before the CSS class names; the sole obligation is to start the lines with three opening curly
	brackets and three closing curly brackets.
</p>
<div class="label">Skriv Markup</div>

<pre><b class="red">{{{</b><b class="blue">css_class1 css_class2</b>
CSS classes apply to all paragraphs.

Whatever their ''number''.

<b class="red">{{{ {{{</b> <b class="blue">css_class3</b>
This paragraph has the **3 CSS classes**.
<b class="red">}}} }}}
}}}</b></pre>

<div class="label">HTML</div>
<pre>&lt;div class="css_class1 css_class2"&gt;
    &lt;p&gt;
        CSS classes apply to all paragraphs.
    &lt;/p&gt;
    &lt;p&gt;
        Whatever their &lt;em&gt;number&lt;/em&gt;.
    &lt;/p&gt;
    &lt;div class="css_class3"&gt;
        &lt;p&gt;
            This paragraph has the &lt;strong&gt;3 CSS classes&lt;/strong&gt;.
        &lt;/p&gt;
    &lt;/div&gt;
&lt;/div&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
        Curly brackets are undeniably bound to CSS syntax. Every web developers have a mental
	connection between CSS instructions and curly brackets.
</div>



<h2 id="smileys-symbols">17. Smileys &amp; Symbols</h2>
<p>
	Skriv Markup provide helper scriptures, for adding special characters that are not easy to write with a regular keyboard.
	These characters are useful to add small illustrations to the text.
</p>

<h3 id="smileys">17.1 Smileys</h3>
<table class="table table-striped table-bordered table-condensed">
	<tr>
		<td style="text-align: right;"><tt>:-)</tt></td>
		<td>☺</td>
		<td style="text-align: right;"><tt>:-(</tt></td>
		<td>☹</td>
		<td style="text-align: right;"><tt>:-D</tt></td>
		<td>😃</td>
		<td style="text-align: right;"><tt>:-p</tt></td>
		<td>😋</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:-|</tt></td>
		<td>😐</td>
		<td style="text-align: right;"><tt>;-)</tt></td>
		<td>😉</td>
		<td style="text-align: right;"><tt>:-o</tt></td>
		<td>😲</td>
		<td style="text-align: right;"><tt>:-x</tt></td>
		<td>😶</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:'-(</tt></td>
		<td>😥</td>
		<td style="text-align: right;"><tt>:-@</tt></td>
		<td>😠</td>
		<td style="text-align: right;"><tt>:-*</tt></td>
		<td>😘</td>
		<td colspan="2"></td>
	</tr>
</table>

<h3 id="symbols">17.2 Symbols</h3>
<table class="table table-striped table-bordered table-condensed">
	<tr>
		<td style="text-align: right;"><tt>:sun:</tt></td>
		<td>☀</td>
		<td style="text-align: right;"><tt>:cloud:</tt></td>
		<td>☁</td>
		<td style="text-align: right;"><tt>:umbrella:</tt></td>
		<td>☂</td>
		<td style="text-align: right;"><tt>:star:</tt></td>
		<td>★</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:phone:</tt></td>
		<td>☎</td>
		<td style="text-align: right;"><tt>:check:</tt></td>
		<td>✔</td>
		<td style="text-align: right;"><tt>:mark:</tt></td>
		<td>✖</td>
		<td style="text-align: right;"><tt>:cross:</tt></td>
		<td>✚</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:skull:</tt></td>
		<td>☠</td>
		<td style="text-align: right;"><tt>:atom:</tt></td>
		<td>⚛</td>
		<td style="text-align: right;"><tt>:radioactive:</tt></td>
		<td>☢</td>
		<td style="text-align: right;"><tt>:biohazard:</tt></td>
		<td>☣</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:moon:</tt></td>
		<td>☽</td>
		<td style="text-align: right;"><tt>:square:</tt></td>
		<td>■</td>
		<td style="text-align: right;"><tt>:circle:</tt></td>
		<td>●</td>
		<td style="text-align: right;"><tt>:triangle:</tt></td>
		<td>▲</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:arrow:</tt></td>
		<td>➔</td>
		<td style="text-align: right;"><tt>:arrowhead:</tt></td>
		<td>▶</td>
		<td style="text-align: right;"><tt>:bullet:</tt></td>
		<td>◉</td>
		<td style="text-align: right;"><tt>:love:</tt></td>
		<td>♥</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:heart:</tt></td>
		<td>♥</td>
		<td style="text-align: right;"><tt>:spade:</tt></td>
		<td>♠</td>
		<td style="text-align: right;"><tt>:diamond:</tt></td>
		<td>♦</td>
		<td style="text-align: right;"><tt>:club:</tt></td>
		<td>♣</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:note:</tt></td>
		<td>♩</td>
		<td style="text-align: right;"><tt>:recycle:</tt></td>
		<td>♻</td>
		<td style="text-align: right;"><tt>:flag:</tt></td>
		<td>⚑</td>
		<td style="text-align: right;"><tt>:scale:</tt></td>
		<td>⚖</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:warning:</tt></td>
		<td>⚠</td>
		<td style="text-align: right;"><tt>/!\</tt></td>
		<td>⚠</td>
		<td style="text-align: right;"><tt>:peace:</tt></td>
		<td>☮</td>
		<td style="text-align: right;"><tt>:yinyang:</tt></td>
		<td>☯</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:clock:</tt></td>
		<td>⌚</td>
		<td style="text-align: right;"><tt>:hourglass:</tt></td>
		<td>⌛</td>
		<td style="text-align: right;"><tt>:command:</tt></td>
		<td>⌘</td>
		<td style="text-align: right;"><tt>:enter:</tt></td>
		<td>⎆</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:infinity:</tt></td>
		<td>∞</td>
		<td colspan="6"></td>
	</tr>
</table>
<table class="table table-striped table-bordered table-condensed">
	<tr>
		<td style="text-align: right;"><tt>:dice1:</tt></td>
		<td>⚀</td>
		<td style="text-align: right;"><tt>:dice2:</tt></td>
		<td>⚁</td>
		<td style="text-align: right;"><tt>:dice3:</tt></td>
		<td>⚂</td>
		<td style="text-align: right;"><tt>:dice4:</tt></td>
		<td>⚃</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:dice5:</tt></td>
		<td>⚄</td>
		<td style="text-align: right;"><tt>:dice6:</tt></td>
		<td>⚅</td>
		<td colspan="4"></td>
	</tr>
</table>
<table class="table table-striped table-bordered table-condensed">
	<tr>
		<td style="text-align: right;"><tt>:_1/2_:</tt></td>
		<td>½</td>
		<td style="text-align: right;"><tt>:_1/3_:</tt></td>
		<td>⅓</td>
		<td style="text-align: right;"><tt>:_2/3_:</tt></td>
		<td>⅔</td>
		<td style="text-align: right;"><tt>:_1/4_:</tt></td>
		<td>¼</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:_3/4_:</tt></td>
		<td>¾</td>
		<td style="text-align: right;"><tt>:_1/5_:</tt></td>
		<td>⅕</td>
		<td style="text-align: right;"><tt>:_2/5_:</tt></td>
		<td>⅖</td>
		<td style="text-align: right;"><tt>:_3/5_:</tt></td>
		<td>⅗</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:_4/5_:</tt></td>
		<td>⅘</td>
		<td colspan="6"></td>
	</tr>
</table>
<table class="table table-striped table-bordered table-condensed">
	<tr>
		<td style="text-align: right;"><tt>:_1_:</tt></td>
		<td>➊</td>
		<td style="text-align: right;"><tt>:_2_:</tt></td>
		<td>➋</td>
		<td style="text-align: right;"><tt>:_3_:</tt></td>
		<td>➌</td>
		<td style="text-align: right;"><tt>:_4_:</tt></td>
		<td>➍</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:_5_:</tt></td>
		<td>➎</td>
		<td style="text-align: right;"><tt>:_6_:</tt></td>
		<td>➏</td>
		<td style="text-align: right;"><tt>:_7_:</tt></td>
		<td>➐</td>
		<td style="text-align: right;"><tt>:_8_:</tt></td>
		<td>➑</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:_9_:</tt></td>
		<td>➒</td>
		<td style="text-align: right;"><tt>:_10_:</tt></td>
		<td>➓</td>
		<td style="text-align: right;"><tt>:_11_:</tt></td>
		<td>⓫</td>
		<td style="text-align: right;"><tt>:_12_:</tt></td>
		<td>⓬</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:_13_:</tt></td>
		<td>⓭</td>
		<td style="text-align: right;"><tt>:_14_:</tt></td>
		<td>⓮</td>
		<td style="text-align: right;"><tt>:_15_:</tt></td>
		<td>⓯</td>
		<td style="text-align: right;"><tt>:_16_:</tt></td>
		<td>⓰</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:_17_:</tt></td>
		<td>⓱</td>
		<td style="text-align: right;"><tt>:_18_:</tt></td>
		<td>⓲</td>
		<td style="text-align: right;"><tt>:_19_:</tt></td>
		<td>⓳</td>
		<td style="text-align: right;"><tt>:_20_:</tt></td>
		<td>⓴</td>
	</tr>
</table>
<table class="table table-striped table-bordered table-condensed">
	<tr>
		<td style="text-align: right;"><tt>:_A_:</tt></td>
		<td>Ⓐ</td>
		<td style="text-align: right;"><tt>:_B_:</tt></td>
		<td>Ⓑ</td>
		<td style="text-align: right;"><tt>:_C_:</tt></td>
		<td>Ⓒ</td>
		<td style="text-align: right;"><tt>:_D_:</tt></td>
		<td>Ⓓ</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:_E_:</tt></td>
		<td>Ⓔ</td>
		<td style="text-align: right;"><tt>:_F_:</tt></td>
		<td>Ⓕ</td>
		<td style="text-align: right;"><tt>:_G_:</tt></td>
		<td>Ⓖ</td>
		<td style="text-align: right;"><tt>:_H_:</tt></td>
		<td>Ⓗ</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:_I_:</tt></td>
		<td>Ⓘ</td>
		<td style="text-align: right;"><tt>:_J_:</tt></td>
		<td>Ⓙ</td>
		<td style="text-align: right;"><tt>:_K_:</tt></td>
		<td>Ⓚ</td>
		<td style="text-align: right;"><tt>:_L_:</tt></td>
		<td>Ⓛ</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:_M_:</tt></td>
		<td>Ⓜ</td>
		<td style="text-align: right;"><tt>:_N_:</tt></td>
		<td>Ⓝ</td>
		<td style="text-align: right;"><tt>:_O_:</tt></td>
		<td>Ⓞ</td>
		<td style="text-align: right;"><tt>:_P_:</tt></td>
		<td>Ⓟ</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:_Q_:</tt></td>
		<td>Ⓠ</td>
		<td style="text-align: right;"><tt>:_R_:</tt></td>
		<td>Ⓡ</td>
		<td style="text-align: right;"><tt>:_S_:</tt></td>
		<td>Ⓢ</td>
		<td style="text-align: right;"><tt>:_T_:</tt></td>
		<td>Ⓣ</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:_U_:</tt></td>
		<td>Ⓤ</td>
		<td style="text-align: right;"><tt>:_V_:</tt></td>
		<td>Ⓥ</td>
		<td style="text-align: right;"><tt>:_W_:</tt></td>
		<td>Ⓦ</td>
		<td style="text-align: right;"><tt>:_X_:</tt></td>
		<td>Ⓧ</td>
	</tr>
	<tr>
		<td style="text-align: right;"><tt>:_Y_:</tt></td>
		<td>Ⓨ</td>
		<td style="text-align: right;"><tt>:_Z_:</tt></td>
		<td>Ⓩ</td>
		<td colspan="4"></td>
	</tr>
</table>



<h2 id="extensions">18. Extensions</h2>
<p>
	Skriv Markup has an extension mechanism, designed to add new features to the language without
	modifying its basic syntax. Extensions may also be called “plugins”.
</p>
<p>
	Extensions are validated before becoming a part of the official Skriv Markup syntax. Official extensions
	SHOULD be available in any Skriv Markup implementation, but they COULD be deactivated at will.<br />
	Unofficial extensions MAY be activated at will.
</p>
<p>
	Look at the <a href="https://markup.skriv.org/language/extensions">page about extensions</a> to get the list of validated plugins.
</p>

<h3 id="extensions-inline">18.1 Inline</h3>
<p>
	Inline extensions are written using double-angle brackets (<tt>&lt;&lt; &gt;&gt;</tt>). The extension's
	name must be written just after the opening brackets. If the plugin needs some parameters, they are
	added just after, separated by pipe (<tt>|</tt>) characters.
</p>
<p>
	Here is an example plugin, which goal is to insert the given number of “lorem ipsum” paragraphs.
</p>
<div class="label">Skriv Markup</div>
<pre><b class="red">&lt;&lt;</b><b class="blue">lipsum</b><b class="red">|</b>2<b class="red">&gt;&gt;</b></pre>
<div class="label">HTML</div>
<pre>&lt;p&gt;
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque leo sem,
    commodo quis tempus luctus, tempor vel libero. Phasellus rutrum ipsum accumsan
    mauris gravida nec ultricies ante mattis. Ut et nibh neque.
&lt;/p&gt;
&lt;p&gt;
    Praesent pulvinar rhoncus tincidunt. Ut eleifend sollicitudin nibh sed
    porttitor. In hac habitasse platea dictumst. Etiam bibendum mi id ligula
    blandit pulvinar et quis neque. Duis sagittis tempus tellus at rutrum.
&lt;/p&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	Angle brackets are not used for any other element of the Skriv Markup syntax.
	However, they are immediately identified as special markup, because of their usage in HTML.
</div>


<h3 id="extensions-block">18.2 Block</h3>
<p>
	Block extensions are very similar to inline ones. They are delimited by triple-angle brackets
	(<tt>&lt;&lt;&lt; &gt;&gt;&gt;</tt>), with the name and possible options just behind the opening
	brackets.
</p>
<p>
	Here is an example plugin, which translates the given text. The first parameter is the input language,
	the second parameter is the output language.
</p>
<div class="label">Skriv Markup</div>
<pre><b class="red">&lt;&lt;&lt;</b><b class="blue">translate</b><b class="red">|</b>french<b class="red">|</b>english
écrire, travailler, organiser
<b class="red">&gt;&gt;&gt;</b></pre>
<div class="label">HTML</div>
<pre>&lt;p&gt;
    write, work, organize
&lt;/p&gt;</pre>
<div class="label label-info">Reasoning</div>
<div class="alert alert-info">
	Same reasoning than for inline extensions. Triple-characters are used for blocks as usual.
</div>


			</div>
		</div>
	</div>

	<footer class="footer">
		<div class="container">
			<p>
				© 2013, Amaury Bouchard | <a href="http://skriv.org">Skriv</a> [write/work/organize]
			</p>
		</div>
	</footer>


</body>
</html>

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/Makefile from [7ca1dd31f3] to [7915fce3ed].

8
9
10
11
12
13
14


15
16
17
18
19
20
21
	wget ${KD2_FILE} -O ${TMP_KD2}/kd2.zip

	rm -rf "include/lib/KD2"
	unzip "${TMP_KD2}/kd2.zip" -d include/lib

	rm -rf ${TMP_KD2}



dev-server:
	php -S localhost:8082 -t www www/_route.php

test:
	find . -name '*.php' -print0 | xargs -0 -n1 php -l > /dev/null

phpstan:







>
>







8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
	wget ${KD2_FILE} -O ${TMP_KD2}/kd2.zip

	rm -rf "include/lib/KD2"
	unzip "${TMP_KD2}/kd2.zip" -d include/lib

	rm -rf ${TMP_KD2}

	wget -O "include/lib/Parsedown.php" "https://raw.githubusercontent.com/erusev/parsedown/1.7.x/Parsedown.php"

dev-server:
	php -S localhost:8082 -t www www/_route.php

test:
	find . -name '*.php' -print0 | xargs -0 -n1 php -l > /dev/null

phpstan:
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
		rsync --files-from=dependencies.list -r ./ /tmp/garradin-build/garradin/src/include/lib/
	mv www/admin/static/mini.css /tmp/garradin-build/garradin/src/www/admin/static/admin.css
	cd /tmp/garradin-build/garradin/src/www/admin/static; \
		rm -f styles/[0-9]*.css; \
		rm -f font/*.css font/*.json
	cd /tmp/garradin-build/garradin/src; \
		rm -f Makefile include/lib/KD2/data/countries.en.json
	cd /tmp/garradin-build/garradin/src/plugins; \
		wget https://fossil.kd2.org/garradin-plugins/uv/welcome.tar.gz
	mv /tmp/garradin-build/garradin/src /tmp/garradin-build/garradin-${VERSION}
	@#cd /tmp/garradin-build/; zip -r -9 garradin-${VERSION}.zip garradin-${VERSION};
	@#mv -f /tmp/garradin-build/garradin-${VERSION}.zip ./
	tar cjvfh garradin-${VERSION}.tar.bz2 -C /tmp/garradin-build garradin-${VERSION}

deb:
	cd ../debian; ./makedeb.sh

publish: release deb
	$(eval VERSION=$(shell cat VERSION))

	fossil uv sync
	#fossil uv ls | fgrep -v 'garradin-0.8.5' | grep '^garradin-.*\.(tar\.bz2|deb)' | xargs fossil uv rm
	fossil uv add garradin-${VERSION}.tar.bz2

	cd ../debian && fossil uv add garradin-${VERSION}-*.deb
	fossil uv sync

check-dependencies:
	grep -hEo '^use \\?KD2\\[^; ]+|\\KD2\\[^\(:; ]+' -R include/lib/Garradin www | sed -r 's/^use \\?KD2\\|^\\KD2\\//' | sort | uniq

minify:
	cat `ls www/admin/static/styles/[0-9]*.css` | sed 's/\.\.\///' > www/admin/static/mini.css
	# Minify is only gaining 500 gzipped bytes (4kB uncompressed) but making things hard to read/hack
	#yui-compressor --nomunge www/admin/static/mini.css -o www/admin/static/mini.css







|











>



>










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
		rsync --files-from=dependencies.list -r ./ /tmp/garradin-build/garradin/src/include/lib/
	mv www/admin/static/mini.css /tmp/garradin-build/garradin/src/www/admin/static/admin.css
	cd /tmp/garradin-build/garradin/src/www/admin/static; \
		rm -f styles/[0-9]*.css; \
		rm -f font/*.css font/*.json
	cd /tmp/garradin-build/garradin/src; \
		rm -f Makefile include/lib/KD2/data/countries.en.json
	cd /tmp/garradin-build/garradin/src/data; mkdir plugins && cd plugins; \
		wget https://fossil.kd2.org/garradin-plugins/uv/welcome.tar.gz
	mv /tmp/garradin-build/garradin/src /tmp/garradin-build/garradin-${VERSION}
	@#cd /tmp/garradin-build/; zip -r -9 garradin-${VERSION}.zip garradin-${VERSION};
	@#mv -f /tmp/garradin-build/garradin-${VERSION}.zip ./
	tar cjvfh garradin-${VERSION}.tar.bz2 -C /tmp/garradin-build garradin-${VERSION}

deb:
	cd ../debian; ./makedeb.sh

publish: release deb
	$(eval VERSION=$(shell cat VERSION))
	gpg --armor --detach-sign garradin-${VERSION}.tar.bz2
	fossil uv sync
	#fossil uv ls | fgrep -v 'garradin-0.8.5' | grep '^garradin-.*\.(tar\.bz2|deb)' | xargs fossil uv rm
	fossil uv add garradin-${VERSION}.tar.bz2
	fossil uv add garradin-${VERSION}.tar.bz2.asc
	cd ../debian && fossil uv add garradin-${VERSION}-*.deb
	fossil uv sync

check-dependencies:
	grep -hEo '^use \\?KD2\\[^; ]+|\\KD2\\[^\(:; ]+' -R include/lib/Garradin www | sed -r 's/^use \\?KD2\\|^\\KD2\\//' | sort | uniq

minify:
	cat `ls www/admin/static/styles/[0-9]*.css` | sed 's/\.\.\///' > www/admin/static/mini.css
	# Minify is only gaining 500 gzipped bytes (4kB uncompressed) but making things hard to read/hack
	#yui-compressor --nomunge www/admin/static/mini.css -o www/admin/static/mini.css

Modified src/VERSION from [05e17b646a] to [c8739f9425].

1
1.1.0
|
1
1.1.12

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 [a935d67622] to [5339c9e64e].

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)
 */

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

































 * 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,
 * %s doit être ajouté à la fin pour indiquer le répertoire et nom du fichier
 *

 * Défaut : null
 *
 * @vararray
 */

//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)
 */

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








































>
>
>
>













|
<

>
|

|











|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
 * 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
 *
 * ATTENTION : activer FileSystem ET ne pas utiliser de sous-domaine (vhost dédié)
 * ferait courir de graves risques de piratage à votre serveur web si vous ne protégez
 * pas correctement le répertoire de stockage des fichiers !
 *
 * 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

/**
 * Commande de création de PDF
 *
 * Commande qui sera exécutée pour créer un fichier PDF à partir d'un HTML.
 * Si laissé non spécifié (ou NULL), Garradin essaiera de détecter une solution entre
 * PrinceXML, Chromium, wkhtmltopdf ou weasyprint.
 *
 * %1$s sera remplacé par le chemin du fichier HTML, et %2$s par le chemin du fichier PDF.
 *
 * Exemple : chromium --headless --print-to-pdf=%2$s %1$s
 *
 * Défaut : null
 */
//const PDF_COMMAND = 'wkhtmltopdf %2$s %1$s';

/**
 * Clé de licence
 *
 * Cette clé permet de débloquer certaines fonctionnalités dans des extensions officielles.
 *
 * Pour l'obtenir il faut se créer un compte sur Garradin.eu
 * et faire une contribution financière.
 * La clé apparaîtra ensuite en dessous des informations
 * de l'association dans la page "Mon abonnement Garradin.eu".
 *
 * Il faut recopier cette clé dans le fichier config.local.php
 * dans la constante CONTRIBUTOR_LICENSE.
 *
 * Merci de ne pas essayer de contourner cette licence et de contribuer au
 * financement de notre travail :-)
 */
//const CONTRIBUTOR_LICENSE = 'XXXXX';

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 [ba81ccc806] to [074699bf2f].

15
16
17
18
19
20
21
22
23
24
25
26
27
28


29
30
31
32
33
34
35
36
-------- MIGRATION COMPTA ---------
INSERT INTO acc_charts (id, country, code, label) VALUES (1, 'FR', 'PCGA1999', 'Plan comptable associatif 1999');

-- Migration comptes de code comme identifiant à ID unique
-- Inversement valeurs actif/passif et produit/charge
INSERT INTO acc_accounts (id, id_chart, code, label, position, user)
	SELECT NULL, 1, id, libelle,
	CASE position
		WHEN 1 THEN 2
		WHEN 2 THEN 1
		WHEN 3 THEN 3
		WHEN 4 THEN 5
		WHEN 8 THEN 4
		-- Suppression de la position "charge ou produit" qui n'a aucun sens


		WHEN 12 THEN 0
		ELSE 0
	END,
	CASE WHEN plan_comptable = 1 THEN 0 ELSE 1 END
	FROM compta_comptes;

-- Migrations projets vers comptes analytiques
INSERT INTO acc_accounts (id_chart, code, label, position, user, type)







|
|
|
|
|
|

>
>
|







15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
-------- MIGRATION COMPTA ---------
INSERT INTO acc_charts (id, country, code, label) VALUES (1, 'FR', 'PCGA1999', 'Plan comptable associatif 1999');

-- Migration comptes de code comme identifiant à ID unique
-- Inversement valeurs actif/passif et produit/charge
INSERT INTO acc_accounts (id, id_chart, code, label, position, user)
	SELECT NULL, 1, id, libelle,
	CASE
		WHEN position = 1 THEN 2
		WHEN position = 2 THEN 1
		WHEN position = 3 THEN 3
		WHEN position = 4 THEN 5
		WHEN position = 8 THEN 4
		-- Suppression de la position "charge ou produit" qui n'a aucun sens
		WHEN position = 12 AND id LIKE '6%' THEN 4
		WHEN position = 12 AND id LIKE '7%' THEN 5
		WHEN position = 12 THEN 0
		ELSE 0
	END,
	CASE WHEN plan_comptable = 1 THEN 0 ELSE 1 END
	FROM compta_comptes;

-- Migrations projets vers comptes analytiques
INSERT INTO acc_accounts (id_chart, code, label, position, user, type)
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
UPDATE acc_accounts SET type = 5, description = (SELECT description FROM compta_categories WHERE compte = acc_accounts.code)
	WHERE id IN (SELECT a.id FROM acc_accounts a INNER JOIN compta_categories c ON c.compte = a.code AND c.type = -1 AND c.compte NOT LIKE '4%' AND a.position = 4);

-- Tiers
UPDATE acc_accounts SET type = 4, description = (SELECT description FROM compta_categories WHERE compte = acc_accounts.code)
	WHERE id IN (SELECT a.id FROM acc_accounts a INNER JOIN compta_categories c ON c.compte = a.code AND c.type = -1 AND c.compte LIKE '4%');

-- Recopie des opérations, mais le nom a changé pour acc_transactions_users
INSERT INTO acc_transactions_users
	SELECT * FROM membres_operations_old;

-- Recopie des exercices, mais la date de fin ne peut être nulle
INSERT INTO acc_years (id, label, start_date, end_date, closed, id_chart)
	SELECT id, libelle, debut, CASE WHEN fin IS NULL THEN date(debut, '+1 year') ELSE fin END, cloture, 1 FROM compta_exercices;

-- Recopie des catégories, on supprime la colonne id_cotisation_obligatoire
INSERT INTO membres_categories
	SELECT id, nom, droit_wiki, droit_membres, droit_compta, droit_inscription, droit_connexion, droit_config, cacher FROM membres_categories_old;

DROP TABLE membres_categories_old;

-- Transfert des rapprochements
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;

INSERT INTO services_users SELECT cm.id, cm.id_membre, cm.id_cotisation,
	cm.id_cotisation,
	1,
	NULL,
	cm.date,







<
<
<
<

















>






|







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
UPDATE acc_accounts SET type = 5, description = (SELECT description FROM compta_categories WHERE compte = acc_accounts.code)
	WHERE id IN (SELECT a.id FROM acc_accounts a INNER JOIN compta_categories c ON c.compte = a.code AND c.type = -1 AND c.compte NOT LIKE '4%' AND a.position = 4);

-- Tiers
UPDATE acc_accounts SET type = 4, description = (SELECT description FROM compta_categories WHERE compte = acc_accounts.code)
	WHERE id IN (SELECT a.id FROM acc_accounts a INNER JOIN compta_categories c ON c.compte = a.code AND c.type = -1 AND c.compte LIKE '4%');





-- Recopie des exercices, mais la date de fin ne peut être nulle
INSERT INTO acc_years (id, label, start_date, end_date, closed, id_chart)
	SELECT id, libelle, debut, CASE WHEN fin IS NULL THEN date(debut, '+1 year') ELSE fin END, cloture, 1 FROM compta_exercices;

-- Recopie des catégories, on supprime la colonne id_cotisation_obligatoire
INSERT INTO membres_categories
	SELECT id, nom, droit_wiki, droit_membres, droit_compta, droit_inscription, droit_connexion, droit_config, cacher FROM membres_categories_old;

DROP TABLE membres_categories_old;

-- Transfert des rapprochements
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;
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 GROUP BY closed ORDER BY closed LIMIT 1)
	FROM cotisations;

INSERT INTO services_users SELECT cm.id, cm.id_membre, cm.id_cotisation,
	cm.id_cotisation,
	1,
	NULL,
	cm.date,
154
155
156
157
158
159
160






161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176




































INSERT INTO services_reminders SELECT * FROM rappels;
INSERT INTO services_reminders_sent SELECT id, id_membre, id_cotisation,
	CASE WHEN id_rappel IS NULL THEN (SELECT MAX(id) FROM rappels) ELSE id_rappel END, date
	FROM rappels_envoyes
	WHERE id_rappel IS NOT NULL
	GROUP BY id_membre, id_cotisation, id_rappel;







DROP TABLE cotisations;
DROP TABLE cotisations_membres;
DROP TABLE rappels;
DROP TABLE rappels_envoyes;

-- Suppression inutilisées
DROP TABLE compta_rapprochement;
DROP TABLE compta_journal;
DROP TABLE compta_categories;
DROP TABLE compta_comptes;
DROP TABLE compta_exercices;
DROP TABLE membres_operations_old;

DROP TABLE compta_projets;
DROP TABLE compta_comptes_bancaires;
DROP TABLE compta_moyens_paiement;











































>
>
>
>
>
>
















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
INSERT INTO services_reminders SELECT * FROM rappels;
INSERT INTO services_reminders_sent SELECT id, id_membre, id_cotisation,
	CASE WHEN id_rappel IS NULL THEN (SELECT MAX(id) FROM rappels) ELSE id_rappel END, date
	FROM rappels_envoyes
	WHERE id_rappel IS NOT NULL
	GROUP BY id_membre, id_cotisation, id_rappel;

-- Recopie des opérations par membre, mais le nom a changé pour acc_transactions_users, et il faut valider l'existence du membre ET du service
INSERT INTO acc_transactions_users
	SELECT a.* FROM membres_operations_old a
	INNER JOIN membres b ON b.id = a.id_membre
	INNER JOIN services_users c ON c.id = a.id_cotisation;

DROP TABLE cotisations;
DROP TABLE cotisations_membres;
DROP TABLE rappels;
DROP TABLE rappels_envoyes;

-- Suppression inutilisées
DROP TABLE compta_rapprochement;
DROP TABLE compta_journal;
DROP TABLE compta_categories;
DROP TABLE compta_comptes;
DROP TABLE compta_exercices;
DROP TABLE membres_operations_old;

DROP TABLE compta_projets;
DROP TABLE compta_comptes_bancaires;
DROP TABLE compta_moyens_paiement;

INSERT INTO acc_charts (country, code, label) VALUES ('FR', 'PCA2018', 'Plan comptable associatif 2018');

CREATE TEMP TABLE tmp_accounts (code,label,description,position,type);

.import charts/fr_2018.csv tmp_accounts

INSERT INTO acc_accounts (id_chart, code, label, description, position, type) SELECT
	(SELECT id FROM acc_charts WHERE code = 'PCA2018'),
	code, label, description,
	CASE position
		WHEN 'Actif' THEN 1
		WHEN 'Passif' THEN 2
		WHEN 'Actif ou passif' THEN 3
		WHEN 'Charge' THEN 4
		WHEN 'Produit' THEN 5
		ELSE 0
	END,
	CASE type
		WHEN 'Banque' THEN 1
		WHEN 'Caisse' THEN 2
		WHEN 'Attente d''encaissement' THEN 3
		WHEN 'Tiers' THEN 4
		WHEN 'Dépenses' THEN 5
		WHEN 'Recettes' THEN 6
		WHEN 'Analytique' THEN 7
		WHEN 'Bénévolat' THEN 8
		WHEN 'Ouverture' THEN 9
		WHEN 'Clôture' THEN 10
		WHEN 'Résultat excédentaire' THEN 11
		WHEN 'Résultat déficitaire' THEN 12
		ELSE 0
	END
	FROM tmp_accounts;

DROP TABLE tmp_accounts;

Modified src/include/data/1.0.0_schema.sql from [4710567bc0] to [292ae06778].

262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    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);
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,








|







262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    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,

287
288
289
290
291
292
293

294
295
296
297
298
299
300

    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_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
(







>







287
288
289
290
291
292
293
294
295
296
297
298
299
300
301

    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
(

Added src/include/data/1.0.3_migration.sql version [9ded2b030d].





>
>
1
2
-- Fix services connected to old closed year
UPDATE services_fees SET id_year = NULL, id_account = NULL WHERE id_year IN (SELECT id FROM acc_years WHERE closed = 1);

Added src/include/data/1.0.6_migration.sql version [6e98c5399a].





>
>
1
2
-- Fix credit/debt payment types
UPDATE acc_transactions SET type = 0 WHERE id_related IS NOT NULL AND type IN (4,5);

Added src/include/data/1.0.7_migration.sql version [f53124e2db].











>
>
>
>
>
1
2
3
4
5
-- Add indexes
DROP INDEX IF EXISTS acc_transactions_type;
CREATE INDEX IF NOT EXISTS acc_transactions_type ON acc_transactions (type, id_year);

CREATE INDEX IF NOT EXISTS acc_transactions_lines_transaction ON acc_transactions_lines (id_transaction);

Modified src/include/data/1.1.0_migration.sql from [35b0e66a01] to [9f5de55bec].


















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

















ALTER TABLE membres_categories RENAME TO membres_categories_old;




.read 1.1.0_schema.sql

INSERT INTO files_contents (id, hash, content, size)

	SELECT id, hash, contenu, taille FROM fichiers_contenu;





INSERT INTO files (id, hash, folder_id, name, type, created, author_id, public, image)
	SELECT f.id, c.hash, NULL, nom, type, datetime, NULL, 0, image FROM fichiers f INNER JOIN fichiers_contenu c ON c.id = f.id_contenu;









INSERT INTO membres_categories
	SELECT id, nom,
		droit_wiki, -- droit_web
		droit_wiki, -- droit_documents
		droit_membres,
		droit_compta,
		droit_inscription,
		droit_connexion,
		droit_config,
		cacher
	FROM membres_categories_old;

DROP TABLE membres_categories_old;




































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


INSERT INTO wiki_as_files
	SELECT
		id, NULL, sha1(contenu), LENGTH(contenu), contenu,
		uri || '.skriv', titre, uri, parent, NULL,
		date_creation, date_modification, id_auteur, chiffrement, 0, NULL,
		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
	INNER JOIN wiki_revisions r ON r.id_page = p.id AND r.revision = p.revision;




UPDATE wiki_as_files SET name = 'index.skriv' WHERE type = 1;

-- Build back path, up to ten levels
--UPDATE wiki_as_files waf SET
--	path = (SELECT uri FROM wiki_as_files WHERE id = waf.parent) || '/' || path,

--	parent = (SELECT parent FROM wiki_as_files WHERE id = waf.parent)

--	WHERE parent > 0;







-- Create private folders
INSERT INTO files_folders (id, parent_id, name, system)

	SELECT old_id, old_parent, uri, 0 FROM wiki_as_files WHERE type = 1;

-- Create web folders
INSERT INTO files_folders (id, parent_id, name, system)








	SELECT old_id + 10000, old_parent + 10000, uri, 1 FROM wiki_as_files WHERE type = 1;

UPDATE files_folders SET parent_id = (SELECT CASE WHEN f.system = 0 THEN f.id ELSE f.id + 10000 END FROM files_folders f WHERE f.id = parent_id);



INSERT INTO files_contents (hash, content, size) SELECT hash, content, size FROM wiki_as_files;





UPDATE wiki_as_files SET content_id = (SELECT fc.id FROM files_contents fc WHERE fc.hash = wiki_as_files.hash);



INSERT INTO files (hash, folder_id, name, type, created, author_id, public, image)
	SELECT
		hash,
		(SELECT CASE WHEN public = 0 THEN f.id ELSE f.id + 10000 END FROM files_folders f WHERE f.id = old_parent),
		name,
		CASE WHEN encrypted THEN 'text/vnd.skriv.encrypted' ELSE 'text/vnd.skriv' END,

		created,


		author_id,

		public,
		image






	FROM wiki_as_files;

INSERT INTO files_search (id, content) SELECT new_id, content FROM wiki_as_files WHERE encrypted = 0;





UPDATE wiki_as_files SET new_id = (SELECT id FROM files WHERE hash = wiki_as_files.hash);

UPDATE wiki_as_files SET new_parent = (SELECT w.new_id FROM wiki_as_files w WHERE w.old_id = wiki_as_files.old_parent);


INSERT INTO web_pages












	SELECT new_id, new_parent, type, 1, uri, title, modified FROM wiki_as_files WHERE public = 1;


INSERT INTO files_links (id, web_page_id)
	SELECT
		id,
		id
	FROM web_pages

	WHERE status = 1;


INSERT INTO files_links (id, file_id)
	SELECT w.fichier, waf.new_id



		FROM fichiers_wiki_pages w
		INNER JOIN wiki_as_files waf ON waf.old_id = w.id
		INNER JOIN files f ON f.hash = waf.hash;












INSERT INTO files_links (id, transaction_id)

	SELECT fichier, id FROM fichiers_acc_transactions;



INSERT INTO files_links (id, config)




	SELECT valeur, cle FROM config WHERE cle = 'image_fond' AND valeur > 0;

UPDATE files SET public = 1 WHERE id = (SELECT valeur FROM config WHERE cle = 'image_fond');



-- Copy connection page
INSERT INTO files (hash, folder_id, name, type, created, author_id, public)
	SELECT hash, NULL, 'Accueil_connexion.skriv', type, created, author_id, 0

	FROM files WHERE id = (SELECT new_id FROM wiki_as_files WHERE uri = (SELECT valeur FROM config WHERE cle = 'accueil_connexion'));




UPDATE config SET valeur = (SELECT id FROM files WHERE name = 'Accueil_connexion.skriv') WHERE cle = 'accueil_connexion';
UPDATE config SET cle = 'admin_homepage' WHERE cle = 'accueil_connexion';
DELETE FROM config WHERE cle = 'accueil_wiki';
INSERT INTO config (cle, valeur) VALUES ('telephone_asso', NULL);




DROP TRIGGER wiki_recherche_delete;


DROP TRIGGER wiki_recherche_update;

DROP TRIGGER wiki_recherche_contenu_insert;
DROP TRIGGER wiki_recherche_contenu_chiffre;


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

>
>
>



|
>
|
>
>
>

>
|
|
>
>
>
>
>
>
>

>
|

|
|










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

|
>



|
<
|



|

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

|
|
>
>
>
>
>
>
>
>
|

<
>

>
|
>
>
>
>
>
|
>

>
|

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


<
>

>
>
>
|
>
|

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

|

|
<
|
>
|

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

>
|
>
|
>
>

|
>
>
>
>
|

<
>
>

|
|
<
>
|
>

>
>
|
<
|
|

>
>
>
|
>
>
|
>
|
|
>












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 WHERE email IS NOT NULL 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;

Modified src/include/data/1.1.0_schema.sql from [fd9926396b] to [e065264ec5].

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
CREATE TABLE IF NOT EXISTS config (
-- Configuration de Garradin
    cle TEXT PRIMARY KEY NOT NULL,
    valeur TEXT
);

CREATE TABLE IF NOT EXISTS membres_categories
-- Catégories de membres
(
    id INTEGER PRIMARY KEY NOT NULL,
    nom TEXT NOT NULL,


    droit_wiki INTEGER NOT NULL DEFAULT 1,
    droit_membres INTEGER NOT NULL DEFAULT 1,
    droit_compta INTEGER NOT NULL DEFAULT 1,


    droit_inscription INTEGER NOT NULL DEFAULT 0,
    droit_connexion INTEGER NOT NULL DEFAULT 1,
    droit_config INTEGER NOT NULL DEFAULT 0,

    cacher INTEGER NOT NULL DEFAULT 0
);



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

<
|
|


|
|


|

>
|
|
|
>
>
|
|
|
>
|

>
>







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
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 IF NOT EXISTS 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
    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,







|
|







59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    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 if fee is not linked to accounting, this is reset using a trigger if the year is deleted
    id_year INTEGER NULL REFERENCES acc_years (id) ON DELETE SET NULL -- NULL if fee is not linked to accounting
);

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,
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
(
    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);

--
-- WIKI
--

CREATE TABLE IF NOT EXISTS wiki_pages
-- Pages du wiki
(
    id INTEGER PRIMARY KEY NOT NULL,
    uri TEXT NOT NULL, -- URI unique (équivalent NomPageWiki)
    titre TEXT NOT NULL,
    date_creation TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP CHECK (datetime(date_creation) IS NOT NULL AND datetime(date_creation) = date_creation),
    date_modification TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP CHECK (datetime(date_modification) IS NOT NULL AND datetime(date_modification) = date_modification),
    parent INTEGER NOT NULL DEFAULT 0, -- ID de la page parent
    revision INTEGER NOT NULL DEFAULT 0, -- Numéro de révision (commence à 0 si pas de texte, +1 à chaque changement du texte)
    droit_lecture INTEGER NOT NULL DEFAULT 0, -- Accès en lecture (-1 = public [site web], 0 = tous ceux qui ont accès en lecture au wiki, 1+ = ID de groupe)
    droit_ecriture INTEGER NOT NULL DEFAULT 0 -- Accès en écriture (0 = tous ceux qui ont droit d'écriture sur le wiki, 1+ = ID de groupe)
);

CREATE UNIQUE INDEX IF NOT EXISTS wiki_uri ON wiki_pages (uri);

CREATE VIRTUAL TABLE IF NOT EXISTS wiki_recherche USING fts4
-- Table dupliquée pour chercher une page
(
    id INT PRIMARY KEY NOT NULL, -- Clé externe obligatoire
    titre TEXT NOT NULL,
    contenu TEXT NULL, -- Contenu de la dernière révision
    FOREIGN KEY (id) REFERENCES wiki_pages(id)
);

CREATE TABLE IF NOT EXISTS wiki_revisions
-- Révisions du contenu des pages
(
    id_page INTEGER NOT NULL REFERENCES wiki_pages (id) ON DELETE CASCADE,
    revision INTEGER NULL,

    id_auteur INTEGER NULL REFERENCES membres (id) ON DELETE SET NULL,

    contenu TEXT NOT NULL,
    modification TEXT NULL, -- Description des modifications effectuées
    chiffrement INTEGER NOT NULL DEFAULT 0, -- 1 si le contenu est chiffré, 0 sinon
    date TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP CHECK (datetime(date) IS NOT NULL AND datetime(date) = date),

    PRIMARY KEY(id_page, revision)
);

CREATE INDEX IF NOT EXISTS wiki_revisions_id_page ON wiki_revisions (id_page);
CREATE INDEX IF NOT EXISTS wiki_revisions_id_auteur ON wiki_revisions (id_auteur);

-- Triggers pour synchro avec table wiki_pages
CREATE TRIGGER IF NOT EXISTS wiki_recherche_delete AFTER DELETE ON wiki_pages
    BEGIN
        DELETE FROM wiki_recherche WHERE id = old.id;
    END;

CREATE TRIGGER IF NOT EXISTS wiki_recherche_update AFTER UPDATE OF id, titre ON wiki_pages
    BEGIN
        UPDATE wiki_recherche SET id = new.id, titre = new.titre WHERE id = old.id;
    END;

-- Trigger pour mettre à jour le contenu de la table de recherche lors d'une nouvelle révision
CREATE TRIGGER IF NOT EXISTS wiki_recherche_contenu_insert AFTER INSERT ON wiki_revisions WHEN new.chiffrement != 1
    BEGIN
        UPDATE wiki_recherche SET contenu = new.contenu WHERE id = new.id_page;
    END;

-- Si le contenu est chiffré, la recherche n'affiche pas de contenu
CREATE TRIGGER IF NOT EXISTS wiki_recherche_contenu_chiffre AFTER INSERT ON wiki_revisions WHEN new.chiffrement = 1
    BEGIN
        UPDATE wiki_recherche SET contenu = '' WHERE id = new.id_page;
    END;

--
-- COMPTA
--

CREATE TABLE IF NOT EXISTS acc_charts
-- Plans comptables : il peut y en avoir plusieurs
(







|
>


|




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







106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121







































































122
123
124
125
126
127
128
(
    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,

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

CREATE UNIQUE INDEX IF NOT EXISTS srs_index ON services_reminders_sent (id_user, id_service, id_reminder, due_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
(
230
231
232
233
234
235
236





237
238
239
240
241
242
243

    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)







>
>
>
>
>







165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183

    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);

-- Make sure id_account is reset when a year is deleted
CREATE TRIGGER IF NOT EXISTS acc_years_delete BEFORE DELETE ON acc_years BEGIN
    UPDATE services_fees SET id_account = NULL, id_year = NULL WHERE id_year = OLD.id;
END;

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)
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
    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);
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,








|







198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
    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,

283
284
285
286
287
288
289

290
291
292
293
294
295
296

    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_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
(







>







223
224
225
226
227
228
229
230
231
232
233
234
235
236
237

    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
(
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
(
    signal TEXT NOT NULL,
    plugin TEXT NOT NULL REFERENCES plugins (id),
    callback TEXT NOT NULL,
    PRIMARY KEY (signal, plugin)
);



CREATE TABLE IF NOT EXISTS fichiers
-- Données sur les fichiers
(
    id INTEGER NOT NULL PRIMARY KEY,


    nom TEXT NOT NULL, -- nom de fichier (par exemple image1234.jpeg)

    type TEXT NULL, -- Type MIME
    image INTEGER NOT NULL DEFAULT 0, -- 1 = image reconnue
    datetime TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP CHECK (datetime(datetime) IS NOT NULL AND datetime(datetime) = datetime), -- Date d'ajout ou mise à jour du fichier

    id_contenu INTEGER NOT NULL REFERENCES fichiers_contenu (id) ON DELETE CASCADE

);




CREATE INDEX IF NOT EXISTS fichiers_date ON fichiers (datetime);


CREATE TABLE IF NOT EXISTS fichiers_contenu
-- Contenu des fichiers
(
    id INTEGER NOT NULL PRIMARY KEY,
    hash TEXT NOT NULL, -- Hash SHA1 du contenu du fichier
    taille INTEGER NOT NULL, -- Taille en octets
    contenu BLOB NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS fichiers_hash ON fichiers_contenu (hash);

CREATE TABLE IF NOT EXISTS fichiers_membres
-- Associations entre fichiers et membres (photo de profil par exemple)
(

    fichier INTEGER NOT NULL REFERENCES fichiers (id) ON DELETE CASCADE,

    id INTEGER NOT NULL REFERENCES membres (id) ON DELETE CASCADE,
    PRIMARY KEY(fichier, id)
);

CREATE TABLE IF NOT EXISTS fichiers_wiki_pages
-- Associations entre fichiers et pages du wiki
(
    fichier INTEGER NOT NULL REFERENCES fichiers (id) ON DELETE CASCADE,
    id INTEGER NOT NULL REFERENCES wiki_pages (id) ON DELETE CASCADE,


    PRIMARY KEY(fichier, id)








);






CREATE TABLE IF NOT EXISTS fichiers_acc_transactions
-- Associations entre fichiers et journal de compta (pièce comptable par exemple)
(
    fichier INTEGER NOT NULL REFERENCES fichiers (id) ON DELETE CASCADE,
    id INTEGER NOT NULL REFERENCES acc_transactions (id) ON DELETE CASCADE,
    PRIMARY KEY(fichier, id)
);

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),







>
>
|
|


>
>
|
>
|
|
|
>
|
>


>
>
>
|
>

|
|

|
|
<
|


|
|
<
<

>
|
>
|
|


|
<

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


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







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
(
    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 IF NOT EXISTS web_pages_path ON web_pages (path);
CREATE UNIQUE INDEX IF NOT EXISTS web_pages_uri ON web_pages (uri);
CREATE UNIQUE INDEX IF NOT EXISTS web_pages_file_path ON web_pages (file_path);
CREATE INDEX IF NOT EXISTS web_pages_parent ON web_pages (parent);
CREATE INDEX IF NOT EXISTS web_pages_published ON web_pages (published);
CREATE INDEX IF NOT EXISTS 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),

Added src/include/data/1.1.3_migration.sql version [18eac8e4eb].









>
>
>
>
1
2
3
4
-- Make sure id_account is reset when a year is deleted
CREATE TRIGGER IF NOT EXISTS acc_years_delete BEFORE DELETE ON acc_years BEGIN
    UPDATE services_fees SET id_account = NULL, id_year = NULL WHERE id_year = OLD.id;
END;

Added src/include/data/1.1.7_migration.sql version [1dab4145d3].





























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
ALTER TABLE services_reminders_sent RENAME TO srs_old;

-- Add new column in services_reminders_sent
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,

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

CREATE UNIQUE INDEX IF NOT EXISTS srs_index ON services_reminders_sent (id_user, id_service, id_reminder, due_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);

INSERT INTO services_reminders_sent SELECT id, id_user, id_service, id_reminder, date, date FROM srs_old;
DROP TABLE srs_old;

-- Missing acc_years_delete trigger, again, because of missing symlink in previous release
-- Make sure id_account is reset when a year is deleted
CREATE TRIGGER IF NOT EXISTS acc_years_delete BEFORE DELETE ON acc_years BEGIN
    UPDATE services_fees SET id_account = NULL, id_year = NULL WHERE id_year = OLD.id;
END;

Added src/include/data/1.1.8_migration.sql version [cc434f178d].











>
>
>
>
>
1
2
3
4
5
-- Remove any leftover duplicates
DELETE FROM web_pages WHERE id IN (SELECT id FROM web_pages GROUP BY uri HAVING COUNT(*) > 1);

-- Add unique index
CREATE UNIQUE INDEX IF NOT EXISTS web_pages_uri ON web_pages (uri);

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

43
44
45
46
47
48
49

50
51
52
53
54
55
56
57
;	install:
;		true = sera ajouté aux fiches membres à l'installation
;		false = sera seulement présent dans les champs supplémentaires possibles (défaut)

[numero]
type = number
title = "Numéro de membre"

mandatory = true
install = true
editable = false
list_row = 1

[nom]
type = text
title = "Nom & prénom"







>
|







43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
;	install:
;		true = sera ajouté aux fiches membres à l'installation
;		false = sera seulement présent dans les champs supplémentaires possibles (défaut)

[numero]
type = number
title = "Numéro de membre"
help = "Doit être unique, laisser vide pour que le numéro soit attribué automatiquement"
mandatory = false
install = true
editable = false
list_row = 1

[nom]
type = text
title = "Nom & prénom"
131
132
133
134
135
136
137






editable = true

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













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

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

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

Added src/include/data/charts/fr_copro_2020.csv version [31afc3676e].



































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
code,label,description,position,type
1,"Classe 1 — Provisions, avances, subventions et emprunts",,Passif,
10,PROVISIONS ET AVANCES,,Passif,
103,Avances,,Passif,
106,Provisions pour travaux,Provisions pour travaux au titre de la délégation de pouvoirs accordée au conseil syndical,Passif,
11,REPORT À NOUVEAU (SOLDE CRÉDITEUR OU DÉBITEUR),,Passif,
110,Report à nouveau (solde créditeur),,Passif,Résultat excédentaire 
119,Report à nouveau (solde débiteur),,Passif,Résultat déficitaire 
12,Solde en attente sur travaux et opérations exceptionnelles,,Passif,
121,Travaux décidés par l'assemblée générale,,Passif,
122,Travaux délégués au conseil syndical ,,Passif,
13,SUBVENTIONS,,Passif,
131, Subventions accordées en instance de versement,,Passif,
138,Autres subventions d’investissement ,,Passif,
139,Subventions d’investissement inscrites au compte de résultat,,Passif,
4,Classe 4 — COPROPRIÉTAIRES ET TIERS,,Actif ou passif,
40,Fournisseurs,,Actif ou passif,
42,Personnel,,Actif ou passif,
43,SÉCURITÉ SOCIALE &  AUTRES ORGANISMES SOCIAUX,,Passif,
431,Sécurité sociale,,Passif,
432,Autres organismes sociaux,,Passif,
44,ÉTAT ET COLLECTIVITÉS TERRITORIALES ,,Actif,
441,État et autres organismes - subventions à recevoir,,Actif,Tiers
442,État - impôts et versements assimilés,,Actif ou passif,Tiers
443,Collectivités territoriales – aides,,Actif ou passif,
45,COLLECTIVITÉ DES COPROPRIÉTAIRES,,Actif ou passif,
46,DÉBITEURS ET CRÉDITEUR DIVERS,,Actif ou passif,
47,COMPTES D'ATTENTE,,Actif ou passif,
471,Compte en attente d’imputation débiteur,,Actif ou passif,
472,Compte en attente d’imputation créditeur,,Actif ou passif,
48,COMPTES DE RÉGULARISATION,,Actif ou passif,
486,Charges payées d'avance,,Actif,Tiers
487,Produits encaissés d’avance,,Passif,Tiers
49,DÉPRÉCIATIONS DES COMPTES DE TIERS,,Actif ou passif,
491,Copropriétaires,,Passif,Tiers
496,Personnes autres que les copropriétaires,,Passif,Tiers
5,Classe 5 — Comptes financiers,,Actif,
50,FONDS PLACÉS,,Actif,
51,"Banques, ou fonds disponibles en banque pour le syndicat",,Actif,
5112,Chèques à encaisser,,Actif ou passif,Attente d'encaissement
5115,Paiements par carte à encaisser,,Actif ou passif,
512,Banques,,Actif ou passif,
53,Caisses,,Actif ou passif,
530,Caisse,,Actif ou passif,Caisse
6,Classe 6 — Comptes de charges,,Charge,
60,ACHATS DE MATIÈRES ET FOURNITURES,,Charge,
601,Eau,,Charge,Dépenses
602,Électricité,,Charge,Dépenses
603,"Chauffage, énergie et combustibles",,Charge,Dépenses
604,Achats produits d'entretien et petits équipements,,Charge,Dépenses
605,Matériel,,Charge,Dépenses
606,Fournitures,,Charge,Dépenses
61,SERVICES EXTÉRIEURS,,Charge,
611,Nettoyage des locaux,,Charge,Dépenses
612,Locations immobilières,,Charge,Dépenses
613,Locations mobilières,,Charge,
614,Contrats de maintenance,,Charge,Dépenses
615,Entretien et petites réparations,,Charge,Dépenses
616,Primes d'assurance,,Charge,Dépenses
62,FRAIS D’ADMINISTRATION ET HONORAIRES,,Charge,
621,Rémunération du syndic sur gestion copropriété,,Charge,
6211,Rémunération du syndic,,Charge,
6212,Débours,,Charge,
6213,Frais postaux,,Charge,Dépenses
622,Autres honoraires du syndic,,Charge,
6221,Honoraires travaux,,Charge,Dépenses
6222,Prestations particulières,,Charge,
6223,Autres honoraires,,Charge,
623,Rémunérations de tiers intervenants,,Charge,
624,Frais du conseil syndical,,Charge,
63,"IMPÔTS, TAXES ET VERSEMENTS ASSIMILÉS",,Charge,
632,Taxe de balayage,,Charge,Dépenses
633,Taxe foncière,,Charge,Dépenses
634,Autre impôt et taxe,,Charge,Dépenses
64,FRAIS DE PERSONNEL,,Charge,
641,Salaires,,Charge,Dépenses
642,Charges sociales et organismes sociaux,,Charge,Dépenses
644,"Autres (médecine du travail, mutuelle, etc.)",,Charge,Dépenses
65,MONTANT SPÉCIFIQUE ALLOUÉ AU CONSEIL SYNDICAL,"Montant spécifique alloué au conseil syndical, au sein du budget prévisionnel, pour l'exercice de sa délégation de pouvoirs",Charge,
66,"CHARGES FINANCIÈRES DES EMPRUNTS, AGIOS OU AUTRES",,Charge,
661,Remboursements d'annuités d'emprunt,,Charge,Dépenses
662,Autres charges financières et agios,,Charge,
67,CHARGES POUR TRAVAUX ET OPÉRATIONS EXCEPTIONNELLES,,Charge,
671,Travaux décidés par l’assemblée générale,,Charge,Dépenses
672,Travaux urgents,,Charge,Dépenses
673,"Études techniques, diagnostic, consultation",,Charge,
677,Pertes sur créances irrécouvrables,,Charge,
678,Charges exceptionnelles,,Charge,
68,DOTATIONS AUX DÉPRÉCIATIONS SUR CRÉANCES DOUTEUSES,,Charge,
7,Classe 7 — Comptes de produits,,Produit,
70,APPELS DE FONDS,,Produit,
701,Provisions sur opérations courantes,,Produit,Recettes
702,Provisions sur travaux de l’article 14-2 et opérations exceptionnelles,,Produit,
703,Avances,,Produit,Recettes
704,Remboursements d’annuités d’emprunts,,Produit,
705,Études,,Produit,
706,Provisions au titre de la délégation de pouvoirs accordée au conseil syndical,,Produit,Recettes
7061,Provisions sur opérations courantes,,Produit,Recettes
7062,Provisions sur travaux et opérations exceptionnelles,,Produit,
71,AUTRES PRODUITS,,Produit,
711,Subventions,,Produit,Recettes
712,Emprunts,,Produit,Recettes
713,Indemnités d’assurance,,Produit,
714,Produits divers (dont intérêts légaux dus par les copropriétaires),,Produit,
716,Produits financiers,,Produit,Recettes
718,Produits exceptionnels,,Produit,
78,REPRISES DE DÉPRÉCIATIONS SUR CRÉANCES DOUTEUSES,Reprises de dépréciations sur créances douteuses,Produit,
8,Classe 8 ­— Comptes spéciaux,,,
89,COMPTES DE BILAN,,,
890,Bilan d'ouverture,,Actif ou passif,Ouverture
891,Bilan de clôture,,Actif ou passif,Clôture
9,Classe 9 — Comptes analytiques,,,
99,Projets,,,Analytique

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





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
354
355
356
357
358
359
360
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 IF NOT EXISTS 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 if fee is not linked to accounting, this is reset using a trigger if the year is deleted
    id_year INTEGER NULL REFERENCES acc_years (id) ON DELETE SET NULL -- NULL if fee is not linked to accounting
);

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,

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

CREATE UNIQUE INDEX IF NOT EXISTS srs_index ON services_reminders_sent (id_user, id_service, id_reminder, due_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);

-- Make sure id_account is reset when a year is deleted
CREATE TRIGGER IF NOT EXISTS acc_years_delete BEFORE DELETE ON acc_years BEGIN
    UPDATE services_fees SET id_account = NULL, id_year = NULL WHERE id_year = OLD.id;
END;

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 IF NOT EXISTS web_pages_path ON web_pages (path);
CREATE UNIQUE INDEX IF NOT EXISTS web_pages_uri ON web_pages (uri);
CREATE UNIQUE INDEX IF NOT EXISTS web_pages_file_path ON web_pages (file_path);
CREATE INDEX IF NOT EXISTS web_pages_parent ON web_pages (parent);
CREATE INDEX IF NOT EXISTS web_pages_published ON web_pages (published);
CREATE INDEX IF NOT EXISTS 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 [411f6a0ac5] to [00b999e74a].

42
43
44
45
46
47
48




























49
50
51
52
53
54
55
	if (@file_exists($file))
	{
		return substr(trim(file_get_contents($file)), 0, 10);
	}

	return false;
}





























if (!defined('\SQLITE3_OPEN_READWRITE')) {
	echo 'Le module de base de données SQLite3 n\'est pas disponible.' . PHP_EOL;
	exit(1);
}

/*







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







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
	if (@file_exists($file))
	{
		return substr(trim(file_get_contents($file)), 0, 10);
	}

	return false;
}

/**
 * Le code de Garradin ne s'écrit pas tout seul comme par magie,
 * merci de soutenir notre travail en faisant une contribution :)
 */
function garradin_contributor_license(): ?int
{
	static $level = null;

	if (null !== $level) {
		return $level;
	}

	if (!CONTRIBUTOR_LICENSE) {
		return null;
	}

	$key = CONTRIBUTOR_LICENSE;
	$key = gzinflate(base64_decode($key));
	list($email, $level, $hash) = explode('==', $key);
	$level = (int)hexdec($level);

	if (substr(sha1($email . $level), 0, 10) != $hash) {
		return null;
	}

	return $level;
}

if (!defined('\SQLITE3_OPEN_READWRITE')) {
	echo 'Le module de base de données SQLite3 n\'est pas disponible.' . PHP_EOL;
	exit(1);
}

/*
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);
	}







|
>
>
>
>
|
|







117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
	}

	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,







>







172
173
174
175
176
177
178
179
180
181
182
183
184
185
186

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
194
195
196
	'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'  => null,
	'FILE_STORAGE_CONFIG'   => [],
	'FILE_STORAGE_QUOTA'    => 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';






// 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'))







|
|

>
>
>
>


















>
>
>
>
>







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
	'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,
	'PDF_COMMAND'           => null,
	'CONTRIBUTOR_LICENSE'   => 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'))
207
208
209
210
211
212
213

214


215













































216
217
218




219
220
221
222
223
224
225

/*
 * Gestion des erreurs et exceptions
 */

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)







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



>
>
>
>







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

/*
 * Gestion des erreurs et exceptions
 */

class UserException extends \LogicException
{
	protected $details;

	public function setMessage(string $message) {
		$this->message = $message;
	}

	public function setDetails($details) {
		$this->details = $details;
	}

	public function getDetails() {
		return $this->details;
	}

	public function hasDetails(): bool {
		return $this->details !== null;
	}

	public function getDetailsHTML() {
		if (func_num_args() == 1) {
			$details = func_get_arg(0);
		}
		else {
			$details = $this->details;
		}

		if (null === $details) {
			return '<em>(nul)</em>';
		}

		if ($details instanceof \DateTimeInterface) {
			return $details->format('d/m/Y');
		}

		if (!is_array($details)) {
			return nl2br(htmlspecialchars($details));
		}

		$out = '<table>';

		foreach ($details as $key => $value) {
			$out .= sprintf('<tr><th>%s</th><td>%s</td></tr>', htmlspecialchars($key), $this->getDetailsHTML($value));
		}

		$out .= '</table>';

		return $out;
	}
}

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)
315
316
317
318
319
320
321
322



323
324
325
326
327
328
329
330
331
332
333

/*
 * Vérifications pour enclencher le processus d'installation ou de mise à jour
 */

if (!defined('Garradin\INSTALL_PROCESS') && !defined('Garradin\UPGRADE_PROCESS'))
{
	if (!file_exists(DB_FILE))



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

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

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







|
>
>
>
|



|






409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430

/*
 * Vérifications pour enclencher le processus d'installation ou de mise à jour
 */

if (!defined('Garradin\INSTALL_PROCESS') && !defined('Garradin\UPGRADE_PROCESS'))
{
	if (!file_exists(DB_FILE)) {
		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 [a8567c62c9].





















































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?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 hasParam(string $param): bool
	{
		return array_key_exists($param, $_GET);
	}

	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()];
		}
	}

	protected function user(string $uri): ?array
	{
		$fn = strtok($uri, '/');

		// CSV import
		if ($fn == 'import') {
			if ($this->method != 'PUT') {
				throw new APIException('Wrong request method', 400);
			}

			$admin_user_id = 1; // FIXME: should be NULL here

			$file = tempnam(CACHE_ROOT, 'tmp-import-api');

			try {
				$stdin = fopen('php://input', 'r');
				$fp = fopen($file, 'w');
				stream_copy_to_stream($stdin, $fp);
				fclose($fp);
				fclose($stdin);

				if (!filesize($file)) {
					throw new APIException('Empty CSV file', 400);
				}

				$import = new Membres\Import;
				$import->fromGarradinCSV($file, $admin_user_id);
			}
			finally {
				Utils::safe_unlink($file);
			}

			return null;
		}
		else {
			throw new APIException('Unknown user action', 404);
		}
	}

	protected function web(string $uri): ?array
	{
		if ($this->method != 'GET') {
			throw new APIException('Wrong request method', 400);
		}

		$fn = strtok($uri, '/');
		$param = strtok('');

		switch ($fn) {
			case 'list':
				return ['categories' => Web::listCategories($param), 'pages' => Web::listPages($param)];
			case 'attachment':
				$attachment = Web::getAttachmentFromURI($param);

				if (!$attachment) {
					throw new APIException('Page not found', 404);
				}

				$attachment->serve();
				return null;
			case 'html':
			case 'page':
				$page = Web::getByURI($param);

				if (!$page) {
					throw new APIException('Page not found', 404);
				}

				if ($fn == 'page') {
					$out = compact('page');

					if ($this->hasParam('html')) {
						$out['html'] = $page->render();
					}

					return $out;
				}

				// HTML render
				echo $page->render();
				return null;
			default:
				throw new APIException('Unknown web action', 404);
		}
	}

	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, string $uri)
	{
		$this->checkAuth();

		switch ($fn) {
			case 'sql':
				return $this->sql();
			case 'download':
				return $this->download();
			case 'web':
				return $this->web($uri);
			case 'user':
				return $this->user($uri);
			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, strtok(''));

			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/Accounts.php from [afc9c5669e] to [0ce7c05e85].

228
229
230
231
232
233
234
235
236
237
238
239

240
241
242
243
244
245
246
	}

	public function getSingleAccountForType(int $type)
	{
		return DB::getInstance()->first('SELECT * FROM acc_accounts WHERE type = ? AND id_chart = ? LIMIT 1;', $type, $this->chart_id);
	}

/* FIXME: implement closing of accounts
	public function getClosingAccountId()
	{
		return DB::getInstance()->firstColumn('SELECT id FROM acc_accounts WHERE type = ? AND id_chart = ?;', Account::TYPE_CLOSING, $this->chart_id);
	}


	public function closeRevenueExpenseAccounts(Year $year, int $user_id)
	{
		$closing_id = $this->getClosingAccountId();

		if (!$closing_id) {
			throw new UserException('Aucun compte n\'est indiqué comme compte de clôture dans le plan comptable');







<




>







228
229
230
231
232
233
234

235
236
237
238
239
240
241
242
243
244
245
246
	}

	public function getSingleAccountForType(int $type)
	{
		return DB::getInstance()->first('SELECT * FROM acc_accounts WHERE type = ? AND id_chart = ? LIMIT 1;', $type, $this->chart_id);
	}


	public function getClosingAccountId()
	{
		return DB::getInstance()->firstColumn('SELECT id FROM acc_accounts WHERE type = ? AND id_chart = ?;', Account::TYPE_CLOSING, $this->chart_id);
	}
/* FIXME: implement closing of accounts

	public function closeRevenueExpenseAccounts(Year $year, int $user_id)
	{
		$closing_id = $this->getClosingAccountId();

		if (!$closing_id) {
			throw new UserException('Aucun compte n\'est indiqué comme compte de clôture dans le plan comptable');

Modified src/include/lib/Garradin/Accounting/Graph.php from [7ff385bce4] to [af4ec17e7a].

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
		],
		'debts' => [
			'Comptes de tiers' => ['type' => Account::TYPE_THIRD_PARTY],
		],
	];

	const PIE_TYPES = [
		'revenue' => ['position' => Account::REVENUE],
		'expense' => ['position' => Account::EXPENSE],
		'assets' => ['type' => [Account::TYPE_BANK, Account::TYPE_CASH, Account::TYPE_OUTSTANDING]],
	];

	const WEEKLY_INTERVAL = 604800; // 7 days
	const MONTHLY_INTERVAL = 2635200; // 1 month

	static public function plot(string $type, array $criterias, int $interval = self::WEEKLY_INTERVAL, int $width = 700)







|
|







44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
		],
		'debts' => [
			'Comptes de tiers' => ['type' => Account::TYPE_THIRD_PARTY],
		],
	];

	const PIE_TYPES = [
		'revenue' => ['position' => Account::REVENUE, 'exclude_type' => Account::TYPE_VOLUNTEERING],
		'expense' => ['position' => Account::EXPENSE, 'exclude_type' => Account::TYPE_VOLUNTEERING],
		'assets' => ['type' => [Account::TYPE_BANK, Account::TYPE_CASH, Account::TYPE_OUTSTANDING]],
	];

	const WEEKLY_INTERVAL = 604800; // 7 days
	const MONTHLY_INTERVAL = 2635200; // 1 month

	static public function plot(string $type, array $criterias, int $interval = self::WEEKLY_INTERVAL, int $width = 700)

Modified src/include/lib/Garradin/Accounting/Reports.php from [1e89c4247c] to [d37a6b0099].

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
		if (!empty($criterias['service_user'])) {
			$where[] = sprintf('t.id IN (SELECT tu.id_transaction FROM acc_transactions_users tu WHERE id_service_user = %d)', $criterias['service_user']);
		}

		if (!empty($criterias['analytical'])) {
			$where[] = sprintf('l.id_analytical = %d', $criterias['analytical']);
		}





		if (!count($where)) {
			throw new \LogicException('Unknown criteria');
		}

		return implode(' AND ', $where);
	}

	/**
	 * Return account sums per year or per account
	 * @param  bool $by_year If true will return accounts grouped by year, if false it will return years grouped by account
	 */
	static public function getAnalyticalSums(bool $by_year = false): \Generator
	{
		$sql = 'SELECT a.label AS account_label, a.description AS account_description, a.id AS id_account,
			y.id AS id_year, y.label AS year_label, y.start_date, y.end_date,
			SUM(l.credit - l.debit) AS sum, SUM(l.credit) AS credit, SUM(l.debit) AS debit,
			(SELECT SUM(l2.credit - l2.debit) FROM acc_transactions_lines l2
				INNER JOIN acc_transactions t2 ON t2.id = l2.id_transaction
				INNER JOIN acc_accounts a2 ON a2.id = l2.id_account
				WHERE a2.position = %d AND l2.id_analytical = l.id_analytical AND t2.id_year = t.id_year) * -1 AS sum_expense,
			(SELECT SUM(l2.credit - l2.debit) FROM acc_transactions_lines l2
				INNER JOIN acc_transactions t2 ON t2.id = l2.id_transaction
				INNER JOIN acc_accounts a2 ON a2.id = l2.id_account
				WHERE a2.position = %d AND l2.id_analytical = l.id_analytical AND t2.id_year = t.id_year) AS sum_revenue
			FROM acc_transactions_lines l
			INNER JOIN acc_transactions t ON t.id = l.id_transaction
			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'];

		$total = function (\stdClass $current, bool $by_year) use ($sums)
		{
			$out = (object) [
				'label' => 'Total',
				'id_account' => $by_year ? null : $current->id,
				'id_year' => $by_year ? $current->id : null,

			];

			foreach ($sums as $s) {
				$out->{$s} = $current->{$s};
			}

			return $out;







>
>
>
>
















|

















|



|














>







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
		if (!empty($criterias['service_user'])) {
			$where[] = sprintf('t.id IN (SELECT tu.id_transaction FROM acc_transactions_users tu WHERE id_service_user = %d)', $criterias['service_user']);
		}

		if (!empty($criterias['analytical'])) {
			$where[] = sprintf('l.id_analytical = %d', $criterias['analytical']);
		}

		if (!empty($criterias['analytical_only'])) {
			$where[] = 'l.id_analytical IS NOT NULL';
		}

		if (!count($where)) {
			throw new \LogicException('Unknown criteria');
		}

		return implode(' AND ', $where);
	}

	/**
	 * Return account sums per year or per account
	 * @param  bool $by_year If true will return accounts grouped by year, if false it will return years grouped by account
	 */
	static public function getAnalyticalSums(bool $by_year = false): \Generator
	{
		$sql = 'SELECT a.label AS account_label, a.description AS account_description, a.id AS id_account,
			y.id AS id_year, y.label AS year_label, y.start_date, y.end_date,
			SUM(l.credit - l.debit) AS sum, SUM(l.credit) AS credit, SUM(l.debit) AS debit, 0 AS total,
			(SELECT SUM(l2.credit - l2.debit) FROM acc_transactions_lines l2
				INNER JOIN acc_transactions t2 ON t2.id = l2.id_transaction
				INNER JOIN acc_accounts a2 ON a2.id = l2.id_account
				WHERE a2.position = %d AND l2.id_analytical = l.id_analytical AND t2.id_year = t.id_year) * -1 AS sum_expense,
			(SELECT SUM(l2.credit - l2.debit) FROM acc_transactions_lines l2
				INNER JOIN acc_transactions t2 ON t2.id = l2.id_transaction
				INNER JOIN acc_accounts a2 ON a2.id = l2.id_account
				WHERE a2.position = %d AND l2.id_analytical = l.id_analytical AND t2.id_year = t.id_year) AS sum_revenue
			FROM acc_transactions_lines l
			INNER JOIN acc_transactions t ON t.id = l.id_transaction
			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'];

		$total = function (\stdClass $current, bool $by_year) use ($sums)
		{
			$out = (object) [
				'label' => 'Total',
				'id_account' => $by_year ? null : $current->id,
				'id_year' => $by_year ? $current->id : null,
				'total' => 1,
			];

			foreach ($sums as $s) {
				$out->{$s} = $current->{$s};
			}

			return $out;
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
			WHERE %s AND a.position = ?;',
			Line::TABLE, Transaction::TABLE, Account::TABLE, $where);

		$db = DB::getInstance();
		$a = $db->firstColumn($sql, Account::REVENUE);
		$b = $db->firstColumn($sql, Account::EXPENSE);

		return (int)$a - abs((int)$b);
	}

	static public function getClosingSumsWithAccounts(array $criterias, ?string $order = null, bool $reverse = false): array
	{
		$where = self::getWhereClause($criterias);

		$order = $order ?: 'a.code COLLATE NOCASE';
		$reverse = $reverse ? '* - 1' : '';


		// Find sums, link them to accounts
		$sql = sprintf('SELECT a.id, a.code, a.label, a.position, SUM(l.credit) AS credit, SUM(l.debit) AS debit,
			SUM(l.credit - l.debit) %s AS sum
			FROM %s l
			INNER JOIN %s t ON t.id = l.id_transaction
			INNER JOIN %s a ON a.id = l.id_account
			WHERE %s
			GROUP BY l.id_account
			HAVING sum != 0

			ORDER BY %s;',
			$reverse, Line::TABLE, Transaction::TABLE, Account::TABLE, $where, $order);
		return DB::getInstance()->getGrouped($sql);
	}






	static public function getBalanceSheet(array $criterias): array
	{
		$out = [
			Account::ASSET => [],
			Account::LIABILITY => [],
			'sums' => [







|


|




|
>









<
>

|


>
>
>
>
>







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
			WHERE %s AND a.position = ?;',
			Line::TABLE, Transaction::TABLE, Account::TABLE, $where);

		$db = DB::getInstance();
		$a = $db->firstColumn($sql, Account::REVENUE);
		$b = $db->firstColumn($sql, Account::EXPENSE);

		return (int)$a - (int)$b * -1;
	}

	static public function getClosingSumsWithAccounts(array $criterias, ?string $order = null, bool $reverse = false, bool $remove_zero = true): array
	{
		$where = self::getWhereClause($criterias);

		$order = $order ?: 'a.code COLLATE NOCASE';
		$reverse = $reverse ? '* -1' : '';
		$remove_zero = $remove_zero ? 'HAVING sum != 0' : '';

		// Find sums, link them to accounts
		$sql = sprintf('SELECT a.id, a.code, a.label, a.position, SUM(l.credit) AS credit, SUM(l.debit) AS debit,
			SUM(l.credit - l.debit) %s AS sum
			FROM %s l
			INNER JOIN %s t ON t.id = l.id_transaction
			INNER JOIN %s a ON a.id = l.id_account
			WHERE %s
			GROUP BY l.id_account

			%s
			ORDER BY %s;',
			$reverse, Line::TABLE, Transaction::TABLE, Account::TABLE, $where, $remove_zero, $order);
		return DB::getInstance()->getGrouped($sql);
	}

	static public function getTrialBalance(array $criterias): array
	{
		return self::getClosingSumsWithAccounts($criterias, null, false, false);
	}

	static public function getBalanceSheet(array $criterias): array
	{
		$out = [
			Account::ASSET => [],
			Account::LIABILITY => [],
			'sums' => [
355
356
357
358
359
360
361
362







363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
	 * Grand livre
	 */
	static public function getGeneralLedger(array $criterias): \Generator
	{
		$where = self::getWhereClause($criterias);

		$db = DB::getInstance();








		$sql = sprintf('SELECT
			t.id_year, l.id_account, t.id, t.date, t.reference,
			l.debit, l.credit, l.reference AS line_reference, t.label, l.label AS line_label,
			a.label AS account_label, a.code AS account_code
			FROM acc_transactions t
			INNER JOIN acc_transactions_lines l ON l.id_transaction = t.id
			INNER JOIN acc_accounts a ON a.id = l.id_account
			WHERE %s
			ORDER BY a.code COLLATE NOCASE, t.date, t.id;', $where);

		$account = null;
		$debit = $credit = 0;

		foreach ($db->iterate($sql) as $row) {
			if (null !== $account && $account->id != $row->id_account) {
				yield $account;








>
>
>
>
>
>
>

|




|

|







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
	 * Grand livre
	 */
	static public function getGeneralLedger(array $criterias): \Generator
	{
		$where = self::getWhereClause($criterias);

		$db = DB::getInstance();

		if (!empty($criterias['analytical_only'])) {
			$join = 'acc_accounts a ON a.id = l.id_analytical';
		}
		else {
			$join = 'acc_accounts a ON a.id = l.id_account';
		}

		$sql = sprintf('SELECT
			t.id_year, a.id AS id_account, t.id, t.date, t.reference,
			l.debit, l.credit, l.reference AS line_reference, t.label, l.label AS line_label,
			a.label AS account_label, a.code AS account_code
			FROM acc_transactions t
			INNER JOIN acc_transactions_lines l ON l.id_transaction = t.id
			INNER JOIN %s
			WHERE %s
			ORDER BY a.code COLLATE NOCASE, t.date, t.id;', $join, $where);

		$account = null;
		$debit = $credit = 0;

		foreach ($db->iterate($sql) as $row) {
			if (null !== $account && $account->id != $row->id_account) {
				yield $account;
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
		$get_sum = function (array $in): int {
			$sum = 0;

			foreach ($in as $row) {
				$sum += $row->sum;
			}

			return abs($sum);
		};

		$revenue_sum = $get_sum($revenue);
		$expense_sum = $get_sum($expense);
		$result = $revenue_sum - $expense_sum;

		return compact('revenue', 'expense', 'revenue_sum', 'expense_sum', 'result');
	}
}







|









493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
		$get_sum = function (array $in): int {
			$sum = 0;

			foreach ($in as $row) {
				$sum += $row->sum;
			}

			return $sum;
		};

		$revenue_sum = $get_sum($revenue);
		$expense_sum = $get_sum($expense);
		$result = $revenue_sum - $expense_sum;

		return compact('revenue', 'expense', 'revenue_sum', 'expense_sum', 'result');
	}
}

Modified src/include/lib/Garradin/Accounting/Transactions.php from [d5e8f78bb7] to [f117213851].

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\Accounting;

use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Line;
use Garradin\Entities\Accounting\Transaction;
use Garradin\Entities\Accounting\Year;
use KD2\DB\EntityManager;

use Garradin\CSV;
use Garradin\CSV_Custom;
use Garradin\DB;
use Garradin\DynamicList;
use Garradin\Utils;
use Garradin\UserException;

class Transactions
{



	const EXPECTED_CSV_COLUMNS_SELF = ['id', 'type', 'status', 'label', 'date', 'notes', 'reference',
		'line_id', 'account', 'credit', 'debit', 'line_reference', 'line_label', 'reconciled'];

	const POSSIBLE_CSV_COLUMNS = [
		'id'             => 'Numéro d\'écriture',
		'label'          => 'Libellé',
		'date'           => 'Date',
		'notes'          => 'Remarques',
		'reference'      => 'Numéro pièce comptable',
		'p_reference'    => 'Référence paiement',
		'debit_account'  => 'Compte de débit',
		'credit_account' => 'Compte de crédit',
		'amount'         => 'Montant',
	];

	const MANDATORY_CSV_COLUMNS = ['id', 'label', 'date', 'credit_account', 'debit_account', 'amount'];

	static public function get(int $id)
	{
		return EntityManager::findOneById(Transaction::class, $id);
	}

	static public function saveReconciled(\Generator $journal, ?array $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
37
38
39
40
41
42
43
44
45
<?php

namespace Garradin\Accounting;

use Garradin\Entities\Accounting\Account;
use Garradin\Entities\Accounting\Line;
use Garradin\Entities\Accounting\Transaction;
use Garradin\Entities\Accounting\Year;
use KD2\DB\EntityManager;
use Garradin\Config;
use Garradin\CSV;
use Garradin\CSV_Custom;
use Garradin\DB;
use Garradin\DynamicList;
use Garradin\Utils;
use Garradin\UserException;

class Transactions
{
	const EXPORT_RAW = 'raw';
	const EXPORT_FULL = 'full';

	const EXPECTED_CSV_COLUMNS_SELF = ['id', 'type', 'status', 'label', 'date', 'notes', 'reference',
		'line_id', 'account', 'credit', 'debit', 'line_reference', 'line_label', 'reconciled'];

	const POSSIBLE_CSV_COLUMNS = [
		'id'             => 'Numéro d\'écriture',
		'label'          => 'Libellé',
		'date'           => 'Date',
		'notes'          => 'Remarques',
		'reference'      => 'Numéro pièce comptable',
		'p_reference'    => 'Référence paiement',
		'debit_account'  => 'Compte de débit',
		'credit_account' => 'Compte de crédit',
		'amount'         => 'Montant',
	];

	const MANDATORY_CSV_COLUMNS = ['label', 'date', 'credit_account', 'debit_account', 'amount'];

	static public function get(int $id)
	{
		return EntityManager::findOneById(Transaction::class, $id);
	}

	static public function saveReconciled(\Generator $journal, ?array $checked)
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);







|










>







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
	{
		$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);
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
	{
		return DB::getInstance()->count('acc_transactions', 'id_creator = ?', $user_id);
	}

	/**
	 * Return all transactions from year
	 */
	static public function export(int $year_id): \Generator
















	{
		$sql = 'SELECT t.id, t.type, t.status, t.label, t.date, t.notes, t.reference,
			l.id AS line_id, a.code AS account, l.debit AS debit, l.credit AS credit,
			l.reference AS line_reference, l.label AS line_label, l.reconciled,
			a2.code AS analytical
			FROM acc_transactions t
			INNER JOIN acc_transactions_lines l ON l.id_transaction = t.id
			INNER JOIN acc_accounts a ON a.id = l.id_account
			LEFT JOIN acc_accounts a2 ON a2.id = l.id_analytical
			WHERE t.id_year = ? ORDER BY t.date, t.id, l.id;';

		$res = DB::getInstance()->iterate($sql, $year_id);

		$previous_id = null;

		foreach ($res as $row) {
			if ($previous_id === $row->id) {
				$row->id = $row->type = $row->status = $row->label = $row->date = $row->notes = $row->reference = null;
			}
			else {
				$row->type = Transaction::TYPES_NAMES[$row->type];

				$status = [];








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
















|







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
	{
		return DB::getInstance()->count('acc_transactions', 'id_creator = ?', $user_id);
	}

	/**
	 * Return all transactions from year
	 */
	static public function export(Year $year, string $format, string $type = self::EXPORT_RAW): void
	{
		$header = null;

		if (self::EXPORT_FULL == $type) {
			$header = ['Numéro', 'Type', 'Statut', 'Libellé', 'Date', 'Remarques', 'Pièce comptable', 'Numéro ligne', 'Compte', 'Débit', 'Crédit', 'Référence ligne', 'Libellé ligne', 'Rapprochement', 'Compte analytique'];
		}

		CSV::export(
			$format,
			sprintf('Export comptable - %s - %s', Config::getInstance()->get('nom_asso'), $year->label),
			self::iterateExport($year->id(), $type),
			$header
		);
	}

	static protected function iterateExport(int $year_id, string $type): \Generator
	{
		$sql = 'SELECT t.id, t.type, t.status, t.label, t.date, t.notes, t.reference,
			l.id AS line_id, a.code AS account, l.debit AS debit, l.credit AS credit,
			l.reference AS line_reference, l.label AS line_label, l.reconciled,
			a2.code AS analytical
			FROM acc_transactions t
			INNER JOIN acc_transactions_lines l ON l.id_transaction = t.id
			INNER JOIN acc_accounts a ON a.id = l.id_account
			LEFT JOIN acc_accounts a2 ON a2.id = l.id_analytical
			WHERE t.id_year = ? ORDER BY t.date, t.id, l.id;';

		$res = DB::getInstance()->iterate($sql, $year_id);

		$previous_id = null;

		foreach ($res as $row) {
			if ($previous_id === $row->id && $type == self::EXPORT_RAW) {
				$row->id = $row->type = $row->status = $row->label = $row->date = $row->notes = $row->reference = null;
			}
			else {
				$row->type = Transaction::TYPES_NAMES[$row->type];

				$status = [];

268
269
270
271
272
273
274
275






276
277
278
279
280
281
282

			if (null !== $transaction) {
				$transaction->save();
			}
		}
		catch (UserException $e) {
			$db->rollback();
			throw new UserException(sprintf('Erreur sur la ligne %d : %s', $l, $e->getMessage()));






		}

		$db->commit();
	}

	static public function importCustom(Year $year, CSV_Custom $csv, int $user_id)
	{







|
>
>
>
>
>
>







289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309

			if (null !== $transaction) {
				$transaction->save();
			}
		}
		catch (UserException $e) {
			$db->rollback();
			$e->setMessage(sprintf('Erreur sur la ligne %d : %s', $l, $e->getMessage()));

			if (null !== $transaction) {
				$e->setDetails($transaction->asDetailsArray());
			}

			throw $e;
		}

		$db->commit();
	}

	static public function importCustom(Year $year, CSV_Custom $csv, int $user_id)
	{
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
					throw new UserException('Une des colonnes compte de crédit, compte de débit ou montant est manquante.');
				}

				if (!empty($row->id)) {
					$transaction = self::get((int)$row->id);

					if (!$transaction) {
						throw new UserException(sprintf('Ligne %d : l\'écriture n°%d est introuvable', $l, $row->id));
					}

					if ($transaction->validated) {
						throw new UserException(sprintf('Ligne %d : l\'écriture n°%d est validée et ne peut être modifiée', $l, $row->id));
					}

					$transaction->resetLines();
				}
				else {
					$transaction = new Transaction;
					$transaction->type = Transaction::TYPE_ADVANCED;







|



|







323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
					throw new UserException('Une des colonnes compte de crédit, compte de débit ou montant est manquante.');
				}

				if (!empty($row->id)) {
					$transaction = self::get((int)$row->id);

					if (!$transaction) {
						throw new UserException(sprintf('l\'écriture n°%d est introuvable', $row->id));
					}

					if ($transaction->validated) {
						throw new UserException(sprintf('l\'écriture n°%d est validée et ne peut être modifiée', $row->id));
					}

					$transaction->resetLines();
				}
				else {
					$transaction = new Transaction;
					$transaction->type = Transaction::TYPE_ADVANCED;
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
				]);
				$transaction->addLine($line);
				$transaction->save();
			}
		}
		catch (UserException $e) {
			$db->rollback();

			throw new UserException(sprintf('Erreur sur la ligne %d : %s', $l, $e->getMessage()));






		}

		$db->commit();
	}

	static public function setAnalytical(?int $id_analytical, array $lines)
	{
		$db = DB::getInstance();

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





		$lines = array_map('intval', $lines);


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

	static public function listByType(int $year_id, int $type)
	{
		$reverse = 1;

		$columns = Account::LIST_COLUMNS;
		unset($columns['line_label'], $columns['sum'], $columns['debit'], $columns['credit']);
		$columns['line_reference']['label'] = 'Réf. paiement';
		$columns['change']['select'] = sprintf('SUM(l.credit) * %d', $reverse);
		$columns['change']['label'] = 'Montant';



		$tables = 'acc_transactions_lines l
			INNER JOIN acc_transactions t ON t.id = l.id_transaction
			INNER JOIN acc_accounts a ON a.id = l.id_account
			LEFT JOIN acc_accounts b ON b.id = l.id_analytical';
		$conditions = sprintf('t.type = %s AND t.id_year = %d', $type, $year_id);

		$sum = 0;

		$list = new DynamicList($columns, $tables, $conditions);
		$list->orderBy('date', true);
		$list->setCount('COUNT(DISTINCT t.id)');
		$list->groupBy('t.id');
		$list->setModifier(function (&$row) {
			$row->date = \DateTime::createFromFormat('!Y-m-d', $row->date);







		});
		$list->setExportCallback(function (&$row) {
			$row->change = Utils::money_format($row->change, '.', '', false);

		});

		return $list;
	}
}







>
|
>
>
>
>
>
>





|



|



>
>
>
>
|
>

|
|
<











>
>















>
>
>
>
>
>
>



>





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
				]);
				$transaction->addLine($line);
				$transaction->save();
			}
		}
		catch (UserException $e) {
			$db->rollback();

			$e->setMessage(sprintf('Erreur sur la ligne %d : %s', $l, $e->getMessage()));

			if (null !== $transaction) {
				$e->setDetails($transaction->asDetailsArray());
			}

			throw $e;
		}

		$db->commit();
	}

	static public function setAnalytical(?int $id_analytical, ?array $transactions = null, ?array $lines = null)
	{
		$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));

	}

	static public function listByType(int $year_id, int $type)
	{
		$reverse = 1;

		$columns = Account::LIST_COLUMNS;
		unset($columns['line_label'], $columns['sum'], $columns['debit'], $columns['credit']);
		$columns['line_reference']['label'] = 'Réf. paiement';
		$columns['change']['select'] = sprintf('SUM(l.credit) * %d', $reverse);
		$columns['change']['label'] = 'Montant';
		$columns['code_analytical']['select'] = 'GROUP_CONCAT(b.code, \',\')';
		$columns['id_analytical']['select'] = 'GROUP_CONCAT(l.id_analytical, \',\')';

		$tables = 'acc_transactions_lines l
			INNER JOIN acc_transactions t ON t.id = l.id_transaction
			INNER JOIN acc_accounts a ON a.id = l.id_account
			LEFT JOIN acc_accounts b ON b.id = l.id_analytical';
		$conditions = sprintf('t.type = %s AND t.id_year = %d', $type, $year_id);

		$sum = 0;

		$list = new DynamicList($columns, $tables, $conditions);
		$list->orderBy('date', true);
		$list->setCount('COUNT(DISTINCT t.id)');
		$list->groupBy('t.id');
		$list->setModifier(function (&$row) {
			$row->date = \DateTime::createFromFormat('!Y-m-d', $row->date);

			if (isset($row->id_analytical, $row->code_analytical)) {
				$row->code_analytical = array_combine(explode(',', $row->id_analytical), explode(',', $row->code_analytical));
			}
			else {
				$row->code_analytical = [];
			}
		});
		$list->setExportCallback(function (&$row) {
			$row->change = Utils::money_format($row->change, '.', '', false);
			$row->code_analytical = implode(', ', $row->code_analytical);
		});

		return $list;
	}
}

Modified src/include/lib/Garradin/Accounting/Years.php from [d5bc306cae] to [9ef2231749].

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
	}

	static public function getCurrentOpenYearId()
	{
		return EntityManager::getInstance(Year::class)->col('SELECT id FROM @TABLE WHERE closed = 0 ORDER BY start_date LIMIT 1;');
	}

	static public function listOpen()
	{
		$db = EntityManager::getInstance(Year::class)->DB();
		return $db->get('SELECT *, (SELECT COUNT(*) FROM acc_transactions WHERE id_year = acc_years.id) AS nb_transactions
			FROM acc_years WHERE closed = 0 ORDER BY end_date;');
	}

	static public function listOpenAssocExcept(int $id)
	{
		$db = EntityManager::getInstance(Year::class)->DB();
		return $db->getAssoc('SELECT id, label FROM acc_years WHERE closed = 0 AND id != ? ORDER BY end_date;', $id);
	}

	static public function listAssoc()
	{
		return DB::getInstance()->getAssoc('SELECT id, label FROM acc_years ORDER BY end_date;');
	}






	static public function listClosed()
	{
		$em = EntityManager::getInstance(Year::class);
		return $em->all('SELECT * FROM @TABLE WHERE closed = 1 ORDER BY end_date;');
	}








|


|
|












>
>
>
>
>







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
	}

	static public function getCurrentOpenYearId()
	{
		return EntityManager::getInstance(Year::class)->col('SELECT id FROM @TABLE WHERE closed = 0 ORDER BY start_date LIMIT 1;');
	}

	static public function listOpen($with_stats = false)
	{
		$db = EntityManager::getInstance(Year::class)->DB();
		$stats = $with_stats ? ', (SELECT COUNT(*) FROM acc_transactions WHERE id_year = acc_years.id) AS nb_transactions' : '';
		return $db->getGrouped(sprintf('SELECT id, * %s FROM acc_years WHERE closed = 0 ORDER BY end_date;', $stats));
	}

	static public function listOpenAssocExcept(int $id)
	{
		$db = EntityManager::getInstance(Year::class)->DB();
		return $db->getAssoc('SELECT id, label FROM acc_years WHERE closed = 0 AND id != ? ORDER BY end_date;', $id);
	}

	static public function listAssoc()
	{
		return DB::getInstance()->getAssoc('SELECT id, label FROM acc_years ORDER BY end_date;');
	}

	static public function listClosedAssoc()
	{
		return DB::getInstance()->getAssoc('SELECT id, label FROM acc_years WHERE closed = 1 ORDER BY end_date;');
	}

	static public function listClosed()
	{
		$em = EntityManager::getInstance(Year::class);
		return $em->all('SELECT * FROM @TABLE WHERE closed = 1 ORDER BY end_date;');
	}

Modified src/include/lib/Garradin/CSV.php from [b79b34dab0] to [1989ff97c6].

150
151
152
153
154
155
156
157
158


159
160

161




162
163
164
165
166
167
168
169
170
171
172
173

		$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');




					}
				}

				$row = self::rowToArray($row, $row_map_callback);

				if (!$header)
				{
					fputs($fp, self::row(array_keys($row)));
					$header = true;
				}

				fputs($fp, self::row($row));







|

>
>

|
>
|
>
>
>
>



<
<







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

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

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

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

				foreach ($row as $key => &$v) {
					if (is_object($v) && $v instanceof \DateTimeInterface) {
						if ($v->format('His') == '000000') {
							$v = $v->format('d/m/Y');
						}
						else {
							$v = $v->format('d/m/Y H:i:s');
						}
					}
				}



				if (!$header)
				{
					fputs($fp, self::row(array_keys($row)));
					$header = true;
				}

				fputs($fp, self::row($row));
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;







|







190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
		$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;
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
			throw new UserException('Le fichier ne peut être ouvert');
		}

		// Find the delimiter
		$delim = self::findDelimiter($fp);
		self::skipBOM($fp);

		$line = 1;

		$columns = fgetcsv($fp, 4096, $delim);
		$columns = array_map('trim', $columns);

		// Check for required columns
		foreach ($expected_columns as $column) {
			if (!in_array($column, $columns, true)) {







|







228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
			throw new UserException('Le fichier ne peut être ouvert');
		}

		// Find the delimiter
		$delim = self::findDelimiter($fp);
		self::skipBOM($fp);

		$line = 0;

		$columns = fgetcsv($fp, 4096, $delim);
		$columns = array_map('trim', $columns);

		// Check for required columns
		foreach ($expected_columns as $column) {
			if (!in_array($column, $columns, true)) {

Modified src/include/lib/Garradin/CSV_Custom.php from [f34f839792] to [fc76dfa5e6].

136
137
138
139
140
141
142




143
144
145
146
147
148
149
		}

		foreach ($this->mandatory_columns as $key) {
			if (!in_array($key, $translation, true)) {
				throw new UserException(sprintf('La colonne "%s" est obligatoire mais n\'a pas été sélectionnée ou n\'existe pas.', $this->columns[$key]));
			}
		}





		$this->translation = $translation;

		$this->session->set($this->key . '_translation', $this->translation);
	}

	public function clear(): void







>
>
>
>







136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
		}

		foreach ($this->mandatory_columns as $key) {
			if (!in_array($key, $translation, true)) {
				throw new UserException(sprintf('La colonne "%s" est obligatoire mais n\'a pas été sélectionnée ou n\'existe pas.', $this->columns[$key]));
			}
		}

		if (!count($translation)) {
			throw new UserException('Aucune colonne n\'a été sélectionnée');
		}

		$this->translation = $translation;

		$this->session->set($this->key . '_translation', $this->translation);
	}

	public function clear(): void

Modified src/include/lib/Garradin/Config.php from [09ca35fa0d] to [977d9aeaa8].

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

namespace Garradin;

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

use KD2\SMTP;

class Config extends Entity
{






	protected $nom_asso;
	protected $adresse_asso;
	protected $email_asso;
	protected $telephone_asso;
	protected $site_asso;

	protected $monnaie;
	protected $pays;

	protected $champs_membres;
	protected $categorie_membres;

	protected $admin_homepage;

	protected $frequence_sauvegardes;
	protected $nombre_sauvegardes;

	protected $champ_identifiant;
	protected $champ_identite;

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

	protected $couleur1;
	protected $couleur2;

	protected $image_fond;



	protected $desactiver_site;

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

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

		'champs_membres'        => Champs::class,

		'categorie_membres'     => 'int',

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

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

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

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

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

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


		'desactiver_site'       => 'bool',
	];

	protected $_modified;

	static protected $_instance = null;

	static public function getInstance()
	{
		return self::$_instance ?: self::$_instance = new self;
	}












>
>
>
>
>
>












<
<






<






|
>
>

|















<
<
|
|




<





>
|
>

|

<
<







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;
use Garradin\Membres\Champs;

use KD2\SMTP;

class Config extends Entity
{
	const DEFAULT_FILES = [
		'admin_background' => File::CONTEXT_CONFIG . '/admin_bg.png',
		'admin_homepage' => File::CONTEXT_CONFIG . '/admin_homepage.skriv',
		'admin_css' => File::CONTEXT_CONFIG . '/admin.css',
	];

	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 $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 $admin_homepage = 'config/admin_homepage.skriv';
	protected $admin_css = 'config/admin.css';

	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',



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

		'site_disabled'         => 'bool',
	];



	static protected $_instance = null;

	static public function getInstance()
	{
		return self::$_instance ?: self::$_instance = new self;
	}
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

	protected function __construct()
	{
		parent::__construct();

		$db = DB::getInstance();

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





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

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

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

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

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

		$this->load($config);

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

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



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

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

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

			}

			$values[$key] = $value;
		}

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

		$db->begin();

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

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

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

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

			// Création de l'index unique
			$db->exec('DROP INDEX IF EXISTS membres_identifiant;');

			$db->exec('CREATE UNIQUE INDEX membres_identifiant ON membres ('.$this->get('champ_identifiant').');');

		}

		$db->commit();

		$this->_modified = [];

		return true;
	}

	public function delete(): bool
	{
		throw new \LogicException('Cannot delete config');
	}

	public function getVersion(): string
	{
		return $this->get('version');

	}








	public function setVersion(string $version): void


	{

		$this->config->version = $version;






		$db = DB::getInstance();







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





			['version', $version]);

	}

	protected function _filterType(string $key, $value)
	{
		switch ($this->_types[$key]) {
			case 'int':
				return (int) $value;
			case 'bool':
				return (bool) $value;
			case 'string':
				return (string) $value;
			case File::class:
			case Champs::class:
				if (!is_object($value) || !($value instanceof $this->_types[$key])) {
					throw new \InvalidArgumentException(sprintf('"%s" is not of type "%s"', $key, $this->_types[$key]));
				}
				return $value;
			default:
				throw new \InvalidArgumentException(sprintf('"%s" has unknown type "%s"', $key, $this->_types[$key]));
		}
	}

	public function selfCheck(): void
	{
		$this->assert(trim($this->nom_asso) != '', 'Le nom de l\'association ne peut rester vide.');
		$this->assert(trim($this->monnaie) != '', 'La monnaie ne peut rester vide.');
		$this->assert(trim($this->pays) != '' && Utils::getCountryName($this->pays), 'Le pays ne peut rester vide.');

		$this->assert(trim($this->email_asso) != '' && SMTP::checkEmailIsValid($this->email_asso, false), 'L\'adresse e-mail de l\'association est  invalide.');
		$this->assert(null === $this->admin_homepage || $this->admin_homepage instanceof File, 'Page d\'accueil invalide');
		$this->assert($this->champs_membres instanceof Champs, 'Objet champs membres invalide');






		$champs = $this->champs_membres;

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

		$db = DB::getInstance();



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

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

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

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







|
>
>
>
>












<
<
<
<













>
>





|
<
<
|
|
|

<
|
>









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


|
<
<
<
<
|
<
|
>
|
>














|

|
>
|

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











<















>

<


>
>
>
>
>






>
>
>
|
|

|
|
<
|
|
<
<
<


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

	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'])) {




			// Regenerate login index

			$db->exec('DROP INDEX IF EXISTS users_id_field;');
			$config = Config::getInstance();
			$champs = $config->get('champs_membres');
			$champs->createIndexes();
		}

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

			$file = Files::get(self::DEFAULT_FILES['admin_background']);

			if ($file) {
				$file->delete();
			}
		}
		elseif (isset($source['admin_background']) && strlen($source['admin_background'])) {
			$file = Files::get(self::DEFAULT_FILES['admin_background']);

			if ($file) {
				$file->storeFromBase64($source['admin_background']);
			}
			else {
				$path = self::DEFAULT_FILES['admin_background'];
				$file = File::createFromBase64(Utils::dirname($path), Utils::basename($path), $source['admin_background']);
			}

			$source['admin_background'] = $file->path;
		}
		else {
			unset($source['admin_background']);
		}

		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($this->champs_membres instanceof Champs, 'Objet champs membres invalide');

		// Files can only have one value: their name
		$this->assert($this->admin_background === null || $this->admin_background === self::DEFAULT_FILES['admin_background']);
		$this->assert($this->admin_homepage === null || $this->admin_homepage === self::DEFAULT_FILES['admin_homepage']);
		$this->assert($this->admin_css === null || $this->admin_css === self::DEFAULT_FILES['admin_css']);

		$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();

		// Check that this field is actually unique
		if (isset($this->_modified['champ_identifiant'])) {
			$sql = sprintf('SELECT (COUNT(DISTINCT %s COLLATE NOCASE) = COUNT(*)) FROM membres WHERE %1$s IS NOT NULL AND %1$s != \'\';', $this->champ_identifiant);
			$is_unique = (bool) $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 [98b21aac12] to [f878c985d1].

10
11
12
13
14
15
16




17
18
19
20
21
22
23
     * 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]);
        }

        return self::$_instance;







>
>
>
>







10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
     * 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 protected $unicode_patterns_cache = [];

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

        return self::$_instance;
43
44
45
46
47
48
49


50





































































































51
52
53
54
55
56
57
        $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;
    }







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







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

        self::registerCustomFunctions($this->db);
    }

    static public function registerCustomFunctions($db)
    {
        $db->createFunction('dirname', [Utils::class, 'dirname']);
        $db->createFunction('basename', [Utils::class, 'basename']);
        $db->createFunction('like', [self::class, 'unicodeLike']);
        $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;
    }
76
77
78
79
80
81
82


83
84
85
86
87
88
89
90
91
92











































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



        if (!$enable) {
            $this->db->exec('PRAGMA legacy_alter_table = ON;');
            $this->db->exec('PRAGMA foreign_keys = OFF;');
        }
        else {
            $this->db->exec('PRAGMA legacy_alter_table = OFF;');
            $this->db->exec('PRAGMA foreign_keys = ON;');
        }
    }
}


















































>
>









|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
    /**
     * @see https://www.sqlite.org/lang_altertable.html
     */
    public function toggleForeignKeys($enable)
    {
        assert(is_bool($enable));

        $this->connect();

        if (!$enable) {
            $this->db->exec('PRAGMA legacy_alter_table = ON;');
            $this->db->exec('PRAGMA foreign_keys = OFF;');
        }
        else {
            $this->db->exec('PRAGMA legacy_alter_table = OFF;');
            $this->db->exec('PRAGMA foreign_keys = ON;');
        }
    }

    /**
     * This is a rewrite of SQLite LIKE function that is transforming
     * the pattern and the value to lowercase ascii, so that we can match
     * "émilie" with "emilie".
     *
     * This is probably not the best way to do that, but we have to resort to that
     * as ICU extension is rarely available.
     *
     * @see https://www.sqlite.org/c3ref/strlike.html
     * @see https://sqlite.org/src/file?name=ext/icu/icu.c&ci=trunk
     */
    static public function unicodeLike($pattern, $value, $escape = null) {
        $id = md5($pattern . $escape);

        if (!array_key_exists($id, self::$unicode_patterns_cache)) {
            $escape = $escape ? '(?!' . preg_quote($escape, '/') . ')' : '';
            preg_match_all('/('.$escape.'[%_])|(\w+)|(.+?)/iu', $pattern, $parts, PREG_SET_ORDER);
            $pattern = '';

            foreach ($parts as $part) {
                if (isset($part[3])) {
                    $pattern .= preg_quote($part[0], '/');
                }
                elseif (isset($part[2])) {
                    $pattern .= Utils::unicodeCaseFold($part[2]);
                }
                elseif ($part[1] == '%') {
                    $pattern .= '.*';
                }
                elseif ($part[1] == '_') {
                    $pattern .= '.';
                }
            }

            $pattern = '/^' . $pattern . '$/im';
            self::$unicode_patterns_cache[$id] = $pattern;
        }

        $value = Utils::unicodeCaseFold($value);

        return (bool) preg_match(self::$unicode_patterns_cache[$id], $value);
    }
}

Modified src/include/lib/Garradin/DynamicList.php from [f85cc3737c] to [4a558ce327].

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;

class DynamicList
{
	protected $columns;
	protected $tables;
	protected $conditions;
	protected $group;
	protected $order;
	protected $modifier;
	protected $export_callback;
	protected $title = 'Liste';
	protected $count = 'COUNT(*)';
	protected $desc = true;
	protected $per_page = 100;
	protected $page = 1;

	private $count_result;

	public function __construct(array $columns, string $tables, string $conditions)
	{
		$this->columns = $columns;
		$this->tables = $tables;
		$this->conditions = $conditions;
		$this->order = key($columns);
	}






	public function __get($key)
	{
		return $this->$key;
	}

	public function setTitle(string $title) {




|
















|






>
>
>
>
>







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;

class DynamicList implements \Countable
{
	protected $columns;
	protected $tables;
	protected $conditions;
	protected $group;
	protected $order;
	protected $modifier;
	protected $export_callback;
	protected $title = 'Liste';
	protected $count = 'COUNT(*)';
	protected $desc = true;
	protected $per_page = 100;
	protected $page = 1;

	private $count_result;

	public function __construct(array $columns, string $tables, string $conditions = '1')
	{
		$this->columns = $columns;
		$this->tables = $tables;
		$this->conditions = $conditions;
		$this->order = key($columns);
	}

	public function __isset($key)
	{
		return property_exists($this, $key);
	}

	public function __get($key)
	{
		return $this->$key;
	}

	public function setTitle(string $title) {
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
	}

	public function groupBy(string $value)
	{
		$this->group = $value;
	}

	public function count()
	{
		if (null === $this->count_result) {
			$sql = sprintf('SELECT %s FROM %s WHERE %s;', $this->count, $this->tables, $this->conditions);
			$this->count_result = DB::getInstance()->firstColumn($sql);
		}

		return $this->count_result;
	}

	public function export(string $name, string $format = 'csv')
	{
		$this->setPageSize(null);
		$columns = [];








|






|







69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
	}

	public function groupBy(string $value)
	{
		$this->group = $value;
	}

	public function count(): int
	{
		if (null === $this->count_result) {
			$sql = sprintf('SELECT %s FROM %s WHERE %s;', $this->count, $this->tables, $this->conditions);
			$this->count_result = DB::getInstance()->firstColumn($sql);
		}

		return (int) $this->count_result;
	}

	public function export(string $name, string $format = 'csv')
	{
		$this->setPageSize(null);
		$columns = [];

98
99
100
101
102
103
104











105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
		else if ('ods' == $format) {
			CSV::toODS($name, $this->iterate(false), $this->getHeaderColumns(true), $this->export_callback);
		}
		else {
			throw new UserException('Invalid export format');
		}
	}












	public function paginationURL()
	{
		return Utils::getModifiedURL('?p=[ID]');
	}

	public function orderURL(string $order, bool $desc)
	{
		$query = array_merge($_GET, ['o' => $order, 'd' => (int) $desc]);
		$url = Utils::getSelfURL($query);
		return $url;
	}

	public function setCount(string $count)
	{
		$this->count = $count;
	}







>
>
>
>
>
>
>
>
>
>
>









|







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
		else if ('ods' == $format) {
			CSV::toODS($name, $this->iterate(false), $this->getHeaderColumns(true), $this->export_callback);
		}
		else {
			throw new UserException('Invalid export format');
		}
	}

	public function asArray(): array
	{
		$out = [];

		foreach ($this->iterate(true) as $row) {
			$out[] = $row;
		}

		return $out;
	}

	public function paginationURL()
	{
		return Utils::getModifiedURL('?p=[ID]');
	}

	public function orderURL(string $order, bool $desc)
	{
		$query = array_merge($_GET, ['o' => $order, 'd' => (int) $desc]);
		$url = Utils::getSelfURI($query);
		return $url;
	}

	public function setCount(string $count)
	{
		$this->count = $count;
	}

Modified src/include/lib/Garradin/Entities/Accounting/Account.php from [bfec22341c] to [cacd2727a4].

209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
			unset($columns['change']);
		}

		$list = new DynamicList($columns, $tables, $conditions);
		$list->orderBy('date', false);
		$list->setCount('COUNT(*)');
		$list->setPageSize(null);
		$list->setModifier(function (&$row) use (&$sum, $reverse) {
			if (property_exists($row, 'sum')) {
				$sum += isset($row->change) ? $row->change : ($row->credit - $row->debit);
				$row->sum = $sum;
			}

			$row->date = \DateTime::createFromFormat('!Y-m-d', $row->date);
		});







|







209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
			unset($columns['change']);
		}

		$list = new DynamicList($columns, $tables, $conditions);
		$list->orderBy('date', false);
		$list->setCount('COUNT(*)');
		$list->setPageSize(null);
		$list->setModifier(function (&$row) use (&$sum) {
			if (property_exists($row, 'sum')) {
				$sum += isset($row->change) ? $row->change : ($row->credit - $row->debit);
				$row->sum = $sum;
			}

			$row->date = \DateTime::createFromFormat('!Y-m-d', $row->date);
		});
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
		$journal = iterator_to_array($journal);
		$i = 0;
		$sum = 0;

		foreach ($csv as $k => &$line) {
			try {
				$date = \DateTime::createFromFormat('!d/m/Y', $line->date);
				$line->amount = ($line->amount < 0 ? -1 : 1) * Utils::moneyToInteger($line->amount);

				if (!$date) {
					throw new UserException('Date invalide : ' . $line->date);
				}

				$line->date = $date;
			}







|







291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
		$journal = iterator_to_array($journal);
		$i = 0;
		$sum = 0;

		foreach ($csv as $k => &$line) {
			try {
				$date = \DateTime::createFromFormat('!d/m/Y', $line->date);
				$line->amount = (substr($line->amount, 0, 1) == '-' ? -1 : 1) * Utils::moneyToInteger($line->amount);

				if (!$date) {
					throw new UserException('Date invalide : ' . $line->date);
				}

				$line->date = $date;
			}
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
			$row = (object) ['csv' => null, 'journal' => $j];

			if (isset($j->debit)) {
				foreach ($csv as &$line) {
					if (!isset($line->date)) {
						 continue;
					}


					if ($j->date->format('Ymd') == $line->date->format('Ymd')
						&& ($j->credit == abs($line->amount) || $j->debit == abs($line->amount))) {

						$row->csv = $line;
						$line = null;
						break;
					}
				}
			}

			$lines[$id] = $row;
		}

























		unset($j);


		foreach ($csv as $line) {
			if (null == $line) {
				continue;
			}

			$id = $line->date->format('Ymd') . '.' . ($i++);
			$lines[$id] = (object) ['csv' => $line, 'journal' => null];







>
>

|
>










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


>







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
			$row = (object) ['csv' => null, 'journal' => $j];

			if (isset($j->debit)) {
				foreach ($csv as &$line) {
					if (!isset($line->date)) {
						 continue;
					}

					// Match date, amount and label
					if ($j->date->format('Ymd') == $line->date->format('Ymd')
						&& ($j->credit * -1 == $line->amount || $j->debit == $line->amount)
						&& strtolower($j->label) == strtolower($line->label)) {
						$row->csv = $line;
						$line = null;
						break;
					}
				}
			}

			$lines[$id] = $row;
		}

		unset($line, $row, $j);

		// Second round to match only amount and label
		foreach ($lines as $row) {
			if ($row->csv || !isset($row->journal->debit)) {
				continue;
			}

			$j = $row->journal;

			foreach ($csv as &$line) {
				if (!isset($line->date)) {
					 continue;
				}

				if ($j->date->format('Ymd') == $line->date->format('Ymd')
					&& ($j->credit * -1 == $line->amount || $j->debit == $line->amount)) {
					$row->csv = $line;
					$line = null;
					break;
				}
			}
		}

		unset($j);

		// Then add CSV lines on the right
		foreach ($csv as $line) {
			if (null == $line) {
				continue;
			}

			$id = $line->date->format('Ymd') . '.' . ($i++);
			$lines[$id] = (object) ['csv' => $line, 'journal' => null];
385
386
387
388
389
390
391










392
393
394
395
396
397
398
			$row->date = \DateTime::createFromFormat('Y-m-d', $row->date);
			$sum += ($row->credit - $row->debit);
			$row->running_sum = $sum;
			$row->checked = array_key_exists($row->id, $checked);
			yield $row;
		}
	}











	public function getSum(int $year_id, bool $simple = false): int
	{
		$sum = (int) DB::getInstance()->firstColumn('SELECT SUM(l.credit) - SUM(l.debit)
			FROM acc_transactions_lines l
			INNER JOIN acc_transactions t ON t.id = l.id_transaction
			wHERE l.id_account = ? AND t.id_year = ?;', $this->id(), $year_id);







>
>
>
>
>
>
>
>
>
>







413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
			$row->date = \DateTime::createFromFormat('Y-m-d', $row->date);
			$sum += ($row->credit - $row->debit);
			$row->running_sum = $sum;
			$row->checked = array_key_exists($row->id, $checked);
			yield $row;
		}
	}

	public function countDepositJournal(int $year_id): int
	{
		 return DB::getInstance()->firstColumn('SELECT COUNT(*)
			FROM acc_transactions_lines l
			INNER JOIN acc_transactions t ON t.id = l.id_transaction
			WHERE t.id_year = ? AND l.id_account = ? AND l.credit = 0 AND NOT (t.status & ?)
			ORDER BY t.date, t.id;',
			$year_id, $this->id(), Transaction::STATUS_DEPOSIT);
	}

	public function getSum(int $year_id, bool $simple = false): int
	{
		$sum = (int) DB::getInstance()->firstColumn('SELECT SUM(l.credit) - SUM(l.debit)
			FROM acc_transactions_lines l
			INNER JOIN acc_transactions t ON t.id = l.id_transaction
			wHERE l.id_account = ? AND t.id_year = ?;', $this->id(), $year_id);
486
487
488
489
490
491
492

493

494
495
496
	public function chart(): Chart
	{
		return Charts::get($this->id_chart);
	}

	public function save(): bool
	{

		Config::getInstance()->set('last_chart_change', time());

		return parent::save();
	}
}







>
|
>



524
525
526
527
528
529
530
531
532
533
534
535
536
	public function chart(): Chart
	{
		return Charts::get($this->id_chart);
	}

	public function save(): bool
	{
		$c = Config::getInstance();
		$c->set('last_chart_change', time());

		return parent::save();
	}
}

Modified src/include/lib/Garradin/Entities/Accounting/Line.php from [0fde672e4f] to [a9f6e82800].

1
2
3
4

5
6
7

8
9
10
11
12
13
14
<?php

namespace Garradin\Entities\Accounting;


use Garradin\Entity;
use Garradin\ValidationException;
use Garradin\Utils;


class Line extends Entity
{
	const TABLE = 'acc_transactions_lines';

	protected $id;
	protected $id_transaction;




>



>







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

namespace Garradin\Entities\Accounting;

use Garradin\DB;
use Garradin\Entity;
use Garradin\ValidationException;
use Garradin\Utils;
use Garradin\Accounting\Accounts;

class Line extends Entity
{
	const TABLE = 'acc_transactions_lines';

	protected $id;
	protected $id_transaction;
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












		'reconciled'     => 'int',
		'id_analytical'  => '?int',
	];

	protected $_form_rules = [
		'id_account'     => 'required|numeric|in_table:acc_accounts,id',
		'id_analytical'  => 'numeric|in_table:acc_accounts,id',
		'credit'         => 'money|min:0',
		'debit'          => 'money|min:0',
		'reference'      => 'string|max:200',
		'label'          => 'string|max:200',
	];

	public function filterUserValue(string $type, $value, string $key)
	{
		if ($key == 'credit' || $key == 'debit')
		{
			$value = Utils::moneyToInteger($value);
		}
		elseif ($key == 'id_analytical' && $value == 0) {
			$value = null;
		}

		$value = parent::filterUserValue($type, $value, $key);

		return $value;
	}

	public function selfCheck(): void
	{
		parent::selfCheck();
		$this->assert($this->credit || $this->debit, 'Aucun montant au débit ou au crédit');

		$this->assert(($this->credit * $this->debit) === 0 && ($this->credit + $this->debit) > 0, 'Ligne non équilibrée : crédit ou débit doit valoir zéro.');
		$this->assert($this->id_transaction, 'Aucun mouvement n\'a été indiqué pour cette ligne.');
		$this->assert($this->reconciled === 0 || $this->reconciled === 1);
	}





}



















<
<






|
<















>



|
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
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
		'reconciled'     => 'int',
		'id_analytical'  => '?int',
	];

	protected $_form_rules = [
		'id_account'     => 'required|numeric|in_table:acc_accounts,id',
		'id_analytical'  => 'numeric|in_table:acc_accounts,id',


		'reference'      => 'string|max:200',
		'label'          => 'string|max:200',
	];

	public function filterUserValue(string $type, $value, string $key)
	{
		if ($key == 'credit' || $key == 'debit') {

			$value = Utils::moneyToInteger($value);
		}
		elseif ($key == 'id_analytical' && $value == 0) {
			$value = null;
		}

		$value = parent::filterUserValue($type, $value, $key);

		return $value;
	}

	public function selfCheck(): void
	{
		parent::selfCheck();
		$this->assert($this->credit || $this->debit, 'Aucun montant au débit ou au crédit');
		$this->assert($this->credit >= 0 && $this->debit >= 0, 'Le montant ne peut être négatif');
		$this->assert(($this->credit * $this->debit) === 0 && ($this->credit + $this->debit) > 0, 'Ligne non équilibrée : crédit ou débit doit valoir zéro.');
		$this->assert($this->id_transaction, 'Aucun mouvement n\'a été indiqué pour cette ligne.');
		$this->assert($this->reconciled === 0 || $this->reconciled === 1);

		$db = DB::getInstance();
		$this->assert($db->firstColumn('SELECT 1 FROM acc_accounts a
			INNER JOIN acc_transactions t ON t.id = ?
			INNER JOIN acc_years y ON y.id = t.id_year
			WHERE a.id = ? AND a.id_chart = y.id_chart;', $this->id_transaction, $this->id_account), 'Le compte sélectionné ne correspond pas à l\'exercice');
	}

	public function asDetailsArray(): array
	{
		return [
			'Compte'    => $this->id_account ? Accounts::getSelectorLabel($this->id_account) : null,
			'Libellé'   => $this->label,
			'Référence' => $this->reference,
			'Crédit'    => Utils::money_format($this->credit),
			'Débit'     => Utils::money_format($this->debit),
		];
	}
}

Modified src/include/lib/Garradin/Entities/Accounting/Transaction.php from [d64763b884] to [32bd594806].

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\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;
	const TYPE_TRANSFER = 3;
	const TYPE_DEBT = 4;
	const TYPE_CREDIT = 5;

	const STATUS_WAITING = 1;
	const STATUS_PAID = 2;
	const STATUS_DEPOSIT = 4;


	const STATUS_NAMES = [
		1 => 'En attente de règlement',
		2 => 'Réglé',
		4 => 'Déposé en banque',
	];






|
|
<
<





>
>
>
>
>
>














>







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\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;
	const TYPE_TRANSFER = 3;
	const TYPE_DEBT = 4;
	const TYPE_CREDIT = 5;

	const STATUS_WAITING = 1;
	const STATUS_PAID = 2;
	const STATUS_DEPOSIT = 4;
	const STATUS_ERROR = 8;

	const STATUS_NAMES = [
		1 => 'En attente de règlement',
		2 => 'Réglé',
		4 => 'Déposé en banque',
	];

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
		'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;
			case Account::TYPE_EXPENSE:
				return self::TYPE_EXPENSE;
			case Account::TYPE_THIRD_PARTY:
				return self::TYPE_DEBT;




			default:
				return self::TYPE_TRANSFER;
		}
	}




	public function getLinesWithAccounts()
	{
		$em = EntityManager::getInstance(Line::class);
		return $em->DB()->get('SELECT



			l.*, a.label AS account_name, a.code AS account_code,
			b.label AS analytical_name
			FROM acc_transactions_lines l
			INNER JOIN acc_accounts a ON a.id = l.id_account


			LEFT JOIN acc_accounts b ON b.id = l.id_analytical
			WHERE l.id_transaction = ? ORDER BY l.id;', $this->id);
	}




































	public function getLines($with_accounts = false)
	{
		if (null === $this->_lines && $this->exists()) {
			$em = EntityManager::getInstance(Line::class);
			$this->_lines = $em->all('SELECT * FROM @TABLE WHERE id_transaction = ? ORDER BY id;', $this->id);
		}
		elseif (null === $this->_lines) {
			$this->_lines = [];







>
>
>
>
>











>
>
>
>

|



>
>
>
|

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







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
		'reference' => 'string|max:200',
		'date'      => 'required|date_format:d/m/Y',
	];

	protected $_lines;
	protected $_old_lines = [];

	protected $_accounts = [];

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

	static public function getTypeFromAccountType(int $account_type)
	{
		switch ($account_type) {
			case Account::TYPE_REVENUE:
				return self::TYPE_REVENUE;
			case Account::TYPE_EXPENSE:
				return self::TYPE_EXPENSE;
			case Account::TYPE_THIRD_PARTY:
				return self::TYPE_DEBT;
			case Account::TYPE_BANK:
			case Account::TYPE_CASH:
			case Account::TYPE_OUTSTANDING:
				return self::TYPE_TRANSFER;
			default:
				return self::TYPE_ADVANCED;
		}
	}

	/**
	 * @param  bool $restrict_year Set to TRUE to only return lines linked to the correct chart, or FALSE (deprecated/legacy) to return all lines even if they are linked to accounts in the wrong chart!
	 */
	public function getLinesWithAccounts(bool $restrict_year = true): array
	{
		$db = EntityManager::getInstance(Line::class)->DB();

		if (null === $this->_lines || $restrict_year === false) {
			$restrict = $restrict_year ? 'AND a.id_chart = y.id_chart' : '';
			$sql = sprintf('SELECT
				l.*, a.label AS account_name, a.code AS account_code,
				b.label AS analytical_name
				FROM acc_transactions_lines l
				INNER JOIN acc_accounts a ON a.id = l.id_account %s
				INNER JOIN acc_transactions t ON t.id = l.id_transaction
				INNER JOIN acc_years y ON y.id = t.id_year
				LEFT JOIN acc_accounts b ON b.id = l.id_analytical
				WHERE l.id_transaction = %d ORDER BY l.id;', $restrict, $this->id());

			return $db->get($sql);
		}
		else {
			// Merge data from accounts with lines
			$accounts = [];
			$lines_with_accounts = [];

			foreach ($this->getLines() as $line) {
				if (!array_key_exists($line->id_account, $this->_accounts)) {
					$accounts[] = $line->id_account;
				}

				if ($line->id_analytical && !array_key_exists($line->id_analytical, $this->_accounts)) {
					$accounts[] = $line->id_analytical;
				}
			}

			if (count($accounts)) {
				$sql = sprintf('SELECT id, label, code FROM acc_accounts WHERE %s;', $db->where('id', 'IN', $accounts));
				$this->_accounts += $db->getGrouped($sql);
			}

			foreach ($this->getLines() as $line) {
				$account = [
					'account_code' => $this->_accounts[$line->id_account]->code,
					'account_name' => $this->_accounts[$line->id_account]->label,
					'analytical_name' => $line->id_analytical ? $this->_accounts[$line->id_analytical]->label : null,
				];

				$lines_with_accounts[] = (object) ($line->asArray() + $account);
			}

			return $lines_with_accounts;
		}
	}

	public function getLines(): array
	{
		if (null === $this->_lines && $this->exists()) {
			$em = EntityManager::getInstance(Line::class);
			$this->_lines = $em->all('SELECT * FROM @TABLE WHERE id_transaction = ? ORDER BY id;', $this->id);
		}
		elseif (null === $this->_lines) {
			$this->_lines = [];
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
			if ($line->id === $id) {
				return $line;
			}
		}

		return null;
	}












	public function getLinesCreditSum()
	{
		$sum = 0;

		foreach ($this->getLines() as $line) {
			$sum += $line->credit;
		}

		return $sum;
	}























	public function getTypesAccounts()
	{
		if ($this->type == self::TYPE_ADVANCED) {
			return [];
		}








>
>
>
>
>
>
>
>
>
>
>











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







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
			if ($line->id === $id) {
				return $line;
			}
		}

		return null;
	}

	public function getFirstLine()
	{
		$lines = $this->getLines();

		if (!count($lines)) {
			return null;
		}

		return reset($lines);
	}

	public function getLinesCreditSum()
	{
		$sum = 0;

		foreach ($this->getLines() as $line) {
			$sum += $line->credit;
		}

		return $sum;
	}

	public function getLinesDebitSum()
	{
		$sum = 0;

		foreach ($this->getLines() as $line) {
			$sum += $line->debit;
		}

		return $sum;
	}

	public function getAnalyticalId(): ?int
	{
		$lines = $this->getLines();

		if (!count($lines)) {
			return null;
		}

		return current($lines)->id_analytical;
	}

	public function getTypesAccounts()
	{
		if ($this->type == self::TYPE_ADVANCED) {
			return [];
		}

196
197
198
199
200
201
202









































203
204
205
206
207
208
209
		$type = $this->getTypesDetails()[$this->type];

		return [
			$type->accounts[0]->position == 'credit' ? $credit : $debit,
			$type->accounts[1]->position == 'credit' ? $credit : $debit,
		];
	}










































/*
	public function getHash()
	{
		if (!$this->id_year) {
			throw new \LogicException('Il n\'est pas possible de hasher un mouvement qui n\'est pas associé à un exercice');
		}







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







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
		$type = $this->getTypesDetails()[$this->type];

		return [
			$type->accounts[0]->position == 'credit' ? $credit : $debit,
			$type->accounts[1]->position == 'credit' ? $credit : $debit,
		];
	}

	/**
	 * Creates a new Transaction entity (not saved) from an existing one,
	 * trying to adapt to a different chart if possible
	 * @param  int    $id
	 * @param  Year   $year Target year
	 * @return Transaction
	 */
	public function duplicate(Year $year): Transaction
	{
		$new = new Transaction;

		$copy = ['type', 'status', 'label', 'notes', 'reference', 'date'];

		foreach ($copy as $field) {
			$new->$field = $this->$field;
		}

		$copy = ['credit', 'debit', 'id_account', 'label', 'reference'];
		$lines = DB::getInstance()->get('SELECT
				l.credit, l.debit, l.label, l.reference, b.id AS id_account
			FROM acc_transactions_lines l
			INNER JOIN acc_accounts a ON a.id = l.id_account
			LEFT JOIN acc_accounts b ON b.code = a.code AND b.id_chart = ?
			WHERE l.id_transaction = ?;',
			$year->chart()->id,
			$this->id()
		);

		foreach ($lines as $l) {
			$line = new Line;
			foreach ($copy as $field) {
				$line->$field = $l->$field;
			}

			$new->addLine($line);
		}

		return $new;
	}


/*
	public function getHash()
	{
		if (!$this->id_year) {
			throw new \LogicException('Il n\'est pas possible de hasher un mouvement qui n\'est pas associé à un exercice');
		}
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
		}

		return $sum;
	}

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



		$db = DB::getInstance();

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

		if (!parent::save()) {
			return false;
		}

		foreach ($this->getLines() as $line)
		{
			$line->id_transaction = $this->id();
			$line->save();
		}

		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->removeStatus(self::STATUS_WAITING);
			$this->_related->addStatus(self::STATUS_PAID);
			$this->_related->save();
		}

		return true;
	}

	public function removeStatus(int $property) {
		$this->set('status', $this->status & ~$property);
	}

	public function addStatus(int $property) {
		$this->set('status', $this->status | $property);
	}






	public function delete(): bool
	{
		if ($this->validated) {
			throw new ValidationException('Il n\'est pas possible de supprimer 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 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')))
		{
			throw new ValidationException('La date ne correspond pas à l\'exercice sélectionné : ' . $this->date->format('d/m/Y'));
		}

		$total = 0;

		$lines = $this->getLines();

		foreach ($lines as $line) {
			$total += $line->credit;
			$total -= $line->debit;
		}

		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_TRANSFER;
		$amount = $source['amount'];

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

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







|
|

>
>




|














>
|
>



<
|
|













>
>
>
>
>













|







<

<

<
<
|
>
>
|
<
|
|
|
<










<
|
|
|
<
|
<












|







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
		}

		return $sum;
	}

	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()) {
			return false;
		}

		foreach ($this->getLines() as $line)
		{
			$line->id_transaction = $this->id();
			$line->save();
		}

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

		// Remove flag

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

		return true;
	}

	public function removeStatus(int $property) {
		$this->set('status', $this->status & ~$property);
	}

	public function addStatus(int $property) {
		$this->set('status', $this->status | $property);
	}

	public function markPaid() {
		$this->removeStatus(self::STATUS_WAITING);
		$this->addStatus(self::STATUS_PAID);
	}

	public function delete(): bool
	{
		if ($this->validated) {
			throw new ValidationException('Il n\'est pas possible de supprimer 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 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();




		$this->assert(null !== $this->id_year, 'Aucun exercice spécifié.');
		$this->assert(array_key_exists($this->type, self::TYPES_NAMES), 'Type d\'écriture inconnu : ' . $this->type);
		$this->assert(null === $this->id_creator || $db->test('membres', 'id = ?', $this->id_creator), 'Le membre créateur de l\'écriture n\'existe pas ou plus');


		$is_in_year = $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'));

		$this->assert($is_in_year, 'La date ne correspond pas à l\'exercice sélectionné : ' . $this->date->format('d/m/Y'));


		$total = 0;

		$lines = $this->getLines();

		foreach ($lines as $line) {
			$total += $line->credit;
			$total -= $line->debit;
		}


		$this->assert(0 === $total, sprintf('Écriture non équilibrée : déséquilibre (%s) entre débits et crédits', Utils::money_format($total)));

		$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_ADVANCED;
		$amount = $source['amount'];

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

		$line = new Line;
		$line->importForm([
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
		}

		$type = $source['type'];

		$this->importForm($source);

		if (self::TYPE_ADVANCED == $type) {




			$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->status = self::STATUS_WAITING;
			}

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

			$amount = $source['amount'];







>
>
>
>






|













|
>
>
>
|







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
		}

		$type = $source['type'];

		$this->importForm($source);

		if (self::TYPE_ADVANCED == $type) {
			if (!isset($source['lines']) || !is_array($source['lines'])) {
				throw new ValidationException('Aucune ligne dans la saisie');
			}

			$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->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'];
438
439
440
441
442
443
444



445
446
447
448
449
450
451
					'debit'         => $debit,
					'id_account'    => $account,
					'id_analytical' => !empty($source['id_analytical']) ? $source['id_analytical'] : null,
				]);
				$this->addLine($line);
			}
		}



	}

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







>
>
>







577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
					'debit'         => $debit,
					'id_account'    => $account,
					'id_analytical' => !empty($source['id_analytical']) ? $source['id_analytical'] : null,
				]);
				$this->addLine($line);
			}
		}

		// Remove error status when changed
		$this->removeStatus(self::STATUS_ERROR);
	}

	public function importFromEditForm(?array $source = null): void
	{
		if (null === $source) {
			$source = $_POST;
		}
475
476
477
478
479
480
481
482
483


484
485




486
487
488
489
490
491
492
		}
		catch (\LogicException $e) {
			throw new ValidationException('Aucun compte sélectionné pour certaines lignes.');
		}

		$debit = $credit = 0;

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


			$line = (new Line)->importForm($line);
			$this->addLine($line);





			$debit += $line->debit;
			$credit += $line->credit;
		}

		if ($debit != $credit) {
			// Add final balance line







|

>
>
|
|
>
>
>
>







617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
		}
		catch (\LogicException $e) {
			throw new ValidationException('Aucun compte sélectionné pour certaines lignes.');
		}

		$debit = $credit = 0;

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

			try {
				$line = (new Line)->importForm($line);
				$this->addLine($line);
			}
			catch (ValidationException $e) {
				throw new ValidationException(sprintf('Ligne %d : %s', $k+1, $e->getMessage()), 0, $e);
			}

			$debit += $line->debit;
			$credit += $line->credit;
		}

		if ($debit != $credit) {
			// Add final balance line
514
515
516
517
518
519
520


521



522
523
524
525
526
527
528
	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 (?, ?, ?);',







>
>
|
>
>
>







662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
	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 (?, ?, ?);',
691
692
693
694
695
696
697
698

























			$out->id_account = $line->id_account;
			break;
		}

		return $out;
	}
}































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

			$out->id_account = $line->id_account;
			break;
		}

		return $out;
	}

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

	public function asDetailsArray(): array
	{
		$lines = [];

		foreach ($this->getLines() as $line) {
			$lines[] = $line->asDetailsArray();
		}

		return [
			'Libellé'         => $this->label,
			'Date'            => $this->date,
			'Pièce comptable' => $this->reference,
			'Remarques'       => $this->notes,
			'Total crédit'    => Utils::money_format($this->getLinesCreditSum()),
			'Total débit'     => Utils::money_format($this->getLinesDebitSum()),
			'Lignes'          => $lines,
		];
	}
}

Modified src/include/lib/Garradin/Entities/Accounting/Year.php from [efb670bde0] 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;
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
	];

	public function selfCheck(): void
	{
		parent::selfCheck();
		$this->assert($this->start_date < $this->end_date, 'La date de fin doit être postérieure à la date de début');
		$this->assert($this->closed === 0 || $this->closed === 1);
		$this->assert($this->closed == 1 || !isset($this->_modified['closed']), 'Il est interdit de réouvrir un exercice clôturé');

		$db = DB::getInstance();

		$this->assert($this->id_chart !== null);

		if ($this->exists()) {
			$this->assert(
				!$db->test(Transaction::TABLE, 'id_year = ? AND date < ?', $this->id(), $this->start_date->format('Y-m-d')),
				'Des mouvements de cet exercice ont une date antérieure à la date de début de l\'exercice.'
			);

			$this->assert(
				!$db->test(Transaction::TABLE, 'id_year = ? AND date > ?', $this->id(), $this->end_date->format('Y-m-d')),
				'Des mouvements de cet exercice ont une date postérieure à la date de fin de l\'exercice.'
			);
		}
	}

	public function close(int $user_id): void
	{
		if ($this->closed) {
			throw new \LogicException('Cet exercice est déjà clôturé');
		}

		$this->set('closed', 1);
		$this->save();
	}
































































	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();







<








|




|














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


<
>
|

|
>
>
>
>
|
>
>







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
	];

	public function selfCheck(): void
	{
		parent::selfCheck();
		$this->assert($this->start_date < $this->end_date, 'La date de fin doit être postérieure à la date de début');
		$this->assert($this->closed === 0 || $this->closed === 1);


		$db = DB::getInstance();

		$this->assert($this->id_chart !== null);

		if ($this->exists()) {
			$this->assert(
				!$db->test(Transaction::TABLE, 'id_year = ? AND date < ?', $this->id(), $this->start_date->format('Y-m-d')),
				'Des écritures de cet exercice ont une date antérieure à la date de début de l\'exercice.'
			);

			$this->assert(
				!$db->test(Transaction::TABLE, 'id_year = ? AND date > ?', $this->id(), $this->end_date->format('Y-m-d')),
				'Des écritures de cet exercice ont une date postérieure à la date de fin de l\'exercice.'
			);
		}
	}

	public function close(int $user_id): void
	{
		if ($this->closed) {
			throw new \LogicException('Cet exercice est déjà clôturé');
		}

		$this->set('closed', 1);
		$this->save();
	}

	public function reopen(int $user_id): void
	{
		if (!$this->closed) {
			throw new \LogicException('This year is already open');
		}

		$closing_id = $this->accounts()->getClosingAccountId();

		if (!$closing_id) {
			throw new UserException('Aucun compte n\'est indiqué comme compte de clôture dans le plan comptable');
		}

		$this->set('closed', 0);
		$this->save();

		// Create validated transaction to show that someone has reopened the year
		$t = new Transaction;
		$t->import([
			'id_year'    => $this->id(),
			'label'      => sprintf('Exercice réouvert le %s', date('d/m/Y à H:i:s')),
			'type'       => Transaction::TYPE_ADVANCED,
			'date'       => $this->end_date->format('d/m/Y'),
			'id_creator' => $user_id,
			'validated'  => 1,
		]);

		$line = new Line;
		$line->import([
			'debit' => 0,
			'credit' => 1,
			'id_account' => $closing_id,
		]);
		$t->addLine($line);

		$line = new Line;
		$line->import([
			'debit'      => 1,
			'credit'     => 0,
			'id_account' => $closing_id,
		]);
		$t->addLine($line);

		$t->save();
	}

	/**
	 * Splits an accounting year between the current year and another one, at a given date
	 * Any transaction after the given date will be moved to the target year.
	 */
	public function split(\DateTime $date, Year $target): void
	{
		if ($this->closed) {
			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();

Modified src/include/lib/Garradin/Entities/Files/File.php from [0d16ff81d1] to [2f3a044bb4].

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

namespace Garradin\Entities\Files;

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

use Garradin\DB;
use Garradin\Entity;

use Garradin\UserException;
use Garradin\Membres\Session;
use Garradin\Membres;
use Garradin\Static_Cache;
use Garradin\Utils;
use Garradin\Entities\Web\Page;


use Garradin\Files\Files;

use const Garradin\{WWW_URL, ENABLE_XSENDFILE};




class File extends Entity
{
	const TABLE = 'files';

	protected $id;
	protected $folder_id;



	protected $name;
	protected $type;



	protected $image;
	protected $public;
	protected $size;
	protected $hash;

	protected $storage;
	protected $storage_path;

	protected $created;

	protected $author_id;

	protected $_types = [
		'id'           => 'int',
		'folder_id'    => '?int',
		'name'         => 'string',
		'type'         => '?string',
		'public'       => 'int',
		'image'        => 'int',
		'size'         => 'int',
		'hash'         => 'string',
		'storage'      => '?string',
		'storage_path' => '?string',
		'created'      => 'DateTime',
		'author_id'    => '?int',
	];





	/**
	 * 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, 1200];


	// Link to another file (ie. image included in a HTML file)


	const LINK_FILE = 'file_id';

	const LINK_USER = 'user_id';
	const LINK_TRANSACTION = 'transaction_id';
	const LINK_CONFIG = 'config';


	const LINK_WEB_PAGE = 'web_page_id';















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






























	public function selfCheck(): void
	{







		parent::selfCheck();



















	}

	public function delete(): bool
	{

		$return = parent::delete();





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







		return $return;
	}

	public function save(): bool
	{
		$return = parent::save();

		// Store content in search table
		if ($return && substr($this->type, 0, 5) == 'text/') {
			$content = Files::callStorage('fetch', $this);



			if ($this->type == Page::FILE_TYPE_HTML) {
				$content = strip_tags($content);
			}



			if ($this->type == Page::FILE_TYPE_ENCRYPTED) {

				$content = 'Contenu chiffré';


			}


			DB::getInstance()->preparedQuery('INSERT OR REPLACE INTO files_search (id, content) VALUES (?, ?);', $this->id(), $content);

		}








		return $return;
	}

	public function store(string $source_path = null, $source_content = null): self
	{
		if ($source_path && !$source_content)
		{
			$this->set('hash', sha1_file($source_path));
			$this->set('size', filesize($source_path));
		}
		else
		{
			$this->set('hash', sha1($source_content));
			$this->set('size', strlen($source_content));
		}



		// 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('hash', sha1($source_content));
					$this->set('size', strlen($source_content));
				}

				unset($i);
			}
			catch (\RuntimeException $e) {



				if (strstr($e->getMessage(), 'No suitable image library found')) {

					throw new \RuntimeException('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');
			}
		}




		if (!Files::callStorage('store', $this, $source_path, $source_content)) {



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







		return $this;
	}






	static protected function create(string $name, string $source_path = null, $source_content = null): self







	{


















		assert($source_path || $source_content);


































































		$finfo = \finfo_open(\FILEINFO_MIME_TYPE);
		$file = new self;


		$file->name = $name;

		if ($source_path && !$source_content) {
			$file->type = finfo_file($finfo, $source_path);

		}
		else {
			$file->type = finfo_buffer($finfo, $source_content);

		}

		$file->image = preg_match('/^image\/(?:png|jpe?g|gif)$/', $file->type);

		$db = DB::getInstance();

		$db->begin();

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

		$db->commit();
		return $file;
	}

	/**
	 * Upload de fichier à partir d'une chaîne en base64

	 * @param  string $name

	 * @param  string $content


	 * @return File


	 */
	static public function storeFromBase64(string $name, string $encoded_content): self
	{
		$content = base64_decode($encoded_content);

		return self::create($name, null, $content);

	}

	/**
	 * Upload du fichier par POST
	 */
	static public function upload(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 = preg_replace('/[^\d\w._-]/ui', '', $name);

		return self::create($name, $file['tmp_name']);
	}


	/**
	 * 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;
		}
	}

	public function url(?int $size = null): string
	{
		return self::getFileURL($this->id, $this->name, $this->hash, $size);

	}



	public function thumb_url(): string
	{
		return $this->url(min(self::ALLOWED_THUMB_SIZES));
	}

	/**
	 * Renvoie l'URL vers un fichier
	 * @param  integer $id   Numéro du fichier
	 * @param  string  $name  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 getFileURL(int $id, string $name, string $hash, ?int $size = null): string
	{

		$url = sprintf('%sf/%s/%s?', WWW_URL, base_convert((int)$id, 10, 36), $name);

		if ($size)
		{
			$url .= self::_findNearestThumbSize($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 _findNearestThumbSize($size)









>

|
|



>





>
>
>





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


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

>
>
>
>





|

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

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



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




>
|
>
>

>
>
|


|


>
>
>
>
>
>
|


|

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

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


|



<




<


>
>















<






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

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


>
>
>
>
>
>




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



>
>
|


|
>


|
>


<
|
<

<
|
|
|
|
|




|
>
|
>
|
>
>
|
>
>

|


>
|
>





|




















|

|













|

















|

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

<
>
|
>
|








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
<?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\Web\Render\Render;

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 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',
	];

	// https://book.hacktricks.xyz/pentesting-web/file-upload
	const FORBIDDEN_EXTENSIONS = '!^(?:cgi|exe|sh|bash|com|pif|jspx?|js[wxv]|action|do|php(?:s|\d+)?|pht|phtml?|shtml|phar|htaccess|inc|cfml?|cfc|dbm|swf|pl|perl|py|pyc|asp|so)$!i';

	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) || '' === $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));
		}

		DB::getInstance()->delete('files_search', 'path = ? OR path LIKE ?', $this->path, $this->path . '/%');

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

		return true;
	}

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



	public function changeFileName(string $new_name): bool
	{
		$new_name = self::filterName($new_name);
		return $this->rename(ltrim($this->parent . '/' . $new_name, '/'));

	}

	public function rename(string $new_path): bool
	{
		self::validatePath($new_path);
		self::validateFileName(Utils::basename($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->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::validateFileName($name);
		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);
		$this->set('modified', new \DateTime);
		$this->store(null, $content);
		return $this;
	}

	/**
	 * 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)
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
				return $s;
			}
		}

		return max(self::ALLOWED_THUMB_SIZES);
	}

	/**
	 * Lier un fichier à un contenu
	 * @param  string $type       Type de contenu (constantes LINK_*)
	 * @param  integer $foreign_id ID du contenu lié
	 * @return boolean TRUE en cas de succès
	 */
	public function linkTo(string $type, int $foreign_id): bool
	{
		$db = DB::getInstance();
		static $types = [self::LINK_WEB_PAGE, self::LINK_FILE, self::LINK_TRANSACTION, self::LINK_USER, self::LINK_CONFIG];

		if (!in_array($type, $types)) {
			throw new \InvalidArgumentException('Unknown file link type.');
		}

		if ($db->test('files_links', 'id = ?', $this->id())) {
			throw new \LogicException('This file is already linked to something else');
		}

		$sql = sprintf('INSERT OR IGNORE INTO files_links (id, %s) VALUES (?, ?);', $type);

		return $db->preparedQuery($sql, [$this->id, $foreign_id]);
	}

	public function getLinkedId(string $type): ?int
	{
		static $types = [self::LINK_WEB_PAGE, self::LINK_FILE, self::LINK_TRANSACTION, self::LINK_USER, self::LINK_CONFIG];

		if (!in_array($type, $types)) {
			throw new \InvalidArgumentException('Unknown file link type.');
		}

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

	public function listLinked(): array
	{
		return EM::getInstance(File::class)->all('SELECT f.* FROM files f INNER JOIN files_links l ON l.id = f.id WHERE l.file_id = ?;', $this->id());
	}

	/**
	 * Envoie le fichier au client HTTP
	 */
	public function serve(?Session $session = null): 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;
		}







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

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

	/**
	 * Envoie une miniature à la taille indiquée au client HTTP
	 */
	public function serveThumbnail(?Session $session = null, ?int $width = null): void
	{








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


|







>
>
>
>
>
>
|


|







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
				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
	{
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
			$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->id(), $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('getPath', $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');







|






|







580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
			$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');
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











































































	/**
	 * 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(?string $path, ?string $content): void
	{
		if ($this->public) {
			Utils::HTTPCache($this->hash, $this->created->getTimestamp());
		}
		else {
			// Disable browser cache
			header('Pragma: private');
			header('Expires: -1');
			header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0');
		}















		header(sprintf('Content-Type: %s', $this->type));
		header(sprintf('Content-Disposition: inline; filename="%s"', $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', $this->size));

		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 checkReadAccess(Session $session): bool
	{
		// Web and config files should be marked as public when not in draft
		if ($this->public) {
			return true;
		}

		$link = DB::getInstance()->first('SELECT * FROM files_links WHERE id = ?;', $this->id());


		if (!$link) {
			return false;
		}

		// If it's linked to a file, then we want to know what the parent file is linked to
		if ($link->{self::LINK_FILE}) {
			return Files::get((int)$link->{self::LINK_FILE})->checkReadAccess($session);
		}

		if ($link->{self::LINK_TRANSACTION} && $session->canAccess(Session::SECTION_ACCOUNTING, Membres::DROIT_ACCES)) {
			return true;
		}
		// The user can access his own profile files
		else if ($link->{self::LINK_USER} && $link->{self::LINK_USER} == $session->getUser()->id) {
			return true;
		}
		// Only users able to manage users can see their profile files







		else if ($link->{self::LINK_USER} && $session->canAccess(Session::SECTION_USERS, Membres::DROIT_ECRITURE)) {

























































































			return true;
		}



		return $session->canAccess(Session::SECTION_DOCUMENTS, Membres::DROIT_ACCES);



	}
}

















































































<

|

|
|








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




|
|




















|




















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

|
|



|
>

|



<
<
<
<
|
<



|



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



>
>
|
>
>
>

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

	/**
	 * 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(?string $user_prefix = null)
	{
		$editor_type = $this->renderFormat();

		if ($editor_type == 'text') {
			return sprintf('<pre>%s</pre>', htmlspecialchars($this->fetch()));
		}
		elseif (!$editor_type) {
			throw new \LogicException('Cannot render file of this type');
		}
		else {
			return Render::render($editor_type, $this, $this->fetch(), $user_prefix);
		}
	}

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

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

	static public function validateFileName(string $name): void
	{
		if (substr($name[0], 0, 1) === '.') {
			throw new ValidationException('Le nom de fichier ne peut commencer par un point');
		}

		if (strpos($name, "\0") !== false) {
			throw new ValidationException('Nom de fichier invalide');
		}

		$extension = strtolower(substr($name, strrpos($name, '.')));

		if (preg_match(self::FORBIDDEN_EXTENSIONS, $extension)) {
			throw new ValidationException('Extension de fichier non autorisée, merci de renommer le fichier avant envoi.');
		}
	}

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

		if (count($path) < 1) {
			throw new ValidationException('Chemin invalide');
		}

		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 renderFormat(): ?string
	{
		if (substr($this->name, -6) == '.skriv') {
			$format = Render::FORMAT_SKRIV;
		}
		elseif (substr($this->name, -3) == '.md') {
			$format = Render::FORMAT_MARKDOWN;
		}
		else if (substr($this->mime, 0, 5) == 'text/') {
			$format = 'text';
		}
		else {
			$format = null;
		}

		return $format;
	}

	public function editorType(): ?string
	{
		$format = $this->renderFormat();

		if ($format == 'text') {
			return 'code';
		}
		elseif ($format == Render::FORMAT_SKRIV || $format == Render::FORMAT_MARKDOWN) {
			return 'web';
		}

		return null;
	}
}

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

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
192
193
194
195
196
		$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)');

		$list->setExportCallback(function (&$row) {
			$row->paid_amount = $row->paid_amount ? Utils::money_format($row->paid_amount, '.', '', false) : null;
		});

		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 [52650ee9cf].

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
		$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',
				'select' => 'srs.date',

			],
		];

		$tables = 'services_reminders_sent srs
			INNER JOIN membres m ON m.id = srs.id_user';
		$conditions = sprintf('srs.id_reminder = %d', $this->id());

		$list = new DynamicList($columns, $tables, $conditions);
		$list->orderBy('date', true);
		return $list;
	}

}







<






|
|
>













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
		$columns = [
			'id_user' => [
				'select' => 'srs.id_user',
			],
			'identity' => [
				'label' => 'Membre',
				'select' => 'm.' . $identity,

			],
			'email' => [
				'label' => 'Adresse e-mail',
				'select' => 'm.email',
			],
			'date' => [
				'label' => 'Date d\'envoi',
				'select' => 'srs.sent_date',
				'order' => 'srs.sent_date %s, srs.id %1$s',
			],
		];

		$tables = 'services_reminders_sent srs
			INNER JOIN membres m ON m.id = srs.id_user';
		$conditions = sprintf('srs.id_reminder = %d', $this->id());

		$list = new DynamicList($columns, $tables, $conditions);
		$list->orderBy('date', true);
		return $list;
	}

}

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

Modified src/include/lib/Garradin/Entities/Services/Service_User.php from [9cb86069a3] to [10de17a459].

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
		if ($this->fee()->label != $label) {
			$label .= ' - ' . $this->fee()->label;
		}

		$label .= sprintf(' (%s)', (new Membres)->getNom($this->id_user));

		$source['label'] = $label;
		$source['date'] = $this->date->format('d/m/Y');

		$transaction->importFromNewForm($source);
		$transaction->save();
		$transaction->linkToUser($this->id_user, $this->id());

		return $transaction;
	}







<







111
112
113
114
115
116
117

118
119
120
121
122
123
124
		if ($this->fee()->label != $label) {
			$label .= ' - ' . $this->fee()->label;
		}

		$label .= sprintf(' (%s)', (new Membres)->getNom($this->id_user));

		$source['label'] = $label;


		$transaction->importFromNewForm($source);
		$transaction->save();
		$transaction->linkToUser($this->id_user, $this->id());

		return $transaction;
	}

Modified src/include/lib/Garradin/Entities/Users/Category.php from [2ef27a72a7] to [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
<?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;');

    }

}


|

|


|
|

|

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

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

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

>
>
|
<
|
<
|
|

|
|
>
|
|
>
|
>

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

Modified src/include/lib/Garradin/Entities/Web/Page.php from [e6ff2bce2b] to [6b459772f9].

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

namespace Garradin\Entities\Web;

use Garradin\DB;
use Garradin\Entity;
use Garradin\UserException;

use Garradin\Entities\Files\File;



use KD2\DB\EntityManager as EM;

use const Garradin\WWW_URL;

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

	protected $id;
	protected $parent_id;





	protected $type;
	protected $status;
	protected $title;
	protected $uri;
	protected $modified;


	protected $_types = [
		'id'        => 'int',
		'parent_id' => '?int',




		'type'      => 'int',
		'status'    => 'int',
		'uri'       => 'string',
		'title'     => 'string',
		'modified'  => 'DateTime',

	];




	protected $_file;






	const STATUS_ONLINE = 1;
	const STATUS_DRAFT = 0;






	const TYPE_CATEGORY = 1;
	const TYPE_PAGE = 2;

	const FILE_TYPE_HTML = 'text/html';



	const FILE_TYPE_ENCRYPTED = 'text/vnd.skriv.encrypted';
	const FILE_TYPE_SKRIV = 'text/vnd.skriv';


	protected $_attachments;
	protected $_content;

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

		if ($this->type == self::TYPE_CATEGORY) {
			$url .= '/';
		}



		return $url;
	}

	public function raw(): string
	{
		if (null === $this->_content) {
			$this->_content = $this->file()->fetch();
		}

		return $this->_content;
	}

	public function created(): \DateTime

	{
		return $this->file()->created;
	}

	public function file(): File
	{
		if (null === $this->_file) {
			$this->_file = EM::findOneById(File::class, $this->id);
		}

		return $this->_file;
	}











	public function setFile(File $file)
	{

























































		$this->_file = $file;


















	}

	public function save(): bool
	{









		$this->set('modified', new \DateTime);

		$file = $this->file();

		$file->save();











		$this->id($file->id());






		return parent::save();
	}

	public function selfCheck(): void
	{

		$this->assert($this->type === self::TYPE_CATEGORY || $this->type === self::TYPE_PAGE, 'Unknown page type');
		$this->assert($this->status === self::STATUS_DRAFT || $this->status === self::STATUS_ONLINE, 'Unknown page status');

		$this->assert(trim($this->title) !== '', 'Le titre ne peut rester vide');


		$this->assert(trim($this->uri) !== '', 'L\'URI ne peut rester vide');
		$this->assert((bool) $this->_file, 'Fichier manquant');


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

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

		if (isset($source['parent_id']) && is_array($source['parent_id'])) {
			$source['parent_id'] = key($source['parent_id']);
		}

		$file = $this->file();

		if (isset($source['content']) && sha1($source['content']) != $file->hash) {
			$this->_content = $source['content'];
			$file->store(null, $source['content']);
		}

		if (isset($source['date']) && isset($source['date_time'])) {
			$file->importForm(['created' => sprintf('%s %s', $source['date'], $source['date_time'])]);
		}

		if (!empty($source['encrypted']) ) {
			$file->set('type', self::FILE_TYPE_ENCRYPTED);
		}
		else {
			$file->set('type', self::FILE_TYPE_SKRIV);
		}

		return $this->import($source);
	}

	static public function create(int $type, string $title, string $content, int $status = self::STATUS_ONLINE): Page
	{
		static $types = [self::TYPE_PAGE, self::TYPE_CATEGORY];

		if (!in_array($type, $types)) {
			throw new \InvalidArgumentException('Unknown type');

		}

		$page = new self;
		$page->type = $type;
		$page->title = $title;
		$page->uri = Utils::transformTitleToURI($title);
		$page->status = $status;

		$file = new File;
		$file->type = 'text/html';
		$file->image = 0;

		if ($type == self::TYPE_PAGE) {
			$file->name = $page->uri . '.html';
		}
		else {
			$file->name = 'index.html';
		}

		$file->store(null, $content);
		$page->save();

		return $page;
	}

	public function render(array $options = []): string
	{
		$file = $this->file();
		$type = $file->type;

		// Load content
		$this->raw();

		if ($type == self::FILE_TYPE_HTML) {
			return \Garradin\Web\Render\HTML::render($file, $this->_content, $options);
		}
		elseif ($type == self::FILE_TYPE_SKRIV) {
			return \Garradin\Web\Render\Skriv::render($file, $this->_content, $options);
		}
		elseif ($type == self::FILE_TYPE_ENCRYPTED) {
			return \Garradin\Web\Render\EncryptedSkriv::render($file, $this->_content, $options);
		}

		throw new \LogicException('Unknown render type: ' . $type);
	}

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

	public function listAttachments(): array
	{
		if (null === $this->_attachments) {







			$this->_attachments = $this->file()->listLinked();
		}

		return $this->_attachments;
	}

	static public function findTaggedAttachments(string $text): array
	{
		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]);
	}

	/**
	 * 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 = [];


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

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

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

			$out[] = $a;
		}

		return $out;
	}


























































































































}







>

>
>










|
>
>
>
>
>


|
|

>



|
>
>
>
>

|
|
|

>


>
>
>
|
>
>
>
>
>

|
|
>
>
>
>
>




|
>
>
>
|
|

>

<

|

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

<
>
|
|


|

|
|





>
>
>
>
>
>
>
>
>
>
|

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




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

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




>

|
>

>
>

|
>

<
|
|








|
|


|

|
|
<


|
<
<
|
|
<

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

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

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

<
<
|
|
<


|


|
|

|

|

|






>
>
>
>
>
>
>
|







|
|




















>


|











|








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

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
<?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\Render;

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 FORMAT_MARKDOWN = 'markdown';

	const FORMATS_LIST = [
		self::FORMAT_SKRIV => 'SkrivML',
		self::FORMAT_MARKDOWN => 'MarkDown',
		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',
	];

	const DUPLICATE_URI_ERROR = 42;

	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->type = $type;

		$db = DB::getInstance();


		if ($db->test(self::TABLE, 'uri = ?', $page->uri)) {


			$page->importForm(['uri' => $page->uri . date('-Y-m-d-His')]);

		}


		$page->file_path = $page->filepath(false);

		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(?string $user_prefix = null): string
	{
		if (!$this->file()) {
			throw new \LogicException('File does not exist: '  . $this->file_path);
		}

		return Render::render($this->format, $this->file(), $this->content, $user_prefix);
	}

	public function preview(string $content): string
	{
		return Render::render($this->format, $this->file(), $content, '#');
	}

	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(string $path): void
	{
		$export = $this->export();

		$exists = Files::callStorage('exists', $path);

		// Create file if required
		if (!$exists) {
			$file = $this->_file = File::createAndStore(Utils::dirname($path), Utils::basename($path), null, $export);
		}
		else {
			$target = $this->filepath(false);

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

			$file = $this->file();

			// Or update file
			if ($file->fetch() !== $export) {
				$file->set('modified', $this->modified);
				$file->store(null, $export);
			}
		}

		$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
	{
		$change_parent = null;

		if (isset($this->_modified['uri']) || isset($this->_modified['path'])) {
			$this->set('file_path', $this->filepath(false));
			$change_parent = $this->_modified['path'];
		}

		// Update modified date if required
		if (count($this->_modified) && !isset($this->_modified['modified'])) {
			$this->set('modified', new \DateTime);
		}

		$current_path = $this->_modified['file_path'] ?? $this->file_path;
		parent::save();
		$this->syncFile($current_path);

		// Rename/move children
		if ($change_parent) {
			$db = DB::getInstance();
			$sql = sprintf('UPDATE web_pages
				SET path = %s || substr(path, %d), parent = %1$s || substr(parent, %2$d)
				WHERE parent LIKE %s;',
				$db->quote($this->path), strlen($change_parent) + 1, $db->quote($change_parent . '/%'));
			$db->exec($sql);
		}

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

	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);

		$this->set('type', $this->checkRealType());
	}

	public function checkRealType(): int
	{
		foreach (Files::list(Utils::dirname($this->filepath())) as $subfile) {
			if ($subfile->type == File::TYPE_DIRECTORY) {
				return self::TYPE_CATEGORY;
			}
		}

		return self::TYPE_PAGE;
	}

	public function toggleType(): void
	{
		$real_type = $this->checkRealType();

		if ($real_type == self::TYPE_CATEGORY) {
			$this->set('type', $real_type);
		}
		elseif ($this->type == self::TYPE_CATEGORY) {
			$this->set('type', self::TYPE_PAGE);
		}
		else {
			$this->set('type', self::TYPE_CATEGORY);
		}
	}

	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 [a696ddf36e] to [46fdcfd8d1].

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















































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






















































|













|


|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
				return \DateTime::createFromFormat('d/m/Y H:i', $value);
			}
		}

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

	protected function assert(?bool $test, string $message = null, int $code = 0): 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, $code);
		}
	}

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

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

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

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

		Plugin::fireSignal('entity.save.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;
		}

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

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

		return $return;
	}
}

Deleted src/include/lib/Garradin/Fichiers.php version [4906849a5d].

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\Graphics\Image;
use Garradin\Membres\Session;

class Fichiers
{

	/**
	 * 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))
		);
	}


	/**
	 * 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);
		});
	}

}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































Modified src/include/lib/Garradin/Files/Files.php from [eb8e50853d] to [9196c1dfe3].

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

<?php

namespace Garradin\Files;

use Garradin\Static_Cache;
use Garradin\DB;



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


use KD2\DB\EntityManager as EM;


use const Garradin\{FILE_STORAGE_BACKEND, FILE_STORAGE_QUOTA};

class Files
{




	static public function getSystemFile(string $file, string $folder, ?string $subfolder = null): ?File

	{




		$where = Folders::getFolderClause(true, $folder, $subfolder);

		return EM::findOne(File::class, sprintf('SELECT * FROM files WHERE name = ? AND folder_id = (%s) LIMIT 1;', $where), $file);



	}














	static public function listSystemFiles(string $folder, ?string $subfolder = null): array
	{



		$where = Folders::getFolderClause(true, $folder, $subfolder);



		return EM::get(sprintf('SELECT * FROM files WHERE folder_id = (%s) ORDER BY name;', $where));




















































	}

	static public function callStorage(string $function, ...$args)
	{
		// Check that we can store this data
		if ($function == 'store') {
			$quota = FILE_STORAGE_QUOTA ?: self::callStorage('getQuota');
			$used = self::callStorage('getTotalSize');

			$size = $args[0] ? filesize($args[1]) : strlen($args[2]);

			if (($used + $size) >= $quota) {
				throw new \OutOfBoundsException('File quota has been exhausted');
			}
		}

		$storage = FILE_STORAGE_BACKEND ?? 'SQLite';
		$class_name = __NAMESPACE__ . '\\Storage\\' . $storage;
		return call_user_func_array([$class_name, $function], $args);
	}






	static public function migrateStorage(string $from, string $to): void
	{


		$res = EM::getInstance(File::class)->iterate('SELECT * FROM @TABLE;');



		$from = get_class(__NAMESPACE__ . '\\Backend\\' . $from);
		$to = get_class(__NAMESPACE__ . '\\Backend\\' . $to);


		foreach ($res as $file) {




			$from_path = call_user_func([$from, 'path'], $file);
			call_user_func([$to, 'store'], $file, $from_path);
		}


	}















	static public function deleteOrphanFiles()

	{
		$db = DB::getInstance();
		$sql = 'SELECT f.* FROM files f LEFT JOIN files_links l ON f.id = l.id WHERE l.id IS NULL;';





		foreach ($db->iterate($sql) as $file) {
			$f = new Fichiers($file->id, (array) $file);

			$f->remove();


		}









		// Remove any left-overs



		$db->exec('DELETE FROM files_contents WHERE hash NOT IN (SELECT DISTINCT hash FROM files);');

	}

	static public function deleteLinkedFiles(string $type, ?int $value = null)




	{

		foreach (self::iterateLinkedTo($type, $value) as $file) {

			$file->delete();


		}



		self::deleteOrphanFiles();




	}



	static public function iterateLinkedTo(string $type, ?int $value = null)

	{



		$where = $value ? sprintf('l.%s = %d', $value) : sprintf('l.%s IS NOT NULL');


		$sql = sprintf('SELECT f.* FROM @TABLE f INNER JOIN files_links l ON l.id = f.id WHERE %s;', $where);




		return EM::getInstance(File::class)->iterate($sql);

	}
































	static public function get(int $id): ?File
	{
		return EM::findOneById(File::class, $id);
	}

	static public function serveFromQueryString(): void
	{
		$id = isset($_GET['id']) ? $_GET['id'] : null;
		$filename = !empty($_GET['file']) ? $_GET['file'] : null;


		$size = null;


		if (empty($id)) {


			header('HTTP/1.1 404 Not Found', true, 404);
			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);


		$file = self::get((int) $id);



		if (!$file) {




			header('HTTP/1.1 404 Not Found', true, 404);




			throw new UserException('Ce fichier n\'existe pas.');




		}











		$session = Session::getInstance();



		if ($size) {
			$file->serveThumbnail($session, $size);



		}
		else {

			$file->serve($session);


		}
	}
}









>
>
>


>
>

>

|



>
>
>
>
|
>

>
>
>
>
|
>
|
>
>
>
|

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

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




<
<
|
<

<
|
<
<
|
<
<
<
<



>
>
>
>
>
|

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

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


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

>
|
>
|
>
>

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

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

|


|

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

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

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

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

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

namespace Garradin\Files;

use Garradin\Static_Cache;
use Garradin\DB;
use Garradin\Utils;
use Garradin\UserException;
use Garradin\ValidationException;
use Garradin\Membres\Session;
use Garradin\Entities\Files\File;
use Garradin\Entities\Web\Page;

use KD2\DB\EntityManager as EM;
use KD2\ZipWriter;

use const Garradin\{FILE_STORAGE_BACKEND, FILE_STORAGE_QUOTA, FILE_STORAGE_CONFIG};

class Files
{
	/**
	 * To enable or disable quota check
	 */
	static protected $quota = true;

	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 zip(string $parent, ?Session $session)
	{
		$file = Files::get($parent);

		if (!$file) {
			throw new UserException('Ce répertoire n\'existe pas.');
		}

		if ($session && !$file->checkReadAccess($session)) {
			throw new UserException('Vous n\'avez pas accès à ce répertoire');
		}

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

		$add_file = function ($subpath) use ($zip, $parent, &$add_file) {
			foreach (self::list($subpath) as $file) {
				if ($file->type == $file::TYPE_DIRECTORY) {
					$add_file($file->path);
					continue;
				}

				$dest_path = substr($file->path, strlen($parent . '/'));
				$zip->add($dest_path, null, $file->fullpath());
			}
		};

		$add_file($parent);

		$zip->close();
	}

	static public function listForContext(string $context, ?string $ref = null)
	{
		$path = $context;

		if ($ref) {
			$path .= '/' . $ref;
		}

		return self::list($path);
	}

	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);
		}
		catch (UserException $e) {
			throw new \RuntimeException('Migration failed', 0, $e);
		}
		finally {
			$db->commit();
			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 (!$file->parent && $file->name == '.lock') {
				// Ignore lock file
				continue;
			}


			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(): float
	{
		return FILE_STORAGE_QUOTA ?? self::callStorage('getQuota');
	}

	static public function getUsedQuota(bool $force_refresh = false): float
	{
		if ($force_refresh || Static_Cache::expired('used_quota', 3600)) {
			$quota = self::callStorage('getTotalSize');
			Static_Cache::store('used_quota', $quota);
		}
		else {
			$quota = (float) Static_Cache::get('used_quota');
		}

		return $quota;
	}


	static public function getRemainingQuota(bool $force_refresh = false): float
	{
		if (FILE_STORAGE_QUOTA !== null) {
			$quota = FILE_STORAGE_QUOTA - self::getUsedQuota($force_refresh);
		}
		else {
			$quota = self::callStorage('getRemainingQuota');
		}



		return max(0, $quota);
	}

	static public function checkQuota(int $size = 0): void
	{
		if (!self::$quota) {
			return;
		}

		$remaining = self::getRemainingQuota(true);

		if (($remaining - (float) $size) < 0) {
			throw new ValidationException('L\'espace disque est insuffisant pour réaliser cette opération');
		}
	}

	static public function enableQuota(): void
	{
		self::$quota = true;
	}

	static public function disableQuota(): void
	{
		self::$quota = false;
	}

	static public function getVirtualTableName(): string
	{
		if (FILE_STORAGE_BACKEND == 'SQLite') {
			return 'files';
		}

		return 'tmp_files';
	}

	static public function syncVirtualTable(string $parent = '', bool $recursive = false)
	{
		if (FILE_STORAGE_BACKEND == 'SQLite') {
			// No need to create a virtual table, use the real one
			return;
		}

		$db = DB::getInstance();
		$db->begin();

		$db->exec('CREATE TEMP TABLE IF NOT EXISTS tmp_files AS SELECT * FROM files WHERE 0;');

		foreach (Files::list($parent) as $file) {
			// Ignore additional directories
			if ($parent == '' && !array_key_exists($file->name, File::CONTEXTS_NAMES)) {
				continue;
			}

			$db->insert('tmp_files', $file->asArray(true));

			if ($recursive && $file->type === $file::TYPE_DIRECTORY) {
				self::syncVirtualTable($file->path, $recursive);
			}
		}

		$db->commit();
	}
}

Deleted src/include/lib/Garradin/Files/Folders.php version [1060e456d3].

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

namespace Garradin\Files;

use Garradin\Static_Cache;
use Garradin\DB;
use Garradin\Membres\Session;
use Garradin\Entities\Files\File;
use KD2\DB\EntityManager as EM;

class Folders
{
	const TEMPLATES = 'skel';
	const USERS = 'users';
	const TRANSACTIONS = 'accounting';
	const WEB = 'web';
	const CONFIG = 'config';

	static public function getFolderClause(bool $system, string $folder, ?string $subfolder = null)
	{
		$db = DB::getInstance();
		$where = sprintf('SELECT id FROM files_folders WHERE system = %d AND name = %s', $system, $db->quote($folder));

		if (null !== $subfolder) {
			$where = sprintf('SELECT id FROM files_folders WHERE system = %d AND name = %s AND parent = (%s)', $system, $db->quote($subfolder), $where);
		}

		return $where;
	}
}

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






























































Modified src/include/lib/Garradin/Files/Storage/FileSystem.php from [84917f0a0f] to [286067b967].

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














<?php

namespace Garradin\Files\Storage;


use Garradin\Entities\Files\File;



use const Garradin\FILE_STORAGE_CONFIG;

/**
 * This class provides storage in the file system
 * You need ton configure FILE_STORAGE_CONFIG to give a file path
 */
class FileSystem implements StorageInterface
{
	static protected $_size;


	static protected function _getRoot()
	{
		if (!FILE_STORAGE_CONFIG) {
			throw new \RuntimeException('Le stockage de fichier n\'a pas été configuré (FILE_STORAGE_CONFIG est vide).');
		}

		if (!is_writable(FILE_STORAGE_CONFIG)) {
			throw new \RuntimeException('Le répertoire de stockage des fichiers est protégé contre l\'écriture.');
		}

		$target = rtrim(FILE_STORAGE_CONFIG, DIRECTORY_SEPARATOR);
		return realpath($target);
	}










	static protected function ensureDirectoryExists(string $path): void
	{
		if (is_dir($path)) {
			return;
		}

		$permissions = fileperms(self::_getRoot(null));
















































































		mkdir($path, $permissions & 0777, true);
	}

	static public function store(File $file, ?string $path, ?string $content): bool
	{

		$target = self::getPath($file);

		self::ensureDirectoryExists(dirname($target));



		if (null !== $path) {










			return copy($path, $target);
		}
		else {


			return file_put_contents($target, $content);





		}


	}


























	static public function list(?string $path): ?array
	{


		$path = self::_getRoot() . ($path ? DIRECTORY_SEPARATOR . $file->path : '') . DIRECTORY_SEPARATOR . '*';




		$files = glob($path);































		$list = [];

		foreach ($files as $file) {
		}

		return $list;
	}

	static public function getPath(File $file): ?string
	{
		$path = '';

		if ($file->path) {
			$path .= DIRECTORY_SEPARATOR . $file->path;
		}

		$path .= DIRECTORY_SEPARATOR . $file->name;

		return self::_getRoot() . $path;
	}

	static public function display(File $file): void
	{
		readfile(self::getPath($file));
	}

	static public function fetch(File $file): string
	{
		return file_get_contents(self::getPath($file));

	}

	static public function delete(File $file): bool
	{
		return unlink(self::getPath($file));
	}

	static public function move(File $old_file, File $new_file): bool
	{
		$target = self::getPath($new_file);
		self::ensureDirectoryExists(dirname($target));

		return rename(self::getPath($old_file), $target);
	}

	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)) as $p) {
			$total += $p->getSize();
		}

		self::$_size = (int) $total;

		return self::$_size;
	}





	static public function getQuota(): int
	{
		return disk_total_space(self::_getRoot());

	}












	static public function cleanup(): void
	{

	}
}


















>

>
>

|



|




>

|

|



|



|
|


>
>
>
>
>
>
>
>
>






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

|


|

>
|
>


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

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

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

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


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

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

<
<
<
<
|
<


|









|



|




>
>
>
>
|

|
>


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

>

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

namespace Garradin\Files\Storage;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\DB;
use Garradin\Utils;

use const Garradin\DATA_ROOT;

/**
 * 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);
		$file->parent = $parent; // Force empty parent to be empty, not null

		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) {
			// Seems that SKIP_DOTS does not work all the time?
			if ($file->getFilename()[0] == '.') {
				continue;
			}

			// 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 listDirectoriesRecursively(string $path): array
	{
		$fullpath = self::_getRoot() . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $path);
		$fullpath = rtrim($fullpath, DIRECTORY_SEPARATOR);

		if (!file_exists($fullpath)) {
			return [];
		}

		return self::_recurseGlob($fullpath, '*', \GLOB_ONLYDIR);
	}

	static protected function _recurseGlob(string $path, string $pattern = '*', int $flags = 0): array
	{
		$target = $path . DIRECTORY_SEPARATOR . $pattern;
		$list = [];



		// glob is the fastest way to recursely list directories and files apparently


		// after comparing with opendir(), dir() and filesystem recursive iterators



		foreach(glob($target, $flags) as $file) {
			$file = basename($file);


			if ($file[0] == '.') {

				continue;

			}



			$list[] = $file;

			if (is_dir($path . DIRECTORY_SEPARATOR . $file)) {


				foreach (self::_recurseGlob($path . DIRECTORY_SEPARATOR . $file, $pattern, $flags) as $subfile) {
					$list[] = $file . DIRECTORY_SEPARATOR . $subfile;
				}
			}



		}





		return $list;

	}

	static public function getTotalSize(): float
	{
		if (null !== self::$_size) {
			return self::$_size;
		}

		$total = 0;

		$path = self::_getRoot();

		foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY, \RecursiveIteratorIterator::CATCH_GET_CHILD) as $p) {
			$total += $p->getSize();
		}

		self::$_size = (float) $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(): float
	{
		$quota = disk_total_space(self::_getRoot());
		return $quota === false ? (float) \PHP_INT_MAX : (float) $quota;
	}

	static public function getRemainingQuota(): float
	{
		$quota = @disk_free_space(self::_getRoot());
		return $quota === false ? (float) \PHP_INT_MAX : (float) $quota;
	}

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

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

	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('FileSystem storage is locked');
		}
	}
}

Modified src/include/lib/Garradin/Files/Storage/SQLite.php from [9d66b11f89] to [69084d5de4].

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

<?php

namespace Garradin\Files\Storage;

use Garradin\Entities\Files\File;


use Garradin\Static_Cache;
use Garradin\DB;




use const Garradin\DB_FILE;

class SQLite implements StorageInterface
{




	/**
	 * 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->hash;

		if (!Static_Cache::exists($cache_id))
		{
			$db = DB::getInstance();
			$id = $db->firstColumn('SELECT id FROM files_contents WHERE hash = ?;', $file->hash);

			$blob = $db->openBlob('files_contents', 'content', (int)$id);









			Static_Cache::storeFromPointer($cache_id, $blob);
			fclose($blob);
		}

		return Static_Cache::getPath($cache_id);
	}

	static public function store(File $file, ?string $path, ?string $content): bool
	{


		$db = DB::getInstance();


		if ($db->test('files_contents', 'hash = ?', $file->hash)) {

			return true;




		}


		$db->preparedQuery('INSERT INTO files_contents (hash, content, size) VALUES (?, zeroblob(?), ?);',

			$file->hash, $file->size, $file->size);



		$id = (int) $db->lastInsertId();



		$blob = $db->openBlob('files_contents', 'content', $id, 'main', SQLITE3_OPEN_READWRITE);

		if (null !== $content) {
			fwrite($blob, $content);
		}
		else {

			fwrite($blob, file_get_contents($path));

		}

		fclose($blob);








		return true;
	}

	static public function list(string $path): ?array
	{
		return null;
	}

	static public function getPath(File $file): ?string
	{
		return self::_getFilePathFromCache($file);
	}

	static public function display(File $file): void
	{
		readfile(self::getFilePathFromCache($file));
	}

	static public function fetch(File $file): string
	{
		return file_get_contents(self::_getFilePathFromCache($file));
	}





























	static public function delete(File $file): bool
	{


		$cache_id = 'files.' . $file->hash;
		Static_Cache::remove($cache_id);

		return DB::getInstance()->delete('files_contents', 'hash = ?', (int)$file->hash);






































	}

	static public function move(File $old_file, File $new_file): bool
	{






		return true;
	}

	static public function getTotalSize(): int
	{
		return (int) DB::getInstance()->firstColumn('SELECT SUM(size) FROM files_contents;');
	}





	static public function getQuota(): int
	{
		return disk_total_space(dirname(DB_FILE));

	}







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


		$sql = 'SELECT c.id, c.hash FROM files_contents c LEFT JOIN files f ON f.hash = c.hash WHERE f.hash IS NULL;';
		$ids = [];




		foreach ($db->iterate($sql) as $row) {
			$cache_id = 'files.' . $row->hash;
			Static_Cache::remove($cache_id);
			$ids[] = $row->id;


		}




		$db->delete('files_contents', $db->where('id', $ids));


	}
}






>



>

>
>
|



>
>
>
>






|




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







|

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


>
|
>
|
>

>
|
>
>

|

|
|


>
|
>



>
>
>
>
>
>
>




<
<
<
<
<
|






|




|


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


>
>
|


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


|

>
>
>
>
>
>



|

|


>
>
>
>
|

|
>


>
>
>
>
>
>
|


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

>
>
>
|
>
>
|
|
>
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
<?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 listDirectoriesRecursively(string $path): array
	{
		$files = [];
		$it = DB::getInstance()->iterate('SELECT path FROM files WHERE parent LIKE ? ORDER BY path;', $path . '/%');

		foreach ($it as $file) {
			$files[] = substr($file->path, strlen($path) + 1);
		}

		return $files;
	}

	static public function exists(string $path): bool
	{
		return DB::getInstance()->test('files', 'path = ?', $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(): float
	{
		return (float) 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(): float
	{
		$quota = @disk_total_space(DATA_ROOT);
		return $quota === false ? (float) \PHP_INT_MAX : (float) $quota;
	}

	static public function getRemainingQuota(): float
	{
		$quota = @disk_free_space(DATA_ROOT);
		return $quota === false ? (float) \PHP_INT_MAX : (float) $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');
		}
	}
}

Modified src/include/lib/Garradin/Files/Storage/StorageInterface.php from [13efeef289] to [67b35b24ca].

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\Files\Storage;

use Garradin\Entities\Files\File;

interface StorageInterface
{



	static public function store(File $file, ?string $path, ?string $content): bool;

	/**
	 * List files contained in a path, this must return an array of File instances
	 * If this storage backend wants to leave the directory handling to Garradin, just return NULL.


	 * @param  string $path




	 * @return array[File...]


	 */
	static public function list(string $path): ?array;

	/**
	 * 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 getPath(File $file): ?string;




	static public function display(File $file): void;




	static public function fetch(File $file): string;




	static public function delete(File $file): bool;






























	static public function move(File $old_file, File $new_file): bool;




	static public function getTotalSize(): int;






























	static public function getQuota(): int;

	static public function cleanup(): void;
}








>
>
>
|


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

|






|

>
>
>


>
>
>


>
>
>


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

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

>
|
|
|

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

	/**
	 * Return an array of (string) paths of all subdirectories inside a path
	 * @param  string $path Parent path
	 */
	static public function listDirectoriesRecursively(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(): float;

	/**
	 * Return total disk space
	 * This will only be called if FILE_STORAGE_QUOTA constant is null
	 */
	static public function getQuota(): float;

	/**
	 * Return available free disk space
	 * This will only be called if FILE_STORAGE_QUOTA constant is null
	 */
	static public function getRemainingQuota(): float;

	/**
	 * 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;
}

Added src/include/lib/Garradin/Files/Transactions.php version [181762b574].



























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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\Files;

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

class Transactions
{
	const LIST_COLUMNS = [
		'id' => [
			'select' => 't.id',
			'label' => 'N°',
		],
		'label' => [
			'select' => 't.label',
			'label' => 'Libellé',
		],
		'date' => [
			'label' => 'Date',
			'select' => 't.date',
			'order' => 't.date %s, t.id %1$s',
		],
		'reference' => [
			'label' => 'Pièce comptable',
			'select' => 't.reference',
		],
		'year' => [
			'select' => 'y.label',
			'label' => 'Exercice',
			'order' => 'y.end_date %s, t.date %1$s, t.id %1$s',
		],
		'path' => [
		],
	];

	static public function list()
	{
		Files::syncVirtualTable(File::CONTEXT_TRANSACTION);

		$columns = self::LIST_COLUMNS;

		$tables = sprintf('%s f
			INNER JOIN acc_transactions t ON t.id = f.name
			INNER JOIN acc_years y ON t.id_year = y.id', Files::getVirtualTableName());

		$sum = 0;

		// Only fetch directories with an ID as the name
		$conditions = sprintf('f.parent = \'%s\' AND f.type = %d AND printf("%%d", f.name) = name', File::CONTEXT_TRANSACTION, File::TYPE_DIRECTORY);

		$list = new DynamicList($columns, $tables, $conditions);
		$list->orderBy('year', true);
		$list->setCount('COUNT(DISTINCT t.id)');
		$list->setModifier(function (&$row) {
			$row->date = \DateTime::createFromFormat('!Y-m-d', $row->date);
		});

		return $list;
	}
}

Added src/include/lib/Garradin/Files/Users.php version [55c1feeac2].











































































































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

namespace Garradin\Files;

use Garradin\Entities\Files\File;
use Garradin\DynamicList;
use Garradin\Config;

class Users
{
	const LIST_COLUMNS = [
		'number' => [
			'select' => 'm.numero',
			'label' => 'Numéro',
		],
		'identity' => [
			'select' => '',
			'label' => '',
		],
		'path' => [
		],
		'id' => [
			'label' => null,
			'select' => 'm.id',
		],
	];

	static public function list()
	{
		Files::syncVirtualTable(File::CONTEXT_USER);

		$config = Config::getInstance();
		$name_field = $config->get('champ_identite');
		$champs = $config->get('champs_membres');

		$columns = self::LIST_COLUMNS;
		$columns['identity']['select'] = 'm.' . $name_field;
		$columns['identity']['label'] = $champs->get($name_field)->title;

		$tables = sprintf('%s f INNER JOIN membres m ON m.id = f.name', Files::getVirtualTableName());

		$sum = 0;

		// Only fetch directories with an ID as the name
		$conditions = sprintf('f.parent = \'%s\' AND f.type = %d AND printf("%%d", f.name) = name', File::CONTEXT_USER, File::TYPE_DIRECTORY);

		$list = new DynamicList($columns, $tables, $conditions);
		$list->orderBy('number', false);
		$list->setCount('COUNT(DISTINCT m.id)');

		return $list;
	}
}

Modified src/include/lib/Garradin/Form.php from [3839ed2cd0] to [7d0dc0a0a9].

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

		// Test si la valeur existe dans cette table
		// in_table:compta_categories,id
		\KD2\Form::registerValidationRule('in_table', function ($name, $params, $value) {
			$db = DB::getInstance();
			return $db->test($params[0], $db->where($params[1], $value));
		});








	}

	public function run(callable $fn, ?string $csrf_key = null, ?string $redirect = null): bool
	{
		if (null !== $csrf_key && !$this->check($csrf_key)) {
			return false;
		}

		try {
			call_user_func($fn);

			if (null !== $redirect) {




				Utils::redirect($redirect);
			}

			return true;
		}
		catch (UserException $e) {
			$this->addError($e->getMessage());
			return false;
		}
	}

	public function runIf($condition, callable $fn, ?string $csrf_key = null, ?string $redirect = null): ?bool
	{
		if (is_string($condition) && empty($_POST[$condition])) {







>
>
>
>
>
>
>
>












>
>
>
>






|







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

		// Test si la valeur existe dans cette table
		// in_table:compta_categories,id
		\KD2\Form::registerValidationRule('in_table', function ($name, $params, $value) {
			$db = DB::getInstance();
			return $db->test($params[0], $db->where($params[1], $value));
		});

		// Catch file size https://stackoverflow.com/questions/2133652/how-to-gracefully-handle-files-that-exceed-phps-post-max-size
		if (empty($_FILES) && empty($_POST)
			&& isset($_SERVER['REQUEST_METHOD'])
			&& !empty($_SERVER['CONTENT_LENGTH'])
			&& strtoupper($_SERVER['REQUEST_METHOD']) == 'POST') {
			$this->addError('Le fichier envoyé dépasse la taille autorisée');
		}
	}

	public function run(callable $fn, ?string $csrf_key = null, ?string $redirect = null): bool
	{
		if (null !== $csrf_key && !$this->check($csrf_key)) {
			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);
			return false;
		}
	}

	public function runIf($condition, callable $fn, ?string $csrf_key = null, ?string $redirect = null): ?bool
	{
		if (is_string($condition) && empty($_POST[$condition])) {

Modified src/include/lib/Garradin/Install.php from [1e3ce59b3f] to [3dd5922cef].

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\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
{
	static public function reset(Membres\Session $session, $password, array $options = [])
	{
		$config = (object) Config::getInstance()->getConfig();
		$user = $session->getUser();

		if (!$session->checkPassword($password, $user->passe))
		{
			throw new UserException('Le mot de passe ne correspond pas.');
		}








>
>
>









|







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
<?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
{
	static public function reset(Membres\Session $session, $password, array $options = [])
	{
		$config = (object) Config::getInstance()->asArray();
		$user = $session->getUser();

		if (!$session->checkPassword($password, $user->passe))
		{
			throw new UserException('Le mot de passe ne correspond pas.');
		}

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
211
212
			// 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.\n\nCe message peut être modifié dans la 'Configuration'.", $name);

		$path = Config::DEFAULT_FILES['admin_homepage'];

		$file = File::createAndStore(Utils::dirname($path), Utils::basename($path), 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)
	{







|
>
>
>
>
>
>
>
>
>



|











>
>
>







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

		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 [3b158cb987] to [927864c538].

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));

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

            if ($db->test('membres', 'numero = ? AND id != ?', (int)$data['numero'], $id))
            {
                throw new UserException('Ce numéro est déjà attribué à un autre membre.');
            }
        }





        if (!empty($data['passe']) && trim($data['passe']))
        {
            Session::checkPasswordValidity($data['passe']);
            $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;
        }








>
>
>
>
|









|

|







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

            if ($db->test('membres', 'numero = ? AND id != ?', (int)$data['numero'], $id))
            {
                throw new UserException('Ce numéro est déjà attribué à un autre membre.');
            }
        }

        if (isset($data['delete_password'])) {
            $data['passe'] = null;
            unset($data['delete_password']);
        }
        elseif (!empty($data['passe']) && trim($data['passe']))
        {
            Session::checkPasswordValidity($data['passe']);
            $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;
        }

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
                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();








|







274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
                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();

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

        if (!count($recipients)) {
        	throw new UserException('Aucun destinataire de la liste ne possède d\'adresse email.');
        }

        foreach ($recipients as $recipient)
        {




            Utils::sendEmail(Utils::EMAIL_CONTEXT_BULK, $recipient->email, $subject, $message, $recipient->id);
        }

        if ($send_copy)
        {
            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 = [







>
>
>
>











|


|


|







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

        if (!count($recipients)) {
        	throw new UserException('Aucun destinataire de la liste ne possède d\'adresse email.');
        }

        foreach ($recipients as $recipient)
        {
            if (!isset($recipient->email, $recipient->id)) {
                throw new UserException('Il manque l\'identifiant ou l\'email dans le résultat');
            }

            Utils::sendEmail(Utils::EMAIL_CONTEXT_BULK, $recipient->email, $subject, $message, $recipient->id);
        }

        if ($send_copy)
        {
            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 = [
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
            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));
    }
}







<
<
<
<
<



|




















|



|










|
>
>
>
>
>











|




|





<
<
|
<
<
<
<
<










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

Modified src/include/lib/Garradin/Membres/Champs.php from [5d64a9e45c] to [8c67451d61].

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') {
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
                continue;
            }

            return $key;
        }
    }

    public function getValidationRules($mode = 'edit')
    {
        assert(in_array($mode, ['edit', 'create', 'user_edit']));

        $all_rules = [];

        foreach ($this->champs as $name => $config)
        {
            if (empty($config->editable) && $mode == 'user_edit')
            {
                $all_rules[$name] = 'absent';
                break;
            }

            $rules = [];

            if (!empty($config->mandatory) && !($name == 'passe' && $mode != 'create'))
            {
                $rules[] = 'required';
            }

            if ($config->type == 'email')
            {
                $rules[] = 'email';
            }
            elseif ($config->type == 'url')
            {
                $rules[] = 'url';
            }
            elseif ($config->type == 'date')
            {
                $rules[] = 'date_format:Y-m-d';
            }
            elseif ($config->type == 'date')
            {
                $rules[] = 'date_format:Y-m-d H\:i';
            }
            elseif ($config->type == 'number' || $config->type == 'multiple')
            {
                $rules[] = 'numeric';
            }
            elseif ($config->type == 'checkbox')
            {
                $rules[] = 'boolean';
            }

            if ($name == 'passe')
            {
                $rules[] = 'min:6';
            }

            if (isset($config->rules))
            {
                $rules[] = $config->rules;
            }

            if (count($rules))
            {
                $all_rules[$name] = implode('|', $rules);
            }
        }

        return $all_rules;
    }

    /**
     * Vérifie la cohérence et la présence des bons éléments pour un champ
     * @param  string $name     Nom du champ
     * @param  array $config    Configuration du champ
     * @return boolean true
     */
    protected function _checkField($name, \stdClass &$config)







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







235
236
237
238
239
240
241

































































242
243
244
245
246
247
248
                continue;
            }

            return $key;
        }
    }


































































    /**
     * Vérifie la cohérence et la présence des bons éléments pour un champ
     * @param  string $name     Nom du champ
     * @param  array $config    Configuration du champ
     * @return boolean true
     */
    protected function _checkField($name, \stdClass &$config)
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;
    }
}







<
<
<
<
<
|

|
|




|






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

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

|
>
>
>
>







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

|

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

>
>
|
>
|
>
>
>


|


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

|
<
|
<




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










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
        }

        $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 IF NOT EXISTS users_id_field ON %s (%s%s);', $table_name, $id_field, $collation));
        }



        $db->exec(sprintf('CREATE UNIQUE INDEX IF NOT EXISTS user_number ON %s (numero);', $table_name));
        $db->exec(sprintf('CREATE INDEX IF NOT EXISTS 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 IF NOT EXISTS 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 [9fc2a43ba6].

8
9
10
11
12
13
14


15
16
17
18
19
20
21
use Garradin\Utils;
use Garradin\CSV;
use Garradin\CSV_Custom;
use Garradin\UserException;

class Import
{


	/**
	 * Importer un CSV générique
	 * @return boolean                   TRUE en cas de succès
	 */
	public function fromCustomCSV(CSV_Custom $csv, int $current_user_id)
	{
		$db = DB::getInstance();







>
>







8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use Garradin\Utils;
use Garradin\CSV;
use Garradin\CSV_Custom;
use Garradin\UserException;

class Import
{
	protected $champs;

	/**
	 * Importer un CSV générique
	 * @return boolean                   TRUE en cas de succès
	 */
	public function fromCustomCSV(CSV_Custom $csv, int $current_user_id)
	{
		$db = DB::getInstance();
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))
		{







<
<
<







88
89
90
91
92
93
94



95
96
97
98
99
100
101
		$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))
		{
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
					$values = explode(';', $data[$name]);
					$data[$name] = 0;

					foreach ($values as $v) {
						$v = trim($v);
						$found = array_search($v, $champs_multiples[$name]->options);

						if ($found) {
							$data[$name] |= 0x01 << $found;
						}
					}
				}
			}

			if (!empty($data['numero']) && $data['numero'] > 0)







|







152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
					$values = explode(';', $data[$name]);
					$data[$name] = 0;

					foreach ($values as $v) {
						$v = trim($v);
						$found = array_search($v, $champs_multiples[$name]->options);

						if ($found !== false) {
							$data[$name] |= 0x01 << $found;
						}
					}
				}
			}

			if (!empty($data['numero']) && $data['numero'] > 0)
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,







|
|







214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
			$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,
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
	public function toODS(array $list = null): void
	{
		list($champs, $result, $name) = $this->export($list);
		CSV::toODS($name, $result, $champs, [$this, 'exportRow']);
	}

	public function exportRow(\stdClass $row) {
		// Pas hyper efficace, il faudrait ne pas récupérer la liste pour chaque ligne... FIXME
		$champs_multiples = Config::getInstance()->get('champs_membres')->getMultiples();









		// convertir les champs à choix multiple de binaire vers liste séparée par des points virgules
		foreach ($champs_multiples as $id=>$config) {
			$out = [];

			foreach ($config->options as $b => $name)
			{
				if ($row->$id & (0x01 << $b)) {
					$out[] = $name;
				}
			}

			$row->$id = implode(';', $out);

		}

		return $row;
	}
}







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

|
|
|
|
|
|

|
|





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
	public function toODS(array $list = null): void
	{
		list($champs, $result, $name) = $this->export($list);
		CSV::toODS($name, $result, $champs, [$this, 'exportRow']);
	}

	public function exportRow(\stdClass $row) {
		if (null === $this->champs) {
			$this->champs = Config::getInstance()->get('champs_membres')->getAll();
		}

		foreach ($this->champs as $id => $config) {
			if ($config->type == 'date') {
				$row->$id = \DateTime::createFromFormat('!Y-m-d', $row->$id);
			}
			elseif ($config->type == 'datetime') {
				$row->$id = \DateTime::createFromFormat('!Y-m-d H:i:s', $row->$id);
			}
			// convertir les champs à choix multiple de binaire vers liste séparée par des points virgules
			elseif ($config->type == 'multiple') {
				$out = [];

				foreach ($config->options as $b => $name)
				{
					if ($row->$id & (0x01 << $b)) {
						$out[] = $name;
					}
				}

				$row->$id = implode(';', $out);
			}
		}

		return $row;
	}
}

Modified src/include/lib/Garradin/Membres/Session.php from [d8f65f6ef2] to [08959104e6].

18
19
20
21
22
23
24
25
26








27
28
29
30
31
32
33
use KD2\Graphics\QRCode;
use KD2\HTTP;

class Session extends \KD2\UserSession
{
	const SECTION_WEB = 'web';
	const SECTION_DOCUMENTS = 'documents';
	const SECTION_USERS = 'membres';
	const SECTION_ACCOUNTING = 'compta';









	// 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;







|
|
>
>
>
>
>
>
>
>







18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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;
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
			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. 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







|







74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
			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
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
	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_web, c.droit_documents,
			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,







|
|


|











|
|

|







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
	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,
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

	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;
320
321
322
323
324
325
326













327
328
329
330
331
332
333
334



335
336
337
338
339
340
341
342
	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 [d9b7c0cb75].

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
503
504
505
506
507
508
509
510
511
		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) {
				$prop = $m[1];
				if (!property_exists($user, $prop)) {
					return 'NULL';
				}

				if (substr($prop, 0, 5) == 'perm_') {
					return (int) $user->$prop;
				}

				return $db->quote($user->$prop);
			}, $condition);

			$query = 'SELECT 1 WHERE ' . $condition . ';';

			$res = $db->protectSelect(['membres' => []], $query);

			if (!$db->firstColumn($query))
			{
				unset($list[$id]);
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
			{
				throw new \RuntimeException('Le fichier garradin_plugin.ini ne contient pas d\'entrée "'.$key.'".');
			}
		}

		if (!empty($infos->min_version) && !version_compare(garradin_version(), $infos->min_version, '>='))
		{
			throw new \RuntimeException('Le plugin '.$id.' nécessite Garradin version '.$infos->min_version.' ou supérieure.');
		}

		if (!empty($infos->max_version) && !version_compare(garradin_version(), $infos->max_version, '>'))
		{
			throw new \RuntimeException('Le plugin '.$id.' nécessite Garradin version '.$infos->max_version.' ou inférieure.');
		}

		if (!empty($infos->menu) && !file_exists($path . '/www/admin/index.php'))
		{
			throw new \RuntimeException('Le plugin '.$id.' ne comporte pas de fichier www/admin/index.php alors qu\'il demande à figurer au menu.');
		}








|




|







725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
			{
				throw new \RuntimeException('Le fichier garradin_plugin.ini ne contient pas d\'entrée "'.$key.'".');
			}
		}

		if (!empty($infos->min_version) && !version_compare(garradin_version(), $infos->min_version, '>='))
		{
			throw new UserException('Le plugin '.$id.' nécessite Garradin version '.$infos->min_version.' ou supérieure.');
		}

		if (!empty($infos->max_version) && !version_compare(garradin_version(), $infos->max_version, '>'))
		{
			throw new UserException('Le plugin '.$id.' nécessite Garradin version '.$infos->max_version.' ou inférieure.');
		}

		if (!empty($infos->menu) && !file_exists($path . '/www/admin/index.php'))
		{
			throw new \RuntimeException('Le plugin '.$id.' ne comporte pas de fichier www/admin/index.php alors qu\'il demande à figurer au menu.');
		}

Modified src/include/lib/Garradin/Recherche.php from [d53f7c5508] to [5e796b3eb4].

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
				}
			}
		}

		return $query;
	}

	public function duplicate(int $id)
	{
		DB::getInstance()->preparedQuery('INSERT INTO recherches (id_membre, intitule, cible, type, contenu)
			SELECT id_membre, \'Copie de : \' || intitule, cible, type, contenu FROM recherches WHERE id = ?;', [$id]);
	}

	public function edit($id, $data)
	{
		$allowed = ['intitule', 'id_membre', 'type', 'cible', 'contenu'];

		// Supprimer les champs qui ne sont pas ceux de la BDD
		$data = array_intersect_key($data, array_flip($allowed));








<
<
<
<
<
<







77
78
79
80
81
82
83






84
85
86
87
88
89
90
				}
			}
		}

		return $query;
	}







	public function edit($id, $data)
	{
		$allowed = ['intitule', 'id_membre', 'type', 'cible', 'contenu'];

		// Supprimer les champs qui ne sont pas ceux de la BDD
		$data = array_intersect_key($data, array_flip($allowed));

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
			}

			$out[$key] = $label;
		}

		return $out;
	}





















	/**
	 * Renvoie la liste des colonnes d'une cible
	 */
	public function getColumns($target)
	{
		$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,







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













|




|







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
			}

			$out[$key] = $label;
		}

		return $out;
	}

	public function getDefaultOrder(string $target): string
	{
		if ($target == 'compta') {
			return 't.date';
		}
		else {
			return Config::getInstance()->get('champ_identite');
		}
	}

	public function getDefaultDesc(string $target): bool
	{
		if ($target == 'compta') {
			return true;
		}
		else {
			return false;
		}
	}

	/**
	 * Renvoie la liste des colonnes d'une cible
	 */
	public function getColumns($target)
	{
		$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,
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
				'null'     => true,
				'alias'    => 'line_label',
			];

			$columns['l.debit'] = (object) [
				'textMatch'=> false,
				'label'    => 'Débit',
				'type'     => 'integer',
				'null'     => false,
				'alias'    => 'debit',
				'originalType' => 'money',
			];

			$columns['l.credit'] = (object) [
				'textMatch'=> false,
				'label'    => 'Crédit',
				'type'     => 'integer',
				'null'     => false,
				'alias'    => 'credit',
				'originalType' => 'money',
			];

			$columns['l.reference'] = (object) [
				'textMatch'=> true,







|








|







321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
				'null'     => true,
				'alias'    => 'line_label',
			];

			$columns['l.debit'] = (object) [
				'textMatch'=> false,
				'label'    => 'Débit',
				'type'     => 'text',
				'null'     => false,
				'alias'    => 'debit',
				'originalType' => 'money',
			];

			$columns['l.credit'] = (object) [
				'textMatch'=> false,
				'label'    => 'Crédit',
				'type'     => 'text',
				'null'     => false,
				'alias'    => 'credit',
				'originalType' => 'money',
			];

			$columns['l.reference'] = (object) [
				'textMatch'=> true,
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
				}

				if (!array_key_exists($condition['column'], $target_columns))
				{
					// Ignorer une condition qui se rapporte à une colonne
					// qui n'existe pas, cas possible si on reprend une recherche
					// 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);







|





<
<
<
<
<
<
|
<



<
<







444
445
446
447
448
449
450
451
452
453
454
455
456






457

458
459
460


461
462
463
464
465
466
467
				}

				if (!array_key_exists($condition['column'], $target_columns))
				{
					// Ignorer une condition qui se rapporte à une colonne
					// qui n'existe pas, cas possible si on reprend une recherche
					// après avoir modifié les fiches de membres
					continue;
				}

				$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);
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
			{
				$query_groups[] = implode(' ' . $group['operator'] . ' ', $query_group_conditions);
			}
		}

		if (!count($query_groups))
		{
			throw new UserException('Aucune clause trouvée dans la recherche.');
		}

		// Ajout du champ identité si pas présent
		if ($target == 'membres')
		{
			$query_columns = array_merge([$config->get('champ_identite')], $query_columns);
		}
		// Ajout de champs compta si pas présents
		elseif ($target == 'compta')
		{
			$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);







|

















|







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
			{
				$query_groups[] = implode(' ' . $group['operator'] . ' ', $query_group_conditions);
			}
		}

		if (!count($query_groups))
		{
			throw new UserException('Aucune clause trouvée dans la recherche : elle contenait peut-être des clauses qui correspondent à des champs qui ont été supprimés ?');
		}

		// Ajout du champ identité si pas présent
		if ($target == 'membres')
		{
			$query_columns = array_merge([$config->get('champ_identite')], $query_columns);
		}
		// Ajout de champs compta si pas présents
		elseif ($target == 'compta')
		{
			$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);
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
		else {
			$sql_query = sprintf('SELECT id, %s FROM %s WHERE %s ORDER BY %s %s LIMIT %d;',
				$query_columns, $target, $query_groups, $order, $desc, (int) $limit);
		}

		return $sql_query;
	}




















	/**
	 * Lancer une recherche SQL
	 */
	public function searchSQL(string $target, $query, array $force_select = null, bool $no_limit = false, bool $unprotected = false)
	{
		if (!in_array($target, self::TARGETS, true))
		{
			throw new \InvalidArgumentException('Cible inconnue : ' . $target);
		}

		if (null !== $force_select)
		{
			$query = preg_replace('/^\s*SELECT.*FROM\s+/Ui', 'SELECT ' . implode(', ', $force_select) . ' FROM ', $query);
		}

		if (!$no_limit && !preg_match('/LIMIT\s+\d+/i', $query))
		{
			$query = preg_replace('/;?\s*$/', '', $query);
			$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];







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













|












|







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
		else {
			$sql_query = sprintf('SELECT id, %s FROM %s WHERE %s ORDER BY %s %s LIMIT %d;',
				$query_columns, $target, $query_groups, $order, $desc, (int) $limit);
		}

		return $sql_query;
	}

	static public function rawSQL(string $query, array $allowed_tables = null, bool $no_limit = false): array
	{
		if (!$no_limit && !preg_match('/LIMIT\s+\d+/i', $query))
		{
			$query = preg_replace('/;?\s*$/', '', $query);
			$query .= ' LIMIT 100';
		}

		$st = DB::getInstance()->protectSelect($allowed_tables, $query);
		$res = $st->execute();
		$out = [];

		while ($row = $res->fetchArray(\SQLITE3_ASSOC)) {
			$out[] = (object) $row;
		}

		return $out;
	}

	/**
	 * Lancer une recherche SQL
	 */
	public function searchSQL(string $target, $query, array $force_select = null, bool $no_limit = false, bool $unprotected = false)
	{
		if (!in_array($target, self::TARGETS, true))
		{
			throw new \InvalidArgumentException('Cible inconnue : ' . $target);
		}

		if (null !== $force_select)
		{
			$query = preg_replace('/^\s*SELECT.*FROM\s+/Uis', 'SELECT ' . implode(', ', $force_select) . ' FROM ', $query);
		}

		if (!$no_limit && !preg_match('/LIMIT\s+\d+/i', $query))
		{
			$query = preg_replace('/;?\s*$/', '', $query);
			$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];
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
	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 [e908d15ab0] to [c99705a80b].

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;






class Sauvegarde
{
	const NEED_UPGRADE = 0x01 << 2;
	const NOT_AN_ADMIN = 0x01 << 3;

	const INTEGRITY_FAIL = 41;
	const NOT_A_DB = 42;
	const NO_APP_ID = 43;

	/**
	 * Renvoie la liste des fichiers SQLite sauvegardés
	 * @param  boolean $auto Si true ne renvoie que la liste des sauvegardes automatiques
	 * @return array 		 Liste des fichiers
	 */
	public function getList($auto = false)
	{
		$ext = $auto ? 'auto\.\d+\.sqlite' : 'sqlite';

		$out = [];
		$dir = dir(DATA_ROOT);

		while ($file = $dir->read())
		{

			if ($file[0] != '.' && is_file(DATA_ROOT . '/' . $file) 
				&& preg_match('![\w\d._-]+\.' . $ext . '$!i', $file) && $file != basename(DB_FILE))


			{


























				$out[$file] = filemtime(DATA_ROOT . '/' . $file);


			}









		}

		$dir->close();


		ksort($out);



		return $out;
	}

	/**
	 * 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($auto = false)
	{
		$suffix = is_string($auto) ? $auto : ($auto ? 'auto.1' : date('Y-m-d-His'));

		$backup = str_replace('.sqlite', sprintf('.%s.sqlite', $suffix), DB_FILE);








		// Acquire a shared lock before copying

		$db = DB::getInstance();
		$db->exec('BEGIN IMMEDIATE TRANSACTION;');







		copy(DB_FILE, $backup);





		$db->exec('END TRANSACTION;');
		return basename($backup);
	}


	/**
	 * Effectue une rotation des sauvegardes automatiques
	 * association.auto.1.sqlite deviendra association.auto.2.sqlite par exemple
	 * @return boolean true
	 */
	public function rotate()
	{
		$config = Config::getInstance();
		$nb = $config->get('nombre_sauvegardes');

		$list = $this->getList(true);


		krsort($list);




		if (count($list) >= $nb)
		{
			$this->remove(key($list));

			array_shift($list);

		}

		foreach ($list as $f=>$d)
		{
			$new = preg_replace_callback('!\.auto\.(\d+)\.sqlite$!', function ($m) {
				return '.auto.' . ((int) $m[1] + 1) . '.sqlite';

			}, $f);




			rename(DATA_ROOT . '/' . $f, DATA_ROOT . '/' . $new);
		}

		return true;
	}

	/**
	 * Crée une sauvegarde automatique si besoin est
	 * @return boolean true
	 */
	public function auto()
	{
		$config = Config::getInstance();

		// Pas besoin d'aller plus loin si on ne fait pas de sauvegarde auto
		if ($config->get('frequence_sauvegardes') == 0 || $config->get('nombre_sauvegardes') == 0)
			return true;

		$list = $this->getList(true);

		if (count($list) > 0)
		{
			$last = current($list);
		}
		else
		{
			$last = false;
		}

		// Test de la date de création de la dernière sauvegarde




>
>
>
>
>














|

|






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




>
|
>
>










|

|



>
>
>
>
>
>
>
|
>

|
>

>
>
>
>
>
|
>
>

>
>
|
|
|
>




<

|





>
>
|
>
>

>
|
|
<
>
|
>


|
|
<
<
>
|
>
>

>
|
|
|
<
















|

|







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
<?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;
	const NO_APP_ID = 43;

	/**
	 * Renvoie la liste des fichiers SQLite sauvegardés
	 * @param  boolean $auto Si true ne renvoie que la liste des sauvegardes automatiques
	 * @return array 		 Liste des fichiers
	 */
	public function getList(bool $auto_only = false): array
	{
		$ext = $auto_only ? 'auto\.\d+\.sqlite' : 'sqlite';

		$out = [];
		$dir = dir(DATA_ROOT);

		while ($file = $dir->read())
		{
			// Keep only backup files
			if ($file[0] == '.' || !is_file(DATA_ROOT . '/' . $file)
				|| !preg_match('![\w\d._-]+\.' . $ext . '$!i', $file) && $file != basename(DB_FILE)) {
				continue;
			}

			if ($file == basename(DB_FILE)) {
				continue;
			}

			$name = preg_replace('/^association\.(.*)\.sqlite$/', '$1', $file);
			$auto = null;

			if (substr($name, 0, 5) == 'auto.') {
				$auto = (int) substr($name, 5);
				$name = sprintf('Automatique n°%d', $auto);
			}
			elseif (0 === strpos($name, 'pre-upgrade-')) {
				$name = sprintf('Avant mise à jour %s', substr($name, strlen('pre-upgrade-')));
			}
			elseif (preg_match('/^\d{4}-/', $name)) {
				$name = 'Sauvegarde manuelle';
			}
			else {
				$name = str_replace('.sqlite', '', $file);
			}

			// 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,
				'can_restore' => version_compare($version, Upgrade::MIN_REQUIRED_VERSION, '>='),
				'auto'        => $auto,
				'size'        => filesize(DATA_ROOT . '/' . $file),
			];
		}

		$dir->close();

		// Reverse date order
		uasort($out, function ($a, $b) {
			return $a->date > $b->date ? -1 : 1;
		});

		return $out;
	}

	/**
	 * 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);
	}

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

		Utils::safe_unlink($dest);

		if ($version['versionNumber'] >= 3027000) {
			// use VACUUM INTO instead when SQLite 3.27+ is required
			$db->exec(sprintf('VACUUM INTO %s;', $db->quote($dest)));
		}
		else {
			// use ::backup since PHP 7.4.0+
			// https://www.php.net/manual/en/sqlite3.backup.php
			$dest_db = new \SQLite3($dest);

			$db->backup($dest_db);
			$dest_db->exec('PRAGMA journal_mode = DELETE;');
			$dest_db->exec('VACUUM;');
			$db->close();
		}
	}

	/**
	 * Effectue une rotation des sauvegardes automatiques
	 * association.auto.1.sqlite deviendra association.auto.2.sqlite par exemple

	 */
	public function rotate(): void
	{
		$config = Config::getInstance();
		$nb = $config->get('nombre_sauvegardes');

		$list = $this->getList(true);

		// Sort backups from oldest to newest
		usort($list, function ($a, $b) {
			return $a->auto > $b->auto ? -1 : 1;
		});

		// Delete oldest backups + 1 as we are about to create a new one
		$delete = count($list) - ($nb - 1);


		for ($i = 0; $i < $delete; $i++) {
			$backup = array_shift($list);
			$this->remove($backup->filename);
		}

		$i = count($list) + 1;



		// Rotate old backups
		foreach ($list as $file) {
			$old = DATA_ROOT . DIRECTORY_SEPARATOR . $file->filename;
			$new = sprintf('%s/association.auto.%d.sqlite', DATA_ROOT, $i--);

			if ($old !== $new) {
				rename($old, $new);
			}
		}

	}

	/**
	 * Crée une sauvegarde automatique si besoin est
	 * @return boolean true
	 */
	public function auto()
	{
		$config = Config::getInstance();

		// Pas besoin d'aller plus loin si on ne fait pas de sauvegarde auto
		if ($config->get('frequence_sauvegardes') == 0 || $config->get('nombre_sauvegardes') == 0)
			return true;

		$list = $this->getList(true);

		if (count($list))
		{
			$last = current($list)->date;
		}
		else
		{
			$last = false;
		}

		// Test de la date de création de la dernière sauvegarde
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
			throw new UserException('Nom de fichier non valide.');
		}

		return Utils::safe_unlink(DATA_ROOT . '/' . $file);
	}

	/**
	 * Renvoie sur la sortie courante le contenu du fichier de base de données courant
	 * @return boolean true
	 */
	public function dump()
	{


		// Acquire a shared lock before copying



		$db = DB::getInstance();


		$db->exec('BEGIN IMMEDIATE TRANSACTION;');






		$in = fopen(DB_FILE, 'r');


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




        while (!feof($in))





        {

        	fwrite($out, fread($in, 8192));


        }



        fclose($in);

        $db->exec('END TRANSACTION;');





        // Ajout du hash pour vérification intégrité


        fwrite($out, sha1_file(DB_FILE));





        fclose($out);




        return true;


	}

	/**
	 * 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
	 */
	public function restoreFromLocal($file, bool $do_backup = true)
	{
		if (preg_match('!\.\.+!', $file) || !preg_match('!^[\w\d._ -]+$!iu', $file))
		{
			throw new UserException('Nom de fichier non valide.');
		}

		if (!file_exists(DATA_ROOT . '/' . $file))
		{
			throw new UserException('Le fichier fourni n\'existe pas.');
		}

		return $this->restoreDB(DATA_ROOT . '/' . $file, false, false, false);
	}

	/**
	 * Restaure une copie distante (fichier envoyé)
	 * @param  array   $file    Tableau provenant de $_FILES
	 * @param  integer $user_id ID du membre actuellement connecté, utilisé pour 
	 * vérifier qu'il est toujours administrateur dans la sauvegarde







|
<

|

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







|











|







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
			throw new UserException('Nom de fichier non valide.');
		}

		return Utils::safe_unlink(DATA_ROOT . '/' . $file);
	}

	/**
	 * 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);

			$file = $tmp_file;
		}
		else {
			if (preg_match('!\.\.+!', $file) || !preg_match('!^[\w\d._ -]+$!iu', $file)) {
				throw new UserException('Nom de fichier non valide.');
			}

			$name = sprintf('%s - %s', $config->get('nom_asso'), str_replace('association.', '', $file));
			$file = DATA_ROOT . '/' . $file;

			if (!file_exists($file)) {
				throw new UserException('Le fichier fourni n\'existe pas.');
			}
		}

		$hash_length = strlen(sha1(''));

		header('Content-type: application/octet-stream');
		header(sprintf('Content-Disposition: attachment; filename="%s"', $name));
		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
	 */
	public function restoreFromLocal(string $file)
	{
		if (preg_match('!\.\.+!', $file) || !preg_match('!^[\w\d._ -]+$!iu', $file))
		{
			throw new UserException('Nom de fichier non valide.');
		}

		if (!file_exists(DATA_ROOT . '/' . $file))
		{
			throw new UserException('Le fichier fourni n\'existe pas.');
		}

		return $this->restoreDB(DATA_ROOT . '/' . $file, false, false);
	}

	/**
	 * Restaure une copie distante (fichier envoyé)
	 * @param  array   $file    Tableau provenant de $_FILES
	 * @param  integer $user_id ID du membre actuellement connecté, utilisé pour 
	 * vérifier qu'il est toujours administrateur dans la sauvegarde
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

	/**
	 * Restauration de base de données, la fonction qui le fait vraiment
	 * @param  string $file Chemin absolu vers la base de données à utiliser
	 * @return mixed 		true si rien ne va plus, ou self::NEED_UPGRADE si la version de la DB
	 * ne correspond pas à la version de Garradin (mise à jour nécessaire).
	 */
	protected function restoreDB($file, $user_id = false, $check_foreign_keys = false, $do_backup = true)
	{
		$return = 1;

		// Essayons déjà d'ouvrir la base de données à restaurer en lecture
		try {
			$db = new \SQLite3($file, \SQLITE3_OPEN_READONLY);
		}
		catch (\Exception $e)
		{
			throw new UserException('Le fichier fourni n\'est pas une base de données valide. ' .
				'Message d\'erreur de SQLite : ' . $e->getMessage(), self::NOT_A_DB);
		}



		try {
			// Regardons ensuite si la base de données n'est pas corrompue
			$check = $db->querySingle('PRAGMA integrity_check;', false);
		}
		catch (\Exception $e)
		{
			// Ici SQLite peut rejeter un message type "file is encrypted or is not a db"
			throw new UserException('Le fichier fourni n\'est pas une base de données valide. ' .
				'Message d\'erreur de SQLite : ' . $e->getMessage(), self::NOT_A_DB);
		}

		if (strtolower(trim($check)) != 'ok')
		{
			throw new UserException('Le fichier fourni est corrompu. SQLite a trouvé ' . $check . ' erreurs.');
		}

		if ($check_foreign_keys)
		{
			$check = $db->querySingle('PRAGMA foreign_key_check;');

			if ($check)







|












>
>














|







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

	/**
	 * Restauration de base de données, la fonction qui le fait vraiment
	 * @param  string $file Chemin absolu vers la base de données à utiliser
	 * @return mixed 		true si rien ne va plus, ou self::NEED_UPGRADE si la version de la DB
	 * ne correspond pas à la version de Garradin (mise à jour nécessaire).
	 */
	protected function restoreDB($file, $user_id = false, $check_foreign_keys = false)
	{
		$return = 1;

		// Essayons déjà d'ouvrir la base de données à restaurer en lecture
		try {
			$db = new \SQLite3($file, \SQLITE3_OPEN_READONLY);
		}
		catch (\Exception $e)
		{
			throw new UserException('Le fichier fourni n\'est pas une base de données valide. ' .
				'Message d\'erreur de SQLite : ' . $e->getMessage(), self::NOT_A_DB);
		}

		DB::registerCustomFunctions($db);

		try {
			// Regardons ensuite si la base de données n'est pas corrompue
			$check = $db->querySingle('PRAGMA integrity_check;', false);
		}
		catch (\Exception $e)
		{
			// Ici SQLite peut rejeter un message type "file is encrypted or is not a db"
			throw new UserException('Le fichier fourni n\'est pas une base de données valide. ' .
				'Message d\'erreur de SQLite : ' . $e->getMessage(), self::NOT_A_DB);
		}

		if (strtolower(trim($check)) != 'ok')
		{
			throw new UserException('Le fichier fourni est corrompu. Erreur SQLite : ' . $check);
		}

		if ($check_foreign_keys)
		{
			$check = $db->querySingle('PRAGMA foreign_key_check;');

			if ($check)
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

		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, '0.9.8', '<'))
		{
			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 pour les versions récentes
		$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;
			}
		}








|


|




|







>


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







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

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

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

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




			if (!$is_still_admin)
			{
				$return |= self::NOT_AN_ADMIN;
			}
		}

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

		if (!copy($file, DB_FILE))
		{
			rename($backup, DB_FILE);
			throw new \RuntimeException('Unable to copy backup DB to main location.');
		}

		if (!$do_backup) {
			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;
		}







<
|
<





|
|
|







505
506
507
508
509
510
511

512

513
514
515
516
517
518
519
520
521
522
523
524
525
526
527

		if (!copy($file, DB_FILE))
		{
			rename($backup, DB_FILE);
			throw new \RuntimeException('Unable to copy backup DB to main location.');
		}


		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;
		}
429
430
431
432
433
434
435
436
437
438
	/**
	 * 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;');
	}
}







|


548
549
550
551
552
553
554
555
556
557
	/**
	 * 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 [a0a1d5ede0] to [98acb50ff8].

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\Services;

use Garradin\Config;
use Garradin\DB;
use Garradin\Membres\Categories;
use Garradin\Entities\Services\Fee;

use KD2\DB\EntityManager;

class Fees
{
	protected $service_id;

	public function __construct(int $id)
	{
		$this->service_id = $id;
	}

	static public function get(int $id)
	{
		return EntityManager::findOneById(Fee::class, $id);
	}















	/**
	 * If $user_id is specified, then it will return a column 'user_amount' containing the amount that this specific user should pay
	 */
	static public function listAllByService(?int $user_id = null)
	{
		$db = DB::getInstance();






|

>















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







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\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;

	public function __construct(int $id)
	{
		$this->service_id = $id;
	}

	static public function get(int $id)
	{
		return EntityManager::findOneById(Fee::class, $id);
	}

	static public function updateYear(Year $old, Year $new): bool
	{
		$db = DB::getInstance();

		if ($new->id_chart == $old->id_chart) {
			$db->preparedQuery('UPDATE services_fees SET id_year = ? WHERE id_year = ?;', $new->id(), $old->id());
			return true;
		}
		else {
			$db->preparedQuery('UPDATE services_fees SET id_year = NULL, id_account = NULL WHERE id_year = ?;', $old->id());
			return false;
		}
	}

	/**
	 * If $user_id is specified, then it will return a column 'user_amount' containing the amount that this specific user should pay
	 */
	static public function listAllByService(?int $user_id = null)
	{
		$db = DB::getInstance();
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

		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 [c3c5d5e6f2].

1
2
3
4
5
6

7
8
9
10
11
12
13
<?php

namespace Garradin\Services;

use Garradin\Config;
use Garradin\DB;

use Garradin\Plugin;
use Garradin\Utils;
use Garradin\Entities\Services\Reminder;
use KD2\DB\EntityManager;

use const Garradin\WWW_URL;
use const Garradin\ADMIN_URL;






>







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\DynamicList;
use Garradin\Plugin;
use Garradin\Utils;
use Garradin\Entities\Services\Reminder;
use KD2\DB\EntityManager;

use const Garradin\WWW_URL;
use const Garradin\ADMIN_URL;
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
	static public function get(int $id)
	{
		return EntityManager::findOneById(Reminder::class, $id);
	}

	static public function listSentForUser(int $user_id)
	{














		return DB::getInstance()->get('SELECT rs.date AS sent_date, r.delay, s.label, rs.id AS sent_id, s.id AS service_id
			FROM services_reminders_sent rs
			INNER JOIN services_reminders r ON r.id = rs.id_reminder
			INNER JOIN services s ON s.id = rs.id_service

			WHERE rs.id_user = ?;', $user_id);



	}

	static public function listSentForReminder(int $reminder_id)
	{
		return DB::getInstance()->get('SELECT rs.date AS sent_date, r.delay, s.label, rs.id AS sent_id, s.id AS service_id
			FROM services_reminders_sent rs
			INNER JOIN services_reminders r ON r.id = rs.id_reminder
			INNER JOIN services s ON s.id = rs.id_service
			WHERE rs.id_reminder = ?;', $reminder_id);
	}

	static public function listForService(int $service_id)
	{
		return DB::getInstance()->get('SELECT * FROM services_reminders WHERE id_service = ? ORDER BY delay, subject;', $service_id);
	}







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




|
|
|
|







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
	static public function get(int $id)
	{
		return EntityManager::findOneById(Reminder::class, $id);
	}

	static public function listSentForUser(int $user_id)
	{
		$columns = [
			'label' => [
				'label' => 'Activité',
				'select' => 's.label',
			],
			'delay' => [
				'label' => 'Délai du rappel',
				'select' => 'r.delay',
			],
			'date' => [
				'label' => 'Date d\'envoi du message',
				'select' => 'srs.sent_date',
			],
		];

		$tables = 'services_reminders_sent srs
			INNER JOIN services_reminders r ON r.id = srs.id_reminder
			INNER JOIN services s ON s.id = srs.id_service';
		$conditions = sprintf('srs.id_user = %d', $user_id);

		$list = new DynamicList($columns, $tables, $conditions);
		$list->orderBy('date', true);
		return $list;
	}

	static public function listSentForReminder(int $reminder_id)
	{
		return DB::getInstance()->get('SELECT srs.sent_date, r.delay, s.label, rs.id AS sent_id, s.id AS service_id
			FROM services_reminders_sent srs
			INNER JOIN services_reminders r ON r.id = srs.id_reminder
			INNER JOIN services s ON s.id = srs.id_service
			WHERE rs.id_reminder = ?;', $reminder_id);
	}

	static public function listForService(int $service_id)
	{
		return DB::getInstance()->get('SELECT * FROM services_reminders WHERE id_service = ? ORDER BY delay, subject;', $service_id);
	}
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
	/**
	 * Envoi de mail pour rappel automatisé
	 */
	static public function sendAuto(\stdClass $reminder)
	{
		$replace = [
			'identite'        => $reminder->identity,
			'date_rappel'     => Utils::date_fr($reminder->reminder_date),
			'date_expiration' => Utils::date_fr($reminder->expiry_date),
			'nb_jours'        => $reminder->nb_days,
			'delai'           => $reminder->delay,
		];

		$subject = self::replaceTagsInContent($reminder->subject, $replace);
		$text = self::replaceTagsInContent($reminder->body, $replace);

		// Envoi du mail
		Utils::sendEmail(Utils::EMAIL_CONTEXT_PRIVATE, $reminder->email, $subject, $text, $reminder->id_user);

		$db = DB::getInstance();
		$db->insert('services_reminders_sent', [
			'id_service'  => $reminder->id_service,
			'id_user'     => $reminder->id_user,
			'id_reminder' => $reminder->id_reminder,

		]);

		Plugin::fireSignal('rappels.auto', $reminder);

		return true;
	}








|
|















>







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
	/**
	 * Envoi de mail pour rappel automatisé
	 */
	static public function sendAuto(\stdClass $reminder)
	{
		$replace = [
			'identite'        => $reminder->identity,
			'date_rappel'     => Utils::date_fr($reminder->reminder_date, 'd/m/Y'),
			'date_expiration' => Utils::date_fr($reminder->expiry_date, 'd/m/Y'),
			'nb_jours'        => $reminder->nb_days,
			'delai'           => $reminder->delay,
		];

		$subject = self::replaceTagsInContent($reminder->subject, $replace);
		$text = self::replaceTagsInContent($reminder->body, $replace);

		// Envoi du mail
		Utils::sendEmail(Utils::EMAIL_CONTEXT_PRIVATE, $reminder->email, $subject, $text, $reminder->id_user);

		$db = DB::getInstance();
		$db->insert('services_reminders_sent', [
			'id_service'  => $reminder->id_service,
			'id_user'     => $reminder->id_user,
			'id_reminder' => $reminder->id_reminder,
			'due_date'    => $reminder->reminder_date,
		]);

		Plugin::fireSignal('rappels.auto', $reminder);

		return true;
	}

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

		$sql = 'SELECT
			date(su.expiry_date, sr.delay || \' days\') AS reminder_date,
			ABS(julianday(date()) - julianday(expiry_date)) AS nb_days,
			MAX(sr.delay) AS delay, sr.subject, sr.body, s.label, s.description,
			su.expiry_date, sr.id AS id_reminder, su.id_service, su.id_user,
			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;';

		$sql = sprintf($sql, $config->get('champ_identite'));

		foreach ($db->iterate($sql) as $row)
		{
			self::sendAuto($row);
		}

		return true;
	}
}







|
|
>
|



|

|


|
|












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

		$sql = 'SELECT
			date(su.expiry_date, sr.delay || \' days\') AS reminder_date,
			ABS(julianday(date()) - julianday(expiry_date)) AS nb_days,
			MAX(sr.delay) AS delay, sr.subject, sr.body, s.label, s.description,
			su.expiry_date, sr.id AS id_reminder, su.id_service, su.id_user,
			m.email, m.%s AS identity
			FROM services_reminders sr
			INNER JOIN services s ON s.id = sr.id_service
			-- Select latest subscription to a service (MAX) only
			INNER JOIN (SELECT MAX(expiry_date) AS expiry_date, id_user, id_service FROM services_users GROUP BY id_user, id_service) AS su ON s.id = 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 (SELECT id, MAX(due_date) AS due_date, id_user, id_reminder FROM services_reminders_sent GROUP BY id_user, id_reminder) AS srs ON su.id_user = srs.id_user AND srs.id_reminder = sr.id
			WHERE
				date() > date(su.expiry_date, sr.delay || \' days\')
				AND (srs.id IS NULL OR srs.due_date < date(su.expiry_date, (sr.delay - 1) || \' days\'))
			GROUP BY su.id_user, sr.id_service
			ORDER BY su.id_user;';

		$sql = sprintf($sql, $config->get('champ_identite'));

		foreach ($db->iterate($sql) as $row)
		{
			self::sendAuto($row);
		}

		return true;
	}
}

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 [00efdbaaf6].

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

namespace Garradin;

use Garradin\Entities\Web\Page;

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 = '';
        $type = null;

        // Types de boucles natifs
        if ($loopType == 'articles' || $loopType == 'rubriques' || $loopType == 'pages')
        {
            $type = Page::class;
            $order = null;
            $limit = $begin = 0;

            $select = 'w.*, strftime(\'%s\', w.modified) AS date_modification, strftime(\'%s\', f.created) AS date_creation';
            $tables = 'web_pages w
                INNER JOIN files f USING (id)
                INNER JOIN files_search s USING (id)';

            $where = sprintf(' AND w.status = %d', Page::STATUS_ONLINE);

            if ($loopType == 'articles') {
                $where .= sprintf(' AND w.type = %d', Page::TYPE_PAGE);
            }
            elseif ($loopType == 'rubriques') {
                $where .= sprintf(' AND w.type = %d ', Page::TYPE_CATEGORY);
            }

            $allowed_fields = [
                'id'                => 'w.id',
                'uri'               => 'w.uri',
                'titre'             => 'w.title',
                'date'              => 'f.created',
                'date_creation'     => 'f.created',
                'date_modification' => 'w.modified',
                'parent'            => 'w.parent_id',
                'rubrique'          => 'w.parent_id',
                'points'            => 'points',
                'recherche'         => 'search',
                'texte'             => 's.content',
                'age'               => 'age'
            ];

            $search = $search_rank = false;

            foreach ($loopCriterias as $criteria_id => $criteria)
            {
                if (isset($criteria['field']))
                {
                    if (!array_key_exists($criteria['field'], $allowed_fields)) {
                        throw new \KD2\MiniSkelMarkupException("Critère '".$criteria['field']."' invalide pour la boucle ".$loopName." de type ".$loopType.".");
                    }

                    $criteria['field'] = $allowed_fields[$criteria['field']];

                    if ($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(f.created)';
                        $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'] == 'search') {
                            $where .= ' AND s MATCH ?';
                            $select .= ', rank(matchinfo(s), 0, 1.0, 1.0) AS points';
                            $search = true;
                        }
                        else
                        {
                            $where .= ' AND '.$criteria['field'].' = ?';

                            if ($criteria['field'] == 'w.parent_id')
                            {
                                $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 = $p->asArray(); $row[\'url\'] = $p->url(); ';
            }

            if (!$limit || $limit > 100) {
                $limit = 100;
            }

            if ($limit)
            {
                if (is_numeric($begin)) {
                    $begin = (int) $begin;
                }
                else {
                    $begin = '?';
                    $query_args[] = ['\'.$this->variables[\'debut_liste\'].\''];
                }
            }

            $query = sprintf('SELECT %s FROM %s WHERE 1 %s ORDER BY %s LIMIT %s, %d;', $select, $tables, $where, $order ?: 'w.id', $begin, $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, sprintf('$e = new %s; $e->import($row); ', $class::class));
        $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;
    }
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted src/include/lib/Garradin/Squelette_Filtres.php version [5060d03e4b].

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
<?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)
    {
        return Utils::relative_date($date, $avec_heure);
    }

    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 [3345559a9c] to [a0f2c0f166].

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?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;
use Garradin\Files\Files;

class Template extends \KD2\Smartyer
{
	static protected $_instance = null;

	static public function getInstance()
	{
		return self::$_instance ?: self::$_instance = new Template;
	}

	public function display($template = null)
	{
		if (isset($_GET['_pdf'])) {
			$out = $this->fetch($template);

			$filename = 'Print';

			if (preg_match('!<title>(.*)</title>!U', $out, $match)) {
				$filename = trim($match[1]);
			}

			header('Content-type: application/pdf');
			header(sprintf('Content-Disposition: attachment; filename="%s.pdf"', Utils::safeFileName($filename)));
			Utils::streamPDF($out);
			return $this;
		}

		return parent::display($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
140

		$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('relative_date', [Utils::class, 'relative_date']);

		$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']);
	}

	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())
		{
			return '';
		}

		$errors = $form->getErrorMessages(!empty($params['membre']) ? true : false);
		$errors = array_map([$this, 'escape'], $errors);



		$errors = array_map('nl2br', $errors);











		return '<div class="block error"><ul><li>' . implode('</li><li>', $errors) . '</li></ul></div>';
	}

	protected function showError($params)
	{
		if (!$params['if'])







>
>
>
>
>
>
>






>




|
<
















|
<
<
<
<
|
<
|


|
|
|

<
<
<
<
<
|
<
>
|

<
<
<
|
<
<
|

<
<











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







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

		$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) {




			$skriv = new Skriv;

			return $skriv->render((string) $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())
		{
			return '';
		}

		$errors = $form->getErrorMessages(!empty($params['membre']) ? true : false);

		foreach ($errors as &$error) {
			if ($error instanceof UserException) {
				$message = nl2br($this->escape($error->getMessage()));

				if ($error->hasDetails()) {
					$message = '<h3>' . $message . '</h3>' . $error->getDetailsHTML();
				}

				$error = $message;
			}
			else {
				$error = nl2br($this->escape($error));
			}
		}

		return '<div class="block error"><ul><li>' . implode('</li><li>', $errors) . '</li></ul></div>';
	}

	protected function showError($params)
	{
		if (!$params['if'])
206
207
208
209
210
211
212


























213
214
215
216
217
218
219
			$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 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));







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







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
			$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));
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
		$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;







|







292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
		$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;
260
261
262
263
264
265
266

267
268
269
270
271
272
273
274
		}
		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') {







>
|







314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
		}
		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') {
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

	protected function customColors()
	{
		$config = Config::getInstance();

		$couleur1 = $config->get('couleur1') ?: ADMIN_COLOR1;
		$couleur2 = $config->get('couleur2') ?: ADMIN_COLOR2;
		$image_fond = ADMIN_BACKGROUND_IMAGE;

		if ($f = $config->get('image_fond')) {
			$image_fond = $f->url();
		}

		// 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);
		}







|

|
|















>
>
>
>
|







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

	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')) && ($file = Files::get($f))) {
			$admin_background = $file->url() . '?' . $file->modified->getTimestamp();
		}

		// 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>';

		if (($f = $config->get('admin_css')) && ($file = Files::get($f))) {
			$out .= "\n" . sprintf('<link rel="stylesheet" type="text/css" href="%s" />', $file->url() . '?' . $file->modified->getTimestamp());
		}

		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);
		}
543
544
545
546
547
548
549


550
551
552
553
554
555
556
557
			case 'tel':
				return '<a href="tel:' . rawurlencode($v) . '">' . htmlspecialchars($v) . '</a>';
			case 'url':
				return '<a href="' . htmlspecialchars($v) . '">' . htmlspecialchars($v) . '</a>';
			case 'country':
				return Utils::getCountryName($v);
			case 'date':


				return Utils::date_fr($v);
			case 'multiple':
				// Useful for search results, if a value is not a number
				if (!is_numeric($v)) {
					return htmlspecialchars($v);
				}

				$out = [];







>
>
|







602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
			case 'tel':
				return '<a href="tel:' . rawurlencode($v) . '">' . htmlspecialchars($v) . '</a>';
			case 'url':
				return '<a href="' . htmlspecialchars($v) . '">' . htmlspecialchars($v) . '</a>';
			case 'country':
				return Utils::getCountryName($v);
			case 'date':
				return Utils::date_fr($v, 'd/m/Y');
			case 'datetime':
				return Utils::date_fr($v, 'd/m/Y à H:i');
			case 'multiple':
				// Useful for search results, if a value is not a number
				if (!is_numeric($v)) {
					return htmlspecialchars($v);
				}

				$out = [];
576
577
578
579
580
581
582





583
584
585
586
587
588
589
		$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))
			{







>
>
>
>
>







637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
		$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))
			{
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
		}

		if (!empty($params['disabled']))
		{
			$attributes .= 'disabled="disabled" ';
		}

		if (!empty($config->mandatory))
		{
			$attributes .= 'required="required" ';
		}

		// Fix for autocomplete, lpignore is for Lastpass
		$attributes .= 'autocomplete="off" data-lpignore="true" ';








|







680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
		}

		if (!empty($params['disabled']))
		{
			$attributes .= 'disabled="disabled" ';
		}

		if (!empty($config->mandatory) && $type != 'checkbox' && $type != 'multiple')
		{
			$attributes .= 'required="required" ';
		}

		// Fix for autocomplete, lpignore is for Lastpass
		$attributes .= 'autocomplete="off" data-lpignore="true" ';

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







|

<
<
|
<
<

<
<
<
<
<
|
<

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





881
882
883
884
885
886
887
888
889


890


891





892

893



894


895

896

897






















































































898
899
900
901
902
			$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 [9d09637b06] to [a3d7e4ed57].

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\Membres\Session;




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

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

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

		if (!$v || version_compare($v, self::MIN_REQUIRED_VERSION, '<'))





>
>
>



|



|







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



















				. 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();

		$user_is_logged = $session->isLogged(true);
		return true;
	}

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

		$session = Session::getInstance();
		$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.1.0', '<='))








































			{
				// Missing trigger
				$db->beginSchemaUpdate();
				$db->createFunction('sha1', 'sha1');













































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














				$db->commitSchemaUpdate();








































































































































			}

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




			Utils::clearCaches();







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






			Static_Cache::remove('upgrade');

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

			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();
		}
	}
}


























>
|





|
|
<
<



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



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

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

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





>
>
>
|
>
>

>
>
>
>
|
>
>
>
>
>

















>
>
>
>






|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
				. 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(true);
		$session->isLogged(true);
		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-rc1', '<'))
			{
				$db->beginSchemaUpdate();
				$db->import(ROOT . '/include/data/1.0.0_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();
			}

			if (version_compare($v, '1.0.3', '<'))
			{
				// Missing trigger
				$db->begin();
				$db->import(ROOT . '/include/data/1.0.3_migration.sql');
				$db->commit();
			}

			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.0.7', '<'))
			{
				// Missing trigger
				$db->begin();
				$db->import(ROOT . '/include/data/1.0.7_migration.sql');
				$db->commit();
			}

			if (version_compare($v, '1.1.0-beta1', '<'))
			{
				// Missing trigger
				$db->beginSchemaUpdate();

				$attachments = $db->getAssoc('SELECT f.id, w.uri || \'/\' || f.id || \'_\' || f.nom FROM fichiers f
					INNER JOIN fichiers_wiki_pages fw ON fw.fichier = f.id
					INNER JOIN wiki_pages w ON w.id = fw.id;');

				// Update Skriv content for attachments
				foreach ($db->iterate('SELECT r.rowid, r.contenu, p.uri FROM wiki_revisions r INNER JOIN wiki_pages p ON p.revision = r.revision AND p.id = r.id_page;') as $r) {
					$uri = $r->uri;
					$content = preg_replace_callback('!<<(image|fichier)\s*\|\s*(\d+)\s*(?:\|\s*(gauche|droite|centre))?\s*(?:\|\s*(.+)\s*)?>>!', function ($match) use ($attachments, $uri) {
						if (isset($attachments[$match[2]])) {
							$name = $attachments[$match[2]];

							if (dirname($name) == $uri) {
								$name = basename($name);
							}
							else {
								$name = '../' . $name;
							}
						}
						else {
							$name = '_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();
				}
			}

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

				if ($bg) {
					$file = Files::get($bg);

					if (!$file) {
						$db->exec('UPDATE config SET value = NULL WHERE key = \'admin_background\';');
					}
				}

				// Fix links of admin homepage
				$homepage = $db->firstColumn('SELECT value FROM config WHERE key = \'admin_homepage\';');

				if ($homepage) {
					$file = Files::get($homepage);

					if ($file) {
						$content = $file->fetch();
						$new_content = preg_replace_callback(';\[\[((?!\]\]).*)\]\];', function ($match) {
							$link = explode('|', $match[1]);
							if (count($link) == 2) {
								list($label, $link) = $link;
							}
							else {
								$label = $link = $link[0];
							}

							if (strpos(trim($link), '/') !== false) {
								return $match[0];
							}

							$link = sprintf('!web/page.php?p=%s', trim($link));
							return sprintf('[[%s|%s]]', $label, $link);
						}, $content);

						if ($new_content != $content) {
							Files::disableQuota();
							$file->setContent($new_content);
						}
					}
				}
			}

			if (version_compare($v, '1.1.3', '<')) {
				// Missing trigger
				$db->begin();
				$db->import(ROOT . '/include/data/1.1.3_migration.sql');
				$db->commit();
			}

			if (version_compare($v, '1.1.4', '<')) {
				// Set config file names
				$config = Config::getInstance();

				$file = Files::get(Config::DEFAULT_FILES['admin_background']);
				$config->set('admin_background', $file ? Config::DEFAULT_FILES['admin_background'] : null);

				$file = Files::get(Config::DEFAULT_FILES['admin_homepage']);
				$config->set('admin_homepage', $file ? Config::DEFAULT_FILES['admin_homepage'] : null);

				$config->save();
			}

			if (version_compare($v, '1.1.7', '<')) {
				$db->begin();
				$db->import(ROOT . '/include/data/1.1.7_migration.sql');
				$db->commit();
			}

			if (version_compare($v, '1.1.8', '<')) {
				$db->begin();
				// Force sync to remove pages that don't exist anymore
				\Garradin\Web\Web::sync();

				$uris = [];
				$i = 1;

				$treat_duplicate_uris = function ($path) use (&$i, &$uris, &$treat_duplicate_uris) {
					// Rename duplicate URIs
					foreach (Files::callStorage('list', $path) as $f) {
						if ($f->type != $f::TYPE_DIRECTORY) {
							continue;
						}

						if (array_key_exists($f->name, $uris)) {
							$f->changeFileName($f->name . '_' . $i++);
						}

						$uris[$f->name] = $f->path;

						$treat_duplicate_uris($f->path);
					}
				};

				$treat_duplicate_uris(\Garradin\Entities\Files\File::CONTEXT_WEB);

				// Force sync to add renamed pages
				\Garradin\Web\Web::sync();

				// Add UNIQUE index
				$db->import(ROOT . '/include/data/1.1.8_migration.sql');

				$db->commit();
			}

			if (version_compare($v, '1.1.8', '==')) {
				// Force sync to add missing pages if you had the buggy 1.1.8 version
				\Garradin\Web\Web::sync(true);
			}

			if (version_compare($v, '1.1.10', '<')) {
				\Garradin\Web\Web::sync(true); // Force sync of web pages
				Files::syncVirtualTable('', true);

				$db->begin();
				$db->exec(sprintf('DELETE FROM files_search WHERE path NOT IN (SELECT path FROM %s);', Files::getVirtualTableName()));
				$db->commit();
			}

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

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

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

Deleted src/include/lib/Garradin/UserTemplate.php version [268e721def].

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

namespace Garradin;

use KD2\Brindille;
use KD2\Brindille_Exception;

use Garradin\Files\Files;
use Garradin\Files\Folders;
use Garradin\Web\Template;
use Garradin\Entities\Web\Page;
use Garradin\Entities\Files\File;
use Garradin\UserTemplate\Modifiers;

class UserTemplate extends Brindille
{
	protected $path;
	protected $hash;
	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', 'champs_membres', '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();
		$image_fond = $config->get('image_fond') ? $config->get('image_fond')->url() : null;

		$config = array_intersect_key($config->asArray(), array_flip($keys)) + ['image_fond' => $image_fond];

		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->hash = sha1(DATA_ROOT . $file->id);
			$this->modified = $file->modified;
		}

		$this->assignArray(self::getRootVariables());

		$this->registerDefaults();

		foreach (Modifiers::DEFAULTS as $name => $callback) {
			$this->registerModifier($name, $callback);
		}

		$params = [
			'template' => $this,
		];

		Plugin::fireSignal('usertemplate.init', $params);

		$this->registerSection('pages', [$this, 'sectionPages']);
		$this->registerSection('articles', [$this, 'sectionArticles']);
		$this->registerSection('categories', [$this, 'sectionCategories']);

		$this->registerSection('files', [$this, 'sectionFiles']);
		$this->registerSection('documents', [$this, 'sectionDocuments']);
		$this->registerSection('images', [$this, 'sectionImages']);

		$this->registerFunction('http', [$this, 'functionHTTP']);
		$this->registerFunction('include', [$this, 'functionInclude']);

	}

	public function setSource(string $path)
	{
		$this->path = $path;
		$this->hash = sha1($path);
		$this->modified = filemtime($path);
	}

	public function display(): void
	{
		$compiled_path = CACHE_ROOT . '/compiled/s_' . $this->hash . '.php';

		if (file_exists($compiled_path) && filemtime($compiled_path) >= $this->modified) {
			require $compiled_path;
			return;
		}

		$tmp_path = $compiled_path . '.tmp';

		try {
			$code = $this->compile($this->file ? $this->file->fetch() : file_get_contents($this->path));
			file_put_contents($tmp_path, $code);

			require $tmp_path;
		}
		catch (Brindille_Exception $e) {
			@unlink($tmp_path);
			throw new Brindille_Exception('Erreur de syntaxe : ' . $e->getMessage(), 0, $e);
		}
		catch (\Throwable $e) {
			// Don't delete temporary file as it can be used to debug
			throw $e;
		}

		if (!file_exists(dirname($compiled_path))) {
			Utils::safe_mkdir(dirname($compiled_path), 0777, true);
		}

		rename($tmp_path, $compiled_path);
	}

	public function fetch(): string
	{
		ob_start();
		$this->display();
		return ob_get_clean();
	}

	public function functionInclude(array $params, UserTemplate $ut, int $line): string
	{
		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']));
		}

		$tpl = new Template($params['file']);

		if (!$tpl->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']]);

		return $tpl->fetch($params);
	}

	public function functionHTTP(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');
		}
	}

	public function sectionCategories(array $params, self $tpl, int $line): \Generator
	{
		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
		}

		$params['where'] .= ' AND w.type = ' . Page::TYPE_CATEGORY;
		return $this->sectionPages($params, $tpl, $line);
	}

	public function sectionArticles(array $params, self $tpl, int $line): \Generator
	{
		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
		}

		$params['where'] .= ' AND w.type = ' . Page::TYPE_PAGE;
		return $this->sectionPages($params, $tpl, $line);
	}

	public function sectionPages(array $params, self $tpl, int $line): \Generator
	{
		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
		}

		$params['select'] = 'w.*';
		$params['tables'] = 'web_pages w INNER JOIN files f USING (id)';

		if (isset($params['search'])) {
			$params['tables'] .= ' INNER JOIN files_search s USING (id)';
			$params['select'] .= ', rank(matchinfo(s), 0, 1.0, 1.0) AS points';
			$params['where'] .= ' AND s MATCH :search';

			if (!isset($params['order'])) {
				$params['order'] = 'points DESC';
			}

			$params[':search'] = $params['search'];
			unset($params['search']);
		}

		if (isset($params['uri'])) {
			$params['where'] .= ' AND w.uri = :uri';
			$params['limit'] = 1;
			$params[':uri'] = $params['uri'];
			unset($params['uri']);
		}

		if (isset($params['parent'])) {
			$params['where'] .= ' AND w.parent_id = :parent_id';
			$params[':parent_id'] = $params['parent'];
			unset($params['parent']);
		}

		foreach ($this->sectionSQL($params, $tpl, $line) as $row) {
			$data = $row;
			unset($data['points']);

			$page = new Page;
			$page->load($data);
			$row = array_merge($row, $page->asArray());
			$row['url'] = $page->url();
			$row['raw'] = $page->raw();
			$row['html'] = $page->render();

			yield $row;
		}
	}

	public function sectionImages(array $params, self $tpl, int $line): \Generator
	{
		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
		}

		$params['where'] .= ' AND f.image = 1';
		return $this->sectionFiles($params, $tpl, $line);
	}

	public function sectionDocuments(array $params, self $tpl, int $line): \Generator
	{
		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
		}

		$params['where'] .= ' AND f.image = 0';
		return $this->sectionFiles($params, $tpl, $line);
	}

	public function sectionFiles(array $params, self $tpl, int $line): \Generator
	{
		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
		}

		$params['select'] = 'f.*';
		$params['tables'] = 'files f';
		$params['where'] .= ' AND f.public = 1';

		if (isset($params['except_in_text'])) {
			$found = Page::findTaggedAttachments($params['except_in_text']);
			$found = array_map('intval', $found);
			$params['where'] .= sprintf(' AND f.id NOT IN (%s)', implode(', ', $found));
		}

		if (isset($params['parent'])) {
			$params['tables'] .= ' INNER JOIN files_links l ON l.id = f.id';
			$params['where'] .= ' AND l.file_id = :parent_id';
			$params[':parent_id'] = $params['parent'];
			unset($params['parent']);
		}

		foreach ($this->sectionSQL($params, $tpl, $line) as $row) {
			$file = new File;
			$file->load($row);
			$row = $file->asArray();
			$row['url'] = $file->url();
			$row['thumb_url'] = $file->image ? $file->thumb_url() : null;

			yield $row;
		}
	}

	public function sectionSQL(array $params, self $tpl, int $line): \Generator
	{
		static $defaults = [
			'select' => '*',
			'order' => '1',
			'begin' => 0,
			'limit' => 1000,
			'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;
			}
		}

		$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']
		);

		try {
			$db = DB::getInstance();
			$statement = $db->protectSelect(null, $sql);

			if (!empty($params['debug'])) {
				echo sprintf('<pre style="padding: 5px; background: yellow;">%s</pre>', htmlspecialchars($statement->getSQL(true)));
			}

			$args = [];

			foreach ($params as $key => $value) {
				if (substr($key, 0, 1) == ':') {
					$args[$key] = $value;
				}
			}

			unset($params, $sql);

			foreach ($args as $key => $value) {
				var_dump($key, $value);
				$statement->bindValue($key, $value, $db->getArgType($value));
			}

			$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/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 [a04e0ffc06].























































































































































































































































































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

namespace Garradin\UserTemplate;

use KD2\Brindille;
use KD2\Brindille_Exception;
use KD2\ErrorManager;

use Garradin\Utils;
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'])) {
			Utils::redirect($params['redirect']);
		}
		elseif (isset($params['type'])) {
			header('Content-Type: ' . $params['type'], true);
		}
		else {
			throw new Brindille_Exception('No valid parameter found for http function');
		}
	}
}

Modified src/include/lib/Garradin/UserTemplate/Modifiers.php from [6da9a83f05] to [98d18e40cb].

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\UserTemplate;

use Garradin\Utils;

class Modifiers
{
	const DEFAULTS = [























		'relative_date' => [Utils::class, 'relative_date'],

		'truncate' => [self::class, 'truncate'],






	];











	/**
	 * 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)
	{
		// 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;
			}
		}



		return trim($str) . $placeholder;
	}
}












































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

>
>
>
>
>
>
>
>
>
>










|




















|
>
|
>


|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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, DATE_ATOM);
	}

	static public function xml_escape($str)
	{
		return htmlspecialchars($str, ENT_XML1 | ENT_QUOTES);
	}
}

Added src/include/lib/Garradin/UserTemplate/Sections.php version [b168f12ea3].



















































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?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 . Utils::basename($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';
		}

		if (!empty($params['where']) && !preg_match('/^\s*AND\s+/i', $params['where'])) {
			$params['where'] = ' AND ' . $params['where'];
		}

		$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 [008bd1b9aa].



































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?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,
			'request_url'  => Utils::getRequestURI(),
			'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 (!is_dir(dirname($compiled_path))) {
			// Force cache directory mkdir
			Utils::safe_mkdir(dirname($compiled_path), 0777, true);
		}

		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();
	}

	public function displayPDF(?string $filename = null): void
	{
		header('Content-type: application/pdf');

		if ($filename) {
			header(sprintf('Content-Disposition: attachment; filename="%s"', Utils::safeFileName($filename)));
		}

		Utils::streamPDF($this->fetch());
	}
}

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 [af79830207] to [2a526310a9].

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

class Utils
{
    const EMAIL_CONTEXT_BULK = 'bulk';
    const EMAIL_CONTEXT_PRIVATE = 'private';
    const EMAIL_CONTEXT_SYSTEM = 'system';




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

class Utils
{
    const EMAIL_CONTEXT_BULK = 'bulk';
    const EMAIL_CONTEXT_PRIVATE = 'private';
    const EMAIL_CONTEXT_SYSTEM = 'system';

    static protected $collator;
    static protected $transliterator;

    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',
        'Jan' => 'jan',
        'Feb' => 'fév',

        'Mar' => 'mar',
        'Apr' => 'avr',
        'Jun' => 'juin',
        'Jul' => 'juil',
        'Aug' => 'août',
        'Sep' => 'sep',
        'Oct' => 'oct',
        'Nov' => 'nov',
        '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);
        }
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
        if (null === $ts) {
            return $ts;
        }

        $date = strftime($format, $ts->getTimestamp());

        $date = strtr($date, self::FRENCH_DATE_NAMES);
        $date = strtolower($date);
        return $date;
    }

    static public function date_fr($ts, $format = null)
    {
        $ts = self::get_datetime($ts);

        if (null === $ts) {
            return $ts;
        }

        if (is_null($format))
        {
            $format = 'd/m/Y à H:i';
        }

        $date = $ts->format($format);

        $date = strtr($date, self::FRENCH_DATE_NAMES);
        $date = strtolower($date);
        return $date;
    }

    static public function relative_date($ts, bool $with_hour = false): string
    {
        $day = null;

        if (null === $ts) {
            return '';
        }

        $date = self::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(self::strftime_fr($date, '%A %e %B'));
        }
        else
        {
            $day = strtolower(self::strftime_fr($date, '%e %B %Y'));
        }

        if ($with_hour)
        {
            $hour = $date->format('H\hi');
            return sprintf('%s, %s', $day, $hour);
        }

        return $day;
    }

    /**
     * @deprecated
     */
    static public function checkDate($str)
    {
        if (!preg_match('!^(\d{4})-(\d{2})-(\d{2})$!', $str, $match))
            return false;







<



















<



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







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
        if (null === $ts) {
            return $ts;
        }

        $date = strftime($format, $ts->getTimestamp());

        $date = strtr($date, self::FRENCH_DATE_NAMES);

        return $date;
    }

    static public function date_fr($ts, $format = null)
    {
        $ts = self::get_datetime($ts);

        if (null === $ts) {
            return $ts;
        }

        if (is_null($format))
        {
            $format = 'd/m/Y à H:i';
        }

        $date = $ts->format($format);

        $date = strtr($date, self::FRENCH_DATE_NAMES);

        return $date;
    }









































    /**
     * @deprecated
     */
    static public function checkDate($str)
    {
        if (!preg_match('!^(\d{4})-(\d{2})-(\d{2})$!', $str, $match))
            return false;
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
        $number = abs((int) $number);

        $decimals = substr('0' . $number, -2);
        $number = (int) substr($number, 0, -2);

        return sprintf('%s%s%s%s', $sign, number_format($number, 0, $dec_point, $thousands_sep), $dec_point, $decimals);
    }
























    static public function getRequestURI()
    {
        if (!empty($_SERVER['REQUEST_URI']))
            return $_SERVER['REQUEST_URI'];
        else
            return false;
    }

    static public function getSelfURL($qs = true)
    {
        $uri = self::getRequestUri();


        if (strpos($uri, WWW_URI) === 0)
        {
            $uri = substr($uri, strlen(WWW_URI));
        }








        if ($qs !== true && (strpos($uri, '?') !== false))
        {
            $uri = substr($uri, 0, strpos($uri, '?'));
        }

        if (is_array($qs))
        {
            $uri .= '?' . http_build_query($qs);
        }

        return str_replace('/admin', '', ADMIN_URL) . $uri;
    }

    static public function getSelfURI($qs = true)
    {
        return str_replace(substr(WWW_URL, 0, -1), '', self::getSelfURL($qs));
    }

    static public function getModifiedURL(string $new)
    {
        return HTTP::mergeURLs(self::getSelfURL(), $new);
    }

    public static function redirect($destination=false, $exit=true)
    {
        if (empty($destination) || !preg_match('/^https?:\/\//', $destination))
        {





            if (empty($destination))
                $destination = WWW_URL;


            else


                $destination = WWW_URL . preg_replace('/^\//', '', $destination);



        }












        if (PHP_SAPI == 'cli') {
            echo 'Please visit ' . $destination . PHP_EOL;
            exit;
        }

        if (headers_sent())







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











|

>
|

|


>
>
>
>
>
>
>










<
<
|
<
<
<







|

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







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
        $number = abs((int) $number);

        $decimals = substr('0' . $number, -2);
        $number = (int) substr($number, 0, -2);

        return sprintf('%s%s%s%s', $sign, number_format($number, 0, $dec_point, $thousands_sep), $dec_point, $decimals);
    }

    static public function getLocalURL(string $url = '', ?string $default_prefix = null): string
    {
        if ($url[0] == '!') {
            return ADMIN_URL . substr($url, 1);
        }
        elseif ($url[0] == '/' && ($pos = strpos($url, WWW_URI)) === 0) {
            return WWW_URL . substr($url, strlen(WWW_URI));
        }
        elseif (substr($url, 0, 5) == 'http:' || substr($url, 0, 6) == 'https:') {
            return $url;
        }
        elseif ($url == '') {
            return ADMIN_URL;
        }
        else {
            if (null !== $default_prefix) {
                $default_prefix = self::getLocalURL($default_prefix);
            }

            return $default_prefix . $url;
        }
    }

    static public function getRequestURI()
    {
        if (!empty($_SERVER['REQUEST_URI']))
            return $_SERVER['REQUEST_URI'];
        else
            return false;
    }

    static public function getSelfURL($qs = true)
    {
        $uri = self::getSelfURI($qs);

        // Make absolute URI relative to parent URI
        if (strpos($uri, WWW_URI . 'admin/') === 0)
        {
            $uri = substr($uri, strlen(WWW_URI . 'admin/'));
        }

        return ADMIN_URL . $uri;
    }

    static public function getSelfURI($qs = true)
    {
        $uri = self::getRequestURI();

        if ($qs !== true && (strpos($uri, '?') !== false))
        {
            $uri = substr($uri, 0, strpos($uri, '?'));
        }

        if (is_array($qs))
        {
            $uri .= '?' . http_build_query($qs);
        }



        return $uri;



    }

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

        if (headers_sent())
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

        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







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







327
328
329
330
331
332
333








































































334
335
336
337
338
339
340

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








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







366
367
368
369
370
371
372
























373
374
375
376
377
378
379
        $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;
        }

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







|
>
>
>
>
>
|
>
>
>
|

>




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












|

|




|







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







|










>
>
|
>
>







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
            }
            $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
    {
892
893
894
895
896
897
898
899













































































































































































































        $str = preg_replace('![^\w\d_-]!i', '-', $str);
        $str = preg_replace('!-{2,}!', '-', $str);
        $str = trim($str, '-');

        return $str;
    }
}



















































































































































































































|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103

        $str = preg_replace('![^\w\d_-]!i', '-', $str);
        $str = preg_replace('!-{2,}!', '-', $str);
        $str = trim($str, '-');

        return $str;
    }

    static public function safeFileName(string $str): string
    {
        $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');

            // This is what makes the comparison case insensitive
            // https://www.php.net/manual/en/collator.setstrength.php
            self::$collator->setAttribute(\Collator::STRENGTH, \Collator::SECONDARY);

            // Don't use \Collator::NUMERIC_COLLATION here as it goes against what would feel logic
            // with NUMERIC_COLLATION: 1, 2, 10, 11, 101
            // without: 1, 10, 101, 11, 2
        }

        if (isset(self::$collator)) {
            return (int) self::$collator->compare($a, $b);
        }

        $a = strtoupper(self::transliterateToAscii($a));
        $b = strtoupper(self::transliterateToAscii($b));

        return strcmp($a, $b);
    }

    /**
     * Transforms a unicode string to lowercase AND removes all diacritics
     *
     * @see https://www.matthecat.com/supprimer-les-accents-d-une-chaine-avec-php.html
     */
    static public function unicodeCaseFold(?string $str): string
    {
        if (null === $str || trim($str) === '') {
            return '';
        }

        if (!isset(self::$transliterator) && function_exists('transliterator_create')) {
            self::$transliterator = \Transliterator::create('Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC; Lower();');
        }

        if (isset(self::$transliterator)) {
            return self::$transliterator->transliterate($str);
        }

        return strtoupper(self::transliterateToAscii($str));
    }

    static public function knatcasesort(array $array)
    {
        uksort($array, [self::class, 'unicodeCaseComparison']);
        return $array;
    }

    /**
     * Displays a PDF from a string, only works when PDF_COMMAND constant is set to "prince"
     * @param  string $str HTML string
     * @return void
     */
    static public function streamPDF(string $str): void
    {
        if (!PDF_COMMAND) {
            // Try to see if there's a plugin
            $in = ['string' => $str];

            if (Plugin::fireSignal('pdf.stream', $in)) {
                return;
            }

            unset($in);
        }

        // Only Prince handles using STDIN and STDOUT
        if (PDF_COMMAND != 'prince') {
            $file = self::filePDF($str);
            readfile($file);
            unlink($file);
            return;
        }

        $descriptorspec = [
            0 => ["pipe", "r"], // stdin is a pipe that the child will read from
            1 => ["pipe", "w"], // stdout is a pipe that the child will write to
            2 => ['pipe', 'w'], // stderr
        ];

        $cmd = 'prince -o - -';
        $process = proc_open($cmd, $descriptorspec, $pipes);

        if (!is_resource($process)) {
            throw new \RuntimeException('Cannot execute Prince XML');
        }

        // $pipes now looks like this:
        // 0 => writeable handle connected to child stdin
        // 1 => readable handle connected to child stdout

        fwrite($pipes[0], $str);
        fclose($pipes[0]);

        echo stream_get_contents($pipes[1]);
        fclose($pipes[1]);

        // It is important that you close any pipes before calling
        // proc_close in order to avoid a deadlock
        proc_close($process);
    }

    /**
     * Creates a PDF file from a HTML string
     * @param  string $str HTML string
     * @return string File path of the PDF file (temporary), you must delete or move it
     */
    static public function filePDF(string $str): ?string
    {
        $source = sprintf('%s/print-%s.html', CACHE_ROOT, md5(random_bytes(16)));
        $target = str_replace('.html', '.pdf', $source);

        file_put_contents($source, $str);

        $cmd = PDF_COMMAND;

        if (!$cmd) {
            // Try to see if there's a plugin
            $in = ['source' => $source, 'target' => $target];

            if (Plugin::fireSignal('pdf.create', $in)) {
                return $target;
            }

            unset($in);

            // Try to find a local executable
            $list = ['prince', 'chromium', 'wkhtmltopdf', 'weasyprint'];

            foreach ($list as $program) {
                if (shell_exec('which ' . $program)) {
                    $cmd = $program;
                    break;
                }
            }

            // We still haven't found anything
            if (!$cmd) {
                throw new \LogicException('No PDF creation executable found. Please install or configure one.');
            }
        }

        switch ($cmd) {
            case 'prince':
                $cmd = 'prince -o %2$s %1$s';
                break;
            case 'chromium':
                $cmd = 'chromium --headless --disable-gpu --run-all-compositor-stages-before-draw --print-to-pdf-no-header --print-to-pdf=%s %s';
                break;
            case 'wkhtmltopdf':
                $cmd = 'wkhtmltopdf %1$s %2$s';
                break;
            case 'weasyprint':
                $cmd = 'weasyprint %1$s %2$s';
                break;
            default:
                break;
        }

        exec(sprintf($cmd, escapeshellarg($source), escapeshellarg($target)));

        if (!file_exists($target)) {
            throw new \RuntimeException('PDF command failed');
        }

        unlink($source);

        return $target;
    }
}

Deleted src/include/lib/Garradin/Web.php version [c77e0de6ee].

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

namespace Garradin;

use Garradin\Entities\Web\Page;
use Garradin\Web\Template;

use KD2\DB\EntityManager as EM;

class Web
{
	static public function search(string $search, bool $online_only = true): array
	{
		if (strlen($search) > 100) {
			throw new UserException('Recherche trop longue : maximum 100 caractères');
		}

		$where = '';

		if ($online_only) {
			$where = sprintf('p.status = %d AND ', Page::STATUS_ONLINE);
		}

		$query = sprintf('SELECT
			p.*,
			snippet(files_search, \'<b>\', \'</b>\', \'...\', -1, -50) AS snippet,
			rank(matchinfo(files_search), 0, 1.0, 1.0) AS points
			FROM files_search AS s
			INNER JOIN web_pages AS p USING (id)
			WHERE %s files_search MATCH ?
			ORDER BY points DESC
			LIMIT 0,50;', $where);

		return DB::getInstance()->get($query, $search);
	}

	static public function listCategories(?int $parent): array
	{
		$where = $parent ? sprintf('parent_id = %d', $parent) : 'parent_id IS NULL';
		$sql = sprintf('SELECT * FROM @TABLE WHERE %s AND type = %d ORDER BY title COLLATE NOCASE;', $where, Page::TYPE_CATEGORY);
		return EM::getInstance(Page::class)->all($sql);
	}

	static public function listPages(?int $parent, bool $order_by_date = true): array
	{
		$where = $parent ? sprintf('parent_id = %d', $parent) : 'parent_id IS NULL';
		$order = $order_by_date ? 'modified DESC' : 'title COLLATE NOCASE';
		$sql = sprintf('SELECT * FROM @TABLE WHERE %s AND type = %d ORDER BY %s;', $where, Page::TYPE_PAGE, $order);
		return EM::getInstance(Page::class)->all($sql);
	}

	static public function listCategoriesTree(?int $current = null): array
	{
		$db = DB::getInstance();
		$flat = $db->get('SELECT id, parent_id, title FROM web_pages ORDER BY title COLLATE NOCASE;');

		$parents = [];

		foreach ($flat as $node) {
			if (!isset($parents[$node->parent_id])) {
				$parents[$node->parent_id] = [];
			}

			$parents[(int) $node->parent_id][] = $node;
		}

		$build_tree = function (int $parent_id, int $level) use ($build_tree, $parents): array {
			$nodes = [];

			if (!isset($parents[$parent_id])) {
				return $nodes;
			}

			foreach ($parents[$parent_id] as $node) {
				$node->level = $level;
				$node->children = $build_tree($node->id, $level + 1);
				$nodes[] = $node;
			}

			return $nodes;
		};

		return $build_tree(0, 0);
	}

	static public function getByURI(string $uri): ?Page
	{
		return EM::findOne(Page::class, 'SELECT * FROM @TABLE WHERE uri = ?;', $uri);
	}

	static public function get(int $id): ?Page
	{
		return EM::findOneById(Page::class, $id);
	}

	static 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 = 'index.html';
		}
		// Redirect old URLs (pre-1.1)
		elseif ($uri == '/feed/atom/') {
			Utils::redirect('/atom.xml');
		}
		// URLs with an ending slash are categories
		elseif (substr($uri, -1) == '/') {
			$skel = 'category.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);

			// Custom templates
			if (preg_match('!^[\w\d_.-]+$!i', $_GET['uri'])) {
				$tpl = new Template($_GET['uri']);

				if ($tpl->exists()) {
					$tpl->serve();
					return;
				}
			}

			// Fallback to article.html
			$skel = 'article.html';
		}

		$tpl = new Template($skel);
		$tpl->serve();
	}
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































































































































































































Added src/include/lib/Garradin/Web/Render/AbstractRender.php version [5c2f7cfe96].



















































































































































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

namespace Garradin\Web\Render;

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

use const Garradin\{WWW_URL, ADMIN_URL};

abstract class AbstractRender
{
	protected $current_path;
	protected $context;
	protected $link_prefix;
	protected $link_suffix;
	protected $user_prefix;

	protected $file;

	public function __construct(?File $file = null, ?string $user_prefix = null)
	{
		$this->file = $file;

		if ($file) {
			$this->isRelativeTo($file);
		}

		$this->user_prefix = $user_prefix;
	}

	abstract public function render(?string $content = null): string;

	protected function resolveAttachment(string $uri) {
		$prefix = $this->current_path;
		$pos = strpos($uri, '/');

		// Absolute URL: treat it as absolute!
		if ($pos === 0) {
			return WWW_URL . ltrim($uri, '/');
		}

		// Handle relative URIs
		return WWW_URL . $prefix . '/' . $uri;
	}

	protected function resolveLink(string $uri) {
		$first = substr($uri, 0, 1);
		if ($first == '/' || $first == '!') {
			return Utils::getLocalURL($uri);
		}

		if (strpos(Utils::basename($uri), '.') === false) {
			$uri .= $this->link_suffix;
		}

		return $this->link_prefix . $uri;
	}

	public function isRelativeTo(File $file) {
		$this->current_path = $file->parent;
		$this->context = $file->context();
		$this->link_suffix = '';

		if ($this->context === File::CONTEXT_WEB) {
			$this->link_prefix = $this->user_prefix ?? WWW_URL;
			$this->current_path = Utils::basename(Utils::dirname($file->path));
		}
		else {
			$this->link_prefix = $this->user_prefix ?? sprintf(ADMIN_URL . 'common/files/preview.php?p=%s/', $this->context);
			$this->link_suffix = '.skriv';
		}
	}
}

Added src/include/lib/Garradin/Web/Render/Blocks.php version [7866908ee6].





















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?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 Parsedown;
use Parsedown_Extra;

use const Garradin\{ADMIN_URL, WWW_URL};

/*
			display: grid;
			grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
			grid-gap: 10px;

 */

class Blocks
{
	static protected $parsedown;
	protected $_stack = [];

	public function render(?File $file, ?string $content = null, array $options = []): string
	{
		$str = $content ?? $file->fetch();

		$out = '<div class="web-blocks">';

		// Skip page metadata
		strtok($str, "\n\n----\n\n");

		while ($block = strtok("\n\n----\n\n")) {
			$out .= $this->block($block);
		}

		if ($block = strtok('')) {
			$out .= $this->block($block);
		}

		strtok('', ''); // Free memory

		foreach ($this->_stack as $type) {
			$out .= '</article></section>';
		}

		$out .= '</div>';

		return $out;
	}

	protected function block(string $block): string
	{
		$header = strtok($block, "\n\n");
		$content = strtok('');
		strtok('', ''); // Free memory
		$out  = '';

		$content = trim($content, "\n");
		$class = sprintf('web-block-%s', $type);

		switch ($type) {
			case 'columns':
				if (array_pop($this->_stack)) {
					$out .= '</article></section>';
				}

				$out .= '<section class="web-columns">';
				return $out;
			case 'column':
				if (array_pop($this->_stack)) {
					$out .= '</article>';
				}

				$out .= '<article class="web-column">';
				$this->_stack[] = 'column';
				return $out;
			case 'code':
				return sprintf('<pre class="%s">%s</pre>', $class, htmlspecialchars($content));
			case 'markdown':
				$md = new Markdown;
				return sprintf('<div class="web-content %s">%s</div>', $class, $md->render($content));
			case 'skriv':
				$skriv = new Skriv;
				return sprintf('<div class="web-content %s">%s</div>', $class, $skriv->render($content));
			case 'image':
				return sprintf('<div class="%s">%s</div>', $this->image($content));
			case 'gallery':
				return sprintf('<div class="%s">%s</div>', $this->gallery($content));
			case 'heading':
				return sprintf('<h2 class="%s">%s</h2>', $class, htmlspecialchars($content));
			case 'quote':
				return sprintf('<blockquote class="%s"><p>%s</p></blockquote>', $class, nl2br(htmlspecialchars($content)));
			case 'video':
				return sprintf('<iframe class="%s" src="%s" frameborder="0" allow="accelerometer; encrypted-media; gyroscope" allowfullscreen></iframe>', $class, htmlspecialchars($content));
			default:
				throw new \LogicException('Unknown type: ' . $type);
		}
	}
}

Modified src/include/lib/Garradin/Web/Render/EncryptedSkriv.php from [252cf26860] to [42fbb7e0fc].

1
2
3
4
5
6

7
8
9
10
11
12



13
14
15
16
<?php

namespace Garradin\Web\Render;

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


class EncryptedSkriv
{
	static public function render(File $file, string $content): string
	{
		$tpl = Template::getInstance();



		$tpl->assign(compact('file', 'content'));
		return $tpl->fetch('common/_file_render_encrypted.tpl');
	}
}






>

|

|


>
>
>

|


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

namespace Garradin\Web\Render;

use Garradin\Entities\Files\File;
use Garradin\Template;
use const Garradin\ADMIN_URL;

class EncryptedSkriv extends AbstractRender
{
	public function render(?string $content = null): string
	{
		$tpl = Template::getInstance();
		$file = $this->file;
		$content = $content ?? $file->fetch();
		$tpl->assign('admin_url', ADMIN_URL);
		$tpl->assign(compact('file', 'content'));
		return $tpl->fetch('common/files/_file_render_encrypted.tpl');
	}
}

Modified src/include/lib/Garradin/Web/Render/HTML.php from [ca31cd740c] to [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): string
	{
		if (null === self::$g2x) {
			$g2x = self::$g2x = new Garbage2xhtml;
			$g2x->auto_br = false;
		}

		return self::$g2x->process($content);
	}
}












|






|


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/Markdown.php version [1e59334a43].







































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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\Web\Render;

use Garradin\Entities\Files\File;

use Garradin\Plugin;
use Garradin\Utils;
use Garradin\Files\Files;
use Garradin\UserTemplate\CommonModifiers;

use const Garradin\{ADMIN_URL, WWW_URL};

class Markdown extends AbstractRender
{
	public function render(?string $content = null): string
	{
		$parsedown = new Parsedown($this->file, $this->user_prefix);
		$parsedown->setBreaksEnabled(true);
		$parsedown->setUrlsLinked(true);
		$parsedown->setSafeMode(true);

		$str = $content ?? $this->file->fetch();

		$str = $parsedown->text($str);

		$str = CommonModifiers::typo($str);

		$str = preg_replace_callback(';<a href="((?!https?://|\w+:|#).+)">;i', function ($matches) {
			return sprintf('<a href="%s" target="_parent">', $this->resolveLink($matches[1]));
		}, $str);

		return sprintf('<div class="web-content">%s</div>', $str);
	}
}

Added src/include/lib/Garradin/Web/Render/Parsedown.php version [8582efeb8b].





































































































































































































































































































































































































































































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

namespace Garradin\Web\Render;

use Parsedown as Parent_Parsedown;

use Garradin\Entities\Files\File;

use Garradin\Utils;

/**
 * Custom Parsedown extension to enable the use of Skriv extensions inside Markdown markup
 *
 * Also adds support for footnotes and Table of Contents
 *
 * @see https://github.com/erusev/parsedown/wiki/Tutorial:-Create-Extensions
 */
class Parsedown extends Parent_Parsedown
{
	protected $skriv;
	protected $toc = [];

	function __construct(?File $file, ?string $user_prefix)
	{
		$this->BlockTypes['<'][] = 'SkrivExtension';
		$this->BlockTypes['['][]= 'TOC';

		# identify footnote definitions before reference definitions
		array_unshift($this->BlockTypes['['], 'Footnote');

		# identify footnote markers before before links
		array_unshift($this->InlineTypes['['], 'FootnoteMarker');

		$this->skriv = new Skriv($file, $user_prefix);
	}

	protected function blockSkrivExtension(array $line): ?array
	{
		$line = $line['text'];

		if (strpos($line, '<<') === 0 && preg_match('/^<<<?([a-z_]+)((?:(?!>>>?).)*?)(>>>?$|$)/i', trim($line), $match)) {
			$text = $this->skriv->callExtension($match);

			return [
				'char'    => $line[0],
				'element' => [
					'name'                   => 'div',
					'rawHtml'                => $text,
					'allowRawHtmlInSafeMode' => true,
				],
				'complete' => true,
			];
		}

		return null;
	}

	protected function blockHeader($line)
	{
		$block = parent::blockHeader($line);

		if (is_array($block)) {
			if (!isset($block['element']['attributes']['id'])) {
				$block['element']['attributes']['id'] = Utils::transformTitleToURI($block['element']['text']);
			}

			$level = substr($block['element']['name'], 1); // h1, h2... -> 1, 2...
			$id = $block['element']['attributes']['id'];
			$label = $block['element']['text'];

			$this->toc[] = compact('level', 'id', 'label');
		}

		return $block;
	}

	protected function blockTOC(array $line): ?array
	{
		if (!preg_match('/^\[(?:toc|sommaire)\]$/', trim($line['text']))) {
			return null;
		}

		return [
			'char'     => $line['text'][0],
			'complete' => true,
			'element'  => [
				'name'                   => 'div',
				'rawHtml'                => '<toc></toc>',
				'allowRawHtmlInSafeMode' => true,
			],
		];
	}

	public function buildTOC(): string
	{
		if (!count($this->toc)) {
			return '';
		}

		$out = '<div class="toc">';

		$level = 0;

		foreach ($this->toc as $h) {
			if ($h['level'] > $level) {
				$out .= str_repeat('<ol>', $h['level'] - $level);
				$level = $h['level'];
			}
			elseif ($h['level'] < $level) {
				$out .= str_repeat('</ol>', $level - $h['level']);
				$level = $h['level'];
			}

			$out .= sprintf('<li><a href="#%s">%s</a></li>', $h['id'], $h['label']);
		}

		if ($level > 0) {
			$out .= str_repeat('</ol>', $level);
		}

		$out .= '</div>';

		return $out;
	}

	/**
	 * Footnotes implementation, inspired by ParsedownExtra
	 * We're not using ParsedownExtra as it's buggy and unmaintained
	 */
	protected function blockFootnote(array $line): ?array
	{
		if (preg_match('/^\[\^(.+?)\]:[ ]?(.*)$/', $line['text'], $matches))
		{
			$block = array(
				'footnotes' => [$matches[1] => $matches[2]],
			);

			return $block;
		}

		return null;
	}

	protected function blockFootnoteContinue(array $line, array $block): ?array
	{
		if ($line['text'][0] === '[' && preg_match('/^\[\^(.+?)\]: ?(.*)$/', $line['text'], $matches))
		{
			$block['footnotes'][$matches[1]] = $matches[2];
			return $block;
		}

		end($block['footnotes']);
		$last = key($block['footnotes']);

		if (isset($block['interrupted']) && $line['indent'] >= 4)
		{
			$block['footnotes'][$last] .= "\n\n" . $line['text'];

			return $block;
		}
		else
		{
			$block['footnotes'][$last] .= "\n" . $line['text'];

			return $block;
		}
	}

	protected function blockFootnoteComplete(array $in)
	{
		$html = '';

		foreach ($in['footnotes'] as $name => $value) {
			$html .= sprintf('<dt id="fn-%s"><a href="#fn-ref-%1$s">%1$s</a></dt><dd>%s</dd>', htmlspecialchars($name), $this->text($value));
		}

		$out = [
			'element' => [
				'name'                   => 'dl',
				'attributes'             => ['class' => 'footnotes'],
				'rawHtml'                => $html,
				'allowRawHtmlInSafeMode' => true,
			],
		];

		return $out;
	}


	protected function inlineFootnoteMarker($Excerpt)
	{
		if (preg_match('/^\[\^(.+?)\]/', $Excerpt['text'], $matches))
		{
			$name = htmlspecialchars($matches[1]);

			$Element = array(
				'name' => 'sup',
				'attributes' => ['id' => 'fn-ref-'.$name],
				'handler' => 'element',
				'text' => array(
					'name' => 'a',
					'attributes' => array('href' => '#fn-'.$name, 'class' => 'footnote-ref'),
					'text' => $name,
				),
			);

			return [
				'extent' => strlen($matches[0]),
				'element' => $Element,
			];
		}
	}


	public function text($text)
	{
		$out = parent::text($text);

		if (false !== strpos($out, '<toc></toc>')) {
			$toc = $this->buildTOC();
			$out = str_replace('<toc></toc>', $toc, $out);
		}

		return $out;
	}
}

Added src/include/lib/Garradin/Web/Render/Render.php version [baee19544e].































































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

namespace Garradin\Web\Render;

use Garradin\Entities\Files\File;

class Render
{

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

	static public function render(string $format, File $file, string $content = null, string $link_prefix = null)
	{
		if ($format == self::FORMAT_SKRIV) {
			$r = new Skriv($file, $link_prefix);
		}
		else if ($format == self::FORMAT_ENCRYPTED) {
			$r = new EncryptedSkriv($file, $link_prefix);
		}
		else if ($format == self::FORMAT_MARKDOWN) {
			$r = new Markdown($file, $link_prefix);
		}
		else {
			throw new \LogicException('Invalid format: ' . $format);
		}

		return $r->render($content);
	}
}

Modified src/include/lib/Garradin/Web/Render/Skriv.php from [f53bca246a] to [ce5e528272].

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
<?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 KD2\SkrivLite;

use const Garradin\WWW_URL;

class Skriv
{
	static protected $skriv;

	static public function render(?File $file, string $str, array $options = []): string
	{
		if (!isset($options['prefix'])) {
			$options['prefix'] = WWW_URL;
		}

		if (!self::$skriv)
		{
			self::$skriv = new \KD2\SkrivLite;

			self::$skriv->registerExtension('fichier', [self::class, 'SkrivFichier']);
			self::$skriv->registerExtension('image', [self::class, '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) {
			$file = Files::get((int)$match[2]);


			if (!$file) {
				return $skriv->parseError('/!\ Lien fichier invalide');
			}



			return $file->url();
		}, $str);

		$str = self::$skriv->render($str);

		$str = Squelette_Filtres::typo_fr($str);

		$str = preg_replace_callback('!<a href="([^/.:@]+)">!i', function ($matches) use ($options) {
			return sprintf('<a href="%s%s">', $options['prefix'], Utils::transformTitleToURI($matches[1]));
		}, $str);



		return $str;
	}

	/**
	 * 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(array $args, ?string $content, SkrivLite $skriv): string
	{
		$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é.');
		}

		$file = Files::get((int)$id);

		if (!$file) {
			return $skriv->parseError('/!\ Tag fichier invalide');
		}

		if (empty($caption))
		{
			$caption = $file->name;
		}



		$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->size)).')</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(array $args, ?string $content, SkrivLite $skriv): string
	{
		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é.');
		}

		$file = Files::get((int)$id);

		if (!$file) {
			return $skriv->parseError('/!\ Tag image invalide');
		}

		if (!$file->image)
		{
			return $skriv->parseError('/!\ Tag image : ce fichier n\'est pas une image.');
		}

		$out = '<a href="'.$file->url().'" class="internal-image">';
		$out .= '<img src="'.$file->url($align == 'centre' ? 500 : 200).'" alt="';

		if ($caption)
		{
			$out .= htmlspecialchars($caption);
		}

		$out .= '" /></a>';

		if (!empty($align))
		{
			$out = '<figure class="image ' . $align . '">' . $out;

			if ($caption)
			{
				$out .= '<figcaption>' . htmlspecialchars($caption) . '</figcaption>';
			}

			$out .= '</figure>';
		}

		return $out;
	}
}






<

|
<



|

|

|

|

<
<
<
|
<
|
|
>
|
|

|
|
|
>
>
>
>

|

|
|
>

<
|
|
>

>
|


|
|
<

|
<
<
|
>
>
|



|


|

|

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

<
<
<
<
<
<
|




|


>
>
|
<
<
<
|
>
>
>






|

|

|

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

|


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



<
<
|
<
|


|





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

namespace Garradin\Web\Render;

use Garradin\Entities\Files\File;


use Garradin\Plugin;
use Garradin\UserTemplate\CommonModifiers;


use KD2\SkrivLite;

use const Garradin\{ADMIN_URL, WWW_URL};

class Skriv extends AbstractRender
{
	protected $skriv;

	public function __construct(?File $file = null, ?string $user_prefix = null)
	{



		parent::__construct($file, $user_prefix);


		$this->skriv = new SkrivLite;
		$this->skriv->registerExtension('file', [$this, 'SkrivFile']);
		$this->skriv->registerExtension('fichier', [$this, 'SkrivFile']);
		$this->skriv->registerExtension('image', [$this, 'SkrivImage']);

		// Enregistrer d'autres extensions éventuellement
		Plugin::fireSignal('skriv.init', ['skriv' => $this->skriv]);
	}

	public function render(?string $content = null): string
	{
		$skriv =& $this->skriv;

		$str = $content ?? $this->file->fetch();

		$str = preg_replace_callback('/#file:\[([^\]\h]+)\]/', function ($match) {
			return $this->resolveAttachment($match[1]);
		}, $str);


		$str = $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">', $this->resolveLink($matches[1]));
		}, $str);

		return sprintf('<div class="web-content">%s</div>', $str);
	}


	public function callExtension(array $match)


	{
		$method = new \ReflectionMethod($this->skriv, '_callExtension');
		$method->setAccessible(true);
		return $method->invoke($this->skriv, $match);
	}

	/**
	 * 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
	 */
	public function SkrivFile(array $args, ?string $content, SkrivLite $skriv): string
	{

		$name = $args[0] ?? null;









		$caption = $args[1] ?? null;


		if (!$name || null === $this->current_path)

		{






			return $skriv->parseError('/!\ Tag file : aucun nom de fichier indiqué.');
		}

		if (empty($caption))
		{
			$caption = $name;
		}

		$url = $this->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
	 */
	public function SkrivImage(array $args, ?string $content, SkrivLite $skriv): string
	{
		static $align_replace = ['gauche' => 'left', 'droite' => 'right', 'centre' => 'center'];



		$name = $args[0] ?? null;








		$align = $args[1] ?? null;



		$caption = $args[2] ?? null;

		$align = strtr($align, $align_replace);


		if (!$name || null === $this->current_path)
		{
			return $skriv->parseError('/!\ Tag image : aucun nom de fichier indiqué.');
		}


		$url = $this->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 [03f267b710].





















































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?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) {
			echo $this->file->fetch();
		}
		else {
			readfile($this->defaultPath());
		}
	}

	public function exists()
	{
		return $this->file ? true : ($this->defaultPath() ? true : false);
	}

	public function raw(): string
	{
		if (!$this->exists()) {
			throw new UserException('Ce fichier n\'existe pas');
		}

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

		$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 = [];

		$path = ROOT . '/www/skel-dist/';
		$i = new \DirectoryIterator($path);

		foreach ($i as $file) {
			if ($file->isDot() || $file->isDir()) {
				continue;
			}

			$mime = mime_content_type($file->getRealPath());

			$sources[$file->getFilename()] = ['is_text' => substr($mime, 0, 5) == 'text/', 'changed' => null];
		}

		unset($i);

		$list = Files::list(File::CONTEXT_SKELETON);

		foreach ($list as $file) {
			if ($file->type != $file::TYPE_FILE) {
				continue;
			}

			$sources[$file->name] = ['is_text' => substr($file->mime, 0, 5) == 'text/', 'changed' => $file->modified];
		}

		ksort($sources);

		return $sources;
	}
}

Deleted src/include/lib/Garradin/Web/Template.php version [e3b11fbc69].

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

namespace Garradin\Web;

use Garradin\Files\Files;
use Garradin\Files\Folders;
use Garradin\Entities\Files\File;
use Garradin\UserException;
use Garradin\UserTemplate;

use const Garradin\ROOT;

class Template
{
	const TEMPLATE_TYPES = '!^(?:text/(?:html|plain)|\w+/(?:\w+\+)?xml)$!';

	protected $template;
	protected $file;

	public function __construct(string $tpl)
	{
		if (!preg_match('!^[\w\d_-]+(?:\.[\w\d_-]+)*$!i', $tpl)) {
			throw new \InvalidArgumentException('Invalid template name');
		}

		$this->file = Files::getSystemFile($tpl, Folders::TEMPLATES);

		if ($this->file && !$this->file->public) {
			throw new \InvalidArgumentException('This file is not public');
		}

		$this->template = $tpl;
	}

	public function defaultPath(): ?string
	{
		$path = ROOT . '/www/skel-dist/' . $this->template;

		if (file_exists($path)) {
			return $path;
		}

		return null;
	}

	public function serve(): 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()));

			$ut->display();
		}
		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) {
			$this->file->fetch();
		}
		else {
			return file_get_contents($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)
	{
		if (!$this->file) {
			$this->file = new File;
			$this->file->set('type', $this->type());
		}

		$this->file->store(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 list(): array
	{
		$defaults = [];

		$dir = dir(ROOT . '/www/skel-dist/');

		while ($file = $dir->read())
		{
			if ($file[0] == '.')
				continue;

			$defaults[$file] = null;
		}

		$dir->close();

		$templates = Files::listSystemFiles(Folders::TEMPLATES);

		$sources = array_merge($defaults, $templates);
		ksort($sources);

		return $sources;
	}

}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































































Added src/include/lib/Garradin/Web/Web.php version [2a719367c6].































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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\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\Plugin;
use Garradin\Utils;
use Garradin\UserException;
use Garradin\ValidationException;
use Garradin\Membres\Session;

use KD2\DB\EntityManager as EM;

use const Garradin\{WWW_URI, ADMIN_URL, FILE_STORAGE_BACKEND};

class Web
{
	static public function search(string $search): array
	{
		$results = Files::search($search, File::CONTEXT_WEB . '%');

		foreach ($results as &$result) {
			$result->path = Utils::dirname(substr($result->path, strlen(File::CONTEXT_WEB) + 1));
			$result->breadcrumbs = [];
			$path = '';

			foreach (explode('/', $result->path) as $part) {
				$path = trim($path . '/' . $part, '/');
				$result->breadcrumbs[$path] = $part;
			}
		}

		return $results;
	}

	/**
	 * This syncs the whole website between the actual files and the web_pages table
	 */
	static public function sync(bool $force = false): array
	{
		// This is only useful if web pages are stored outside of the database
		if (FILE_STORAGE_BACKEND == 'SQLite' && !$force) {
			return [];
		}

		$path = File::CONTEXT_WEB;
		$errors = [];

		$exists = array_flip(Files::callStorage('listDirectoriesRecursively', $path));

		$db = DB::getInstance();

		$in_db = $db->getGrouped('SELECT path, file_path, modified FROM web_pages;');

		$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 (array_keys($new) as $path) {
			$f = Files::get(File::CONTEXT_WEB . '/' . $path . '/index.txt');

			if (!$f) {
				// This is a directory without content, ignore
				continue;
			}

			try {
				Page::fromFile($f)->save();
			}
			catch (ValidationException $e) {
				// Ignore validation errors, just don't add pages to index
				$errors[] = sprintf('Erreur à l\'import, page "%s": %s', str_replace(File::CONTEXT_WEB . '/', '', $f->parent), $e->getMessage());
			}
		}

		return $errors;

		/*
		// 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 listAll(string $parent): array
	{
		$sql = 'SELECT * FROM @TABLE WHERE parent = ? ORDER BY title COLLATE NOCASE;';
		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 (Plugin::fireSignal('http.request.file.before', compact('file', 'uri', 'session'))) {
				// If a plugin handled the request, let's stop here
				return;
			}

			if ($size) {
				$file->serveThumbnail($session, $size);
			}
			else {
				$file->serve($session, isset($_GET['download']) ? true : false);
			}

			Plugin::fireSignal('http.request.file.after', compact('file', 'uri', 'session'));

			return;
		}

		$site_disabled = Config::getInstance()->get('site_disabled');

		// Redirect old categories
		if (substr($uri, -1) == '/') {
			http_response_code(301);
			Utils::redirect('/' . rtrim($uri, '/'));
		}

		$page = null;

		if ($uri == '') {
			$skel = 'index.html';
		}
		elseif (!$site_disabled && ($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';
		}

		if ($site_disabled && ($skel == '404.html' || $uri == '')) {
			Utils::redirect(ADMIN_URL);
		}

		if (Plugin::fireSignal('http.request.skeleton.before', compact('page', 'skel', 'uri'))) {
			return;
		}

		$s = new Skeleton($skel);
		$s->serve(compact('uri', 'page', 'skel'));

		Plugin::fireSignal('http.request.skeleton.after', compact('page', 'skel', 'uri'));
	}
}

Deleted src/include/lib/Garradin/Wiki.php version [9fc9e84930].

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

    // 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 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 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 [9aeb838738].

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
25
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
Parsedown.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 [f852009f8f].

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
21
22
<?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();

Plugin::fireSignal('cron');

Modified src/scripts/upgrade.php from [53bc57b249] to [63ad14ab52].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php

namespace Garradin;

const UPGRADE_PROCESS = true;

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

$config = Config::getInstance();

try {
	if (Upgrade::preCheck()) {
		Upgrade::upgrade();
		exit(2);
	}
	else {
		exit(0);
	}
}
catch (UserException $e) {
	echo $e->getMessage() . PHP_EOL;
	exit(1);
}








<
<













1
2
3
4
5
6
7
8


9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

namespace Garradin;

const UPGRADE_PROCESS = true;

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



try {
	if (Upgrade::preCheck()) {
		Upgrade::upgrade();
		exit(2);
	}
	else {
		exit(0);
	}
}
catch (UserException $e) {
	echo $e->getMessage() . PHP_EOL;
	exit(1);
}

Modified src/templates/acc/accounts/deposit.tpl from [f0e1448813] to [42c0a571f4].

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
{include file="admin/_head.tpl" title="Dépôt en banque : %s — %s"|args:$account.code,$account.label current="acc/accounts"}

<p class="help">
	Cocher les cases correspondant aux montants à déposer, une nouvelle écriture sera générée.
</p>

{form_errors}










<form method="post" action="{$self_url}" data-focus="1">
	<table class="list">
		<thead>
			<tr>
				<td class="check"><input type="checkbox" title="Tout cocher / décocher" id="f_all" /><label for="f_all"></label></td>
				<td></td>
				<td>Date</td>
				<td>Réf. écriture</td>
				<td>Réf. ligne</td>
				<th>Libellé</th>
				<td class="money">Montant</td>
				<td class="money">Solde cumulé</td>
			</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>
		<legend>Détails de l'écriture de dépôt</legend>
		<dl>
			{input type="text" name="label" label="Libellé" required=1 default="Dépôt en banque"}
			{input type="date" name="date" default=$date label="Date" required=1}
			{input type="money" name="amount" label="Montant" required=1}
			{input type="list" target="acc/charts/accounts/selector.php?chart=%d&targets=%d"|args:$account.id_chart,$target name="account_transfer" label="Compte de dépôt" required=1}
			{input type="text" name="reference" label="Numéro de pièce comptable"}
			{input type="textarea" name="notes" label="Remarques" rows=4 cols=30}
		</dl>
	</fieldset>

	<p class="submit">
		{csrf_field key="acc_deposit_%s"|args:$account.id}
		{button type="submit" name="save" label="Enregistrer" class="main" shape="check"}
	</p>
</form>

{literal}
<script type="text/javascript">
var total = 0;
$('tbody input[type=checkbox]').forEach((e) => {
	e.addEventListener('change', () => {
		var v = e.getAttribute('data-debit') || e.getAttribute('data-credit');
		v = parseInt(v, 10);
		total += e.checked ? v : -v;
		if (total < 0) {
			total = 0;
		}
		$('#f_amount').value = g.formatMoney(total);
	});
});

$('#f_all').addEventListener('change', (e) => {
	$('#f_amount').value = '';
	total = 0;
});
</script>
{/literal}


{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
93
94
95
96
{include file="admin/_head.tpl" title="Dépôt en banque : %s — %s"|args:$account.code,$account.label current="acc/accounts"}





{form_errors}

{if !$journal_count}
	<p class="alert block">Il n'y a aucune écriture qui nécessite un dépôt.<br />
		{linkbutton href="!acc/transactions/new.php" shape="plus" label="Saisir un virement"}
	</p>
{else}
	<p class="help">
		Cocher les cases correspondant aux montants à déposer, une nouvelle écriture sera générée.
	</p>

	<form method="post" action="{$self_url}" data-focus="1">
		<table class="list">
			<thead>
				<tr>
					<td class="check"><input type="checkbox" title="Tout cocher / décocher" id="f_all" /><label for="f_all"></label></td>
					<td></td>
					<td>Date</td>
					<td>Réf. écriture</td>
					<td>Réf. ligne</td>
					<th>Libellé</th>
					<td class="money">Montant</td>
					<td class="money">Solde cumulé</td>
				</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>
			<legend>Détails de l'écriture de dépôt</legend>
			<dl>
				{input type="text" name="label" label="Libellé" required=1 default="Dépôt en banque"}
				{input type="date" name="date" default=$date label="Date" required=1}
				{input type="money" name="amount" label="Montant" required=1}
				{input type="list" target="acc/charts/accounts/selector.php?chart=%d&targets=%d"|args:$account.id_chart,$target name="account_transfer" label="Compte de dépôt" required=1}
				{input type="text" name="reference" label="Numéro de pièce comptable"}
				{input type="textarea" name="notes" label="Remarques" rows=4 cols=30}
			</dl>
		</fieldset>

		<p class="submit">
			{csrf_field key="acc_deposit_%s"|args:$account.id}
			{button type="submit" name="save" label="Enregistrer" class="main" shape="check"}
		</p>
	</form>

	{literal}
	<script type="text/javascript">
	var total = 0;
	$('tbody input[type=checkbox]').forEach((e) => {
		e.addEventListener('change', () => {
			var v = e.getAttribute('data-debit') || e.getAttribute('data-credit');
			v = parseInt(v, 10);
			total += e.checked ? v : -v;
			if (total < 0) {
				total = 0;
			}
			$('#f_amount').value = g.formatMoney(total);
		});
	});

	$('#f_all').addEventListener('change', (e) => {
		$('#f_amount').value = '';
		total = 0;
	});
	</script>
	{/literal}
{/if}

{include file="admin/_foot.tpl"}

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 [98708499a9] to [8864e5930b].

38
39
40
41
42
43
44




45
46
47
48
49
50
51
52
53
54
55
56
57
58
			{/if}
		{elseif $account.type == $account::TYPE_OUTSTANDING}
			{if $sum < 0}
				<p class="error block">Ce compte est débiteur <strong>{$sum|abs|raw|money_currency}</strong>. Est-ce normal&nbsp;? Une vérification est peut-être nécessaire&nbsp;?</p>
			{elseif $sum >= 0}
				<p class="confirm block">Ce compte d'attente est créditeur de <strong>{$sum|abs|raw|money_currency}</strong>. {if $sum > 200}Un dépôt à la banque serait peut-être une bonne idée&nbsp;?{/if}</p>
			{/if}




		{/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}







>
>
>
>






|







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
			{/if}
		{elseif $account.type == $account::TYPE_OUTSTANDING}
			{if $sum < 0}
				<p class="error block">Ce compte est débiteur <strong>{$sum|abs|raw|money_currency}</strong>. Est-ce normal&nbsp;? Une vérification est peut-être nécessaire&nbsp;?</p>
			{elseif $sum >= 0}
				<p class="confirm block">Ce compte d'attente est créditeur de <strong>{$sum|abs|raw|money_currency}</strong>. {if $sum > 200}Un dépôt à la banque serait peut-être une bonne idée&nbsp;?{/if}</p>
			{/if}
		{elseif $account.type == $account::TYPE_REVENUE && $sum < 0}
			<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 dû procéder à des remboursements par exemple, et que ceux-ci couvrent des recettes perçues sur un exercice précédent.</p>
		{elseif $account.type == $account::TYPE_EXPENSE && $sum < 0}
			<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}
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
			<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">
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
	<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 [d7fc6d0db8].

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

<form method="post" action="{$self_url}" enctype="multipart/form-data">
	{if !$csv->loaded()}
		<fieldset>
			<legend>Relevé de compte</legend>
			<p class="help block">
				Le rapprochement assisté permet de s'aider d'un relevé de compte au format CSV pour trouver les écritures manquantes ou erronées.<br />
				<a href="https://fossil.kd2.org/garradin/wiki?name=Compta/Rapprochement_assist%C3%A9" target="_blank">Aide détaillée</a>
			</p>
			<dl>
				{include file="common/_csv_help.tpl"}
				{input type="file" name="file" label="Fichier CSV" accept=".csv,text/csv" required=1}
			</dl>
			<p class="submit">
				{csrf_field key=$csrf_key}







|







13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

<form method="post" action="{$self_url}" enctype="multipart/form-data">
	{if !$csv->loaded()}
		<fieldset>
			<legend>Relevé de compte</legend>
			<p class="help block">
				Le rapprochement assisté permet de s'aider d'un relevé de compte au format CSV pour trouver les écritures manquantes ou erronées.<br />
				<a href="https://garradin.eu/Rapprochement_assiste" target="_blank">Aide détaillée</a>
			</p>
			<dl>
				{include file="common/_csv_help.tpl"}
				{input type="file" name="file" label="Fichier CSV" accept=".csv,text/csv" required=1}
			</dl>
			<p class="submit">
				{csrf_field key=$csrf_key}
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 [55f085e703] 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
46
47
48
49
				{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">{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">
					{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}
					{elseif $line.type == Entities\Accounting\Transaction::TYPE_CREDIT && ($line.status & Entities\Accounting\Transaction::STATUS_WAITING)}
						{linkbutton shape="export" label="Régler cette créance" href="!acc/transactions/new.php?payoff_for=%d"|args:$line.id}
					{/if}








|



|







31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
				{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}
					{elseif $line.type == Entities\Accounting\Transaction::TYPE_CREDIT && ($line.status & Entities\Accounting\Transaction::STATUS_WAITING)}
						{linkbutton shape="export" label="Régler cette créance" href="!acc/transactions/new.php?payoff_for=%d"|args:$line.id}
					{/if}

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 [a831512af8].

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
{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; ?>
	{foreach from=$grouped_accounts item="group"}
		<h2 class="ruler">{$group.label}</h2>

		<table class="list">
			<tbody>
			{foreach from=$group.accounts item="account"}
				<tr data-idx="{$index}">
					<td>{$account.code}</td>
					<th>{$account.label}</th>
					<td class="desc">{$account.description}</td>
					<td class="actions">
						<button class="icn-btn" value="{$account.id}" data-label="{$account.code} — {$account.label}" data-icon="&rarr;">Sélectionner</button>
					</td>
				</tr>
				<?php $index++; ?>
			{/foreach}
			</tbody>
		</table>
	{/foreach}

{else}

	<h2 class="ruler">
		<input type="text" placeholder="Recherche rapide" id="lookup" />

		<label>{input type="checkbox" name="typed_only" value=0 default=0 default=$all} N'afficher que les comptes favoris</label>

	</h2>


























	<table class="accounts">
		<tbody>
		{foreach from=$accounts item="account"}
			<tr data-idx="{$iteration}" class="account-level-{$account.code|strlen}">
				<td>{$account.code}</td>
				<th>{$account.label}</th>
				<td>
				{if $account.type}
					{icon shape="star"} <?=Entities\Accounting\Account::TYPES_NAMES[$account->type]?>
				{/if}
				</td>
				<td class="actions">
					<button class="icn-btn" value="{$account.id}" data-label="{$account.code} — {$account.label}" data-icon="&rarr;">Sélectionner</button>
				</td>
			</tr>
		{/foreach}
		</tbody>
	</table>


{/if}

<script type="text/javascript" src="{$admin_url}static/scripts/selector.js?{$version_hash}"></script>

{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
{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>
























{else}

	<h2 class="ruler">
		<input type="text" placeholder="Recherche rapide" id="lookup" />
		{if !isset($grouped_accounts)}
		<label>{input type="checkbox" name="typed_only" value=0 default=0 default=$all} N'afficher que les comptes favoris</label>
		{/if}
	</h2>


	{if isset($grouped_accounts)}
		<?php $index = 1; ?>
		{foreach from=$grouped_accounts item="group"}
			<h2 class="ruler">{$group.label}</h2>

			<table class="list">
				<tbody>
				{foreach from=$group.accounts item="account"}
					<tr data-idx="{$index}">
						<td>{$account.code}</td>
						<th>{$account.label}</th>
						<td class="desc">{$account.description}</td>
						<td class="actions">
							<button class="icn-btn" value="{$account.id}" data-label="{$account.code} — {$account.label}" data-icon="&rarr;">Sélectionner</button>
						</td>
					</tr>
					<?php $index++; ?>
				{/foreach}
				</tbody>
			</table>
		{/foreach}

	{else}

		<table class="accounts">
			<tbody>
			{foreach from=$accounts item="account"}
				<tr data-idx="{$iteration}" class="account-level-{$account.code|strlen}">
					<td>{$account.code}</td>
					<th>{$account.label}</th>
					<td>
					{if $account.type}
						{icon shape="star"} <?=Entities\Accounting\Account::TYPES_NAMES[$account->type]?>
					{/if}
					</td>
					<td class="actions">
						<button class="icn-btn" value="{$account.id}" data-label="{$account.code} — {$account.label}" data-icon="&rarr;">Sélectionner</button>
					</td>
				</tr>
			{/foreach}
			</tbody>
		</table>

	{/if}
{/if}

<script type="text/javascript" src="{$admin_url}static/scripts/selector.js?{$version_hash}"></script>

{include file="admin/_foot.tpl"}

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/_header.tpl from [8e4c7a5fd3] to [b23bfd50d9].

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
<div class="year-header">

	<nav class="tabs noprint">
		<ul>
			{if isset($analytical)}
			<li><strong><a href="{$admin_url}acc/reports/projects.php">Projets</a></strong></li>
			{/if}



			<li{if $current == "graphs"} class="current"{/if}><a href="{$admin_url}acc/reports/graphs.php?{$criterias_query}">Graphiques</a></li>
			<li{if $current == "trial_balance"} class="current"{/if}><a href="{$admin_url}acc/reports/trial_balance.php?{$criterias_query}">Balance générale</a></li>
			<li{if $current == "journal"} class="current"{/if}><a href="{$admin_url}acc/reports/journal.php?{$criterias_query}">Journal général</a></li>
			<li{if $current == "ledger"} class="current"{/if}><a href="{$admin_url}acc/reports/ledger.php?{$criterias_query}">Grand livre</a></li>
			<li{if $current == "statement"} class="current"{/if}><a href="{$admin_url}acc/reports/statement.php?{$criterias_query}">Compte de résultat</a></li>
			<li{if $current == "balance_sheet"} class="current"{/if}><a href="{$admin_url}acc/reports/balance_sheet.php?{$criterias_query}">Bilan</a></li>

		</ul>
	</nav>

	<h2>{$config.nom_asso} — {$title}</h2>
	{if isset($analytical)}
		<h3>Projet&nbsp;: {$analytical.label}</h3>
	{/if}
	{if isset($year)}
		<p>Exercice comptable {if $year.closed}clôturé{else}en cours{/if} du
			{$year.start_date|date_short} au {$year.end_date|date_short}, généré le {$close_date|date_short}</p>
	{/if}

	<p class="noprint print-btn">
		<button onclick="window.print(); return false;" class="icn-btn" data-icon="⎙">Imprimer</button>

	</p>
</div>




|

|
>
>
>






>








|
|




>


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
<div class="year-header">

	<nav class="tabs noprint">
		<ul>
		{if isset($analytical) || $current == 'analytical_ledger'}
			<li><strong><a href="{$admin_url}acc/reports/projects.php">Projets</a></strong></li>
		{/if}
		{if $current == 'analytical_ledger'}
				<li class="current"><a href="{$admin_url}acc/reports/ledger.php?{$criterias_query}">Grand livre analytique</a></li>
		{else}
			<li{if $current == "graphs"} class="current"{/if}><a href="{$admin_url}acc/reports/graphs.php?{$criterias_query}">Graphiques</a></li>
			<li{if $current == "trial_balance"} class="current"{/if}><a href="{$admin_url}acc/reports/trial_balance.php?{$criterias_query}">Balance générale</a></li>
			<li{if $current == "journal"} class="current"{/if}><a href="{$admin_url}acc/reports/journal.php?{$criterias_query}">Journal général</a></li>
			<li{if $current == "ledger"} class="current"{/if}><a href="{$admin_url}acc/reports/ledger.php?{$criterias_query}">Grand livre</a></li>
			<li{if $current == "statement"} class="current"{/if}><a href="{$admin_url}acc/reports/statement.php?{$criterias_query}">Compte de résultat</a></li>
			<li{if $current == "balance_sheet"} class="current"{/if}><a href="{$admin_url}acc/reports/balance_sheet.php?{$criterias_query}">Bilan</a></li>
		{/if}
		</ul>
	</nav>

	<h2>{$config.nom_asso} — {$title}</h2>
	{if isset($analytical)}
		<h3>Projet&nbsp;: {$analytical.label}</h3>
	{/if}
	{if isset($year)}
		<p>Exercice&nbsp;: {$year.label} ({if $year.closed}clôturé{else}en cours{/if}, du
			{$year.start_date|date_short} au {$year.end_date|date_short}, généré le {$close_date|date_short})</p>
	{/if}

	<p class="noprint print-btn">
		<button onclick="window.print(); return false;" class="icn-btn" data-icon="⎙">Imprimer</button>
		{linkbutton shape="download" href="%s&_pdf"|args:$self_url label="Télécharger en PDF"}
	</p>
</div>

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 [5c2ec98ec8].


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="Grand livre" current="acc/years"}



{include file="acc/reports/_header.tpl" current="ledger" title="Grand livre"}


<div class="year-header noprint">
	<button type="button" data-icon="↓" class="icn-btn" id="open_details">Déplier tous les comptes</button>
	<button type="button" data-icon="↑" class="icn-btn" id="close_details">Replier tous les comptes</button>
</div>

{foreach from=$ledger item="account"}

<details open="open">
	<summary><h2 class="ruler"><a href="{$admin_url}acc/accounts/journal.php?id={$account.id}&amp;year={$account.id_year}">{$account.code} — {$account.label}</a></h2></summary>








	<table class="list">
		<thead>
			<tr>
				<td></td>
				<td>N° pièce</td>
				<td>Réf. ligne</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
{if !empty($criterias.analytical_only)}
	{include file="admin/_head.tpl" title="Grand livre analytique" current="acc/years"}
	{include file="acc/reports/_header.tpl" current="analytical_ledger" title="Grand livre analytique"}
{else}
	{include file="admin/_head.tpl" title="Grand livre" current="acc/years"}
	{include file="acc/reports/_header.tpl" current="ledger" title="Grand livre"}
{/if}

<div class="year-header noprint">
	<button type="button" data-icon="↓" class="icn-btn" id="open_details">Déplier tous les comptes</button>
	<button type="button" data-icon="↑" class="icn-btn" id="close_details">Replier tous les comptes</button>
</div>

{foreach from=$ledger item="account"}

<details open="open">
	<summary><h2 class="ruler">
		{if !empty($criterias.analytical_only)}
			<?php $link = sprintf('%sacc/reports/trial_balance.php?analytical=%d&year=%d', $admin_url, $account->id, $account->id_year); ?>
		{else}
			<?php $link = sprintf('%sacc/reports/journal.php?id=%d&year=%d', $admin_url, $account->id, $account->id_year); ?>
		{/if}
			<a href="{$link}">{$account.code} — {$account.label}</a>
	</h2></summary>

	<table class="list">
		<thead>
			<tr>
				<td></td>
				<td>N° pièce</td>
				<td>Réf. ligne</td>
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}







|
|
|







|
|
|

















|
|







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
		{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 [c7e14dfc07].

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>
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
					</th>
				</tr>
			{foreach from=$parent.items item="item"}
				<tr>
					<th>{$item.label}</th>
					<td>
					<span class="noprint">
						<a href="{$admin_url}acc/reports/graphs.php?analytical={$item.id_account}&year={$item.id_year}">Graphiques</a>
						| <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}







|
|
|
|
|
|
>
>
>


|
|
|
|
|







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
					</th>
				</tr>
			{foreach from=$parent.items item="item"}
				<tr>
					<th>{$item.label}</th>
					<td>
					<span class="noprint">
						<a href="{$admin_url}acc/reports/graphs.php?analytical={$item.id_account}&amp;year={$item.id_year}">Graphiques</a>
						| <a href="{$admin_url}acc/reports/trial_balance.php?analytical={$item.id_account}&amp;year={$item.id_year}">Balance générale</a>
						| <a href="{$admin_url}acc/reports/journal.php?analytical={$item.id_account}&amp;year={$item.id_year}">Journal général</a>
						| <a href="{$admin_url}acc/reports/ledger.php?analytical={$item.id_account}&amp;year={$item.id_year}">Grand livre</a>
						| <a href="{$admin_url}acc/reports/statement.php?analytical={$item.id_account}&amp;year={$item.id_year}">Compte de résultat</a>
						| <a href="{$admin_url}acc/reports/balance_sheet.php?analytical={$item.id_account}&amp;year={$item.id_year}">Bilan</a>
						{if $item.total && $by_year}
						| <a href="{$admin_url}acc/reports/ledger.php?analytical_only=1&amp;year={$item.id_year}">Grand livre analytique</a>
						{/if}
					</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 [1184e1ecfe] to [7cddfa9ea3].

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
{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 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/actions_analytical.tpl from [326812a369] to [8c967ee289].

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="Ajouter/supprimer des écritures à un projet" current="acc/accounts"}

{form_errors}

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

	<fieldset>
		<legend>Affecter {$count} écritures sélectionnées à un projet</legend>
		<dl>
			<dd>
				{input type="select" name="id_analytical" options=$analytical_accounts label="Projet à utiliser" help="Pour retirer les écritures de leur projet actuellement affecté, sélectionner simplement « Aucun projet »."}

			</dd>
		</dl>
	</fieldset>

	<p class="submit">
		{csrf_field key="acc_actions"}
		<input type="hidden" name="action" value="add" />
		{button type="submit" name="change_analytical" label="Modifier les écritures" shape="right" class="main"}









<
|
>
|







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="Ajouter/supprimer des écritures à un projet" current="acc/accounts"}

{form_errors}

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

	<fieldset>
		<legend>Affecter {$count} écritures sélectionnées à un projet</legend>
		<dl>

			{input type="select" name="id_analytical" options=$analytical_accounts label="Projet à utiliser" help="Pour retirer les écritures de leur projet actuellement affecté, sélectionner « Aucun projet »."}
			{input type="checkbox" name="apply_lines" value="1" default="1" checked=1 label="Appliquer à toutes les lignes des écritures"}
			<dd class="help">Si décoché, alors seules les lignes sélectionnées seront modifiées. Si coché, toutes les lignes des écritures sélectionnées seront modifiées. Laisser coché en cas de doute.</dd>
		</dl>
	</fieldset>

	<p class="submit">
		{csrf_field key="acc_actions"}
		<input type="hidden" name="action" value="add" />
		{button type="submit" name="change_analytical" label="Modifier les écritures" shape="right" class="main"}

Modified src/templates/acc/transactions/details.tpl from [42225313b2] to [53732e7b12].

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
20
21
22
{include file="admin/_head.tpl" title="Écriture n°%d"|args:$transaction.id current="acc"}


<nav class="tabs">
{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_WRITE)}
	<aside>{linkbutton href="new.php?copy=%d"|args:$transaction.id shape="plus" label="Dupliquer cette écriture"}</aside>
{/if}
{if $session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_ADMIN) && !$transaction->validated && !$tr_year->closed}
	<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>

{/if}
</nav>

{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
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
	<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}
	</dd>

	<dt>Écriture liée à</dt>
	{if empty($related_users)}
		<dd><em>Aucun membre n'est lié à cette écriture.</em></dd>
	{else}
		{foreach from=$related_users item="u"}
			<dd>
				<a href="{$admin_url}membres/fiche.php?id={$u.id}">{$u.identity}</a>
				{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"}







|













|
















|






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



















|
|












>
>
>
>
>
>
>

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
	<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}
	</dd>

	<dt>Écriture liée à</dt>
	{if empty($related_users)}
		<dd><em>Aucun membre n'est lié à cette écriture.</em></dd>
	{else}
		{foreach from=$related_users item="u"}
			<dd>
				<a href="{$admin_url}membres/fiche.php?id={$u.id}">{$u.identity}</a>
				{if $u.id_service_user}— en règlement d'une <a href="{$admin_url}services/user/?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 $files_edit || count($files)}
<div class="attachments">
	<h3 class="ruler">Fichiers joints</h3>
	{include file="common/files/_context_list.tpl" files=$files edit=$files_edit 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 [7fde859c77] to [91b454b44d].

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>
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
			</dl>
		</fieldset>
	{/if}

	<fieldset>
		<legend>Informations</legend>
		<dl>
			{input type="date" name="date" default=$date label="Date" required=1 source=$transaction}
			{input type="text" name="label" label="Libellé" required=1 source=$transaction}
			{input type="text" name="reference" label="Numéro de pièce comptable" help="Numéro de facture, de note de frais, etc."}
		</dl>
		<dl data-types="all-but-advanced">
			{input type="money" name="amount" label="Montant" required=1 default=$amount}
		</dl>
	</fieldset>

	{if !$payoff_for}

		{foreach from=$types_details item="type"}
			<fieldset data-types="t{$type.id}">
				<legend>{$type.label}</legend>
				{if $type.id == $transaction::TYPE_ADVANCED}
					{* Saisie avancée *}
					{include file="acc/transactions/_lines_form.tpl" chart_id=$current_year.id_chart}
				{else}
					<dl>
					{foreach from=$type.accounts key="key" item="account"}

						{input type="list" target="acc/charts/accounts/selector.php?targets=%s&chart=%d"|args:$account.targets_string,$chart_id name="account_%d_%d"|args:$type.id,$key label=$account.label required=1}
					{/foreach}
					</dl>
				{/if}
			</fieldset>
		{/foreach}
	{/if}

	<fieldset>
		<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>







|



















>
|















<
<







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
			</dl>
		</fieldset>
	{/if}

	<fieldset>
		<legend>Informations</legend>
		<dl>
			{input type="date" name="date" label="Date" required=1 source=$transaction}
			{input type="text" name="label" label="Libellé" required=1 source=$transaction}
			{input type="text" name="reference" label="Numéro de pièce comptable" help="Numéro de facture, de note de frais, etc."}
		</dl>
		<dl data-types="all-but-advanced">
			{input type="money" name="amount" label="Montant" required=1 default=$amount}
		</dl>
	</fieldset>

	{if !$payoff_for}

		{foreach from=$types_details item="type"}
			<fieldset data-types="t{$type.id}">
				<legend>{$type.label}</legend>
				{if $type.id == $transaction::TYPE_ADVANCED}
					{* Saisie avancée *}
					{include file="acc/transactions/_lines_form.tpl" chart_id=$current_year.id_chart}
				{else}
					<dl>
					{foreach from=$type.accounts key="key" item="account"}
						<?php $selected = $types_accounts[$key] ?? null; ?>
						{input type="list" target="acc/charts/accounts/selector.php?targets=%s&chart=%d"|args:$account.targets_string,$chart_id name="account_%d_%d"|args:$type.id,$key label=$account.label required=1 default=$selected}
					{/foreach}
					</dl>
				{/if}
			</fieldset>
		{/foreach}
	{/if}

	<fieldset>
		<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 [46d5909f35].

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="Écritures liées à une inscription" current="acc/accounts"}

<p>
	{linkbutton href="!membres/fiche.php?id=%d"|args:$user_id label="Retour à la fiche membre" shape="user"}

</p>

{include file="acc/reports/_journal.tpl"}

<h2 class="ruler">Solde des comptes</h2>

<table class="list">
	<thead>
		<tr>
			<td>Numéro</td>
			<th>Compte</th>
			<td class="money">Solde débiteur</td>
			<td class="money">Solde créditeur</td>
		</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"}


|

>
|



















|
|






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="Écritures liées à une inscription" current="acc/accounts"}

<nav class="tabs">
	{linkbutton href="!membres/fiche.php?id=%d"|args:$user_id label="Retour à la fiche membre" shape="user"}
	{linkbutton href="!services/user/payment.php?id=%d"|args:$service_user_id label="Nouveau règlement" shape="plus"}
</nav>

{include file="acc/reports/_journal.tpl"}

<h2 class="ruler">Solde des comptes</h2>

<table class="list">
	<thead>
		<tr>
			<td>Numéro</td>
			<th>Compte</th>
			<td class="money">Solde débiteur</td>
			<td class="money">Solde créditeur</td>
		</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"}

Added src/templates/acc/years/export.tpl version [640274763b].





















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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="Export d'exercice" current="acc/years"}

<nav class="acc-year">
	<h4>Exercice sélectionné&nbsp;:</h4>
	<h3>{$year.label} — {$year.start_date|date_short} au {$year.end_date|date_short}</h3>
</nav>

<nav class="tabs">
	<ul>
		{if !$year.closed}
		<li><a href="{$admin_url}acc/years/import.php?id={$year.id}">Import</a></li>
		{/if}
		<li class="current"><a href="{$admin_url}acc/years/import.php?id={$year.id}">Export</a></li>
	</ul>
</nav>

{form_errors}

<form method="get" action="{$self_url}">

<fieldset>
	<legend>Export du journal général</legend>
	<dl>
		<dt>Format d'export</dt>
		{input type="radio" name="format" value="ods" default="ods" label="Tableur" help="pour LibreOffice ou autre tableur"}
		{input type="radio" name="format" value="csv" label="CSV"}
		<dt>Type d'export</dt>
		{input type="radio" name="type" value="full" label="Export comptable complet" default="full" help="conseillé pour transfert vers un autre logiciel"}
		{input type="radio" name="type" value="raw" label="Export natif Garradin"}
	</dl>
</fieldset>

<p class="submit">
	<input type="hidden" name="id" value="{$year.id}" />
	{button type="submit" name="load" label="Télécharger" shape="download" class="main"}
</p>



</form>

{include file="admin/_foot.tpl"}

Modified src/templates/acc/years/import.tpl from [83c69987e2] to [1a8a438acd].

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="Importer des écritures" current="acc/years"}

<nav class="acc-year">
	<h4>Exercice sélectionné&nbsp;:</h4>
	<h3>{$year.label} — {$year.start_date|date_short} au {$year.end_date|date_short}</h3>
</nav>

<nav class="tabs">
	<ul>
		<li class="current"><a href="{$admin_url}acc/years/import.php?id={$year.id}">Import</a></li>
		<li><a href="{$admin_url}acc/years/import.php?id={$year.id}&amp;export=csv">Export journal général - CSV</a></li>
		<li><a href="{$admin_url}acc/years/import.php?id={$year.id}&amp;export=ods">Export journal général - tableur</a></li>
	</ul>
</nav>

{form_errors}

<form method="post" action="{$self_url}" enctype="multipart/form-data">











|
<







1
2
3
4
5
6
7
8
9
10
11

12
13
14
15
16
17
18
{include file="admin/_head.tpl" title="Importer des écritures" current="acc/years"}

<nav class="acc-year">
	<h4>Exercice sélectionné&nbsp;:</h4>
	<h3>{$year.label} — {$year.start_date|date_short} au {$year.end_date|date_short}</h3>
</nav>

<nav class="tabs">
	<ul>
		<li class="current"><a href="{$admin_url}acc/years/import.php?id={$year.id}">Import</a></li>
		<li><a href="{$admin_url}acc/years/export.php?id={$year.id}">Export</a></li>

	</ul>
</nav>

{form_errors}

<form method="post" action="{$self_url}" enctype="multipart/form-data">

29
30
31
32
33
34
35
36
37

38


39
40


41
42
43
44
45
46
47
48

{else}

	<fieldset>
		<legend>Import d'écritures</legend>
		<dl>
			<dt><label for="f_type_garradin">Format de fichier</label></dt>
			{input type="radio" name="type" value="garradin" label="Journal général au format CSV Garradin" default="garradin"}
			{input type="radio" name="type" value="csv" label="Journal au format CSV libre"}

			{include file="common/_csv_help.tpl"}


			{input type="file" name="file" label="Fichier CSV" accept=".csv,text/csv" required=1}
			<dd class="help block">


				- Les lignes comportant un numéro d'écriture mettront à jour les écritures existantes correspondant à ces numéros (sauf si celles-ci ont été validées), alors que les lignes sans numéro créeront de nouvelles écritures.<br />
				- Si le fichier comporte des écritures dont la date est en dehors de l'exercice courant, elles seront ignorées.
			</dd>
		</dl>
	</fieldset>

	<p class="submit">
		{csrf_field key=$csrf_key}







<
|
>

>
>


>
>
|







28
29
30
31
32
33
34

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

{else}

	<fieldset>
		<legend>Import d'écritures</legend>
		<dl>
			<dt><label for="f_type_garradin">Format de fichier</label></dt>

			{input type="radio" name="type" value="csv" label="Journal au format CSV libre"  default="csv"}
			<dd class="help">Ce format ne permet d'importer que des écritures simples (un débit et un crédit par écriture) mais convient à la plupart des utilisations.</dd>
			{include file="common/_csv_help.tpl"}
			{input type="radio" name="type" value="garradin" label="Journal général au format CSV Garradin"}
			<dd class="help">Ce format permet d'importer des écritures comportant plusieurs lignes. Le format attendu est identique à l'export de journal général qui peut servir d'exemple.</dd>
			{input type="file" name="file" label="Fichier CSV" accept=".csv,text/csv" required=1}
			<dd class="help block">
				- Les lignes comportant un numéro d'écriture existant mettront à jour les écritures correspondant à ces numéros.<br />
				- Les lignes comportant un numéro inexistant renverront une erreur.<br />
				- Les lignes sans numéro créeront de nouvelles écritures.<br />
				- Si le fichier comporte des écritures dont la date est en dehors de l'exercice courant, elles seront ignorées.
			</dd>
		</dl>
	</fieldset>

	<p class="submit">
		{csrf_field key=$csrf_key}

Modified src/templates/acc/years/index.tpl from [40b0f49623] to [fbfa64b72c].

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
{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 !empty($list)}
	{if count($list) > 1}
	<section class="year-infos">
		<section class="graphs">
			<figure>
				<img src="{$admin_url}acc/reports/graph_plot_all.php?type=assets" 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
34
35
36
37
{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">
	Des tarifs d'activité étaient associés à l'ancien exercice clôturé.
	Ces tarifs ont été déconnectés de la comptabilité à cause du changement de plan comptable, il vous faudra les reconnecter manuellement au nouvel exercice.
</p>
{/if}

{if !empty($list)}
	{if count($list) > 1}
	<section class="year-infos">
		<section class="graphs">
			<figure>
				<img src="{$admin_url}acc/reports/graph_plot_all.php?type=assets" alt="" />
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
					| <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}
						{linkbutton label="Supprimer" shape="delete" href="delete.php?id=%d"|args:$year.id}
					{/if}







|
|
<







60
61
62
63
64
65
66
67
68

69
70
71
72
73
74
75
					| <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" shape="export" href="export.php?id=%d"|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}
						{linkbutton label="Supprimer" shape="delete" href="delete.php?id=%d"|args:$year.id}
					{/if}

Modified src/templates/acc/years/new.tpl from [847d4ab122] to [c8bd7f28b5].

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

<form method="post" action="{$self_url}" data-focus="1">

	<fieldset>
		<legend>Commencer un nouvel exercice</legend>
		<dl>
			{input type="select_groups" options=$charts name="id_chart" label="Plan comptable" required=true}
			<dd class="help">Attention, il ne sera pas possible de modifier ou supprimer un compte du plan comptable si le compte est utilisé dans un exercice clôturé.<br />
				Si vous souhaitez modifier le plan comptable pour ce nouvel exercice, il est recommandé de créer un nouveau plan comptable, recopié à partir de l'ancien plan comptable. Ainsi tous les comptes seront modifiables et supprimables.</dd>
			<dd class="help">{linkbutton shape="settings" label="Gestion des plans comptables" href="!acc/charts/"}</dd>
			{input type="text" name="label" label="Libellé" required=true}
			{input type="date" label="Début de l'exercice" name="start_date" required=true default=$start_date}
			{input type="date" label="Fin de l'exercice" name="end_date" required=true default=$end_date}
		</dl>
	</fieldset>

	<p class="submit">
		{csrf_field key="acc_years_new"}
		{button type="submit" name="new" label="Créer ce nouvel exercice" shape="right" class="main"}
	</p>

</form>

{include file="admin/_foot.tpl"}







|


|













11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

<form method="post" action="{$self_url}" data-focus="1">

	<fieldset>
		<legend>Commencer un nouvel exercice</legend>
		<dl>
			{input type="select_groups" options=$charts name="id_chart" label="Plan comptable" required=true}
			<dd class="help">Il ne sera pas possible de modifier ou supprimer un compte du plan comptable si le compte est utilisé dans un exercice clôturé.<br />
				Si vous souhaitez modifier le plan comptable pour ce nouvel exercice, il est recommandé de créer un nouveau plan comptable, recopié à partir de l'ancien plan comptable. Ainsi tous les comptes seront modifiables et supprimables.</dd>
			<dd class="help">{linkbutton shape="settings" label="Gestion des plans comptables" href="!acc/charts/"}</dd>
			{input type="text" name="label" label="Libellé" required=true default=$label}
			{input type="date" label="Début de l'exercice" name="start_date" required=true default=$start_date}
			{input type="date" label="Fin de l'exercice" name="end_date" required=true default=$end_date}
		</dl>
	</fieldset>

	<p class="submit">
		{csrf_field key="acc_years_new"}
		{button type="submit" name="new" label="Créer ce nouvel exercice" shape="right" class="main"}
	</p>

</form>

{include file="admin/_foot.tpl"}

Modified src/templates/admin/_head.tpl from [ec48b7346f] to [cd5caa4701].

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="{$www_url}favicon.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
121
122
123
124
125
126
                <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>
            {if $session->canAccess('membres', Membres::DROIT_ECRITURE)}
            <ul>

                <li class="member new{if $current == 'membres/ajouter'} current{/if}"><a href="{$admin_url}membres/ajouter.php">Ajouter</a></li>

                <li class="{if $current == 'membres/services'} current{/if}"><a href="{$admin_url}services/">Activités &amp; cotisations</a></li>

                <li class="member message{if $current == 'membres/message'} current{/if}"><a href="{$admin_url}membres/message_collectif.php">Message collectif</a></li>
            </ul>
            {/if}

            </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('documents', Membres::DROIT_ACCES)}
            <li class="{if $current == 'docs'} current{elseif $current_parent == 'docs'} current_parent{/if}"><a href="{$admin_url}docs/"><b class="icn">🗀</b><i> Fichiers</i></a>
            <ul>
                <li class="{if $current == 'docs/recent'} current{/if}"><a href="{$admin_url}docs/recent.php">Récents</a></li>
            </ul>
            </li>
        {/if}

        {if $session->canAccess('web', Membres::DROIT_ACCES)}
            <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>
            {* TODO
            <ul>
                <li class="{if $current == 'web/themes'} current{/if}"><a href="{$admin_url}web/themes/">Thèmes</a></li>
            </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 == 'me'} current{elseif $current_parent == 'me'} current_parent{/if}">
            <a href="{$admin_url}me/"><b class="icn">👤</b><i> Mes infos personnelles</i></a>
            <ul>
                <li{if $current == 'me/services'}  class="current"{/if}><a href="{$admin_url}me/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 [ff6a70ffdf] to [91dfe799a4].

1
2
3
4
5
6
7







8
9
10
11

12
<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 == 'donnees'} class="current"{/if}><a href="{$admin_url}config/donnees/">Sauvegarde et restauration</a></li>
		<li{if $current == 'plugins'} class="current"{/if}><a href="{$admin_url}config/plugins.php">Extensions</a></li>







		{if ENABLE_TECH_DETAILS}
		<li{if $current == 'logs'} class="current"{/if}><a href="{$admin_url}config/logs.php?type=errors">Journaux</a></li>
		{/if}
	</ul>

</nav>





|

>
>
>
>
>
>
>

|


>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<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>
		<li{if $sub_current == 'sql'} class="current"{/if}><a href="{$admin_url}config/advanced/sql.php">SQL</a></li>
		{if ENABLE_TECH_DETAILS}
		<li{if $sub_current == 'errors'} class="current"{/if}><a href="{$admin_url}config/advanced/errors.php">Journal d'erreurs</a></li>
		{/if}
	</ul>
	{/if}
</nav>

Modified src/templates/admin/config/advanced/errors.tpl from [3872ee463d] to [39b2ff6b31].

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="Journaux" current="config" custom_css=["styles/config.css"]}

{include file="admin/config/_menu.tpl" current="logs"}

{if ENABLE_TECH_DETAILS}
<nav class="tabs">
	<ul class="sub">
		{*<li{if $type != 'errors'} class="current"{/if}><a href="{$self_url_no_qs}">Actions utilisateurs</a></li>*}
		<li{if $type == 'errors'} class="current"{/if}><a href="?type=errors">Erreurs système</a></li>
	</ul>
</nav>
{/if}

{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>
			{if !empty($error.backtrace)}
				{foreach from=$error.backtrace item=trace}
|

|
<
<
<
<
<
<
<
<
<







1
2
3









4
5
6
7
8
9
10
{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>
			{if !empty($error.backtrace)}
				{foreach from=$error.backtrace item=trace}
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
				</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)}
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
				<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}
{else}
	<p class="help">
		Cette page permet de suivre les actions effectuées par les utilisateurs.
	</p>

	{if empty($list)}
		<p class="block alert">
			Aucune entrée dans le journal d'actions.
		</p>
	{/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"}

Added src/templates/admin/config/advanced/index.tpl version [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
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
{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>
	<p class="block error">
		Attention : toutes les données seront effacées&nbsp;! Ceci inclut les membres, les écritures comptables, les pages du wiki, etc.
		Seul votre compte membre sera re-créé avec le même email et mot de passe.
	</p>
	<p class="help">
		Une sauvegarde sera automatiquement créée avant de procéder à la remise à zéro.
	</p>
	<dl>
		<dt><label for="f_passe_verif">Votre mot de passe</label> (pour vérification)</dt>
		<dd><input type="password" name="passe_verif" id="f_passe_verif" /></dd>
	</dl>
	<p>
		{csrf_field key="reset"}
		{button type="submit" name="reset_ok" label="Oui, je veux remettre à zéro" shape="delete"}
	</p>
</fieldset>

</form>


{include file="admin/_foot.tpl"}

Added src/templates/admin/config/advanced/sql.tpl version [02fdf7334b].









































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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="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>

	<form method="post" action="{$self_url}">
		<fieldset>
			<legend>Requête SQL</legend>
			<dl>
				{input type="textarea" cols="70" rows="10" name="query" default=$query}
			</dl>
			<p class="submit">
				{button type="submit" name="run" label="Exécuter" shape="search" class="main"}
			</p>
		</fieldset>
	</form>

	{if !empty($result)}

		<p class="help">{$result|count} résultats trouvés pour cette requête.</p>
		<table class="list search">
			<thead>
				<tr>
					{foreach from=$result_header item="label"}
						<td>{$label}</td>
					{/foreach}
					<td></td>
				</tr>
			</thead>
			<tbody>
				{foreach from=$result item="row"}
					<tr>
						{foreach from=$row key="key" item="value"}
							<td>
								{if null === $value}
									<em>NULL</em>
								{else}
									{$value}
								{/if}
							</td>
						{/foreach}
					</tr>
				{/foreach}
			</tbody>
		</table>

	{elseif $result !== null}

		<p class="block alert">
			Aucun résultat trouvé.
		</p>

	{/if}

{elseif $table}
	<h2 class="ruler">Table : {$table}</h2>

	{include file="common/dynamic_list_head.tpl"}

		{foreach from=$list->iterate() item="row"}
			<tr>
				{foreach from=$row item="value"}
				<td>
					{if null == $value}
						<em>NULL</em>
					{else}
						{$value}
					{/if}
				</td>
				{/foreach}
				<td></td>
			</tr>
		{/foreach}

		</tbody>
	</table>

	{pagination url=$list->paginationURL() page=$list.page bypage=$list.per_page total=$list->count()}

{else}

	<p class="help block">
		Cette page vous permet de visualiser les données brutes de la base de données.
	</p>

	<form method="post" action="{$self_url}">
		<fieldset>
			<legend>Requête SQL</legend>
			<dl>
				{input type="textarea" cols="70" rows="10" name="query" default=$query}
			</dl>
			<p class="submit">
				{button type="submit" name="run" label="Exécuter" shape="search" class="main"}
			</p>
		</fieldset>
	</form>

	<h2 class="ruler">Liste des tables</h2>

	<dl class="describe">
		{foreach from=$tables_list key="name" item="table"}
			<dt><a href="?table={$name}">{$name}</a></dt>
			<dd><em>{$table.count} lignes</em></dd>
			<dd><pre>{$table.sql}</pre></dd>
		{/foreach}
	</dl>

	<h2 class="ruler">Liste des index</h2>

	<dl class="describe">
		{foreach from=$index_list key="name" item="sql"}
			<dt>{$name}</dt>
			<dd><pre>{$sql}</pre></dd>
		{/foreach}
	</dl>

	<h2 class="ruler">Liste des triggers</h2>

	<dl class="describe">
		{foreach from=$triggers_list key="name" item="sql"}
			<dt>{$name}</dt>
			<dd><pre>{$sql}</pre></dd>
		{/foreach}
	</dl>

{/if}

{include file="admin/_foot.tpl"}

Modified src/templates/admin/config/backup/_menu.tpl from [96b956198e] to [6843e6c837].

1
2
3
4
5
6
7
8
9
10
11
<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}
		<li{if $current == 'reset'} class="current"{/if}><a href="{$admin_url}config/donnees/reset.php">Remise à zéro</a></li>
	</ul>
</nav>


|
|
<
<
<
<
|


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>

Modified src/templates/admin/config/backup/index.tpl from [19ab1e4db0] to [e84c2fbbb2].

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"}
|

|

|


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



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
{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/export.php">Export des données comptables</a></dd>
	</dl>
</fieldset>

{include file="admin/_foot.tpl"}

Modified src/templates/admin/config/backup/restore.tpl from [b1089b8af9] to [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
{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>Copies de sauvegarde disponibles</legend>
    {if empty($liste)}
        <p class="help">Aucune copie de sauvegarde disponible.</p>
    {else}



        <dl>
            <dt><label for="f_select">Sélectionner une sauvegarde</label></dt>
            <dd>
                <select name="file" id="f_select">







                {foreach from=$liste key="f" item="d"}




                    <option value="{$f}">{$f} — {$d|date_long}</option>





                {/foreach}
                </select>
            </dd>
            <dd class="help">
                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. Cependant, afin de prévenir toute erreur
                une sauvegarde des données sera réalisée avant la restauration.
            </dd>
        </dl>
        <p>
            {csrf_field key="backup_manage"}
            {button type="submit" name="restore" label="Restaurer cette sauvegarde" shape="reset"}
            {button type="submit" name="delete" label="Supprimer cette sauvegarde" shape="delete"}
        </p>
    {/if}
</fieldset>

</form>

<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 des données" shape="right" class="main"}
    </p>
</fieldset>

</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
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"}

Modified src/templates/admin/config/backup/save.tpl from [45e209af0c] to [4752a2358e].

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. Si vous désirez revenir en arrière, vous pouvez utiliser la sauvegarde automatique nommée <em>{$now_date}.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>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"}
|

|

|



|
|
|
>
|
>
>

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

>




|

>
|

|
|
|
|




|


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





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
{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 é 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.<br />
		Cette sauvegarde ne concerne que la base de données, mais pas les documents, fichiers joints aux écritures ou aux membres, ni le contenu du site web.
	</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.
		{if FILE_STORAGE_BACKEND != 'SQLite'}<br /><br />
		La sauvegarde automatique ne concerne que la base de données, mais pas les documents, fichiers joints aux écritures ou aux membres, ni le contenu du site web.{/if}

	</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 [fb8b7e4413] 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 cotisations)</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 affecter des cotisations aux membres)</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/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/reset.tpl version [c696026876].

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
{include file="admin/_head.tpl" title="Remise à zéro" current="config"}

{include file="admin/config/_menu.tpl" current="donnees"}

{include file="admin/config/donnees/_menu.tpl" current="reset"}

{form_errors}

{if $ok !== null}
    <p class="block confirm">La remise à zéro a été effectuée. Une sauvegarde a également été créée.</p>
    </p>
{/if}

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

<fieldset>
    <legend>Remise à zéro</legend>
	<p class="block error">
		Attention : toutes les données seront effacées&nbsp;! Ceci inclut les membres, les écritures comptables, les pages du wiki, etc.
        Seul votre compte membre sera re-créé avec le même email et mot de passe.
	</p>
    <p class="help">
        Une sauvegarde sera automatiquement créée avant de procéder à la remise à zéro.
    </p>
    <dl>
        <dt><label for="f_passe_verif">Votre mot de passe</label> (pour vérification)</dt>
        <dd><input type="password" name="passe_verif" id="f_passe_verif" /></dd>
    </dl>
    <p>
        {csrf_field key="reset"}
        <input type="submit" name="reset_ok" value="Oui, je veux remettre à zéro" />
    </p>
</fieldset>

</form>


{include file="admin/_foot.tpl"}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































Modified src/templates/admin/config/index.tpl from [8115cb5714] to [fc444db700].

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
93
94
95
96
97
{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>
			<dt>Texte de la page d'accueil</dt>
			<dd>
				{linkbutton href="!config/edit_file.php?k=%s"|args:'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>
			{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"}
			<dt>Personnalisation CSS de l'administration</dt>
			<dd>
				{linkbutton href="!config/edit_file.php?k=%s"|args:'admin_css' label="Modifier" shape="edit" target="_dialog" data-dialog-height="90%"}
			</dd>
			<dd class="help">
				Permet de rajouter des <a href="https://developer.mozilla.org/fr/docs/Learn/CSS/First_steps" target="_blank">règles CSS</a> qui modifieront l'apparence de l'interface d'administration.
			</dd>
		</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 [f041717c0e] to [e15825a3fa].

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">
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
                <dd><input type="hidden" name="champs[{$nom}][type]" value="{$champ.type}" />{$champ.type|get_type}</dd>
                <dt><label for="f_{$nom}_title">Titre</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
                <dd><input type="text" name="champs[{$nom}][title]" id="f_{$nom}_title" value="{form_field data=$champ name=title}" required="required" /></dd>
                <dt><label for="f_{$nom}_help">Aide</label></dt>
                <dd><input type="text" name="champs[{$nom}][help]" id="f_{$nom}_help" value="{form_field data=$champ name=help}" /></dd>

                <dt><input type="checkbox" name="champs[{$nom}][private]" value="1" {form_field data=$champ name=private checked="1"} id="f_{$nom}_private"/> <label for="f_{$nom}_private">Caché pour les membres</label></dt>
                <dd class="help">Si coché, ce champ ne sera pas visible par les membres dans leur espace personnel.</dd>
                <dt><input type="checkbox" name="champs[{$nom}][editable]" value="1" {form_field data=$champ name=editable checked="1"} id="f_{$nom}_editable" /> <label for="f_{$nom}_editable">Modifiable par les membres</label></dt>
                <dd class="help">Si coché, les membres pourront changer cette information depuis leur espace personnel.</dd>
                <dt><label><input type="checkbox" name="champs[{$nom}][mandatory]" value="1" {form_field data=$champ name=mandatory checked="1"} for="f_{$nom}_mandatory" /> <label for="f_{$nom}_mandatory">Champ obligatoire</label></dt>
                <dd class="help">Si coché, ce champ ne pourra rester vide.</dd>

                {if $champ.type == 'select' || $champ.type == 'multiple'}
                    <dt><label>Options disponibles</label></dt>
                    {if $champ.type == 'multiple'}
                        <dd class="help">Attention changer l'ordre des options peut avoir des effets indésirables.</dd>
                    {else}







|


|







127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
                <dd><input type="hidden" name="champs[{$nom}][type]" value="{$champ.type}" />{$champ.type|get_type}</dd>
                <dt><label for="f_{$nom}_title">Titre</label> <b title="(Champ obligatoire)">obligatoire</b></dt>
                <dd><input type="text" name="champs[{$nom}][title]" id="f_{$nom}_title" value="{form_field data=$champ name=title}" required="required" /></dd>
                <dt><label for="f_{$nom}_help">Aide</label></dt>
                <dd><input type="text" name="champs[{$nom}][help]" id="f_{$nom}_help" value="{form_field data=$champ name=help}" /></dd>

                <dt><input type="checkbox" name="champs[{$nom}][private]" value="1" {form_field data=$champ name=private checked="1"} id="f_{$nom}_private"/> <label for="f_{$nom}_private">Caché pour les membres</label></dt>
                <dd class="help">Si coché, ce champ ne sera pas visible par les membres dans leur espace personnel. Attention, il apparaîtra quand même sur l'export de données RGPD que le membre peut télécharger, et qui contiendra toutes les données concernant ce membre.</dd>
                <dt><input type="checkbox" name="champs[{$nom}][editable]" value="1" {form_field data=$champ name=editable checked="1"} id="f_{$nom}_editable" /> <label for="f_{$nom}_editable">Modifiable par les membres</label></dt>
                <dd class="help">Si coché, les membres pourront changer cette information depuis leur espace personnel.</dd>
                <dt><label><input type="checkbox" name="champs[{$nom}][mandatory]" value="1" {form_field data=$champ name=mandatory checked="1"} id="f_{$nom}_mandatory" /> <label for="f_{$nom}_mandatory">Champ obligatoire</label></dt>
                <dd class="help">Si coché, ce champ ne pourra rester vide.</dd>

                {if $champ.type == 'select' || $champ.type == 'multiple'}
                    <dt><label>Options disponibles</label></dt>
                    {if $champ.type == 'multiple'}
                        <dd class="help">Attention changer l'ordre des options peut avoir des effets indésirables.</dd>
                    {else}

Modified src/templates/admin/index.tpl from [8e64b12bbb] to [39b0508d91].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{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>






|
|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{include file="admin/_head.tpl" title="Bonjour %s !"|args:$user.identite current="home"}

{$banner|raw}

<nav class="tabs">
	<ul>
		<li><a href="{$admin_url}me/">Modifier mes informations personnelles</a></li>
		<li><a href="{$admin_url}me/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>
30
31
32
33
34
35
36
37
38
39
40
41
42
	<p>
		Web : <a href="{$config.site_asso}" target="_blank">{$config.site_asso}</a>
	</p>
	{/if}
</aside>

{if $homepage}
	<article class="web">
		{$homepage->render()}
	</article>
{/if}

{include file="admin/_foot.tpl"}







|
|




30
31
32
33
34
35
36
37
38
39
40
41
42
	<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/login.tpl from [5f99a8a020] to [f3e8752670].

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
                        <span class="error">Connexion non-sécurisée&nbsp;!</span>
                        <a href="{$own_https_url}">Se connecter en HTTPS (sécurisé)</a>
                    {else}
                        <span class="alert">Connexion non-sécurisée</span>
                    {/if}
                {/if}
            </dd>
            {input type="checkbox" name="permanent" value="1" label="Rester connectée" help="recommandé seulement sur ordinateur personnel"}
        </dl>
    </fieldset>

    <p class="submit">
        {csrf_field key="login"}
        {button type="submit" name="login" label="Se connecter" shape="right" class="main"}
    </p>

    <p class="help">
        <a href="{$admin_url}password.php">Pas de mot de passe ou mot de passe perdu ?</a>
    </p>

</form>

{literal}
<script type="text/javascript">
if (window.navigator.userAgent.match(/MSIE|Trident\/|Edge\//)) {







|









|







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
                        <span class="error">Connexion non-sécurisée&nbsp;!</span>
                        <a href="{$own_https_url}">Se connecter en HTTPS (sécurisé)</a>
                    {else}
                        <span class="alert">Connexion non-sécurisée</span>
                    {/if}
                {/if}
            </dd>
            {input type="checkbox" name="permanent" value="1" label="Rester connectée" help="recommandé seulement sur ordinateur personnel"}
        </dl>
    </fieldset>

    <p class="submit">
        {csrf_field key="login"}
        {button type="submit" name="login" label="Se connecter" shape="right" class="main"}
    </p>

    <p class="help">
        <a href="{$admin_url}password.php">Première connexion ou mot de passe perdu ?</a>
    </p>

</form>

{literal}
<script type="text/javascript">
if (window.navigator.userAgent.match(/MSIE|Trident\/|Edge\//)) {

Added src/templates/admin/membres/_details.tpl version [059439d1b5].





























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
assert(isset($data, $champs, $show_message_button));
$user_files_path = (new Membres)->getAttachementsDirectory($data->id);
?>

<dl class="describe">
	{foreach from=$champs key="c" item="c_config"}
	<?php
	// Skip private fields from "my info" page
	if ($mode == 'user' && $c_config->private) {
		continue;
	}

	// Skip files from export
	if ($mode == 'export' && $c_config->type == 'file') {
		continue;
	}

	$value = $data->$c ?? null;
	?>
	<dt>{$c_config.title}</dt>
	<dd>
		{if $c_config.type == 'checkbox'}
			{if $value}Oui{else}Non{/if}
		{elseif $c_config.type == 'file'}
			<?php
			$edit = ($c_config->editable || $mode == 'edit');
			?>
			{include file="common/files/_context_list.tpl" limit=1 path="%s/%s"|args:$user_files_path,$c}
		{elseif empty($value)}
			<em>(Non renseigné)</em>
		{elseif $c == $c_config.champ_identite}
			<strong>{$value}</strong>
		{elseif $c_config.type == 'email'}
			<a href="mailto:{$value|escape:'url'}">{$value}</a>
			{if $c == 'email' && $show_message_button}
				{linkbutton href="!membres/message.php?id=%d"|args:$data.id label="Envoyer un message" shape="mail"}
			{/if}
		{elseif $c_config.type == 'tel'}
			<a href="tel:{$value}">{$value|format_tel}</a>
		{elseif $c_config.type == 'country'}
			{$value|get_country_name}
		{elseif $c_config.type == 'date'}
			{$value|date_short}
		{elseif $c_config.type == 'datetime'}
			{$value|date}
		{elseif $c_config.type == 'password'}
			*******
		{elseif $c_config.type == 'multiple'}
			<ul>
			{foreach from=$c_config.options key="b" item="name"}
				{if $value & (0x01 << $b)}
					<li>{$name}</li>
				{/if}
			{/foreach}
			</ul>
		{else}
			{$value|escape|rtrim|nl2br}
		{/if}
	</dd>
	{/foreach}
</dl>

Modified src/templates/admin/membres/_list_actions.tpl from [143fb71a16] to [9f86dc3d7a].

1
2
3
4
5
6
7
8
9

10
11

12
13
14
15
16
17
18
19
		<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>
						<option value="ods">Exporter en classeur Office</option>

						<option value="delete">Supprimer</option>
					</select>
					<noscript>
						<input type="submit" value="OK" />
					</noscript>
				</td>
			</tr>
		</tfoot>


|






>


>








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
		<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>
						{if !isset($export) || $export != false}
						<option value="csv">Exporter en tableau CSV</option>
						<option value="ods">Exporter en classeur Office</option>
						{/if}
						<option value="delete">Supprimer</option>
					</select>
					<noscript>
						<input type="submit" value="OK" />
					</noscript>
				</td>
			</tr>
		</tfoot>

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/action.tpl from [076d7f7b64] to [3bdaad34d2].

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

    {if $action == 'move'}
    <fieldset>
        <legend>Changer la catégorie des {$nb_selected} membres sélectionnés</legend>
        <dl>
            <dt><label for="f_cat">Nouvelle catégorie</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}">{$nom}</option>
                {/foreach}
                </select>
            </dd>
        </dl>
    </fieldset>







|







15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

    {if $action == 'move'}
    <fieldset>
        <legend>Changer la catégorie des {$nb_selected} membres sélectionnés</legend>
        <dl>
            <dt><label for="f_cat">Nouvelle catégorie</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}">{$nom}</option>
                {/foreach}
                </select>
            </dd>
        </dl>
    </fieldset>

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 [858a55f227].

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>
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
    {foreachelse}
    <dd>
        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)}
					(<b class="icn">🔒</b> avec second facteur)
				{else}
					(<b class="icn">🔓</b> sans second facteur)
				{/if}
		{/if}
		</dd>
	</dl>
</aside>

<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>
                {/if}
            {/foreach}
            </ul>
        {else}
            {$membre->$c|escape|rtrim|nl2br}
        {/if}
    </dd>
    {/foreach}
</dl>

{include file="admin/_foot.tpl"}







|

|
|


>
>
>
>
>
|














|



|
















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


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
    {foreachelse}
    <dd>
        Ce membre n'est inscrit à aucune activité ou cotisation.
    </dd>
    {/foreach}
    <dd>
        {if count($services)}
            {linkbutton href="!services/user/?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/user/add.php?user=%d"|args:$membre.id label="Inscrire à une activité" shape="plus"}
        {/if}
    </dd>
    {if count($services)}
    <dd>
        {linkbutton shape="alert" label="Liste des rappels envoyés" href="!services/reminders/user.php?id=%d"|args:$membre.id}
    </dd>
    {/if}
    {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)}
					(<b class="icn">🔒</b> avec second facteur)
				{else}
					(<b class="icn">🔓</b> sans second facteur)
				{/if}
		{/if}
		</dd>
	</dl>
</aside>





















{include file="admin/membres/_details.tpl" champs=$champs data=$membre show_message_button=true mode="edit"}



















{include file="admin/_foot.tpl"}

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 [bf6707b31f].

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}

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
            <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" value="{form_field name=passe}" pattern="{$password_pattern}" autocomplete="off" /></dd>
            <dt><label for="f_repasse">Encore le mot de passe</label> (vérification){if $champs.passe.mandatory} <b title="(Champ obligatoire)">obligatoire</b>{/if}</dt>
            <dd><input type="password" name="passe_confirmed" id="f_repasse" value="{form_field name=passe_confirmed}" pattern="{$password_pattern}" autocomplete="off" /></dd>





        </dl>
    </fieldset>

    {if $membre.secret_otp || $membre.clef_pgp}
    <fieldset>
        <legend>Options de sécurité</legend>
        <dl>
        {if $membre.secret_otp}
            {input type="checkbox" name="clear_otp" value="1" label="Désactiver l'authentification à double facteur TOTP"}
        {/if}
        {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>







>
>
>
>
>

















|





|







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
            <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" value="{form_field name=passe}" pattern="{$password_pattern}" autocomplete="off" /></dd>
            <dt><label for="f_repasse">Encore le mot de passe</label> (vérification){if $champs.passe.mandatory} <b title="(Champ obligatoire)">obligatoire</b>{/if}</dt>
            <dd><input type="password" name="passe_confirmed" id="f_repasse" value="{form_field name=passe_confirmed}" pattern="{$password_pattern}" autocomplete="off" /></dd>
        {if $membre.passe}
            <dd>
                {input type="checkbox" name="delete_password" label="Supprimer le mot de passe de ce membre" value=1}
            </dd>
        {/if}
        </dl>
    </fieldset>

    {if $membre.secret_otp || $membre.clef_pgp}
    <fieldset>
        <legend>Options de sécurité</legend>
        <dl>
        {if $membre.secret_otp}
            {input type="checkbox" name="clear_otp" value="1" label="Désactiver l'authentification à double facteur TOTP"}
        {/if}
        {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/password.tpl from [c3884ccc30] to [6998bc730a].

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="Mot de passe oublié ou pas de mot de passe ?"}


{if !empty($sent)}
    <p class="block confirm">
        Un e-mail vous a été envoyé, cliquez sur le lien dans cet e-mail
        pour modifier votre mot de passe.
    </p>
    <p class="block alert">
        Si le message n'apparaît pas dans les prochaines minutes, vérifiez le dossier Spam ou Indésirables.
    </p>

{else}

    {form_errors}

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

        <fieldset>
            <legend>Recevoir un e-mail avec un nouveau mot de passe</legend>
            <p class="help">
                Inscrivez ici votre {$champ.title}.
                Nous vous enverrons un message vous indiquant un lien permettant de recevoir un
                nouveau mot de passe.
            </p>
            <dl>
                <dt><label for="f_id">{$champ.title}</label></dt>
                <dd><input type="text" name="id" id="f_id" value="{form_field name=id}" /></dd>
            </dl>
        </fieldset>

|




















|
|
<







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
{include file="admin/_head.tpl" title="Mot de passe oublié ou première connexion ?"}


{if !empty($sent)}
    <p class="block confirm">
        Un e-mail vous a été envoyé, cliquez sur le lien dans cet e-mail
        pour modifier votre mot de passe.
    </p>
    <p class="block alert">
        Si le message n'apparaît pas dans les prochaines minutes, vérifiez le dossier Spam ou Indésirables.
    </p>

{else}

    {form_errors}

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

        <fieldset>
            <legend>Recevoir un e-mail avec un nouveau mot de passe</legend>
            <p class="help">
                Inscrivez ici votre identifiant.
                Nous vous enverrons un e-mail avec un lien vous permettant de créer ou changer le mot de passe.

            </p>
            <dl>
                <dt><label for="f_id">{$champ.title}</label></dt>
                <dd><input type="text" name="id" id="f_id" value="{form_field name=id}" /></dd>
            </dl>
        </fieldset>

Modified src/templates/common/_csv_help.tpl from [2cbd2ae88a] to [109bc3ecbe].

1
2
3
4
5
6
7
8
9
10
11
<dd class="help">
	Règles à suivre pour créer le fichier CSV&nbsp;:
	<ul>
		<li>Il est recommandé d'utiliser LibreOffice pour créer le fichier CSV</li>
		<li>Le fichier doit être en UTF-8</li>
		<li>Le séparateur doit être le point-virgule ou la virgule</li>
		<li>Cocher l'option <em>"Mettre en guillemets toutes les cellules du texte"</em></li>
		<li>Le fichier doit comporter les colonnes suivantes : <em>{$csv->getColumnsString()}</em></li>
		<li>Le fichier peut également comporter les colonnes suivantes : <em>{$csv->getMandatoryColumnsString()}</em></li>
	</ul>
</dd>








|


1
2
3
4
5
6
7
8
9
10
11
<dd class="help">
	Règles à suivre pour créer le fichier CSV&nbsp;:
	<ul>
		<li>Il est recommandé d'utiliser LibreOffice pour créer le fichier CSV</li>
		<li>Le fichier doit être en UTF-8</li>
		<li>Le séparateur doit être le point-virgule ou la virgule</li>
		<li>Cocher l'option <em>"Mettre en guillemets toutes les cellules du texte"</em></li>
		<li>Le fichier doit comporter les colonnes suivantes : <em>{$csv->getColumnsString()}</em></li>
		{if $columns = $csv->getMandatoryColumnsString()}<li>Le fichier peut également comporter les colonnes suivantes : <em>{$columns}</em></li>{/if}
	</ul>
</dd>

Modified src/templates/common/_csv_match_columns.tpl from [f8a953f97c] to [09427edd39].

1
2
3
4
5
6
7
8






9
10
11
12
13
14
15
<fieldset>
	<legend>Importer depuis un fichier CSV générique</legend>
	<dl>
		<dd class="help">{$csv->count()} lignes trouvées dans le fichier</dd>
		<dt>{input type="checkbox" name="skip_first_line" value="1" label="Ne pas importer la première ligne" help="Décocher cette case si la première ligne ne contient pas l'intitulé des colonnes, mais des données" default=1}
		<dt><label>Correspondance des colonnes</label></dt>
		<dd>
			<table class="list auto">






				<tbody>
				{foreach from=$csv->getFirstLine() key="index" item="csv_field"}
					<tr>
						<th>{$csv_field}</th>
						<td>
							<select name="translation_table[{$index}]">
							<?php $selected = $csv->getSelectedTable(); ?>








>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<fieldset>
	<legend>Importer depuis un fichier CSV générique</legend>
	<dl>
		<dd class="help">{$csv->count()} lignes trouvées dans le fichier</dd>
		<dt>{input type="checkbox" name="skip_first_line" value="1" label="Ne pas importer la première ligne" help="Décocher cette case si la première ligne ne contient pas l'intitulé des colonnes, mais des données" default=1}
		<dt><label>Correspondance des colonnes</label></dt>
		<dd>
			<table class="list auto">
				<thead>
					<tr>
						<th>Colonne du CSV à importer</th>
						<th>Importer cette colonne comme…</th>
					</tr>
				</thead>
				<tbody>
				{foreach from=$csv->getFirstLine() key="index" item="csv_field"}
					<tr>
						<th>{$csv_field}</th>
						<td>
							<select name="translation_table[{$index}]">
							<?php $selected = $csv->getSelectedTable(); ?>

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 [9143e41708].









































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
assert(isset($path, $edit));

if (!isset($files)) {
	$files = Files\Files::list($path);
}

$can_upload = false;

if ($edit
	&& Entities\Files\File::checkCreateAccess($path, $session)
	&& (!isset($limit) || count($files) < $limit)) {
	$can_upload = true;
}

?>

{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 $edit && $file->checkDeleteAccess($session)}
			{linkbutton shape="delete" target="_dialog" href="!common/files/delete.php?p=%s"|args:$file.path label="Supprimer"}
		{/if}
	</aside>
{foreachelse}
	{if !$can_upload}
		<em>--</em>
	{/if}
{/foreach}
</div>

Modified src/templates/common/files/_file_render_encrypted.tpl from [fc5e705fb9] to [8602ee5447].

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="wikiContent" style="display: none;" id="wikiEncryptedContent">
	{$page.contenu.contenu}
</div>








|


|
|

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 pleaseDecrypt();" value="Entrer le mot de passe" />
	</p>
</div>
<div class="web-content" style="display: none;" id="wikiEncryptedContent">
	{$content}
</div>

Modified src/templates/common/files/_preview.tpl from [9200569279] to [d04060e5dd].

1
2
3
4
5
6
7
{include file="admin/_head.tpl" title="Web" current="web" is_popup=1 body_id="transparent"}

<div class="wikiContent">
	{$content|raw}
</div>

{include file="admin/_foot.tpl"}
|

<
|
<


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"}

Modified src/templates/common/files/delete.tpl from [42a5f97ba7] to [6b7ff711ef].

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"}


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


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 [c721ff089b].































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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.path data-fullscreen="1" data-attachments="0" data-savebtn="1" data-format=$file->renderFormat()}
	</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/rename.tpl version [8196200baf].









































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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="Renommer" current=null}

{form_errors}

<form method="post" action="{$self_url}" data-focus="1">
	<fieldset>
		<legend>Renommer</legend>
		<dl>
			<dt>Nom actuel</dt>
			<dd><input type="text" disabled="disabled" value="{$file.name}" /></dd>
			{input type="text" name="new_name" required="required" label="Nouveau nom" default=$file.name}
		</dl>
		<p class="submit">
			{csrf_field key=$csrf_key}
			{button type="submit" name="rename" label="Renommer" shape="right" class="main"}
		</p>
	</fieldset>
</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 [4ff50293ec] 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
<?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>Schéma des tables SQL</legend>
		<pre class="sql_schema">{foreach from=$schema item="table"}{$table}<br />{/foreach}</pre>
		<dl>
			{input type="textarea" name="sql_query" cols="100" rows="7" 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}







		</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"}

			{else}
				{button name="save" value=1 type="submit" label="Enregistrer cette recherche" shape="upload"}
			{/if}



		</p>
	{elseif !$sql_query}
		<legend>Rechercher</legend>
		<div class="queryBuilder" id="queryBuilder"></div>
		<p class="actions">
			<label>Trier par
				<select name="order">





|







|
<

|
|



>
>
>
>
>
>
>






>



>
>
>







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
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">
			<label>Trier par
				<select name="order">
45
46
47
48
49
50
51

52
53
54
55
56
57
58
		</p>
		<p class="submit">
			{button name="search" value=1 type="submit" label="Chercher" shape="search" id="send" class="main"}
			<input type="hidden" name="q" id="jsonQuery" />
			<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"}

			{else}
				{button name="save" value=1 type="submit" label="Enregistrer cette recherche" shape="upload"}
			{/if}
			{if $is_admin}
				{button name="to_sql" value=1 type="submit" label="Recherche SQL" shape="edit"}
			{/if}
		</p>







>







55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
		</p>
		<p class="submit">
			{button name="search" value=1 type="submit" label="Chercher" shape="search" id="send" class="main"}
			<input type="hidden" name="q" id="jsonQuery" />
			<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 $is_admin}
				{button name="to_sql" value=1 type="submit" label="Recherche SQL" shape="edit"}
			{/if}
		</p>

Modified src/templates/common/search/saved_searches.tpl from [4b50bfbcd9] to [c5426cd9d9].

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
			{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="?duplicate=%d"|args:$recherche.id shape="export" label="Dupliquer"}
						{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 [fb879e1eb5].

















































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?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?path=%s"|args:$path}
	{/if}
	{if $can_upload}
		{linkbutton shape="plus" label="Nouveau fichier texte" target="_dialog" href="!docs/new_file.php?path=%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_READ)}
			<li{if $context == File::CONTEXT_TRANSACTION} class="current"{/if}><a href="./?path=<?=File::CONTEXT_TRANSACTION?>">Fichiers des écritures</a></li>
		{/if}
		{if $session->canAccess($session::SECTION_USERS, $session::ACCESS_READ)}
			<li{if $context == File::CONTEXT_USER} class="current"{/if}><a href="./?path=<?=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="./?path=<?=File::CONTEXT_SKELETON?>">Squelettes du site web</a></li>
		{/if}
	</ul>

</nav>

<nav class="breadcrumbs">
	{if count($breadcrumbs) > 1}
		{linkbutton href="?path=%s"|args:$parent_path label="Retour au répertoire parent" shape="left"}
	{/if}

{if $context == File::CONTEXT_TRANSACTION}
	{if $context_ref}
		{linkbutton href="!acc/transactions/details.php?id=%d"|args:$context_ref|local_url label="Détails de l'écriture" shape="menu"}
	{/if}
{elseif $context == File::CONTEXT_USER}
	{if $context_ref}
		{linkbutton href="!membres/fiche.php?id=%d"|args:$context_ref|local_url label="Fiche du membre" shape="user"}
	{/if}
{else}
	<ul>
	{foreach from=$breadcrumbs item="name" key="bc_path"}
		<li><a href="?path={$bc_path}">{$name}</a></li>
	{/foreach}
	</ul>
{/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 && $can_upload}
<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($list)}
<form method="post" action="{"!docs/action.php"|local_url}" target="_dialog">

	{if is_array($list)}

		<table class="list">
			<thead>
				<tr>
					{if $can_delete}
						<td class="check"><input type="checkbox" value="Tout cocher / décocher" id="f_all" /><label for="f_all"></label></td>
					{/if}
					<th>Nom</th>
					<td>Modifié</td>
					<td>Type</td>
					<td>Taille</td>
					<td></td>
				</tr>
			</thead>

			<tbody>

			{foreach from=$list 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="?path={$file.path}">{$file.name}</a></th>
					<td></td>
					<td>Répertoire</td>
					<td></td>
					<td class="actions">
					{if $can_write && ($context == File::CONTEXT_SKELETON || $context == File::CONTEXT_DOCUMENTS)}
						{linkbutton href="!common/files/rename.php?p=%s"|args:$file.path label="Renommer" shape="minus" target="_dialog"}
					{/if}
					{if $can_delete}
						{linkbutton href="!common/files/delete.php?p=%s"|args:$file.path label="Supprimer" shape="delete" target="_dialog"}
					{/if}
					</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->editorType()}
							{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"}
						{if $can_write}
							{linkbutton href="!common/files/rename.php?p=%s"|args:$file.path label="Renommer" shape="minus" target="_dialog"}
						{/if}
						{if $can_delete}
							{linkbutton href="!common/files/delete.php?p=%s"|args:$file.path label="Supprimer" shape="delete" target="_dialog"}
						{/if}
					</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 sélectionnés&nbsp;:</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>
					</td>
				</tr>
			</tfoot>
			{/if}
		</table>
	{elseif $list instanceof \Garradin\DynamicList}

		{include file="common/dynamic_list_head.tpl" check=false}


		{foreach from=$list->iterate() item="item"}
			<tr>
				{if $context == File::CONTEXT_TRANSACTION}
					<td class="num"><a href="{$admin_url}acc/transactions/details.php?id={$item.id}">#{$item.id}</a></td>
					<th><a href="?path={$item.path}">{$item.label}</a></th>
					<td>{$item.date|date_short}</td>
					<td>{$item.reference}</td>
					<td>{$item.year}</td>
					<td class="actions">
						{linkbutton href="!docs/?path=%s"|args:$item.path label="Fichiers" shape="menu"}
						{linkbutton href="!acc/transactions/details.php?id=%d"|args:$item.id label="Écriture" shape="search"}
					</td>
				{else}
					<td class="num"><a href="{$admin_url}membres/fiche.php?id={$item.id}">#{$item.number}</a></td>
					<th><a href="?path={$item.path}">{$item.identity}</a></th>
					<td class="actions">
						{linkbutton href="!docs/?path=%s"|args:$item.path label="Fichiers" shape="menu"}
						{linkbutton href="!membres/fiche.php?id=%d"|args:$item.id label="Fiche membre" shape="user"}
					</td>
				{/if}
			</tr>
		{/foreach}
		</tbody>
		</table>

		{pagination url=$list->paginationURL() page=$list.page bypage=$list.per_page total=$list->count()}

	{/if}

	<p class="actions">
		{linkbutton href="!docs/zip.php?path=%s"|args:$path label="Télécharger ce répertoire (ZIP)" shape="download"}
	</p>

</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"}

Added src/templates/me/edit.tpl version [30ffe59eb4].











































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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="Mes informations personnelles" current="me"}

<nav class="tabs">
	<ul>
		<li class="current"><a href="{$admin_url}me/">Mes informations personnelles</a></li>
		<li><a href="{$admin_url}me/security.php">Mot de passe et options de sécurité</a></li>
	</ul>
</nav>

{form_errors membre=1}

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

	<fieldset>
		<legend>Informations personnelles</legend>
		<dl>
			{foreach from=$champs item="champ" key="nom"}
			{if empty($champ.private) && $nom != 'passe'}
				{html_champ_membre config=$champ name=$nom data=$data user_mode=true}
			{/if}
			{/foreach}
		</dl>
	</fieldset>

	<fieldset>
		<legend>Changer mon mot de passe</legend>
		<p><a href="{$admin_url}me/security.php">Modifier mon mot de passe ou autres informations de sécurité.</a></p>
	</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"}

Added src/templates/me/export.tpl version [8a7de5d535].





































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<!DOCTYPE html>
<html>
<head>
	<title>Données utilisateur</title>
</head>

<body>
<h1>Données utilisateur</h1>
<p>Ce document contient une copie de toutes les données détenues sur vous par {$config.nom_asso}, conformément à la réglementation.</p>

<hr />

<h2>Profil</h2>

{include file="admin/membres/_details.tpl" champs=$champs_list data=$data show_message_button=false mode="export"}

<hr />

<h2>Inscriptions aux activités et cotisations</h2>

<table>
	<thead>
		<tr>
		{foreach from=$services_list->getHeaderColumns() key="key" item="column"}
			<th>{$column.label}</th>
		{/foreach}
		</tr>
	</thead>

	<tbody>

	{foreach from=$services_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">
			</td>
		</tr>
	{/foreach}

	</tbody>
</table>


</body>
</html>

Modified src/templates/me/index.tpl from [acc847c498] to [40ad0c52b7].

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="Mes informations personnelles" current="mes_infos"}

<nav class="tabs">
    <ul>
        <li class="current"><a href="{$admin_url}mes_infos.php">Mes informations personnelles</a></li>
        <li><a href="{$admin_url}mes_infos_securite.php">Mot de passe et options de sécurité</a></li>
    </ul>
</nav>

{form_errors membre=1}

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

    <fieldset>
        <legend>Informations personnelles</legend>
        <dl>
            {foreach from=$champs item="champ" key="nom"}
            {if empty($champ.private) && $nom != 'passe'}
                {html_champ_membre config=$champ name=$nom data=$membre user_mode=true}
            {/if}
            {/foreach}




        </dl>
    </fieldset>

    <fieldset>
        <legend>Changer mon mot de passe</legend>
            <p><a href="{$admin_url}mes_infos_securite.php">Modifier mon mot de passe ou autres informations de sécurité.</a></p>
    </fieldset>


    <p class="submit">
        {csrf_field key="edit_me"}
        {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
{include file="admin/_head.tpl" title="Mes informations personnelles" current="me"}

<nav class="tabs">
	<ul>
		<li class="current"><a href="{$admin_url}me/">Mes informations personnelles</a></li>
		<li><a href="{$admin_url}me/security.php">Mot de passe et options de sécurité</a></li>
	</ul>
</nav>


{if $ok !== null}

<p class="confirm block">

	Les modifications ont bien été enregistrées.
</p>



{/if}

<dl class="describe">
	<dd>
		{linkbutton href="!me/edit.php" label="Modifier mes informations" shape="edit"}
	</dd>
</dl>






{include file="admin/membres/_details.tpl" champs=$champs data=$data show_message_button=false mode="user"}

<p>


	{linkbutton href="!me/export.php" label="Télécharger toutes les données détenues sur moi" shape="download"}
</p>



{include file="admin/_foot.tpl"}

Modified src/templates/me/security.tpl from [99becf7d6d] to [c9bb6e985d].

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
{include file="admin/_head.tpl" title="Mes informations de connexion et sécurité" current="mes_infos"}

<nav class="tabs">
    <ul>
        <li><a href="{$admin_url}mes_infos.php">Mes informations personnelles</a></li>
        <li class="current"><a href="{$admin_url}mes_infos_securite.php">Mot de passe et options de sécurité</a></li>
    </ul>
</nav>

{if $ok}
<p class="block confirm">
    Changements enregistrés.
</p>
{/if}

{form_errors}

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

    {if !empty($otp) && $otp == 'disable'}
        <p class="block alert">
            Confirmez la désactivation de l'authentification à double facteur TOTP.
        </p>
    {elseif !empty($otp)}
        <p class="block alert">
            Confirmez l'activation de l'authentification à double facteur TOTP en l'utilisant une première fois.
        </p>

        <fieldset>
            <legend>Confirmer l'activation de l'authentification à double facteur (2FA)</legend>
            <img class="qrcode" src="{$otp.qrcode}" alt="" />
            <dl>
                <dt>Votre clé secrète est&nbsp;:</dt>
                <dd><code>{$otp.secret_display}</code></dd>
                <dd class="help">Recopiez la clé secrète ou scannez le QR code pour configurer votre application TOTP (par exemple <a href="https://freeotp.github.io/">FreeOTP</a>), puis utilisez celle-ci pour générer un code d'accès et confirmer l'activation.</dd>
                <dd class="help">Pour configurer une autre application, vous pouvez utiliser ces paramètres&nbsp;: <tt>{$otp.url}</tt></dd>
                <dt><label for="f_code">Code TOTP</label></dt>
                <dd class="help">Entrez ici le code donné par l'application d'authentification double facteur.</dd>
                <dd><input type="text" name="code" id="f_code" value="{form_field name=code}" autocomplete="off" /></dd>
            </dl>
        </fieldset>
    {/if}

    <fieldset>
        <legend>Confirmer les changements</legend>
        <dl>
            <dt><label for="f_passe_confirm">Mot de passe actuel</label></dt>
            <dd class="help">Entrez votre mot de passe actuel pour confirmer les changements demandés.</dd>
            <dd><input type="password" name="passe_check" autocomplete="current-password" /></dd>
        </dl>
    </fieldset>

    <p class="submit">
        {csrf_field key="edit_me_security"}
        <input type="hidden" name="passe" value="{form_field name="passe"}" />
        <input type="hidden" name="passe_confirmed" value="{form_field name="passe_confirmed"}" />
        <input type="hidden" name="clef_pgp" value="{form_field name="clef_pgp"}" />
        {if !empty($otp)}
        <input type="hidden" name="otp_secret" value="{$otp.secret}" />
        {/if}
        {button type="submit" name="confirm" label="Confirmer" shape="right" class="main"}
    </p>

    </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 
                        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" 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_passe_confirmed" value="{form_field name=passe_confirmed}" pattern="{$password_pattern}" autocomplete="new-password" /></dd>
                </dl>
            {/if}
        </fieldset>

        <fieldset>
            <legend>Authentification à double facteur (2FA)</legend>
            <p class="help">Pour renforcer la sécurité de votre connexion en cas de vol de votre mot de passe, vous pouvez activer
                l'authentification à double facteur. Cela nécessite d'installer une application comme <a href="https://freeotp.github.io/">FreeOTP</a>
                sur votre téléphone.</p>
            <dl>
                <dt>Authentification à double facteur (TOTP)</dt>
            {if $membre.secret_otp}
                {input type="radio" name="otp" value="" default="" label="Activée"}
                {input type="radio" name="otp" value="generate" label="Re-générer une nouvelle clé secrète" help="Si la clé a été compromise ou perdue"}
                {input type="radio" name="otp" value="disable" label="Désactiver l'authentification à double facteur"}
            {else}
                <dd><em>Désactivée</em></dd>
                {input type="checkbox" name="otp" value="generate" label="Activer"}
            {/if}
            </dl>
        </fieldset>

        {if $pgp_disponible}
        <fieldset>
            <legend>Protéger mes mails personnels par chiffrement PGP/GnuPG</legend>
            <dl>
                <dt><label for="f_clef_pgp">Ma clé publique PGP</label></dt>
                <dd class="help">En inscrivant ici votre clé publique, tous les emails personnels (non collectifs) qui vous
                    sont envoyés seront chiffrés (cryptés) avec cette clé&nbsp;: messages envoyés par les membres, rappels de cotisation,
                    procédure de récupération de mot de passe, etc.</dd>
                <dd><textarea name="clef_pgp" id="f_clef_pgp" cols="90" rows="5">{form_field name="clef_pgp" data=$user}</textarea></dd>
                {if $clef_pgp_fingerprint}<dd class="help">L'empreinte de la clé est&nbsp;: <code>{$clef_pgp_fingerprint}</code></dd>{/if}
            </dl>
            <p class="block alert">
                Attention&nbsp;: en inscrivant ici votre clé PGP, les emails de récupération de mot de passe perdu vous seront envoyés chiffrés
                et ne pourront être lus sans utiliser le mot de passe protégeant votre clé privée correspondante.
            </p>
        </fieldset>
        {/if}

        <p class="submit">
            {csrf_field key="edit_me_security"}
            {button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
        </p>

    </form>

    <script type="text/javascript">
    {literal}
    g.script('scripts/password.js', () => {
        initPasswordField('pw_suggest', 'f_passe', 'f_passe_confirmed');
    });
    {/literal}
    </script>
{/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
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
{include file="admin/_head.tpl" title="Mes informations de connexion et sécurité" current="me"}

<nav class="tabs">
	<ul>
		<li><a href="{$admin_url}me/">Mes informations personnelles</a></li>
		<li class="current"><a href="{$admin_url}me/security.php">Mot de passe et options de sécurité</a></li>
	</ul>
</nav>

{if $ok}
<p class="block confirm">
	Changements enregistrés.
</p>
{/if}

{form_errors}

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

	{if !empty($otp) && $otp == 'disable'}
		<p class="block alert">
			Confirmez la désactivation de l'authentification à double facteur TOTP.
		</p>
	{elseif !empty($otp)}
		<p class="block alert">
			Confirmez l'activation de l'authentification à double facteur TOTP en l'utilisant une première fois.
		</p>

		<fieldset>
			<legend>Confirmer l'activation de l'authentification à double facteur (2FA)</legend>
			<img class="qrcode" src="{$otp.qrcode}" alt="" />
			<dl>
				<dt>Votre clé secrète est&nbsp;:</dt>
				<dd><code>{$otp.secret_display}</code></dd>
				<dd class="help">Recopiez la clé secrète ou scannez le QR code pour configurer votre application TOTP (par exemple <a href="https://getaegis.app/" target="_blank">Aegis</a>), puis utilisez celle-ci pour générer un code d'accès et confirmer l'activation.</dd>
				<dd class="help">Pour configurer une autre application, vous pouvez utiliser ces paramètres&nbsp;: <tt>{$otp.url}</tt></dd>
				<dt><label for="f_code">Code TOTP</label></dt>
				<dd class="help">Entrez ici le code donné par l'application d'authentification double facteur.</dd>
				<dd><input type="text" name="code" id="f_code" value="{form_field name=code}" autocomplete="off" /></dd>
			</dl>
		</fieldset>
	{/if}

	<fieldset>
		<legend>Confirmer les changements</legend>
		<dl>
			<dt><label for="f_passe_confirm">Mot de passe actuel</label></dt>
			<dd class="help">Entrez votre mot de passe actuel pour confirmer les changements demandés.</dd>
			<dd><input type="password" name="passe_check" autocomplete="current-password" /></dd>
		</dl>
	</fieldset>

	<p class="submit">
		{csrf_field key="edit_me_security"}
		<input type="hidden" name="passe" value="{form_field name="passe"}" />
		<input type="hidden" name="passe_confirmed" value="{form_field name="passe_confirmed"}" />
		<input type="hidden" name="clef_pgp" value="{form_field name="clef_pgp"}" />
		{if !empty($otp)}
		<input type="hidden" name="otp_secret" value="{$otp.secret}" />
		{/if}
		{button type="submit" name="confirm" label="Confirmer" shape="right" class="main"}
	</p>

	</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 
						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" 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_passe_confirmed" value="{form_field name=passe_confirmed}" pattern="{$password_pattern}" autocomplete="new-password" /></dd>
				</dl>
			{/if}
		</fieldset>

		<fieldset>
			<legend>Authentification à double facteur (2FA)</legend>
			<p class="help">Pour renforcer la sécurité de votre connexion en cas de vol de votre mot de passe, vous pouvez activer
				l'authentification à double facteur. Cela nécessite d'installer une application comme <a href="https://getaegis.app/" target="_blank">Aegis</a>
				sur votre téléphone.</p>
			<dl>
				<dt>Authentification à double facteur (TOTP)</dt>
			{if $membre.secret_otp}
				{input type="radio" name="otp" value="" default="" label="Activée"}
				{input type="radio" name="otp" value="generate" label="Re-générer une nouvelle clé secrète" help="Si la clé a été compromise ou perdue"}
				{input type="radio" name="otp" value="disable" label="Désactiver l'authentification à double facteur"}
			{else}
				<dd><em>Désactivée</em></dd>
				{input type="checkbox" name="otp" value="generate" label="Activer"}
			{/if}
			</dl>
		</fieldset>

		{if $pgp_disponible}
		<fieldset>
			<legend>Protéger mes mails personnels par chiffrement PGP/GnuPG</legend>
			<dl>
				<dt><label for="f_clef_pgp">Ma clé publique PGP</label></dt>
				<dd class="help">En inscrivant ici votre clé publique, tous les emails personnels (non collectifs) qui vous
					sont envoyés seront chiffrés (cryptés) avec cette clé&nbsp;: messages envoyés par les membres, rappels de cotisation,
					procédure de récupération de mot de passe, etc.</dd>
				<dd><textarea name="clef_pgp" id="f_clef_pgp" cols="90" rows="5">{form_field name="clef_pgp" data=$user}</textarea></dd>
				{if $clef_pgp_fingerprint}<dd class="help">L'empreinte de la clé est&nbsp;: <code>{$clef_pgp_fingerprint}</code></dd>{/if}
			</dl>
			<p class="block alert">
				Attention&nbsp;: en inscrivant ici votre clé PGP, les emails de récupération de mot de passe perdu vous seront envoyés chiffrés
				et ne pourront être lus sans utiliser le mot de passe protégeant votre clé privée correspondante.
			</p>
		</fieldset>
		{/if}

		<p class="submit">
			{csrf_field key="edit_me_security"}
			{button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
		</p>

	</form>

	<script type="text/javascript">
	{literal}
	g.script('scripts/password.js', () => {
		initPasswordField('pw_suggest', 'f_passe', 'f_passe_confirmed');
	});
	{/literal}
	</script>
{/if}

{include file="admin/_foot.tpl"}

Modified src/templates/me/services.tpl from [79bef75320] to [4bbaabc663].

1
2
3
4
5
6
7
8
{include file="admin/_head.tpl" title="Mes activités & cotisations" current="my_services"}

<dl class="cotisation">
	<dt>Mes activités et cotisations</dt>
	{foreach from=$services item="service"}
	<dd>
		{$service.label}
		{if $service.status == -1 && $service.end_date} — terminée
|







1
2
3
4
5
6
7
8
{include file="admin/_head.tpl" title="Mes activités & cotisations" current="me/services"}

<dl class="cotisation">
	<dt>Mes activités et cotisations</dt>
	{foreach from=$services item="service"}
	<dd>
		{$service.label}
		{if $service.status == -1 && $service.end_date} — terminée

Modified src/templates/services/_nav.tpl from [a7923367e8] to [0eb2ad0dc5].

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
<nav class="tabs">
	<ul>
		<li{if $current == 'index'} class="current"{/if}><a href="{$admin_url}services/">Activités et cotisations</a></li>

		<li{if $current == 'save'} class="current"{/if}><a href="{$admin_url}services/save.php">Inscrire à une activité</a></li>

		{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">
			{$current_service.label} —
			{if $current_service.duration}
				{$current_service.duration} jours
			{elseif $current_service.start_date}
				du {$current_service.start_date|date_short} au {$current_service.end_date|date_short}
			{else}
				ponctuelle
			{/if}
		</li>
		<li{if $service_page == 'index'} class="current"{/if}><a href="{$admin_url}services/fees/?id={$current_service.id}"><strong>Gestion des tarifs</strong></a></li>
		<li{if $service_page == 'paid'} class="current"{/if}><a href="{$admin_url}services/details.php?id={$current_service.id}">À jour et payés</a></li>
		<li{if $service_page == 'expired'} class="current"{/if}><a href="{$admin_url}services/details.php?id={$current_service.id}&amp;type=expired">Inscription expirée</a></li>
		<li{if $service_page == 'unpaid'} class="current"{/if}><a href="{$admin_url}services/details.php?id={$current_service.id}&amp;type=unpaid">En attente de règlement</a></li>
	</ul>
	{/if}

	{if isset($current_fee)}



>
|
>
|
















|







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
<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/user/add.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">
			{$current_service.label} —
			{if $current_service.duration}
				{$current_service.duration} jours
			{elseif $current_service.start_date}
				du {$current_service.start_date|date_short} au {$current_service.end_date|date_short}
			{else}
				ponctuelle
			{/if}
		</li>
		<li{if $service_page == 'index'} class="current"{/if}><a href="{$admin_url}services/fees/?id={$current_service.id}"><strong>Tarifs</strong></a></li>
		<li{if $service_page == 'paid'} class="current"{/if}><a href="{$admin_url}services/details.php?id={$current_service.id}">À jour et payés</a></li>
		<li{if $service_page == 'expired'} class="current"{/if}><a href="{$admin_url}services/details.php?id={$current_service.id}&amp;type=expired">Inscription expirée</a></li>
		<li{if $service_page == 'unpaid'} class="current"{/if}><a href="{$admin_url}services/details.php?id={$current_service.id}&amp;type=unpaid">En attente de règlement</a></li>
	</ul>
	{/if}

	{if isset($current_fee)}

Modified src/templates/services/delete.tpl from [e828c3fad7] to [19b7097afc].

1
2
3
4
5
6

7
8
9
10
11
{include file="admin/_head.tpl" title="Supprimer une activité" current="membres/services"}

{include file="services/_nav.tpl" current="index"}

{include file="common/delete_form.tpl"
	legend="Supprimer cette activité ?"

	warning="Êtes-vous sûr de vouloir supprimer l'activité « %s » ?"|args:$service.label
	alert="Attention, cela supprimera également l'historique des membres inscrits à cette activité, ainsi que les rappels associés."
	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"}






>

|



1
2
3
4
5
6
7
8
9
10
11
12
{include file="admin/_head.tpl" title="Supprimer une activité" current="membres/services"}

{include file="services/_nav.tpl" current="index"}

{include file="common/delete_form.tpl"
	legend="Supprimer cette activité ?"
	confirm="Cocher cette case pour supprimer l'activité, les tarifs associés, toutes les inscriptions et les rappels !"
	warning="Êtes-vous sûr de vouloir supprimer l'activité « %s » ?"|args:$service.label
	alert="Attention, cela supprimera également tous les tarifs, mais aussi l'historique des membres inscrits à cette activité, ainsi que les rappels associés."
	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"}

Modified src/templates/services/details.tpl from [61301fabc6] to [0d42873582].

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
{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"}

	{foreach from=$list->iterate() item="row"}
		<tr>




			<th><a href="../membres/fiche.php?id={$row.id_user}">{$row.identity}</a></th>
			<td>
				{if $row.status == 1 && $row.end_date}
					En cours
				{elseif $row.status == 1}
					<b class="confirm">À jour</b>
				{elseif $row.status == -1 && $row.end_date}
					Terminée
				{elseif $row.status == -1}
					<b class="error">En retard</b>
				{else}
					Pas d'expiration
				{/if}
			</td>
			<td>{if $row.paid}<b class="confirm">Oui</b>{else}<b class="error">Non</b>{/if}</td>
			<td>{$row.expiry|date_short}</td>
			<td>{$row.fee}</td>
			<td>{$row.date|date_short}</td>
			<td class="actions">
				{linkbutton shape="user" label="Toutes les activités de ce membre" href="!services/user.php?id=%d"|args:$row.id_user}
				{*FIXME TODO linkbutton shape="alert" label="Rappels envoyés" href="!services/reminders/user.php?id=%d"|args:$row.id_user*}
			</td>
		</tr>
	{/foreach}

	</tbody>




</table>





{pagination url=$list->paginationURL() page=$list.page bypage=$list.per_page total=$list->count()}


{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
{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>

<?php
$can_action = $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);
?>

{if $can_action}
	<form method="post" action="{"!membres/action.php"|local_url}">
{/if}

{include file="common/dynamic_list_head.tpl" check=$can_action}

	{foreach from=$list->iterate() item="row"}
		<tr>
			{if $can_action}
			<td class="check">{input type="checkbox" name="selected[]" value=$row.id_user}</td>
			{/if}

			<th><a href="../membres/fiche.php?id={$row.id_user}">{$row.identity}</a></th>
			<td>
				{if $row.status == 1 && $row.end_date}
					En cours
				{elseif $row.status == 1}
					<b class="confirm">À jour</b>
				{elseif $row.status == -1 && $row.end_date}
					Terminée
				{elseif $row.status == -1}
					<b class="error">En retard</b>
				{else}
					Pas d'expiration
				{/if}
			</td>
			<td>{if $row.paid}<b class="confirm">Oui</b>{else}<b class="error">Non</b>{/if}</td>
			<td>{$row.expiry|date_short}</td>
			<td>{$row.fee}</td>
			<td>{$row.date|date_short}</td>
			<td class="actions">
				{linkbutton shape="user" label="Toutes les activités de ce membre" href="!services/user/?id=%d"|args:$row.id_user}
				{linkbutton shape="alert" label="Rappels envoyés" href="!services/reminders/user.php?id=%d"|args:$row.id_user}
			</td>
		</tr>
	{/foreach}

	</tbody>
	{if $can_action}
		{include file="admin/membres/_list_actions.tpl" colspan=7 export=false}
	{/if}

</table>

{if $can_action}
</form>
{/if}

{pagination url=$list->paginationURL() page=$list.page bypage=$list.per_page total=$list->count()}


{include file="admin/_foot.tpl"}

Modified src/templates/services/fees/_fee_form.tpl from [d8e5596d6c] to [9d5c15a2e4].

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
				</dl>
			</dd>
			{input name="amount_type" type="radio" value="2" label="Montant variable" default=$amount_type}
			<dd class="amount_type_2">
				<dl>
					{input name="formula" type="textarea" label="Formule de calcul" source=$fee fake_required=1}
					<dd class="help">
						<a href="https://fossil.kd2.org/garradin/wiki?name=Formule_calcul_activit%C3%A9">Aide sur les formules de calcul</a>
					</dd>
				</dl>
			</dd>
			<dt><strong>Comptabilité</strong></dt>
			{input name="accounting" type="checkbox" value="1" label="Enregistrer en comptabilité" default=$accounting_enabled}
			<dd class="help">Laissez cette case décochée si vous n'utilisez pas Garradin pour la comptabilité. Il ne sera pas possible de suivre le montant des règlements effectués pour ce tarif.</dd>
		</dl>
	</fieldset>

	<fieldset class="accounting">
		<legend>Enregistrer en comptabilité</legend>
		<p class="help">Chaque règlement d'un membre lié à ce tarif sera enregistré dans la comptabilité, permettant de suivre le montant des règlements effectués.</p>
		{if !count($years)}
			<p class="error block">Il n'y a aucun exercice ouvert dans la comptabilité, il n'est donc pas possible d'enregistrer les activités dans la comptabilité. Merci de commencer par <a href="{$admin_url}acc/years/new.php">créer un exercice</a>.</p>
		{else}
		<dl>
			<dt><label for="f_id_year">Exercice</label> <b>(obligatoire)</b></dt>
			<dd>
				<select id="f_id_year" name="id_year">

					{foreach from=$years item="year"}
					<option value="{$year.id}"{if $year.id == $fee.id_year} selected="selected"{/if}>{$year.label} — {$year.start_date|date_short} au {$year.end_date|date_short}</option>
					{/foreach}
				</select>
			</dd>
			{input type="list" target="acc/charts/accounts/selector.php?targets=%s&year=%d"|args:$targets,$fee.id_year name="account" label="Compte à utiliser" default=$account required=1}
		</dl>







|



















>







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
				</dl>
			</dd>
			{input name="amount_type" type="radio" value="2" label="Montant variable" default=$amount_type}
			<dd class="amount_type_2">
				<dl>
					{input name="formula" type="textarea" label="Formule de calcul" source=$fee fake_required=1}
					<dd class="help">
						<a href="https://garradin.eu/Formule-calcul-activite">Aide sur les formules de calcul</a>
					</dd>
				</dl>
			</dd>
			<dt><strong>Comptabilité</strong></dt>
			{input name="accounting" type="checkbox" value="1" label="Enregistrer en comptabilité" default=$accounting_enabled}
			<dd class="help">Laissez cette case décochée si vous n'utilisez pas Garradin pour la comptabilité. Il ne sera pas possible de suivre le montant des règlements effectués pour ce tarif.</dd>
		</dl>
	</fieldset>

	<fieldset class="accounting">
		<legend>Enregistrer en comptabilité</legend>
		<p class="help">Chaque règlement d'un membre lié à ce tarif sera enregistré dans la comptabilité, permettant de suivre le montant des règlements effectués.</p>
		{if !count($years)}
			<p class="error block">Il n'y a aucun exercice ouvert dans la comptabilité, il n'est donc pas possible d'enregistrer les activités dans la comptabilité. Merci de commencer par <a href="{$admin_url}acc/years/new.php">créer un exercice</a>.</p>
		{else}
		<dl>
			<dt><label for="f_id_year">Exercice</label> <b>(obligatoire)</b></dt>
			<dd>
				<select id="f_id_year" name="id_year">
					<option value="">-- Sélectionner un exercice</option>
					{foreach from=$years item="year"}
					<option value="{$year.id}"{if $year.id == $fee.id_year} selected="selected"{/if}>{$year.label} — {$year.start_date|date_short} au {$year.end_date|date_short}</option>
					{/foreach}
				</select>
			</dd>
			{input type="list" target="acc/charts/accounts/selector.php?targets=%s&year=%d"|args:$targets,$fee.id_year name="account" label="Compte à utiliser" default=$account required=1}
		</dl>

Modified src/templates/services/fees/delete.tpl from [ab39799ac0] to [600a2693ac].

1
2
3
4
5
6

7
8
9
10
11
{include file="admin/_head.tpl" title="Supprimer un tarif" current="membres/services"}

{include file="services/_nav.tpl" current="index"}

{include file="common/delete_form.tpl"
	legend="Supprimer ce tarif ?"

	warning="Êtes-vous sûr de vouloir supprimer le tarif « %s » ?"|args:$fee.label
	alert="Attention, cela supprimera également l'historique des membres ayant réglé ce tarif."
	info="Les écritures comptables liées à l'historique des membres ayant réglé ce tarif ne seront pas supprimées, et la comptabilité demeurera inchangée."}

{include file="admin/_foot.tpl"}






>





1
2
3
4
5
6
7
8
9
10
11
12
{include file="admin/_head.tpl" title="Supprimer un tarif" current="membres/services"}

{include file="services/_nav.tpl" current="index"}

{include file="common/delete_form.tpl"
	legend="Supprimer ce tarif ?"
	confirm="Cocher cette case pour confirmer la suppression de ce tarif et de tout l'historique des membres !"
	warning="Êtes-vous sûr de vouloir supprimer le tarif « %s » ?"|args:$fee.label
	alert="Attention, cela supprimera également l'historique des membres ayant réglé ce tarif."
	info="Les écritures comptables liées à l'historique des membres ayant réglé ce tarif ne seront pas supprimées, et la comptabilité demeurera inchangée."}

{include file="admin/_foot.tpl"}

Modified src/templates/services/fees/details.tpl from [bab86fda03] to [614b52eea9].

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
{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"}

	{foreach from=$list->iterate() item="row"}
		<tr>



			<th><a href="../../membres/fiche.php?id={$row.id_user}">{$row.identity}</a></th>
			<td>{if $row.paid}<b class="confirm">Oui</b>{else}<b class="error">Non</b>{/if}</td>
			<td class="money">{$row.paid_amount|raw|money_currency}</td>
			<td>{$row.date|date_short}</td>
			<td class="actions">
				{linkbutton shape="user" label="Toutes les activités de ce membre" href="!services/user.php?id=%d"|args:$row.id_user}
				{* FIXME TODO {linkbutton shape="alert" label="Rappels envoyés" href="!services/reminders/user.php?id=%d"|args:$row.id_user} *}
			</td>
		</tr>
	{/foreach}

	</tbody>





</table>





{pagination url=$list->paginationURL() page=$list.page bypage=$list.per_page total=$list->count()}


{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
{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>

<?php
$can_action = $session->canAccess($session::SECTION_USERS, $session::ACCESS_ADMIN);
?>

{if $can_action}
	<form method="post" action="{"!membres/action.php"|local_url}">
{/if}

{include file="common/dynamic_list_head.tpl" check=$can_action}

	{foreach from=$list->iterate() item="row"}
		<tr>
			{if $can_action}
			<td class="check">{input type="checkbox" name="selected[]" value=$row.id_user}</td>
			{/if}
			<th><a href="../../membres/fiche.php?id={$row.id_user}">{$row.identity}</a></th>
			<td>{if $row.paid}<b class="confirm">Oui</b>{else}<b class="error">Non</b>{/if}</td>
			<td class="money">{$row.paid_amount|raw|money_currency}</td>
			<td>{$row.date|date_short}</td>
			<td class="actions">
				{linkbutton shape="user" label="Toutes les activités de ce membre" href="!services/user/?id=%d"|args:$row.id_user}
				{linkbutton shape="alert" label="Rappels envoyés" href="!services/reminders/user.php?id=%d"|args:$row.id_user}
			</td>
		</tr>
	{/foreach}

	</tbody>

	{if $can_action}
		{include file="admin/membres/_list_actions.tpl" colspan=5 export=false}
	{/if}

</table>

{if $can_action}
</form>
{/if}

{pagination url=$list->paginationURL() page=$list.page bypage=$list.per_page total=$list->count()}


{include file="admin/_foot.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"}

Added src/templates/services/reminders/user.tpl version [f448277717].























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{include file="admin/_head.tpl" title="Rappels envoyés à un membre" current="membres/services"}

<nav class="tabs">
	<ul>
		<li><a href="{$admin_url}membres/fiche.php?id={$user_id}">Fiche membre</a></li>
		<li class="current"><a href="{$self_url}">Liste des rappels envoyés</a></li>
	</ul>
</nav>

{include file="common/dynamic_list_head.tpl"}

	{foreach from=$list->iterate() item="row"}
		<tr>
			<th>{$row.label}</th>
			<td>{if $row.delay > 0}{$row.delay} jours après l'expiration{elseif $row.delay < 0}{$row.delay|abs} jours avant l'expiration{else}le jour de l'expiration{/if}</td>
			<td>{$row.date|date_short}</td>
			<td></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/services/user/_choice_form.tpl version [2bdf0b250d].































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<dl>

	<dt><label for="f_service_ID">Activité</label> <b>(obligatoire)</b></dt>

	{foreach from=$grouped_services item="service"}
		<dd class="radio-btn">
			{input type="radio" name="id_service" value=$service.id data-duration=$service.duration data-expiry=$service.expiry_date|date_short label=null}
			<label for="f_id_service_{$service.id}">
				<div>
					<h3>{$service.label}</h3>
					<p>
						{if $service.duration}
							{$service.duration} jours
						{elseif $service.start_date}
							du {$service.start_date|date_short} au {$service.end_date|date_short}
						{else}
							ponctuelle
						{/if}
					</p>
					{if $service.description}
					<p class="help">
						{$service.description|escape|nl2br}
					</p>
					{/if}
				</div>
			</label>
		</dd>
	{foreachelse}
		<dd><p class="error block">Aucune activité trouvée</p></dd>
	{/foreach}

</dl>

{foreach from=$grouped_services item="service"}
<?php if (!count($service->fees)) { continue; } ?>
<dl data-service="s{$service.id}">
	<dt><label for="f_fee">Tarif</label> <b>(obligatoire)</b></dt>
	{foreach from=$service.fees key="service_id" item="fee"}
	<dd class="radio-btn">
		{input type="radio" name="id_fee" value=$fee.id data-user-amount=$fee.user_amount data-account=$fee.id_account data-year=$fee.id_year label=null}
		<label for="f_id_fee_{$fee.id}">
			<div>
				<h3>{$fee.label}</h3>
				<p>
					{if !$fee.user_amount}
						prix libre ou gratuit
					{elseif $fee.user_amount && $fee.formula}
						<strong>{$fee.user_amount|raw|money_currency}</strong> (montant calculé)
					{elseif $fee.user_amount}
						<strong>{$fee.user_amount|raw|money_currency}</strong>
					{/if}
				</p>
				{if $fee.description}
				<p class="help">
					{$fee.description|escape|nl2br}
				</p>
				{/if}
			</div>
		</label>
	</dd>
	{/foreach}
</dl>
{/foreach}

Added src/templates/services/user/_service_user_form.tpl version [c3ab4accdb].





































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
assert(isset($create) && is_bool($create));
assert(isset($has_past_services) && is_bool($has_past_services));
assert(isset($current_only) && is_bool($current_only));
assert(!empty($user_name) && !empty($user_id));
assert(isset($form_url) && is_string($form_url));
assert(isset($today) && $today instanceof \DateTimeInterface);
assert($create === false || isset($account_targets));
assert(isset($grouped_services) && is_array($grouped_services));
?>

<form method="post" action="{$self_url}" data-focus="1" data-create="{$create|escape:json}">

	{if $has_past_services}
	<nav class="tabs">
		<ul class="sub">
			<li{if $current_only} class="current"{/if}><a href="{$form_url}">Inscrire à une activité courante</a></li>
			<li{if !$current_only} class="current"{/if}><a href="{$form_url}past_services=1">Inscrire à une activité passée</a></li>
		</ul>
	</nav>
	{/if}

	<fieldset>
		<legend>Inscrire un membre à une activité</legend>

		<dl>
			<dt>Membre sélectionné</dt>
			<dd><h3>{$user_name}</h3><input type="hidden" name="id_user" value="{$user_id}" /></dd>

			<dt><label for="f_service_ID">Activité</label> <b>(obligatoire)</b></dt>

			{foreach from=$grouped_services item="service"}
				<dd class="radio-btn">
					{input type="radio" name="id_service" value=$service.id data-duration=$service.duration data-expiry=$service.expiry_date|date_short label=null source=$service_user}
					<label for="f_id_service_{$service.id}">
						<div>
							<h3>{$service.label}</h3>
							<p>
								{if $service.duration}
									{$service.duration} jours
								{elseif $service.start_date}
									du {$service.start_date|date_short} au {$service.end_date|date_short}
								{else}
									ponctuelle
								{/if}
							</p>
							{if $service.description}
							<p class="help">
								{$service.description|escape|nl2br}
							</p>
							{/if}
						</div>
					</label>
				</dd>
			{foreachelse}
				<dd><p class="error block">Aucune activité trouvée</p></dd>
			{/foreach}

		</dl>

		{foreach from=$grouped_services item="service"}
		<?php if (!count($service->fees)) { continue; } ?>
		<dl data-service="s{$service.id}">
			<dt><label for="f_fee">Tarif</label> <b>(obligatoire)</b></dt>
			{foreach from=$service.fees key="service_id" item="fee"}
			<dd class="radio-btn">
				{input type="radio" name="id_fee" value=$fee.id data-user-amount=$fee.user_amount data-account=$fee.id_account data-year=$fee.id_year label=null source=$service_user }
				<label for="f_id_fee_{$fee.id}">
					<div>
						<h3>{$fee.label}</h3>
						<p>
							{if !$fee.user_amount}
								prix libre ou gratuit
							{elseif $fee.user_amount && $fee.formula}
								<strong>{$fee.user_amount|raw|money_currency}</strong> (montant calculé)
							{elseif $fee.user_amount}
								<strong>{$fee.user_amount|raw|money_currency}</strong>
							{/if}
						</p>
						{if $fee.description}
						<p class="help">
							{$fee.description|escape|nl2br}
						</p>
						{/if}
					</div>
				</label>
			</dd>
			{/foreach}
		</dl>
		{/foreach}

	</fieldset>


	</fieldset>

	<fieldset>
		<legend>Détails</legend>
		<dl>
			{input type="date" name="date" required=1 default=$today source=$service_user label="Date d'inscription"}
			{input type="date" name="expiry_date" source=$service_user label="Date d'expiration de l'inscription"}
			{input type="checkbox" name="paid" value="1" source=$service_user default="1" label="Marquer cette inscription comme payée"}
			<dd class="help">Décocher cette case pour pouvoir suivre les règlements de personnes qui payent en plusieurs fois. Il sera possible de cocher cette case lorsque le solde aura été réglé.</dd>
		</dl>
	</fieldset>

	{if $create}
	<fieldset class="accounting">
		<legend>{input type="checkbox" name="create_payment" value=1 default=1 label="Enregistrer en comptabilité"}</legend>

		<dl>
			{input type="money" name="amount" label="Montant réglé par le membre" fake_required=1 help="En cas de règlement en plusieurs fois il sera possible d'ajouter des règlements via la page de suivi des activités de ce membre."}
			{input type="list" target="acc/charts/accounts/selector.php?targets=%s"|args:$account_targets name="account" label="Compte de règlement" fake_required=1}
			{input type="text" name="reference" label="Numéro de pièce comptable" help="Numéro de facture, de note de frais, etc."}
			{input type="text" name="payment_reference" label="Référence de paiement" help="Numéro de chèque, numéro de transaction CB, etc."}
			{input type="textarea" name="notes" label="Remarques"}
		</dl>
	</fieldset>
	{/if}

	<p class="submit">
		{csrf_field key=$csrf_key}
		{button type="submit" name="save" label="Enregistrer" shape="right" class="main"}

		{if $create}
			{button type="submit" name="save_and_add_payment" class="accounting" label="Enregistrer et ajouter un autre règlement" shape="plus"}
		{/if}
	</p>

</form>

Modified src/templates/services/user/add.tpl from [f442aa1d24] to [f7d8e48aef].

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
{include file="admin/_head.tpl" title="Enregistrer un règlement" current="membres/services"}

{include file="services/_nav.tpl" current="save" fee=null service=null}

<form method="post" action="{$self_url}" data-focus="1">

	{if $user_id && $has_past_services}
	<nav class="tabs">
		<ul class="sub">
			<li{if $current_only} class="current"{/if}><a href="?user={$user_id}">Inscrire à une activité courante</a></li>
			<li{if !$current_only} class="current"{/if}><a href="?user={$user_id}&amp;past_services=1">Inscrire à une activité passée</a></li>
		</ul>
	</nav>
	{/if}

{form_errors}
	<fieldset>
		<legend>Inscrire un membre à une activité</legend>

{if !$user_id}
		<dl>
			{input type="list" name="user" required=1 label="Sélectionner un membre" default=$selected_user target="membres/selector.php"}
		</dl>
{else}
		<dl>
			<dt>Membre sélectionné</dt>
			<dd><h3>{$user_name}</h3><input type="hidden" name="id_user" value="{$user_id}" /></dd>
			<dt><label for="f_service_ID">Activité</label> <b>(obligatoire)</b></dt>

		{foreach from=$grouped_services item="service"}
			<dd class="radio-btn">
				{input type="radio" name="id_service" value=$service.id data-expiry=$service.expiry_date|date_short label=null}
				<label for="f_id_service_{$service.id}">
					<div>
						<h3>{$service.label}</h3>
						<p>
							{if $service.duration}
								{$service.duration} jours
							{elseif $service.start_date}
								du {$service.start_date|date_short} au {$service.end_date|date_short}
							{else}
								ponctuelle
							{/if}
						</p>
						{if $service.description}
						<p class="help">
							{$service.description|escape|nl2br}
						</p>
						{/if}
					</div>
				</label>
			</dd>
		{foreachelse}
			<dd><p class="error block">Aucune activité trouvée</p></dd>
		{/foreach}

		</dl>

		{foreach from=$grouped_services item="service"}
		<?php if (!count($service->fees)) { continue; } ?>
		<dl data-service="s{$service.id}">
			<dt><label for="f_fee">Tarif</label> <b>(obligatoire)</b></dt>
			{foreach from=$service.fees key="service_id" item="fee"}
			<dd class="radio-btn">
				{input type="radio" name="id_fee" value=$fee.id data-user-amount=$fee.user_amount data-account=$fee.id_account label=null}
				<label for="f_id_fee_{$fee.id}">
					<div>
						<h3>{$fee.label}</h3>
						<p>
							{if !$fee.user_amount}
								prix libre ou gratuit
							{elseif $fee.user_amount && $fee.formula}
								<strong>{$fee.user_amount|raw|money_currency}</strong> (montant calculé)
							{elseif $fee.user_amount}
								<strong>{$fee.user_amount|raw|money_currency}</strong>
							{/if}
						</p>
						{if $fee.description}
						<p class="help">
							{$fee.description|escape|nl2br}
						</p>
						{/if}
					</div>
				</label>
			</dd>
			{/foreach}
		</dl>
		{/foreach}
	</fieldset>

	<fieldset>
		<legend>Détails</legend>
		<dl>
			{input type="date" name="date" required=1 default=$today label="Date d'inscription"}
			{input type="date" name="expiry_date" label="Date d'expiration de l'inscription"}
			{input type="checkbox" name="paid" value="1" default="1" label="Marquer cette inscription comme payée"}
			<dd class="help">Décocher cette case pour pouvoir suivre les règlements de personnes qui payent en plusieurs fois. Il sera possible de cocher cette case lorsque le solde aura été réglé.</dd>
		</dl>
	</fieldset>

	<fieldset class="accounting">
		<legend>{input type="checkbox" name="create_payment" value=1 default=1 label="Enregistrer en comptabilité"}</legend>

		<dl>
			{input type="money" name="amount" label="Montant réglé par le membre" fake_required=1 help="En cas de règlement en plusieurs fois il sera possible d'ajouter des règlements via la page de suivi des activités de ce membre."}
			{input type="list" target="acc/charts/accounts/selector.php?targets=%s"|args:$account_targets name="account" label="Compte de règlement" required=1}
			{input type="text" name="reference" label="Numéro de pièce comptable" help="Numéro de facture, de note de frais, etc."}
			{input type="text" name="payment_reference" label="Référence de paiement" help="Numéro de chèque, numéro de transaction CB, etc."}
		</dl>
{/if}
	</fieldset>

	<p class="submit">
		{csrf_field key=$csrf_key}
		{if $user_id}
			{button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
		{else}
			{button type="submit" name="next" label="Continuer" shape="right" class="main"}
		{/if}
	</p>

</form>

{literal}
<script type="text/javascript">
function selectService(elm, first_load) {
	$('[data-service]').forEach((e) => {
		e.style.display = ('s' + elm.value == e.getAttribute('data-service')) ? 'block' : 'none';
	});

	let expiry = $('#f_expiry_date');

	if (!first_load || !expiry.value) {
		expiry.value = elm.dataset.expiry;
	}

	var first = document.querySelector('[data-service="s' + elm.value + '"] input[name=id_fee]');

	if (first) {
		first.checked = true;
		selectFee(first, first_load);
	}
}

function selectFee(elm, first_load) {
	var amount = parseInt(elm.getAttribute('data-user-amount'), 10);

	// Toggle accounting part of the form
	var accounting = elm.getAttribute('data-account') ? true : false;
	g.toggle('.accounting', accounting);
	$('#f_amount').required = accounting;

	// Fill the amount paid by the user
	if (amount && !first_load) {
		$('#f_amount').value = g.formatMoney(amount);
	}
}

$('input[name=id_service]').forEach((e) => {
	e.onchange = () => { selectService(e); };
});

$('input[name=id_fee]').forEach((e) => {
	e.onchange = () => { selectFee(e); };
});

var selected = document.querySelector('input[name="id_service"]:checked') || document.querySelector('input[name="id_service"]');
selected.checked = true;

g.toggle('.accounting', false);
selectService(selected, true);

$('#f_create_payment_1').onchange = (e) => {
	g.toggle('.accounting dl', $('#f_create_payment_1').checked);
};
</script>
{/literal}

{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
{include file="admin/_head.tpl" title="Inscrire à une activité" current="membres/services"}

{include file="services/_nav.tpl" current="save" fee=null service=null}












{form_errors}



{if !$user_id}








<form method="post" action="{$self_url}" data-focus="1">





























































	<fieldset>
		<legend>Inscrire un membre à une activité</legend>
		<dl>






			{input type="list" name="user" required=1 label="Sélectionner un membre" default=$selected_user target="membres/selector.php"}








		</dl>

	</fieldset>

	<p class="submit">
		{csrf_field key=$csrf_key}



		{button type="submit" name="next" label="Continuer" shape="right" class="main"}

	</p>

</form>
{else}








	{include file="services/user/_service_user_form.tpl" create=true}



{/if}










































{include file="admin/_foot.tpl"}

Modified src/templates/services/user/delete.tpl from [e256118085] to [191f44fc8d].

1
2
3
4
5
6
7
8

9
10
{include file="admin/_head.tpl" title="Supprimer une inscription" current="membres/services"}

{include file="services/_nav.tpl" current="index"}

{include file="common/delete_form.tpl"
	legend="Supprimer cette inscription ?"
	warning="Êtes-vous sûr de vouloir supprimer cette inscription ?"
	info="Les écritures comptables liées à cette inscription ne seront pas supprimées, la comptabilité demeurera inchangée."}


{include file="admin/_foot.tpl"}
|

<
<

|
|
|
>


1
2


3
4
5
6
7
8
9
{include file="admin/_head.tpl" title="%s : Supprimer une inscription"|args:$user_name current="membres/services"}



{include file="common/delete_form.tpl"
	legend="Supprimer l'inscription ?"
	warning="Êtes-vous sûr de vouloir supprimer l'inscription ?"
	alert="Les écritures comptables liées à cette inscription ne seront pas supprimées, la comptabilité demeurera inchangée."
	info="%s – à « %s — %s »"|args:$user_name,$service_name,$fee_name}

{include file="admin/_foot.tpl"}

Added src/templates/services/user/edit.tpl version [60f58e104c].















>
>
>
>
>
>
>
1
2
3
4
5
6
7
{include file="admin/_head.tpl" title="Modifier une inscription" current="membres/services"}

{form_errors}

{include file="services/user/_service_user_form.tpl" create=false}

{include file="admin/_foot.tpl"}

Modified src/templates/services/user/index.tpl from [dbd53507fd] to [0bde5bd459].

1
2
3
4
5
6
7
8
9
10
11
12
{include file="admin/_head.tpl" title="%s — Inscriptions aux activités et cotisations"|args:$user.identite current="membres/services"}

<p>
	{linkbutton href="!membres/fiche.php?id=%d"|args:$user.id label="Retour à la fiche membre" shape="user"}
	{linkbutton href="!services/save.php?user=%d"|args:$user.id label="Inscrire à une activité" shape="plus"}
</p>

{form_errors}

<dl class="cotisation">
	<dt>Statut des inscriptions</dt>
	{foreach from=$services item="service"}




|







1
2
3
4
5
6
7
8
9
10
11
12
{include file="admin/_head.tpl" title="%s — Inscriptions aux activités et cotisations"|args:$user.identite current="membres/services"}

<p>
	{linkbutton href="!membres/fiche.php?id=%d"|args:$user.id label="Retour à la fiche membre" shape="user"}
	{linkbutton href="!services/user/add.php?user=%d"|args:$user.id label="Inscrire à une activité" shape="plus"}
</p>

{form_errors}

<dl class="cotisation">
	<dt>Statut des inscriptions</dt>
	{foreach from=$services item="service"}
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
73
	<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="?id=%d&export=csv"|args:$user.id shape="export" label="Export CSV"}
			{linkbutton href="?id=%d&export=ods"|args:$user.id 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="edit" label="Modifier" href="edit.php?id=%d"|args:$row.id}
					{linkbutton shape="delete" label="Supprimer" href="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"}

Modified src/templates/services/user/payment.tpl from [10d2082879] to [c4cd0c545e].

8
9
10
11
12
13
14

15
16
17
18
19
20
21
22
23
24

25
26
27
28
29
		<legend>Enregistrer un règlement</legend>

		<dl>
			<dt>Membre sélectionné</dt>
			<dd><h3>{$user_name}</h3></dd>
			<dt><strong>Inscription</strong></dt>
			{input type="checkbox" name="paid" value="1" default=$su.paid label="Marquer cette inscription comme payée"}

			{input type="money" name="amount" label="Montant réglé par le membre" required=1}
			{input type="list" target="acc/charts/accounts/selector.php?targets=%s"|args:$account_targets name="account" label="Compte de règlement" required=1}
			{input type="text" name="reference" label="Numéro de pièce comptable" help="Numéro de facture, de note de frais, etc."}
			{input type="text" name="payment_reference" label="Référence de paiement" help="Numéro de chèque, numéro de transaction CB, etc."}
		</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"}







>










>





8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
		<legend>Enregistrer un règlement</legend>

		<dl>
			<dt>Membre sélectionné</dt>
			<dd><h3>{$user_name}</h3></dd>
			<dt><strong>Inscription</strong></dt>
			{input type="checkbox" name="paid" value="1" default=$su.paid label="Marquer cette inscription comme payée"}
			{input type="date" name="date" label="Date" required=1 source=$su}
			{input type="money" name="amount" label="Montant réglé par le membre" required=1}
			{input type="list" target="acc/charts/accounts/selector.php?targets=%s"|args:$account_targets name="account" label="Compte de règlement" required=1}
			{input type="text" name="reference" label="Numéro de pièce comptable" help="Numéro de facture, de note de frais, etc."}
			{input type="text" name="payment_reference" label="Référence de paiement" help="Numéro de chèque, numéro de transaction CB, etc."}
		</dl>
	</fieldset>

	<p class="submit">
		{csrf_field key=$csrf_key}
		{button type="submit" name="save" label="Enregistrer" shape="right" class="main"}
		{button type="submit" name="save_and_add_payment" label="Enregistrer et ajouter un autre règlement" shape="plus"}
	</p>

</form>

{include file="admin/_foot.tpl"}

Modified src/templates/web/_attach.tpl from [d60f271cf8] to [0bf38746a5].

1
2
3
4
5
6
7
8
{include file="admin/_head.tpl" title="Inclure un fichier" current="web" 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>
		<dl>
|







1
2
3
4
5
6
7
8
{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>
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
			<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_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"}

				{csrf_field key=$csrf_key}
				<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_key}
					<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"}







|
|
|













|
>
>
>


>

|








|


|

|
|


>
|

|










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
			<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>
			<figcaption>
				<a href="{$file->url()}" data-name="{$file.name}" data-insert="image" data-thumb="{$file->thumb_url()}">{$file.name}</a>
			</figcaption>
			<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"}

Modified src/templates/web/_selector.tpl from [ce1e224960] to [f6ba705f24].

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" body_id="popup" is_popup=true}

<table class="web-tree list">
	<tbody>
		<tr{if !$parent} class="focused"{/if}>
			<td><input type="button" value="Choisir" data-id="0" data-label="Racine du site" /></td>
			<th><h3><a href="?">Racine du site</a></h3></th>
		</tr>
		<?php $last = 1; ?>
		{foreach from=$breadcrumbs item="_title" key="_id"}
		<tr{if $_id == $parent} class="focused"{/if}>
			<td><input type="button" value="Choisir" data-id="{$_id}" data-label="{$_title}" /></td>
			<th><?=str_repeat('<i>&nbsp;</i>', $last)?> <b class="icn">&rarr;</b> <a href="?parent={$_id}">{$_title}</a></th>
			<?php $last = $iteration; ?>
		</tr>
		{/foreach}
		{foreach from=$categories item="cat"}
		<tr{if $cat.id == $parent} class="focused"{/if}>
			<td><input type="button" value="Choisir" data-id="{$cat.id}" data-label="{$cat.title}" /></td>
			<th><?=str_repeat('<i>&nbsp;</i>', $last)?> <b class="icn">&rarr;</b> <a href="?parent={$cat.id}">{$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.id, e.dataset.label);
	};
});
</script>
{/literal}

{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
{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>', $iteration)?> <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+1)?> <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"}

Modified src/templates/web/config.tpl from [31bee0260a] to [6540f9cc0f].

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="Configuration" current="web"}

<nav class="tabs">
	<ul>
		<li><a href="./">Gestion du site web</a></li>
		{if $session->canAccess($session::SECTION_WEB, Membres::DROIT_ADMIN)}
			{*<li><a href="theme.php">Thèmes</a></li>*}
			<li class="current"><a href="config.php">Configuration</a></li>
		{/if}



	</ul>
</nav>

{form_errors}

{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>





|



>
>
>





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







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
{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>
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
			{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>



	<form method="post" action="{$self_url}">
	<fieldset class="templatesList">
		<legend>Squelettes du site</legend>

		{if $reset_ok}
		<p class="block confirm">







<
<
<
|



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






|










>
>







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
			{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">
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
					<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="?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"}







|

|

|

>

>











>
>
>
>


>



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
					<td class="check"></td>
					<th>Fichier</th>
					<td>Dernière modification</td>
					<td></td>
				</tr>
			</thead>
			<tbody>
			{foreach from=$sources key="source" item="props"}
				<tr>
					<td>{if $props.changed}<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 $props.changed}{$props.changed|date}{else}<em>(fichier non modifié)</em>{/if}</td>
					<td class="actions">
						{if $props.is_text}
						{linkbutton shape="edit" label="Éditer" href="?edit=%s"|args:$source}
						{/if}
					</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/?path=skel" label="Gérer les fichiers de squelettes" shape="folder"}
		</p>
	</fieldset>
	</form>

{/if}

{include file="admin/_foot.tpl"}

Modified src/templates/web/edit.tpl from [08595d53aa] to [4b0b9a3fe9].

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="É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">

	<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" source=$page 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_id" label="Catégorie" default=$parent target="web/_selector.php?parent=%d"|args:$page.parent_id required=true}
			{input type="datetime" name="date" label="Date" required=true default=$page->file()->created}
			<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é, 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">
			{input type="textarea" name="content" cols="70" rows="35" default=$page->raw() required=true}
		</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" shape="upload" class="main"}
		{button type="submit" name="cancel" label="Retourner à la liste" shape="reset"}
	</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
{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&parent=%s"|args:$page.path,$page.parent 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"}
			{input type="select" name="format" options=$formats source=$page label="Format"}
		</dl>
	</fieldset>

	<fieldset class="wikiEncrypt">
		<dl>




			<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 data-format="#f_format"}
		</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"}

Modified src/templates/web/index.tpl from [28b776b678] to [38a56e5fed].

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=$title current="web"}

<nav class="tabs">
	<aside>


		{linkbutton shape="plus" label="Nouvelle page" href="new.php?type=%d&parent=%d"|args:$type_page,$parent}
		{linkbutton shape="plus" label="Nouvelle catégorie" href="new.php?type=%d&parent=%d"|args:$type_category,$parent}

	</aside>
	<ul>
		<li class="current"><a href="./">Gestion du site web</a></li>
		{if $session->canAccess($session::SECTION_WEB, Membres::DROIT_ADMIN)}
			{*<li><a href="theme.php">Thèmes</a></li>*}
			<li><a href="config.php">Configuration</a></li>
		{/if}



	</ul>
</nav>



























{if count($categories)}
	<h2 class="ruler">Catégories</h2>
	<table class="list">
		<tbody>
			{foreach from=$categories item="p"}
			<tr>
				<th><a href="?parent={$p.id}">{$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.desactiver_site}
						{linkbutton shape="eye" label="Voir sur le site" href=$p->url() target="_blank"}
					{/if}
					{linkbutton shape="menu" label="Sous-catégories et pages" href="?parent=%d"|args:$p.id}
					{linkbutton shape="image" label="Prévisualiser" href="page.php?id=%d"|args:$p.id}

					{linkbutton shape="edit" label="Modifier" href="edit.php?id=%d"|args:$p.id}
					{linkbutton shape="delete" label="Supprimer" href="delete.php?id=%d"|args:$p.id}

				</td>
			</tr>
			{/foreach}
		</tbody>
	</table>
{else}
	<p class="submit">
		{linkbutton class="main" shape="plus" label="Nouvelle catégorie" href="new.php?type=%d&parent=%d"|args:$type_category,$parent}
	</p>
{/if}

{if count($pages)}
	<h2 class="ruler">Pages</h2>
	<p>
		{if !$order_date}
			{linkbutton shape="down" label="Trier par date" href="?parent=%d"|args:$parent}
		{else}
			{linkbutton shape="up" label="Trier par titre" href="?parent=%d&order_title"|args:$parent}
		{/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?id=%d"|args:$p.id}

					{linkbutton shape="edit" label="Modifier" href="edit.php?id=%d"|args:$p.id}
					{linkbutton shape="delete" label="Supprimer" href="delete.php?id=%d"|args:$p.id}

				</td>
			</tr>
			{/foreach}
		</tbody>
	</table>
{else}
	<p class="submit">
		{linkbutton shape="plus" class="main" label="Nouvelle page" href="new.php?type=%d&parent=%d"|args:$type_page,$parent}
	</p>
{/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
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
{include file="admin/_head.tpl" title=$title current="web"}

<nav class="tabs">
	<aside>
		{linkbutton shape="search" label="Rechercher" target="_dialog" href="search.php"}
		{if $session->canAccess($session::SECTION_WEB, $session::ACCESS_WRITE)}
		{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}
		{/if}
	</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"}
		{if $session->canAccess($session::SECTION_WEB, $session::ACCESS_WRITE)}
		{linkbutton href="edit.php?p=%s"|args:$current_path label="Éditer cette catégorie" shape="edit"}
		{/if}
	{/if}

</nav>

{if $config.site_disabled && $session->canAccess($session::SECTION_WEB, $session::ACCESS_ADMIN)}
	<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}

{form_errors}

{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}
					{if $session->canAccess($session::SECTION_WEB, $session::ACCESS_WRITE)}
					{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}
					{/if}
				</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&order_date"|args:$current_path}
		{else}
			{linkbutton shape="up" label="Trier par titre" href="?p=%s"|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 && !$config.site_disabled}
						{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}
					{if $session->canAccess($session::SECTION_WEB, $session::ACCESS_WRITE)}
					{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}
					{/if}
				</td>
			</tr>
			{/foreach}
		</tbody>
	</table>
{/if}

{if !count($categories) && !count($pages)}
	<p class="alert block">Il n'y a aucune page ou sous-catégorie dans cette catégorie.</p>
{/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"}

Modified src/templates/web/page.tpl from [b6013c91da] to [3803091252].

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
{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.id}
		{linkbutton shape="plus" label="Nouvelle catégorie" href="new.php?type=%d&parent=%d"|args:$type_category,$page.id}
	</aside>




	{/if}
	<ul>
		<li><a href="{$admin_url}web/?parent={$page.parent_id}">Retour à la liste</a></li>
		{if $session->canAccess($session::SECTION_WEB, Membres::DROIT_ECRITURE)}
			<li><a href="{$admin_url}web/edit.php?id={$page.id}">Modifier</a></li>
		{/if}
		{if $page.status == $page::STATUS_ONLINE && !$config.desactiver_site}
			<li><a href="{$page->url()}">Voir sur le site</a></li>
		{/if}
		{if $session->canAccess($session::SECTION_WEB, Membres::DROIT_ADMIN)}
			<li><a href="{$admin_url}web/delete.php?id={$page.id}">Supprimer</a></li>
		{/if}
	</ul>
</nav>

{if !empty($breadcrumbs)}
<div class="breadCrumbs">
	<ul>

		{foreach from=$breadcrumbs key="id" item="title"}
			<li><a href="?id={$id}">{$title}</a></li>
		{/foreach}
	</ul>
</div>
{/if}

{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 !$content}
		<p class="block alert">Cette page est vide, cliquez sur « Modifier » pour commencer à rédiger son contenu.</p>
	{else}
		<div class="wikiContent">
			{$content|raw}
		</div>

		{if !empty($images) || !empty($files)}
		<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($files)}
			<ul class="files">
				{foreach from=$files 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.modified|date_long}
			par {$auteur}
		</p>
	{/if}
{/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
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=$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>
	{else}
	<aside>
		{linkbutton href="?p=%s&toggle_type"|args:$page.path label="Transformer en catégorie" shape="reset"}
	</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_WRITE)}
			<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"}

Modified src/templates/web/search.tpl from [b5b27035db] to [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
{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"}
|

|
|
|
|
|
|
|
|


|
<
|
<
<
<
<
|
|

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



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/.htaccess from [5189696f0f] to [229f2663a8].

1
2
3
4






5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Options -MultiViews -Indexes
DirectoryIndex disabled
DirectoryIndex index.php







# FallbackResource n'est dispo que depuis Apache 2.2.16, soit Debian Wheezy (2013)
# Mais bugue avant Apache 2.4.15, il faut donc bien désactiver le DirectoryIndex
# cf. https://bz.apache.org/bugzilla/show_bug.cgi?id=58292
# et https://serverfault.com/questions/559067/apache-hangs-for-five-seconds-with-fallbackresource-when-accessing
<IfModule mod_version.c>
	<IfVersion >= 2.2.16>
		FallbackResource /_route.php
	</IfVersion>
</IfModule>

# Utilisation de ErrorDocument 404 à la place de FallbackResource si possible
ErrorDocument 404 /_route.php

# Un peu de sécurité
<IfModule mod_alias.c>
	RedirectMatch 404 _inc\.php
</IfModule>




>
>
>
>
>
>
|



<
<
<
<
<
<
<
<





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








15
16
17
18
19
Options -MultiViews -Indexes
DirectoryIndex disabled
DirectoryIndex index.php

# Rediriger les adresses dynamiques vers le routeur
FallbackResource /_route.php

# Si FallbackResource ne fonctionne pas, utiliser ceci :
#ErrorDocument 404 /_route.php

# Explication : FallbackResource n'est dispo que depuis Apache 2.2.16, soit Debian Wheezy (2013)
# Mais bugue avant Apache 2.4.15, il faut donc bien désactiver le DirectoryIndex
# cf. https://bz.apache.org/bugzilla/show_bug.cgi?id=58292
# et https://serverfault.com/questions/559067/apache-hangs-for-five-seconds-with-fallbackresource-when-accessing









# Un peu de sécurité
<IfModule mod_alias.c>
	RedirectMatch 404 _inc\.php
</IfModule>

Modified src/www/_route.php from [d7347d2841] to [9acabfe9b8].

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

namespace Garradin;

if (empty($_SERVER['REQUEST_URI'])) {

	die('Appel non supporté');
}

$uri = $_SERVER['REQUEST_URI'];

if ('_route.php' === basename($uri)) {

	die('Appel interdit');
}



if ('favicon.ico' === basename($uri)) {
	die('');
}

if (($pos = strpos($uri, '?')) !== false)
{
	$uri = substr($uri, 0, $pos);
}

if (file_exists(__DIR__ . $uri))
{
	if (PHP_SAPI != 'cli-server') {

		die('Erreur de configuration du serveur web: cette URL ne devrait pas être traitée par Garradin');
	}

	return false;
}
elseif (preg_match('!/p/(.+?)/(.*)!', $uri, $match))
{
	$_GET['_p'] = $match[1];
	$_GET['_u'] = $match[2];
	require __DIR__ . '/plugin.php';
}
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';
}





>






>


>
>













>

















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




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;

if (empty($_SERVER['REQUEST_URI'])) {
	http_response_code(500);
	die('Appel non supporté');
}

$uri = $_SERVER['REQUEST_URI'];

if ('_route.php' === basename($uri)) {
	http_response_code(403);
	die('Appel interdit');
}

http_response_code(200);

if ('favicon.ico' === basename($uri)) {
	die('');
}

if (($pos = strpos($uri, '?')) !== false)
{
	$uri = substr($uri, 0, $pos);
}

if (file_exists(__DIR__ . $uri))
{
	if (PHP_SAPI != 'cli-server') {
		http_response_code(500);
		die('Erreur de configuration du serveur web: cette URL ne devrait pas être traitée par Garradin');
	}

	return false;
}
elseif (preg_match('!/p/(.+?)/(.*)!', $uri, $match))
{
	$_GET['_p'] = $match[1];
	$_GET['_u'] = $match[2];
	require __DIR__ . '/plugin.php';
}
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 [37f9d2a893] 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);
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
$form = new Form;
$tpl->assign_by_ref('form', $form);

$session = Session::getInstance();
$config = Config::getInstance();

$tpl->assign('session', $session);
$tpl->assign('config', $config->getConfig());

if (!defined('Garradin\LOGIN_PROCESS'))
{
    if (!$session->isLogged())
    {
        if ($session->isOTPRequired())
        {







|







45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
$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())
        {
72
73
74
75
76
77
78
79
80
81
82
83






    $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 [07c8f2aab9] 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
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
<?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;

$rules = [
	'deposit' => 'array|required',
];


// Enregistrement des cases cochées
if (f('save') && $form->check('acc_deposit_' . $account->id, $rules))
{
	try {
		$transaction->importFromDepositForm();
		Transactions::saveDeposit($transaction, $journal, f('deposit'));

		Utils::redirect(ADMIN_URL . 'acc/transactions/details.php?id=' . $transaction->id());

	}

	catch (UserException $e) {
		$journal = $account->getDepositJournal(CURRENT_YEAR_ID);
		$form->addError($e->getMessage());
	}
}

$date = new \DateTime;

if ($date > $current_year->end_date) {
	$date = $current_year->end_date;
}

$target = $account::TYPE_BANK;



$tpl->assign(compact(
	'account',
	'journal',
	'date',
	'target',
	'checked'

));

$tpl->display('acc/accounts/deposit.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
<?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);

	Utils::redirect(ADMIN_URL . 'acc/transactions/details.php?id=' . $transaction->id());
}, 'acc_deposit_' . $account->id());

// Uncheck everything if there was an error
if ($form->hasErrors()) {
	$journal = $account->getDepositJournal(CURRENT_YEAR_ID);


}

$date = new \DateTime;

if ($date > $current_year->end_date) {
	$date = $current_year->end_date;
}

$target = $account::TYPE_BANK;

$journal_count = $account->countDepositJournal(CURRENT_YEAR_ID);

$tpl->assign(compact(
	'account',
	'journal',
	'date',
	'target',
	'checked',
	'journal_count'
));

$tpl->display('acc/accounts/deposit.tpl');

Modified src/www/admin/acc/accounts/journal.php from [c1a4bdf85e] to [da00ba6416].

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
$account = Accounts::get((int) qg('id'));

if (!$account) {
	throw new UserException("Le compte demandé n'existe pas.");
}

$year_id = (int) qg('year') ?: CURRENT_YEAR_ID;





if ($year_id === CURRENT_YEAR_ID) {
	$year = $current_year;
}
else {
	$year = Years::get($year_id);

	if (!$year) {
		throw new UserException("L'exercice demandé n'existe pas.");
	}

	$tpl->assign('year', $year);
}

// 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 != $current_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;
}








>
>
>
>
















|
>
>
>
>
>
>



|







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
$account = Accounts::get((int) qg('id'));

if (!$account) {
	throw new UserException("Le compte demandé n'existe pas.");
}

$year_id = (int) qg('year') ?: CURRENT_YEAR_ID;

if (!$year_id) {
	Utils::redirect(ADMIN_URL . 'acc/years/?msg=OPEN');
}

if ($year_id === CURRENT_YEAR_ID) {
	$year = $current_year;
}
else {
	$year = Years::get($year_id);

	if (!$year) {
		throw new UserException("L'exercice demandé n'existe pas.");
	}

	$tpl->assign('year', $year);
}

// 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 [c613212e83] 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'));

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
$journal = $account->getReconcileJournal($current_year->id(), $start, $end, $only);

// Enregistrement des cases cochées
$form->runIf(f('save') || f('save_next'), function () use ($journal, $start, $end, $account, $only) {
	Transactions::saveReconciled($journal, f('reconcile'));

	if (f('save')) {
		Utils::redirect(Utils::getSelfURL());
	}
	else {
		$start->modify('+1 month');
		$end->modify('+1 month');
		$url = sprintf('%sacc/accounts/reconcile.php?id=%s&start=%s&end=%s&only=%d',
			ADMIN_URL, $account->id(), $start->format('d/m/Y'), $end->format('d/m/Y'), $only);
		Utils::redirect($url);







|







53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
$journal = $account->getReconcileJournal($current_year->id(), $start, $end, $only);

// Enregistrement des cases cochées
$form->runIf(f('save') || f('save_next'), function () use ($journal, $start, $end, $account, $only) {
	Transactions::saveReconciled($journal, f('reconcile'));

	if (f('save')) {
		Utils::redirect(Utils::getSelfURI());
	}
	else {
		$start->modify('+1 month');
		$end->modify('+1 month');
		$url = sprintf('%sacc/accounts/reconcile.php?id=%s&start=%s&end=%s&only=%d',
			ADMIN_URL, $account->id(), $start->format('d/m/Y'), $end->format('d/m/Y'), $only);
		Utils::redirect($url);

Modified src/www/admin/acc/accounts/reconcile_assist.php from [a3c486e0c0] 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'));

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
	'amount'         => 'Montant',
]);

$csv->setMandatoryColumns(['label', 'date', 'amount']);

$form->runIf('cancel', function () use ($csv) {
	$csv->clear();
}, $csrf_key, Utils::getSelfURL());

$form->runIf(f('upload') && isset($_FILES['file']['name']), function () use ($csv) {
	$csv->load($_FILES['file']);
}, $csrf_key, Utils::getSelfURL());

$form->runIf('assign', function () use ($csv) {
	$csv->setTranslationTable(f('translation_table'));
	$csv->skip((int)f('skip_first_line'));
}, $csrf_key, Utils::getSelfURL());

$start = null;
$end = null;
$journal = null;

if ($csv->ready()) {
	foreach ($csv->iterate() as $line => $row) {







|



|




|







30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
	'amount'         => 'Montant',
]);

$csv->setMandatoryColumns(['label', 'date', 'amount']);

$form->runIf('cancel', function () use ($csv) {
	$csv->clear();
}, $csrf_key, Utils::getSelfURI());

$form->runIf(f('upload') && isset($_FILES['file']['name']), function () use ($csv) {
	$csv->load($_FILES['file']);
}, $csrf_key, Utils::getSelfURI());

$form->runIf('assign', function () use ($csv) {
	$csv->setTranslationTable(f('translation_table'));
	$csv->skip((int)f('skip_first_line'));
}, $csrf_key, Utils::getSelfURI());

$start = null;
$end = null;
$journal = null;

if ($csv->ready()) {
	foreach ($csv->iterate() as $line => $row) {
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
	$journal = $account->getReconcileJournal(CURRENT_YEAR_ID, $start, $end);
}

// Enregistrement des cases cochées
$form->runIf('save', function () use ($journal, $csv) {
	Transactions::saveReconciled($journal, f('reconcile'));
	$csv->clear();
}, $csrf_key, Utils::getSelfURL());

$lines = null;

if ($journal && $csv->ready()) {
	try {
		$lines = $account->mergeReconcileJournalAndCSV($journal, $csv);
	}







|







79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
	$journal = $account->getReconcileJournal(CURRENT_YEAR_ID, $start, $end);
}

// Enregistrement des cases cochées
$form->runIf('save', function () use ($journal, $csv) {
	Transactions::saveReconciled($journal, f('reconcile'));
	$csv->clear();
}, $csrf_key, Utils::getSelfURI());

$lines = null;

if ($journal && $csv->ready()) {
	try {
		$lines = $account->mergeReconcileJournalAndCSV($journal, $csv);
	}

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/index.php from [5e00b51e32] to [bd5f5966a0].

18
19
20
21
22
23
24
25
26
if (!$chart) {
	throw new UserException('Aucun plan comptable spécifié');
}

$accounts = $chart->accounts();

$tpl->assign('chart', $chart);
$tpl->assign('accounts_grouped', $accounts->listCommonGrouped());
$tpl->display('acc/charts/accounts/index.tpl');







|

18
19
20
21
22
23
24
25
26
if (!$chart) {
	throw new UserException('Aucun plan comptable spécifié');
}

$accounts = $chart->accounts();

$tpl->assign('chart', $chart);
$tpl->assign('accounts_grouped', $accounts->listCommonGrouped(null, true));
$tpl->display('acc/charts/accounts/index.tpl');

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 [17dde2f21a] to [f3271645a4].

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
<?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');

// Cache the page until the charts have changed
$hash = sha1($targets . $chart);
$expiry = Config::getInstance()->get('last_chart_change') ?: time();


Utils::HTTPCache($hash, $expiry);

if ($chart) {
	$chart = Charts::get((int)qg('chart'));
}
elseif (qg('year')) {
	$year = Years::get((int)qg('year'));











<
<





|

>
|







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\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'));

37
38
39
40
41
42
43






44
45
46
47
48
49
50
51
52
53
54
55
	throw new UserException('Aucun exercice ouvert disponible');
}

$accounts = $chart->accounts();

$tpl->assign(compact('chart', 'targets'));







$all = (bool) qg('all');

if (!$targets) {
	$tpl->assign('accounts', !$all ? $accounts->listCommonTypes() : $accounts->listAll());
}
else {
	$tpl->assign('grouped_accounts', $accounts->listCommonGrouped(explode(':', $targets)));
}

$tpl->assign('all', $all);

$tpl->display('acc/charts/accounts/selector.tpl');







>
>
>
>
>
>
|











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
	throw new UserException('Aucun exercice ouvert disponible');
}

$accounts = $chart->accounts();

$tpl->assign(compact('chart', 'targets'));

$all = qg('all');

if (null !== $all) {
	$session->set('account_selector_all', (bool) $all);
}

$all = (bool) $session->get('account_selector_all');

if (!$targets) {
	$tpl->assign('accounts', !$all ? $accounts->listCommonTypes() : $accounts->listAll());
}
else {
	$tpl->assign('grouped_accounts', $accounts->listCommonGrouped(explode(':', $targets)));
}

$tpl->assign('all', $all);

$tpl->display('acc/charts/accounts/selector.tpl');

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 [f1d40ee231] 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());

$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 [c7c07f3287].

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'));

31
32
33
34
35
36
37




38
39
40
41
42
43

44
		throw new UserException('Exercice inconnu.');
	}

	$criterias['year'] = $year->id();
	$tpl->assign('year', $year);
	$tpl->assign('close_date', $year->closed ? $year->end_date : time());
}





if (!count($criterias))
{
	throw new UserException('Critère de rapport inconnu.');
}


$tpl->assign('criterias_query', http_build_query($criterias));







>
>
>
>






>

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
		throw new UserException('Exercice inconnu.');
	}

	$criterias['year'] = $year->id();
	$tpl->assign('year', $year);
	$tpl->assign('close_date', $year->closed ? $year->end_date : time());
}

if (qg('analytical_only')) {
	$criterias['analytical_only'] = true;
}

if (!count($criterias))
{
	throw new UserException('Critère de rapport inconnu.');
}

$tpl->assign('criterias', $criterias);
$tpl->assign('criterias_query', http_build_query($criterias));

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/reports/trial_balance.php from [a483e23c57] to [c1cd5c7e43].

1
2
3
4
5
6
7
8
9
10
11
<?php

namespace Garradin;

use Garradin\Accounting\Reports;

require_once __DIR__ . '/_inc.php';

$tpl->assign('balance', Reports::getClosingSumsWithAccounts($criterias));

$tpl->display('acc/reports/trial_balance.tpl');








|


1
2
3
4
5
6
7
8
9
10
11
<?php

namespace Garradin;

use Garradin\Accounting\Reports;

require_once __DIR__ . '/_inc.php';

$tpl->assign('balance', Reports::getTrialBalance($criterias));

$tpl->display('acc/reports/trial_balance.tpl');

Modified src/www/admin/acc/transactions/actions.php from [0ea83417c0] 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.');
}

30
31
32
33
34
35
36
37
38








39
40
41
42
43
44
45
46
		}

		$transaction->delete();
	}
}, $csrf_key, f('from') ?: ADMIN_URL);

// Add/remove lines to analytical
$form->runIf('change_analytical', function () use ($lines) {
	$id = f('id_analytical') ?: null;








	Transactions::setAnalytical($id, $lines);
}, $csrf_key, f('from') ?: ADMIN_URL);

$from = f('from');
$count = count($check);
$extra = compact('check', 'from');
$tpl->assign(compact('csrf_key', 'check', 'count', 'extra'));








|

>
>
>
>
>
>
>
>
|







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
		}

		$transaction->delete();
	}
}, $csrf_key, f('from') ?: ADMIN_URL);

// Add/remove lines to analytical
$form->runIf('change_analytical', function () use ($transactions, $lines) {
	$id = f('id_analytical') ?: null;

	if (f('apply_lines')) {
		$lines = null;
	}
	else {
		$transactions = null;
	}

	Transactions::setAnalytical($id, $transactions, $lines);
}, $csrf_key, f('from') ?: ADMIN_URL);

$from = f('from');
$count = count($check);
$extra = compact('check', 'from');
$tpl->assign(compact('csrf_key', 'check', 'count', 'extra'));

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 [6bfbc75fb3] to [4fb5b3b805].

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26


27
28
29
}

$csrf_key = 'details_' . $transaction->id();

$form->runIf('mark_paid', function () use ($transaction) {
	$transaction->markPaid();
	$transaction->save();
}, $csrf_key, Utils::getSelfURL());

$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');







|







>
>



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
}

$csrf_key = 'details_' . $transaction->id();

$form->runIf('mark_paid', function () use ($transaction) {
	$transaction->markPaid();
	$transaction->save();
}, $csrf_key, Utils::getSelfURI());

$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('files_edit', $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 [7be38ce3db] 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([]);
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
	$lines = Utils::array_transpose($_POST['lines']);

	foreach ($lines as &$line) {
		$line = (object) $line;
		$line->credit = Utils::moneyToInteger($line->credit);
		$line->debit = Utils::moneyToInteger($line->debit);
	}


}
else {
	$lines = $transaction->getLinesWithAccounts();

	foreach ($lines as $k => &$line) {
		$line->account = [$line->id_account => sprintf('%s — %s', $line->account_code, $line->account_name)];
	}
}



$has_reconciled_lines = true;

array_walk($lines, function ($l) use (&$has_reconciled_lines) {
	if (!empty($line->reconciled)) {
		$has_reconciled_lines = true;

	}
});


$first_line = $transaction->getFirstLine();

if ($transaction->type != Transaction::TYPE_ADVANCED) {
	$types_accounts = $transaction->getTypesAccounts();
}








>
>







|
>
|
>
|

|


>

<
>







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
	$lines = Utils::array_transpose($_POST['lines']);

	foreach ($lines as &$line) {
		$line = (object) $line;
		$line->credit = Utils::moneyToInteger($line->credit);
		$line->debit = Utils::moneyToInteger($line->debit);
	}

	unset($line);
}
else {
	$lines = $transaction->getLinesWithAccounts();

	foreach ($lines as $k => &$line) {
		$line->account = [$line->id_account => sprintf('%s — %s', $line->account_code, $line->account_name)];
	}

	unset($line);
}

$has_reconciled_lines = false;

foreach ($lines as $line) {
	if (!empty($line->reconciled)) {
		$has_reconciled_lines = true;
		break;
	}

}

$first_line = $transaction->getFirstLine();

if ($transaction->type != Transaction::TYPE_ADVANCED) {
	$types_accounts = $transaction->getTypesAccounts();
}

Modified src/www/admin/acc/transactions/new.php from [42b86feb65] to [c93d48adea].

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\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();

$transaction = new Transaction;
$lines = [[], []];
$amount = 0;
$payoff_for = qg('payoff_for') ?: f('payoff_for');































// Quick pay-off for debts and credits, directly from a debt/credit details page
if ($id = $payoff_for) {
	$payoff_for = $transaction->payOffFrom($id);

	if (!$payoff_for) {
		throw new UserException('Écriture inconnue');





>
>




|












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







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\Entities\Accounting\Account;
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_WRITE);

if (!CURRENT_YEAR_ID) {
	Utils::redirect(ADMIN_URL . 'acc/years/?msg=OPEN');
}

$chart = $current_year->chart();
$accounts = $chart->accounts();

$transaction = new Transaction;
$lines = [[], []];
$amount = 0;
$payoff_for = qg('payoff_for') ?: f('payoff_for');
$types_accounts = null;

// Duplicate transaction
if (qg('copy')) {
	$old = Transactions::get((int)qg('copy'));
	$transaction = $old->duplicate($current_year);
	$lines = $transaction->getLinesWithAccounts();
	$payoff_for = null;
	$amount = $transaction->getLinesCreditSum();
	$types_accounts = $transaction->getTypesAccounts();
	$transaction->resetLines();

	foreach ($lines as $k => &$line) {
		$line->account = [$line->id_account => sprintf('%s — %s', $line->account_code, $line->account_name)];
	}

	unset($line);
}

$date = new \DateTime;

if ($session->get('acc_last_date')) {
	$date = \DateTime::createFromFormat('!d/m/Y', $session->get('acc_last_date'));
}

if (!$date || ($date < $current_year->start_date || $date > $current_year->end_date)) {
	$date = $current_year->start_date;
}

$transaction->date = $date;

// Quick pay-off for debts and credits, directly from a debt/credit details page
if ($id = $payoff_for) {
	$payoff_for = $transaction->payOffFrom($id);

	if (!$payoff_for) {
		throw new UserException('Écriture inconnue');
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
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'));

		Utils::redirect(Utils::getSelfURL(false) . '?ok=' . $transaction->id());
	}
	catch (UserException $e) {
		$form->addError($e->getMessage());
	}
}

$date = new \DateTime;

if ($session->get('acc_last_date')) {
	$date = \DateTime::createFromFormat('!d/m/Y', $session->get('acc_last_date'));
}

if (!$date || ($date < $current_year->start_date || $date > $current_year->end_date)) {
	$date = $current_year->start_date;
}

$tpl->assign('date', $date->format('d/m/Y'));
$tpl->assign(compact('transaction', 'payoff_for', 'amount', 'lines'));
$tpl->assign('payoff_targets', implode(':', [Account::TYPE_BANK, Account::TYPE_CASH, Account::TYPE_OUTSTANDING]));
$tpl->assign('ok', (int) qg('ok'));

$tpl->assign('types_details', Transaction::getTypesDetails());
$tpl->assign('chart_id', $chart->id());

$tpl->assign('analytical_accounts', ['' => '-- Aucun'] + $accounts->listAnalytical());
$tpl->display('acc/transactions/new.tpl');







<
<
<
<
<
<







|






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








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
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'));

		Utils::redirect(Utils::getSelfURI(false) . '?ok=' . $transaction->id());
	}
	catch (UserException $e) {
		$form->addError($e->getMessage());
	}
}












$tpl->assign(compact('transaction', 'payoff_for', 'amount', 'lines', 'types_accounts'));
$tpl->assign('payoff_targets', implode(':', [Account::TYPE_BANK, Account::TYPE_CASH, Account::TYPE_OUTSTANDING]));
$tpl->assign('ok', (int) qg('ok'));

$tpl->assign('types_details', Transaction::getTypesDetails());
$tpl->assign('chart_id', $chart->id());

$tpl->assign('analytical_accounts', ['' => '-- Aucun'] + $accounts->listAnalytical());
$tpl->display('acc/transactions/new.tpl');

Modified src/www/admin/acc/transactions/service_user.php from [0473be53b7] to [6aaa90de39].

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
18
<?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->assign('service_user_id', qg('id'));

$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 [e25c1f315a] to [124836d0d2].

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;

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.');
}

if ($year->closed) {
	throw new UserException('Impossible de modifier un exercice clôturé.');
}

$csrf_key = 'acc_years_close_' . $year->id();

$form->runIf('close', function () use ($year, $user, $session) {
	$year->close($user->id);
	$year->save();
	$session->set('acc_year', null);
}, $csrf_key, ADMIN_URL . 'acc/years/');

$tpl->assign(compact('year', 'csrf_key'));

$tpl->display('acc/years/close.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
<?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.');
}

if ($year->closed) {
	throw new UserException('Impossible de modifier un exercice clôturé.');
}

$csrf_key = 'acc_years_close_' . $year->id();

$form->runIf('close', function () use ($year, $user, $session) {
	$year->close($user->id);
	$year->save();
	$session->set('acc_year', null);
}, $csrf_key, ADMIN_URL . 'acc/years/new.php?from=' . $year->id());

$tpl->assign(compact('year', 'csrf_key'));

$tpl->display('acc/years/close.tpl');

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.');
}

Added src/www/admin/acc/years/export.php version [5fa4e489df].





































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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\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 {
	$year = Years::get($year_id);
}

if (!$year) {
	throw new UserException("L'exercice demandé n'existe pas.");
}

$format = qg('format');
$type = qg('type');

if (null !== $format && null !== $type) {
	Transactions::export($year, $format, $type);
	exit;
}

$tpl->assign(compact('year'));

$tpl->display('acc/years/export.tpl');

Modified src/www/admin/acc/years/import.php from [e202ee058f] to [2d7d375a16].

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\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 {
	$year = Years::get($year_id);


	if (!$year) {
		throw new UserException("L'exercice demandé n'existe pas.");
	}
}

if (qg('export')) {
	CSV::export(
		qg('export'),
		sprintf('Export comptable - %s - %s', Config::getInstance()->get('nom_asso'), $year->label),
		Transactions::export($year->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
<?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 {
	$year = Years::get($year_id);
}

if (!$year) {
	throw new UserException("L'exercice demandé n'existe pas.");

}

if (qg('export')) {
	CSV::export(
		qg('export'),
		sprintf('Export comptable - %s - %s', Config::getInstance()->get('nom_asso'), $year->label),
		Transactions::export($year->id())
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

$csv = new CSV_Custom($session, 'acc_import_year');
$csv->setColumns(Transactions::POSSIBLE_CSV_COLUMNS);
$csv->setMandatoryColumns(Transactions::MANDATORY_CSV_COLUMNS);

if (f('cancel')) {
	$csv->clear();
	Utils::redirect(Utils::getSelfURL());
}

$csrf_key = 'acc_years_import_' . $year->id();

$form->runIf(f('assign') && $csv->loaded(), function () use ($csv, $year, $user) {
	$csv->skip((int)f('skip_first_line'));
	$csv->setTranslationTable(f('translation_table'));







|







36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

$csv = new CSV_Custom($session, 'acc_import_year');
$csv->setColumns(Transactions::POSSIBLE_CSV_COLUMNS);
$csv->setMandatoryColumns(Transactions::MANDATORY_CSV_COLUMNS);

if (f('cancel')) {
	$csv->clear();
	Utils::redirect(Utils::getSelfURI());
}

$csrf_key = 'acc_years_import_' . $year->id();

$form->runIf(f('assign') && $csv->loaded(), function () use ($csv, $year, $user) {
	$csv->skip((int)f('skip_first_line'));
	$csv->setTranslationTable(f('translation_table'));

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 [52e738c176] to [089708c6e5].

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\Years;
use Garradin\Accounting\Charts;

use Garradin\Entities\Accounting\Year;

require_once __DIR__ . '/../../_inc.php';

$session->requireAccess('compta', Membres::DROIT_ADMIN);

if (f('new') && $form->check('acc_years_new')) {
	try {
		$year = new Year;
		$year->importForm();
		$year->save();


		if (Years::countClosed()) {
			Utils::redirect(ADMIN_URL . 'acc/years/balance.php?id=' . $year->id());

		}
		else {

			Utils::redirect(ADMIN_URL . 'acc/years/');
		}
	}
	catch (UserException $e)
	{
		$form->addError($e->getMessage());

	}

}

$new_dates = Years::getNewYearDates();
$tpl->assign('start_date', $new_dates[0]);
$tpl->assign('end_date', $new_dates[1]);

$tpl->assign('charts', Charts::listByCountry());

$tpl->display('acc/years/new.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
<?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')) {
		$old = Years::get((int) $old_id);

		$changed = Fees::updateYear($old, $year);


		if (!$changed) {
			Utils::redirect(ADMIN_URL . 'acc/years/?msg=UPDATE_FEES');
		}
	}


	if (Years::countClosed()) {
		Utils::redirect(ADMIN_URL . 'acc/years/balance.php?id=' . $year->id());
	}
}, 'acc_years_new', '!acc/years/');


$new_dates = Years::getNewYearDates();
$tpl->assign('start_date', $new_dates[0]);
$tpl->assign('end_date', $new_dates[1]);
$tpl->assign('label', sprintf('Exercice %d', $new_dates[0]->format('Y')));
$tpl->assign('charts', Charts::listByCountry());

$tpl->display('acc/years/new.tpl');

Modified src/www/admin/common/files/_preview.php from [ddb1e2954c] to [a08e5e24c0].

1
2
3
4


5

6
7
8


9


10
11


12

























13
<?php

namespace Garradin;



use Garradin\Web\Render\Skriv;


require_once __DIR__ . '/_inc.php';



$session->requireAccess($session::SECTION_WEB, Membres::DROIT_ECRITURE);



$tpl->assign('content', Skriv::render(null, (string) f('content'), ['prefix' => '#']));




























$tpl->display('web/_preview.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
<?php

namespace Garradin;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\Web\Render\Render;
use Garradin\Web\Web;

require_once __DIR__ . '/../../_inc.php';

$page = null;
$content = f('content');

if (null == $content) {
	throw new UserException('Aucun contenu à prévisualiser');
}

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=';

$content = Render::render(f('format'), $file, f('content'), ADMIN_URL . $prefix);

$tpl->assign(compact('file', 'content'));

$tpl->assign('custom_css', ['!web/css.php']);

$tpl->display('common/files/_preview.tpl');

Modified src/www/admin/common/files/delete.php from [dbcb7d7cc0] to [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
<?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');



>
|

<
|
|
>

|
|


<
|
<
<
|


|
|
>
|


>
>

|
|



|
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 [5a8ed5bb74].



















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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->editorType();
$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 [5a776333ed].





















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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('common/files/_preview.php?p='));
	$tpl->assign('file', $file);
	$tpl->display('common/files/_preview.tpl');
}
catch (\LogicException $e) {
	$file->serve($session);
}

Added src/www/admin/common/files/rename.php version [c1d61a3f81].



























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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\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.');
}

$context = $file->context();

$csrf_key = 'file_rename_' . $file->pathHash();

$form->runIf('rename', function () use ($file) {
	$file->changeFileName(f('new_name'));
}, $csrf_key, '!');

$tpl->assign(compact('file', 'csrf_key'));

$tpl->display('common/files/rename.tpl');

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 [e1f8499fe1] to [b986545306].

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';

if (empty($target) || !in_array($target, Recherche::TARGETS)) {
    throw new UserException('Cible inconnue');
}







$recherche = new Recherche;
$mode = null;

if (qg('edit') || qg('delete') || qg('duplicate'))
{
	$r = $recherche->get(qg('edit') ?: (qg('delete') ?: qg('duplicate')));

	if (!$r)
	{
		throw new UserException('Recherche non trouvée');
	}

	if ($r->id_membre !== null && $r->id_membre != $user->id)
	{
		throw new UserException('Recherche privée appartenant à un autre membre.');
	}

	if (qg('duplicate')) {
		$recherche->duplicate($r->id);
		Utils::redirect(Utils::getSelfURI(false));
	}

	$tpl->assign('recherche', $r);

	$mode = qg('edit') ? 'edit' : 'delete';
}

if ($mode == 'edit' && f('save') && $form->check('edit_recherche_' . $r->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;

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'));

	if (!$r)
	{
		throw new UserException('Recherche non trouvée');
	}

	if ($r->id_membre !== null && $r->id_membre != $user->id)
	{
		throw new UserException('Recherche privée appartenant à un autre membre.');
	}






	$tpl->assign('recherche', $r);

	$mode = qg('edit') ? 'edit' : 'delete';
}

if ($mode == 'edit' && f('save') && $form->check('edit_recherche_' . $r->id))
{
55
56
57
58
59
60
61
62
63
64
}

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 [f997b1b1c1] to [f310a1310c].

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\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'),
	'limit' => f('limit') ?: 100,
	'desc'  => (bool) f('desc'),
];



$text_query = trim(qg('qt'));
$result = null;
$sql_query = null;
$search = null;
$id = f('id') ?: qg('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
<?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),
];

$query->desc = (bool) f('desc');

$text_query = trim(qg('qt'));
$result = null;
$sql_query = null;
$search = null;
$id = f('id') ?: qg('id');

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

// Execute search
if ($query->query || $sql_query) {
	try {
		if ($sql_query) {
			$sql = $sql_query;
		}
		else {
			$sql = $recherche->buildQuery($target, $query->query, $query->order, $query->desc, $query->limit);
		}

	   $result = $recherche->searchSQL($target, $sql, null, false, $is_unprotected);




	}
	catch (UserException $e) {
		$form->addError($e->getMessage());
	}

	if (f('to_sql')) {
		$sql_query = $sql;
	}
}

if (null !== $result)
{
	if (count($result) == 1 && $text_query !== '' && $target === 'membres') {
		Utils::redirect(ADMIN_URL . 'membres/fiche.php?id=' . (int)$result[0]->_user_id);
	}

	if (f('save') && !$form->hasErrors())
	{
		if (!$sql_query) {
			$type = Recherche::TYPE_JSON;
		}
		elseif ($is_unprotected) {
			$type = Recherche::TYPE_SQL_UNPROTECTED;
		}
		else {
			$type = Recherche::TYPE_SQL;
		}

		if ($id) {
			$recherche->edit($id, [
				'type'    => $type,
				'contenu' => $sql_query ?: $query,
			]);
		}
		else
		{
			$label = $sql_query ? 'Recherche SQL du ' : 'Recherche avancée du ';
			$label .= date('d/m/Y à H:i:s');
			$id = $recherche->add($label, $user->id, $type, $target, $sql_query ?: $query);
		}

		$url = $target == 'compta' ? '/admin/acc/saved_searches.php?id=' : '/admin/membres/recherches.php?id=';
		Utils::redirect($url . $id);
	}

	$tpl->assign('result_header', $recherche->getResultHeader($target, $result));
}
elseif ($target === 'membres')
{







|


|


















>
>
>
>




<
<
<
<








|











|












|







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

// Execute search
if ($query->query || $sql_query) {
	try {
		if ($sql_query) {
			$sql = $sql_query;
		}
		else {
			$sql = $recherche->buildQuery($target, $query->query, $query->order, $query->desc, $query->limit);
		}

	   $result = $recherche->searchSQL($target, $sql, null, false, $is_unprotected);

		if (f('to_sql')) {
			$sql_query = $sql;
		}
	}
	catch (UserException $e) {
		$form->addError($e->getMessage());
	}




}

if (null !== $result)
{
	if (count($result) == 1 && $text_query !== '' && $target === 'membres') {
		Utils::redirect(ADMIN_URL . 'membres/fiche.php?id=' . (int)$result[0]->_user_id);
	}

	if ((f('save_new') || f('save')) && !$form->hasErrors())
	{
		if (!$sql_query) {
			$type = Recherche::TYPE_JSON;
		}
		elseif ($is_unprotected) {
			$type = Recherche::TYPE_SQL_UNPROTECTED;
		}
		else {
			$type = Recherche::TYPE_SQL;
		}

		if ($id && !f('save_new')) {
			$recherche->edit($id, [
				'type'    => $type,
				'contenu' => $sql_query ?: $query,
			]);
		}
		else
		{
			$label = $sql_query ? 'Recherche SQL du ' : 'Recherche avancée du ';
			$label .= date('d/m/Y à H:i:s');
			$id = $recherche->add($label, $user->id, $type, $target, $sql_query ?: $query);
		}

		$url = $target == 'compta' ? '!acc/saved_searches.php?edit=' : '!membres/recherches.php?edit=';
		Utils::redirect($url . $id);
	}

	$tpl->assign('result_header', $recherche->getResultHeader($target, $result));
}
elseif ($target === 'membres')
{
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
	}

	$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/errors.php from [3f8055d3aa] to [99e2c2d1c3].

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;

use KD2\ErrorManager;

require_once __DIR__ . '/_inc.php';

if (qg('type') == 'errors' && ENABLE_TECH_DETAILS)


{
    $reports = ErrorManager::getReportsFromLog(null, qg('id'));

    $reports = array_reverse($reports, true);

    foreach ($reports as &$report)
    {
        $report->context->date = strtotime($report->context->date);
    }

    unset($report);

    $errors = [];

    if (qg('id'))
    {
        if (!count($reports)) {
            throw new UserException('Erreur inconnue');
        }

        $tpl->assign('id', qg('id'));
        $tpl->assign('main', reset($reports));
        $tpl->assign('reports', $reports);
    }
    else
    {
        foreach ($reports as $report)
        {
            if (!isset($errors[$report->context->id]))
            {
                $errors[$report->context->id] = [
                    'message' => $report->errors[0]->message,
                    'source' => sprintf('%s:%d', $report->errors[0]->backtrace[0]->file, $report->errors[0]->backtrace[0]->line),
                    'count' => 0,
                ];
            }

            $errors[$report->context->id]['last_seen'] = $report->context->date;
            $errors[$report->context->id]['count']++;
        }

        $tpl->assign('errors', $errors);
    }
}

$tpl->assign('type', qg('type'));
$tpl->display('admin/config/logs.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
<?php
namespace Garradin;

use KD2\ErrorManager;

require_once __DIR__ . '/../_inc.php';

if (!ENABLE_TECH_DETAILS) {
    throw new UserException('Détails techniques désactivés');
}

$reports = ErrorManager::getReportsFromLog(null, qg('id'));

$reports = array_reverse($reports, true);

foreach ($reports as &$report)
{
    $report->context->date = strtotime($report->context->date);
}

unset($report);

$errors = [];

if (qg('id'))
{
    if (!count($reports)) {
        throw new UserException('Erreur inconnue');
    }

    $tpl->assign('id', qg('id'));
    $tpl->assign('main', reset($reports));
    $tpl->assign('reports', $reports);
}
else
{
    foreach ($reports as $report)
    {
        if (!isset($errors[$report->context->id]))
        {
            $errors[$report->context->id] = [
                'message' => $report->errors[0]->message,
                'source' => sprintf('%s:%d', $report->errors[0]->backtrace[0]->file, $report->errors[0]->backtrace[0]->line),
                'count' => 0,
            ];
        }

        $errors[$report->context->id]['last_seen'] = $report->context->date;
        $errors[$report->context->id]['count']++;
    }

    $tpl->assign('errors', $errors);
}



$tpl->display('admin/config/advanced/errors.tpl');

Added src/www/admin/config/advanced/index.php version [391415153c].







































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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(true);

$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/advanced/sql.php version [33f27e5775].

























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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 KD2\ErrorManager;

require_once __DIR__ . '/../_inc.php';

$list = null;
$table = qg('table');
$query = f('query');

$db = DB::getInstance();
$tables_list = $db->getGrouped('SELECT name, sql, NULL AS count FROM sqlite_master WHERE type = \'table\' ORDER BY name;');
$index_list = null;
$triggers_list = null;
$result = null;
$result_header = null;

if ($table) {
	$all_columns = $db->get(sprintf('PRAGMA table_info(%s);', $db->quoteIdentifier($table)));

	if (!$all_columns) {
		throw new UserException('This table does not exist');
	}

	$columns = [];

	foreach ($all_columns as $c) {
		$columns[$c->name] = ['label' => $c->name];
	}

	$list = new DynamicList($columns, $table);
	$list->orderBy(key($columns), false);
	$list->loadFromQueryString();
}
elseif ($query) {
	try {
		$result = Recherche::rawSQL($query);

		if (count($result)) {
			$result_header = array_keys((array)reset($result));
		}
	}
	catch (\Exception $e) {
		$form->addError($e->getMessage());
	}
}
else {
	foreach ($tables_list as $name => &$data) {
		$data->count = $db->count($name);
	}

	unset($data);
	$index_list = $db->getAssoc('SELECT name, sql FROM sqlite_master WHERE type = \'index\' AND name NOT LIKE \'sqlite_%\' ORDER BY name;');
	$triggers_list = $db->getAssoc('SELECT name, sql FROM sqlite_master WHERE type = \'trigger\' ORDER BY name;');
}

$tpl->assign(compact('index_list', 'triggers_list', 'tables_list', 'query', 'table', 'list', 'result', 'result_header'));

$tpl->display('admin/config/advanced/sql.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');

Modified src/www/admin/config/backup/restore.php from [c67b3c1387] to [c5bad54374].

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';

$s = new Sauvegarde;


if (f('create'))



{
    $form->check('backup_create');



    if (!$form->hasErrors())
    {
        try {
            $s->create();
            Utils::redirect(ADMIN_URL . 'config/donnees/local.php?ok=create');
        } catch (UserException $e) {
            $form->addError($e->getMessage());

        }



    }
}
if (f('restore'))

{
    $form->check('backup_manage');

    if (!$form->hasErrors())


    {
        try {
            $r = $s->restoreFromLocal(f('file'));
            Utils::redirect(ADMIN_URL . 'config/donnees/local.php?ok=restore&code=' . (int)$r);
        } catch (UserException $e) {
            $form->addError($e->getMessage());
        }
    }
}
elseif (f('remove'))
{
    $form->check('backup_manage');

    if (!$form->hasErrors())

    {
        try {
            $s->remove(f('file'));
            Utils::redirect(ADMIN_URL . 'config/donnees/local.php?ok=remove');
        } catch (UserException $e) {
            $form->addError($e->getMessage());
        }
    }
}

$tpl->assign('ok_code', qg('code'));
$tpl->assign('ok', qg('ok'));
$tpl->assign('liste', $s->getList());

$tpl->display('admin/config/donnees/local.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;

require_once __DIR__ . '/../_inc.php';

$s = new Sauvegarde;
$code = null; // error code

if (qg('download')) {
	$s->dump(qg('download'));
	exit;
}

$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(Utils::getSelfURI(['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');

Modified src/www/admin/config/backup/save.php from [a41ebc5c56] to [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
<?php
namespace Garradin;



require_once __DIR__ . '/../_inc.php';

$s = new Sauvegarde;

if (f('download'))
{



    $form->check('backup_download');

    if (!$form->hasErrors())
    {
        header('Content-type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $config->get('nom_asso') . ' - Sauvegarde données - ' . date('Y-m-d') . '.sqlite"');
        header('Content-Length: ' . $s->getDBSize(true));

        $s->dump();
        exit;

    }
}


elseif (f('restore_file'))

{
    $form->check('backup_restore');



    if (!$form->hasErrors())

    {
        // 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'], $user->id, $check);
            Utils::redirect(ADMIN_URL . 'config/donnees/?ok=restore&code=' . (int)$r);
        } catch (UserException $e) {
            $form->addError($e->getMessage());
            $code = $e->getCode();
        }


    }
}






$tpl->assign('db_size', $s->getDBSize());
$tpl->assign('files_size', $s->getDBFilesSize());

$tpl->assign('code', isset($code) ? $code : null);
$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');


>
>





|
<
>
>
>
|

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

|
|

<
<
|
<

|

|
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 [4d5e12122b].

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
53
<?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();
	$cat->hidden = (int) f('hidden');

	// 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/reset.php version [3891123042].

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;

require_once __DIR__ . '/../_inc.php';

$s = new Sauvegarde;

if (f('reset_ok'))
{
    $form->check('reset');

    if (!$form->hasErrors())
    {
        try {
            Install::reset($session, f('passe_verif'));
            Utils::redirect(ADMIN_URL . 'config/donnees/reset.php?ok');
        } catch (UserException $e) {
            $form->addError($e->getMessage());
        }
    }
}

$tpl->assign('ok', qg('ok'));

$tpl->display('admin/config/donnees/reset.tpl');
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































Added src/www/admin/config/edit_file.php version [8a746033ac].













































































































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

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

require __DIR__ . '/_inc.php';

$key = qg('k');

if (!isset(Config::DEFAULT_FILES[$key])) {
	throw new UserException('Fichier invalide');
}

$file_path = Config::DEFAULT_FILES[$key];

$file = Files::get($file_path);

if (!$file) {
	$file = File::create(Utils::dirname($file_path), Utils::basename($file_path), null, '');
	$content = '';
}
else {
	$content = $file->fetch();
}

$editor = $file->editorType();
$csrf_key = 'edit_file_' . $file->pathHash();

$form->runIf('save', function () use ($file, $key) {
	// For config files, make sure config value is updated
	$config = Config::getInstance();

	if (trim(f('content')) === '') {
		$file->delete();
		$config->set($key, null);
		$config->save();
	}
	else {
		$file->setContent(f('content'));
		$config->set($key, $file->path);
		$config->save();
	}

	if (qg('js') !== null) {
		die('{"success":true}');
	}

}, $csrf_key, Utils::getSelfURI());

$tpl->assign('file', $file);

$tpl->assign(compact('csrf_key', 'content'));
$tpl->display(sprintf('common/files/edit_%s.tpl', $editor));

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 [097a1ffa72].

52
53
54
55
56
57
58


59


}
else
{
    $tpl->assign('liste_telecharges', Plugin::listDownloaded());
    $tpl->assign('liste_installes', Plugin::listInstalled());
}



$tpl->display('admin/config/plugins.tpl');









>
>

>
>
52
53
54
55
56
57
58
59
60
61
62
63
}
else
{
    $tpl->assign('liste_telecharges', Plugin::listDownloaded());
    $tpl->assign('liste_installes', Plugin::listInstalled());
}

$tpl->assign('garradin_website', WEBSITE);

$tpl->display('admin/config/plugins.tpl');

Plugin::upgradeAllIfRequired();

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 [1987800963].













































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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/?path=' . $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/?path=' . $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 [7fe6a0182d].





























































































































































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

namespace Garradin;

use Garradin\Files\Files;
use Garradin\Files\Transactions;
use Garradin\Files\Users;
use Garradin\Entities\Files\File;

require_once __DIR__ . '/_inc.php';

$path = trim(qg('path')) ?: File::CONTEXT_DOCUMENTS;

$context = Files::getContext($path);
$context_ref = Files::getContextRef($path);
$list = null;

// Specific lists for some contexts
if ($context == File::CONTEXT_TRANSACTION) {
	if (!$session->canAccess($session::SECTION_ACCOUNTING, $session::ACCESS_READ)) {
		throw new UserException('Vous n\'avez pas accès à ce répertoire');
	}

	if (!$context_ref) {
		$list = Transactions::list();
		$can_delete = $can_write = false;
	}
}
elseif ($context == File::CONTEXT_USER) {
	if (!$session->canAccess($session::SECTION_USERS, $session::ACCESS_READ)) {
		throw new UserException('Vous n\'avez pas accès à ce répertoire');
	}

	if (!$context_ref) {
		$list = Users::list();
		$can_delete = $can_write = false;
	}
}

if (null == $list) {
	$list = Files::list($path);

	// We consider that the first file has the same rights as the others
	if (count($list)) {
		$first = current($list);

		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;
	}
}
elseif ($list instanceof DynamicList) {
	$list->loadFromQueryString();
}

$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 = $quota_max ? round(($quota_used / $quota_max) * 100) : 100;

$tpl->assign(compact('path', 'list', '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 [d2c27619fc].





















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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('path'));

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/?path=' . $parent);

$tpl->assign(compact('csrf_key'));

$tpl->display('docs/new_dir.tpl');

Added src/www/admin/docs/new_file.php version [b548528de7].



































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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('path'));

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/?path=' . $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');

Added src/www/admin/docs/zip.php version [21577262c1].







































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

namespace Garradin;

use Garradin\Files\Files;
use Garradin\Files\Transactions;
use Garradin\Files\Users;
use Garradin\Entities\Files\File;

require_once __DIR__ . '/_inc.php';

$path = trim(qg('path')) ?: File::CONTEXT_DOCUMENTS;

$name = preg_replace('/[^\p{L}_-]+/i', '_', $path);
$name = sprintf('%s - Fichiers - %s.zip', Config::getInstance()->get('nom_asso'), $name);
header('Content-type: application/zip');
header(sprintf('Content-Disposition: attachment; filename="%s"', $name));

Files::zip($path, $session);

Modified src/www/admin/index.php from [d909595888] to [025ac1c529].

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;

require_once __DIR__ . '/_inc.php';



$cats = new Membres\Categories;
$categorie = $cats->get($user->id_categorie);


$homepage = Config::getInstance()->get('admin_homepage');

$banner = null;
Plugin::fireSignal('accueil.banniere', ['user' => $user, 'session' => $session], $banner);








$tpl->assign(compact('categorie', 'homepage', '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(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 [d0c2a835bd] 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
<?php
namespace Garradin;



const INSTALL_PROCESS = true;

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







Install::checkAndCreateDirectories();






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 [939e98ed56] to [052d532ffd].

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 LOGIN_PROCESS = true;

require_once __DIR__ . '/_inc.php';

// L'utilisateur est déjà connecté
if ($session->isLogged())
{
    Utils::redirect(ADMIN_URL . '');
}

// Relance session_start et renvoie une image de 1px transparente
if (qg('keepSessionAlive') !== null)
{
    $session->keepAlive();

    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

    header('Content-Type: image/gif');
    echo base64_decode("R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==");

    exit;
}







$champs = $config->get('champs_membres');
$id_field = (object) $champs->get($config->get('champ_identifiant'));
$id_field_name = $id_field->title;

$form->runIf('login', function () use ($id_field_name, $session) {
    if (!trim(f('_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
<?php
namespace Garradin;

const LOGIN_PROCESS = true;

require_once __DIR__ . '/_inc.php';







// Relance session_start et renvoie une image de 1px transparente
if (qg('keepSessionAlive') !== null)
{
    $session->keepAlive();

    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

    header('Content-Type: image/gif');
    echo base64_decode("R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==");

    exit;
}

// L'utilisateur est déjà connecté
if ($session->isLogged())
{
    Utils::redirect(ADMIN_URL . '');
}

$champs = $config->get('champs_membres');
$id_field = (object) $champs->get($config->get('champ_identifiant'));
$id_field_name = $id_field->title;

$form->runIf('login', function () use ($id_field_name, $session) {
    if (!trim(f('_id'))) {
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::getSelfURL()));

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

Added src/www/admin/me/edit.php version [80d70aeee3].































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$csrf_key = 'edit_my_info';

$form->runIf('save', function () use ($session) {
	$data = [];
	$config = Config::getInstance();
	$champs = Config::getInstance()->get('champs_membres');

	foreach ($champs->getAll() as $key=>$c) {
		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);
}, $csrf_key, '!me/?ok');

$data = $session->getUser();
$champs = Config::getInstance()->get('champs_membres')->getAll();

$tpl->assign(compact('csrf_key', 'champs', 'data'));

$tpl->display('me/edit.tpl');

Added src/www/admin/me/export.php version [0d8851baae].























































































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

use Garradin\Services\Services_User;
use Garradin\Files\Files;
use Garradin\Entities\Files\File;

use KD2\ZipWriter;

require_once __DIR__ . '/../_inc.php';

$data = $session->getUser();
$champs = Config::getInstance()->get('champs_membres');
$champs_list = $champs->getList();

$services_list = Services_User::perUserList($user->id);
$services_list->setPageSize(null);

$export_data = [
	'user' => $data,
	'services' => $services_list->asArray(),
];

$tpl->assign(compact('champs_list', 'data', 'services_list'));

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

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


$zip->add('info.html', $tpl->fetch('me/export.tpl'));
$zip->add('info.json', json_encode($export_data));

foreach (Files::listForContext(File::CONTEXT_USER, $data->id) as $dir) {
	foreach (Files::list($dir->path) as $file) {
		$zip->add($file->path, null, $file->fullpath());
	}
}

$zip->close();

Modified src/www/admin/me/index.php from [dd87b3ed86] to [cd4ab73468].

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;

require_once __DIR__ . '/_inc.php';

$champs = $config->get('champs_membres');

if (f('save'))
{
    $form->check('edit_me', $champs->getValidationRules('user_edit'));

    if (!$form->hasErrors())
    {
        try {
            $data = [];

            foreach ($champs->getAll() as $key=>$c)
            {
                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);
        }
        catch (UserException $e)
        {
            $form->addError($e->getMessage());
        }
    }
}

$tpl->assign('champs', $champs->getAll());

$tpl->assign('membre', $session->getUser());

$tpl->display('admin/mes_infos.tpl');



|

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

<
<
<
<
<
<
<
<
<
<
<
<
<
|
1
2
3
4
5









6
7

8





9


10
11

12













13
<?php
namespace Garradin;

require_once __DIR__ . '/../_inc.php';










$data = $session->getUser();
$champs = Config::getInstance()->get('champs_membres')->getList();







$ok = qg('ok');



$tpl->assign(compact('champs', 'data', 'ok'));















$tpl->display('me/index.tpl');

Modified src/www/admin/me/security.php from [07c69221f1] to [52a874b9dd].

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;

require_once __DIR__ . '/_inc.php';

$confirm = false;

if (f('confirm'))
{
    $form->check('edit_me_security', [
        'passe'       => 'confirmed|min:6',
        'passe_check' => 'required',
    ]);

    if (f('passe_check') && !$session->checkPassword(f('passe_check'), $user->passe))
    {
        $form->addError('Le mot de passe fourni ne correspond pas au mot de passe actuel. Merci de bien vouloir renseigner votre mot de passe courant pour confirmer les changements.');
    }
    elseif (f('otp_secret') && f('otp_secret') != 'disable' && !f('code')) {
        $form->addError('Le code OTP est obligatoire');
    }
    elseif (f('code') && !$session->checkOTP(f('otp_secret'), f('code')))
    {
        $form->addError('Le code TOTP entré n\'est pas valide.');
    }

    if (!$form->hasErrors())
    {
        try {
            $data = [
                'clef_pgp' => f('clef_pgp'),
            ];

            if (f('passe') && !empty($config->get('champs_membres')->get('passe')->editable))
            {
                $data['passe'] = f('passe');
            }

            if (f('otp_secret') == 'disable')
            {
                $data['secret_otp'] = null;
            }
            elseif (f('otp_secret') !== null)
            {
                $data['secret_otp'] = f('otp_secret');
            }

            $session->editSecurity($data);
            Utils::redirect(ADMIN_URL . 'mes_infos_securite.php?ok');
        }
        catch (UserException $e)
        {
            $form->addError($e->getMessage());
        }
    }

    $confirm = true;
}
elseif (f('save'))
{
    $form->check('edit_me_security', [
        'passe'       => 'confirmed|min:6',
    ]);

    if (f('clef_pgp') && !$session->getPGPFingerprint(f('clef_pgp')))
    {
        $form->addError('Clé PGP invalide : impossible de récupérer l\'empreinte de la clé.');
    }
    
    if (!$form->hasErrors())
    {
        $confirm = true;
    }
}

$tpl->assign('confirm', $confirm);

if (f('otp') == 'generate')
{
    $tpl->assign('otp', $session->getNewOTPSecret());
}
elseif (f('otp') == 'disable')
{
    $tpl->assign('otp', 'disable');
}
elseif (f('otp_secret'))
{
    $tpl->assign('otp', $session->getOTPSecret(f('otp_secret')));
}
else
{
    $tpl->assign('otp', false);
}

$tpl->assign('pgp_disponible', \KD2\Security::canUseEncryption());

$fingerprint = '';

if ($user->clef_pgp)
{
    $fingerprint = $session->getPGPFingerprint($user->clef_pgp, true);
}

$tpl->assign('clef_pgp_fingerprint', $fingerprint);

$tpl->assign('passphrase', Utils::suggestPassword());
$tpl->assign('champs', $config->get('champs_membres')->getAll());

$tpl->assign('membre', $user);
$tpl->assign('ok', qg('ok') !== null);

$tpl->display('admin/mes_infos_securite.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php

namespace Garradin;

require_once __DIR__ . '/../_inc.php';

$confirm = false;

if (f('confirm'))
{
	$form->check('edit_me_security', [
		'passe'       => 'confirmed|min:6',
		'passe_check' => 'required',
	]);

	if (f('passe_check') && !$session->checkPassword(f('passe_check'), $user->passe))
	{
		$form->addError('Le mot de passe fourni ne correspond pas au mot de passe actuel. Merci de bien vouloir renseigner votre mot de passe courant pour confirmer les changements.');
	}
	elseif (f('otp_secret') && f('otp_secret') != 'disable' && !f('code')) {
		$form->addError('Le code OTP est obligatoire');
	}
	elseif (f('code') && !$session->checkOTP(f('otp_secret'), f('code')))
	{
		$form->addError('Le code TOTP entré n\'est pas valide.');
	}

	if (!$form->hasErrors())
	{
		try {
			$data = [
				'clef_pgp' => f('clef_pgp'),
			];

			if (f('passe') && !empty($config->get('champs_membres')->get('passe')->editable))
			{
				$data['passe'] = f('passe');
			}

			if (f('otp_secret') == 'disable')
			{
				$data['secret_otp'] = null;
			}
			elseif (f('otp_secret') !== null)
			{
				$data['secret_otp'] = f('otp_secret');
			}

			$session->editSecurity($data);
			Utils::redirect(ADMIN_URL . 'me/security.php?ok');
		}
		catch (UserException $e)
		{
			$form->addError($e->getMessage());
		}
	}

	$confirm = true;
}
elseif (f('save'))
{
	$form->check('edit_me_security', [
		'passe'       => 'confirmed|min:6',
	]);

	if (f('clef_pgp') && !$session->getPGPFingerprint(f('clef_pgp')))
	{
		$form->addError('Clé PGP invalide : impossible de récupérer l\'empreinte de la clé.');
	}
	
	if (!$form->hasErrors())
	{
		$confirm = true;
	}
}

$tpl->assign('confirm', $confirm);

if (f('otp') == 'generate')
{
	$tpl->assign('otp', $session->getNewOTPSecret());
}
elseif (f('otp') == 'disable')
{
	$tpl->assign('otp', 'disable');
}
elseif (f('otp_secret'))
{
	$tpl->assign('otp', $session->getOTPSecret(f('otp_secret')));
}
else
{
	$tpl->assign('otp', false);
}

$tpl->assign('pgp_disponible', \KD2\Security::canUseEncryption());

$fingerprint = '';

if ($user->clef_pgp)
{
	$fingerprint = $session->getPGPFingerprint($user->clef_pgp, true);
}

$tpl->assign('clef_pgp_fingerprint', $fingerprint);

$tpl->assign('passphrase', Utils::suggestPassword());
$tpl->assign('champs', $config->get('champs_membres')->getAll());

$tpl->assign('membre', $user);
$tpl->assign('ok', qg('ok') !== null);

$tpl->display('me/security.tpl');

Modified src/www/admin/me/services.php from [395c086295] to [29032889e2].

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;

require_once __DIR__ . '/_inc.php';

$tpl->assign('membre', $user);

$list = Services_User::perUserList($user->id);
$list->loadFromQueryString();

$tpl->assign(compact('list'));

$tpl->assign('services', Services_User::listDistinctForUser($user->id));

$tpl->display('my_services.tpl');





|










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

require_once __DIR__ . '/../_inc.php';

$tpl->assign('membre', $user);

$list = Services_User::perUserList($user->id);
$list->loadFromQueryString();

$tpl->assign(compact('list'));

$tpl->assign('services', Services_User::listDistinctForUser($user->id));

$tpl->display('me/services.tpl');

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 [4096d65e9e].

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
<?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->display('admin/membres/fiche.tpl');

Modified src/www/admin/membres/import.php from [34b02fc73c] 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')
{
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    $columns[$key] = $config->title;
}

$csv->setColumns($columns);

if (f('cancel')) {
    $csv->clear();
    Utils::redirect(Utils::getSelfURL(false));
}

$form->runIf(f('import') && $csv->loaded(), function () use ($csv, $import, $user) {
    $csv->setTranslationTable(f('translation_table'));
    $csv->skip((int)f('skip_first_line'));
    $import->fromCustomCSV($csv, $user->id);
    $csv->clear();
}, $csrf_key, ADMIN_URL . 'membres/import.php?ok');

$form->runIf(f('import') && f('type') == 'garradin' && !empty($_FILES['upload']['tmp_name']), function () use ($import, $user) {
    $import->fromGarradinCSV($_FILES['upload']['tmp_name'], $user->id);







|



|







34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    $columns[$key] = $config->title;
}

$csv->setColumns($columns);

if (f('cancel')) {
    $csv->clear();
    Utils::redirect(Utils::getSelfURI(false));
}

$form->runIf(f('import') && $csv->loaded(), function () use ($csv, $import, $user) {
    $csv->setTranslationTable(f('translation_table') ?? []);
    $csv->skip((int)f('skip_first_line'));
    $import->fromCustomCSV($csv, $user->id);
    $csv->clear();
}, $csrf_key, ADMIN_URL . 'membres/import.php?ok');

$form->runIf(f('import') && f('type') == 'garradin' && !empty($_FILES['upload']['tmp_name']), function () use ($import, $user) {
    $import->fromGarradinCSV($_FILES['upload']['tmp_name'], $user->id);

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 [b187670977] to [040e680ac0].

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;



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',
        'recipients' => 'required|string',
    ]);

    if (preg_match('/^(categorie|recherche)_(\d+)$/', f('recipients'), $match))
    {
        if ($match[1] == 'categorie')
        {
            $recipients = $membres->listAllByCategory($match[2], true);
        }
        else
        {
            try {
                $recipients = $recherche->search($match[2], ['id', 'email'], true);
            }
            catch (UserException $e) {
                $form->addError($e->getMessage());
            }
        }

        if (isset($recipients) && !count($recipients))


>
>



<



















|







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\Users\Categories;

require_once __DIR__ . '/_inc.php';


$recherche = new Recherche;

if (f('send'))
{
    $form->check('send_message_co', [
        'sujet'      => 'required|string',
        'message'    => 'required|string',
        'recipients' => 'required|string',
    ]);

    if (preg_match('/^(categorie|recherche)_(\d+)$/', f('recipients'), $match))
    {
        if ($match[1] == 'categorie')
        {
            $recipients = $membres->listAllByCategory($match[2], true);
        }
        else
        {
            try {
                $recipients = $recherche->search($match[2], ['membres.id', 'membres.email'], true);
            }
            catch (UserException $e) {
                $form->addError($e->getMessage());
            }
        }

        if (isset($recipients) && !count($recipients))
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 [cbd131a783].

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, pour éviter de vous empêcher de vous reconnecter.\nUtilisez la page 'Mes infos personnelles' pour modifier vos informations.");
}


$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
64
65
66
67
            $data = [];

            foreach ($champs->getAll() as $key=>$config)
            {
                $data[$key] = f($key);
            }

            if (f('delete_password')) {
                $data['delete_password'] = true;
            }

            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');







|
|

|




86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
}

$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/password.php from [51fae7e937] to [8dbf35c476].

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    }
    else
    {
        if (f('change') && $form->check('changePassword'))
        {
            try {
                $session->recoverPasswordChange(qg('c'), f('passe'), f('passe_confirmed'));
                Utils::redirect('/admin/login.php?changed');
            }
            catch (UserException $e) {
                $form->addError($e->getMessage());
            }
        }

        $tpl->assign('passphrase', Utils::suggestPassword());







|







14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    }
    else
    {
        if (f('change') && $form->check('changePassword'))
        {
            try {
                $session->recoverPasswordChange(qg('c'), f('passe'), f('passe_confirmed'));
                Utils::redirect('!login.php?changed');
            }
            catch (UserException $e) {
                $form->addError($e->getMessage());
            }
        }

        $tpl->assign('passphrase', Utils::suggestPassword());

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 [abf3bfa33d].

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;

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");
}

$csrf_key = 'service_delete_' . $service->id();

$form->runIf('delete', function () use ($service) {




	$service->delete();
}, $csrf_key, ADMIN_URL . 'services/');

$tpl->assign(compact('service', 'csrf_key'));

$tpl->display('services/delete.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\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");
}

$csrf_key = 'service_delete_' . $service->id();

$form->runIf('delete', function () use ($service) {
	if (!f('confirm_delete')) {
		throw new UserException('Merci de cocher la case pour confirmer la suppression.');
	}

	$service->delete();
}, $csrf_key, ADMIN_URL . 'services/');

$tpl->assign(compact('service', 'csrf_key'));

$tpl->display('services/delete.tpl');

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 [36d8ff0ccb].

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\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");
}

$csrf_key = 'fee_delete_' . $fee->id();

$form->runIf('delete', function () use ($fee) {




	$fee->delete();
}, $csrf_key, ADMIN_URL . 'services/fees/?id=' . $fee->id_service);

$tpl->assign(compact('fee', 'csrf_key'));

$tpl->display('services/fees/delete.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\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");
}

$csrf_key = 'fee_delete_' . $fee->id();

$form->runIf('delete', function () use ($fee) {
	if (!f('confirm_delete')) {
		throw new UserException('Merci de cocher la case pour confirmer la suppression.');
	}

	$fee->delete();
}, $csrf_key, ADMIN_URL . 'services/fees/?id=' . $fee->id_service);

$tpl->assign(compact('fee', 'csrf_key'));

$tpl->display('services/fees/delete.tpl');

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/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 [98a8dbe0ad] to [afd86fb166].

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\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');
}

$csrf_key = 'reminder_add';

$form->runIf('save', function () {
	$reminder = new Reminder;
	$reminder->importForm();
	$reminder->save();
}, $csrf_key, Utils::getSelfURL());

$list = Reminders::list();
$services_list = Services::listAssoc();

$default_subject = '[#NOM_ASSO] Échéance de cotisation';
$default_body = "Bonjour #IDENTITE,\n\nVotre cotisation arrive à échéance dans #NB_JOURS jours.\n\n"
	.   "Merci de nous contacter pour renouveler votre cotisation.\n\nCordialement.\n\n"
	.   "--\n#NOM_ASSO\n#ADRESSE_ASSO\nE-Mail : #EMAIL_ASSO\nSite web : #SITE_ASSO";

$tpl->assign(compact('csrf_key', 'list', 'services_list', 'default_subject', 'default_body'));

$tpl->display('services/reminders/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
<?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');
}

$csrf_key = 'reminder_add';

$form->runIf('save', function () {
	$reminder = new Reminder;
	$reminder->importForm();
	$reminder->save();
}, $csrf_key, Utils::getSelfURI());

$list = Reminders::list();
$services_list = Services::listAssoc();

$default_subject = '[#NOM_ASSO] Échéance de cotisation';
$default_body = "Bonjour #IDENTITE,\n\nVotre cotisation arrive à échéance dans #NB_JOURS jours.\n\n"
	.   "Merci de nous contacter pour renouveler votre cotisation.\n\nCordialement.\n\n"
	.   "--\n#NOM_ASSO\n#ADRESSE_ASSO\nE-Mail : #EMAIL_ASSO\nSite web : #SITE_ASSO";

$tpl->assign(compact('csrf_key', 'list', 'services_list', 'default_subject', 'default_body'));

$tpl->display('services/reminders/index.tpl');

Added src/www/admin/services/reminders/user.php version [2a049e4faf].































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace Garradin;

use Garradin\Entities\Services\Reminder;
use Garradin\Services\Reminders;
use Garradin\Services\Services;

require_once __DIR__ . '/../_inc.php';

$user_id = (int) qg('id');
$list = Reminders::listSentForUser($user_id);

$tpl->assign(compact('list', 'user_id'));

$tpl->display('services/reminders/user.tpl');

Added src/www/admin/services/user/_form.php version [355c6ae19e].





































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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\Services\Services;


if (!defined('\Garradin\ROOT')) {
	die();
}

assert(isset($tpl, $form_url));

$current_only = !qg('past_services');

$grouped_services = Services::listGroupedWithFees($user_id, $current_only);

if (!count($grouped_services)) {
	Utils::redirect($form_url . 'past_services=' . (int) $current_only);
}

if (!isset($count_all)) {
	$count_all = Services::count();
}

$has_past_services = count($grouped_services) != $count_all;

$today = new \DateTime;

$tpl->assign([
	'custom_js' => ['service_form.js'],
]);

$tpl->assign(compact('form_url', 'today', 'grouped_services', 'user_name', 'user_id', 'current_only', 'has_past_services'));

Modified src/www/admin/services/user/add.php from [0bec8e59c8] to [7cb44e6fd8].

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
<?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');
}

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
$user_id = (int) $user_id ?: null;
$user_name = $user_id ? (new Membres)->getNom($user_id) : null;

if (!$user_name) {
	$user_id = null;
}


$current_only = !qg('past_services');

$grouped_services = Services::listGroupedWithFees($user_id, $current_only);



if (!count($grouped_services)) {
	Utils::redirect(Utils::getSelfURI(['user' => $user_id, 'past_services' => $current_only]));
}

$has_past_services = count($grouped_services) != $count_all;


$csrf_key = 'service_save';

$form->runIf('save', function () use ($session) {
	$su = Service_User::saveFromForm($session->getUser()->id);

	Utils::redirect(ADMIN_URL . 'services/user.php?id=' . $su->id_user);
}, $csrf_key);

$selected_user = $user_name ? [$user_id => $user_name] : null;

$types_details = Transaction::getTypesDetails();
$account_targets = $types_details[Transaction::TYPE_REVENUE]->accounts[1]->targets_string;

$today = new \DateTime;

$tpl->assign(compact('today', 'grouped_services', 'csrf_key', 'selected_user', 'account_targets', 'user_name', 'user_id', 'current_only', 'has_past_services'));

$tpl->display('services/save.tpl');







>
|

<
>

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

|







|

|

|
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
$user_id = (int) $user_id ?: null;
$user_name = $user_id ? (new Membres)->getNom($user_id) : null;

if (!$user_name) {
	$user_id = null;
}

$form_url  = sprintf('?user=%d&', $user_id);
$csrf_key = 'service_save';


require __DIR__ . '/_form.php';

$form->runIf(f('save') || f('save_and_add_payment'), function () use ($session) {
	$su = Service_User::saveFromForm($session->getUser()->id);


	if (f('save_and_add_payment')) {
		$url = ADMIN_URL . 'services/user/payment.php?id=' . $su->id;
	}
	else {
		$url = ADMIN_URL . 'services/user/?id=' . $su->id_user;
	}



	Utils::redirect($url);
}, $csrf_key);

$selected_user = $user_name ? [$user_id => $user_name] : null;

$types_details = Transaction::getTypesDetails();
$account_targets = $types_details[Transaction::TYPE_REVENUE]->accounts[1]->targets_string;

$service_user = null;

$tpl->assign(compact('csrf_key', 'selected_user', 'account_targets', 'service_user'));

$tpl->display('services/user/add.tpl');

Modified src/www/admin/services/user/delete.php from [c5d8584c97] to [7095fc2db0].

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\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");
}

$csrf_key = 'su_delete_' . $su->id();
$user_id = $su->id_user;

$form->runIf('delete', function () use ($su) {
	$su->delete();
}, $csrf_key, ADMIN_URL . 'services/user.php?id=' . $user_id);






$tpl->assign(compact('csrf_key'));

$tpl->display('services/user_delete.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
<?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");
}

$csrf_key = 'su_delete_' . $su->id();
$user_id = $su->id_user;

$form->runIf('delete', function () use ($su) {
	$su->delete();
}, $csrf_key, ADMIN_URL . 'services/user/?id=' . $user_id);

$user_name = (new Membres)->getNom($user_id);

$service_name = $su->service()->label;
$fee_name = $su->fee()->label;

$tpl->assign(compact('csrf_key', 'user_name', 'fee_name', 'service_name'));

$tpl->display('services/user/delete.tpl');

Added src/www/admin/services/user/edit.php version [b0b3db3c77].

































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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_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");
}

$csrf_key = 'su_edit_' . $su->id();
$user_id = $su->id_user;
$user_name = (new Membres)->getNom($user_id);
$form_url = sprintf('edit.php?id=%d&', $su->id());

require __DIR__ . '/_form.php';

$form->runIf('save', function () use ($su) {
	$su->importForm();
	$su->save();
}, $csrf_key, ADMIN_URL . 'services/user/?id=' . $user_id);

$service_user = $su;

$tpl->assign(compact('csrf_key', 'service_user'));

$tpl->display('services/user/edit.tpl');

Modified src/www/admin/services/user/index.php from [e3055067d1] to [1dbf771034].

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\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');
	$su->save();
}, null, ADMIN_URL . 'services/user.php?id=' . $user->id);

$list = Services_User::perUserList($user->id);
$list->setTitle(sprintf('Inscriptions — %s', $user->identite));
$list->loadFromQueryString();

$tpl->assign('services', Services_User::listDistinctForUser($user->id));
$tpl->assign(compact('list', 'user'));

$tpl->display('services/user.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
<?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');
	$su->save();
}, null, ADMIN_URL . 'services/user/?id=' . $user->id);

$list = Services_User::perUserList($user->id);
$list->setTitle(sprintf('Inscriptions — %s', $user->identite));
$list->loadFromQueryString();

$tpl->assign('services', Services_User::listDistinctForUser($user->id));
$tpl->assign(compact('list', 'user'));

$tpl->display('services/user/index.tpl');

Modified src/www/admin/services/user/payment.php from [a8ad0d0fc0] to [9913d7fba3].

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;

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");
}

$user_name = (new Membres)->getNom($su->id_user);

$csrf_key = 'service_pay';

$form->runIf('save', function () use ($su, $session) {
	$su->addPayment($session->getUser()->id);

	if ($su->paid != (bool) f('paid')) {
		$su->paid = (bool) f('paid');
		$su->save();
	}








	Utils::redirect(ADMIN_URL . 'services/user.php?id=' . $su->id_user);
}, $csrf_key);

$types_details = Transaction::getTypesDetails();
$account_targets = $types_details[Transaction::TYPE_REVENUE]->accounts[1]->targets_string;

$tpl->assign(compact('csrf_key', 'account_targets', 'user_name', 'su'));

$tpl->display('services/payment.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
<?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");
}

$user_name = (new Membres)->getNom($su->id_user);

$csrf_key = 'service_pay';

$form->runIf(f('save') || f('save_and_add_payment'), function () use ($su, $session) {
	$su->addPayment($session->getUser()->id);

	if ($su->paid != (bool) f('paid')) {
		$su->paid = (bool) f('paid');
		$su->save();
	}

	if (f('save_and_add_payment')) {
		$url = ADMIN_URL . 'services/user/payment.php?id=' . $su->id;
	}
	else {
		$url = ADMIN_URL . 'services/user/?id=' . $su->id_user;
	}

	Utils::redirect($url);
}, $csrf_key);

$types_details = Transaction::getTypesDetails();
$account_targets = $types_details[Transaction::TYPE_REVENUE]->accounts[1]->targets_string;

$tpl->assign(compact('csrf_key', 'account_targets', 'user_name', 'su'));

$tpl->display('services/user/payment.tpl');

Modified src/www/admin/static/handheld.css from [82c8dcdda9] to [796936d9ab].

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

.filterCategory, .searchMember {
	width: auto;
	float: none;
}

pre.sql_schema, .wikiChildren, fieldset.wikiMain, fieldset.wikiRights, fieldset.wikiEncrypt {
	float: none;
	width: auto;
}

dl.describe {
	margin: 0 .5em;
}







|







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

.filterCategory, .searchMember {
	width: auto;
	float: none;
}

.wikiChildren, fieldset.wikiMain, fieldset.wikiRights, fieldset.wikiEncrypt {
	float: none;
	width: auto;
}

dl.describe {
	margin: 0 .5em;
}

Modified src/www/admin/static/print.css from [5d6f8ad8c8] to [6937e4b226].

1
2
3
4




5
6
7
8
9
10
11
@page {
    size: A4 landscape;
    margin: 0;
}





body {
    background: #fff;
    padding: 0;
    margin: 1cm;
    font-size: 10pt;
}




>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@page {
    size: A4 landscape;
    margin: 0;
}

html {
    height: auto;
}

body {
    background: #fff;
    padding: 0;
    margin: 1cm;
    font-size: 10pt;
}
97
98
99
100
101
102
103








    text-decoration: none;
}

/* Don't repeat the table footer on every printed page */
table tfoot{
    display:table-row-group;
}















>
>
>
>
>
>
>
>
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    text-decoration: none;
}

/* Don't repeat the table footer on every printed page */
table tfoot{
    display:table-row-group;
}

details summary::after {
    display: none;
}

.ruler::after, .ruler::before {
    display: none;
}

Modified src/www/admin/static/scripts/accounting.js from [f16f1d5eef] to [2c31b52794].

97
98
99
100
101
102
103

104
105
106
107
108
109
110
111

			i.value = '';
		})

		var b = n.querySelector('.input-list button');
		b.onclick = () => {
			g.current_list_input = b.parentNode;

			g.openFrameDialog(b.value);
			return false;
		};
		line.parentNode.appendChild(n);
		initLine(n);
	};

	updateTotals();







>
|







97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

			i.value = '';
		})

		var b = n.querySelector('.input-list button');
		b.onclick = () => {
			g.current_list_input = b.parentNode;
			let url = b.value + (b.value.indexOf('?') > 0 ? '&' : '?') + '_dialog';
			g.openFrameDialog(url);
			return false;
		};
		line.parentNode.appendChild(n);
		initLine(n);
	};

	updateTotals();

Name change from src/www/admin/static/scripts/skel_editor.css to src/www/admin/static/scripts/code_editor.css.

Modified src/www/admin/static/scripts/code_editor.js from [807c3cfad0] to [81fbe437c7].

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
(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 = '?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();

|
|


<
<














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

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







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
(function (){
	g.style('scripts/code_editor.css');
	g.script('scripts/lib/code_editor.min.js', function ()
	{
		var save_btn = document.querySelector('[name=save]');


		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 ()
		{


			save_btn.click();






























		};

		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();
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

		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 = '';









		}
	});
}());







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


>









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



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

		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;
			};
		}
		else {
			appendButton('fullscreen', 'Plein écran', code.toggleFullscreen);
		}
	});
}());

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 [0da4b43a86].

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
441
		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'))
				{
					this.selectedIndex = 0;
					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);

Name change from src/www/admin/static/scripts/code_editor.min.js to src/www/admin/static/scripts/lib/code_editor.min.js.

Name change from src/www/admin/static/scripts/text_editor.min.js to src/www/admin/static/scripts/lib/text_editor.min.js.

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);

Modified src/www/admin/static/scripts/selector.js from [049f79c975] to [09cbc2d747].

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

rows.forEach((e, k) => {
	e.classList.add('clickable');
	var l = e.querySelector('td').innerText + ' ' + e.querySelector('th').innerText;
	e.setAttribute('data-search-label', normalizeString(l));

	e.querySelector('button').onfocus = () => {
		rows.forEach((r) => {
			if (r == e) {
				return;
			}

			r.classList.remove('focused');
		});

		e.classList.add('focused');
	};

	e.onclick = (evt) => {
		if (evt.target.tagName && evt.target.tagName == 'BUTTON') {
			return;
		}

		e.querySelector('button').click();
	};
});

document.onkeydown = (evt) => {
	let focus = document.activeElement;

	let new_focus;



	// Get first element

	if (focus.tagName != 'BUTTON') {

		new_focus = document.querySelector('table tr');


	}

	if (evt.key == 'ArrowUp' && !new_focus) {
		let idx = focus.parentNode.parentNode.dataset.idx - 1;

		if (idx == 0) {
			return true;
		}


		new_focus = rows[idx - 1];
	}
	else if (evt.key == 'ArrowDown' && !new_focus) {
		let idx = focus.parentNode.parentNode.dataset.idx - 1;





		if (idx >= rows.length - 1) {
			return true;
		}




		new_focus = rows[idx + 1];
	}
	else {
		new_focus = null;

	}

	if (!new_focus) {
		return true;
	}





	new_focus.querySelector('button').focus();


	return false;
};

buttons[0].focus();

var q = document.getElementById('lookup');

if (q) {
	q.onkeyup = (e) => {
		var query = new RegExp(RegExp.escape(normalizeString(q.value)), 'i');

		rows.forEach((elm) => {
			if (elm.getAttribute('data-search-label').match(query)) {
				elm.style.display = null;
			}
			else {
				elm.style.display = 'none';
			}
		});














		return false;
	};

	q.focus();
}

var o = document.getElementById('f_typed_only_0');

if (o) {
	o.onchange = () => {
		let s = new URLSearchParams(window.location.search);
		s.set("all", o.checked ? 0 : 1);
		window.location.search = s.toString();
	};
}







<
<
<
<
|
|
<
|












|
|
>
|

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

|
|
|

>
|

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


<
>


|
|

>
>
|
>
>
|
>
>

|






|




|


|



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

|













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

rows.forEach((e, k) => {
	e.classList.add('clickable');
	var l = e.querySelector('td').innerText + ' ' + e.querySelector('th').innerText;
	e.setAttribute('data-search-label', normalizeString(l));

	e.querySelector('button').onfocus = () => {




		if (f = document.querySelector('tr.focused')) {
			f.classList.remove('focused');

		}
		e.classList.add('focused');
	};

	e.onclick = (evt) => {
		if (evt.target.tagName && evt.target.tagName == 'BUTTON') {
			return;
		}

		e.querySelector('button').click();
	};
});

document.addEventListener('keydown', (evt) => {
	let current = document.querySelector('tbody tr.focused:not(.hidden)') || document.querySelector('tbody tr');
	let available = [];
	let idx = 0;

	for (var i = 0; i < rows.length; i++) {
		if (rows[i].classList.contains('hidden')) {
			continue;
		}

		available.push(rows[i]);

		if (rows[i] === current) {
			idx = available.length - 1;
		}
	}



	if (!available.length) {
		return false;
	}

	if (evt.key == 'ArrowUp') { // Previous item
		idx--;
	}
	else if (evt.key == 'ArrowDown') {
		idx++;
	}
	else if (evt.key == 'PageUp') {
		idx-=10;
	}
	else if (evt.key == 'PageDown') {
		idx+=10;

	}
	else if (evt.key == 'Home') {
		idx = 0;
	}
	else if (evt.key == 'End') {
		idx = available.length;
	}
	else {

		return true;
	}

	if (idx < 0) {
		idx = 0;
	}
	else if (idx >= available.length - 1) {
		idx = available.length - 1;
	}

	current = available[idx];
	current.querySelector('button').focus();

	evt.preventDefault();
	return false;
});

buttons[0].focus();

var q = document.getElementById('lookup');

if (q) {
	q.addEventListener('keyup', (e) => {
		var query = new RegExp(RegExp.escape(normalizeString(q.value)), 'i');

		rows.forEach((elm) => {
			if (elm.getAttribute('data-search-label').match(query)) {
				g.toggle(elm, true);
			}
			else {
				g.toggle(elm, false);
			}
		});

		if (first = document.querySelector('tbody tr:not(.hidden)')) {
			if (f = document.querySelector('tr.focused')) {
				f.classList.remove('focused');
			}
			first.classList.add('focused');
		}

		if (e.key == 'Enter') {
			if (first = document.querySelector('tbody tr.focused:not(.hidden) button')) {
				first.click();
			}
		}

		return false;
	});

	q.focus();
}

var o = document.getElementById('f_typed_only_0');

if (o) {
	o.onchange = () => {
		let s = new URLSearchParams(window.location.search);
		s.set("all", o.checked ? 0 : 1);
		window.location.search = s.toString();
	};
}

Added src/www/admin/static/scripts/service_form.js version [cf77dd0e5b].













































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
(function () {
let create = false;

function selectService(elm, first_load) {
	$('[data-service]').forEach((e) => {
		e.style.display = ('s' + elm.value == e.getAttribute('data-service')) ? 'block' : 'none';
	});

	let expiry = $('#f_expiry_date');

	if (create && (!first_load || !expiry.value)) {
		// Set the expiry date
		expiry.value = elm.dataset.expiry;
	}

	var first = document.querySelector('[data-service="s' + elm.value + '"] input[name=id_fee]');

	if (first) {
		first.checked = true;
		selectFee(first);
	}
}

function selectFee(elm) {
	var amount = parseInt(elm.getAttribute('data-user-amount'), 10);

	// Toggle accounting part of the form
	var accounting = elm.getAttribute('data-account') ? true : false;
	g.toggle('.accounting', accounting);

	if (accounting) {
		$('#f_create_payment_1').checked = true;
		let btn = $('#f_account_container').firstElementChild;
		btn.value = btn.value.replace(/&year=\d+/, '') + '&year=' + elm.getAttribute('data-year');
	}

	// Fill the amount paid by the user
	if (amount && create) {
		$('#f_amount').value = g.formatMoney(amount);
	}
}

function initForm() {
	$('input[name=id_service]').forEach((e) => {
		e.onchange = () => { selectService(e); };
	});

	$('input[name=id_fee]').forEach((e) => {
		e.onchange = () => { selectFee(e); };
	});

	var selected = document.querySelector('input[name="id_service"]:checked') || document.querySelector('input[name="id_service"]');
	selected.checked = true;

	g.toggle('.accounting', false);
	selectService(selected, true);

	if (create) {
		let checkbox = $('#f_create_payment_1');
		checkbox.onchange = (e) => {
			g.toggle('.accounting dl', checkbox.checked);
			//$('#f_amount').required = checkbox.checked;
		};
	}

	// Automatically increase expiry date when date is changed
	let date_input = $('#f_date');
	let expiry_input = $('#f_expiry_date');

	date_input.onchange = (e) => {
		if (!selected.dataset.duration) {
			return;
		}

		let d = date_input.value.split('/').reverse();
		d = new Date(d[0], d[1]-1, d[2], 12);
		d.setDate(d.getDate() + parseInt(selected.dataset.duration, 10));
		expiry_input.value = d.toISOString().split('T')[0].split('-').reverse().join('/');
	};

	create = date_input.form.dataset.create == 'true';
}

g.onload(initForm);

})();

Added src/www/admin/static/scripts/web_editor.js version [882b005b1b].





































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
(function () {

const TYPES = ['code', ];

window.WebEditor = class {
	constructor(textarea) {
		this.textarea = textarea;
		this.parse(textarea.value)
		this.editor = 
	}

	build() {

	}

	parse(text) {
		var blocks = text.split("\n\n----\n\n");
		this.blocks = [];

		for (var i = 0; i < blocks.length; i++) {
			let block = blocks[i];

			if ((i % 1) == 0) {
				this.blocks.push(this.parseMeta(block));
			}
			else {
				this.blocks[this.blocks.length - 1].content = block.trim("\r\n");
			}
		}
	}

	parseMeta(text) {
		var lines = text.split("\n");
		var meta = {};

		for (var i = 0; i < lines.length; i++) {
			var line = lines[i].split(':', 2);

			if (line.length != 2) {
				continue;
			}

			meta[line[0].trim().toLowerCase()] = line[1].trim();
		}

		return meta;
	}
}

})();

Modified src/www/admin/static/scripts/wiki-encryption.js from [78239d4188] to [f41b9dc8c7].

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');
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

		// nl2br
		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_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_encrypted').checked = false;
					checkEncryption(document.getElementById('f_encrypted'));
				}
				else
				{
					wikiDecrypt();
				}
			}

			return;
		}

		iteration = 0;
		decrypt();
	};

	var decrypt = function ()
	{
		if (typeof GibberishAES == 'undefined')
		{
			if (iteration >= 10)
			{
				iteration = 0;
				encryptPassword = null;
				window.alert("Impossible de charger la bibliothèque AES, empêchant le déchiffrement de la page.\nAttendez quelques instants avant de recommencer ou rechargez la page.");
				return;
			}

			iteration++;
			window.setTimeout(decrypt, 500);
			return;
		}

		var content = document.getElementById('f_content');
		var edit = true;

		if (!content) {
		 	content = document.getElementById('wikiEncryptedContent');
		 	edit = false;
		}

		var wikiContent = content.value || content.innerText;
		wikiContent = wikiContent.replace(/\s+/g, '');

		try {
			wikiContent = GibberishAES.dec(wikiContent, encryptPassword);
		}
		catch (e)
		{
			encryptPassword = null;
			window.alert('Impossible de déchiffrer. Mauvais mot de passe ?');

			if (edit)
			{
				// Redemander le mot de passe
				wikiDecrypt();
			}
			return false;
		}

		if (!edit)
		{
			content.style.display = 'block';
			document.getElementById('wikiEncryptedMessage').style.display = 'none';
			content.innerHTML = formatContent(wikiContent);
		}
		else
		{
			content.value = wikiContent;
			checkEncryption(document.getElementById('f_encrypted'));
		}
	};

	window.checkEncryption = function(elm)
	{
		String.prototype.repeat = function(num)
		{
			return new Array(num + 1).join(this);
		};

		if (elm.checked)
		{
			if (!encryptPassword)
			{
				encryptPassword = window.prompt('Mot de passe à utiliser ?');
			}

			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_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;


			document.getElementById('f_form').onsubmit = null;
		}



	};


} ());







<
<
<
|
<

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





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

<
<



















|







>
>
>
>





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



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

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

		// nl2br
		content = content.replace(/\r/g, '').replace(/\n/g, '<br />');

		return content;
	}




	let edit = document.getElementById('f_content') ? true : false;


	let disableEncryption = (reset) => {


		if (reset) {
			document.getElementById('f_content').value = '';



			document.getElementById('f_format').selectedIndex = 0;


		}






























		document.getElementById('f_content').disabled = false;















		encryptPassword = null;






	};


	let enableEncryption = (form, do_decrypt) => {









		document.getElementById('f_content').disabled = true;





		String.prototype.repeat = function(num)
		{
			return new Array(num + 1).join(this);
		};

		load_aes(function () {

			askPassword();



			document.getElementById('f_content').disabled = false;


			if (do_decrypt) {
				decrypt();

			}



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

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

				if (!encryptPassword) {
					return;
				}

				var content = document.getElementById('f_content');
				content.value = GibberishAES.enc(content.value, encryptPassword);
				content.readOnly = true;
				return true;
			};
		});
	};

	let askPassword = () => {
		load_aes();

		encryptPassword = window.prompt('Mot de passe ?');

		if (!encryptPassword)
		{
			encryptPassword = null;

			if (edit)
			{
				if (window.confirm("Aucun mot de passe entré.\nDésactiver le chiffrement et effacer le contenu ?"))
				{
					disableEncryption(true);
				}
			}

			return;
		}

		iteration = 0;
	};

	window.pleaseDecrypt = () => {
		askPassword();
		decrypt();
	};

	var decrypt = function ()
	{
		if (!encryptPassword) {
			return;
		}

		if (typeof GibberishAES == 'undefined')
		{
			if (iteration >= 10)
			{
				iteration = 0;
				encryptPassword = null;
				window.alert("Impossible de charger la bibliothèque AES, empêchant le déchiffrement de la page.\nAttendez quelques instants avant de recommencer ou rechargez la page.");
				return;
			}

			iteration++;
			window.setTimeout(decrypt, 500);
			return;
		}

		if (edit) {
			var content = document.getElementById('f_content');
		}
		else {
		 	var content = document.getElementById('wikiEncryptedContent');
		}

		var wikiContent = content.value || content.innerText;
		wikiContent = wikiContent.replace(/\s+/g, '');

		try {
			wikiContent = GibberishAES.dec(wikiContent, encryptPassword);
		}
		catch (e)
		{
			encryptPassword = null;
			window.alert('Impossible de déchiffrer. Mauvais mot de passe ?');

			if (edit)
			{
				// Redemander le mot de passe
				askPassword();
				decrypt();
			}
			return false;
		}

		if (!edit)
		{
			content.style.display = 'block';
			document.getElementById('wikiEncryptedMessage').style.display = 'none';
			content.innerHTML = formatContent(wikiContent);
		}
		else
		{
			content.value = wikiContent;
		}
	};

	document.addEventListener('DOMContentLoaded', () => {
		if (e = document.getElementById('f_format')) {
			edit = true;

			if (e.value == "skriv/encrypted") {
				enableEncryption(e.form, true);
			}

			e.addEventListener('change', () => {
				if (e.value == 'skriv/encrypted') {
					enableEncryption(e.form);
				}
				else if (encryptPassword) {
					disableEncryption(false);
				}
			})
		}
	});
} ());

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 [140dc73887] to [b95d10b6d7].

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
(function () {
	var wiki_id = window.location.search.match(/id=(\d+)/)[1];

	g.onload(function () {
		if (location.hash == '#saved') {
			location.hash = '';

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





		g.script('scripts/text_editor.min.js', function () {
			var t = new textEditor('f_content');
			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 + 'web/_preview.php?id=' + wiki_id;
				form.style.display = 'none';
				form.method = 'post';
				document.body.appendChild(form);
				form.submit();
				//document.body.removeChild(form);
				return true;
			};

			var openSyntaxHelp = function ()
			{
				openIFrame(g.admin_url + 'web/_syntaxe.html');
				return true;
			};

			var openFileInsert = function ()
			{
				openIFrame(g.admin_url + 'web/_attach.php?page=' + wiki_id);
				return true;
			};

			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 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 () {

				t.textarea.form.action = t.textarea.form.action.replace(/&pos=\d+/, '');






				t.textarea.form.action += '&pos=' + t.getSelection().start;








				t.textarea.form.querySelector('[name="save"]').click();
				return true;
			};


			appendButton('title', "== Titre", function () { wrapTags("== ", ""); } );
			appendButton('bold', '**gras**', function () { wrapTags('**', '**'); } );
			appendButton('italic', "''italique''", function () { wrapTags("''", "''"); } );
			appendButton('link', "[[lien|http://]]", insertURL);
			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("''", "''"); } });
			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: 'i', callback: openFileInsert});
			t.shortcuts.push({ctrl: true, shift: true, key: 'p', callback: openPreview});
			t.shortcuts.push({key: 'F1', callback: openSyntaxHelp});

			if (m = window.location.search.match(/pos=(\d+)/))
			{
				t.textarea.focus();
				t.setSelection(m[1], m[1]);
				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
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
(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'),
			format: t.textarea.getAttribute('data-format')








		};






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

		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;
			let f = document.createElement('input');
			f.type = 'hidden';
			f.name = 'format';
			f.value = config.format;
			form.appendChild(f);
			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 ()
		{
			let url = config.format == 'markdown' ? '_syntax_markdown.html' : '_syntax_skriv.html';
			url = g.admin_url + 'web/' + url;

			openIFrame(url);
		};

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

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

		let applyHeader = () => {
			wrapTags(config.format == 'markdown' ? '## ' : '== ', '');
		};

		let applyBold = () => {
			wrapTags('**', '**');
		};

		let applyItalic = () => {
			if (config.format == 'markdown') {
				wrapTags("_", "_");
			}
			else {
				wrapTags("''", "''");
			}
		};

		var wrapTags = function (left, right)
		{
			t.wrapSelection(t.getSelection(), left, right);
			return true;
		};

		let insertURL = function () {
			let url = window.prompt('Adresse URL ?');

			if (!url) {
				return true;
			}

			if (config.format == 'markdown') {
				wrapTags("[", "](" + url + ')');
			}
			else {
				wrapTags("[[", "|" + url + ']]');
			}
		};

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

		let createToolbar = () => {
			appendButton('title', "Titre", applyHeader );
			appendButton('bold', 'Gras', applyBold );
			appendButton('italic', "Italique", applyItalic );
			appendButton('link', "Lien", 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);
		}

		let toggleFormat = (format) => {
			config.format = format;
			g.toggle('.wikiEncrypt', format == 'skriv/encrypted');
		};

		if (config.format.substr(0, 1) == '#') {
			let s = document.querySelector(config.format);
			s.onchange = () => {
				toggleFormat(s.value);
			};
			toggleFormat(s.value);
		}
		else {
			toggleFormat(config.format);
		}

		createToolbar();

		t.shortcuts.push({key: 'F11', callback: toggleFullscreen});
		t.shortcuts.push({ctrl: true, key: 'b', callback: applyBold });
		t.shortcuts.push({ctrl: true, key: 'g', callback: applyBold });
		t.shortcuts.push({ctrl: true, key: 'i', callback: applyItalic });
		t.shortcuts.push({ctrl: true, key: 't', callback: applyHeader });
		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 [d78f436e36] 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_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.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 [14d9c47672] to [5c586c401b].

15
16
17
18
19
20
21










22
23
24
25
26
27
28
span.alert, b.alert {
    color: #990;
}

.alert p, .error p, .confirm p {
    margin-bottom: .8em;
}











.alert.block, .error.block, .confirm.block, .help.block {
    border: 1px solid #ccc;
    padding: .5em;
    margin-bottom: 1em;
    border-radius: .3em;
    padding-left: 3em;







>
>
>
>
>
>
>
>
>
>







15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
span.alert, b.alert {
    color: #990;
}

.alert p, .error p, .confirm p {
    margin-bottom: .8em;
}

.block table {
    margin: 1rem 0;
}

.block table th, .block table td {
    vertical-align: top;
    padding: .2rem .4rem;
    border: 1px solid #666;
}

.alert.block, .error.block, .confirm.block, .help.block {
    border: 1px solid #ccc;
    padding: .5em;
    margin-bottom: 1em;
    border-radius: .3em;
    padding-left: 3em;
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;







|







88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
    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;







|






|









|




|















|















|





|





|





|











|







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
}

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







|







294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
}

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;
}
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358

aside.describe dl.describe dt {
    text-align: left;
    font-weight: bold;
    color: #000;
}

pre.sql_schema {
    float: right;
    color: #666;
    font-size: .9em;
    width: 30%;
    overflow: auto;
}

.hidden {
    display: none;
}

img.qrcode {
    float: right;
    padding: .5em;







<
<
<
<
<
<
<
<







347
348
349
350
351
352
353








354
355
356
357
358
359
360

aside.describe dl.describe dt {
    text-align: left;
    font-weight: bold;
    color: #000;
}









.hidden {
    display: none;
}

img.qrcode {
    float: right;
    padding: .5em;
408
409
410
411
412
413
414

































































































    padding-right: 4em !important;
}

details summary.block::after {
    right: 0;
    left: inherit;
}








































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
    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 [cb1bad2db4] to [d66655de4b].

8
9
10
11
12
13
14

15
16
17
18
19
20
21
22

fieldset legend {
    padding: 0 0.5em;
    font-weight: bold;
    color: #000;
}


table tr.clickable:hover {
    cursor: pointer;
    color: #633;
    background: #ffc;
}

table tr.focused {
    color: #633;







>
|







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

fieldset legend {
    padding: 0 0.5em;
    font-weight: bold;
    color: #000;
}

/* Override selector in 06-tables.css */
table tr.clickable:hover, table tr.clickable:nth-child(even):hover {
    cursor: pointer;
    color: #633;
    background: #ffc;
}

table tr.focused {
    color: #633;
383
384
385
386
387
388
389

390
391
392
393
394
395
396
}

dialog[open] {
    display: block;
}

dialog.datepicker {

    position: absolute;
    left: 0;
    margin: 0;
    padding: .3rem;
    border: none;
    box-shadow: 0 0 5px #000;
    border-radius: .5rem;







>







384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
}

dialog[open] {
    display: block;
}

dialog.datepicker {
    user-select: none;
    position: absolute;
    left: 0;
    margin: 0;
    padding: .3rem;
    border: none;
    box-shadow: 0 0 5px #000;
    border-radius: .5rem;
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
    z-index: 200;
}

fieldset.memberMessage {
    max-width: 30em;
}

fieldset.memberMessage #f_sujet, fieldset.memberMessage #f_message, fieldset.memberMessage select {
    width: calc(100% - 2em);
}


#queryBuilder .column select, #queryBuilderForm .actions select {
    max-width: 15em;
}







|







496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
    z-index: 200;
}

fieldset.memberMessage {
    max-width: 30em;
}

fieldset.memberMessage #f_sujet, fieldset.memberMessage #f_message, fieldset.memberMessage select, #queryBuilderForm textarea {
    width: calc(100% - 2em);
}


#queryBuilder .column select, #queryBuilderForm .actions select {
    max-width: 15em;
}
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;







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







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

Modified src/www/admin/static/styles/wiki.css from [1069760ac6] to [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
.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;
}

.web-edit {
    display: grid;
    grid-template-columns: 1fr 30%;
    grid-template-rows: .3fr .3fr .3fr;
    grid-gap: 2em;
}

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



























































































































1
2
3
4
5
6
7




















































































































.web-edit {
    display: grid;
    grid-template-columns: 1fr 30%;
    grid-template-rows: .3fr .3fr .3fr;
    grid-gap: 2em;
}

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

.wikiChildren ul {
    color: #ccc;
    list-style-type: square;
    margin-left: 1em;
}

.web-tree ul {
    margin-left: 1em;
    list-style-type: none;
}

.web-tree a {
    color: #666;
}

.web-tree td {
    width: 15%;
}

.web-tree i {
    display: inline-block;
    padding: 0 .5em;
}

.web-tree b {
    display: inline-block;
    padding: 0 .5em;
    color: #999;
}

.web-tree em {
    font-weight: normal;
}

.web-tree h3 {
    display: inline-block;
}

.web-tree .current > a {
    font-weight: bold;
    color: #000;
}

.web-tree .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;
}

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

#confirm_saved {
    position: absolute;
    top: .5em;
    right: 4em;
    text-align: center;
    transition: all .5s, opacity 3s;
}

.diff {
    margin: 1em;
}

.diff .ins {diff
    background: #cfc;
    width: 45%;







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




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







74
75
76
77
78
79
80


















































































81
82
83
84






























































































85
86
87
88
89
90
91

.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%;

Modified src/www/admin/web/_attach.php from [38bb4e03a5] to [c602997b78].

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
<?php
namespace Garradin;

require_once __DIR__ . '/_inc.php';

use Garradin\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, Membres::DROIT_ECRITURE);

$page = Web::get((int) qg('page'));

if (!$page) {
	throw new UserException('Page inconnue');
}

$csrf_key = 'attach_' . $page->id();

$form->runIf('delete', function () use ($page) {

	$file = Files::get((int) f('delete'));

	if (!$file->getLinkedId($file::LINK_FILE) == $page->id()) {
		throw new UserException('Ce fichier n\'est pas lié à cette page');
	}

	$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.');
	}

	$file = File::upload('file');

	// Lier le fichier à la page wiki
	$file->linkTo(File::LINK_FILE, $page->id());

	if (f('uploadHelper_status') !== null)
	{
		$uri = Utils::getSelfURI() . '&sent';
		echo json_encode([
			'redirect'  =>  $uri,
			'callback'  =>  'insertHelper',
			'file'      =>  [
				'image' =>  (int)$file->image,
				'id'    =>  (int)$file->id(),
				'nom'   =>  $file->name,
				'thumb' =>  $file->image ? $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.js', 'wiki_fichiers.js']);


$tpl->display('web/_attach.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
<?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 ($page, $session) {
	$path = Utils::dirname($page->file_path) . '/' . f('delete');
	$file = Files::get($path);

	if (!$file || !$file->checkDeleteAccess($session)) {
		throw new UserException('Vous ne pouvez pas supprimer ce fichier');
	}

	$file->delete();

	Utils::redirect(Utils::getSelfURI());
}, $csrf_key);


$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');

Modified src/www/admin/web/_inc.php from [c90c669bb9] to [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, Membres::DROIT_ACCES);

$tpl->assign('custom_css', ['wiki.css']);








|


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']);

Modified src/www/admin/web/_selector.php from [cbc3cfd0f5] to [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
<?php
namespace Garradin;

use Garradin\Web;
use Garradin\Entities\Web\Page;

require_once __DIR__ . '/_inc.php';





$parent = (int)qg('parent');

$breadcrumbs = [];

if ($parent) {
	$page = Web::get($parent);

	if (!$page) {
		throw new UserException('Page inconnue');
	}

	$tpl->assign('page', $page);
	$breadcrumbs = $page->getBreadcrumbs();
}


$tpl->assign(compact('breadcrumbs', 'parent'));




$tpl->assign('categories', Web::listCategories($parent));


$tpl->display('web/_selector.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\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/_syntax_markdown.html version [cb696910b0].

































































































































































































































































































































































































































































































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

  code {
    background: #ccc;
    padding: .2em;
  }

  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>F1</kbd></th>
        <td>Afficher l'aide</td>
      </tr>
    </tbody>
  </table>
</section>

<section>
  <h2>Extensions Markdown</h2>
  <h3>Sommaire / table des matières automatique</h3>
  <p>Il suffit de placer la mention <code>[toc]</code> ou <code>[sommaire]</code> sur une ligne (sans aucun autre texte) pour afficher un sommaire automatique de la page&nbsp;:</p>
<div class="toc"><ol><li><a href="#La-syntaxe-markdown">La syntaxe markdown</a></li><ol><li><a href="#Styles-de-texte">Styles de texte</a></li><li><a href="#Blocs-de-code">Blocs de code</a></li><li><a href="#Liens">Liens</a></li><li><a href="#Images">Images</a></li><li><a href="#Citation">Citation</a></li><li><a href="#Listes">Listes</a></li><li><a href="#Titres">Titres</a></li><li><a href="#Tableaux">Tableaux</a></li></ol></ol></div>
  <h3>Images</h3>
  <p>Il est possible d'intégrer une image jointe à la page web en plaçant le code suivant sur une ligne (sans autre texte)&nbsp;:</p>
  <pre>&lt;&lt;image|nom_fichier.jpg|alignement|Légende&gt;&gt;</pre>
  <p><code>nom_fichier.jpg</code> indique le nom du fichier de l'image</p>
  <p><code>alignement</code> indique l'alignement de l'image peut être <code>centre</code>, <code>gauche</code>, ou <code>droite</code></p>
  <p><code>Légende</code> indique une légende facultative à afficher en dessous de l'image</p>
  <h3>Fichiers</h3>
  <p>Pour créer un bouton permettant de voir ou télécharger un fichier joint à la page web, il suffit d'utiliser la syntaxe suivante :</p>
  <pre>&lt;&lt;fichier|nom_fichier.pdf|Légende&gt;&gt;</pre>
  <p><code>nom_fichier.jpg</code> indique le nom du fichier</p>
  <p><code>Légende</code> indique une légende facultative pour le texte du bouton, si aucune légende n'est donnée alors c'est le nom du fichier qui sera affiché</p>
  <h3>Notes de bas de page</h3>
  <pre>Texte très intéressant[^1]<br><br>[^1]: Ceci est une note de bas de page</pre>
</section>

<section>

<div class="web-content"><h1>La syntaxe markdown</h1>
<p>Pour formater votre texte vous avez la possibilité d'utiliser la barre d'outils située au-dessus de la zone de texte, ou vous pouvez utiliser la syntaxe markdown.</p>
<h2>Styles de texte</h2>
<p>Vous pouvez utiliser <code>_</code> ou <code>*</code> autour d'un mot pour le mettre en italique. Mettez-en deux pour le mettre en gras.</p>
<ul>
<li><code>_italique_</code> s'affiche ainsi&nbsp;: <em>italique</em></li>
<li><code>**gras**</code> s'affiche ainsi&nbsp;: <strong>gras</strong></li>
<li><code>**_gras-italique_**</code> s'affiche ainsi&nbsp;: <strong><em>gras-italique</em></strong></li>
<li><code>~~barré~~</code> s'affiche ainsi&nbsp;: <del>barré</del></li>
</ul>
<h2>Blocs de code</h2>
<p>Créez un bloc de code en indentant chaque ligne avec quatre espaces, ou en mettant trois accents graves sur la ligne au dessus et en dessous de votre code.<br>
Exemple :</p>
<p><code>```<br />bloc de code<br />```</code></p>
<p>s'affiche ainsi :</p>
<pre>bloc de code</pre>
<h2>Liens</h2>
<p>Créez un lien intégré en mettant le texte désiré entre crochets et le lien associé entre parenthèses.</p>
<p><code>Je connais un super gestionnaire [d'association](https://garradin.eu/) !</code></p>
<p>s'affichera :</p>
<p>Je connais un super gestionnaire <a href="https://garradin.eu/" target="_blank">d'association</a> !</p>
<h2>Images</h2>
<p>Utilisez une image en ligne en copiant son adresse (finissant par <code>.jpg</code>, <code>.png</code>, <code>.gif</code> etc…) avec un texte alternatif entre crochets (qui sera affiché si l'image n'apparaît pas) et le lien entre parenthèses.</p>
<pre>![Logo Garradin](https://fossil.kd2.org/garradin/logo)</pre>
<p>donnera :</p>
<p><img src="https://fossil.kd2.org/garradin/logo" alt="Logo Garradin"></p>
<h2>Citation</h2>
<p>Les citations se font avec le signe <code>&gt;</code> :</p>
<pre>&gt; Ah je ris de me voir si belle !</pre>
<blockquote>
<p>Ah je ris de me voir si belle !</p>
</blockquote>
<h2>Listes</h2>
<p>Vous pouvez créer des listes avec les caractères <code>*</code> et <code>-</code> pour des listes non ordonnées ou avec des nombres pour des listes ordonnées.</p>
<p>Une liste non ordonnée :</p>
<pre>* une élément
* un autre
 * un sous élément
 * un autre sous élément
* un dernier élément</pre>
<ul>
<li>une élément</li>
<li>un autre
<ul>
<li>un sous élément</li>
<li>un autre sous élément</li>
</ul></li>
<li>un dernier élément</li>
</ul>
<p>Une liste ordonnée :</p>
<pre>1. élément un
2. élément deux</pre>
<ol>
<li>élément un</li>
<li>élément deux</li>
</ol>
<h2>Titres</h2>
<p>Pour faire un titre, vous devez mettre un <code>#</code> devant la ligne. Pour faire un titre plus petit, ajoutez un <code>#</code> (jusque 6) :</p>
<pre># Un grand titre
## Un titre un peu moins grand
### Un titre encore moins grand</pre>
<h2>Tableaux</h2>
<p>Pour créer un tableau vous devez placer une ligne de tirets (<code>-</code>) sous la ligne d'entête et séparer les colonnes avec des <code>|</code>. Vous pouvez aussi préciser l'alignement en utilisant des <code>:</code>. :</p>
<pre>| Aligné à gauche  | Centré          | Aligné à droite |
| :--------------- |:---------------:| -----:|
| Aligné à gauche  |   ce texte        |  Aligné à droite |
| Aligné à gauche  | est             |   Aligné à droite |
| Aligné à gauche  | centré          |    Aligné à droite |</pre>
<table>
<thead>
<tr>
<th style="text-align&nbsp;: left;">Aligné à gauche</th>
<th style="text-align&nbsp;: center;">Centré</th>
<th style="text-align&nbsp;: right;">Aligné à droite</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align&nbsp;: left;">Aligné à gauche</td>
<td style="text-align&nbsp;: center;">ce texte</td>
<td style="text-align&nbsp;: right;">Aligné à droite</td>
</tr>
<tr>
<td style="text-align&nbsp;: left;">Aligné à gauche</td>
<td style="text-align&nbsp;: center;">est</td>
<td style="text-align&nbsp;: right;">Aligné à droite</td>
</tr>
<tr>
<td style="text-align&nbsp;: left;">Aligné à gauche</td>
<td style="text-align&nbsp;: center;">centré</td>
<td style="text-align&nbsp;: right;">Aligné à droite</td>
</tr>
</tbody>
</table></div>
</section>

</body>
</html>

Modified src/www/admin/web/_syntax_skriv.html from [1b5e7a5287] to [a383e52cdf].

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







|








|


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







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
				<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>F1</kbd></th>
				<td>Afficher l'aide</td>
			</tr>
		</tbody>
	</table>
</section>

<header>
	<h1>Syntaxe</h1>
	<p>Garradin utilise la syntaxe <a href="https://fossil.kd2.org/garradin/doc/trunk/doc/skrivml.html" target="_blank">SkrivML</a> pour 
		le formatage du texte dans le wiki.</p>
</header>

<section>
	<h2>Extensions</h2>
	<h3>Images</h3>
	<p>Il est possible d'intégrer une image jointe à la page web en plaçant le code suivant sur une ligne (sans autre texte)&nbsp;:</p>
	<pre>&lt;&lt;image|nom_fichier.jpg|alignement|Légende&gt;&gt;</pre>
	<p><code>nom_fichier.jpg</code> indique le nom du fichier de l'image</p>
	<p><code>alignement</code> indique l'alignement de l'image peut être <code>centre</code>, <code>gauche</code>, ou <code>droite</code></p>
	<p><code>Légende</code> indique une légende facultative à afficher en dessous de l'image</p>
	<h3>Fichiers</h3>
	<p>Pour créer un bouton permettant de voir ou télécharger un fichier joint à la page web, il suffit d'utiliser la syntaxe suivante :</p>
	<pre>&lt;&lt;fichier|nom_fichier.pdf|Légende&gt;&gt;</pre>
	<p><code>nom_fichier.jpg</code> indique le nom du fichier</p>
	<p><code>Légende</code> indique une légende facultative pour le texte du bouton, si aucune légende n'est donnée alors c'est le nom du fichier qui sera affiché</p>
</section>


<section>
	<h2>Styles de base</h2>
	<article>
		<h3>Gras</h3>
		<pre>Utiliser **deux astérisques**.</pre>
		<samp>Utiliser <b>deux astérisques</b>.</samp>
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
	<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>







|
|













|




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
	<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>[[https://garradin.eu/]]</pre>
		<samp><a>https://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" target="_blank">SkrivML</a>.</p>
</section>

</body>
</html>

Modified src/www/admin/web/config.php from [57c41f518e] to [3dd1c46ed9].

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
<?php
namespace Garradin;



require_once __DIR__ . '/_inc.php';

$config = Config::getInstance();



if (f('desactiver_site') && $form->check('config_site'))
{
	$config->set('desactiver_site', true);
	$config->save();
	Utils::redirect(Utils::getSelfURI());
}
elseif (f('activer_site') && $form->check('config_site'))
{
	$config->set('desactiver_site', false);
	$config->save();
	Utils::redirect(Utils::getSelfURI());
}

$form->runIf('reset', function () {
	foreach (f('select') as $source)
	{
		if (!Squelette::resetSource($source))
		{
			throw new UserException('Impossible de réinitialiser le squelette.');

		}
	}

}, 'squelettes', Utils::getSelfURI('reset_ok'));


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'));

	$form->runIf('save', function () {

		if (Squelette::editSource(qg('edit'), f('content')))
		{
			$fullscreen = null !== qg('fullscreen') ? '#fullscreen' : '';
			Utils::redirect(Utils::getSelfURI(sprintf('edit=%s&ok%s', rawurlencode(qg('edit')), $fullscreen)));
		}
		else
		{




			throw new UserException("Impossible d'enregistrer le squelette.");
		}
	}, $csrf_key);

	$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('web/config.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\Web\Skeleton;

require_once __DIR__ . '/_inc.php';

$config = Config::getInstance();

$session->requireAccess($session::SECTION_WEB, $session::ACCESS_ADMIN);

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 () {
	if (!f('select')) {




		return;
	}

	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);


	try {
		$skel = new Skeleton($source);
	}
	catch (\InvalidArgumentException $e) {
		throw new UserException('Nom de squelette invalide');
	}


	$tpl->assign('edit', ['file' => $source, 'content' => $skel->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();

Modified src/www/admin/web/delete.php from [12541ce824] to [8bec9db821].

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;
use Garradin\Entities\Web\Page;

require_once __DIR__ . '/_inc.php';



$page = Web::get((int) qg('id'));

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_id);

$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');



|




>
>
|









|






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
<?php
namespace Garradin;

use Garradin\Web\Web;
use Garradin\Entities\Web\Page;

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 = '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');

Modified src/www/admin/web/edit.php from [ef9c3a4f34] to [d2da8ff862].

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;

use Garradin\Web;
use Garradin\Entities\Web\Page;

use KD2\SimpleDiff;

require_once __DIR__ . '/_inc.php';


$id = (int) qg('id');
$page = Web::get($id);

if (!$page) {
	throw new UserException('Page inconnue');
}





$csrf_key = 'edit_' . $page->id();

$editing_started = f('editing_started') ?: date('Y-m-d H:i:s');

if (f('cancel')) {
	Utils::redirect(ADMIN_URL . 'web/?parent=' . $page->parent_id);
}

$show_diff = false;

$form->runIf('save', function () use ($page, $editing_started, &$show_diff) {
	$editing_started = new \DateTime($editing_started);

	if ($editing_started < $page->modified) {
		$show_diff = true;

		throw new UserException('La page a été modifiée par quelqu\'un d\'autre pendant que vous éditiez le contenu.');
	}

	$page->importForm();

	$page->save();






}, $csrf_key, Utils::getSelfURI() . '#saved');

$parent = $page->parent_id ? [$page->parent_id => Web::get($page->parent_id)->title] : null;
$encrypted = f('encrypted') || $page->file()->type == Page::FILE_TYPE_ENCRYPTED;

$old_content = f('content');
$new_content = $page->raw();



$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', 'scripts/wiki_editor.css']);

$tpl->display('web/edit.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
<?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';

$session->requireAccess($session::SECTION_WEB, $session::ACCESS_WRITE);

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

$formats = $page::FORMATS_LIST;

$tpl->assign(compact('page', 'parent', 'editing_started', 'encrypted', 'csrf_key', 'old_content', 'new_content', 'show_diff', 'formats'));

$tpl->assign('custom_js', ['wiki_editor.js', 'wiki-encryption.js']);
$tpl->assign('custom_css', ['wiki.css']);

$tpl->display('web/edit.tpl');

Modified src/www/admin/web/index.php from [70815962e3] to [fbf5316a30].

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;

use Garradin\Web;
use Garradin\Entities\Web\Page;

require_once __DIR__ . '/_inc.php';


$parent = (int) qg('parent') ?: null;

if ($parent) {
	$cat = Web::get($parent);

	if (!$cat) {
		throw new UserException('Catégorie inconnue');
	}
}






$order_date = qg('order_title') === null;

$categories = Web::listCategories($parent);
$pages = Web::listPages($parent, $order_date);
$title = $parent ? sprintf('Gestion du site web : %s', $cat->title) : 'Gestion du site web';
$type_page = Page::TYPE_PAGE;
$type_category = Page::TYPE_CATEGORY;




$tpl->assign(compact('categories', 'pages', 'title', 'parent', 'type_page', 'type_category', 'order_date'));

$tpl->display('web/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
<?php

namespace Garradin;

use Garradin\Web\Web;
use Garradin\Entities\Web\Page;

require_once __DIR__ . '/_inc.php';

$current_path = qg('p') ?: '';
$cat = null;

if ($current_path) {
	$cat = Web::get($current_path);

	if (!$cat) {
		throw new UserException('Catégorie inconnue');
	}
}
else {
	foreach (Web::sync() as $error) {
		$form->addError($error);
	}
}

$order_date = qg('order_date') !== 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 [dae08411a4].









































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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;
use Garradin\Entities\Files\File;
use KD2\SimpleDiff;

require_once __DIR__ . '/_inc.php';

$session->requireAccess($session::SECTION_WEB, $session::ACCESS_WRITE);

$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');

Modified src/www/admin/web/page.php from [9a89e62767] to [7684223213].

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\Web;
use Garradin\Entities\Web\Page;

require_once __DIR__ . '/_inc.php';

if ($uri = qg('uri'))
{
	$page_uri = Wiki::transformTitleToURI($uri);
	$page = Web::getByURI($page_uri);
}
else
{
	$page = Web::get((int) qg('id'));
}

if (!$page) {
	throw new UserException('Page inconnue');
}







$membres = new Membres;

$tpl->assign('breadcrumbs', $page->getBreadcrumbs());
$tpl->assign('auteur', $page->file()->author_id ? $membres->getNom($page->file()->author_id) : null);

$images = $page->getImageGallery(false);
$files = $page->getAttachmentsGallery(false);

$content = $page->render(['prefix' => ADMIN_URL . 'web/page.php?uri=']);

$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->display('web/page.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
<?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');
}

if (qg('toggle_type') !== null) {
	$page->toggleType();
	$page->save();
	Utils::redirect('!web/page.php?p=' . $page->path);
}

$membres = new Membres;

$tpl->assign('breadcrumbs', $page->getBreadcrumbs());


$images = $page->getImageGallery(true);
$files = $page->getAttachmentsGallery(true);

$content = $page->render(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');

Modified src/www/admin/web/search.php from [6cce625794] to [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
<?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');



>
>
>


|

|

|
<
|
|
|


|
<
|




|
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/file.php version [596ad632c6].

1
2
3
4
5
6
7
8
9
<?php

namespace Garradin;

use Garradin\Files\Files;

require __DIR__ . '/_inc.php';

Files::serveFromQueryString();
<
<
<
<
<
<
<
<
<


















Modified src/www/index.php from [45447c0558] to [058717db8f].

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

namespace Garradin;

use Garradin\Web;

require __DIR__ . '/_inc.php';

if (Config::getInstance()->get('desactiver_site'))
{
	Utils::redirect(ADMIN_URL);
}

Web::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>

Modified src/www/skel-dist/_head.html from [4e9dd4b6de] to [a4ef48e61c].

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
<!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="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}}<h4>{{$config.adresse_asso}}</h4>{{/if}}


















	<nav>
		<ul>
		{{#categories parent=null order="title"}}
			<li><a href="{{$url}}">{{ $title }}</a></li>
		{{/categories}}
		</ul>
	</nav>
</header>

<section class="page">





>


>
















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











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
<!DOCTYPE html>
<html lang="fr">
<head>
	<meta charset="utf-8" />
	<title>{{if $title}}{{$title}} — {{/if}}{{$config.nom_asso}}</title>
	<link rel="icon" type="image/png" href="{{$root_url}}favicon.png" />
	<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">

Modified src/www/skel-dist/article.html from [2e1ae57822] to [0d3f6a0c3e].

1
2
3
4
5
6
7

8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{{#articles uri=$_GET.uri}}

	{{:include file="_head.html"}}

	<article>
		<h1>{{$title}}</h1>


		<div class="corps">
			{{$html|raw}}
		</div>

		{{:include file="gallery.html" parent=$id}}
		{{:include file="documents.html" parent=$id}}
	</article>

	{{:include file="_foot.html"}}

{{else}}

	{{:include file="404.html"}}

{{/articles}}

|

|

|
|

>
|
|
<

|
|
|

|
<
<
<
<
<
<
<
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"}}







Modified src/www/skel-dist/atom.xml from [44b3d262e2] to [e7112a7e8e].

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|escape:xml}}</title>
	<link href="{{$root_url|escape:xml}}" rel="alternate" type="text/html" title="{{$config.nom_asso|escape:xml}}" />

	{{#articles order="created DESC" limit=1}}
	<updated>{{$created|atom_date}}</updated>
	{{/articles}}

	<author>
		<name>{{$config.nom_asso|escape:xml}}</name>
	</author>

	<id>{{$root_url|escape:xml}}</id>
	<generator uri="https://fossil.kd2.org/garradin/">Garradin</generator>

	{{#articles order="created DESC" limit=20}}
	<entry>
		<title>{{$title|escape:xml}}</title>
		<link href="{{$url|escape:xml}}" rel="alternate" type="text/html" title="{{$title|escape:xml}}" />
		<id>{{$url|escape:xml}}</id>
		<updated>{{$modified|atom_date}}</updated>
		<author><name>{{$config.nom_asso|escape:xml}}</name></author>
		<content type="html">

			{{$html|raw|escape:xml}}

		</content>
	</entry>
	{{/articles}}

</feed>




>
|
|

|
|



|


|


|

|
|
|
|
|

>
|
>





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
{{: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">

	<link rel="self" href="{{$request_url}}" />
	<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>{{$published|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>{{$published|atom_date}}</updated>
		<author><name>{{$config.nom_asso|xml_escape}}</name></author>
		<content type="html">
			<![CDATA[
			{{$html|raw}}
			]]>
		</content>
	</entry>
	{{/articles}}

</feed>

Modified src/www/skel-dist/category.html from [4011f2f7c2] to [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
33
34
35
36
37
38
39
40
{{#categories uri=$_GET.uri}}

	{{:include file="_head.html"}}



	<section class="subcategories">
		{{#categories parent=$id order="title"}}
		<article>
			<h2><a href="{{$url}}">{{$title}}</a></h2>
		</article>
		{{/categories}}
	</section>

	<article>
		<h1>{{$title}}</h1>

		<div class="corps">
			{{$html|raw}}
		</div>

		{{:include file="gallery.html" parent=$id}}
		{{:include file="documents.html" parent=$id}}
	</article>

	<section class="articles">
		{{#articles parent=$id order="created DESC"}}
		<article>
			<h3><a href="{{$url}}">{{$title}}</a></h3>

			<p>{{$html|raw|strip_tags|truncate:200}}</p>
		</article>
		{{/articles}}
	</section>

	{{:include file="_foot.html"}}

{{else}}

	{{:include file="404.html"}}

{{/categories}}
<
<
|

>

|
|
|
|
|
|
|

|
|

<
|
<

|
|
|

|
|
|
|
>
|
|
|
|

|
<
<
<
<
<
<


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 [dd0eed56a6].























































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
.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, .web-content pre {
    margin: .8em 0;
}

.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 blockquote::before {
    content: "”";
    color: #999;
    display: block;
    position: absolute;
    font-style: italic;
    font-size: 3rem;
    line-height: 2rem;
    margin-left: -3rem;
}

.web-content blockquote {
    font-size: 1.1em;
    padding-left: 3rem;
    margin: 1rem 0;
}

.web-content a.footnote-ref, .web-content .footnotes dt a {
    color: blue;
}

.web-content a.footnote-ref::before, .web-content .footnotes dt a::before {
    content: "[";
}

.web-content a.footnote-ref::after, .web-content .footnotes dt a::after {
    content: "]";
}

.web-content dl.footnotes {
    display: grid;
    grid-template-columns: .1fr .9fr;
    border-top: 2px solid #999;
    margin-top: 1rem;
    padding-top: 1rem;
}

.web-content code {
    background: rgba(100, 100, 100, 0.2);
    padding: .2rem;
}

.web-content dl.footnotes dd {
    margin: 0;
    margin-bottom: 1rem;
}

.web-content dl.footnotes dd p {
    margin: 0;
    margin-bottom: 1rem;
}

.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 .toc {
    margin: 1rem 0;
    border: 1px solid rgba(0, 0, 0, 0.2);
    background: rgba(0, 0, 0, 0.1);
    padding: .3rem;
    width: max-content;
}

.web-content .toc ol {
    list-style: none;
    counter-reset: item;
    margin: .5rem 0 .5rem .5rem;
}

.web-content .toc ol li:before {
    content: counters(item, ".") " ";
    counter-increment: item;
    color: #666;
}

.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%;
    }
}

Modified src/www/skel-dist/default.css from [4d22b01b8b] to [c5d9c9f441].

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

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 {







<












>






|
|







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

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 {
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
}

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







<
<
<
<
<
<
<





|


<
<
<


|

|
>


|

|
|



|


|
|
<
>







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
}

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;
}
137
138
139
140
141
142
143
144










145

146
147
148
149
150
151
152
    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;








>
>
>
>
>
>
>
>
>
>

>







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
    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;
169
170
171
172
173
174
175





176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

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







>
>
>
>
>





<
<
<
<







171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187




188
189
190
191
192
193
194

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







|
|
>
|
>
>


|
|
|
<
|


|
>
>
|
>
>
>
|
|
|


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


|
|


|
>
>
>



|
|


<
|
<
|
<

<
|
>
>
|
>
|
<
|
>


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


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


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







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
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;
    }
316
317
318
319
320
321
322





323


324





325
326
327
328
329
330
331
332
333
334
335
336
        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; }







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




|







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

Modified src/www/skel-dist/documents.html from [3338b0694f] to [b071506de9].

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

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>

Name change from src/www/admin/static/icon.png to src/www/skel-dist/favicon.png.

cannot compute difference between binary files

Modified src/www/skel-dist/gallery.html from [9c13f3c7ad] to [3e079fae32].

1
2
3
4
5
6
7
8
9
10
11
12
<section class="galerie">
{{#images order="name" parent=$parent debug=1}}
	<figure>
		<a href="{{$url}}" class="internal-image"><img src="{{$thumb_url}}" alt="{{$name}}" /></a>
	</figure>
{{/images}}
</section>

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






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

Modified src/www/skel-dist/index.html from [9bf1249c8a] to [64144e4af6].

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
{{:include file="_head.html"}}

{{#articles order="modified DESC" limit=1}}
<section class="articles">
	<article>
	<h1><a href="{{ $url }}">{{ $title }}</a></h1>
	<h5>Posté : {{ $modified|relative_date }}</h5>
	<p>{{ $html|raw|strip_tags|truncate:600 }}</p>
	</article>
</section>
{{/articles}}

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


{{:include file="_foot.html"}}


|
|

|
|
|




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


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="_head.html"}}

{{#articles order="published DESC" future=false limit=1}}
<section class="articles main">
	<article>
		<h1><a href="{{ $url }}">{{ $title }}</a></h1>
		<h5>Posté : {{ $published|relative_date }}</h5>
		<p>{{ $html|raw }}</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/robots.txt version [9d03a7f081].









>
>
>
>
1
2
3
4
User-agent: *
Disallow: /admin/

Sitemap: {{$root_url}}sitemap.xml

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"}}

Added src/www/skel-dist/sitemap.xml version [923be64ae6].

































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{{#pages limit=1 order="modified DESC"}}
	<url>
		<loc>{{$root_url}}</loc>
		<lastmod>{{$modified|atom_date}}</lastmod>
	</url>
{{/pages}}

{{#pages limit=10000}}
	<url>
		<loc>{{$url}}</loc>
		<lastmod>{{$modified|atom_date}}</lastmod>
	</url>
{{/pages}}
</urlset>

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'));