Overview
Comment:Refactor Skeleton class to manage web dans form skeletons in the same place
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | dev
Files: files | file ages | folders
SHA3-256: 688da32e8c31c939e21286c60d5d305a2af71ae67cbd8f6aece190757afb7a6b
User & Date: bohwaz on 2022-11-20 04:35:26
Other Links: branch diff | manifest | tags
Context
2022-11-27
04:33
Use a different session name for WebDAV/NextCloud apps to avoid security issues check-in: 4ba510f315 user: bohwaz tags: dev
2022-11-20
04:35
Refactor Skeleton class to manage web dans form skeletons in the same place check-in: 688da32e8c user: bohwaz tags: dev
04:34
Fix some details on ouvertures check-in: 5a9c99dd3f user: bohwaz tags: dev
Changes

Modified src/include/lib/Garradin/Entities/UserForm.php from [1213ea3d8c] to [d9df494e1c].

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
		if (null !== $params) {
			$params = '?' . http_build_query($params);
		}

		return sprintf('%sform/%s/%s%s', WWW_URL, $this->name, $file, $params);
	}

	public function serve(string $file)
	{
		$this->template($file)->serve();
	}

	public function fetch(string $file, array $variables = [])
	{
		try {
			$t = $this->template($file);
			$t->assignArray($variables);
			return $t->fetch();
		}
		catch (Brindille_Exception $e) {
			return sprintf('<div style="border: 5px solid orange; padding: 10px; background: yellow;"><h2>Erreur dans le code du document</h2><p>%s</p></div>', nl2br(htmlspecialchars($e->getMessage())));
		}
	}

	public function template(string $file)
	{
		if ($file == self::CONFIG_TEMPLATE) {
			Session::getInstance()->requireAccess(Session::SECTION_CONFIG, Session::ACCESS_ADMIN);
		}

		if (!preg_match('!^(?:snippets/)?[\w\d_-]+(?:\.[\w\d_-]+)*$!i', $file)) {







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







144
145
146
147
148
149
150

















151
152
153
154
155
156
157
		if (null !== $params) {
			$params = '?' . http_build_query($params);
		}

		return sprintf('%sform/%s/%s%s', WWW_URL, $this->name, $file, $params);
	}


















	public function template(string $file)
	{
		if ($file == self::CONFIG_TEMPLATE) {
			Session::getInstance()->requireAccess(Session::SECTION_CONFIG, Session::ACCESS_ADMIN);
		}

		if (!preg_match('!^(?:snippets/)?[\w\d_-]+(?:\.[\w\d_-]+)*$!i', $file)) {

Modified src/include/lib/Garradin/UserTemplate/Functions.php from [ae984cc587] to [2a6ac40a43].

8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
use KD2\JSONSchema;

use Garradin\Config;
use Garradin\DB;
use Garradin\Template;
use Garradin\Utils;
use Garradin\UserException;
use Garradin\Web\Skeleton;
use Garradin\Email\Emails;
use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\Entities\UserForm;

use const Garradin\{ROOT, WWW_URL};








<







8
9
10
11
12
13
14

15
16
17
18
19
20
21
use KD2\JSONSchema;

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

use Garradin\Email\Emails;
use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\Entities\UserForm;

use const Garradin\{ROOT, WWW_URL};

Modified src/include/lib/Garradin/UserTemplate/Modifiers.php from [aaa136b6f0] to [d22bcb5c5d].

15
16
17
18
19
20
21

22
23
24
25
26
27
28
class Modifiers
{
	const PHP_MODIFIERS_LIST = [
		'strtolower',
		'strtoupper',
		'ucfirst',
		'ucwords',

		'htmlentities',
		'htmlspecialchars',
		'trim',
		'ltrim',
		'rtrim',
		'lcfirst',
		'md5',







>







15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Modifiers
{
	const PHP_MODIFIERS_LIST = [
		'strtolower',
		'strtoupper',
		'ucfirst',
		'ucwords',
		'strtotime',
		'htmlentities',
		'htmlspecialchars',
		'trim',
		'ltrim',
		'rtrim',
		'lcfirst',
		'md5',
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
		'get_leading_number',
		'spell_out_number',
		'parse_date',
		'math',
		'money_int' => [Utils::class, 'moneyToInteger'],
		'array_transpose' => [Utils::class, 'array_transpose'],
		'check_email',
		'validate_date_string',
	];

	const LEADING_NUMBER_REGEXP = '/^([\d.]+)\s*[.\)]\s*/';

	static public function __callStatic(string $name, array $arguments)
	{
		if (!in_array($name, self::PHP_MODIFIERS_LIST)) {







<







62
63
64
65
66
67
68

69
70
71
72
73
74
75
		'get_leading_number',
		'spell_out_number',
		'parse_date',
		'math',
		'money_int' => [Utils::class, 'moneyToInteger'],
		'array_transpose' => [Utils::class, 'array_transpose'],
		'check_email',

	];

	const LEADING_NUMBER_REGEXP = '/^([\d.]+)\s*[.\)]\s*/';

	static public function __callStatic(string $name, array $arguments)
	{
		if (!in_array($name, self::PHP_MODIFIERS_LIST)) {
87
88
89
90
91
92
93
94
95




96
97
98
99
100
101
102

			unset($arg);
		}

		return call_user_func_array($name, $arguments);
	}

	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((string) $pattern, (string) $replace, (string) $str);
	}







|

>
>
>
>







87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

			unset($arg);
		}

		return call_user_func_array($name, $arguments);
	}

	static public function replace($str, $find, $replace = null): string
	{
		if (is_array($find) && null === $replace) {
			return strtr($str, $find);
		}

		return str_replace($find, $replace, $str);
	}

	static public function regexp_replace($str, $pattern, $replace)
	{
		return preg_replace((string) $pattern, (string) $replace, (string) $str);
	}
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
			return $value;
		}
		else {
			return false;
		}
	}

	static public function validate_date_string(string $value): bool
	{
		return (bool) strtotime($value);
	}

	static public function math(string $expression, ... $params)
	{
		static $tokens_list = [
			'function'  => '(?:round|ceil|floor|cos|sin|tan|asin|acos|atan|sinh|cosh|tanh|abs|max|min|exp|sqrt|log10|log|pi)\(',
			'open'      => '\(',
			'close'     => '\)',
			'number'    => '-?\d+(?:[,\.]\d+)?',







<
<
<
<
<







245
246
247
248
249
250
251





252
253
254
255
256
257
258
			return $value;
		}
		else {
			return false;
		}
	}






	static public function math(string $expression, ... $params)
	{
		static $tokens_list = [
			'function'  => '(?:round|ceil|floor|cos|sin|tan|asin|acos|atan|sinh|cosh|tanh|abs|max|min|exp|sqrt|log10|log|pi)\(',
			'open'      => '\(',
			'close'     => '\)',
			'number'    => '-?\d+(?:[,\.]\d+)?',

Modified src/include/lib/Garradin/UserTemplate/Sections.php from [be6bbc8f3e] to [a9fab8bded].

31
32
33
34
35
36
37

38
39
40
41
42
43
44
		'transactions',
		'transaction_lines',
		'transaction_users',
		'accounts',
		'balances',
		'sql',
		'restrict',

	];

	static protected $_cache = [];

	static protected function cache(string $id, callable $callback)
	{
		if (!array_key_exists($id, self::$_cache)) {







>







31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
		'transactions',
		'transaction_lines',
		'transaction_users',
		'accounts',
		'balances',
		'sql',
		'restrict',
		'form',
	];

	static protected $_cache = [];

	static protected function cache(string $id, callable $callback)
	{
		if (!array_key_exists($id, self::$_cache)) {
585
586
587
588
589
590
591


















592
593
594
595
596
597
598
			$params['order'] .= ' COLLATE U_NOCASE';
		}

		foreach (self::sql($params, $tpl, $line) as $row) {
			yield json_decode($row['data'], true);
		}
	}



















	static public function sql(array $params, UserTemplate $tpl, int $line): \Generator
	{
		static $defaults = [
			'select' => '*',
			'order' => '1',
			'begin' => 0,







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







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
			$params['order'] .= ' COLLATE U_NOCASE';
		}

		foreach (self::sql($params, $tpl, $line) as $row) {
			yield json_decode($row['data'], true);
		}
	}

	static public function form(array $params, UserTemplate $tpl, int $line): \Generator
	{
		if (empty($params['name'])) {
			throw new Brindille_Exception('Missing parameter "name"');
		}

		$form = DB::getInstance()->first('SELECT * FROM user_forms WHERE name = ?;', $params['name']);

		if (!$form || !$form->enabled) {
			return null;
		}

		$form->config = json_decode($form->config);
		$form->path = 'forms/' . $form->name;

		yield (array) $form;
	}

	static public function sql(array $params, UserTemplate $tpl, int $line): \Generator
	{
		static $defaults = [
			'select' => '*',
			'order' => '1',
			'begin' => 0,

Modified src/include/lib/Garradin/UserTemplate/UserForms.php from [ef28c77aa4] to [2e3b77848a].

102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
	}

	static public function get(string $name): ?UserForm
	{
		return EM::findOne(UserForm::class, 'SELECT * FROM @TABLE WHERE name = ?;', $name);
	}

	static public function serve(string $uri): void
	{
		$name = substr($uri, 0, strrpos($uri, '/'));
		$file = substr($uri, strrpos($uri, '/') + 1) ?: 'index.html';

		$form = self::get($name);

		if (!$form || !$form->enabled) {
			http_response_code(404);
			throw new UserException('Ce formulaire n\'existe pas');
		}

		$form->serve($file);
	}

}







|

<
<
|
<
|
<
<
<
|
<
<
<
<
<
102
103
104
105
106
107
108
109
110


111

112



113





	}

	static public function get(string $name): ?UserForm
	{
		return EM::findOne(UserForm::class, 'SELECT * FROM @TABLE WHERE name = ?;', $name);
	}

	static public function isEnabled(string $name): bool
	{


		return (bool) EM::getInstance(UserForm::class)->col('SELECT 1 FROM @TABLE WHERE name = ? AND enabled = 1;', $name);

	}



}





Modified src/include/lib/Garradin/UserTemplate/UserTemplate.php from [854992b7f6] to [1f47d33901].

8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

30
31
32
33
34
35
36

use Garradin\Config;
use Garradin\Plugin;
use Garradin\Utils;
use Garradin\UserException;
use Garradin\Users\Session;

use Garradin\Web\Skeleton;
use Garradin\Entities\Files\File;
use Garradin\Files\Files;

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, ROOT, LEGAL_LINE};

class UserTemplate extends \KD2\Brindille
{
	const DIST_ROOT = ROOT . '/skel-dist/';

	public $_tpl_path;

	protected $modified;
	protected $file = null;
	protected $code = null;
	protected $cache_path = USER_TEMPLATES_CACHE_ROOT;

	protected $escape_default = 'html';








<














>







8
9
10
11
12
13
14

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

use Garradin\Config;
use Garradin\Plugin;
use Garradin\Utils;
use Garradin\UserException;
use Garradin\Users\Session;


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

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, ROOT, LEGAL_LINE};

class UserTemplate extends \KD2\Brindille
{
	const DIST_ROOT = ROOT . '/skel-dist/';

	public $_tpl_path;
	protected $content_type = null;
	protected $modified;
	protected $file = null;
	protected $code = null;
	protected $cache_path = USER_TEMPLATES_CACHE_ROOT;

	protected $escape_default = 'html';

83
84
85
86
87
88
89




90
91
92
93
94
95
96
		];

		return self::$root_variables;
	}

	public function __construct(string $path)
	{




		$this->_tpl_path = $path;

		if ($file = Files::get(File::CONTEXT_SKELETON . '/' . $path)) {
			if ($file->type != $file::TYPE_FILE) {
				throw new \LogicException('Cannot construct a UserTemplate with a directory');
			}








>
>
>
>







83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
		];

		return self::$root_variables;
	}

	public function __construct(string $path)
	{
		if (!self::isTemplate($path)) {
			throw new \InvalidArgumentException('Not a valid template file extension: ' . $path);
		}

		$this->_tpl_path = $path;

		if ($file = Files::get(File::CONTEXT_SKELETON . '/' . $path)) {
			if ($file->type != $file::TYPE_FILE) {
				throw new \LogicException('Cannot construct a UserTemplate with a directory');
			}

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
			header(sprintf('Content-Disposition: attachment; filename="%s"', Utils::safeFileName($filename)));
		}

		header('Content-type: application/pdf');
		Utils::streamPDF($html);
	}

	public function type(): ?string
	{
		$name = $this->file->name ?? $this->path;
		$dot = strrpos($name, '.');

		// Templates with no extension are returned as HTML by default
		// unless {{:http type=...}} is used
		if ($dot === false) {
			return 'text/html';
		}

		$ext = substr($name, $dot+1);

		switch ($ext) {
			case 'txt':
				return 'text/plain';
			case 'css':
				return 'text/css';
			case 'html':
			case 'htm':
				return 'text/html';
			case 'xml':
				return 'text/xml';
			case 'js':
				return 'text/javascript';
			case 'png':
			case 'gif':
			case 'webp':
				return 'image/' . $ext;
			case 'jpeg':
			case 'jpg':
				return 'image/jpeg';
		}

		if (preg_match('/php\d*/i', $ext)) {
			return null;
		}

		if ($this->file) {
			return $this->file->mime;
  		}

		$finfo = \finfo_open(\FILEINFO_MIME_TYPE);
		return finfo_file($finfo, $this->path);
	}


	public function serve(): void
	{
		$content = $this->fetch();
		$type = null;



		// When the header has already been defined by the template
		foreach (headers_list() as $header) {
			if (preg_match('/^Content-Type: ([\w-]+\/[\w-]+)$/', $header, $match)) {
				$type = $match[1];
				break;
			}
		}

		if (!$type) {
			$type = $this->type();
		}

		$type = $type ?: 'text/html';
		header(sprintf('Content-Type: %s;charset=utf-8', $type), true);

		if ($type == 'application/pdf') {
			Utils::streamPDF($content);
		}
		else {
			echo $content;







|

<
|







|


<
<
<
<


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

|
<
<
<
<
<
<
<
<





>
>









<
<
<
<
<







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
			header(sprintf('Content-Disposition: attachment; filename="%s"', Utils::safeFileName($filename)));
		}

		header('Content-type: application/pdf');
		Utils::streamPDF($html);
	}

	static public function isTemplate(string $filename): bool
	{

		$dot = strrpos($filename, '.');

		// Templates with no extension are returned as HTML by default
		// unless {{:http type=...}} is used
		if ($dot === false) {
			return 'text/html';
		}

		$ext = substr($filename, $dot+1);

		switch ($ext) {




			case 'html':
			case 'htm':

			case 'tpl':

			case 'btpl':

			case 'b':
			case 'skel':




				return true;

			default:

				return false;
		}
	}









	public function serve(): void
	{
		$content = $this->fetch();
		$type = null;

		$type = 'text/html';

		// When the header has already been defined by the template
		foreach (headers_list() as $header) {
			if (preg_match('/^Content-Type: ([\w-]+\/[\w-]+)$/', $header, $match)) {
				$type = $match[1];
				break;
			}
		}






		header(sprintf('Content-Type: %s;charset=utf-8', $type), true);

		if ($type == 'application/pdf') {
			Utils::streamPDF($content);
		}
		else {
			echo $content;

Modified src/include/lib/Garradin/Web/Router.php from [865ece4df6] to [50f539cc4c].

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

namespace Garradin\Web;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\Files\WebDAV\Server as WebDAV_Server;

use Garradin\UserTemplate\UserForms;
use Garradin\Web\Skeleton;
use Garradin\Web\Web;

use Garradin\API;
use Garradin\Config;
use Garradin\Plugin;
use Garradin\UserException;








<







1
2
3
4
5
6
7
8

9
10
11
12
13
14
15
<?php

namespace Garradin\Web;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\Files\WebDAV\Server as WebDAV_Server;


use Garradin\Web\Skeleton;
use Garradin\Web\Web;

use Garradin\API;
use Garradin\Config;
use Garradin\Plugin;
use Garradin\UserException;
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
			http_response_code(404);
			throw new UserException('Cette page n\'existe pas.');
		}
		elseif ('api' == $first) {
			API::dispatchURI(substr($uri, 4));
			return;
		}
		elseif ('form' == $first) {
			$uri = substr($uri, 5);
			UserForms::serve($uri);
			return;
		}
		elseif ((in_array($uri, self::DAV_ROUTES) || in_array($first, self::DAV_ROUTES))
			&& WebDAV_Server::route($uri)) {
			return;
		}
		elseif (Files::getContext($uri)
			&& (($file = Files::getFromURI($uri))
				|| ($file = Web::getAttachmentFromURI($uri)))) {







<
<
<
<
<







84
85
86
87
88
89
90





91
92
93
94
95
96
97
			http_response_code(404);
			throw new UserException('Cette page n\'existe pas.');
		}
		elseif ('api' == $first) {
			API::dispatchURI(substr($uri, 4));
			return;
		}





		elseif ((in_array($uri, self::DAV_ROUTES) || in_array($first, self::DAV_ROUTES))
			&& WebDAV_Server::route($uri)) {
			return;
		}
		elseif (Files::getContext($uri)
			&& (($file = Files::getFromURI($uri))
				|| ($file = Web::getAttachmentFromURI($uri)))) {
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
			}

			Plugin::fireSignal('http.request.file.after', compact('file', 'uri', 'session'));

			return;
		}

		if (Config::getInstance()->site_disabled) {
			Utils::redirect(ADMIN_URL);
		}

		$page = null;

		if ($uri == '') {
			$skel = 'index.html';
		}
		elseif (($page = Web::getByURI($uri)) && $page->status == Page::STATUS_ONLINE) {
			$skel = $page->template();
			$page = $page->asTemplateArray();
		}
		// No page with this URI, then we expect this might be a skeleton path
		elseif (Skeleton::isValidPath($uri)) {
			$skel = $uri;
		}
		else {
			$skel = '404.html';
		}

		$s = new Skeleton($skel);
		$s->serve(compact('uri', 'page', 'skel'));
	}

	static public function log(string $message, ...$params)
	{
		if (!HTTP_LOG_FILE) {
			return;
		}







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







121
122
123
124
125
126
127





















128

129
130
131
132
133
134
135
			}

			Plugin::fireSignal('http.request.file.after', compact('file', 'uri', 'session'));

			return;
		}






















		Skeleton::route($uri);

	}

	static public function log(string $message, ...$params)
	{
		if (!HTTP_LOG_FILE) {
			return;
		}

Modified src/include/lib/Garradin/Web/Skeleton.php from [169b8b9203] to [7acfb1b470].

1
2
3
4
5
6
7

8

9
10
11
12
13
14
15
16
17
18
19
20
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
<?php

namespace Garradin\Web;

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

use Garradin\UserTemplate\UserTemplate;

use Garradin\Plugin;
use Garradin\Utils;

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 ?string $path;
	protected ?File $file = null;














































	public function __construct(string $path)
	{
		if (!self::isValidPath($path)) {



			throw new \InvalidArgumentException('Invalid skeleton name');
		}

		$this->path = $path;
	}

	static public function isValidPath(string $path)
	{
		return (bool) preg_match('!^[\w\d_-]+(?:\.[\w\d_-]+)*$!i', $path);
	}

	public function defaultPath(): ?string
	{
		$path = ROOT . '/skel-dist/web/' . $this->path;

		if (file_exists($path)) {
			return $path;
		}

		return null;
	}

	public function error_404(): void
	{
		// Detect loop if 404.html does not exist
		if (Utils::basename($this->path) == '404.html') {
			throw new UserException('Cette page n\'existe pas.');
		}

		header('Content-Type: text/html;charset=utf-8', true);
		header('HTTP/1.1 404 Not Found', true);
		$tpl = new self('404.html');

		if (!$tpl->exists()) {
			throw new UserException('Cette page n\'existe pas.');
		}

		$tpl->serve();
	}

	public function serve(array $params = []): void
	{
		if (Plugin::fireSignal('http.request.skeleton.before', $params)) {
			return;
		}

		if (!$this->exists()) {
			$this->error_404();
			return;
		}

		$type = $this->type();

		// Unknown type
		if (null === $type) {
			$this->error_404();
			return;
		}

		// We can't serve directories
		if ($this->file && $this->file->type != $this->file::TYPE_FILE) {
			$this->error_404();
			return;
		}

		// Serve a template
		if (preg_match(self::TEMPLATE_TYPES, $type)) {

			header(sprintf('Content-Type: %s;charset=utf-8', $this->type()));

			try {

				$ut = new UserTemplate('web/' . $this->path);
			}


			catch (\InvalidArgumentException $e) {
				header('HTTP/1.1 404 Not Found', true);

				// Fallback to 404
				$ut = new UserTemplate('web/404.html');
				$ut->assignArray($params);
				$ut->display();
			}



			try {

				$ut->assignArray($params);
				$ut->displayWeb();
			}
			catch (Brindille_Exception $e) {
				if (!headers_sent()) {
					header('Content-Type: text/html; charset=utf-8', true);
				}

				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())));
			}
		}
		// Serve a static file
		elseif ($file = $this->file()) {
			$file->serve();
		}
		// Serve a static skeleton file (from skel-dist)
		else {
			header(sprintf('Content-Type: %s;charset=utf-8', $type), true);
			readfile($this->defaultPath());
		}

		Plugin::fireSignal('http.request.skeleton.after', $params);
	}

	public function file(): ?File
	{
		return Files::get(File::CONTEXT_SKELETON . '/web/' . $this->path);
	}

	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 ($file = $this->file()) {
			return $this->file();
		}

		return (string) @file_get_contents($this->defaultPath());
	}

	public function edit(string $content)
	{
		if ($file = $this->file()) {
			$file->setContent($content);
		}
		else {
			Files::createFromString(sprintf('%s/web/%s', File::CONTEXT_SKELETON, $this->path), $content);
		}
	}

	public function reset()
	{
		if ($file = $this->file()) {
			$file->delete();
		}







>

>















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



>
>
>
|







|




|








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





<
<
<
<
<


<
|
<
<
<
|
<
<
<
<




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

|
<
<
<
<
<
<
<

















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







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
<?php

namespace Garradin\Web;

use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\UserException;
use Garradin\UserTemplate\UserForms;
use Garradin\UserTemplate\UserTemplate;
use Garradin\Config;
use Garradin\Plugin;
use Garradin\Utils;

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 ?string $path;
	protected ?File $file = null;

	static public function route(string $uri): void
	{
		$page = null;

		if (substr($uri, 0, 5) == 'form/') {
			$uri = substr($uri, 5);
			$path = 'forms/' . $uri;
		}
		else {
			if (Config::getInstance()->site_disabled && $uri != 'content.css') {
				Utils::redirect(ADMIN_URL);
			}

			if ($uri == '') {
				$path = 'web/index.html';
			}
			elseif (($page = Web::getByURI($uri)) && $page->status == Page::STATUS_ONLINE) {
				$path = 'web/' . $page->template();
				$page = $page->asTemplateArray();
			}
			// No page with this URI, then we expect this might be a skeleton path
			else {
				$path = 'web/' . $uri;
			}
		}

		try {
			$s = new self($path);
			$s->serve($uri, compact('page'));
		}
		catch (\InvalidArgumentException $e) {
			if (file_exists(UserTemplate::DIST_ROOT . 'web/404.html')) {
				header('Content-Type: text/html;charset=utf-8', true);
				header('HTTP/1.1 404 Not Found', true);
				$path = 'web/404.html';

				$s = new self($path);
				$s->serve($uri);
			}
			else {
				throw new UserException('Cette page n\'existe pas');
			}
		}
	}

	public function __construct(string $path)
	{
		if (!self::isValidPath($path)) {
		}

		if (!Files::exists(File::CONTEXT_SKELETON . '/' . $path) && !file_exists(UserTemplate::DIST_ROOT . $path)) {
			throw new \InvalidArgumentException('This skeleton does not exist');
		}

		$this->path = $path;
	}

	static public function isValidPath(string $path)
	{
		return (bool) preg_match('!^(?:web|forms/[\w\d_-]+)/[\w\d_-]+(?:\.[\w\d_-]+)*$!i', $path);
	}

	public function defaultPath(): ?string
	{
		$path = UserTemplate::DIST_ROOT . $this->path;

		if (file_exists($path)) {
			return $path;
		}

		return null;
	}



















	public function serve(string $uri, array $params = []): void
	{
		if (Plugin::fireSignal('http.request.skeleton.before', $params)) {
			return;
		}






		$type = $this->type();


		if (!$type) {



			throw new \InvalidArgumentException('Invalid skeleton type');




		}

		// Serve a template
		if (preg_match(self::TEMPLATE_TYPES, $type)) {
			if (substr($this->path, 0, 6) == 'forms/') {

				$name = substr($uri, 0, strrpos($uri, '/'));

				$file = substr($uri, strrpos($uri, '/') + 1) ?: 'index.html';
				$form = UserForms::get($name);

				if (!$form || !$form->enabled) {
					http_response_code(404);
					throw new UserException('Ce formulaire n\'existe pas ou n\'est pas activé.');

				}





				$path = 'forms/' . $name . '/' . $file;
				$form->template($file)->serve();
			}
			else {
				$ut = new UserTemplate($this->path);
				$ut->assignArray($params);
				$ut->serve();







			}
		}
		// Serve a static file
		elseif ($file = $this->file()) {
			$file->serve();
		}
		// Serve a static skeleton file (from skel-dist)
		else {
			header(sprintf('Content-Type: %s;charset=utf-8', $type), true);
			readfile($this->defaultPath());
		}

		Plugin::fireSignal('http.request.skeleton.after', $params);
	}

	public function file(): ?File
	{
		return Files::get(File::CONTEXT_SKELETON . '/' . $this->path);










































































	}

	public function reset()
	{
		if ($file = $this->file()) {
			$file->delete();
		}
254
255
256
257
258
259
260
261

















































			$sources[$file->name] = ['is_text' => substr($file->mime, 0, 5) == 'text/', 'changed' => $file->modified];
		}

		ksort($sources);

		return $sources;
	}
}
























































