* Replaced luafilesystem with luaposix library
[project/luci.git] / src / ffluci / template.lua
1 --[[
2 FFLuCI - Template Parser
3
4 Description:
5 A template parser supporting includes, translations, Lua code blocks
6 and more. It can be used either as a compiler or as an interpreter.
7
8 FileId: $Id$
9
10 License:
11 Copyright 2008 Steven Barth <steven@midlink.org>
12
13 Licensed under the Apache License, Version 2.0 (the "License");
14 you may not use this file except in compliance with the License.
15 You may obtain a copy of the License at 
16
17         http://www.apache.org/licenses/LICENSE-2.0 
18
19 Unless required by applicable law or agreed to in writing, software
20 distributed under the License is distributed on an "AS IS" BASIS,
21 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 See the License for the specific language governing permissions and
23 limitations under the License.
24
25 ]]--
26 module("ffluci.template", package.seeall)
27
28 require("ffluci.config")
29 require("ffluci.util")
30 require("ffluci.fs")
31 require("ffluci.i18n")
32 require("ffluci.model.uci")
33
34 viewdir = ffluci.fs.dirname(ffluci.util.__file__()) .. "/view/"
35
36
37 -- Compile modes:
38 -- none:        Never compile, only use precompiled data from files
39 -- memory:      Always compile, do not save compiled files, ignore precompiled 
40 -- file:        Compile on demand, save compiled files, update precompiled
41 compiler_mode = "memory"
42
43
44 -- This applies to compiler modes "always" and "smart"
45 --
46 -- Produce compiled lua code rather than lua sourcecode
47 -- WARNING: Increases template size heavily!!!
48 -- This produces the same bytecode as luac but does not have a strip option
49 compiler_enable_bytecode = false
50
51
52 -- Define the namespace for template modules
53 viewns = {
54         translate  = ffluci.i18n.translate,
55         config     = function(...) return ffluci.model.uci.get(...) or "" end,
56         controller = os.getenv("SCRIPT_NAME"),
57         media      = ffluci.config.main.mediaurlbase,
58         write      = io.write,
59         include    = function(name) Template(name):render(getfenv(2)) end,      
60 }
61
62 -- Compiles a given template into an executable Lua module
63 function compile(template)      
64         -- Search all <% %> expressions (remember: Lua table indexes begin with #1)
65         local function expr_add(command)
66                 table.insert(expr, command)
67                 return "<%" .. tostring(#expr) .. "%>"
68         end
69         
70         -- As "expr" should be local, we have to assign it to the "expr_add" scope 
71         local expr = {}
72         ffluci.util.extfenv(expr_add, "expr", expr)
73         
74         -- Save all expressiosn to table "expr"
75         template = template:gsub("<%%(.-)%%>", expr_add)
76         
77         local function sanitize(s)
78                 s = ffluci.util.escape(s)
79                 s = ffluci.util.escape(s, "'")
80                 s = ffluci.util.escape(s, "\n")
81                 return s
82         end
83         
84         -- Escape and sanitize all the template (all non-expressions)
85         template = sanitize(template)
86
87         -- Template module header/footer declaration
88         local header = "write('"
89         local footer = "')"
90         
91         template = header .. template .. footer
92         
93         -- Replacements
94         local r_include = "')\ninclude('%s')\nwrite('"
95         local r_i18n    = "'..translate('%1','%2')..'"
96         local r_uci     = "'..config('%1','%2','%3')..'"
97         local r_pexec   = "'..%s..'"
98         local r_exec    = "')\n%s\nwrite('"
99         
100         -- Parse the expressions
101         for k,v in pairs(expr) do
102                 local p = v:sub(1, 1)
103                 local re = nil
104                 if p == "+" then
105                         re = r_include:format(sanitize(string.sub(v, 2)))
106                 elseif p == ":" then
107                         re = sanitize(v):gsub(":(.-) (.+)", r_i18n)
108                 elseif p == "~" then
109                         re = sanitize(v):gsub("~(.-)%.(.-)%.(.+)", r_uci)
110                 elseif p == "=" then
111                         re = r_pexec:format(v:sub(2))
112                 else
113                         re = r_exec:format(v)
114                 end
115                 template = template:gsub("<%%"..tostring(k).."%%>", re)
116         end
117
118         if compiler_enable_bytecode then 
119                 tf = loadstring(template)
120                 template = string.dump(tf)
121         end
122         
123         c = c or 1
124         ffluci.fs.writefile("/tmp/"..tostring(c), template)
125         c = c+1
126         
127         return template
128 end
129
130 -- Oldstyle render shortcut
131 function render(name, scope, ...)
132         scope = scope or getfenv(2)
133         local s, t = pcall(Template, name)
134         if not s then
135                 error(t)
136         else
137                 t:render(scope, ...)
138         end
139 end
140
141
142 -- Template class
143 Template = ffluci.util.class()
144
145 -- Shared template cache to store templates in to avoid unnecessary reloading
146 Template.cache = {}
147
148
149 -- Constructor - Reads and compiles the template on-demand
150 function Template.__init__(self, name)  
151         if self.cache[name] then
152                 self.template = self.cache[name]
153         else
154                 self.template = nil
155         end
156         
157         -- Create a new namespace for this template
158         self.viewns = {}
159         
160         -- Copy over from general namespace
161         for k, v in pairs(viewns) do
162                 self.viewns[k] = v
163         end     
164         
165         -- If we have a cached template, skip compiling and loading
166         if self.template then
167                 return
168         end
169         
170         -- Compile and build
171         local sourcefile   = viewdir .. name .. ".htm"
172         local compiledfile = viewdir .. name .. ".lua"
173         local err       
174         
175         if compiler_mode == "file" then
176                 local tplmt = ffluci.fs.mtime(sourcefile)
177                 local commt = ffluci.fs.mtime(compiledfile)
178                                 
179                 -- Build if there is no compiled file or if compiled file is outdated
180                 if ((commt == nil) and not (tplmt == nil))
181                 or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
182                         local compiled = compile(ffluci.fs.readfile(sourcefile))
183                         ffluci.fs.writefile(compiledfile, compiled)
184                         self.template, err = loadstring(compiled)
185                 else
186                         self.template, err = loadfile(compiledfile)
187                 end
188                 
189         elseif compiler_mode == "none" then
190                 self.template, err = loadfile(self.compiledfile)
191                 
192         elseif compiler_mode == "memory" then
193                 self.template, err = loadstring(compile(ffluci.fs.readfile(sourcefile)))
194                         
195         end
196         
197         -- If we have no valid template throw error, otherwise cache the template
198         if not self.template then
199                 error(err)
200         else
201                 self.cache[name] = self.template
202         end
203 end
204
205
206 -- Renders a template
207 function Template.render(self, scope)
208         scope = scope or getfenv(2)
209         
210         -- Save old environment
211         local oldfenv = getfenv(self.template)
212         
213         -- Put our predefined objects in the scope of the template
214         ffluci.util.resfenv(self.template)
215         ffluci.util.updfenv(self.template, scope)
216         ffluci.util.updfenv(self.template, self.viewns)
217         
218         -- Now finally render the thing
219         self.template()
220         
221         -- Reset environment
222         setfenv(self.template, oldfenv)
223 end