. * */ namespace Friendica\Render; use Friendica\Core\Hook; use Friendica\DI; use Friendica\Util\Strings; /** * Smarty implementation of the Friendica template abstraction */ final class FriendicaSmartyEngine extends TemplateEngine { static $name = "smarty3"; const FILE_PREFIX = 'file:'; const STRING_PREFIX = 'string:'; /** @var FriendicaSmarty */ private $smarty; /** * @inheritDoc */ public function __construct(string $theme, array $theme_info) { $this->theme = $theme; $this->theme_info = $theme_info; $this->smarty = new FriendicaSmarty($this->theme, $this->theme_info); if (!is_writable(DI::basePath() . '/view/smarty3')) { echo "ERROR: folder view/smarty3/ must be writable by webserver."; exit(); } } /** * @inheritDoc */ public function replaceMacros(string $template, array $vars) { if (!Strings::startsWith($template, self::FILE_PREFIX)) { $template = self::STRING_PREFIX . $template; } // "middleware": inject variables into templates $arr = [ 'template' => basename($this->smarty->filename), 'vars' => $vars ]; Hook::callAll('template_vars', $arr); $vars = $arr['vars']; foreach ($vars as $key => $value) { if ($key[0] === '$') { $key = substr($key, 1); } $this->smarty->assign($key, $value); } return $this->smarty->fetch($template); } /** * @inheritDoc */ public function getTemplateFile(string $file, string $subDir = '') { // Make sure $root ends with a slash / if ($subDir !== '' && substr($subDir, -1, 1) !== '/') { $subDir = $subDir . '/'; } $root = DI::basePath() . '/' . $subDir; $filename = $this->smarty::SMARTY3_TEMPLATE_FOLDER . '/' . $file; if (file_exists("{$root}view/theme/$this->theme/$filename")) { $template_file = "{$root}view/theme/$this->theme/$filename"; } elseif (!empty($this->theme_info['extends']) && file_exists(sprintf('%sview/theme/%s}/%s', $root, $this->theme_info['extends'], $filename))) { $template_file = sprintf('%sview/theme/%s}/%s', $root, $this->theme_info['extends'], $filename); } elseif (file_exists("{$root}/$filename")) { $template_file = "{$root}/$filename"; } else { $template_file = "{$root}view/$filename"; } $this->smarty->filename = $template_file; return self::FILE_PREFIX . $template_file; } }