|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
			$sources[$file->name] = ['is_text' => substr($file->mime, 0, 5) == 'text/', 'changed' => $file->modified];
		}

		ksort($sources);

		return $sources;
	}

	public function type(): ?string
	{
		$name = $this->file->name ?? $this->path;
		$dot = strrpos($name, '.');

		// Templates with no extension are returned as HTML by default
		// unless {{:http type=...}} is used
		if ($dot === false) {
			return 'text/html';
		}

		$ext = substr($name, $dot+1);

		// Common types
		switch ($ext) {
			case 'txt':
				return 'text/plain';
			case 'html':
			case 'htm':
			case 'tpl':
			case 'btpl':
			case 'skel':
				return 'text/html';
			case 'xml':
				return 'text/xml';
			case 'css':
				return 'text/css';
			case 'js':
				return 'text/javascript';
			case 'png':
			case 'gif':
			case 'webp':
				return 'image/' . $ext;
			case 'jpeg':
			case 'jpg':
				return 'image/jpeg';
		}

		if (preg_match('/php\d*/i', $ext)) {
			return null;
		}

		if ($this->file) {
			return $this->file->mime;
  		}

		return null;
	}
}

Modified src/templates/config/forms/index.tpl from [0990b8ef7e] to [f3fa1d1f58].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{include file="_head.tpl" title="Formulaires & modèles" current="config"}

