1 -- Copyright 2008 Steven Barth <steven@midlink.org>
2 -- Licensed to the public under the Apache License 2.0.
4 module("luci.cbi", package.seeall)
6 require("luci.template")
7 local util = require("luci.util")
11 --local event = require "luci.sys.event"
12 local fs = require("nixio.fs")
13 local uci = require("luci.model.uci")
14 local datatypes = require("luci.cbi.datatypes")
15 local dispatcher = require("luci.dispatcher")
16 local class = util.class
17 local instanceof = util.instanceof
29 CREATE_PREFIX = "cbi.cts."
30 REMOVE_PREFIX = "cbi.rts."
31 RESORT_PREFIX = "cbi.sts."
32 FEXIST_PREFIX = "cbi.cbe."
34 -- Loads a CBI map from given file, creating an environment and returns it
35 function load(cbimap, ...)
36 local fs = require "nixio.fs"
37 local i18n = require "luci.i18n"
38 require("luci.config")
41 local upldir = "/etc/luci-uploads/"
42 local cbidir = luci.util.libpath() .. "/model/cbi/"
45 if fs.access(cbidir..cbimap..".lua") then
46 func, err = loadfile(cbidir..cbimap..".lua")
47 elseif fs.access(cbimap) then
48 func, err = loadfile(cbimap)
50 func, err = nil, "Model '" .. cbimap .. "' not found!"
56 translate=i18n.translate,
57 translatef=i18n.translatef,
61 setfenv(func, setmetatable(env, {__index =
63 return rawget(tbl, key) or _M[key] or _G[key]
66 local maps = { func() }
68 local has_upload = false
70 for i, map in ipairs(maps) do
71 if not instanceof(map, Node) then
72 error("CBI map returns no valid map object!")
76 if map.upload_fields then
78 for _, field in ipairs(map.upload_fields) do
80 field.config .. '.' ..
81 (field.section.sectiontype or '1') .. '.' ..
90 local uci = luci.model.uci.cursor()
91 local prm = luci.http.context.request.message.params
94 luci.http.setfilehandler(
95 function( field, chunk, eof )
96 if not field then return end
97 if field.name and not cbid then
98 local c, s, o = field.name:gmatch(
99 "cbid%.([^%.]+)%.([^%.]+)%.([^%.]+)"
102 if c and s and o then
103 local t = uci:get( c, s ) or s
104 if uploads[c.."."..t.."."..o] then
105 local path = upldir .. field.name
106 fd = io.open(path, "w")
115 if field.name == cbid and fd then
132 -- Compile a datatype specification into a parse tree for evaluation later on
134 local cdt_cache = { }
136 function compile_datatype(code)
143 for i = 1, #code+1 do
144 local byte = code:byte(i) or 44
147 elseif byte == 92 then
149 elseif byte == 40 or byte == 44 then
152 local label = code:sub(pos, i-1)
157 if #label > 0 and tonumber(label) then
158 stack[#stack+1] = tonumber(label)
159 elseif label:match("^'.*'$") or label:match('^".*"$') then
160 stack[#stack+1] = label:gsub("[\"'](.*)[\"']", "%1")
161 elseif type(datatypes[label]) == "function" then
162 stack[#stack+1] = datatypes[label]
163 stack[#stack+1] = { }
165 error("Datatype error, bad token %q" % label)
170 depth = depth + (byte == 40 and 1 or 0)
171 elseif byte == 41 then
174 if type(stack[#stack-1]) ~= "function" then
175 error("Datatype error, argument list follows non-function")
177 stack[#stack] = compile_datatype(code:sub(pos, i-1))
186 function verify_datatype(dt, value)
187 if dt and #dt > 0 then
188 if not cdt_cache[dt] then
189 local c = compile_datatype(dt)
190 if c and type(c[1]) == "function" then
193 error("Datatype error, not a function expression")
196 if cdt_cache[dt] then
197 return cdt_cache[dt][1](value, unpack(cdt_cache[dt][2]))
204 -- Node pseudo abstract class
207 function Node.__init__(self, title, description)
209 self.title = title or ""
210 self.description = description or ""
211 self.template = "cbi/node"
215 function Node._run_hook(self, hook)
216 if type(self[hook]) == "function" then
217 return self[hook](self)
221 function Node._run_hooks(self, ...)
224 for _, f in ipairs(arg) do
225 if type(self[f]) == "function" then
234 function Node.prepare(self, ...)
235 for k, child in ipairs(self.children) do
240 -- Append child nodes
241 function Node.append(self, obj)
242 table.insert(self.children, obj)
245 -- Parse this node and its children
246 function Node.parse(self, ...)
247 for k, child in ipairs(self.children) do
253 function Node.render(self, scope)
257 luci.template.render(self.template, scope)
260 -- Render the children
261 function Node.render_children(self, ...)
263 for k, node in ipairs(self.children) do
264 node.last_child = (k == #self.children)
271 A simple template element
273 Template = class(Node)
275 function Template.__init__(self, template)
277 self.template = template
280 function Template.render(self)
281 luci.template.render(self.template, {self=self})
284 function Template.parse(self, readinput)
285 self.readinput = (readinput ~= false)
286 return Map.formvalue(self, "cbi.submit") and FORM_DONE or FORM_NODATA
291 Map - A map describing a configuration file
295 function Map.__init__(self, config, ...)
296 Node.__init__(self, ...)
299 self.parsechain = {self.config}
300 self.template = "cbi/map"
301 self.apply_on_parse = nil
302 self.readinput = true
306 self.uci = uci.cursor()
311 local path = "%s/%s" %{ self.uci:get_confdir(), self.config }
312 if fs.stat(path, "type") ~= "reg" then
313 fs.writefile(path, "")
316 local ok, err = self.uci:load(self.config)
318 local url = dispatcher.build_url(unpack(dispatcher.context.request))
319 local source = self:formvalue("cbi.source")
320 if type(source) == "string" then
321 fs.writefile(path, source:gsub("\r\n", "\n"))
322 ok, err = self.uci:load(self.config)
324 luci.http.redirect(url)
331 self.template = "cbi/error"
333 self.source = fs.readfile(path) or ""
334 self.pageaction = false
338 function Map.formvalue(self, key)
339 return self.readinput and luci.http.formvalue(key) or nil
342 function Map.formvaluetable(self, key)
343 return self.readinput and luci.http.formvaluetable(key) or {}
346 function Map.get_scheme(self, sectiontype, option)
348 return self.scheme and self.scheme.sections[sectiontype]
350 return self.scheme and self.scheme.variables[sectiontype]
351 and self.scheme.variables[sectiontype][option]
355 function Map.submitstate(self)
356 return self:formvalue("cbi.submit")
359 -- Chain foreign config
360 function Map.chain(self, config)
361 table.insert(self.parsechain, config)
364 function Map.state_handler(self, state)
368 -- Use optimized UCI writing
369 function Map.parse(self, readinput, ...)
370 if self:formvalue("cbi.skip") then
371 self.state = FORM_SKIP
372 elseif not self.save then
373 self.state = FORM_INVALID
374 elseif not self:submitstate() then
375 self.state = FORM_NODATA
378 -- Back out early to prevent unauthorized changes on the subsequent parse
379 if self.state ~= nil then
380 return self:state_handler(self.state)
383 self.readinput = (readinput ~= false)
384 self:_run_hooks("on_parse")
386 Node.parse(self, ...)
388 self:_run_hooks("on_save", "on_before_save")
389 for i, config in ipairs(self.parsechain) do
390 self.uci:save(config)
392 self:_run_hooks("on_after_save")
393 if (not self.proceed and self.flow.autoapply) or luci.http.formvalue("cbi.apply") then
394 self:_run_hooks("on_before_commit")
395 for i, config in ipairs(self.parsechain) do
396 self.uci:commit(config)
398 -- Refresh data because commit changes section names
399 self.uci:load(config)
401 self:_run_hooks("on_commit", "on_after_commit", "on_before_apply")
402 if self.apply_on_parse then
403 self.uci:apply(self.parsechain)
404 self:_run_hooks("on_apply", "on_after_apply")
406 -- This is evaluated by the dispatcher and delegated to the
407 -- template which in turn fires XHR to perform the actual
409 self.apply_needed = true
413 Node.parse(self, true)
415 for i, config in ipairs(self.parsechain) do
416 self.uci:unload(config)
418 if type(self.commit_handler) == "function" then
419 self:commit_handler(self:submitstate())
423 self.state = FORM_PROCEED
424 elseif self.changed then
425 self.state = FORM_CHANGED
427 self.state = FORM_VALID
430 return self:state_handler(self.state)
433 function Map.render(self, ...)
434 self:_run_hooks("on_init")
435 Node.render(self, ...)
438 -- Creates a child section
439 function Map.section(self, class, ...)
440 if instanceof(class, AbstractSection) then
441 local obj = class(self, ...)
445 error("class must be a descendent of AbstractSection")
450 function Map.add(self, sectiontype)
451 return self.uci:add(self.config, sectiontype)
455 function Map.set(self, section, option, value)
456 if type(value) ~= "table" or #value > 0 then
458 return self.uci:set(self.config, section, option, value)
460 return self.uci:set(self.config, section, value)
463 return Map.del(self, section, option)
468 function Map.del(self, section, option)
470 return self.uci:delete(self.config, section, option)
472 return self.uci:delete(self.config, section)
477 function Map.get(self, section, option)
479 return self.uci:get_all(self.config)
481 return self.uci:get(self.config, section, option)
483 return self.uci:get_all(self.config, section)
490 Compound = class(Node)
492 function Compound.__init__(self, ...)
494 self.template = "cbi/compound"
495 self.children = {...}
498 function Compound.populate_delegator(self, delegator)
499 for _, v in ipairs(self.children) do
500 v.delegator = delegator
504 function Compound.parse(self, ...)
505 local cstate, state = 0
507 for k, child in ipairs(self.children) do
508 cstate = child:parse(...)
509 state = (not state or cstate < state) and cstate or state
517 Delegator - Node controller
519 Delegator = class(Node)
520 function Delegator.__init__(self, ...)
521 Node.__init__(self, ...)
523 self.defaultpath = {}
524 self.pageaction = false
525 self.readinput = true
526 self.allow_reset = false
527 self.allow_cancel = false
528 self.allow_back = false
529 self.allow_finish = false
530 self.template = "cbi/delegator"
533 function Delegator.set(self, name, node)
534 assert(not self.nodes[name], "Duplicate entry")
536 self.nodes[name] = node
539 function Delegator.add(self, name, node)
540 node = self:set(name, node)
541 self.defaultpath[#self.defaultpath+1] = name
544 function Delegator.insert_after(self, name, after)
545 local n = #self.chain + 1
546 for k, v in ipairs(self.chain) do
552 table.insert(self.chain, n, name)
555 function Delegator.set_route(self, ...)
556 local n, chain, route = 0, self.chain, {...}
558 if chain[i] == self.current then
567 for i = n + 1, #chain do
572 function Delegator.get(self, name)
573 local node = self.nodes[name]
575 if type(node) == "string" then
576 node = load(node, name)
579 if type(node) == "table" and getmetatable(node) == nil then
580 node = Compound(unpack(node))
586 function Delegator.parse(self, ...)
587 if self.allow_cancel and Map.formvalue(self, "cbi.cancel") then
588 if self:_run_hooks("on_cancel") then
593 if not Map.formvalue(self, "cbi.delg.current") then
594 self:_run_hooks("on_init")
598 self.chain = self.chain or self:get_chain()
599 self.current = self.current or self:get_active()
600 self.active = self.active or self:get(self.current)
601 assert(self.active, "Invalid state")
603 local stat = FORM_DONE
604 if type(self.active) ~= "function" then
605 self.active:populate_delegator(self)
606 stat = self.active:parse()
611 if stat > FORM_PROCEED then
612 if Map.formvalue(self, "cbi.delg.back") then
613 newcurrent = self:get_prev(self.current)
615 newcurrent = self:get_next(self.current)
617 elseif stat < FORM_PROCEED then
622 if not Map.formvalue(self, "cbi.submit") then
624 elseif stat > FORM_PROCEED
625 and (not newcurrent or not self:get(newcurrent)) then
626 return self:_run_hook("on_done") or FORM_DONE
628 self.current = newcurrent or self.current
629 self.active = self:get(self.current)
630 if type(self.active) ~= "function" then
631 self.active:populate_delegator(self)
632 local stat = self.active:parse(false)
633 if stat == FORM_SKIP then
634 return self:parse(...)
639 return self:parse(...)
644 function Delegator.get_next(self, state)
645 for k, v in ipairs(self.chain) do
647 return self.chain[k+1]
652 function Delegator.get_prev(self, state)
653 for k, v in ipairs(self.chain) do
655 return self.chain[k-1]
660 function Delegator.get_chain(self)
661 local x = Map.formvalue(self, "cbi.delg.path") or self.defaultpath
662 return type(x) == "table" and x or {x}
665 function Delegator.get_active(self)
666 return Map.formvalue(self, "cbi.delg.current") or self.chain[1]
674 Page.__init__ = Node.__init__
675 Page.parse = function() end
679 SimpleForm - A Simple non-UCI form
681 SimpleForm = class(Node)
683 function SimpleForm.__init__(self, config, title, description, data)
684 Node.__init__(self, title, description)
686 self.data = data or {}
687 self.template = "cbi/simpleform"
689 self.pageaction = false
690 self.readinput = true
693 SimpleForm.formvalue = Map.formvalue
694 SimpleForm.formvaluetable = Map.formvaluetable
696 function SimpleForm.parse(self, readinput, ...)
697 self.readinput = (readinput ~= false)
699 if self:formvalue("cbi.skip") then
703 if self:formvalue("cbi.cancel") and self:_run_hooks("on_cancel") then
707 if self:submitstate() then
708 Node.parse(self, 1, ...)
712 for k, j in ipairs(self.children) do
713 for i, v in ipairs(j.children) do
715 and (not v.tag_missing or not v.tag_missing[1])
716 and (not v.tag_invalid or not v.tag_invalid[1])
722 not self:submitstate() and FORM_NODATA
723 or valid and FORM_VALID
726 self.dorender = not self.handle
728 local nrender, nstate = self:handle(state, self.data)
729 self.dorender = self.dorender or (nrender ~= false)
730 state = nstate or state
735 function SimpleForm.render(self, ...)
736 if self.dorender then
737 Node.render(self, ...)
741 function SimpleForm.submitstate(self)
742 return self:formvalue("cbi.submit")
745 function SimpleForm.section(self, class, ...)
746 if instanceof(class, AbstractSection) then
747 local obj = class(self, ...)
751 error("class must be a descendent of AbstractSection")
755 -- Creates a child field
756 function SimpleForm.field(self, class, ...)
758 for k, v in ipairs(self.children) do
759 if instanceof(v, SimpleSection) then
765 section = self:section(SimpleSection)
768 if instanceof(class, AbstractValue) then
769 local obj = class(self, section, ...)
770 obj.track_missing = true
774 error("class must be a descendent of AbstractValue")
778 function SimpleForm.set(self, section, option, value)
779 self.data[option] = value
783 function SimpleForm.del(self, section, option)
784 self.data[option] = nil
788 function SimpleForm.get(self, section, option)
789 return self.data[option]
793 function SimpleForm.get_scheme()
798 Form = class(SimpleForm)
800 function Form.__init__(self, ...)
801 SimpleForm.__init__(self, ...)
809 AbstractSection = class(Node)
811 function AbstractSection.__init__(self, map, sectiontype, ...)
812 Node.__init__(self, ...)
813 self.sectiontype = sectiontype
815 self.config = map.config
820 self.tag_invalid = {}
821 self.tag_deperror = {}
825 self.addremove = false
829 -- Define a tab for the section
830 function AbstractSection.tab(self, tab, title, desc)
831 self.tabs = self.tabs or { }
832 self.tab_names = self.tab_names or { }
834 self.tab_names[#self.tab_names+1] = tab
842 -- Check whether the section has tabs
843 function AbstractSection.has_tabs(self)
844 return (self.tabs ~= nil) and (next(self.tabs) ~= nil)
847 -- Appends a new option
848 function AbstractSection.option(self, class, option, ...)
849 if instanceof(class, AbstractValue) then
850 local obj = class(self.map, self, option, ...)
852 self.fields[option] = obj
854 elseif class == true then
855 error("No valid class was given and autodetection failed.")
857 error("class must be a descendant of AbstractValue")
861 -- Appends a new tabbed option
862 function AbstractSection.taboption(self, tab, ...)
864 assert(tab and self.tabs and self.tabs[tab],
865 "Cannot assign option to not existing tab %q" % tostring(tab))
867 local l = self.tabs[tab].childs
868 local o = AbstractSection.option(self, ...)
870 if o then l[#l+1] = o end
875 -- Render a single tab
876 function AbstractSection.render_tab(self, tab, ...)
878 assert(tab and self.tabs and self.tabs[tab],
879 "Cannot render not existing tab %q" % tostring(tab))
882 for k, node in ipairs(self.tabs[tab].childs) do
883 node.last_child = (k == #self.tabs[tab].childs)
888 -- Parse optional options
889 function AbstractSection.parse_optionals(self, section, noparse)
890 if not self.optional then
894 self.optionals[section] = {}
898 field = self.map:formvalue("cbi.opt."..self.config.."."..section)
901 for k,v in ipairs(self.children) do
902 if v.optional and not v:cfgvalue(section) and not self:has_tabs() then
903 if field == v.option then
905 self.map.proceed = true
907 table.insert(self.optionals[section], v)
912 if field and #field > 0 and self.dynamic then
913 self:add_dynamic(field)
917 -- Add a dynamic option
918 function AbstractSection.add_dynamic(self, field, optional)
919 local o = self:option(Value, field, field)
920 o.optional = optional
923 -- Parse all dynamic options
924 function AbstractSection.parse_dynamic(self, section)
925 if not self.dynamic then
929 local arr = luci.util.clone(self:cfgvalue(section))
930 local form = self.map:formvaluetable("cbid."..self.config.."."..section)
931 for k, v in pairs(form) do
935 for key,val in pairs(arr) do
938 for i,c in ipairs(self.children) do
939 if c.option == key then
944 if create and key:sub(1, 1) ~= "." then
945 self.map.proceed = true
946 self:add_dynamic(key, true)
951 -- Returns the section's UCI table
952 function AbstractSection.cfgvalue(self, section)
953 return self.map:get(section)
957 function AbstractSection.push_events(self)
958 --luci.util.append(self.map.events, self.events)
959 self.map.changed = true
962 -- Removes the section
963 function AbstractSection.remove(self, section)
964 self.map.proceed = true
965 return self.map:del(section)
968 -- Creates the section
969 function AbstractSection.create(self, section)
973 stat = section:match("^[%w_]+$") and self.map:set(section, nil, self.sectiontype)
975 section = self.map:add(self.sectiontype)
980 for k,v in pairs(self.children) do
982 self.map:set(section, v.option, v.default)
986 for k,v in pairs(self.defaults) do
987 self.map:set(section, k, v)
991 self.map.proceed = true
997 SimpleSection = class(AbstractSection)
999 function SimpleSection.__init__(self, form, ...)
1000 AbstractSection.__init__(self, form, nil, ...)
1001 self.template = "cbi/nullsection"
1005 Table = class(AbstractSection)
1007 function Table.__init__(self, form, data, ...)
1008 local datasource = {}
1010 datasource.config = "table"
1011 self.data = data or {}
1013 datasource.formvalue = Map.formvalue
1014 datasource.formvaluetable = Map.formvaluetable
1015 datasource.readinput = true
1017 function datasource.get(self, section, option)
1018 return tself.data[section] and tself.data[section][option]
1021 function datasource.submitstate(self)
1022 return Map.formvalue(self, "cbi.submit")
1025 function datasource.del(...)
1029 function datasource.get_scheme()
1033 AbstractSection.__init__(self, datasource, "table", ...)
1034 self.template = "cbi/tblsection"
1035 self.rowcolors = true
1036 self.anonymous = true
1039 function Table.parse(self, readinput)
1040 self.map.readinput = (readinput ~= false)
1041 for i, k in ipairs(self:cfgsections()) do
1042 if self.map:submitstate() then
1048 function Table.cfgsections(self)
1051 for i, v in luci.util.kspairs(self.data) do
1052 table.insert(sections, i)
1058 function Table.update(self, data)
1065 NamedSection - A fixed configuration section defined by its name
1067 NamedSection = class(AbstractSection)
1069 function NamedSection.__init__(self, map, section, stype, ...)
1070 AbstractSection.__init__(self, map, stype, ...)
1073 self.addremove = false
1074 self.template = "cbi/nsection"
1075 self.section = section
1078 function NamedSection.prepare(self)
1079 AbstractSection.prepare(self)
1080 AbstractSection.parse_optionals(self, self.section, true)
1083 function NamedSection.parse(self, novld)
1084 local s = self.section
1085 local active = self:cfgvalue(s)
1087 if self.addremove then
1088 local path = self.config.."."..s
1089 if active then -- Remove the section
1090 if self.map:formvalue("cbi.rns."..path) and self:remove(s) then
1094 else -- Create and apply default values
1095 if self.map:formvalue("cbi.cns."..path) then
1103 AbstractSection.parse_dynamic(self, s)
1104 if self.map:submitstate() then
1107 AbstractSection.parse_optionals(self, s)
1109 if self.changed then
1117 TypedSection - A (set of) configuration section(s) defined by the type
1118 addremove: Defines whether the user can add/remove sections of this type
1119 anonymous: Allow creating anonymous sections
1120 validate: a validation function returning nil if the section is invalid
1122 TypedSection = class(AbstractSection)
1124 function TypedSection.__init__(self, map, type, ...)
1125 AbstractSection.__init__(self, map, type, ...)
1127 self.template = "cbi/tsection"
1129 self.anonymous = false
1132 function TypedSection.prepare(self)
1133 AbstractSection.prepare(self)
1136 for i, s in ipairs(self:cfgsections()) do
1137 AbstractSection.parse_optionals(self, s, true)
1141 -- Return all matching UCI sections for this TypedSection
1142 function TypedSection.cfgsections(self)
1144 self.map.uci:foreach(self.map.config, self.sectiontype,
1146 if self:checkscope(section[".name"]) then
1147 table.insert(sections, section[".name"])
1154 -- Limits scope to sections that have certain option => value pairs
1155 function TypedSection.depends(self, option, value)
1156 table.insert(self.deps, {option=option, value=value})
1159 function TypedSection.parse(self, novld)
1160 if self.addremove then
1162 local crval = REMOVE_PREFIX .. self.config
1163 local name = self.map:formvaluetable(crval)
1164 for k,v in pairs(name) do
1165 if k:sub(-2) == ".x" then
1166 k = k:sub(1, #k - 2)
1168 if self:cfgvalue(k) and self:checkscope(k) then
1175 for i, k in ipairs(self:cfgsections()) do
1176 AbstractSection.parse_dynamic(self, k)
1177 if self.map:submitstate() then
1178 Node.parse(self, k, novld)
1180 AbstractSection.parse_optionals(self, k)
1183 if self.addremove then
1186 local crval = CREATE_PREFIX .. self.config .. "." .. self.sectiontype
1187 local origin, name = next(self.map:formvaluetable(crval))
1188 if self.anonymous then
1190 created = self:create(nil, origin)
1194 -- Ignore if it already exists
1195 if self:cfgvalue(name) then
1199 name = self:checkscope(name)
1202 self.err_invalid = true
1205 if name and #name > 0 then
1206 created = self:create(name, origin) and name
1208 self.invalid_cts = true
1215 AbstractSection.parse_optionals(self, created)
1219 if self.sortable then
1220 local stval = RESORT_PREFIX .. self.config .. "." .. self.sectiontype
1221 local order = self.map:formvalue(stval)
1222 if order and #order > 0 then
1225 for sid in util.imatch(order) do
1226 self.map.uci:reorder(self.config, sid, num)
1229 self.changed = (num > 0)
1233 if created or self.changed then
1238 -- Verifies scope of sections
1239 function TypedSection.checkscope(self, section)
1240 -- Check if we are not excluded
1241 if self.filter and not self:filter(section) then
1245 -- Check if at least one dependency is met
1246 if #self.deps > 0 and self:cfgvalue(section) then
1249 for k, v in ipairs(self.deps) do
1250 if self:cfgvalue(section)[v.option] == v.value then
1260 return self:validate(section)
1264 -- Dummy validate function
1265 function TypedSection.validate(self, section)
1271 AbstractValue - An abstract Value Type
1272 null: Value can be empty
1273 valid: A function returning the value if it is valid otherwise nil
1274 depends: A table of option => value pairs of which one must be true
1275 default: The default value
1276 size: The size of the input fields
1277 rmempty: Unset value if empty
1278 optional: This value is optional (see AbstractSection.optionals)
1280 AbstractValue = class(Node)
1282 function AbstractValue.__init__(self, map, section, option, ...)
1283 Node.__init__(self, ...)
1284 self.section = section
1285 self.option = option
1287 self.config = map.config
1288 self.tag_invalid = {}
1289 self.tag_missing = {}
1290 self.tag_reqerror = {}
1294 --self.cast = "string"
1296 self.track_missing = false
1300 self.optional = false
1303 function AbstractValue.prepare(self)
1304 self.cast = self.cast or "string"
1307 -- Add a dependencie to another section field
1308 function AbstractValue.depends(self, field, value)
1310 if type(field) == "string" then
1317 table.insert(self.deps, {deps=deps, add=""})
1320 -- Generates the unique CBID
1321 function AbstractValue.cbid(self, section)
1322 return "cbid."..self.map.config.."."..section.."."..self.option
1325 -- Return whether this object should be created
1326 function AbstractValue.formcreated(self, section)
1327 local key = "cbi.opt."..self.config.."."..section
1328 return (self.map:formvalue(key) == self.option)
1331 -- Returns the formvalue for this object
1332 function AbstractValue.formvalue(self, section)
1333 return self.map:formvalue(self:cbid(section))
1336 function AbstractValue.additional(self, value)
1337 self.optional = value
1340 function AbstractValue.mandatory(self, value)
1341 self.rmempty = not value
1344 function AbstractValue.add_error(self, section, type, msg)
1345 self.error = self.error or { }
1346 self.error[section] = msg or type
1348 self.section.error = self.section.error or { }
1349 self.section.error[section] = self.section.error[section] or { }
1350 table.insert(self.section.error[section], msg or type)
1352 if type == "invalid" then
1353 self.tag_invalid[section] = true
1354 elseif type == "missing" then
1355 self.tag_missing[section] = true
1358 self.tag_error[section] = true
1359 self.map.save = false
1362 function AbstractValue.parse(self, section, novld)
1363 local fvalue = self:formvalue(section)
1364 local cvalue = self:cfgvalue(section)
1366 -- If favlue and cvalue are both tables and have the same content
1367 -- make them identical
1368 if type(fvalue) == "table" and type(cvalue) == "table" then
1369 local equal = #fvalue == #cvalue
1372 if cvalue[i] ~= fvalue[i] then
1382 if fvalue and #fvalue > 0 then -- If we have a form value, write it to UCI
1384 fvalue, val_err = self:validate(fvalue, section)
1385 fvalue = self:transform(fvalue)
1387 if not fvalue and not novld then
1388 self:add_error(section, "invalid", val_err)
1391 if fvalue and (self.forcewrite or not (fvalue == cvalue)) then
1392 if self:write(section, fvalue) then
1394 self.section.changed = true
1395 --luci.util.append(self.map.events, self.events)
1398 else -- Unset the UCI or error
1399 if self.rmempty or self.optional then
1400 if self:remove(section) then
1402 self.section.changed = true
1403 --luci.util.append(self.map.events, self.events)
1405 elseif cvalue ~= fvalue and not novld then
1406 -- trigger validator with nil value to get custom user error msg.
1407 local _, val_err = self:validate(nil, section)
1408 self:add_error(section, "missing", val_err)
1413 -- Render if this value exists or if it is mandatory
1414 function AbstractValue.render(self, s, scope)
1415 if not self.optional or self.section:has_tabs() or self:cfgvalue(s) or self:formcreated(s) then
1418 scope.cbid = self:cbid(s)
1419 Node.render(self, scope)
1423 -- Return the UCI value of this object
1424 function AbstractValue.cfgvalue(self, section)
1426 if self.tag_error[section] then
1427 value = self:formvalue(section)
1429 value = self.map:get(section, self.option)
1434 elseif not self.cast or self.cast == type(value) then
1436 elseif self.cast == "string" then
1437 if type(value) == "table" then
1440 elseif self.cast == "table" then
1445 -- Validate the form value
1446 function AbstractValue.validate(self, value)
1447 if self.datatype and value then
1448 if type(value) == "table" then
1450 for _, v in ipairs(value) do
1451 if v and #v > 0 and not verify_datatype(self.datatype, v) then
1456 if not verify_datatype(self.datatype, value) then
1465 AbstractValue.transform = AbstractValue.validate
1469 function AbstractValue.write(self, section, value)
1470 return self.map:set(section, self.option, value)
1474 function AbstractValue.remove(self, section)
1475 return self.map:del(section, self.option)
1482 Value - A one-line value
1483 maxlength: The maximum length
1485 Value = class(AbstractValue)
1487 function Value.__init__(self, ...)
1488 AbstractValue.__init__(self, ...)
1489 self.template = "cbi/value"
1495 function Value.reset_values(self)
1500 function Value.value(self, key, val)
1502 table.insert(self.keylist, tostring(key))
1503 table.insert(self.vallist, tostring(val))
1506 function Value.parse(self, section, novld)
1507 if self.readonly then return end
1508 AbstractValue.parse(self, section, novld)
1511 -- DummyValue - This does nothing except being there
1512 DummyValue = class(AbstractValue)
1514 function DummyValue.__init__(self, ...)
1515 AbstractValue.__init__(self, ...)
1516 self.template = "cbi/dvalue"
1520 function DummyValue.cfgvalue(self, section)
1523 if type(self.value) == "function" then
1524 value = self:value(section)
1529 value = AbstractValue.cfgvalue(self, section)
1534 function DummyValue.parse(self)
1540 Flag - A flag being enabled or disabled
1542 Flag = class(AbstractValue)
1544 function Flag.__init__(self, ...)
1545 AbstractValue.__init__(self, ...)
1546 self.template = "cbi/fvalue"
1550 self.default = self.disabled
1553 -- A flag can only have two states: set or unset
1554 function Flag.parse(self, section, novld)
1555 local fexists = self.map:formvalue(
1556 FEXIST_PREFIX .. self.config .. "." .. section .. "." .. self.option)
1559 local fvalue = self:formvalue(section) and self.enabled or self.disabled
1560 local cvalue = self:cfgvalue(section)
1562 fvalue, val_err = self:validate(fvalue, section)
1565 self:add_error(section, "invalid", val_err)
1569 if fvalue == self.default and (self.optional or self.rmempty) then
1570 self:remove(section)
1572 self:write(section, fvalue)
1574 if (fvalue ~= cvalue) then self.section.changed = true end
1576 self:remove(section)
1577 self.section.changed = true
1581 function Flag.cfgvalue(self, section)
1582 return AbstractValue.cfgvalue(self, section) or self.default
1584 function Flag.validate(self, value)
1589 ListValue - A one-line value predefined in a list
1590 widget: The widget that will be used (select, radio)
1592 ListValue = class(AbstractValue)
1594 function ListValue.__init__(self, ...)
1595 AbstractValue.__init__(self, ...)
1596 self.template = "cbi/lvalue"
1601 self.widget = "select"
1604 function ListValue.reset_values(self)
1609 function ListValue.value(self, key, val, ...)
1610 if luci.util.contains(self.keylist, key) then
1615 table.insert(self.keylist, tostring(key))
1616 table.insert(self.vallist, tostring(val))
1618 for i, deps in ipairs({...}) do
1619 self.subdeps[#self.subdeps + 1] = {add = "-"..key, deps=deps}
1623 function ListValue.validate(self, val)
1624 if luci.util.contains(self.keylist, val) then
1634 MultiValue - Multiple delimited values
1635 widget: The widget that will be used (select, checkbox)
1636 delimiter: The delimiter that will separate the values (default: " ")
1638 MultiValue = class(AbstractValue)
1640 function MultiValue.__init__(self, ...)
1641 AbstractValue.__init__(self, ...)
1642 self.template = "cbi/mvalue"
1647 self.widget = "checkbox"
1648 self.delimiter = " "
1651 function MultiValue.render(self, ...)
1652 if self.widget == "select" and not self.size then
1653 self.size = #self.vallist
1656 AbstractValue.render(self, ...)
1659 function MultiValue.reset_values(self)
1664 function MultiValue.value(self, key, val)
1665 if luci.util.contains(self.keylist, key) then
1670 table.insert(self.keylist, tostring(key))
1671 table.insert(self.vallist, tostring(val))
1674 function MultiValue.valuelist(self, section)
1675 local val = self:cfgvalue(section)
1677 if not(type(val) == "string") then
1681 return luci.util.split(val, self.delimiter)
1684 function MultiValue.validate(self, val)
1685 val = (type(val) == "table") and val or {val}
1689 for i, value in ipairs(val) do
1690 if luci.util.contains(self.keylist, value) then
1691 result = result and (result .. self.delimiter .. value) or value
1699 StaticList = class(MultiValue)
1701 function StaticList.__init__(self, ...)
1702 MultiValue.__init__(self, ...)
1704 self.valuelist = self.cfgvalue
1706 if not self.override_scheme
1707 and self.map:get_scheme(self.section.sectiontype, self.option) then
1708 local vs = self.map:get_scheme(self.section.sectiontype, self.option)
1709 if self.value and vs.values and not self.override_values then
1710 for k, v in pairs(vs.values) do
1717 function StaticList.validate(self, value)
1718 value = (type(value) == "table") and value or {value}
1721 for i, v in ipairs(value) do
1722 if luci.util.contains(self.keylist, v) then
1723 table.insert(valid, v)
1730 DynamicList = class(AbstractValue)
1732 function DynamicList.__init__(self, ...)
1733 AbstractValue.__init__(self, ...)
1734 self.template = "cbi/dynlist"
1740 function DynamicList.reset_values(self)
1745 function DynamicList.value(self, key, val)
1747 table.insert(self.keylist, tostring(key))
1748 table.insert(self.vallist, tostring(val))
1751 function DynamicList.write(self, section, value)
1754 if type(value) == "table" then
1756 for _, x in ipairs(value) do
1757 if x and #x > 0 then
1765 if self.cast == "string" then
1766 value = table.concat(t, " ")
1771 return AbstractValue.write(self, section, value)
1774 function DynamicList.cfgvalue(self, section)
1775 local value = AbstractValue.cfgvalue(self, section)
1777 if type(value) == "string" then
1780 for x in value:gmatch("%S+") do
1791 function DynamicList.formvalue(self, section)
1792 local value = AbstractValue.formvalue(self, section)
1794 if type(value) == "string" then
1795 if self.cast == "string" then
1798 for x in value:gmatch("%S+") do
1812 TextValue - A multi-line value
1815 TextValue = class(AbstractValue)
1817 function TextValue.__init__(self, ...)
1818 AbstractValue.__init__(self, ...)
1819 self.template = "cbi/tvalue"
1825 Button = class(AbstractValue)
1827 function Button.__init__(self, ...)
1828 AbstractValue.__init__(self, ...)
1829 self.template = "cbi/button"
1830 self.inputstyle = nil
1832 self.unsafeupload = false
1836 FileUpload = class(AbstractValue)
1838 function FileUpload.__init__(self, ...)
1839 AbstractValue.__init__(self, ...)
1840 self.template = "cbi/upload"
1841 if not self.map.upload_fields then
1842 self.map.upload_fields = { self }
1844 self.map.upload_fields[#self.map.upload_fields+1] = self
1848 function FileUpload.formcreated(self, section)
1849 if self.unsafeupload then
1850 return AbstractValue.formcreated(self, section) or
1851 self.map:formvalue("cbi.rlf."..section.."."..self.option) or
1852 self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") or
1853 self.map:formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox")
1855 return AbstractValue.formcreated(self, section) or
1856 self.map:formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox")
1860 function FileUpload.cfgvalue(self, section)
1861 local val = AbstractValue.cfgvalue(self, section)
1862 if val and fs.access(val) then
1868 -- If we have a new value, use it
1869 -- otherwise use old value
1870 -- deletion should be managed by a separate button object
1871 -- unless self.unsafeupload is set in which case if the user
1872 -- choose to remove the old file we do so.
1873 -- Also, allow to specify (via textbox) a file already on router
1874 function FileUpload.formvalue(self, section)
1875 local val = AbstractValue.formvalue(self, section)
1877 if self.unsafeupload then
1878 if not self.map:formvalue("cbi.rlf."..section.."."..self.option) and
1879 not self.map:formvalue("cbi.rlf."..section.."."..self.option..".x")
1886 elseif val ~= "" then
1890 val = luci.http.formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox")
1894 if not self.unsafeupload then
1896 val = self.map:formvalue("cbi.rlf."..section.."."..self.option)
1902 function FileUpload.remove(self, section)
1903 if self.unsafeupload then
1904 local val = AbstractValue.formvalue(self, section)
1905 if val and fs.access(val) then fs.unlink(val) end
1906 return AbstractValue.remove(self, section)
1912 FileBrowser = class(AbstractValue)
1914 function FileBrowser.__init__(self, ...)
1915 AbstractValue.__init__(self, ...)
1916 self.template = "cbi/browser"