7fb11b12f21b7a6598a70b2ddf4e3c427b445e0a
[project/luci.git] / libs / uvl / luasrc / uvl.lua
1 --[[
2
3 UCI Validation Layer - Main Library
4 (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
5 (c) 2008 Steven Barth <steven@midlink.org>
6
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
10
11         http://www.apache.org/licenses/LICENSE-2.0
12
13 $Id$
14
15 ]]--
16
17
18 --- UVL - UCI Validation Layer
19 -- @class       module
20 -- @cstyle      instance
21
22 module( "luci.uvl", package.seeall )
23
24 require("luci.fs")
25 require("luci.util")
26 require("luci.model.uci")
27 require("luci.uvl.errors")
28 require("luci.uvl.datatypes")
29 require("luci.uvl.validation")
30 require("luci.uvl.dependencies")
31
32
33 TYPE_SCHEME   = 0x00
34 TYPE_CONFIG   = 0x01
35 TYPE_SECTION  = 0x02
36 TYPE_VARIABLE = 0x03
37 TYPE_OPTION   = 0x04
38 TYPE_ENUM     = 0x05
39
40 --- Boolean; default true;
41 -- treat sections found in config but not in scheme as error
42 STRICT_UNKNOWN_SECTIONS    = true
43
44 --- Boolean; default true;
45 -- treat options found in config but not in scheme as error
46 STRICT_UNKNOWN_OPTIONS     = true
47
48 --- Boolean; default true;
49 -- treat failed external validators as error
50 STRICT_EXTERNAL_VALIDATORS = true
51
52 --- Boolean; default true;
53 -- treat list values stored as options like errors
54 STRICT_LIST_TYPE           = true
55
56
57 local default_schemedir = "/lib/uci/schema"
58 local default_savedir = "/tmp/.uvl"
59 local ERR = luci.uvl.errors
60
61
62 --- Object constructor
63 -- @class                       function
64 -- @name                        UVL
65 -- @param schemedir     Path to the scheme directory (optional)
66 -- @return                      Instance object
67 UVL = luci.util.class()
68
69 function UVL.__init__( self, schemedir )
70         self.schemedir  = schemedir or default_schemedir
71         self.packages   = { }
72         self.beenthere  = { }
73         self.depseen    = { }
74         self.uci                = luci.model.uci
75         self.err                = luci.uvl.errors
76         self.dep                = luci.uvl.dependencies
77         self.datatypes  = luci.uvl.datatypes
78 end
79
80
81 --- Parse given scheme and return the scheme tree.
82 -- @param scheme        Name of the scheme to parse
83 -- @return                      Table containing the parsed scheme or nil on error
84 -- @return                      String containing the reason for errors (if any)
85 function UVL.get_scheme( self, scheme )
86         if not self.packages[scheme] then
87                 local ok, err = self:read_scheme( scheme )
88                 if not ok then
89                         return nil, err
90                 end
91         end
92         return self.packages[scheme], nil
93 end
94
95 --- Validate given configuration, section or option.
96 -- @param config        Name of the configuration to validate
97 -- @param section       Name of the section to validate (optional)
98 -- @param option        Name of the option to validate (optional)
99 -- @return                      Boolean indicating whether the given config validates
100 -- @return                      String containing the reason for errors (if any)
101 function UVL.validate( self, config, section, option )
102         if config and section and option then
103                 return self:validate_option( config, section, option )
104         elseif config and section then
105                 return self:validate_section( config, section )
106         elseif config then
107                 return self:validate_config( config )
108         end
109 end
110
111 --- Validate given configuration.
112 -- @param config        Name of the configuration to validate
113 -- @return                      Boolean indicating whether the given config validates
114 -- @return                      String containing the reason for errors (if any)
115 function UVL.validate_config( self, config, uci )
116
117         if not self.packages[config] then
118                 local ok, err = self:read_scheme(config)
119                 if not ok then
120                         return false, err
121                 end
122         end
123
124         local co = luci.uvl.config( self, uci or config, uci and config )
125         local sc = { }
126
127         self.beenthere = { }
128         self.depseen   = { }
129
130         if not co:config() then
131                 return false, co:errors()
132         end
133
134         local function _uci_foreach( type, func )
135                 for k, v in pairs(co:config()) do
136                         if v['.type'] == type then
137                                 sc[type] = sc[type] + 1
138                                 local ok, err = func( k, v )
139                                 if not ok then co:error(err) end
140                         end
141                 end
142         end
143
144         for k, v in pairs( self.packages[config].sections ) do
145                 sc[k] = 0
146                 _uci_foreach( k,
147                         function(s)
148                                 return self:_validate_section( co:section(s) )
149                         end
150                 )
151         end
152
153         if STRICT_UNKNOWN_SECTIONS then
154                 for k, v in pairs(co:config()) do
155                         local so = co:section(k)
156                         if not self.beenthere[so:cid()] then
157                                 co:error(ERR.SECT_UNKNOWN(so))
158                         end
159                 end
160         end
161
162         for _, k in ipairs(luci.util.keys(sc)) do
163                 local so = co:section(k)
164                 if so:scheme('required') and sc[k] == 0 then
165                         co:error(ERR.SECT_REQUIRED(so))
166                 elseif so:scheme('unique') and sc[k] > 1 then
167                         co:error(ERR.SECT_UNIQUE(so))
168                 end
169         end
170
171         return co:ok(), co:errors()
172 end
173
174 --- Validate given config section.
175 -- @param config        Name of the configuration to validate
176 -- @param section       Name of the section to validate
177 -- @return                      Boolean indicating whether the given config validates
178 -- @return                      String containing the reason for errors (if any)
179 function UVL.validate_section( self, config, section, uci )
180
181         if not self.packages[config] then
182                 local ok, err = self:read_scheme( config )
183                 if not ok then
184                         return false, err
185                 end
186         end
187
188         local co = luci.uvl.config( self, uci or config, uci and config )
189         local so = co:section( section )
190
191         self.beenthere = { }
192         self.depseen   = { }
193
194         if not co:config() then
195                 return false, co:errors()
196         end
197
198         if so:config() then
199                 return self:_validate_section( so )
200         else
201                 return false, ERR.SECT_NOTFOUND(so)
202         end
203 end
204
205 --- Validate given config option.
206 -- @param config        Name of the configuration to validate
207 -- @param section       Name of the section to validate
208 -- @param option        Name of the option to validate
209 -- @return                      Boolean indicating whether the given config validates
210 -- @return                      String containing the reason for errors (if any)
211 function UVL.validate_option( self, config, section, option, uci )
212
213         if not self.packages[config] then
214                 local ok, err = self:read_scheme( config )
215                 if not ok then
216                         return false, err
217                 end
218         end
219
220         local co = luci.uvl.config( self, uci or config, uci and config )
221         local so = co:section( section )
222         local oo = so:option( option )
223
224         if not co:config() then
225                 return false, co:errors()
226         end
227
228         if so:config() and oo:config() then
229                 return self:_validate_option( oo )
230         else
231                 return false, ERR.OPT_NOTFOUND(oo)
232         end
233 end
234
235
236 function UVL._validate_section( self, section )
237
238         self.beenthere[section:cid()] = true
239
240         if section:config() then
241                 if section:scheme('named') == true and
242                    section:config('.anonymous') == true
243                 then
244                         return false, ERR.SECT_NAMED(section)
245                 end
246
247                 for _, v in ipairs(section:variables()) do
248                         local ok, err = self:_validate_option( v )
249                         if not ok and (
250                                 v:scheme('required') or v:scheme('type') == "enum" or (
251                                         not err:is(ERR.ERR_DEP_NOTEQUAL) and
252                                         not err:is(ERR.ERR_DEP_NOVALUE)
253                                 )
254                         ) then
255                                 section:error(err)
256                         end
257                 end
258
259                 local ok, err = luci.uvl.dependencies.check( self, section )
260                 if not ok then
261                         section:error(err)
262                 end
263         else
264                 return false, ERR.SECT_NOTFOUND(section)
265         end
266
267         if STRICT_UNKNOWN_OPTIONS and not section:scheme('dynamic') then
268                 for k, v in pairs(section:config()) do
269                         local oo = section:option(k)
270                         if k:sub(1,1) ~= "." and not self.beenthere[oo:cid()] then
271                                 section:error(ERR.OPT_UNKNOWN(oo))
272                         end
273                 end
274         end
275
276         return section:ok(), section:errors()
277 end
278
279 function UVL._validate_option( self, option, nodeps )
280
281         self.beenthere[option:cid()] = true
282
283         if not option:scheme() and not option:parent():scheme('dynamic') then
284                 return false, option:error(ERR.OPT_UNKNOWN(option))
285
286         elseif option:scheme() then
287                 if option:scheme('required') and not option:value() then
288                         return false, option:error(ERR.OPT_REQUIRED(option))
289
290                 elseif option:value() then
291                         local val = option:value()
292
293                         if option:scheme('type') == "reference" or
294                            option:scheme('type') == "enum"
295                         then
296                                 if not option:scheme('values') or
297                                    not option:scheme('values')[val]
298                                 then
299                                         return false, option:error( ERR.OPT_BADVALUE(
300                                                 option, luci.util.serialize_data(
301                                                         luci.util.keys(option:scheme('values') or {})
302                                                 )
303                                         ) )
304                                 end
305                         elseif option:scheme('type') == "list" then
306                                 if type(val) ~= "table" and STRICT_LIST_TYPE then
307                                         return false, option:error(ERR.OPT_NOTLIST(option))
308                                 end
309                         elseif option:scheme('datatype') then
310                                 local dt = option:scheme('datatype')
311
312                                 if self.datatypes[dt] then
313                                         val = ( type(val) == "table" and val or { val } )
314                                         for i, v in ipairs(val) do
315                                                 if not self.datatypes[dt]( v ) then
316                                                         return false, option:error(
317                                                                 ERR.OPT_INVVALUE(option, dt)
318                                                         )
319                                                 end
320                                         end
321                                 else
322                                         return false, option:error(ERR.OPT_DATATYPE(option, dt))
323                                 end
324                         end
325                 end
326
327                 if not nodeps then
328                         local ok, err = luci.uvl.dependencies.check( self, option )
329                         if not ok then
330                                 option:error(err)
331                         end
332                 end
333
334                 local ok, err = luci.uvl.validation.check( self, option )
335                 if not ok and STRICT_EXTERNAL_VALIDATORS then
336                         return false, option:error(err)
337                 end
338         end
339
340         return option:ok(), option:errors()
341 end
342
343 --- Find all parts of given scheme and construct validation tree.
344 -- This is normally done on demand, so you don't have to call this function
345 -- by yourself.
346 -- @param scheme        Name of the scheme to parse
347 function UVL.read_scheme( self, scheme )
348
349         local so = luci.uvl.scheme( self, scheme )
350
351         local schemes = { }
352         local files = luci.fs.glob(self.schemedir .. '/*/' .. scheme)
353
354         if files then
355                 for i, file in ipairs( files ) do
356                         if not luci.fs.access(file) then
357                                 return so:error(ERR.SME_READ(so,file))
358                         end
359
360                         local uci = luci.model.uci.cursor( luci.fs.dirname(file), default_savedir )
361
362                         local sd, err = uci:get_all( luci.fs.basename(file) )
363
364                         if not sd then
365                                 return false, ERR.UCILOAD(so, err)
366                         end
367
368                         table.insert( schemes, sd )
369                 end
370
371                 return self:_read_scheme_parts( so, schemes )
372         else
373                 return false, so:error(ERR.SME_FIND(so, self.schemedir))
374         end
375 end
376
377 -- Process all given parts and construct validation tree
378 function UVL._read_scheme_parts( self, scheme, schemes )
379
380         -- helper function to check for required fields
381         local function _req( c, t, r )
382                 for i, v in ipairs(r) do
383                         if not t[v] then
384                                 return false, ERR.SME_REQFLD({c,t}, v)
385                         end
386                 end
387                 return true
388         end
389
390         -- helper function to validate references
391         local function _ref( c, t )
392                 local k, n
393                 if c == TYPE_SECTION then
394                         k = "package"
395                         n = 1
396                 elseif c == TYPE_VARIABLE then
397                         k = "section"
398                         n = 2
399                 elseif c == TYPE_ENUM then
400                         k = "variable"
401                         n = 3
402                 end
403
404                 local r = luci.util.split( t[k], "." )
405                 r[1] = ( #r[1] > 0 and r[1] or scheme:sid() )
406
407                 if #r ~= n then
408                         return false, ERR.SME_BADREF(scheme, k)
409                 end
410
411                 return r
412         end
413
414         -- helper function to read bools
415         local function _bool( v )
416                 return ( v == "true" or v == "yes" or v == "on" or v == "1" )
417         end
418
419
420         local ok, err
421
422         -- Step 0: get package meta information
423         for i, conf in ipairs( schemes ) do
424                 for k, v in pairs( conf ) do
425                         if v['.type'] == 'package' then
426                                 self.packages[scheme:sid()] =
427                                         self.packages[scheme:sid()] or {
428                                                 ["name"]      = scheme:sid();
429                                                 ["sections"]  = { };
430                                                 ["variables"] = { };
431                                         }
432
433                                 for k, v2 in pairs(v) do
434                                         if k == "title" or k == "description" then
435                                                 self.packages[scheme:sid()][k] = v2
436                                         end
437                                 end
438                         end
439                 end
440         end
441
442         -- Step 1: get all sections
443         for i, conf in ipairs( schemes ) do
444                 for k, v in pairs( conf ) do
445                         if v['.type'] == 'section' then
446
447                                 ok, err = _req( TYPE_SECTION, v, { "name", "package" } )
448                                 if err then return false, scheme:error(err) end
449
450                                 local r, err = _ref( TYPE_SECTION, v )
451                                 if err then return false, scheme:error(err) end
452
453                                 self.packages[r[1]] =
454                                         self.packages[r[1]] or {
455                                                 ["name"]      = r[1];
456                                                 ["sections"]  = { };
457                                                 ["variables"] = { };
458                                         }
459
460                                 local p = self.packages[r[1]]
461                                           p.sections[v.name]  = p.sections[v.name]  or { }
462                                           p.variables[v.name] = p.variables[v.name] or { }
463
464                                 local s  = p.sections[v.name]
465                                 local so = scheme:section(v.name)
466
467                                 for k, v2 in pairs(v) do
468                                         if k ~= "name" and k ~= "package" and k:sub(1,1) ~= "." then
469                                                 if k == "depends" then
470                                                         s.depends = self:_read_dependency( v2, s.depends )
471                                                         if not s.depends then
472                                                                 return false, scheme:error(
473                                                                         ERR.SME_BADDEP(so, luci.util.serialize_data(s.depends))
474                                                                 )
475                                                         end
476                                                 elseif k == "dynamic" or k == "unique" or
477                                                        k == "required" or k == "named"
478                                                 then
479                                                         s[k] = _bool(v2)
480                                                 else
481                                                         s[k] = v2
482                                                 end
483                                         end
484                                 end
485
486                                 s.dynamic  = s.dynamic  or false
487                                 s.unique   = s.unique   or false
488                                 s.required = s.required or false
489                                 s.named    = s.named    or false
490                         end
491                 end
492         end
493
494         -- Step 2: get all variables
495         for i, conf in ipairs( schemes ) do
496                 for k, v in pairs( conf ) do
497                         if v['.type'] == "variable" then
498
499                                 ok, err = _req( TYPE_VARIABLE, v, { "name", "section" } )
500                                 if err then return false, scheme:error(err) end
501
502                                 local r, err = _ref( TYPE_VARIABLE, v )
503                                 if err then return false, scheme:error(err) end
504
505                                 local p = self.packages[r[1]]
506                                 if not p then
507                                         return false, scheme:error(
508                                                 ERR.SME_VBADPACK({scheme:sid(), '', v.name}, r[1])
509                                         )
510                                 end
511
512                                 local s = p.variables[r[2]]
513                                 if not s then
514                                         return false, scheme:error(
515                                                 ERR.SME_VBADSECT({scheme:sid(), '', v.name}, r[2])
516                                         )
517                                 end
518
519                                 s[v.name] = s[v.name] or { }
520
521                                 local t  = s[v.name]
522                                 local so = scheme:section(r[2])
523                                 local to = so:option(v.name)
524
525                                 for k, v2 in pairs(v) do
526                                         if k ~= "name" and k ~= "section" and k:sub(1,1) ~= "." then
527                                                 if k == "depends" then
528                                                         t.depends = self:_read_dependency( v2, t.depends )
529                                                         if not t.depends then
530                                                                 return false, scheme:error(so:error(
531                                                                         ERR.SME_BADDEP(to, luci.util.serialize_data(v2))
532                                                                 ))
533                                                         end
534                                                 elseif k == "validator" then
535                                                         t.validators = self:_read_validator( v2, t.validators )
536                                                         if not t.validators then
537                                                                 return false, scheme:error(so:error(
538                                                                         ERR.SME_BADVAL(to, luci.util.serialize_data(v2))
539                                                                 ))
540                                                         end
541                                                 elseif k == "valueof" then
542                                                         local values, err = self:_read_reference( v2 )
543                                                         if err then
544                                                                 return false, scheme:error(so:error(
545                                                                         ERR.REFERENCE(to, luci.util.serialize_data(v2)):child(err)
546                                                                 ))
547                                                         end
548                                                         t.type   = "reference"
549                                                         t.values = values
550                                                 elseif k == "required" then
551                                                         t[k] = _bool(v2)
552                                                 else
553                                                         t[k] = t[k] or v2
554                                                 end
555                                         end
556                                 end
557
558                                 t.type     = t.type     or "variable"
559                                 t.datatype = t.datatype or "string"
560                                 t.required = t.required or false
561                         end
562                 end
563         end
564
565         -- Step 3: get all enums
566         for i, conf in ipairs( schemes ) do
567                 for k, v in pairs( conf ) do
568                         if v['.type'] == "enum" then
569
570                                 ok, err = _req( TYPE_ENUM, v, { "value", "variable" } )
571                                 if err then return false, scheme:error(err) end
572
573                                 local r, err = _ref( TYPE_ENUM, v )
574                                 if err then return false, scheme:error(err) end
575
576                                 local p = self.packages[r[1]]
577                                 if not p then
578                                         return false, scheme:error(
579                                                 ERR.SME_EBADPACK({scheme:sid(), '', '', v.value}, r[1])
580                                         )
581                                 end
582
583                                 local s = p.variables[r[2]]
584                                 if not s then
585                                         return false, scheme:error(
586                                                 ERR.SME_EBADSECT({scheme:sid(), '', '', v.value}, r[2])
587                                         )
588                                 end
589
590                                 local t = s[r[3]]
591                                 if not t then
592                                         return false, scheme:error(
593                                                 ERR.SME_EBADOPT({scheme:sid(), '', '', v.value}, r[3])
594                                         )
595                                 end
596
597
598                                 local so = scheme:section(r[2])
599                                 local oo = so:option(r[3])
600                                 local eo = oo:enum(v.value)
601
602                                 if t.type ~= "enum" then
603                                         return false, scheme:error(ERR.SME_EBADTYPE(eo))
604                                 end
605
606                                 if not t.values then
607                                         t.values = { [v.value] = v.title or v.value }
608                                 else
609                                         t.values[v.value] = v.title or v.value
610                                 end
611
612                                 if not t.enum_depends then
613                                         t.enum_depends = { }
614                                 end
615
616                                 if v.default then
617                                         if t.default then
618                                                 return false, scheme:error(ERR.SME_EBADDEF(eo))
619                                         end
620                                         t.default = v.value
621                                 end
622
623                                 if v.depends then
624                                         t.enum_depends[v.value] = self:_read_dependency(
625                                                 v.depends, t.enum_depends[v.value]
626                                         )
627
628                                         if not t.enum_depends[v.value] then
629                                                 return false, scheme:error(so:error(oo:error(
630                                                         ERR.SME_BADDEP(eo, luci.util.serialize_data(v.depends))
631                                                 )))
632                                         end
633                                 end
634                         end
635                 end
636         end
637
638         return self
639 end
640
641 -- Read a dependency specification
642 function UVL._read_dependency( self, values, deps )
643         local expr = "%$?[a-zA-Z0-9_]+"
644         if values then
645                 values = ( type(values) == "table" and values or { values } )
646                 for _, value in ipairs(values) do
647                         local parts     = luci.util.split( value, "%s*,%s*", nil, true )
648                         local condition = { }
649                         for i, val in ipairs(parts) do
650                                 local k, v = unpack(luci.util.split(val, "%s*=%s*", nil, true))
651
652                                 if k and (
653                                         k:match("^"..expr.."%."..expr.."%."..expr.."$") or
654                                         k:match("^"..expr.."%."..expr.."$") or
655                                         k:match("^"..expr.."$")
656                                 ) then
657                                         condition[k] = v or true
658                                 else
659                                         return nil
660                                 end
661                         end
662
663                         if not deps then
664                                 deps = { condition }
665                         else
666                                 table.insert( deps, condition )
667                         end
668                 end
669         end
670
671         return deps
672 end
673
674 -- Read a validator specification
675 function UVL._read_validator( self, values, validators )
676         if values then
677                 values = ( type(values) == "table" and values or { values } )
678                 for _, value in ipairs(values) do
679                         local validator
680
681                         if value:match("^exec:") then
682                                 validator = value:gsub("^exec:","")
683                         elseif value:match("^lua:") then
684                                 validator = self:_resolve_function( (value:gsub("^lua:","") ) )
685                         end
686
687                         if validator then
688                                 if not validators then
689                                         validators = { validator }
690                                 else
691                                         table.insert( validators, validator )
692                                 end
693                         else
694                                 return nil
695                         end
696                 end
697
698                 return validators
699         end
700 end
701
702 -- Read a reference specification (XXX: We should validate external configs too...)
703 function UVL._read_reference( self, values )
704         local val = { }
705         values = ( type(values) == "table" and values or { values } )
706
707         for _, value in ipairs(values) do
708                 local ref = luci.util.split(value, ".")
709
710                 if #ref == 2 or #ref == 3 then
711                         local co = luci.uvl.config( self, ref[1] )
712                         if not co:config() then return false, co:errors() end
713
714                         for k, v in pairs(co:config()) do
715                                 if v['.type'] == ref[2] then
716                                         if #ref == 2 then
717                                                 if v['.anonymous'] == true then
718                                                         return false, ERR.SME_INVREF('', value)
719                                                 end
720                                                 val[k] = k      -- XXX: title/description would be nice
721                                         elseif v[ref[3]] then
722                                                 val[v[ref[3]]] = v[ref[3]]  -- XXX: dito
723                                         end
724                                 end
725                         end
726                 else
727                         return false, ERR.SME_BADREF('', value)
728                 end
729         end
730
731         return val, nil
732 end
733
734 -- Resolve given path
735 function UVL._resolve_function( self, value )
736         local path = luci.util.split(value, ".")
737
738         for i=1, #path-1 do
739                 local stat, mod = luci.util.copcall(
740                         require, table.concat(path, ".", 1, i)
741                 )
742
743                 if stat and mod then
744                         for j=i+1, #path-1 do
745                                 if not type(mod) == "table" then
746                                         break
747                                 end
748                                 mod = mod[path[j]]
749                                 if not mod then
750                                         break
751                                 end
752                         end
753                         mod = type(mod) == "table" and mod[path[#path]] or nil
754                         if type(mod) == "function" then
755                                 return mod
756                         end
757                 end
758         end
759 end
760
761
762 --- Object representation of an uvl item - base class.
763 uvlitem = luci.util.class()
764
765 function uvlitem.cid(self)
766         return table.concat( self.cref, '.' )
767 end
768
769 function uvlitem.sid(self)
770         return table.concat( self.sref, '.' )
771 end
772
773 function uvlitem.scheme(self, opt)
774         local s
775
776         if #self.sref == 4 or #self.sref == 3 then
777                 s = self.s
778                         .packages[self.sref[1]]
779                         .variables[self.sref[2]][self.sref[3]]
780         elseif #self.sref == 2 then
781                 s = self.s
782                         .packages[self.sref[1]]
783                         .sections[self.sref[2]]
784         else
785                 s = self.s
786                         .packages[self.sref[1]]
787         end
788
789         if s and opt then
790                 return s[opt]
791         elseif s then
792                 return s
793         end
794 end
795
796 function uvlitem.config(self, opt)
797         local c
798
799         if #self.cref == 4 or #self.cref == 3 then
800                 c = self.c and self.c[self.cref[2]] or nil
801                 c = c      and c[self.cref[3]]      or nil
802         elseif #self.cref == 2 then
803                 c = self.c and self.c[self.cref[2]] or nil
804         else
805                 c = self.c
806         end
807
808         if c and opt then
809                 return c[opt]
810         elseif c then
811                 return c
812         end
813 end
814
815 function uvlitem.title(self)
816         return self:scheme() and self:scheme('title') or
817                 self.cref[3] or self.cref[2] or self.cref[1]
818 end
819
820 function uvlitem.type(self)
821         if self.t == luci.uvl.TYPE_CONFIG then
822                 return 'config'
823         elseif self.t == luci.uvl.TYPE_SECTION then
824                 return 'section'
825         elseif self.t == luci.uvl.TYPE_OPTION then
826                 return 'option'
827         elseif self.t == luci.uvl.TYPE_ENUM then
828                 return 'enum'
829         end
830 end
831
832 function uvlitem.error(self, ...)
833         if not self.e then
834                 local errconst = { ERR.CONFIG, ERR.SECTION, ERR.OPTION, ERR.OPTION }
835                 self.e = errconst[#self.cref]( self )
836         end
837
838         return self.e:child( ... )
839 end
840
841 function uvlitem.errors(self)
842         return self.e
843 end
844
845 function uvlitem.ok(self)
846         return not self:errors()
847 end
848
849 function uvlitem.parent(self)
850         if self.p then
851                 return self.p
852         elseif #self.cref == 3 or #self.cref == 4 then
853                 return luci.uvl.section( self.s, self.c, self.cref[1], self.cref[2] )
854         elseif #self.cref == 2 then
855                 return luci.uvl.config( self.s, self.c, self.cref[1] )
856         else
857                 return nil
858         end
859 end
860
861 function uvlitem._loadconf(self, co, c)
862         if not co then
863                 local uci, err = luci.model.uci.cursor(), nil
864                 co, err = uci:get_all(c)
865
866                 if err then
867                         self:error(ERR.UCILOAD(self, err))
868                 end
869         end
870         return co
871 end
872
873
874 --- Object representation of a scheme.
875 -- @class       scheme
876 -- @cstyle      instance
877 -- @name        luci.uvl.scheme
878
879 --- Scheme instance constructor.
880 -- @class                       function
881 -- @name                        scheme
882 -- @param scheme        Scheme instance
883 -- @param co            Configuration data
884 -- @param c                     Configuration name
885 -- @return                      Config instance
886 scheme = luci.util.class(uvlitem)
887
888 function scheme.__init__(self, scheme, co, c)
889         if not c then
890                 c, co = co, nil
891         end
892
893         self.cref = { c }
894         self.sref = { c }
895         self.c    = self:_loadconf(co, c)
896         self.s    = scheme
897         self.t    = luci.uvl.TYPE_SCHEME
898 end
899
900 --- Add an error to scheme.
901 -- @return      Scheme error context
902 function scheme.error(self, ...)
903         if not self.e then self.e = ERR.SCHEME( self ) end
904         return self.e:child( ... )
905 end
906
907 --- Get an associated config object.
908 -- @return      Config instance
909 function scheme.config(self)
910         local co = luci.uvl.config( self.s, self.cref[1] )
911               co.p = self
912
913         return co
914 end
915
916 --- Get all section objects associated with this scheme.
917 -- @return      Table containing all associated luci.uvl.section instances
918 function scheme.sections(self)
919         local v = { }
920         if self.s.packages[self.sref[1]].sections then
921                 for o, _ in pairs( self.s.packages[self.sref[1]].sections ) do
922                         table.insert( v, luci.uvl.option(
923                                 self.s, self.c, self.cref[1], self.cref[2], o
924                         ) )
925                 end
926         end
927         return v
928 end
929
930 --- Get an associated section object.
931 -- @param s     Section to select
932 -- @return      Section instance
933 function scheme.section(self, s)
934         local so = luci.uvl.section( self.s, self.c, self.cref[1], s )
935               so.p = self
936
937         return so
938 end
939
940
941 --- Object representation of a config.
942 -- @class       config
943 -- @cstyle      instance
944 -- @name        luci.uvl.config
945
946 --- Config instance constructor.
947 -- @class                       function
948 -- @name                        config
949 -- @param scheme        Scheme instance
950 -- @param co            Configuration data
951 -- @param c                     Configuration name
952 -- @return                      Config instance
953 config = luci.util.class(uvlitem)
954
955 function config.__init__(self, scheme, co, c)
956         if not c then
957                 c, co = co, nil
958         end
959
960         self.cref = { c }
961         self.sref = { c }
962         self.c    = self:_loadconf(co, c)
963         self.s    = scheme
964         self.t    = luci.uvl.TYPE_CONFIG
965 end
966
967 --- Get all section objects associated with this config.
968 -- @return      Table containing all associated luci.uvl.section instances
969 function config.sections(self)
970         local v = { }
971         if self.s.packages[self.sref[1]].sections then
972                 for o, _ in pairs( self.s.packages[self.sref[1]].sections ) do
973                         table.insert( v, luci.uvl.option(
974                                 self.s, self.c, self.cref[1], self.cref[2], o
975                         ) )
976                 end
977         end
978         return v
979 end
980
981 --- Get an associated section object.
982 -- @param s     Section to select
983 -- @return      Section instance
984 function config.section(self, s)
985         local so = luci.uvl.section( self.s, self.c, self.cref[1], s )
986               so.p = self
987
988         return so
989 end
990
991
992 --- Object representation of a scheme/config section.
993 -- @class       module
994 -- @cstyle      instance
995 -- @name        luci.uvl.section
996
997 --- Section instance constructor.
998 -- @class                       function
999 -- @name                        section
1000 -- @param scheme        Scheme instance
1001 -- @param co            Configuration data
1002 -- @param c                     Configuration name
1003 -- @param s                     Section name
1004 -- @return                      Section instance
1005 section = luci.util.class(uvlitem)
1006
1007 function section.__init__(self, scheme, co, c, s)
1008         self.cref = { c, s }
1009         self.sref = { c, co and co[s] and co[s]['.type'] or s }
1010         self.c    = self:_loadconf(co, c)
1011         self.s    = scheme
1012         self.t    = luci.uvl.TYPE_SECTION
1013 end
1014
1015 --- Get all option objects associated with this section.
1016 -- @return      Table containing all associated luci.uvl.option instances
1017 function section.variables(self)
1018         local v = { }
1019         if self.s.packages[self.sref[1]].variables[self.sref[2]] then
1020                 for o, _ in pairs(
1021                         self.s.packages[self.sref[1]].variables[self.sref[2]]
1022                 ) do
1023                         table.insert( v, luci.uvl.option(
1024                                 self.s, self.c, self.cref[1], self.cref[2], o
1025                         ) )
1026                 end
1027         end
1028         return v
1029 end
1030
1031 --- Get an associated option object.
1032 -- @param o     Option to select
1033 -- @return      Option instance
1034 function section.option(self, o)
1035         local oo = luci.uvl.option( self.s, self.c, self.cref[1], self.cref[2], o )
1036               oo.p = self
1037
1038         return oo
1039 end
1040
1041
1042 --- Object representation of a scheme/config option.
1043 -- @class       module
1044 -- @cstyle      instance
1045 -- @name        luci.uvl.option
1046
1047 --- Section instance constructor.
1048 -- @class                       function
1049 -- @name                        option
1050 -- @param scheme        Scheme instance
1051 -- @param co            Configuration data
1052 -- @param c                     Configuration name
1053 -- @param s                     Section name
1054 -- @param o                     Option name
1055 -- @return                      Option instance
1056 option = luci.util.class(uvlitem)
1057
1058 function option.__init__(self, scheme, co, c, s, o)
1059         self.cref = { c, s, o }
1060         self.sref = { c, co and co[s] and co[s]['.type'] or s, o }
1061         self.c    = self:_loadconf(co, c)
1062         self.s    = scheme
1063         self.t    = luci.uvl.TYPE_OPTION
1064 end
1065
1066 --- Get the value of this option.
1067 -- @return      The associated configuration value
1068 function option.value(self)
1069         return self:config()
1070 end
1071
1072 --- Get the associated section information in scheme.
1073 -- @return      Table containing the scheme properties
1074 function option.section(self)
1075         return self.s.packages[self.sref[1]].sections[self.sref[2]]
1076 end
1077
1078 --- Construct an enum object instance from given or default value.
1079 -- @param v     Value to select
1080 -- @return      Enum instance for selected value
1081 function option.enum(self, val)
1082         return enum(
1083                 self.s, self.c,
1084                 self.cref[1], self.cref[2], self.cref[3],
1085                 val or self:value()
1086         )
1087 end
1088
1089
1090 --- Object representation of a enum value.
1091 -- @class       module
1092 -- @cstyle      instance
1093 -- @name        luci.uvl.enum
1094
1095 --- Section instance constructor.
1096 -- @class                       function
1097 -- @name                        enum
1098 -- @param scheme        Scheme instance
1099 -- @param co            Configuration data
1100 -- @param c                     Configuration name
1101 -- @param s                     Section name
1102 -- @param o                     Enum name
1103 -- @param v                     Enum value
1104 -- @return                      Enum value instance
1105 enum = luci.util.class(option)
1106
1107 function enum.__init__(self, scheme, co, c, s, o, v)
1108         self.cref = { c, s, o, v }
1109         self.sref = { c, co and co[s] and co[s]['.type'] or s, o, v }
1110         self.c    = self:_loadconf(co, c)
1111         self.s    = scheme
1112         self.t    = luci.uvl.TYPE_ENUM
1113 end