Overview
Comment:Move type detection to UserTemplate, add nicer error messages
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | dev
Files: files | file ages | folders
SHA3-256: c67050ca7eabe51b7c8ab0196fee9bffe7e94bcf35473930c4dd28d5dd64cb5b
User & Date: bohwaz on 2022-11-20 02:05:55
Other Links: branch diff | manifest | tags
Context
2022-11-20
04:26
Completed all features of ouvertures check-in: f4440c64d9 user: bohwaz tags: dev
02:05
Move type detection to UserTemplate, add nicer error messages check-in: c67050ca7e user: bohwaz tags: dev
02:04
Implement math and json_encode modifiers check-in: 73e45ba011 user: bohwaz tags: dev
Changes

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

144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
		if (null !== $params) {
			$params = '?' . http_build_query($params);
		}

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

	public function displayWeb(string $file)
	{
		try {
			$this->template($file)->displayWeb();
		}
		catch (Brindille_Exception $e) {
			printf('<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 fetch(string $file, array $variables = [])
	{
		try {
			$t = $this->template($file);
			$t->assignArray($variables);







|

<
|
<
<
<
<







144
145
146
147
148
149
150
151
152

153




154
155
156
157
158
159
160
		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);

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

114
115
116
117
118
119
120
121
122
123
124
		$form = self::get($name);

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

		$form->displayWeb($file);
	}

}







|



114
115
116
117
118
119
120
121
122
123
124
		$form = self::get($name);

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

		$form->serve($file);
	}

}

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

1
2
3
4
5
6
7
8
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\UserTemplate;

use KD2\Brindille;
use KD2\Brindille_Exception;
use KD2\Translate;

use Garradin\Config;
use Garradin\Plugin;
use Garradin\Utils;

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
{


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

	protected $escape_default = 'html';











>














>
>







1
2
3
4
5
6
7
8
9
10
11
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\UserTemplate;

use KD2\Brindille;
use KD2\Brindille_Exception;
use KD2\Translate;

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';
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
				throw new \LogicException('Cannot construct a UserTemplate with a directory');
			}

			$this->file = $file;
			$this->modified = $file->modified->getTimestamp();
		}
		else {
			$this->path = ROOT . '/skel-dist/' . $path;

			if (!($this->modified = @filemtime($this->path))) {
				throw new \InvalidArgumentException('File not found: ' . $this->path);
			}
		}

		$this->assignArray(self::getRootVariables());







|







94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
				throw new \LogicException('Cannot construct a UserTemplate with a directory');
			}

			$this->file = $file;
			$this->modified = $file->modified->getTimestamp();
		}
		else {
			$this->path = self::DIST_ROOT . $path;

			if (!($this->modified = @filemtime($this->path))) {
				throw new \InvalidArgumentException('File not found: ' . $this->path);
			}
		}

		$this->assignArray(self::getRootVariables());
174
175
176
177
178
179
180
















181
182
183
184
185
186
187
			$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->file = null;
		$this->path = $path;
		$this->modified = filemtime($path);







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







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
			$this->registerFunction($name, [Functions::class, $name]);
		}

		// Local sections
		foreach (Sections::SECTIONS_LIST as $name) {
			$this->registerSection($name, [Sections::class, $name]);
		}

		$this->registerCompileBlock(':break', function (string $name, string $params, Brindille $tpl, int $line) {
			$in_loop = false;
			foreach ($this->_stack as $element) {
				if ($element[0] == $this::SECTION) {
					$in_loop = true;
					break;
				}
			}

			if (!$in_loop) {
				throw new Brindille_Exception(sprintf('Error on line %d: break can only be used inside a section', $line));
			}

			return '<?php break; ?>';
		});
	}

	public function setSource(string $path)
	{
		$this->file = null;
		$this->path = $path;
		$this->modified = filemtime($path);
234
235
236
237
238
239
240
241
242

243














244
245
246
247
248
249
250
		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 : ($this->code ? 'code' : 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))) {







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







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
		try {
			$code = $this->compile($source);
			file_put_contents($tmp_path, $code);

			require $tmp_path;
		}
		catch (Brindille_Exception $e) {

			$path = $this->file ? $this->file->name : ($this->code ? 'code' : Utils::basename($this->path));

			$message = sprintf("Erreur dans '%s' :\n%s", $path, $e->getMessage());

			if (0 === strpos($this->path ?? '', self::DIST_ROOT)) {
				// We want errors in shipped code to be reported, it is not normal
				throw new \RuntimeException($message, 0, $e);
			}
			elseif (Session::getInstance()->isAdmin()) {
				// Report error to admin with the highlighted line
				$this->error($e, $message);
				return;
			}
			else {
				// Only report error
				throw new UserException($message, 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))) {
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





































			header(sprintf('Content-Disposition: attachment; filename="%s"', Utils::safeFileName($filename)));
		}

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
















































	public function displayWeb(): void
	{
		$content = $this->fetch();



		foreach (headers_list() as $header) {
			if (preg_match('/^Content-Type: (.*)$/', $header, $match)) {
				$type = $match[1];
				break;
			}
		}





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

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












































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


>

>

|





>
>
>
>
|









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

	public function error(\Exception $e, string $message)
	{
		$header = ini_get('error_prepend_string');
		$header = preg_replace('!<if\((sent|logged|report|email|log)\)>(.*?)</if>!is', '', $header);
		echo $header;

		$path = $this->file->name ?? $this->path;
		$location = false !== strpos($path, '/web/') ? 'Dans un squelette du site web' : 'Dans le code d\'un formulaire';

		printf('<section><header><h1>%s</h1><h2>%s</h2></header>',
			$location, nl2br(htmlspecialchars($message)));

		if ($this->code || !preg_match('/Line (\d+)\s*:/i', $message, $match)) {
			return;
		}

		$line = $match[1] - 1;

		$file = file($path);
		$start = max(0, $line - 5);
		$max = min(count($file), $line + 6);

		echo '<pre><code>';

		for ($i = $start; $i < $max; $i++) {
			$code = sprintf('<b>%d</b>%s', $i + 1, htmlspecialchars($file[$i]));

			if ($i == $line) {
				$code = sprintf('<u>%s</u>', $code);
			}

			echo $code;
		}

		echo '</code></pre>';
	}
}

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

95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
			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);
			$ut->setContentType($type);

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








<







95
96
97
98
99
100
101

102
103
104
105
106
107
108
			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();
			}

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
			$file->setContent($content);
		}
		else {
			Files::createFromString(sprintf('%s/web/%s', File::CONTEXT_SKELETON, $this->path), $content);
		}
	}

	public function type(): ?string
	{
		$name = $this->file->name ?? $this->defaultPath();
		$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->defaultPath());
	}

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








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







206
207
208
209
210
211
212














































213
214
215
216
217
218
219
			$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();
		}
	}