{include file="config/_menu.tpl" current="forms"}

<table class="list">
	<tbody>
		{foreach from=$list item="form"}
		<tr>
			<td><h3>{$form.label}</h3>{$form.description|escape|nl2br}</td>
			<td class="actions">
				{*{linkbutton label="Modifier" href="edit.php?form=%s"|args:$form.name shape="edit" target="_dialog"}*}
				{if $form->hasConfig()}
					{linkbutton label="Configurer" href=$form->url($form::CONFIG_TEMPLATE) shape="settings" target="_dialog"}
				{/if}
				{if $form->canDelete()}
					{if $form->hasDist()}
						{linkbutton label="Remettre à zéro" href="delete.php?form=%s"|args:$form.name shape="reset" target="_dialog"}
					{else}
						{linkbutton label="Supprimer" href="delete.php?form=%s"|args:$form.name shape="delete" target="_dialog"}











|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{include file="_head.tpl" title="Formulaires & modèles" current="config"}

{include file="config/_menu.tpl" current="forms"}

<table class="list">
	<tbody>
		{foreach from=$list item="form"}
		<tr>
			<td><h3>{$form.label}</h3>{$form.description|escape|nl2br}</td>
			<td class="actions">
				{*{linkbutton label="Modifier" href="edit.php?form=%s"|args:$form.name shape="edit" target="_dialog"}*}
				{if $form->hasConfig() && $form.enabled}
					{linkbutton label="Configurer" href=$form->url($form::CONFIG_TEMPLATE) shape="settings" target="_dialog"}
				{/if}
				{if $form->canDelete()}
					{if $form->hasDist()}
						{linkbutton label="Remettre à zéro" href="delete.php?form=%s"|args:$form.name shape="reset" target="_dialog"}
					{else}
						{linkbutton label="Supprimer" href="delete.php?form=%s"|args:$form.name shape="delete" target="_dialog"}