luci/libs/web/luasrc/template.lua

255 lines
6.5 KiB
Lua
Raw Normal View History

--[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
2008-09-01 16:05:40 +00:00
local fs = require"luci.fs"
local sys = require "luci.sys"
local util = require "luci.util"
local table = require "table"
local string = require "string"
local config = require "luci.config"
local coroutine = require "coroutine"
local tostring, pairs, loadstring = tostring, pairs, loadstring
local setmetatable, loadfile = setmetatable, loadfile
local getfenv, setfenv = getfenv, setfenv
local assert, type, error = assert, type, error
2008-09-01 16:05:40 +00:00
--- LuCI template library.
module "luci.template"
2008-09-01 16:05:40 +00:00
config.template = config.template or {}
2008-09-01 16:05:40 +00:00
viewdir = config.template.viewdir or util.libpath() .. "/view"
compiledir = config.template.compiledir or util.libpath() .. "/view"
-- Compile modes:
-- memory: Always compile, do not save compiled files, ignore precompiled
-- file: Compile on demand, save compiled files, update precompiled
2008-09-01 16:05:40 +00:00
compiler_mode = config.template.compiler_mode or "memory"
-- Define the namespace for template modules
2008-09-01 16:05:40 +00:00
context = util.threadlocal()
viewns = {
include = function(name) Template(name):render(getfenv(2)) end,
}
--- Manually compile a given template into an executable Lua function
-- @param template LuCI template
-- @return Lua template function
function compile(template)
2008-09-01 16:05:40 +00:00
local expr = {}
-- Search all <% %> expressions
local function expr_add(ws1, skip1, command, skip2, ws2)
table.insert(expr, command)
return ( #skip1 > 0 and "" or ws1 ) ..
"<%" .. tostring(#expr) .. "%>" ..
( #skip2 > 0 and "" or ws2 )
end
-- Save all expressiosn to table "expr"
template = template:gsub("(%s*)<%%(%-?)(.-)(%-?)%%>(%s*)", expr_add)
local function sanitize(s)
2008-09-01 16:05:40 +00:00
s = "%q" % s
2008-07-26 17:24:46 +00:00
return s:sub(2, #s-1)
end
-- Escape and sanitize all the template (all non-expressions)
template = sanitize(template)
-- Template module header/footer declaration
2008-07-31 09:54:09 +00:00
local header = 'write("'
local footer = '")'
template = header .. template .. footer
-- Replacements
2008-07-31 09:54:09 +00:00
local r_include = '")\ninclude("%s")\nwrite("'
local r_i18n = '"..translate("%1","%2").."'
local r_i18n2 = '"..translate("%1", "").."'
local r_pexec = '"..(%s or "").."'
local r_exec = '")\n%s\nwrite("'
-- Parse the expressions
for k,v in pairs(expr) do
local p = v:sub(1, 1)
v = v:gsub("%%", "%%%%")
local re = nil
if p == "+" then
re = r_include:format(sanitize(string.sub(v, 2)))
elseif p == ":" then
2008-06-09 10:10:29 +00:00
if v:find(" ") then
re = sanitize(v):gsub(":(.-) (.*)", r_i18n)
else
re = sanitize(v):gsub(":(.+)", r_i18n2)
end
elseif p == "=" then
re = r_pexec:format(v:sub(2))
2008-07-07 20:58:10 +00:00
elseif p == "#" then
re = ""
else
re = r_exec:format(v)
end
template = template:gsub("<%%"..tostring(k).."%%>", re)
end
return loadstring(template)
end
--- Render a certain template.
-- @param name Template name
2008-09-01 16:05:40 +00:00
-- @param scope Scope to assign to template (optional)
function render(name, scope)
return Template(name):render(scope or getfenv(2))
end
-- Template class
2008-09-01 16:05:40 +00:00
Template = util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
2008-09-01 16:05:40 +00:00
Template.cache = setmetatable({}, {__mode = "v"})
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name, srcfile, comfile)
2008-09-01 16:05:40 +00:00
local function _encode_filename(str)
local function __chrenc( chr )
return "%%%02x" % string.byte( chr )
end
if type(str) == "string" then
str = str:gsub(
"([^a-zA-Z0-9$_%-%.%+!*'(),])",
__chrenc
)
end
return str
end
self.template = self.cache[name]
self.name = name
-- Create a new namespace for this template
2008-09-01 16:05:40 +00:00
self.viewns = {sink=self.sink}
-- Copy over from general namespace
2008-09-01 16:05:40 +00:00
util.update(self.viewns, viewns)
if context.viewns then
2008-09-01 16:05:40 +00:00
util.update(self.viewns, context.viewns)
end
-- If we have a cached template, skip compiling and loading
if self.template then
return
end
-- Enforce cache security
2008-09-01 16:05:40 +00:00
local cdir = compiledir .. "/" .. sys.process.info("uid")
-- Compile and build
local sourcefile = srcfile or (viewdir .. "/" .. name .. ".htm")
local compiledfile = comfile or (cdir .. "/" .. _encode_filename(name) .. ".lua")
local err
if compiler_mode == "file" then
2008-09-01 16:05:40 +00:00
local tplmt = fs.mtime(sourcefile)
local commt = fs.mtime(compiledfile)
2008-09-01 16:05:40 +00:00
if not fs.mtime(cdir) then
fs.mkdir(cdir, true)
fs.chmod(fs.dirname(cdir), "a+rxw")
end
-- Build if there is no compiled file or if compiled file is outdated
if ((commt == nil) and not (tplmt == nil))
or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
local source
2008-09-01 16:05:40 +00:00
source, err = fs.readfile(sourcefile)
if source then
local compiled, err = compile(source)
2008-09-01 16:05:40 +00:00
fs.writefile(compiledfile, util.get_bytecode(compiled))
fs.chmod(compiledfile, "a-rwx,u+rw")
self.template = compiled
end
else
2008-09-01 16:05:40 +00:00
assert(
sys.process.info("uid") == fs.stat(compiledfile, "uid")
and fs.stat(compiledfile, "mode") == "rw-------",
"Fatal: Cachefile is not sane!"
)
self.template, err = loadfile(compiledfile)
end
elseif compiler_mode == "memory" then
local source
2008-09-01 16:05:40 +00:00
source, err = fs.readfile(sourcefile)
if source then
self.template, err = compile(source)
end
end
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error(err)
else
self.cache[name] = self.template
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Save old environment
local oldfenv = getfenv(self.template)
-- Put our predefined objects in the scope of the template
2008-09-01 16:05:40 +00:00
util.resfenv(self.template)
util.updfenv(self.template, scope)
util.updfenv(self.template, self.viewns)
-- Now finally render the thing
2008-09-01 16:05:40 +00:00
local stat, err = util.copcall(self.template)
if not stat then
2008-09-01 16:05:40 +00:00
setfenv(self.template, oldfenv)
error("Error in template %s: %s" % {self.name, err})
end
-- Reset environment
setfenv(self.template, oldfenv)
end