web-base/Core/API/TemplateAPI.class.php

74 lines
2.3 KiB
PHP
Raw Normal View History

2021-12-08 16:53:43 +01:00
<?php
2022-11-18 18:06:46 +01:00
namespace Core\API {
2021-12-08 16:53:43 +01:00
2022-11-18 18:06:46 +01:00
use Core\Objects\Context;
2021-12-08 16:53:43 +01:00
abstract class TemplateAPI extends Request {
2022-06-20 19:52:31 +02:00
function __construct(Context $context, bool $externalCall = false, array $params = array()) {
parent::__construct($context, $externalCall, $params);
2021-12-08 16:53:43 +01:00
$this->isPublic = false; // internal API
}
}
}
2022-11-18 18:06:46 +01:00
namespace Core\API\Template {
2021-12-08 16:53:43 +01:00
2022-11-18 18:06:46 +01:00
use Core\API\Parameter\ArrayType;
use Core\API\Parameter\Parameter;
use Core\API\Parameter\StringType;
use Core\API\TemplateAPI;
use Core\Objects\Context;
2021-12-08 16:53:43 +01:00
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Loader\FilesystemLoader;
class Render extends TemplateAPI {
2022-06-20 19:52:31 +02:00
public function __construct(Context $context, bool $externalCall = false) {
parent::__construct($context, $externalCall, [
2021-12-08 16:53:43 +01:00
"file" => new StringType("file"),
"parameters" => new ArrayType("parameters", Parameter::TYPE_MIXED, false, true, [])
]);
}
2022-02-21 13:01:03 +01:00
public function _execute(): bool {
2021-12-08 16:53:43 +01:00
$templateFile = $this->getParam("file");
$parameters = $this->getParam("parameters");
$extension = pathinfo($templateFile, PATHINFO_EXTENSION);
$allowedExtensions = ["html", "twig"];
if (!in_array($extension, $allowedExtensions)) {
return $this->createError("Invalid template file extension. Allowed: " . implode(",", $allowedExtensions));
}
2022-11-18 18:06:46 +01:00
$templateDir = WEBROOT . "/Core/Templates/";
$templateCache = WEBROOT . "/Core/Cache/Templates/";
2021-12-08 16:53:43 +01:00
$path = realpath($templateDir . $templateFile);
if (!startsWith($path, realpath($templateDir))) {
return $this->createError("Template file not in template directory");
} else if (!is_file($path)) {
return $this->createError("Template file not found");
}
$twigLoader = new FilesystemLoader($templateDir);
$twigEnvironment = new Environment($twigLoader, [
'cache' => $templateCache,
'auto_reload' => true
]);
try {
$this->result["html"] = $twigEnvironment->render($templateFile, $parameters);
} catch (LoaderError | RuntimeError | SyntaxError $e) {
return $this->createError("Error rendering twig template: " . $e->getMessage());
}
2022-03-08 11:50:18 +01:00
return true;
2021-12-08 16:53:43 +01:00
}
}
}