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, ...)
389 self:_run_hooks("on_save", "on_before_save")
390 for i, config in ipairs(self.parsechain) do
391 self.uci:save(config)
393 self:_run_hooks("on_after_save")
394 if (not self.proceed and self.flow.autoapply) or luci.http.formvalue("cbi.apply") then
395 self:_run_hooks("on_before_commit")
396 for i, config in ipairs(self.parsechain) do
397 self.uci:commit(config)
399 -- Refresh data because commit changes section names
400 self.uci:load(config)
402 self:_run_hooks("on_commit", "on_after_commit", "on_before_apply")
403 if self.apply_on_parse then
404 self.uci:apply(self.parsechain)
405 self:_run_hooks("on_apply", "on_after_apply")
407 -- This is evaluated by the dispatcher and delegated to the
408 -- template which in turn fires XHR to perform the actual
410 self.apply_needed = true
414 Node.parse(self, true)
416 for i, config in ipairs(self.parsechain) do
417 self.uci:unload(config)
419 if type(self.commit_handler) == "function" then
420 self:commit_handler(self:submitstate())
424 if not self.save then
425 self.state = FORM_INVALID
426 elseif self.proceed then
427 self.state = FORM_PROCEED
428 elseif self.changed then
429 self.state = FORM_CHANGED
431 self.state = FORM_VALID
434 return self:state_handler(self.state)
437 function Map.render(self, ...)
438 self:_run_hooks("on_init")
439 Node.render(self, ...)
442 -- Creates a child section
443 function Map.section(self, class, ...)
444 if instanceof(class, AbstractSection) then
445 local obj = class(self, ...)
449 error("class must be a descendent of AbstractSection")
454 function Map.add(self, sectiontype)
455 return self.uci:add(self.config, sectiontype)
459 function Map.set(self, section, option, value)
460 if type(value) ~= "table" or #value > 0 then
462 return self.uci:set(self.config, section, option, value)
464 return self.uci:set(self.config, section, value)
467 return Map.del(self, section, option)
472 function Map.del(self, section, option)
474 return self.uci:delete(self.config, section, option)
476 return self.uci:delete(self.config, section)
481 function Map.get(self, section, option)
483 return self.uci:get_all(self.config)
485 return self.uci:get(self.config, section, option)
487 return self.uci:get_all(self.config, section)
494 Compound = class(Node)
496 function Compound.__init__(self, ...)
498 self.template = "cbi/compound"
499 self.children = {...}
502 function Compound.populate_delegator(self, delegator)
503 for _, v in ipairs(self.children) do
504 v.delegator = delegator
508 function Compound.parse(self, ...)
509 local cstate, state = 0
511 for k, child in ipairs(self.children) do
512 cstate = child:parse(...)
513 state = (not state or cstate < state) and cstate or state
521 Delegator - Node controller
523 Delegator = class(Node)
524 function Delegator.__init__(self, ...)
525 Node.__init__(self, ...)
527 self.defaultpath = {}
528 self.pageaction = false
529 self.readinput = true
530 self.allow_reset = false
531 self.allow_cancel = false
532 self.allow_back = false
533 self.allow_finish = false
534 self.template = "cbi/delegator"
537 function Delegator.set(self, name, node)
538 assert(not self.nodes[name], "Duplicate entry")
540 self.nodes[name] = node
543 function Delegator.add(self, name, node)
544 node = self:set(name, node)
545 self.defaultpath[#self.defaultpath+1] = name
548 function Delegator.insert_after(self, name, after)
549 local n = #self.chain + 1
550 for k, v in ipairs(self.chain) do
556 table.insert(self.chain, n, name)
559 function Delegator.set_route(self, ...)
560 local n, chain, route = 0, self.chain, {...}
562 if chain[i] == self.current then
571 for i = n + 1, #chain do
576 function Delegator.get(self, name)
577 local node = self.nodes[name]
579 if type(node) == "string" then
580 node = load(node, name)
583 if type(node) == "table" and getmetatable(node) == nil then
584 node = Compound(unpack(node))
590 function Delegator.parse(self, ...)
591 if self.allow_cancel and Map.formvalue(self, "cbi.cancel") then
592 if self:_run_hooks("on_cancel") then
597 if not Map.formvalue(self, "cbi.delg.current") then
598 self:_run_hooks("on_init")
602 self.chain = self.chain or self:get_chain()
603 self.current = self.current or self:get_active()
604 self.active = self.active or self:get(self.current)
605 assert(self.active, "Invalid state")
607 local stat = FORM_DONE
608 if type(self.active) ~= "function" then
609 self.active:populate_delegator(self)
610 stat = self.active:parse()
615 if stat > FORM_PROCEED then
616 if Map.formvalue(self, "cbi.delg.back") then
617 newcurrent = self:get_prev(self.current)
619 newcurrent = self:get_next(self.current)
621 elseif stat < FORM_PROCEED then
626 if not Map.formvalue(self, "cbi.submit") then
628 elseif stat > FORM_PROCEED
629 and (not newcurrent or not self:get(newcurrent)) then
630 return self:_run_hook("on_done") or FORM_DONE
632 self.current = newcurrent or self.current
633 self.active = self:get(self.current)
634 if type(self.active) ~= "function" then
635 self.active:populate_delegator(self)
636 local stat = self.active:parse(false)
637 if stat == FORM_SKIP then
638 return self:parse(...)
643 return self:parse(...)
648 function Delegator.get_next(self, state)
649 for k, v in ipairs(self.chain) do
651 return self.chain[k+1]
656 function Delegator.get_prev(self, state)
657 for k, v in ipairs(self.chain) do
659 return self.chain[k-1]
664 function Delegator.get_chain(self)
665 local x = Map.formvalue(self, "cbi.delg.path") or self.defaultpath
666 return type(x) == "table" and x or {x}
669 function Delegator.get_active(self)
670 return Map.formvalue(self, "cbi.delg.current") or self.chain[1]
678 Page.__init__ = Node.__init__
679 Page.parse = function() end
683 SimpleForm - A Simple non-UCI form
685 SimpleForm = class(Node)
687 function SimpleForm.__init__(self, config, title, description, data)
688 Node.__init__(self, title, description)
690 self.data = data or {}
691 self.template = "cbi/simpleform"
693 self.pageaction = false
694 self.readinput = true
697 SimpleForm.formvalue = Map.formvalue
698 SimpleForm.formvaluetable = Map.formvaluetable
700 function SimpleForm.parse(self, readinput, ...)
701 self.readinput = (readinput ~= false)
703 if self:formvalue("cbi.skip") then
707 if self:formvalue("cbi.cancel") and self:_run_hooks("on_cancel") then
711 if self:submitstate() then
712 Node.parse(self, 1, ...)
716 for k, j in ipairs(self.children) do
717 for i, v in ipairs(j.children) do
719 and (not v.tag_missing or not v.tag_missing[1])
720 and (not v.tag_invalid or not v.tag_invalid[1])
726 not self:submitstate() and FORM_NODATA
727 or valid and FORM_VALID
730 self.dorender = not self.handle
732 local nrender, nstate = self:handle(state, self.data)
733 self.dorender = self.dorender or (nrender ~= false)
734 state = nstate or state
739 function SimpleForm.render(self, ...)
740 if self.dorender then
741 Node.render(self, ...)
745 function SimpleForm.submitstate(self)
746 return self:formvalue("cbi.submit")
749 function SimpleForm.section(self, class, ...)
750 if instanceof(class, AbstractSection) then
751 local obj = class(self, ...)
755 error("class must be a descendent of AbstractSection")
759 -- Creates a child field
760 function SimpleForm.field(self, class, ...)
762 for k, v in ipairs(self.children) do
763 if instanceof(v, SimpleSection) then
769 section = self:section(SimpleSection)
772 if instanceof(class, AbstractValue) then
773 local obj = class(self, section, ...)
774 obj.track_missing = true
778 error("class must be a descendent of AbstractValue")
782 function SimpleForm.set(self, section, option, value)
783 self.data[option] = value
787 function SimpleForm.del(self, section, option)
788 self.data[option] = nil
792 function SimpleForm.get(self, section, option)
793 return self.data[option]
797 function SimpleForm.get_scheme()
802 Form = class(SimpleForm)
804 function Form.__init__(self, ...)
805 SimpleForm.__init__(self, ...)
813 AbstractSection = class(Node)
815 function AbstractSection.__init__(self, map, sectiontype, ...)
816 Node.__init__(self, ...)
817 self.sectiontype = sectiontype
819 self.config = map.config
824 self.tag_invalid = {}
825 self.tag_deperror = {}
829 self.addremove = false
833 -- Define a tab for the section
834 function AbstractSection.tab(self, tab, title, desc)
835 self.tabs = self.tabs or { }
836 self.tab_names = self.tab_names or { }
838 self.tab_names[#self.tab_names+1] = tab
846 -- Check whether the section has tabs
847 function AbstractSection.has_tabs(self)
848 return (self.tabs ~= nil) and (next(self.tabs) ~= nil)
851 -- Appends a new option
852 function AbstractSection.option(self, class, option, ...)
853 if instanceof(class, AbstractValue) then
854 local obj = class(self.map, self, option, ...)
856 self.fields[option] = obj
858 elseif class == true then
859 error("No valid class was given and autodetection failed.")
861 error("class must be a descendant of AbstractValue")
865 -- Appends a new tabbed option
866 function AbstractSection.taboption(self, tab, ...)
868 assert(tab and self.tabs and self.tabs[tab],
869 "Cannot assign option to not existing tab %q" % tostring(tab))
871 local l = self.tabs[tab].childs
872 local o = AbstractSection.option(self, ...)
874 if o then l[#l+1] = o end
879 -- Render a single tab
880 function AbstractSection.render_tab(self, tab, ...)
882 assert(tab and self.tabs and self.tabs[tab],
883 "Cannot render not existing tab %q" % tostring(tab))
886 for k, node in ipairs(self.tabs[tab].childs) do
887 node.last_child = (k == #self.tabs[tab].childs)
892 -- Parse optional options
893 function AbstractSection.parse_optionals(self, section, noparse)
894 if not self.optional then
898 self.optionals[section] = {}
902 field = self.map:formvalue("cbi.opt."..self.config.."."..section)
905 for k,v in ipairs(self.children) do
906 if v.optional and not v:cfgvalue(section) and not self:has_tabs() then
907 if field == v.option then
909 self.map.proceed = true
911 table.insert(self.optionals[section], v)
916 if field and #field > 0 and self.dynamic then
917 self:add_dynamic(field)
921 -- Add a dynamic option
922 function AbstractSection.add_dynamic(self, field, optional)
923 local o = self:option(Value, field, field)
924 o.optional = optional
927 -- Parse all dynamic options
928 function AbstractSection.parse_dynamic(self, section)
929 if not self.dynamic then
933 local arr = luci.util.clone(self:cfgvalue(section))
934 local form = self.map:formvaluetable("cbid."..self.config.."."..section)
935 for k, v in pairs(form) do
939 for key,val in pairs(arr) do
942 for i,c in ipairs(self.children) do
943 if c.option == key then
948 if create and key:sub(1, 1) ~= "." then
949 self.map.proceed = true
950 self:add_dynamic(key, true)
955 -- Returns the section's UCI table
956 function AbstractSection.cfgvalue(self, section)
957 return self.map:get(section)
961 function AbstractSection.push_events(self)
962 --luci.util.append(self.map.events, self.events)
963 self.map.changed = true
966 -- Removes the section
967 function AbstractSection.remove(self, section)
968 self.map.proceed = true
969 return self.map:del(section)
972 -- Creates the section
973 function AbstractSection.create(self, section)
977 stat = section:match("^[%w_]+$") and self.map:set(section, nil, self.sectiontype)
979 section = self.map:add(self.sectiontype)
984 for k,v in pairs(self.children) do
986 self.map:set(section, v.option, v.default)
990 for k,v in pairs(self.defaults) do
991 self.map:set(section, k, v)
995 self.map.proceed = true
1001 SimpleSection = class(AbstractSection)
1003 function SimpleSection.__init__(self, form, ...)
1004 AbstractSection.__init__(self, form, nil, ...)
1005 self.template = "cbi/nullsection"
1009 Table = class(AbstractSection)
1011 function Table.__init__(self, form, data, ...)
1012 local datasource = {}
1014 datasource.config = "table"
1015 self.data = data or {}
1017 datasource.formvalue = Map.formvalue
1018 datasource.formvaluetable = Map.formvaluetable
1019 datasource.readinput = true
1021 function datasource.get(self, section, option)
1022 return tself.data[section] and tself.data[section][option]
1025 function datasource.submitstate(self)
1026 return Map.formvalue(self, "cbi.submit")
1029 function datasource.del(...)
1033 function datasource.get_scheme()
1037 AbstractSection.__init__(self, datasource, "table", ...)
1038 self.template = "cbi/tblsection"
1039 self.rowcolors = true
1040 self.anonymous = true
1043 function Table.parse(self, readinput)
1044 self.map.readinput = (readinput ~= false)
1045 for i, k in ipairs(self:cfgsections()) do
1046 if self.map:submitstate() then
1052 function Table.cfgsections(self)
1055 for i, v in luci.util.kspairs(self.data) do
1056 table.insert(sections, i)
1062 function Table.update(self, data)
1069 NamedSection - A fixed configuration section defined by its name
1071 NamedSection = class(AbstractSection)
1073 function NamedSection.__init__(self, map, section, stype, ...)
1074 AbstractSection.__init__(self, map, stype, ...)
1077 self.addremove = false
1078 self.template = "cbi/nsection"
1079 self.section = section
1082 function NamedSection.prepare(self)
1083 AbstractSection.prepare(self)
1084 AbstractSection.parse_optionals(self, self.section, true)
1087 function NamedSection.parse(self, novld)
1088 local s = self.section
1089 local active = self:cfgvalue(s)
1091 if self.addremove then
1092 local path = self.config.."."..s
1093 if active then -- Remove the section
1094 if self.map:formvalue("cbi.rns."..path) and self:remove(s) then
1098 else -- Create and apply default values
1099 if self.map:formvalue("cbi.cns."..path) then
1107 AbstractSection.parse_dynamic(self, s)
1108 if self.map:submitstate() then
1111 AbstractSection.parse_optionals(self, s)
1113 if self.changed then
1121 TypedSection - A (set of) configuration section(s) defined by the type
1122 addremove: Defines whether the user can add/remove sections of this type
1123 anonymous: Allow creating anonymous sections
1124 validate: a validation function returning nil if the section is invalid
1126 TypedSection = class(AbstractSection)
1128 function TypedSection.__init__(self, map, type, ...)
1129 AbstractSection.__init__(self, map, type, ...)
1131 self.template = "cbi/tsection"
1133 self.anonymous = false
1136 function TypedSection.prepare(self)
1137 AbstractSection.prepare(self)
1140 for i, s in ipairs(self:cfgsections()) do
1141 AbstractSection.parse_optionals(self, s, true)
1145 -- Return all matching UCI sections for this TypedSection
1146 function TypedSection.cfgsections(self)
1148 self.map.uci:foreach(self.map.config, self.sectiontype,
1150 if self:checkscope(section[".name"]) then
1151 table.insert(sections, section[".name"])
1158 -- Limits scope to sections that have certain option => value pairs
1159 function TypedSection.depends(self, option, value)
1160 table.insert(self.deps, {option=option, value=value})
1163 function TypedSection.parse(self, novld)
1164 if self.addremove then
1166 local crval = REMOVE_PREFIX .. self.config
1167 local name = self.map:formvaluetable(crval)
1168 for k,v in pairs(name) do
1169 if k:sub(-2) == ".x" then
1170 k = k:sub(1, #k - 2)
1172 if self:cfgvalue(k) and self:checkscope(k) then
1179 for i, k in ipairs(self:cfgsections()) do
1180 AbstractSection.parse_dynamic(self, k)
1181 if self.map:submitstate() then
1182 Node.parse(self, k, novld)
1184 AbstractSection.parse_optionals(self, k)
1187 if self.addremove then
1190 local crval = CREATE_PREFIX .. self.config .. "." .. self.sectiontype
1191 local origin, name = next(self.map:formvaluetable(crval))
1192 if self.anonymous then
1194 created = self:create(nil, origin)
1198 -- Ignore if it already exists
1199 if self:cfgvalue(name) then
1203 name = self:checkscope(name)
1206 self.err_invalid = true
1209 if name and #name > 0 then
1210 created = self:create(name, origin) and name
1212 self.invalid_cts = true
1219 AbstractSection.parse_optionals(self, created)
1223 if self.sortable then
1224 local stval = RESORT_PREFIX .. self.config .. "." .. self.sectiontype
1225 local order = self.map:formvalue(stval)
1226 if order and #order > 0 then
1229 for sid in util.imatch(order) do
1230 self.map.uci:reorder(self.config, sid, num)
1233 self.changed = (num > 0)
1237 if created or self.changed then
1242 -- Verifies scope of sections
1243 function TypedSection.checkscope(self, section)
1244 -- Check if we are not excluded
1245 if self.filter and not self:filter(section) then
1249 -- Check if at least one dependency is met
1250 if #self.deps > 0 and self:cfgvalue(section) then
1253 for k, v in ipairs(self.deps) do
1254 if self:cfgvalue(section)[v.option] == v.value then
1264 return self:validate(section)
1268 -- Dummy validate function
1269 function TypedSection.validate(self, section)
1275 AbstractValue - An abstract Value Type
1276 null: Value can be empty
1277 valid: A function returning the value if it is valid otherwise nil
1278 depends: A table of option => value pairs of which one must be true
1279 default: The default value
1280 size: The size of the input fields
1281 rmempty: Unset value if empty
1282 optional: This value is optional (see AbstractSection.optionals)
1284 AbstractValue = class(Node)
1286 function AbstractValue.__init__(self, map, section, option, ...)
1287 Node.__init__(self, ...)
1288 self.section = section
1289 self.option = option
1291 self.config = map.config
1292 self.tag_invalid = {}
1293 self.tag_missing = {}
1294 self.tag_reqerror = {}
1298 --self.cast = "string"
1300 self.track_missing = false
1304 self.optional = false
1307 function AbstractValue.prepare(self)
1308 self.cast = self.cast or "string"
1311 -- Add a dependencie to another section field
1312 function AbstractValue.depends(self, field, value)
1314 if type(field) == "string" then
1321 table.insert(self.deps, {deps=deps, add=""})
1324 -- Generates the unique CBID
1325 function AbstractValue.cbid(self, section)
1326 return "cbid."..self.map.config.."."..section.."."..self.option
1329 -- Return whether this object should be created
1330 function AbstractValue.formcreated(self, section)
1331 local key = "cbi.opt."..self.config.."."..section
1332 return (self.map:formvalue(key) == self.option)
1335 -- Returns the formvalue for this object
1336 function AbstractValue.formvalue(self, section)
1337 return self.map:formvalue(self:cbid(section))
1340 function AbstractValue.additional(self, value)
1341 self.optional = value
1344 function AbstractValue.mandatory(self, value)
1345 self.rmempty = not value
1348 function AbstractValue.add_error(self, section, type, msg)
1349 self.error = self.error or { }
1350 self.error[section] = msg or type
1352 self.section.error = self.section.error or { }
1353 self.section.error[section] = self.section.error[section] or { }
1354 table.insert(self.section.error[section], msg or type)
1356 if type == "invalid" then
1357 self.tag_invalid[section] = true
1358 elseif type == "missing" then
1359 self.tag_missing[section] = true
1362 self.tag_error[section] = true
1363 self.map.save = false
1366 function AbstractValue.parse(self, section, novld)
1367 local fvalue = self:formvalue(section)
1368 local cvalue = self:cfgvalue(section)
1370 -- If favlue and cvalue are both tables and have the same content
1371 -- make them identical
1372 if type(fvalue) == "table" and type(cvalue) == "table" then
1373 local equal = #fvalue == #cvalue
1376 if cvalue[i] ~= fvalue[i] then
1386 if fvalue and #fvalue > 0 then -- If we have a form value, write it to UCI
1388 fvalue, val_err = self:validate(fvalue, section)
1389 fvalue = self:transform(fvalue)
1391 if not fvalue and not novld then
1392 self:add_error(section, "invalid", val_err)
1395 if fvalue and (self.forcewrite or not (fvalue == cvalue)) then
1396 if self:write(section, fvalue) then
1398 self.section.changed = true
1399 --luci.util.append(self.map.events, self.events)
1402 else -- Unset the UCI or error
1403 if self.rmempty or self.optional then
1404 if self:remove(section) then
1406 self.section.changed = true
1407 --luci.util.append(self.map.events, self.events)
1409 elseif cvalue ~= fvalue and not novld then
1410 -- trigger validator with nil value to get custom user error msg.
1411 local _, val_err = self:validate(nil, section)
1412 self:add_error(section, "missing", val_err)
1417 -- Render if this value exists or if it is mandatory
1418 function AbstractValue.render(self, s, scope)
1419 if not self.optional or self.section:has_tabs() or self:cfgvalue(s) or self:formcreated(s) then
1422 scope.cbid = self:cbid(s)
1423 Node.render(self, scope)
1427 -- Return the UCI value of this object
1428 function AbstractValue.cfgvalue(self, section)
1430 if self.tag_error[section] then
1431 value = self:formvalue(section)
1433 value = self.map:get(section, self.option)
1438 elseif not self.cast or self.cast == type(value) then
1440 elseif self.cast == "string" then
1441 if type(value) == "table" then
1444 elseif self.cast == "table" then
1449 -- Validate the form value
1450 function AbstractValue.validate(self, value)
1451 if self.datatype and value then
1452 if type(value) == "table" then
1454 for _, v in ipairs(value) do
1455 if v and #v > 0 and not verify_datatype(self.datatype, v) then
1460 if not verify_datatype(self.datatype, value) then
1469 AbstractValue.transform = AbstractValue.validate
1473 function AbstractValue.write(self, section, value)
1474 return self.map:set(section, self.option, value)
1478 function AbstractValue.remove(self, section)
1479 return self.map:del(section, self.option)
1486 Value - A one-line value
1487 maxlength: The maximum length
1489 Value = class(AbstractValue)
1491 function Value.__init__(self, ...)
1492 AbstractValue.__init__(self, ...)
1493 self.template = "cbi/value"
1499 function Value.reset_values(self)
1504 function Value.value(self, key, val)
1506 table.insert(self.keylist, tostring(key))
1507 table.insert(self.vallist, tostring(val))
1510 function Value.parse(self, section, novld)
1511 if self.readonly then return end
1512 AbstractValue.parse(self, section, novld)
1515 -- DummyValue - This does nothing except being there
1516 DummyValue = class(AbstractValue)
1518 function DummyValue.__init__(self, ...)
1519 AbstractValue.__init__(self, ...)
1520 self.template = "cbi/dvalue"
1524 function DummyValue.cfgvalue(self, section)
1527 if type(self.value) == "function" then
1528 value = self:value(section)
1533 value = AbstractValue.cfgvalue(self, section)
1538 function DummyValue.parse(self)
1544 Flag - A flag being enabled or disabled
1546 Flag = class(AbstractValue)
1548 function Flag.__init__(self, ...)
1549 AbstractValue.__init__(self, ...)
1550 self.template = "cbi/fvalue"
1554 self.default = self.disabled
1557 -- A flag can only have two states: set or unset
1558 function Flag.parse(self, section, novld)
1559 local fexists = self.map:formvalue(
1560 FEXIST_PREFIX .. self.config .. "." .. section .. "." .. self.option)
1563 local fvalue = self:formvalue(section) and self.enabled or self.disabled
1564 local cvalue = self:cfgvalue(section)
1566 fvalue, val_err = self:validate(fvalue, section)
1569 self:add_error(section, "invalid", val_err)
1573 if fvalue == self.default and (self.optional or self.rmempty) then
1574 self:remove(section)
1576 self:write(section, fvalue)
1578 if (fvalue ~= cvalue) then self.section.changed = true end
1580 self:remove(section)
1581 self.section.changed = true
1585 function Flag.cfgvalue(self, section)
1586 return AbstractValue.cfgvalue(self, section) or self.default
1588 function Flag.validate(self, value)
1593 ListValue - A one-line value predefined in a list
1594 widget: The widget that will be used (select, radio)
1596 ListValue = class(AbstractValue)
1598 function ListValue.__init__(self, ...)
1599 AbstractValue.__init__(self, ...)
1600 self.template = "cbi/lvalue"
1605 self.widget = "select"
1608 function ListValue.reset_values(self)
1613 function ListValue.value(self, key, val, ...)
1614 if luci.util.contains(self.keylist, key) then
1619 table.insert(self.keylist, tostring(key))
1620 table.insert(self.vallist, tostring(val))
1622 for i, deps in ipairs({...}) do
1623 self.subdeps[#self.subdeps + 1] = {add = "-"..key, deps=deps}
1627 function ListValue.validate(self, val)
1628 if luci.util.contains(self.keylist, val) then
1638 MultiValue - Multiple delimited values
1639 widget: The widget that will be used (select, checkbox)
1640 delimiter: The delimiter that will separate the values (default: " ")
1642 MultiValue = class(AbstractValue)
1644 function MultiValue.__init__(self, ...)
1645 AbstractValue.__init__(self, ...)
1646 self.template = "cbi/mvalue"
1651 self.widget = "checkbox"
1652 self.delimiter = " "
1655 function MultiValue.render(self, ...)
1656 if self.widget == "select" and not self.size then
1657 self.size = #self.vallist
1660 AbstractValue.render(self, ...)
1663 function MultiValue.reset_values(self)
1668 function MultiValue.value(self, key, val)
1669 if luci.util.contains(self.keylist, key) then
1674 table.insert(self.keylist, tostring(key))
1675 table.insert(self.vallist, tostring(val))
1678 function MultiValue.valuelist(self, section)
1679 local val = self:cfgvalue(section)
1681 if not(type(val) == "string") then
1685 return luci.util.split(val, self.delimiter)
1688 function MultiValue.validate(self, val)
1689 val = (type(val) == "table") and val or {val}
1693 for i, value in ipairs(val) do
1694 if luci.util.contains(self.keylist, value) then
1695 result = result and (result .. self.delimiter .. value) or value
1703 StaticList = class(MultiValue)
1705 function StaticList.__init__(self, ...)
1706 MultiValue.__init__(self, ...)
1708 self.valuelist = self.cfgvalue
1710 if not self.override_scheme
1711 and self.map:get_scheme(self.section.sectiontype, self.option) then
1712 local vs = self.map:get_scheme(self.section.sectiontype, self.option)
1713 if self.value and vs.values and not self.override_values then
1714 for k, v in pairs(vs.values) do
1721 function StaticList.validate(self, value)
1722 value = (type(value) == "table") and value or {value}
1725 for i, v in ipairs(value) do
1726 if luci.util.contains(self.keylist, v) then
1727 table.insert(valid, v)
1734 DynamicList = class(AbstractValue)
1736 function DynamicList.__init__(self, ...)
1737 AbstractValue.__init__(self, ...)
1738 self.template = "cbi/dynlist"
1744 function DynamicList.reset_values(self)
1749 function DynamicList.value(self, key, val)
1751 table.insert(self.keylist, tostring(key))
1752 table.insert(self.vallist, tostring(val))
1755 function DynamicList.write(self, section, value)
1758 if type(value) == "table" then
1760 for _, x in ipairs(value) do
1761 if x and #x > 0 then
1769 if self.cast == "string" then
1770 value = table.concat(t, " ")
1775 return AbstractValue.write(self, section, value)
1778 function DynamicList.cfgvalue(self, section)
1779 local value = AbstractValue.cfgvalue(self, section)
1781 if type(value) == "string" then
1784 for x in value:gmatch("%S+") do
1795 function DynamicList.formvalue(self, section)
1796 local value = AbstractValue.formvalue(self, section)
1798 if type(value) == "string" then
1799 if self.cast == "string" then
1802 for x in value:gmatch("%S+") do
1816 TextValue - A multi-line value
1819 TextValue = class(AbstractValue)
1821 function TextValue.__init__(self, ...)
1822 AbstractValue.__init__(self, ...)
1823 self.template = "cbi/tvalue"
1829 Button = class(AbstractValue)
1831 function Button.__init__(self, ...)
1832 AbstractValue.__init__(self, ...)
1833 self.template = "cbi/button"
1834 self.inputstyle = nil
1836 self.unsafeupload = false
1840 FileUpload = class(AbstractValue)
1842 function FileUpload.__init__(self, ...)
1843 AbstractValue.__init__(self, ...)
1844 self.template = "cbi/upload"
1845 if not self.map.upload_fields then
1846 self.map.upload_fields = { self }
1848 self.map.upload_fields[#self.map.upload_fields+1] = self
1852 function FileUpload.formcreated(self, section)
1853 if self.unsafeupload then
1854 return AbstractValue.formcreated(self, section) or
1855 self.map:formvalue("cbi.rlf."..section.."."..self.option) or
1856 self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") or
1857 self.map:formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox")
1859 return AbstractValue.formcreated(self, section) or
1860 self.map:formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox")
1864 function FileUpload.cfgvalue(self, section)
1865 local val = AbstractValue.cfgvalue(self, section)
1866 if val and fs.access(val) then
1872 -- If we have a new value, use it
1873 -- otherwise use old value
1874 -- deletion should be managed by a separate button object
1875 -- unless self.unsafeupload is set in which case if the user
1876 -- choose to remove the old file we do so.
1877 -- Also, allow to specify (via textbox) a file already on router
1878 function FileUpload.formvalue(self, section)
1879 local val = AbstractValue.formvalue(self, section)
1881 if self.unsafeupload then
1882 if not self.map:formvalue("cbi.rlf."..section.."."..self.option) and
1883 not self.map:formvalue("cbi.rlf."..section.."."..self.option..".x")
1890 elseif val ~= "" then
1894 val = luci.http.formvalue("cbid."..self.map.config.."."..section.."."..self.option..".textbox")
1898 if not self.unsafeupload then
1900 val = self.map:formvalue("cbi.rlf."..section.."."..self.option)
1906 function FileUpload.remove(self, section)
1907 if self.unsafeupload then
1908 local val = AbstractValue.formvalue(self, section)
1909 if val and fs.access(val) then fs.unlink(val) end
1910 return AbstractValue.remove(self, section)
1916 FileBrowser = class(AbstractValue)
1918 function FileBrowser.__init__(self, ...)
1919 AbstractValue.__init__(self, ...)
1920 self.template = "cbi/browser"