4e872188d0082c52a1b128273e10888e0066a593
2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String
.prototype.format = function()
15 var html_esc
= [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g
, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d
+)?(\.\d
+)?(%|b
|c
|d
|u
|f
|o
|s
|x
|X
|q
|h
|j
|t
|m
))/;
27 var a
= b
= [], numSubstitutions
= 0, numMatches
= 0;
29 while ((a
= re
.exec(str
)) != null)
32 var leftpart
= a
[2], pPad
= a
[3], pJustify
= a
[4], pMinLength
= a
[5];
33 var pPrecision
= a
[6], pType
= a
[7];
43 if (numSubstitutions
< arguments
.length
)
45 var param
= arguments
[numSubstitutions
++];
48 if (pPad
&& pPad
.substr(0,1) == "'")
49 pad
= leftpart
.substr(1,1);
53 var justifyRight
= true;
54 if (pJustify
&& pJustify
=== "-")
59 minLength
= parseInt(pMinLength
);
62 if (pPrecision
&& pType
== 'f')
63 precision
= parseInt(pPrecision
.substring(1));
70 subst
= (parseInt(param
) || 0).toString(2);
74 subst
= String
.fromCharCode(parseInt(param
) || 0);
78 subst
= (parseInt(param
) || 0);
82 subst
= Math
.abs(parseInt(param
) || 0);
86 subst
= (precision
> -1)
87 ? ((parseFloat(param
) || 0.0)).toFixed(precision
)
88 : (parseFloat(param
) || 0.0);
92 subst
= (parseInt(param
) || 0).toString(8);
100 subst
= ('' + (parseInt(param
) || 0).toString(16)).toLowerCase();
104 subst
= ('' + (parseInt(param
) || 0).toString(16)).toUpperCase();
108 subst
= esc(param
, html_esc
);
112 subst
= esc(param
, quot_esc
);
116 subst
= String
.serialize(param
);
123 var ts
= (param
|| 0);
126 tm
= Math
.floor(ts
/ 60);
131 th
= Math
.floor(tm
/ 60);
136 td
= Math
.floor(th
/ 24);
141 ? '%dd %dh %dm %ds'.format(td
, th
, tm
, ts
)
142 : '%dh %dm %ds'.format(th
, tm
, ts
);
147 var mf
= pMinLength
? parseInt(pMinLength
) : 1000;
148 var pr
= pPrecision
? Math
.floor(10*parseFloat('0'+pPrecision
)) : 2;
151 var val
= parseFloat(param
|| 0);
152 var units
= [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i
= 0; (i
< units
.length
) && (val
> mf
); i
++)
157 subst
= val
.toFixed(pr
) + ' ' + units
[i
];
161 subst
= (typeof(subst
) == 'undefined') ? '' : subst
.toString();
163 if (minLength
> 0 && pad
.length
> 0)
164 for (var i
= 0; i
< (minLength
- subst
.length
); i
++)
165 subst
= justifyRight
? (pad
+ subst
) : (subst
+ pad
);
169 out
+= leftpart
+ subst
;
170 str
= str
.substr(m
.length
);
180 var Class = function() { };
182 Class
.extend = function(properties
)
184 Class
.initializing
= true;
186 var prototype = new this();
187 var superprot
= this.prototype;
189 Class
.initializing
= false;
191 $.extend(prototype, properties
, {
192 callSuper: function() {
194 var meth
= arguments
[0];
196 if (typeof(superprot
[meth
]) != 'function')
199 for (var i
= 1; i
< arguments
.length
; i
++)
200 args
.push(arguments
[i
]);
202 return superprot
[meth
].apply(this, args
);
208 this.options
= arguments
[0] || { };
210 if (!Class
.initializing
&& typeof(this.init
) == 'function')
211 this.init
.apply(this, arguments
);
214 _class
.prototype = prototype;
215 _class
.prototype.constructor = _class
;
217 _class
.extend
= Class
.extend
;
222 this.defaults = function(obj
, def
)
225 if (typeof(obj
[key
]) == 'undefined')
231 this.isDeferred = function(x
)
233 return (typeof(x
) == 'object' &&
234 typeof(x
.then
) == 'function' &&
235 typeof(x
.promise
) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments
[0]))
243 var d
= $.Deferred();
244 d
.resolve
.apply(d
, arguments
);
253 plural: function(n
) { return 0 + (n
!= 1) },
256 if (_luci2
.i18n
.loaded
)
259 var lang
= (navigator
.userLanguage
|| navigator
.language
|| 'en').toLowerCase();
260 var langs
= (lang
.indexOf('-') > -1) ? [ lang
, lang
.split(/-/)[0] ] : [ lang
];
262 for (var i
= 0; i
< langs
.length
; i
++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2
.globals
.resource
, langs
[i
]), {
267 success: function(data
) {
268 $.extend(_luci2
.i18n
.catalog
, data
);
270 var pe
= _luci2
.i18n
.catalog
[''];
273 delete _luci2
.i18n
.catalog
[''];
275 var pf
= new Function('n', 'return 0 + (' + pe
+ ')');
276 _luci2
.i18n
.plural
= pf
;
282 _luci2
.i18n
.loaded
= true;
287 this.tr = function(msgid
)
291 var msgstr
= _luci2
.i18n
.catalog
[msgid
];
293 if (typeof(msgstr
) == 'undefined')
295 else if (typeof(msgstr
) == 'string')
301 this.trp = function(msgid
, msgid_plural
, count
)
305 var msgstr
= _luci2
.i18n
.catalog
[msgid
];
307 if (typeof(msgstr
) == 'undefined')
308 return (count
== 1) ? msgid
: msgid_plural
;
309 else if (typeof(msgstr
) == 'string')
312 return msgstr
[_luci2
.i18n
.plural(count
)];
315 this.trc = function(msgctx
, msgid
)
319 var msgstr
= _luci2
.i18n
.catalog
[msgid
+ '\u0004' + msgctx
];
321 if (typeof(msgstr
) == 'undefined')
323 else if (typeof(msgstr
) == 'string')
329 this.trcp = function(msgctx
, msgid
, msgid_plural
, count
)
333 var msgstr
= _luci2
.i18n
.catalog
[msgid
+ '\u0004' + msgctx
];
335 if (typeof(msgstr
) == 'undefined')
336 return (count
== 1) ? msgid
: msgid_plural
;
337 else if (typeof(msgstr
) == 'string')
340 return msgstr
[_luci2
.i18n
.plural(count
)];
343 this.setHash = function(key
, value
)
346 var data
= this.getHash(undefined);
348 if (typeof(value
) == 'undefined')
359 for (var i
= 0; i
< keys
.length
; i
++)
364 h
+= keys
[i
] + ':' + data
[keys
[i
]];
368 location
.hash
= '#' + h
;
373 this.getHash = function(key
)
376 var tuples
= (location
.hash
|| '#').substring(1).split(/,/);
378 for (var i
= 0; i
< tuples
.length
; i
++)
380 var tuple
= tuples
[i
].split(/:/);
381 if (tuple
.length
== 2)
382 data
[tuple
[0]] = tuple
[1];
385 if (typeof(key
) != 'undefined')
391 this.toArray = function(x
)
401 var l
= x
.split(/\s+/);
402 for (var i
= 0; i
< l
.length
; i
++)
411 for (var i
= 0; i
< x
.length
; i
++)
415 else if ($.isPlainObject(x
))
419 if (x
.hasOwnProperty(k
))
428 this.toObject = function(x
)
438 var l
= x
.split(/\x+/);
439 for (var i
= 0; i
< l
.length
; i
++)
448 for (var i
= 0; i
< x
.length
; i
++)
452 else if ($.isPlainObject(x
))
461 this.filterArray = function(array
, item
)
463 if (!$.isArray(array
))
466 for (var i
= 0; i
< array
.length
; i
++)
467 if (array
[i
] === item
)
468 array
.splice(i
--, 1);
473 this.toClassName = function(str
, suffix
)
476 var l
= str
.split(/[\/.]/);
478 for (var i
= 0; i
< l
.length
; i
++)
480 n
+= l
[i
].charAt(0).toUpperCase() + l
[i
].substr(1).toLowerCase();
482 if (typeof(suffix
) == 'string')
491 sid
: '00000000000000000000000000000000'
500 _call: function(req
, cb
)
502 return $.ajax('/ubus', {
504 contentType
: 'application/json',
505 data
: JSON
.stringify(req
),
508 timeout
: _luci2
.globals
.timeout
,
513 _list_cb: function(msg
)
515 var list
= msg
.result
;
517 /* verify message frame */
518 if (typeof(msg
) != 'object' || msg
.jsonrpc
!= '2.0' || !msg
.id
|| !$.isArray(list
))
521 return $.Deferred().resolveWith(this, [ list
]);
524 _call_cb: function(msg
)
527 var type
= Object
.prototype.toString
;
528 var reqs
= this._rpc_req
;
530 if (!$.isArray(reqs
))
536 for (var i
= 0; i
< msg
.length
; i
++)
538 /* fetch related request info */
539 var req
= _luci2
.rpc
._requests
[reqs
[i
].id
];
540 if (typeof(req
) != 'object')
541 throw 'No related request for JSON response';
543 /* fetch response attribute and verify returned type */
546 /* verify message frame */
547 if (typeof(msg
[i
]) == 'object' && msg
[i
].jsonrpc
== '2.0')
548 if ($.isArray(msg
[i
].result
) && msg
[i
].result
[0] == 0)
549 ret
= (msg
[i
].result
.length
> 1) ? msg
[i
].result
[1] : msg
[i
].result
[0];
553 for (var key
in req
.expect
)
555 if (typeof(ret
) != 'undefined' && key
!= '')
558 if (typeof(ret
) == 'undefined' || type
.call(ret
) != type
.call(req
.expect
[key
]))
559 ret
= req
.expect
[key
];
566 if (typeof(req
.filter
) == 'function')
569 req
.priv
[1] = req
.params
;
570 ret
= req
.filter
.apply(_luci2
.rpc
, req
.priv
);
573 /* store response data */
574 if (typeof(req
.index
) == 'number')
575 data
[req
.index
] = ret
;
579 /* delete request object */
580 delete _luci2
.rpc
._requests
[reqs
[i
].id
];
583 return $.Deferred().resolveWith(this, [ data
]);
589 for (var i
= 0; i
< arguments
.length
; i
++)
590 params
[i
] = arguments
[i
];
596 params
: (params
.length
> 0) ? params
: undefined
599 return this._call(msg
, this._list_cb
);
604 if (!$.isArray(this._batch
))
610 if (!$.isArray(this._batch
))
611 return _luci2
.deferrable([ ]);
613 var req
= this._batch
;
617 return this._call(req
, this._call_cb
);
620 declare: function(options
)
625 /* build parameter object */
628 if ($.isArray(options
.params
))
629 for (p_off
= 0; p_off
< options
.params
.length
; p_off
++)
630 params
[options
.params
[p_off
]] = arguments
[p_off
];
632 /* all remaining arguments are private args */
633 var priv
= [ undefined, undefined ];
634 for (; p_off
< arguments
.length
; p_off
++)
635 priv
.push(arguments
[p_off
]);
637 /* store request info */
638 var req
= _rpc
._requests
[_rpc
._id
] = {
639 expect
: options
.expect
,
640 filter
: options
.filter
,
645 /* build message object */
658 /* when a batch is in progress then store index in request data
659 * and push message object onto the stack */
660 if ($.isArray(_rpc
._batch
))
662 req
.index
= _rpc
._batch
.push(msg
) - 1;
663 return _luci2
.deferrable(msg
);
667 return _rpc
._call(msg
, _rpc
._call_cb
);
676 return _luci2
.session
.access('ubus', 'uci', 'commit');
679 add
: _luci2
.rpc
.declare({
682 params
: [ 'config', 'type', 'name', 'values' ],
683 expect
: { section
: '' }
691 configs
: _luci2
.rpc
.declare({
694 expect
: { configs
: [ ] }
697 _changes
: _luci2
.rpc
.declare({
700 params
: [ 'config' ],
701 expect
: { changes
: [ ] }
704 changes: function(config
)
706 if (typeof(config
) == 'string')
707 return this._changes(config
);
710 return this.configs().then(function(configs
) {
712 configlist
= configs
;
714 for (var i
= 0; i
< configs
.length
; i
++)
715 _luci2
.uci
._changes(configs
[i
]);
717 return _luci2
.rpc
.flush();
718 }).then(function(changes
) {
721 for (var i
= 0; i
< configlist
.length
; i
++)
722 if (changes
[i
].length
)
723 rv
[configlist
[i
]] = changes
[i
];
729 commit
: _luci2
.rpc
.declare({
735 _delete_one
: _luci2
.rpc
.declare({
738 params
: [ 'config', 'section', 'option' ]
741 _delete_multiple
: _luci2
.rpc
.declare({
744 params
: [ 'config', 'section', 'options' ]
747 'delete': function(config
, section
, option
)
749 if ($.isArray(option
))
750 return this._delete_multiple(config
, section
, option
);
752 return this._delete_one(config
, section
, option
);
755 delete_all
: _luci2
.rpc
.declare({
758 params
: [ 'config', 'type', 'match' ]
761 _foreach
: _luci2
.rpc
.declare({
764 params
: [ 'config', 'type' ],
765 expect
: { values
: { } }
768 foreach: function(config
, type
, cb
)
770 return this._foreach(config
, type
).then(function(sections
) {
771 for (var s
in sections
)
776 get: _luci2
.rpc
.declare({
779 params
: [ 'config', 'section', 'option' ],
781 filter: function(data
, params
) {
782 if (typeof(params
.option
) == 'undefined')
783 return data
.values
? data
.values
['.type'] : undefined;
789 get_all
: _luci2
.rpc
.declare({
792 params
: [ 'config', 'section' ],
793 expect
: { values
: { } },
794 filter: function(data
, params
) {
795 if (typeof(params
.section
) == 'string')
796 data
['.section'] = params
.section
;
797 else if (typeof(params
.config
) == 'string')
798 data
['.package'] = params
.config
;
803 get_first: function(config
, type
, option
)
805 return this._foreach(config
, type
).then(function(sections
) {
806 for (var s
in sections
)
808 var val
= (typeof(option
) == 'string') ? sections
[s
][option
] : sections
[s
]['.name'];
810 if (typeof(val
) != 'undefined')
818 section
: _luci2
.rpc
.declare({
821 params
: [ 'config', 'type', 'name', 'values' ],
822 expect
: { section
: '' }
825 _set
: _luci2
.rpc
.declare({
828 params
: [ 'config', 'section', 'values' ]
831 set: function(config
, section
, option
, value
)
833 if (typeof(value
) == 'undefined' && typeof(option
) == 'string')
834 return this.section(config
, section
, option
); /* option -> type */
835 else if ($.isPlainObject(option
))
836 return this._set(config
, section
, option
); /* option -> values */
839 values
[option
] = value
;
841 return this._set(config
, section
, values
);
844 order
: _luci2
.rpc
.declare({
847 params
: [ 'config', 'sections' ]
852 listNetworkNames: function() {
853 return _luci2
.rpc
.list('network.interface.*').then(function(list
) {
855 for (var name
in list
)
856 if (name
!= 'network.interface.loopback')
857 names
.push(name
.substring(18));
863 listDeviceNames
: _luci2
.rpc
.declare({
864 object
: 'network.device',
867 filter: function(data
) {
869 for (var name
in data
)
877 getNetworkStatus: function()
882 return this.listNetworkNames().then(function(names
) {
885 for (var i
= 0; i
< names
.length
; i
++)
886 _luci2
.network
.getInterfaceStatus(names
[i
]);
888 return _luci2
.rpc
.flush();
889 }).then(function(networks
) {
890 for (var i
= 0; i
< networks
.length
; i
++)
892 var net
= nets
[i
] = networks
[i
];
893 var dev
= net
.l3_device
|| net
.l2_device
;
895 net
.device
= devs
[dev
] || (devs
[dev
] = { });
900 for (var dev
in devs
)
901 _luci2
.network
.getDeviceStatus(dev
);
903 return _luci2
.rpc
.flush();
904 }).then(function(devices
) {
907 for (var i
= 0; i
< devices
.length
; i
++)
909 var brm
= devices
[i
]['bridge-members'];
910 delete devices
[i
]['bridge-members'];
912 $.extend(devs
[devices
[i
]['device']], devices
[i
]);
917 devs
[devices
[i
]['device']].subdevices
= [ ];
919 for (var j
= 0; j
< brm
.length
; j
++)
924 _luci2
.network
.getDeviceStatus(brm
[j
]);
927 devs
[devices
[i
]['device']].subdevices
[j
] = devs
[brm
[j
]];
931 return _luci2
.rpc
.flush();
932 }).then(function(subdevices
) {
933 for (var i
= 0; i
< subdevices
.length
; i
++)
934 $.extend(devs
[subdevices
[i
]['device']], subdevices
[i
]);
938 for (var dev
in devs
)
939 _luci2
.wireless
.getDeviceStatus(dev
);
941 return _luci2
.rpc
.flush();
942 }).then(function(wifidevices
) {
943 for (var i
= 0; i
< wifidevices
.length
; i
++)
945 devs
[wifidevices
[i
]['device']].wireless
= wifidevices
[i
];
947 nets
.sort(function(a
, b
) {
948 if (a
['interface'] < b
['interface'])
950 else if (a
['interface'] > b
['interface'])
960 findWanInterfaces: function(cb
)
962 return this.listNetworkNames().then(function(names
) {
965 for (var i
= 0; i
< names
.length
; i
++)
966 _luci2
.network
.getInterfaceStatus(names
[i
]);
968 return _luci2
.rpc
.flush();
969 }).then(function(interfaces
) {
970 var rv
= [ undefined, undefined ];
972 for (var i
= 0; i
< interfaces
.length
; i
++)
974 if (!interfaces
[i
].route
)
977 for (var j
= 0; j
< interfaces
[i
].route
.length
; j
++)
979 var rt
= interfaces
[i
].route
[j
];
981 if (typeof(rt
.table
) != 'undefined')
984 if (rt
.target
== '0.0.0.0' && rt
.mask
== 0)
985 rv
[0] = interfaces
[i
];
986 else if (rt
.target
== '::' && rt
.mask
== 0)
987 rv
[1] = interfaces
[i
];
995 getDHCPLeases
: _luci2
.rpc
.declare({
996 object
: 'luci2.network',
997 method
: 'dhcp_leases',
998 expect
: { leases
: [ ] }
1001 getDHCPv6Leases
: _luci2
.rpc
.declare({
1002 object
: 'luci2.network',
1003 method
: 'dhcp6_leases',
1004 expect
: { leases
: [ ] }
1007 getRoutes
: _luci2
.rpc
.declare({
1008 object
: 'luci2.network',
1010 expect
: { routes
: [ ] }
1013 getIPv6Routes
: _luci2
.rpc
.declare({
1014 object
: 'luci2.network',
1016 expect
: { routes
: [ ] }
1019 getARPTable
: _luci2
.rpc
.declare({
1020 object
: 'luci2.network',
1021 method
: 'arp_table',
1022 expect
: { entries
: [ ] }
1025 getInterfaceStatus
: _luci2
.rpc
.declare({
1026 object
: 'network.interface',
1028 params
: [ 'interface' ],
1029 expect
: { '': { } },
1030 filter: function(data
, params
) {
1031 data
['interface'] = params
['interface'];
1032 data
['l2_device'] = data
['device'];
1033 delete data
['device'];
1038 getDeviceStatus
: _luci2
.rpc
.declare({
1039 object
: 'network.device',
1042 expect
: { '': { } },
1043 filter: function(data
, params
) {
1044 data
['device'] = params
['name'];
1049 getConntrackCount
: _luci2
.rpc
.declare({
1050 object
: 'luci2.network',
1051 method
: 'conntrack_count',
1052 expect
: { '': { count
: 0, limit
: 0 } }
1055 listSwitchNames
: _luci2
.rpc
.declare({
1056 object
: 'luci2.network',
1057 method
: 'switch_list',
1058 expect
: { switches
: [ ] }
1061 getSwitchInfo
: _luci2
.rpc
.declare({
1062 object
: 'luci2.network',
1063 method
: 'switch_info',
1064 params
: [ 'switch' ],
1065 expect
: { info
: { } },
1066 filter: function(data
, params
) {
1067 data
['attrs'] = data
['switch'];
1068 data
['vlan_attrs'] = data
['vlan'];
1069 data
['port_attrs'] = data
['port'];
1070 data
['switch'] = params
['switch'];
1079 getSwitchStatus
: _luci2
.rpc
.declare({
1080 object
: 'luci2.network',
1081 method
: 'switch_status',
1082 params
: [ 'switch' ],
1083 expect
: { ports
: [ ] }
1087 runPing
: _luci2
.rpc
.declare({
1088 object
: 'luci2.network',
1091 expect
: { '': { code
: -1 } }
1094 runPing6
: _luci2
.rpc
.declare({
1095 object
: 'luci2.network',
1098 expect
: { '': { code
: -1 } }
1101 runTraceroute
: _luci2
.rpc
.declare({
1102 object
: 'luci2.network',
1103 method
: 'traceroute',
1105 expect
: { '': { code
: -1 } }
1108 runTraceroute6
: _luci2
.rpc
.declare({
1109 object
: 'luci2.network',
1110 method
: 'traceroute6',
1112 expect
: { '': { code
: -1 } }
1115 runNslookup
: _luci2
.rpc
.declare({
1116 object
: 'luci2.network',
1119 expect
: { '': { code
: -1 } }
1123 setUp
: _luci2
.rpc
.declare({
1124 object
: 'luci2.network',
1127 expect
: { '': { code
: -1 } }
1130 setDown
: _luci2
.rpc
.declare({
1131 object
: 'luci2.network',
1134 expect
: { '': { code
: -1 } }
1139 listDeviceNames
: _luci2
.rpc
.declare({
1142 expect
: { 'devices': [ ] },
1143 filter: function(data
) {
1149 getDeviceStatus
: _luci2
.rpc
.declare({
1152 params
: [ 'device' ],
1153 expect
: { '': { } },
1154 filter: function(data
, params
) {
1155 if (!$.isEmptyObject(data
))
1157 data
['device'] = params
['device'];
1164 getAssocList
: _luci2
.rpc
.declare({
1166 method
: 'assoclist',
1167 params
: [ 'device' ],
1168 expect
: { results
: [ ] },
1169 filter: function(data
, params
) {
1170 for (var i
= 0; i
< data
.length
; i
++)
1171 data
[i
]['device'] = params
['device'];
1173 data
.sort(function(a
, b
) {
1174 if (a
.bssid
< b
.bssid
)
1176 else if (a
.bssid
> b
.bssid
)
1186 getWirelessStatus: function() {
1187 return this.listDeviceNames().then(function(names
) {
1190 for (var i
= 0; i
< names
.length
; i
++)
1191 _luci2
.wireless
.getDeviceStatus(names
[i
]);
1193 return _luci2
.rpc
.flush();
1194 }).then(function(networks
) {
1198 'country', 'channel', 'frequency', 'frequency_offset',
1199 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1203 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1204 'signal', 'noise', 'bitrate', 'encryption'
1207 for (var i
= 0; i
< networks
.length
; i
++)
1209 var phy
= rv
[networks
[i
].phy
] || (
1210 rv
[networks
[i
].phy
] = { networks
: [ ] }
1214 device
: networks
[i
].device
1217 for (var j
= 0; j
< phy_attrs
.length
; j
++)
1218 phy
[phy_attrs
[j
]] = networks
[i
][phy_attrs
[j
]];
1220 for (var j
= 0; j
< net_attrs
.length
; j
++)
1221 net
[net_attrs
[j
]] = networks
[i
][net_attrs
[j
]];
1223 phy
.networks
.push(net
);
1230 getAssocLists: function()
1232 return this.listDeviceNames().then(function(names
) {
1235 for (var i
= 0; i
< names
.length
; i
++)
1236 _luci2
.wireless
.getAssocList(names
[i
]);
1238 return _luci2
.rpc
.flush();
1239 }).then(function(assoclists
) {
1242 for (var i
= 0; i
< assoclists
.length
; i
++)
1243 for (var j
= 0; j
< assoclists
[i
].length
; j
++)
1244 rv
.push(assoclists
[i
][j
]);
1250 formatEncryption: function(enc
)
1252 var format_list = function(l
, s
)
1255 for (var i
= 0; i
< l
.length
; i
++)
1256 rv
.push(l
[i
].toUpperCase());
1257 return rv
.join(s
? s
: ', ');
1260 if (!enc
|| !enc
.enabled
)
1261 return _luci2
.tr('None');
1265 if (enc
.wep
.length
== 2)
1266 return _luci2
.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1267 else if (enc
.wep
[0] == 'shared')
1268 return _luci2
.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1270 return _luci2
.tr('WEP Open System') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1274 if (enc
.wpa
.length
== 2)
1275 return _luci2
.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1276 format_list(enc
.authentication
, '/'),
1277 format_list(enc
.ciphers
, ', ')
1279 else if (enc
.wpa
[0] == 2)
1280 return 'WPA2 %s (%s)'.format(
1281 format_list(enc
.authentication
, '/'),
1282 format_list(enc
.ciphers
, ', ')
1285 return 'WPA %s (%s)'.format(
1286 format_list(enc
.authentication
, '/'),
1287 format_list(enc
.ciphers
, ', ')
1291 return _luci2
.tr('Unknown');
1296 getZoneColor: function(zone
)
1298 if ($.isPlainObject(zone
))
1303 else if (zone
== 'wan')
1306 for (var i
= 0, hash
= 0;
1308 hash
= zone
.charCodeAt(i
++) + ((hash
<< 5) - hash
));
1310 for (var i
= 0, color
= '#';
1312 color
+= ('00' + ((hash
>> i
++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1317 findZoneByNetwork: function(network
)
1320 var zone
= undefined;
1322 return _luci2
.uci
.foreach('firewall', 'zone', function(z
) {
1323 if (!z
.name
|| !z
.network
)
1326 if (!$.isArray(z
.network
))
1327 z
.network
= z
.network
.split(/\s+/);
1329 for (var i
= 0; i
< z
.network
.length
; i
++)
1331 if (z
.network
[i
] == network
)
1337 }).then(function() {
1339 zone
.color
= self
.getZoneColor(zone
);
1347 getSystemInfo
: _luci2
.rpc
.declare({
1353 getBoardInfo
: _luci2
.rpc
.declare({
1359 getDiskInfo
: _luci2
.rpc
.declare({
1360 object
: 'luci2.system',
1365 getInfo: function(cb
)
1369 this.getSystemInfo();
1370 this.getBoardInfo();
1373 return _luci2
.rpc
.flush().then(function(info
) {
1376 $.extend(rv
, info
[0]);
1377 $.extend(rv
, info
[1]);
1378 $.extend(rv
, info
[2]);
1384 getProcessList
: _luci2
.rpc
.declare({
1385 object
: 'luci2.system',
1386 method
: 'process_list',
1387 expect
: { processes
: [ ] },
1388 filter: function(data
) {
1389 data
.sort(function(a
, b
) { return a
.pid
- b
.pid
});
1394 getSystemLog
: _luci2
.rpc
.declare({
1395 object
: 'luci2.system',
1400 getKernelLog
: _luci2
.rpc
.declare({
1401 object
: 'luci2.system',
1406 getZoneInfo: function(cb
)
1408 return $.getJSON(_luci2
.globals
.resource
+ '/zoneinfo.json', cb
);
1411 sendSignal
: _luci2
.rpc
.declare({
1412 object
: 'luci2.system',
1413 method
: 'process_signal',
1414 params
: [ 'pid', 'signal' ],
1415 filter: function(data
) {
1420 initList
: _luci2
.rpc
.declare({
1421 object
: 'luci2.system',
1422 method
: 'init_list',
1423 expect
: { initscripts
: [ ] },
1424 filter: function(data
) {
1425 data
.sort(function(a
, b
) { return (a
.start
|| 0) - (b
.start
|| 0) });
1430 initEnabled: function(init
, cb
)
1432 return this.initList().then(function(list
) {
1433 for (var i
= 0; i
< list
.length
; i
++)
1434 if (list
[i
].name
== init
)
1435 return !!list
[i
].enabled
;
1441 initRun
: _luci2
.rpc
.declare({
1442 object
: 'luci2.system',
1443 method
: 'init_action',
1444 params
: [ 'name', 'action' ],
1445 filter: function(data
) {
1450 initStart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'start', cb
) },
1451 initStop: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'stop', cb
) },
1452 initRestart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'restart', cb
) },
1453 initReload: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'reload', cb
) },
1454 initEnable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'enable', cb
) },
1455 initDisable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'disable', cb
) },
1458 getRcLocal
: _luci2
.rpc
.declare({
1459 object
: 'luci2.system',
1460 method
: 'rclocal_get',
1461 expect
: { data
: '' }
1464 setRcLocal
: _luci2
.rpc
.declare({
1465 object
: 'luci2.system',
1466 method
: 'rclocal_set',
1471 getCrontab
: _luci2
.rpc
.declare({
1472 object
: 'luci2.system',
1473 method
: 'crontab_get',
1474 expect
: { data
: '' }
1477 setCrontab
: _luci2
.rpc
.declare({
1478 object
: 'luci2.system',
1479 method
: 'crontab_set',
1484 getSSHKeys
: _luci2
.rpc
.declare({
1485 object
: 'luci2.system',
1486 method
: 'sshkeys_get',
1487 expect
: { keys
: [ ] }
1490 setSSHKeys
: _luci2
.rpc
.declare({
1491 object
: 'luci2.system',
1492 method
: 'sshkeys_set',
1497 setPassword
: _luci2
.rpc
.declare({
1498 object
: 'luci2.system',
1499 method
: 'password_set',
1500 params
: [ 'user', 'password' ]
1504 listLEDs
: _luci2
.rpc
.declare({
1505 object
: 'luci2.system',
1507 expect
: { leds
: [ ] }
1510 listUSBDevices
: _luci2
.rpc
.declare({
1511 object
: 'luci2.system',
1513 expect
: { devices
: [ ] }
1517 testUpgrade
: _luci2
.rpc
.declare({
1518 object
: 'luci2.system',
1519 method
: 'upgrade_test',
1523 startUpgrade
: _luci2
.rpc
.declare({
1524 object
: 'luci2.system',
1525 method
: 'upgrade_start',
1529 cleanUpgrade
: _luci2
.rpc
.declare({
1530 object
: 'luci2.system',
1531 method
: 'upgrade_clean'
1535 restoreBackup
: _luci2
.rpc
.declare({
1536 object
: 'luci2.system',
1537 method
: 'backup_restore'
1540 cleanBackup
: _luci2
.rpc
.declare({
1541 object
: 'luci2.system',
1542 method
: 'backup_clean'
1546 getBackupConfig
: _luci2
.rpc
.declare({
1547 object
: 'luci2.system',
1548 method
: 'backup_config_get',
1549 expect
: { config
: '' }
1552 setBackupConfig
: _luci2
.rpc
.declare({
1553 object
: 'luci2.system',
1554 method
: 'backup_config_set',
1559 listBackup
: _luci2
.rpc
.declare({
1560 object
: 'luci2.system',
1561 method
: 'backup_list',
1562 expect
: { files
: [ ] }
1566 testReset
: _luci2
.rpc
.declare({
1567 object
: 'luci2.system',
1568 method
: 'reset_test',
1569 expect
: { supported
: false }
1572 startReset
: _luci2
.rpc
.declare({
1573 object
: 'luci2.system',
1574 method
: 'reset_start'
1578 performReboot
: _luci2
.rpc
.declare({
1579 object
: 'luci2.system',
1585 updateLists
: _luci2
.rpc
.declare({
1586 object
: 'luci2.opkg',
1591 _allPackages
: _luci2
.rpc
.declare({
1592 object
: 'luci2.opkg',
1594 params
: [ 'offset', 'limit', 'pattern' ],
1598 _installedPackages
: _luci2
.rpc
.declare({
1599 object
: 'luci2.opkg',
1600 method
: 'list_installed',
1601 params
: [ 'offset', 'limit', 'pattern' ],
1605 _findPackages
: _luci2
.rpc
.declare({
1606 object
: 'luci2.opkg',
1608 params
: [ 'offset', 'limit', 'pattern' ],
1612 _fetchPackages: function(action
, offset
, limit
, pattern
)
1616 return action(offset
, limit
, pattern
).then(function(list
) {
1617 if (!list
.total
|| !list
.packages
)
1618 return { length
: 0, total
: 0 };
1620 packages
.push
.apply(packages
, list
.packages
);
1621 packages
.total
= list
.total
;
1626 if (packages
.length
>= limit
)
1631 for (var i
= offset
+ packages
.length
; i
< limit
; i
+= 100)
1632 action(i
, (Math
.min(i
+ 100, limit
) % 100) || 100, pattern
);
1634 return _luci2
.rpc
.flush();
1635 }).then(function(lists
) {
1636 for (var i
= 0; i
< lists
.length
; i
++)
1638 if (!lists
[i
].total
|| !lists
[i
].packages
)
1641 packages
.push
.apply(packages
, lists
[i
].packages
);
1642 packages
.total
= lists
[i
].total
;
1649 listPackages: function(offset
, limit
, pattern
)
1651 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._allPackages
, offset
, limit
, pattern
);
1654 installedPackages: function(offset
, limit
, pattern
)
1656 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._installedPackages
, offset
, limit
, pattern
);
1659 findPackages: function(offset
, limit
, pattern
)
1661 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._findPackages
, offset
, limit
, pattern
);
1664 installPackage
: _luci2
.rpc
.declare({
1665 object
: 'luci2.opkg',
1667 params
: [ 'package' ],
1671 removePackage
: _luci2
.rpc
.declare({
1672 object
: 'luci2.opkg',
1674 params
: [ 'package' ],
1678 getConfig
: _luci2
.rpc
.declare({
1679 object
: 'luci2.opkg',
1680 method
: 'config_get',
1681 expect
: { config
: '' }
1684 setConfig
: _luci2
.rpc
.declare({
1685 object
: 'luci2.opkg',
1686 method
: 'config_set',
1693 login
: _luci2
.rpc
.declare({
1696 params
: [ 'username', 'password' ],
1700 access
: _luci2
.rpc
.declare({
1703 params
: [ 'scope', 'object', 'function' ],
1704 expect
: { access
: false }
1709 return _luci2
.session
.access('ubus', 'session', 'access');
1712 startHeartbeat: function()
1714 this._hearbeatInterval
= window
.setInterval(function() {
1715 _luci2
.session
.isAlive().then(function(alive
) {
1718 _luci2
.session
.stopHeartbeat();
1719 _luci2
.ui
.login(true);
1723 }, _luci2
.globals
.timeout
* 2);
1726 stopHeartbeat: function()
1728 if (typeof(this._hearbeatInterval
) != 'undefined')
1730 window
.clearInterval(this._hearbeatInterval
);
1731 delete this._hearbeatInterval
;
1738 saveScrollTop: function()
1740 this._scroll_top
= $(document
).scrollTop();
1743 restoreScrollTop: function()
1745 if (typeof(this._scroll_top
) == 'undefined')
1748 $(document
).scrollTop(this._scroll_top
);
1750 delete this._scroll_top
;
1753 loading: function(enable
)
1755 var win
= $(window
);
1756 var body
= $('body');
1758 var state
= _luci2
.ui
._loading
|| (_luci2
.ui
._loading
= {
1760 .addClass('modal fade')
1761 .append($('<div />')
1762 .addClass('modal-dialog')
1763 .append($('<div />')
1764 .addClass('modal-content luci2-modal-loader')
1765 .append($('<div />')
1766 .addClass('modal-body')
1767 .text(_luci2
.tr('Loading data…')))))
1775 state
.modal
.modal(enable
? 'show' : 'hide');
1778 dialog: function(title
, content
, options
)
1780 var win
= $(window
);
1781 var body
= $('body');
1783 var state
= _luci2
.ui
._dialog
|| (_luci2
.ui
._dialog
= {
1784 dialog
: $('<div />')
1785 .addClass('modal fade')
1786 .append($('<div />')
1787 .addClass('modal-dialog')
1788 .append($('<div />')
1789 .addClass('modal-content')
1790 .append($('<div />')
1791 .addClass('modal-header')
1793 .addClass('modal-title'))
1794 .append($('<div />')
1795 .addClass('modal-body'))
1796 .append($('<div />')
1797 .addClass('modal-footer')
1798 .append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
1800 $(this).parents('div.modal').modal('hide');
1805 if (typeof(options
) != 'object')
1808 if (title
=== false)
1810 state
.dialog
.modal('hide');
1815 var cnt
= state
.dialog
.children().children().children('div.modal-body');
1816 var ftr
= state
.dialog
.children().children().children('div.modal-footer');
1820 if (options
.style
== 'confirm')
1822 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Ok'), 'primary')
1823 .click(options
.confirm
|| function() { _luci2
.ui
.dialog(false) }));
1825 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Cancel'), 'default')
1826 .click(options
.cancel
|| function() { _luci2
.ui
.dialog(false) }));
1828 else if (options
.style
== 'close')
1830 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
1831 .click(options
.close
|| function() { _luci2
.ui
.dialog(false) }));
1833 else if (options
.style
== 'wait')
1835 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
1836 .attr('disabled', true));
1839 state
.dialog
.find('h4:first').text(title
);
1840 state
.dialog
.modal('show');
1842 cnt
.empty().append(content
);
1845 upload: function(title
, content
, options
)
1847 var state
= _luci2
.ui
._upload
|| (_luci2
.ui
._upload
= {
1849 .attr('method', 'post')
1850 .attr('action', '/cgi-bin/luci-upload')
1851 .attr('enctype', 'multipart/form-data')
1852 .attr('target', 'cbi-fileupload-frame')
1854 .append($('<input />')
1855 .attr('type', 'hidden')
1856 .attr('name', 'sessionid'))
1857 .append($('<input />')
1858 .attr('type', 'hidden')
1859 .attr('name', 'filename'))
1860 .append($('<input />')
1861 .attr('type', 'file')
1862 .attr('name', 'filedata')
1863 .addClass('cbi-input-file'))
1864 .append($('<div />')
1865 .css('width', '100%')
1866 .addClass('progress progress-striped active')
1867 .append($('<div />')
1868 .addClass('progress-bar')
1869 .css('width', '100%')))
1870 .append($('<iframe />')
1871 .addClass('pull-right')
1872 .attr('name', 'cbi-fileupload-frame')
1873 .css('width', '1px')
1874 .css('height', '1px')
1875 .css('visibility', 'hidden')),
1877 finish_cb: function(ev
) {
1878 $(this).off('load');
1880 var body
= (this.contentDocument
|| this.contentWindow
.document
).body
;
1881 if (body
.firstChild
.tagName
.toLowerCase() == 'pre')
1882 body
= body
.firstChild
;
1886 json
= $.parseJSON(body
.innerHTML
);
1889 message
: _luci2
.tr('Invalid server response received'),
1890 error
: [ -1, _luci2
.tr('Invalid data') ]
1896 L
.ui
.dialog(L
.tr('File upload'), [
1897 $('<p />').text(_luci2
.tr('The file upload failed with the server response below:')),
1898 $('<pre />').addClass('alert-message').text(json
.message
|| json
.error
[1]),
1899 $('<p />').text(_luci2
.tr('In case of network problems try uploading the file again.'))
1900 ], { style
: 'close' });
1902 else if (typeof(state
.success_cb
) == 'function')
1904 state
.success_cb(json
);
1908 confirm_cb: function() {
1909 var f
= state
.form
.find('.cbi-input-file');
1910 var b
= state
.form
.find('.progress');
1911 var p
= state
.form
.find('p');
1916 state
.form
.find('iframe').on('load', state
.finish_cb
);
1917 state
.form
.submit();
1921 p
.text(_luci2
.tr('File upload in progress …'));
1923 state
.form
.parent().parent().find('button').prop('disabled', true);
1927 state
.form
.find('.progress').hide();
1928 state
.form
.find('.cbi-input-file').val('').show();
1929 state
.form
.find('p').text(content
|| _luci2
.tr('Select the file to upload and press "%s" to proceed.').format(_luci2
.tr('Ok')));
1931 state
.form
.find('[name=sessionid]').val(_luci2
.globals
.sid
);
1932 state
.form
.find('[name=filename]').val(options
.filename
);
1934 state
.success_cb
= options
.success
;
1936 _luci2
.ui
.dialog(title
|| _luci2
.tr('File upload'), state
.form
, {
1938 confirm
: state
.confirm_cb
1942 reconnect: function()
1944 var protocols
= (location
.protocol
== 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1945 var ports
= (location
.protocol
== 'https:') ? [ 80, location
.port
|| 443 ] : [ location
.port
|| 80 ];
1946 var address
= location
.hostname
.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location
.hostname
+ ']' : location
.hostname
;
1948 var interval
, timeout
;
1951 _luci2
.tr('Waiting for device'), [
1952 $('<p />').text(_luci2
.tr('Please stand by while the device is reconfiguring …')),
1954 .css('width', '100%')
1955 .addClass('progressbar')
1956 .addClass('intermediate')
1957 .append($('<div />')
1958 .css('width', '100%'))
1959 ], { style
: 'wait' }
1962 for (var i
= 0; i
< protocols
.length
; i
++)
1963 images
= images
.add($('<img />').attr('url', protocols
[i
] + '://' + address
+ ':' + ports
[i
]));
1965 //_luci2.network.getNetworkStatus(function(s) {
1966 // for (var i = 0; i < protocols.length; i++)
1968 // for (var j = 0; j < s.length; j++)
1970 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1971 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1973 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1974 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1977 //}).then(function() {
1978 images
.on('load', function() {
1979 var url
= this.getAttribute('url');
1980 _luci2
.session
.isAlive().then(function(access
) {
1983 window
.clearTimeout(timeout
);
1984 window
.clearInterval(interval
);
1985 _luci2
.ui
.dialog(false);
1990 location
.href
= url
;
1995 interval
= window
.setInterval(function() {
1996 images
.each(function() {
1997 this.setAttribute('src', this.getAttribute('url') + _luci2
.globals
.resource
+ '/icons/loading.gif?r=' + Math
.random());
2001 timeout
= window
.setTimeout(function() {
2002 window
.clearInterval(interval
);
2006 _luci2
.tr('Device not responding'),
2007 _luci2
.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2014 login: function(invalid
)
2016 var state
= _luci2
.ui
._login
|| (_luci2
.ui
._login
= {
2019 .attr('method', 'post')
2021 .addClass('alert-message')
2022 .text(_luci2
.tr('Wrong username or password given!')))
2024 .append($('<label />')
2025 .text(_luci2
.tr('Username'))
2026 .append($('<br />'))
2027 .append($('<input />')
2028 .attr('type', 'text')
2029 .attr('name', 'username')
2030 .attr('value', 'root')
2031 .addClass('form-control')
2032 .keypress(function(ev
) {
2033 if (ev
.which
== 10 || ev
.which
== 13)
2037 .append($('<label />')
2038 .text(_luci2
.tr('Password'))
2039 .append($('<br />'))
2040 .append($('<input />')
2041 .attr('type', 'password')
2042 .attr('name', 'password')
2043 .addClass('form-control')
2044 .keypress(function(ev
) {
2045 if (ev
.which
== 10 || ev
.which
== 13)
2049 .text(_luci2
.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2
.tr('Ok')))),
2051 response_cb: function(response
) {
2052 if (!response
.ubus_rpc_session
)
2054 _luci2
.ui
.login(true);
2058 _luci2
.globals
.sid
= response
.ubus_rpc_session
;
2059 _luci2
.setHash('id', _luci2
.globals
.sid
);
2060 _luci2
.session
.startHeartbeat();
2061 _luci2
.ui
.dialog(false);
2062 state
.deferred
.resolve();
2066 confirm_cb: function() {
2067 var u
= state
.form
.find('[name=username]').val();
2068 var p
= state
.form
.find('[name=password]').val();
2074 _luci2
.tr('Logging in'), [
2075 $('<p />').text(_luci2
.tr('Log in in progress …')),
2077 .css('width', '100%')
2078 .addClass('progressbar')
2079 .addClass('intermediate')
2080 .append($('<div />')
2081 .css('width', '100%'))
2082 ], { style
: 'wait' }
2085 _luci2
.globals
.sid
= '00000000000000000000000000000000';
2086 _luci2
.session
.login(u
, p
).then(state
.response_cb
);
2090 if (!state
.deferred
|| state
.deferred
.state() != 'pending')
2091 state
.deferred
= $.Deferred();
2093 /* try to find sid from hash */
2094 var sid
= _luci2
.getHash('id');
2095 if (sid
&& sid
.match(/^[a-f0-9]{32}$/))
2097 _luci2
.globals
.sid
= sid
;
2098 _luci2
.session
.isAlive().then(function(access
) {
2101 _luci2
.session
.startHeartbeat();
2102 state
.deferred
.resolve();
2106 _luci2
.setHash('id', undefined);
2111 return state
.deferred
;
2115 state
.form
.find('.alert-message').show();
2117 state
.form
.find('.alert-message').hide();
2119 _luci2
.ui
.dialog(_luci2
.tr('Authorization Required'), state
.form
, {
2121 confirm
: state
.confirm_cb
2124 state
.form
.find('[name=password]').focus();
2126 return state
.deferred
;
2129 cryptPassword
: _luci2
.rpc
.declare({
2133 expect
: { crypt
: '' }
2137 _acl_merge_scope: function(acl_scope
, scope
)
2139 if ($.isArray(scope
))
2141 for (var i
= 0; i
< scope
.length
; i
++)
2142 acl_scope
[scope
[i
]] = true;
2144 else if ($.isPlainObject(scope
))
2146 for (var object_name
in scope
)
2148 if (!$.isArray(scope
[object_name
]))
2151 var acl_object
= acl_scope
[object_name
] || (acl_scope
[object_name
] = { });
2153 for (var i
= 0; i
< scope
[object_name
].length
; i
++)
2154 acl_object
[scope
[object_name
][i
]] = true;
2159 _acl_merge_permission: function(acl_perm
, perm
)
2161 if ($.isPlainObject(perm
))
2163 for (var scope_name
in perm
)
2165 var acl_scope
= acl_perm
[scope_name
] || (acl_perm
[scope_name
] = { });
2166 this._acl_merge_scope(acl_scope
, perm
[scope_name
]);
2171 _acl_merge_group: function(acl_group
, group
)
2173 if ($.isPlainObject(group
))
2175 if (!acl_group
.description
)
2176 acl_group
.description
= group
.description
;
2180 var acl_perm
= acl_group
.read
|| (acl_group
.read
= { });
2181 this._acl_merge_permission(acl_perm
, group
.read
);
2186 var acl_perm
= acl_group
.write
|| (acl_group
.write
= { });
2187 this._acl_merge_permission(acl_perm
, group
.write
);
2192 _acl_merge_tree: function(acl_tree
, tree
)
2194 if ($.isPlainObject(tree
))
2196 for (var group_name
in tree
)
2198 var acl_group
= acl_tree
[group_name
] || (acl_tree
[group_name
] = { });
2199 this._acl_merge_group(acl_group
, tree
[group_name
]);
2204 listAvailableACLs
: _luci2
.rpc
.declare({
2207 expect
: { acls
: [ ] },
2208 filter: function(trees
) {
2210 for (var i
= 0; i
< trees
.length
; i
++)
2211 _luci2
.ui
._acl_merge_tree(acl_tree
, trees
[i
]);
2216 renderMainMenu
: _luci2
.rpc
.declare({
2219 expect
: { menu
: { } },
2220 filter: function(entries
) {
2221 _luci2
.globals
.mainMenu
= new _luci2
.ui
.menu();
2222 _luci2
.globals
.mainMenu
.entries(entries
);
2226 .append(_luci2
.globals
.mainMenu
.render(0, 1));
2230 renderViewMenu: function()
2234 .append(_luci2
.globals
.mainMenu
.render(2, 900));
2237 renderView: function()
2239 var node
= arguments
[0];
2240 var name
= node
.view
.split(/\//).join('.');
2243 for (var i
= 1; i
< arguments
.length
; i
++)
2244 args
.push(arguments
[i
]);
2246 if (_luci2
.globals
.currentView
)
2247 _luci2
.globals
.currentView
.finish();
2249 _luci2
.ui
.renderViewMenu();
2252 _luci2
._views
= { };
2254 _luci2
.setHash('view', node
.view
);
2256 if (_luci2
._views
[name
] instanceof _luci2
.ui
.view
)
2258 _luci2
.globals
.currentView
= _luci2
._views
[name
];
2259 return _luci2
._views
[name
].render
.apply(_luci2
._views
[name
], args
);
2262 var url
= _luci2
.globals
.resource
+ '/view/' + name
+ '.js';
2264 return $.ajax(url
, {
2268 }).then(function(data
) {
2270 var viewConstructorSource
= (
2271 '(function(L, $) { ' +
2273 '})(_luci2, $);\n\n' +
2275 ).format(data
, url
);
2277 var viewConstructor
= eval(viewConstructorSource
);
2279 _luci2
._views
[name
] = new viewConstructor({
2281 acls
: node
.write
|| { }
2284 _luci2
.globals
.currentView
= _luci2
._views
[name
];
2285 return _luci2
._views
[name
].render
.apply(_luci2
._views
[name
], args
);
2288 alert('Unable to instantiate view "%s": %s'.format(url
, e
));
2291 return $.Deferred().resolve();
2295 updateHostname: function()
2297 return _luci2
.system
.getBoardInfo().then(function(info
) {
2299 $('#hostname').text(info
.hostname
);
2303 updateChanges: function()
2305 return _luci2
.uci
.changes().then(function(changes
) {
2309 for (var config
in changes
)
2313 for (var i
= 0; i
< changes
[config
].length
; i
++)
2315 var c
= changes
[config
][i
];
2324 log
.push('uci delete %s.<del>%s</del>'.format(config
, c
[1]));
2326 log
.push('uci delete %s.%s.<del>%s</del>'.format(config
, c
[1], c
[2]));
2331 log
.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3]));
2333 log
.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2337 log
.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config
, c
[2], c
[1]));
2341 log
.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2345 log
.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2350 log
.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
2352 log
.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2357 html
+= '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config
, log
.join('\n'));
2358 n
+= changes
[config
].length
;
2369 .text(_luci2
.trcp('Pending configuration changes', '1 change', '%d changes', n
).format(n
))
2370 .click(function(ev
) {
2371 _luci2
.ui
.dialog(_luci2
.tr('Staged configuration changes'), html
, { style
: 'close' });
2372 ev
.preventDefault();
2382 _luci2
.ui
.loading(true);
2385 _luci2
.ui
.updateHostname(),
2386 _luci2
.ui
.updateChanges(),
2387 _luci2
.ui
.renderMainMenu()
2389 _luci2
.ui
.renderView(_luci2
.globals
.defaultNode
).then(function() {
2390 _luci2
.ui
.loading(false);
2395 button: function(label
, style
, title
)
2397 style
= style
|| 'default';
2399 return $('<button />')
2400 .attr('type', 'button')
2401 .attr('title', title
? title
: '')
2402 .addClass('btn btn-' + style
)
2407 this.ui
.AbstractWidget
= Class
.extend({
2408 i18n: function(text
) {
2413 var key
= arguments
[0];
2416 for (var i
= 1; i
< arguments
.length
; i
++)
2417 args
.push(arguments
[i
]);
2419 switch (typeof(this.options
[key
]))
2425 return this.options
[key
].apply(this, args
);
2428 return ''.format
.apply('' + this.options
[key
], args
);
2432 toString: function() {
2433 return $('<div />').append(this.render()).html();
2436 insertInto: function(id
) {
2437 return $(id
).empty().append(this.render());
2440 appendTo: function(id
) {
2441 return $(id
).append(this.render());
2445 this.ui
.view
= this.ui
.AbstractWidget
.extend({
2446 _fetch_template: function()
2448 return $.ajax(_luci2
.globals
.resource
+ '/template/' + this.options
.name
+ '.htm', {
2452 success: function(data
) {
2453 data
= data
.replace(/<%([#:=])?(.+?)%>/g, function(match
, p1
, p2
) {
2454 p2
= p2
.replace(/^\s+/, '').replace(/\s+$/, '');
2461 return _luci2
.tr(p2
);
2464 return _luci2
.globals
[p2
] || '';
2467 return '(?' + match
+ ')';
2471 $('#maincontent').append(data
);
2478 throw "Not implemented";
2483 var container
= $('#maincontent');
2488 container
.append($('<h2 />').append(this.title
));
2490 if (this.description
)
2491 container
.append($('<p />').append(this.description
));
2496 for (var i
= 0; i
< arguments
.length
; i
++)
2497 args
.push(arguments
[i
]);
2499 return this._fetch_template().then(function() {
2500 return _luci2
.deferrable(self
.execute
.apply(self
, args
));
2504 repeat: function(func
, interval
)
2508 if (!self
._timeouts
)
2509 self
._timeouts
= [ ];
2511 var index
= self
._timeouts
.length
;
2513 if (typeof(interval
) != 'number')
2516 var setTimer
, runTimer
;
2518 setTimer = function() {
2520 self
._timeouts
[index
] = window
.setTimeout(runTimer
, interval
);
2523 runTimer = function() {
2524 _luci2
.deferrable(func
.call(self
)).then(setTimer
, setTimer
);
2532 if ($.isArray(this._timeouts
))
2534 for (var i
= 0; i
< this._timeouts
.length
; i
++)
2535 window
.clearTimeout(this._timeouts
[i
]);
2537 delete this._timeouts
;
2542 this.ui
.menu
= this.ui
.AbstractWidget
.extend({
2547 entries: function(entries
)
2549 for (var entry
in entries
)
2551 var path
= entry
.split(/\//);
2552 var node
= this._nodes
;
2554 for (i
= 0; i
< path
.length
; i
++)
2559 if (!node
.childs
[path
[i
]])
2560 node
.childs
[path
[i
]] = { };
2562 node
= node
.childs
[path
[i
]];
2565 $.extend(node
, entries
[entry
]);
2569 _indexcmp: function(a
, b
)
2571 var x
= a
.index
|| 0;
2572 var y
= b
.index
|| 0;
2576 firstChildView: function(node
)
2582 for (var child
in (node
.childs
|| { }))
2583 nodes
.push(node
.childs
[child
]);
2585 nodes
.sort(this._indexcmp
);
2587 for (var i
= 0; i
< nodes
.length
; i
++)
2589 var child
= this.firstChildView(nodes
[i
]);
2592 for (var key
in child
)
2593 if (!node
.hasOwnProperty(key
) && child
.hasOwnProperty(key
))
2594 node
[key
] = child
[key
];
2603 _onclick: function(ev
)
2605 _luci2
.ui
.loading(true);
2606 _luci2
.ui
.renderView(ev
.data
).then(function() {
2607 _luci2
.ui
.loading(false);
2610 ev
.preventDefault();
2614 _render: function(childs
, level
, min
, max
)
2617 for (var node
in childs
)
2619 var child
= this.firstChildView(childs
[node
]);
2621 nodes
.push(childs
[node
]);
2624 nodes
.sort(this._indexcmp
);
2626 var list
= $('<ul />');
2629 list
.addClass('nav').addClass('navbar-nav');
2630 else if (level
== 1)
2631 list
.addClass('dropdown-menu').addClass('navbar-inverse');
2633 for (var i
= 0; i
< nodes
.length
; i
++)
2635 if (!_luci2
.globals
.defaultNode
)
2637 var v
= _luci2
.getHash('view');
2638 if (!v
|| v
== nodes
[i
].view
)
2639 _luci2
.globals
.defaultNode
= nodes
[i
];
2642 var item
= $('<li />')
2645 .text(_luci2
.tr(nodes
[i
].title
)))
2648 if (nodes
[i
].childs
&& level
< max
)
2650 item
.addClass('dropdown');
2653 .addClass('dropdown-toggle')
2654 .attr('data-toggle', 'dropdown')
2655 .append('<b class="caret"></b>');
2657 item
.append(this._render(nodes
[i
].childs
, level
+ 1));
2661 item
.find('a').click(nodes
[i
], this._onclick
);
2668 render: function(min
, max
)
2670 var top
= min
? this.getNode(_luci2
.globals
.defaultNode
.view
, min
) : this._nodes
;
2671 return this._render(top
.childs
, 0, min
, max
);
2674 getNode: function(path
, max
)
2676 var p
= path
.split(/\//);
2677 var n
= this._nodes
;
2679 if (typeof(max
) == 'undefined')
2682 for (var i
= 0; i
< max
; i
++)
2684 if (!n
.childs
[p
[i
]])
2694 this.ui
.table
= this.ui
.AbstractWidget
.extend({
2700 row: function(values
)
2702 if ($.isArray(values
))
2704 this._rows
.push(values
);
2706 else if ($.isPlainObject(values
))
2709 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2711 var col
= this.options
.columns
[i
];
2713 if (typeof col
.key
== 'string')
2714 v
.push(values
[col
.key
]);
2722 rows: function(rows
)
2724 for (var i
= 0; i
< rows
.length
; i
++)
2728 render: function(id
)
2730 var fieldset
= document
.createElement('fieldset');
2731 fieldset
.className
= 'cbi-section';
2733 if (this.options
.caption
)
2735 var legend
= document
.createElement('legend');
2736 $(legend
).append(this.options
.caption
);
2737 fieldset
.appendChild(legend
);
2740 var table
= document
.createElement('table');
2741 table
.className
= 'table table-condensed table-hover';
2743 var has_caption
= false;
2744 var has_description
= false;
2746 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2747 if (this.options
.columns
[i
].caption
)
2752 else if (this.options
.columns
[i
].description
)
2754 has_description
= true;
2760 var tr
= table
.insertRow(-1);
2761 tr
.className
= 'cbi-section-table-titles';
2763 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2765 var col
= this.options
.columns
[i
];
2766 var th
= document
.createElement('th');
2767 th
.className
= 'cbi-section-table-cell';
2772 th
.style
.width
= col
.width
;
2775 th
.style
.textAlign
= col
.align
;
2778 $(th
).append(col
.caption
);
2782 if (has_description
)
2784 var tr
= table
.insertRow(-1);
2785 tr
.className
= 'cbi-section-table-descr';
2787 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2789 var col
= this.options
.columns
[i
];
2790 var th
= document
.createElement('th');
2791 th
.className
= 'cbi-section-table-cell';
2796 th
.style
.width
= col
.width
;
2799 th
.style
.textAlign
= col
.align
;
2801 if (col
.description
)
2802 $(th
).append(col
.description
);
2806 if (this._rows
.length
== 0)
2808 if (this.options
.placeholder
)
2810 var tr
= table
.insertRow(-1);
2811 var td
= tr
.insertCell(-1);
2812 td
.className
= 'cbi-section-table-cell';
2814 td
.colSpan
= this.options
.columns
.length
;
2815 $(td
).append(this.options
.placeholder
);
2820 for (var i
= 0; i
< this._rows
.length
; i
++)
2822 var tr
= table
.insertRow(-1);
2824 for (var j
= 0; j
< this.options
.columns
.length
; j
++)
2826 var col
= this.options
.columns
[j
];
2827 var td
= tr
.insertCell(-1);
2829 var val
= this._rows
[i
][j
];
2831 if (typeof(val
) == 'undefined')
2832 val
= col
.placeholder
;
2834 if (typeof(val
) == 'undefined')
2838 td
.style
.width
= col
.width
;
2841 td
.style
.textAlign
= col
.align
;
2843 if (typeof col
.format
== 'string')
2844 $(td
).append(col
.format
.format(val
));
2845 else if (typeof col
.format
== 'function')
2846 $(td
).append(col
.format(val
, i
));
2854 fieldset
.appendChild(table
);
2860 this.ui
.progress
= this.ui
.AbstractWidget
.extend({
2863 var vn
= parseInt(this.options
.value
) || 0;
2864 var mn
= parseInt(this.options
.max
) || 100;
2865 var pc
= Math
.floor((100 / mn
) * vn
);
2869 if (typeof(this.options
.format
) == 'string')
2870 text
= this.options
.format
.format(this.options
.value
, this.options
.max
, pc
);
2871 else if (typeof(this.options
.format
) == 'function')
2872 text
= this.options
.format(pc
);
2874 text
= '%.2f%%'.format(pc
);
2877 .addClass('progress')
2878 .append($('<div />')
2879 .addClass('progress-bar')
2880 .addClass('progress-bar-info')
2881 .css('width', pc
+ '%'))
2882 .append($('<small />')
2887 this.ui
.devicebadge
= this.ui
.AbstractWidget
.extend({
2890 var l2dev
= this.options
.l2_device
|| this.options
.device
;
2891 var l3dev
= this.options
.l3_device
;
2892 var dev
= l3dev
|| l2dev
|| '?';
2894 var span
= document
.createElement('span');
2895 span
.className
= 'badge';
2897 if (typeof(this.options
.signal
) == 'number' ||
2898 typeof(this.options
.noise
) == 'number')
2901 if (typeof(this.options
.signal
) != 'undefined' &&
2902 typeof(this.options
.noise
) != 'undefined')
2904 var q
= (-1 * (this.options
.noise
- this.options
.signal
)) / 5;
2917 span
.appendChild(document
.createElement('img'));
2918 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/signal-' + r
+ '.png';
2921 span
.title
= _luci2
.tr('No signal');
2923 span
.title
= '%s: %d %s / %s: %d %s'.format(
2924 _luci2
.tr('Signal'), this.options
.signal
, _luci2
.tr('dBm'),
2925 _luci2
.tr('Noise'), this.options
.noise
, _luci2
.tr('dBm')
2930 var type
= 'ethernet';
2931 var desc
= _luci2
.tr('Ethernet device');
2936 desc
= _luci2
.tr('Tunnel interface');
2938 else if (dev
.indexOf('br-') == 0)
2941 desc
= _luci2
.tr('Bridge');
2943 else if (dev
.indexOf('.') > 0)
2946 desc
= _luci2
.tr('VLAN interface');
2948 else if (dev
.indexOf('wlan') == 0 ||
2949 dev
.indexOf('ath') == 0 ||
2950 dev
.indexOf('wl') == 0)
2953 desc
= _luci2
.tr('Wireless Network');
2956 span
.appendChild(document
.createElement('img'));
2957 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/' + type
+ (this.options
.up
? '' : '_disabled') + '.png';
2961 $(span
).append(' ');
2962 $(span
).append(dev
);
2968 var type = function(f
, l
)
2978 _luci2
.cbi
.validation
.message
= _luci2
.tr(msg
);
2981 compile: function(code
)
2986 var types
= _luci2
.cbi
.validation
.types
;
2991 for (var i
= 0; i
< code
.length
; i
++)
2999 switch (code
.charCodeAt(i
))
3011 var label
= code
.substring(pos
, i
);
3012 label
= label
.replace(/\\(.)/g, '$1');
3013 label
= label
.replace(/^[ \t]+/g, '');
3014 label
= label
.replace(/[ \t]+$/g, '');
3016 if (label
&& !isNaN(label
))
3018 stack
.push(parseFloat(label
));
3020 else if (label
.match(/^(['"]).*\1$/))
3022 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
3024 else if (typeof types
[label
] == 'function')
3026 stack
.push(types
[label
]);
3031 throw "Syntax error, unhandled token '"+label
+"'";
3036 depth
+= (code
.charCodeAt(i
) == 40);
3042 if (typeof stack
[stack
.length
-2] != 'function')
3043 throw "Syntax error, argument list follows non-function";
3045 stack
[stack
.length
-1] =
3046 _luci2
.cbi
.validation
.compile(code
.substring(pos
, i
));
3059 var validation
= this.cbi
.validation
;
3061 validation
.types
= {
3062 'integer': function()
3064 if (this.match(/^-?[0-9]+$/) != null)
3067 validation
.i18n('Must be a valid integer');
3071 'uinteger': function()
3073 if (validation
.types
['integer'].apply(this) && (this >= 0))
3076 validation
.i18n('Must be a positive integer');
3082 if (!isNaN(parseFloat(this)))
3085 validation
.i18n('Must be a valid number');
3089 'ufloat': function()
3091 if (validation
.types
['float'].apply(this) && (this >= 0))
3094 validation
.i18n('Must be a positive number');
3098 'ipaddr': function()
3100 if (validation
.types
['ip4addr'].apply(this) ||
3101 validation
.types
['ip6addr'].apply(this))
3104 validation
.i18n('Must be a valid IP address');
3108 'ip4addr': function()
3110 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
3112 if ((RegExp
.$1 >= 0) && (RegExp
.$1 <= 255) &&
3113 (RegExp
.$2 >= 0) && (RegExp
.$2 <= 255) &&
3114 (RegExp
.$3 >= 0) && (RegExp
.$3 <= 255) &&
3115 (RegExp
.$4 >= 0) && (RegExp
.$4 <= 255) &&
3116 ((RegExp
.$6.indexOf('.') < 0)
3117 ? ((RegExp
.$6 >= 0) && (RegExp
.$6 <= 32))
3118 : (validation
.types
['ip4addr'].apply(RegExp
.$6))))
3122 validation
.i18n('Must be a valid IPv4 address');
3126 'ip6addr': function()
3128 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
3130 if (!RegExp
.$2 || ((RegExp
.$3 >= 0) && (RegExp
.$3 <= 128)))
3132 var addr
= RegExp
.$1;
3139 if (addr
.indexOf('.') > 0)
3141 var off
= addr
.lastIndexOf(':');
3143 if (!(off
&& validation
.types
['ip4addr'].apply(addr
.substr(off
+1))))
3145 validation
.i18n('Must be a valid IPv6 address');
3149 addr
= addr
.substr(0, off
) + ':0:0';
3152 if (addr
.indexOf('::') >= 0)
3157 for (var i
= 1; i
< (addr
.length
-1); i
++)
3158 if (addr
.charAt(i
) == ':')
3163 validation
.i18n('Must be a valid IPv6 address');
3167 for (var i
= 0; i
< (7 - colons
); i
++)
3170 if (addr
.match(/^(.*?)::(.*?)$/))
3171 addr
= (RegExp
.$1 ? RegExp
.$1 + ':' : '') + fill
+
3172 (RegExp
.$2 ? ':' + RegExp
.$2 : '');
3175 if (addr
.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
3178 validation
.i18n('Must be a valid IPv6 address');
3183 validation
.i18n('Must be a valid IPv6 address');
3189 if (validation
.types
['integer'].apply(this) &&
3190 (this >= 0) && (this <= 65535))
3193 validation
.i18n('Must be a valid port number');
3197 'portrange': function()
3199 if (this.match(/^(\d+)-(\d+)$/))
3204 if (validation
.types
['port'].apply(p1
) &&
3205 validation
.types
['port'].apply(p2
) &&
3206 (parseInt(p1
) <= parseInt(p2
)))
3209 else if (validation
.types
['port'].apply(this))
3214 validation
.i18n('Must be a valid port range');
3218 'macaddr': function()
3220 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
3223 validation
.i18n('Must be a valid MAC address');
3229 if (validation
.types
['hostname'].apply(this) ||
3230 validation
.types
['ipaddr'].apply(this))
3233 validation
.i18n('Must be a valid hostname or IP address');
3237 'hostname': function()
3239 if ((this.length
<= 253) &&
3240 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
3241 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
3242 this.match(/[^0-9.]/)))))
3245 validation
.i18n('Must be a valid host name');
3249 'network': function()
3251 if (validation
.types
['uciname'].apply(this) ||
3252 validation
.types
['host'].apply(this))
3255 validation
.i18n('Must be a valid network name');
3259 'wpakey': function()
3263 if ((v
.length
== 64)
3264 ? (v
.match(/^[a-fA-F0-9]{64}$/) != null)
3265 : ((v
.length
>= 8) && (v
.length
<= 63)))
3268 validation
.i18n('Must be a valid WPA key');
3272 'wepkey': function()
3276 if (v
.substr(0,2) == 's:')
3279 if (((v
.length
== 10) || (v
.length
== 26))
3280 ? (v
.match(/^[a-fA-F0-9]{10,26}$/) != null)
3281 : ((v
.length
== 5) || (v
.length
== 13)))
3284 validation
.i18n('Must be a valid WEP key');
3288 'uciname': function()
3290 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
3293 validation
.i18n('Must be a valid UCI identifier');
3297 'range': function(min
, max
)
3299 var val
= parseFloat(this);
3301 if (validation
.types
['integer'].apply(this) &&
3302 !isNaN(min
) && !isNaN(max
) && ((val
>= min
) && (val
<= max
)))
3305 validation
.i18n('Must be a number between %d and %d');
3309 'min': function(min
)
3311 var val
= parseFloat(this);
3313 if (validation
.types
['integer'].apply(this) &&
3314 !isNaN(min
) && !isNaN(val
) && (val
>= min
))
3317 validation
.i18n('Must be a number greater or equal to %d');
3321 'max': function(max
)
3323 var val
= parseFloat(this);
3325 if (validation
.types
['integer'].apply(this) &&
3326 !isNaN(max
) && !isNaN(val
) && (val
<= max
))
3329 validation
.i18n('Must be a number lower or equal to %d');
3333 'rangelength': function(min
, max
)
3335 var val
= '' + this;
3337 if (!isNaN(min
) && !isNaN(max
) &&
3338 (val
.length
>= min
) && (val
.length
<= max
))
3341 validation
.i18n('Must be between %d and %d characters');
3345 'minlength': function(min
)
3347 var val
= '' + this;
3349 if (!isNaN(min
) && (val
.length
>= min
))
3352 validation
.i18n('Must be at least %d characters');
3356 'maxlength': function(max
)
3358 var val
= '' + this;
3360 if (!isNaN(max
) && (val
.length
<= max
))
3363 validation
.i18n('Must be at most %d characters');
3371 for (var i
= 0; i
< arguments
.length
; i
+= 2)
3373 delete validation
.message
;
3375 if (typeof(arguments
[i
]) != 'function')
3377 if (arguments
[i
] == this)
3381 else if (arguments
[i
].apply(this, arguments
[i
+1]))
3386 if (validation
.message
)
3387 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
3390 validation
.message
= msgs
.join( _luci2
.tr(' - or - '));
3398 for (var i
= 0; i
< arguments
.length
; i
+= 2)
3400 delete validation
.message
;
3402 if (typeof arguments
[i
] != 'function')
3404 if (arguments
[i
] != this)
3408 else if (!arguments
[i
].apply(this, arguments
[i
+1]))
3413 if (validation
.message
)
3414 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
3417 validation
.message
= msgs
.join(', ');
3423 return validation
.types
['or'].apply(
3424 this.replace(/^[ \t]*![ \t]*/, ''), arguments
);
3427 'list': function(subvalidator
, subargs
)
3429 if (typeof subvalidator
!= 'function')
3432 var tokens
= this.match(/[^ \t]+/g);
3433 for (var i
= 0; i
< tokens
.length
; i
++)
3434 if (!subvalidator
.apply(tokens
[i
], subargs
))
3440 'phonedigit': function()
3442 if (this.match(/^[0-9\*#!\.]+$/) != null)
3445 validation
.i18n('Must be a valid phone number digit');
3449 'string': function()
3456 this.cbi
.AbstractValue
= this.ui
.AbstractWidget
.extend({
3457 init: function(name
, options
)
3460 this.instance
= { };
3461 this.dependencies
= [ ];
3462 this.rdependency
= { };
3464 this.options
= _luci2
.defaults(options
, {
3474 return this.section
.id('field', sid
|| '__unknown__', this.name
);
3477 render: function(sid
, condensed
)
3479 var i
= this.instance
[sid
] = { };
3481 i
.top
= $('<div />');
3485 i
.top
.addClass('form-group');
3487 if (typeof(this.options
.caption
) == 'string')
3489 .addClass('col-lg-2 control-label')
3490 .attr('for', this.id(sid
))
3491 .text(this.options
.caption
)
3495 i
.error
= $('<div />')
3497 .addClass('label label-danger');
3499 i
.widget
= $('<div />')
3501 .append(this.widget(sid
))
3507 i
.widget
.addClass('col-lg-5');
3510 .addClass('col-lg-5')
3511 .text((typeof(this.options
.description
) == 'string') ? this.options
.description
: '')
3518 ucipath: function(sid
)
3521 config
: (this.options
.uci_package
|| this.map
.uci_package
),
3522 section
: (this.options
.uci_section
|| sid
),
3523 option
: (this.options
.uci_option
|| this.name
)
3527 ucivalue: function(sid
)
3529 var uci
= this.ucipath(sid
);
3530 var val
= this.map
.get(uci
.config
, uci
.section
, uci
.option
);
3532 if (typeof(val
) == 'undefined')
3533 return this.options
.initial
;
3538 formvalue: function(sid
)
3540 var v
= $('#' + this.id(sid
)).val();
3541 return (v
=== '') ? undefined : v
;
3544 textvalue: function(sid
)
3546 var v
= this.formvalue(sid
);
3548 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
3549 v
= this.ucivalue(sid
);
3551 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
3552 v
= this.options
.placeholder
;
3554 if (typeof(v
) == 'undefined' || v
=== '')
3557 if (typeof(v
) == 'string' && $.isArray(this.choices
))
3559 for (var i
= 0; i
< this.choices
.length
; i
++)
3560 if (v
=== this.choices
[i
][0])
3561 return this.choices
[i
][1];
3563 else if (v
=== true)
3564 return _luci2
.tr('yes');
3565 else if (v
=== false)
3566 return _luci2
.tr('no');
3567 else if ($.isArray(v
))
3568 return v
.join(', ');
3573 changed: function(sid
)
3575 var a
= this.ucivalue(sid
);
3576 var b
= this.formvalue(sid
);
3578 if (typeof(a
) != typeof(b
))
3581 if (typeof(a
) == 'object')
3583 if (a
.length
!= b
.length
)
3586 for (var i
= 0; i
< a
.length
; i
++)
3598 var uci
= this.ucipath(sid
);
3600 if (this.instance
[sid
].disabled
)
3602 if (!this.options
.keep
)
3603 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3608 var chg
= this.changed(sid
);
3609 var val
= this.formvalue(sid
);
3612 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
);
3617 _ev_validate: function(ev
)
3621 var val
= d
.elem
.val();
3622 var vstack
= d
.vstack
;
3624 if (vstack
&& typeof(vstack
[0]) == 'function')
3626 delete validation
.message
;
3628 if ((val
.length
== 0 && !d
.opt
))
3630 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
3631 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
3633 d
.inst
.error
.text(_luci2
.tr('Field must not be empty')).show();
3636 else if (val
.length
> 0 && !vstack
[0].apply(val
, vstack
[1]))
3638 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
3639 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
3641 d
.inst
.error
.text(validation
.message
.format
.apply(validation
.message
, vstack
[1])).show();
3646 d
.elem
.parents('div.form-group, td').first().removeClass('luci2-form-error');
3647 d
.elem
.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
3649 if (d
.multi
&& d
.inst
.widget
&& d
.inst
.widget
.find('input.error, select.error').length
> 0)
3652 d
.inst
.error
.text('').hide();
3657 for (var field
in d
.self
.rdependency
)
3658 d
.self
.rdependency
[field
].toggle(d
.sid
);
3663 validator: function(sid
, elem
, multi
)
3665 if (typeof(this.options
.datatype
) == 'undefined' && $.isEmptyObject(this.rdependency
))
3669 if (typeof(this.options
.datatype
) == 'string')
3672 vstack
= _luci2
.cbi
.validation
.compile(this.options
.datatype
);
3675 else if (typeof(this.options
.datatype
) == 'function')
3677 var vfunc
= this.options
.datatype
;
3678 vstack
= [ function(elem
) {
3679 var rv
= vfunc(this, elem
);
3681 validation
.message
= rv
;
3682 return (rv
=== true);
3692 inst
: this.instance
[sid
],
3693 opt
: this.options
.optional
3696 if (elem
.prop('tagName') == 'SELECT')
3698 elem
.change(evdata
, this._ev_validate
);
3700 else if (elem
.prop('tagName') == 'INPUT' && elem
.attr('type') == 'checkbox')
3702 elem
.click(evdata
, this._ev_validate
);
3703 elem
.blur(evdata
, this._ev_validate
);
3707 elem
.keyup(evdata
, this._ev_validate
);
3708 elem
.blur(evdata
, this._ev_validate
);
3711 elem
.attr('cbi-validate', true).on('validate', evdata
, this._ev_validate
);
3716 validate: function(sid
)
3718 var i
= this.instance
[sid
];
3720 i
.widget
.find('[cbi-validate]').trigger('validate');
3722 return (i
.disabled
|| i
.error
.text() == '');
3725 depends: function(d
, v
)
3732 for (var i
= 0; i
< d
.length
; i
++)
3734 if (typeof(d
[i
]) == 'string')
3736 else if (d
[i
] instanceof _luci2
.cbi
.AbstractValue
)
3737 dep
[d
[i
].name
] = true;
3740 else if (d
instanceof _luci2
.cbi
.AbstractValue
)
3743 dep
[d
.name
] = (typeof(v
) == 'undefined') ? true : v
;
3745 else if (typeof(d
) == 'object')
3749 else if (typeof(d
) == 'string')
3752 dep
[d
] = (typeof(v
) == 'undefined') ? true : v
;
3755 if (!dep
|| $.isEmptyObject(dep
))
3758 for (var field
in dep
)
3760 var f
= this.section
.fields
[field
];
3762 f
.rdependency
[this.name
] = this;
3767 if ($.isEmptyObject(dep
))
3770 this.dependencies
.push(dep
);
3775 toggle: function(sid
)
3777 var d
= this.dependencies
;
3778 var i
= this.instance
[sid
];
3783 for (var n
= 0; n
< d
.length
; n
++)
3787 for (var field
in d
[n
])
3789 var val
= this.section
.fields
[field
].formvalue(sid
);
3790 var cmp
= d
[n
][field
];
3792 if (typeof(cmp
) == 'boolean')
3794 if (cmp
== (typeof(val
) == 'undefined' || val
=== '' || val
=== false))
3800 else if (typeof(cmp
) == 'string')
3808 else if (typeof(cmp
) == 'function')
3816 else if (cmp
instanceof RegExp
)
3841 i
.top
.is(':visible') ? i
.top
.fadeOut() : i
.top
.hide();
3848 this.cbi
.CheckboxValue
= this.cbi
.AbstractValue
.extend({
3849 widget: function(sid
)
3851 var o
= this.options
;
3853 if (typeof(o
.enabled
) == 'undefined') o
.enabled
= '1';
3854 if (typeof(o
.disabled
) == 'undefined') o
.disabled
= '0';
3856 var i
= $('<input />')
3857 .attr('id', this.id(sid
))
3858 .attr('type', 'checkbox')
3859 .prop('checked', this.ucivalue(sid
));
3862 .addClass('checkbox')
3863 .append(this.validator(sid
, i
));
3866 ucivalue: function(sid
)
3868 var v
= this.callSuper('ucivalue', sid
);
3870 if (typeof(v
) == 'boolean')
3873 return (v
== this.options
.enabled
);
3876 formvalue: function(sid
)
3878 var v
= $('#' + this.id(sid
)).prop('checked');
3880 if (typeof(v
) == 'undefined')
3881 return !!this.options
.initial
;
3888 var uci
= this.ucipath(sid
);
3890 if (this.instance
[sid
].disabled
)
3892 if (!this.options
.keep
)
3893 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3898 var chg
= this.changed(sid
);
3899 var val
= this.formvalue(sid
);
3903 if (this.options
.optional
&& val
== this.options
.initial
)
3904 this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3906 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
? this.options
.enabled
: this.options
.disabled
);
3913 this.cbi
.InputValue
= this.cbi
.AbstractValue
.extend({
3914 widget: function(sid
)
3916 var i
= $('<input />')
3917 .addClass('form-control')
3918 .attr('id', this.id(sid
))
3919 .attr('type', 'text')
3920 .attr('placeholder', this.options
.placeholder
)
3921 .val(this.ucivalue(sid
));
3923 return this.validator(sid
, i
);
3927 this.cbi
.PasswordValue
= this.cbi
.AbstractValue
.extend({
3928 widget: function(sid
)
3930 var i
= $('<input />')
3931 .addClass('form-control')
3932 .attr('id', this.id(sid
))
3933 .attr('type', 'password')
3934 .attr('placeholder', this.options
.placeholder
)
3935 .val(this.ucivalue(sid
));
3937 var t
= $('<span />')
3938 .addClass('input-group-btn')
3939 .append(_luci2
.ui
.button(_luci2
.tr('Reveal'), 'default')
3940 .click(function(ev
) {
3942 var i
= b
.parent().prev();
3943 var t
= i
.attr('type');
3944 b
.text(t
== 'password' ? _luci2
.tr('Hide') : _luci2
.tr('Reveal'));
3945 i
.attr('type', (t
== 'password') ? 'text' : 'password');
3949 this.validator(sid
, i
);
3952 .addClass('input-group')
3958 this.cbi
.ListValue
= this.cbi
.AbstractValue
.extend({
3959 widget: function(sid
)
3961 var s
= $('<select />')
3962 .addClass('form-control');
3964 if (this.options
.optional
)
3967 .text(_luci2
.tr('-- Please choose --'))
3971 for (var i
= 0; i
< this.choices
.length
; i
++)
3973 .attr('value', this.choices
[i
][0])
3974 .text(this.choices
[i
][1])
3977 s
.attr('id', this.id(sid
)).val(this.ucivalue(sid
));
3979 return this.validator(sid
, s
);
3982 value: function(k
, v
)
3987 this.choices
.push([k
, v
|| k
]);
3992 this.cbi
.MultiValue
= this.cbi
.ListValue
.extend({
3993 widget: function(sid
)
3995 var v
= this.ucivalue(sid
);
3996 var t
= $('<div />').attr('id', this.id(sid
));
3999 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
4002 for (var i
= 0; i
< v
.length
; i
++)
4006 for (var i
= 0; i
< this.choices
.length
; i
++)
4009 .addClass('checkbox')
4010 .append($('<input />')
4011 .attr('type', 'checkbox')
4012 .attr('value', this.choices
[i
][0])
4013 .prop('checked', s
[this.choices
[i
][0]]))
4014 .append(this.choices
[i
][1])
4021 formvalue: function(sid
)
4024 var fields
= $('#' + this.id(sid
) + ' > label > input');
4026 for (var i
= 0; i
< fields
.length
; i
++)
4027 if (fields
[i
].checked
)
4028 rv
.push(fields
[i
].getAttribute('value'));
4033 textvalue: function(sid
)
4035 var v
= this.formvalue(sid
);
4039 for (var i
= 0; i
< this.choices
.length
; i
++)
4040 c
[this.choices
[i
][0]] = this.choices
[i
][1];
4044 for (var i
= 0; i
< v
.length
; i
++)
4045 t
.push(c
[v
[i
]] || v
[i
]);
4047 return t
.join(', ');
4051 this.cbi
.ComboBox
= this.cbi
.AbstractValue
.extend({
4052 _change: function(ev
)
4055 var self
= ev
.data
.self
;
4057 if (s
.selectedIndex
== (s
.options
.length
- 1))
4059 ev
.data
.select
.hide();
4060 ev
.data
.input
.show().focus();
4062 var v
= ev
.data
.input
.val();
4063 ev
.data
.input
.val(' ');
4064 ev
.data
.input
.val(v
);
4066 else if (self
.options
.optional
&& s
.selectedIndex
== 0)
4068 ev
.data
.input
.val('');
4072 ev
.data
.input
.val(ev
.data
.select
.val());
4079 var val
= this.value
;
4080 var self
= ev
.data
.self
;
4082 ev
.data
.select
.empty();
4084 if (self
.options
.optional
)
4087 .text(_luci2
.tr('-- please choose --'))
4088 .appendTo(ev
.data
.select
);
4091 for (var i
= 0; i
< self
.choices
.length
; i
++)
4093 if (self
.choices
[i
][0] == val
)
4097 .attr('value', self
.choices
[i
][0])
4098 .text(self
.choices
[i
][1])
4099 .appendTo(ev
.data
.select
);
4102 if (!seen
&& val
!= '')
4106 .appendTo(ev
.data
.select
);
4110 .text(_luci2
.tr('-- custom --'))
4111 .appendTo(ev
.data
.select
);
4113 ev
.data
.input
.hide();
4114 ev
.data
.select
.val(val
).show().focus();
4117 _enter: function(ev
)
4122 ev
.preventDefault();
4123 ev
.data
.self
._blur(ev
);
4127 widget: function(sid
)
4129 var d
= $('<div />')
4130 .attr('id', this.id(sid
));
4132 var t
= $('<input />')
4133 .attr('type', 'text')
4137 var s
= $('<select />')
4142 input
: this.validator(sid
, t
),
4143 select
: this.validator(sid
, s
)
4146 s
.change(evdata
, this._change
);
4147 t
.blur(evdata
, this._blur
);
4148 t
.keydown(evdata
, this._enter
);
4150 t
.val(this.ucivalue(sid
));
4156 value: function(k
, v
)
4161 this.choices
.push([k
, v
|| k
]);
4165 formvalue: function(sid
)
4167 var v
= $('#' + this.id(sid
)).children('input').val();
4168 return (v
== '') ? undefined : v
;
4172 this.cbi
.DynamicList
= this.cbi
.ComboBox
.extend({
4173 _redraw: function(focus
, add
, del
, s
)
4175 var v
= s
.values
|| [ ];
4178 $(s
.parent
).children('div.input-group').children('input').each(function(i
) {
4180 v
.push(this.value
|| '');
4183 $(s
.parent
).empty();
4188 v
.splice(focus
, 0, '');
4190 else if (v
.length
== 0)
4196 for (var i
= 0; i
< v
.length
; i
++)
4203 remove
: ((i
+1) < v
.length
)
4208 btn
= _luci2
.ui
.button('–', 'danger').click(evdata
, this._btnclick
);
4210 btn
= _luci2
.ui
.button('+', 'success').click(evdata
, this._btnclick
);
4214 var txt
= $('<input />')
4215 .addClass('form-control')
4216 .attr('type', 'text')
4219 var sel
= $('<select />')
4220 .addClass('form-control');
4223 .addClass('input-group')
4226 .append($('<span />')
4227 .addClass('input-group-btn')
4229 .appendTo(s
.parent
);
4231 evdata
.input
= this.validator(s
.sid
, txt
, true);
4232 evdata
.select
= this.validator(s
.sid
, sel
, true);
4234 sel
.change(evdata
, this._change
);
4235 txt
.blur(evdata
, this._blur
);
4236 txt
.keydown(evdata
, this._keydown
);
4241 if (i
== focus
|| -(i
+1) == focus
)
4248 var f
= $('<input />')
4249 .attr('type', 'text')
4251 .attr('placeholder', (i
== 0) ? this.options
.placeholder
: '')
4252 .addClass('form-control')
4253 .keydown(evdata
, this._keydown
)
4254 .keypress(evdata
, this._keypress
)
4258 .addClass('input-group')
4260 .append($('<span />')
4261 .addClass('input-group-btn')
4263 .appendTo(s
.parent
);
4269 else if (-(i
+1) == focus
)
4273 /* force cursor to end */
4279 evdata
.input
= this.validator(s
.sid
, f
, true);
4290 _keypress: function(ev
)
4294 /* backspace, delete */
4297 if (ev
.data
.input
.val() == '')
4299 ev
.preventDefault();
4305 /* enter, arrow up, arrow down */
4309 ev
.preventDefault();
4316 _keydown: function(ev
)
4318 var input
= ev
.data
.input
;
4322 /* backspace, delete */
4325 if (input
.val().length
== 0)
4327 ev
.preventDefault();
4329 var index
= ev
.data
.index
;
4335 ev
.data
.self
._redraw(focus
, -1, index
, ev
.data
);
4343 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
4348 var prev
= input
.parent().prevAll('div.input-group:first').children('input');
4349 if (prev
.is(':visible'))
4352 prev
.next('select').focus();
4357 var next
= input
.parent().nextAll('div.input-group:first').children('input');
4358 if (next
.is(':visible'))
4361 next
.next('select').focus();
4368 _btnclick: function(ev
)
4370 if (!this.getAttribute('disabled'))
4374 var index
= ev
.data
.index
;
4375 ev
.data
.self
._redraw(-index
, -1, index
, ev
.data
);
4379 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
4386 widget: function(sid
)
4388 this.options
.optional
= true;
4390 var v
= this.ucivalue(sid
);
4393 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
4395 var d
= $('<div />')
4396 .attr('id', this.id(sid
))
4397 .addClass('cbi-input-dynlist');
4399 this._redraw(NaN
, -1, -1, {
4409 ucivalue: function(sid
)
4411 var v
= this.callSuper('ucivalue', sid
);
4414 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
4419 formvalue: function(sid
)
4422 var fields
= $('#' + this.id(sid
) + ' > input');
4424 for (var i
= 0; i
< fields
.length
; i
++)
4425 if (typeof(fields
[i
].value
) == 'string' && fields
[i
].value
.length
)
4426 rv
.push(fields
[i
].value
);
4432 this.cbi
.DummyValue
= this.cbi
.AbstractValue
.extend({
4433 widget: function(sid
)
4436 .addClass('form-control-static')
4437 .attr('id', this.id(sid
))
4438 .html(this.ucivalue(sid
));
4441 formvalue: function(sid
)
4443 return this.ucivalue(sid
);
4447 this.cbi
.NetworkList
= this.cbi
.AbstractValue
.extend({
4452 if (!self
.interfaces
)
4454 self
.interfaces
= [ ];
4455 return _luci2
.network
.getNetworkStatus().then(function(ifaces
) {
4456 self
.interfaces
= ifaces
;
4464 _device_icon: function(dev
)
4466 var type
= 'ethernet';
4467 var desc
= _luci2
.tr('Ethernet device');
4469 if (dev
.type
== 'IP tunnel')
4472 desc
= _luci2
.tr('Tunnel interface');
4474 else if (dev
['bridge-members'])
4477 desc
= _luci2
.tr('Bridge');
4479 else if (dev
.wireless
)
4482 desc
= _luci2
.tr('Wireless Network');
4484 else if (dev
.device
.indexOf('.') > 0)
4487 desc
= _luci2
.tr('VLAN interface');
4491 .attr('src', _luci2
.globals
.resource
+ '/icons/' + type
+ (dev
.up
? '' : '_disabled') + '.png')
4492 .attr('title', '%s (%s)'.format(desc
, dev
.device
));
4495 widget: function(sid
)
4497 var id
= this.id(sid
);
4498 var ul
= $('<ul />')
4500 .addClass('list-unstyled');
4502 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
4503 var value
= this.ucivalue(sid
);
4506 if (!this.options
.multiple
)
4507 check
[value
] = true;
4509 for (var i
= 0; i
< value
.length
; i
++)
4510 check
[value
[i
]] = true;
4512 if (this.interfaces
)
4514 for (var i
= 0; i
< this.interfaces
.length
; i
++)
4516 var iface
= this.interfaces
[i
];
4517 var badge
= $('<span />')
4519 .text('%s: '.format(iface
['interface']));
4521 if (iface
.device
&& iface
.device
.subdevices
)
4522 for (var j
= 0; j
< iface
.device
.subdevices
.length
; j
++)
4523 badge
.append(this._device_icon(iface
.device
.subdevices
[j
]));
4524 else if (iface
.device
)
4525 badge
.append(this._device_icon(iface
.device
));
4527 badge
.append($('<em />').text(_luci2
.tr('(No devices attached)')));
4530 .append($('<label />')
4531 .addClass(itype
+ ' inline')
4532 .append($('<input />')
4533 .attr('name', itype
+ id
)
4534 .attr('type', itype
)
4535 .attr('value', iface
['interface'])
4536 .prop('checked', !!check
[iface
['interface']]))
4542 if (!this.options
.multiple
)
4545 .append($('<label />')
4546 .addClass(itype
+ ' inline text-muted')
4547 .append($('<input />')
4548 .attr('name', itype
+ id
)
4549 .attr('type', itype
)
4551 .prop('checked', !value
))
4552 .append(_luci2
.tr('unspecified')))
4559 ucivalue: function(sid
)
4561 var v
= this.callSuper('ucivalue', sid
);
4563 if (!this.options
.multiple
)
4569 else if (typeof(v
) == 'string')
4572 return v
? v
[0] : undefined;
4579 if (typeof(v
) == 'string')
4580 v
= v
.match(/\S+/g);
4586 formvalue: function(sid
)
4588 var inputs
= $('#' + this.id(sid
) + ' input');
4590 if (!this.options
.multiple
)
4592 for (var i
= 0; i
< inputs
.length
; i
++)
4593 if (inputs
[i
].checked
&& inputs
[i
].value
!== '')
4594 return inputs
[i
].value
;
4601 for (var i
= 0; i
< inputs
.length
; i
++)
4602 if (inputs
[i
].checked
)
4603 rv
.push(inputs
[i
].value
);
4605 return rv
.length
? rv
: undefined;
4610 this.cbi
.AbstractSection
= this.ui
.AbstractWidget
.extend({
4613 var s
= [ arguments
[0], this.map
.uci_package
, this.uci_type
];
4615 for (var i
= 1; i
< arguments
.length
; i
++)
4616 s
.push(arguments
[i
].replace(/\./g, '_'));
4621 option: function(widget
, name
, options
)
4623 if (this.tabs
.length
== 0)
4624 this.tab({ id
: '__default__', selected
: true });
4626 return this.taboption('__default__', widget
, name
, options
);
4629 tab: function(options
)
4631 if (options
.selected
)
4632 this.tabs
.selected
= this.tabs
.length
;
4636 caption
: options
.caption
,
4637 description
: options
.description
,
4643 taboption: function(tabid
, widget
, name
, options
)
4646 for (var i
= 0; i
< this.tabs
.length
; i
++)
4648 if (this.tabs
[i
].id
== tabid
)
4656 throw 'Cannot append to unknown tab ' + tabid
;
4658 var w
= widget
? new widget(name
, options
) : null;
4660 if (!(w
instanceof _luci2
.cbi
.AbstractValue
))
4661 throw 'Widget must be an instance of AbstractValue';
4666 this.fields
[name
] = w
;
4672 ucipackages: function(pkg
)
4674 for (var i
= 0; i
< this.tabs
.length
; i
++)
4675 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4676 if (this.tabs
[i
].fields
[j
].options
.uci_package
)
4677 pkg
[this.tabs
[i
].fields
[j
].options
.uci_package
] = true;
4680 formvalue: function()
4684 this.sections(function(s
) {
4685 var sid
= s
['.name'];
4686 var sv
= rv
[sid
] || (rv
[sid
] = { });
4688 for (var i
= 0; i
< this.tabs
.length
; i
++)
4689 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4691 var val
= this.tabs
[i
].fields
[j
].formvalue(sid
);
4692 sv
[this.tabs
[i
].fields
[j
].name
] = val
;
4699 validate_section: function(sid
)
4701 var inst
= this.instance
[sid
];
4704 var badge
= $('#' + this.id('teaser', sid
)).children('span:first');
4706 for (var i
= 0; i
< this.tabs
.length
; i
++)
4709 var stbadge
= $('#' + this.id('nodetab', sid
, this.tabs
[i
].id
)).children('span:first');
4711 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4712 if (!this.tabs
[i
].fields
[j
].validate(sid
))
4718 .attr('title', _luci2
.trp('1 Error', '%d Errors', inval
).format(inval
));
4728 .attr('title', _luci2
.trp('1 Error', '%d Errors', invals
).format(invals
));
4735 validate: function()
4737 this.error_count
= 0;
4739 var as
= this.sections();
4741 for (var i
= 0; i
< as
.length
; i
++)
4743 var invals
= this.validate_section(as
[i
]['.name']);
4746 this.error_count
+= invals
;
4749 var badge
= $('#' + this.id('sectiontab')).children('span:first');
4751 if (this.error_count
> 0)
4753 .text(this.error_count
)
4754 .attr('title', _luci2
.trp('1 Error', '%d Errors', this.error_count
).format(this.error_count
));
4758 return (this.error_count
== 0);
4762 this.cbi
.TypedSection
= this.cbi
.AbstractSection
.extend({
4763 init: function(uci_type
, options
)
4765 this.uci_type
= uci_type
;
4766 this.options
= options
;
4769 this.error_count
= 0;
4770 this.active_panel
= 0;
4771 this.active_tab
= { };
4774 filter: function(section
)
4779 sections: function(cb
)
4781 var s1
= this.map
.ucisections(this.map
.uci_package
);
4784 for (var i
= 0; i
< s1
.length
; i
++)
4785 if (s1
[i
]['.type'] == this.uci_type
)
4786 if (this.filter(s1
[i
]))
4789 if (typeof(cb
) == 'function')
4790 for (var i
= 0; i
< s2
.length
; i
++)
4791 cb
.apply(this, [ s2
[i
] ]);
4798 this.map
.add(this.map
.uci_package
, this.uci_type
, name
);
4801 remove: function(sid
)
4803 this.map
.remove(this.map
.uci_package
, sid
);
4806 _ev_add: function(ev
)
4809 var name
= undefined;
4810 var self
= ev
.data
.self
;
4812 if (addb
.prev().prop('nodeName') == 'INPUT')
4813 name
= addb
.prev().val();
4815 if (addb
.prop('disabled') || name
=== '')
4818 _luci2
.ui
.saveScrollTop();
4820 self
.active_panel
= -1;
4825 _luci2
.ui
.restoreScrollTop();
4828 _ev_remove: function(ev
)
4830 var self
= ev
.data
.self
;
4831 var sid
= ev
.data
.sid
;
4833 _luci2
.ui
.saveScrollTop();
4839 _luci2
.ui
.restoreScrollTop();
4841 ev
.stopPropagation();
4844 _ev_sid: function(ev
)
4846 var self
= ev
.data
.self
;
4848 var addb
= text
.next();
4849 var errt
= addb
.next();
4850 var name
= text
.val();
4853 if (!/^[a-zA-Z0-9_]*$/.test(name
))
4855 errt
.text(_luci2
.tr('Invalid section name')).show();
4856 text
.addClass('error');
4857 addb
.prop('disabled', true);
4861 for (var sid
in self
.map
.uci
.values
[self
.map
.uci_package
])
4868 for (var sid
in self
.map
.uci
.creates
[self
.map
.uci_package
])
4877 errt
.text(_luci2
.tr('Name already used')).show();
4878 text
.addClass('error');
4879 addb
.prop('disabled', true);
4883 errt
.text('').hide();
4884 text
.removeClass('error');
4885 addb
.prop('disabled', false);
4889 _ev_tab: function(ev
)
4891 var self
= ev
.data
.self
;
4892 var sid
= ev
.data
.sid
;
4895 self
.active_tab
[sid
] = parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
4898 _ev_panel_collapse: function(ev
)
4900 var self
= ev
.data
.self
;
4902 var this_panel
= $(ev
.target
);
4903 var this_toggle
= this_panel
.prevAll('[data-toggle="collapse"]:first');
4905 var prev_toggle
= $($(ev
.delegateTarget
).find('[data-toggle="collapse"]:eq(%d)'.format(self
.active_panel
)));
4906 var prev_panel
= $(prev_toggle
.attr('data-target'));
4910 .addClass('collapse');
4912 prev_toggle
.find('.luci2-section-teaser')
4914 .children('span:last')
4916 .append(self
.teaser(prev_panel
.attr('data-luci2-sid')));
4918 this_toggle
.find('.luci2-section-teaser')
4921 self
.active_panel
= parseInt(this_panel
.attr('data-luci2-panel-index'));
4925 _ev_panel_open: function(ev
)
4927 var self
= ev
.data
.self
;
4928 var panel
= $($(this).attr('data-target'));
4929 var index
= parseInt(panel
.attr('data-luci2-panel-index'));
4931 if (index
== self
.active_panel
)
4932 ev
.stopPropagation();
4935 _ev_sort: function(ev
)
4937 var self
= ev
.data
.self
;
4938 var cur_idx
= ev
.data
.index
;
4939 var new_idx
= cur_idx
+ (ev
.data
.up
? -1 : 1);
4940 var s
= self
.sections();
4942 if (new_idx
>= 0 && new_idx
< s
.length
)
4944 var tmp
= s
[cur_idx
]['.index'];
4946 s
[cur_idx
]['.index'] = s
[new_idx
]['.index'];
4947 s
[new_idx
]['.index'] = tmp
;
4949 if (self
.active_panel
== cur_idx
)
4950 self
.active_panel
= new_idx
;
4951 else if (self
.active_panel
== new_idx
)
4952 self
.active_panel
= cur_idx
;
4954 self
.map
.uci
.reorder
= true;
4960 ev
.stopPropagation();
4963 teaser: function(sid
)
4965 var tf
= this.teaser_fields
;
4969 tf
= this.teaser_fields
= [ ];
4971 if ($.isArray(this.options
.teasers
))
4973 for (var i
= 0; i
< this.options
.teasers
.length
; i
++)
4975 var f
= this.options
.teasers
[i
];
4976 if (f
instanceof _luci2
.cbi
.AbstractValue
)
4978 else if (typeof(f
) == 'string' && this.fields
[f
] instanceof _luci2
.cbi
.AbstractValue
)
4979 tf
.push(this.fields
[f
]);
4984 for (var i
= 0; tf
.length
<= 5 && i
< this.tabs
.length
; i
++)
4985 for (var j
= 0; tf
.length
<= 5 && j
< this.tabs
[i
].fields
.length
; j
++)
4986 tf
.push(this.tabs
[i
].fields
[j
]);
4992 for (var i
= 0; i
< tf
.length
; i
++)
4994 if (tf
[i
].instance
[sid
] && tf
[i
].instance
[sid
].disabled
)
4997 var n
= tf
[i
].options
.caption
|| tf
[i
].name
;
4998 var v
= tf
[i
].textvalue(sid
);
5000 if (typeof(v
) == 'undefined')
5003 t
= t
+ '%s%s: <strong>%s</strong>'.format(t
? ' | ' : '', n
, v
);
5009 _render_add: function()
5011 if (!this.options
.addremove
)
5014 var text
= _luci2
.tr('Add section');
5015 var ttip
= _luci2
.tr('Create new section...');
5017 if ($.isArray(this.options
.add_caption
))
5018 text
= this.options
.add_caption
[0], ttip
= this.options
.add_caption
[1];
5019 else if (typeof(this.options
.add_caption
) == 'string')
5020 text
= this.options
.add_caption
, ttip
= '';
5022 var add
= $('<div />');
5024 if (this.options
.anonymous
=== false)
5027 .addClass('cbi-input-text')
5028 .attr('type', 'text')
5029 .attr('placeholder', ttip
)
5030 .blur({ self
: this }, this._ev_sid
)
5031 .keyup({ self
: this }, this._ev_sid
)
5035 .attr('src', _luci2
.globals
.resource
+ '/icons/cbi/add.gif')
5036 .attr('title', text
)
5037 .addClass('cbi-button')
5038 .click({ self
: this }, this._ev_add
)
5042 .addClass('cbi-value-error')
5048 _luci2
.ui
.button(text
, 'success', ttip
)
5049 .click({ self
: this }, this._ev_add
)
5056 _render_remove: function(sid
, index
)
5058 if (!this.options
.addremove
)
5061 var text
= _luci2
.tr('Remove');
5062 var ttip
= _luci2
.tr('Remove this section');
5064 if ($.isArray(this.options
.remove_caption
))
5065 text
= this.options
.remove_caption
[0], ttip
= this.options
.remove_caption
[1];
5066 else if (typeof(this.options
.remove_caption
) == 'string')
5067 text
= this.options
.remove_caption
, ttip
= '';
5069 return _luci2
.ui
.button(text
, 'danger', ttip
)
5070 .click({ self
: this, sid
: sid
, index
: index
}, this._ev_remove
);
5073 _render_sort: function(sid
, index
)
5075 if (!this.options
.sortable
)
5078 var b1
= _luci2
.ui
.button('↑', 'info', _luci2
.tr('Move up'))
5079 .click({ self
: this, index
: index
, up
: true }, this._ev_sort
);
5081 var b2
= _luci2
.ui
.button('↓', 'info', _luci2
.tr('Move down'))
5082 .click({ self
: this, index
: index
, up
: false }, this._ev_sort
);
5087 _render_caption: function()
5090 .addClass('panel-title')
5091 .append(this.label('caption') || this.uci_type
);
5094 _render_description: function()
5096 var text
= this.label('description');
5100 .addClass('luci2-section-description')
5106 _render_teaser: function(sid
, index
)
5108 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
5111 .attr('id', this.id('teaser', sid
))
5112 .addClass('luci2-section-teaser well well-sm')
5113 .append($('<span />')
5115 .append($('<span />'));
5121 _render_head: function(condensed
)
5127 .addClass('panel-heading')
5128 .append(this._render_caption())
5129 .append(this._render_description());
5132 _render_tab_description: function(sid
, index
, tab_index
)
5134 var tab
= this.tabs
[tab_index
];
5136 if (typeof(tab
.description
) == 'string')
5139 .addClass('cbi-tab-descr')
5140 .text(tab
.description
);
5146 _render_tab_head: function(sid
, index
, tab_index
)
5148 var tab
= this.tabs
[tab_index
];
5149 var cur
= this.active_tab
[sid
] || 0;
5151 var tabh
= $('<li />')
5153 .attr('id', this.id('nodetab', sid
, tab
.id
))
5154 .attr('href', '#' + this.id('node', sid
, tab
.id
))
5155 .attr('data-toggle', 'tab')
5156 .attr('data-luci2-tab-index', tab_index
)
5157 .text((tab
.caption
? tab
.caption
.format(tab
.id
) : tab
.id
) + ' ')
5158 .append($('<span />')
5160 .on('shown.bs.tab', { self
: this, sid
: sid
}, this._ev_tab
));
5162 if (cur
== tab_index
)
5163 tabh
.addClass('active');
5168 _render_tab_body: function(sid
, index
, tab_index
)
5170 var tab
= this.tabs
[tab_index
];
5171 var cur
= this.active_tab
[sid
] || 0;
5173 var tabb
= $('<div />')
5174 .addClass('tab-pane')
5175 .attr('id', this.id('node', sid
, tab
.id
))
5176 .attr('data-luci2-tab-index', tab_index
)
5177 .append(this._render_tab_description(sid
, index
, tab_index
));
5179 if (cur
== tab_index
)
5180 tabb
.addClass('active');
5182 for (var i
= 0; i
< tab
.fields
.length
; i
++)
5183 tabb
.append(tab
.fields
[i
].render(sid
));
5188 _render_section_head: function(sid
, index
)
5190 var head
= $('<div />')
5191 .addClass('luci2-section-header')
5192 .append(this._render_teaser(sid
, index
))
5193 .append($('<div />')
5194 .addClass('btn-group')
5195 .append(this._render_sort(sid
, index
))
5196 .append(this._render_remove(sid
, index
)));
5198 if (this.options
.collabsible
)
5200 head
.attr('data-toggle', 'collapse')
5201 .attr('data-parent', this.id('sectiongroup'))
5202 .attr('data-target', '#' + this.id('panel', sid
))
5203 .on('click', { self
: this }, this._ev_panel_open
);
5209 _render_section_body: function(sid
, index
)
5211 var body
= $('<div />')
5212 .attr('id', this.id('panel', sid
))
5213 .attr('data-luci2-panel-index', index
)
5214 .attr('data-luci2-sid', sid
);
5216 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
5218 body
.addClass('panel-collapse collapse');
5220 if (index
== this.active_panel
)
5221 body
.addClass('in');
5224 var tab_heads
= $('<ul />')
5225 .addClass('nav nav-tabs');
5227 var tab_bodies
= $('<div />')
5228 .addClass('form-horizontal tab-content')
5231 for (var j
= 0; j
< this.tabs
.length
; j
++)
5233 tab_heads
.append(this._render_tab_head(sid
, index
, j
));
5234 tab_bodies
.append(this._render_tab_body(sid
, index
, j
));
5237 body
.append(tab_bodies
);
5239 if (this.tabs
.length
<= 1)
5245 _render_body: function(condensed
)
5247 var s
= this.sections();
5249 if (this.active_panel
< 0)
5250 this.active_panel
+= s
.length
;
5251 else if (this.active_panel
>= s
.length
)
5252 this.active_panel
= s
.length
- 1;
5254 var body
= $('<ul />')
5255 .addClass('list-group');
5257 if (this.options
.collabsible
)
5259 body
.attr('id', this.id('sectiongroup'))
5260 .on('show.bs.collapse', { self
: this }, this._ev_panel_collapse
);
5265 body
.append($('<li />')
5266 .addClass('list-group-item text-muted')
5267 .text(this.label('placeholder') || _luci2
.tr('There are no entries defined yet.')))
5270 for (var i
= 0; i
< s
.length
; i
++)
5272 var sid
= s
[i
]['.name'];
5273 var inst
= this.instance
[sid
] = { tabs
: [ ] };
5275 body
.append($('<li />')
5276 .addClass('list-group-item')
5277 .append(this._render_section_head(sid
, i
))
5278 .append(this._render_section_body(sid
, i
)));
5284 render: function(condensed
)
5286 this.instance
= { };
5288 var panel
= $('<div />')
5289 .addClass('panel panel-default')
5290 .append(this._render_head(condensed
))
5291 .append(this._render_body(condensed
));
5293 if (this.options
.addremove
)
5294 panel
.append($('<div />')
5295 .addClass('panel-footer')
5296 .append(this._render_add()));
5303 var s
= this.sections();
5305 for (var i
= 0; i
< s
.length
; i
++)
5307 var sid
= s
[i
]['.name'];
5309 this.validate_section(sid
);
5311 if (i
!= this.active_panel
)
5312 $('#' + this.id('teaser', sid
)).children('span:last')
5313 .append(this.teaser(sid
));
5315 $('#' + this.id('teaser', sid
))
5321 this.cbi
.TableSection
= this.cbi
.TypedSection
.extend({
5322 _render_table_head: function()
5324 var thead
= $('<thead />')
5326 .addClass('cbi-section-table-titles'));
5328 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
5329 thead
.children().append($('<th />')
5330 .addClass('cbi-section-table-cell')
5331 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
5332 .append(this.tabs
[0].fields
[j
].label('caption')));
5334 if (this.options
.addremove
!== false || this.options
.sortable
)
5335 thead
.children().append($('<th />')
5336 .addClass('cbi-section-table-cell')
5342 _render_table_row: function(sid
, index
)
5344 var row
= $('<tr />')
5345 .attr('data-luci2-sid', sid
);
5347 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
5349 row
.append($('<td />')
5350 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
5351 .append(this.tabs
[0].fields
[j
].render(sid
, true)));
5354 if (this.options
.addremove
!== false || this.options
.sortable
)
5356 row
.append($('<td />')
5357 .addClass('text-right')
5358 .append($('<div />')
5359 .addClass('btn-group')
5360 .append(this._render_sort(sid
, index
))
5361 .append(this._render_remove(sid
, index
))));
5367 _render_table_body: function()
5369 var s
= this.sections();
5371 var tbody
= $('<tbody />');
5375 var cols
= this.tabs
[0].fields
.length
;
5377 if (this.options
.addremove
!== false || this.options
.sortable
)
5380 tbody
.append($('<tr />')
5382 .addClass('text-muted')
5383 .attr('colspan', cols
)
5384 .text(this.label('placeholder') || _luci2
.tr('There are no entries defined yet.'))));
5387 for (var i
= 0; i
< s
.length
; i
++)
5389 var sid
= s
[i
]['.name'];
5390 var inst
= this.instance
[sid
] = { tabs
: [ ] };
5392 tbody
.append(this._render_table_row(sid
, i
));
5398 _render_body: function(condensed
)
5400 return $('<table />')
5401 .addClass('table table-condensed table-hover')
5402 .append(this._render_table_head())
5403 .append(this._render_table_body());
5407 this.cbi
.NamedSection
= this.cbi
.TypedSection
.extend({
5408 sections: function(cb
)
5411 var pkg
= this.map
.uci
.values
[this.map
.uci_package
];
5414 if (pkg
[s
]['.name'] == this.uci_type
)
5420 if (typeof(cb
) == 'function' && sa
.length
> 0)
5421 cb
.apply(this, [ sa
[0] ]);
5427 this.cbi
.DummySection
= this.cbi
.TypedSection
.extend({
5428 sections: function(cb
)
5430 if (typeof(cb
) == 'function')
5431 cb
.apply(this, [ { '.name': this.uci_type
} ]);
5433 return [ { '.name': this.uci_type
} ];
5437 this.cbi
.Map
= this.ui
.AbstractWidget
.extend({
5438 init: function(uci_package
, options
)
5442 this.uci_package
= uci_package
;
5443 this.sections
= [ ];
5444 this.options
= _luci2
.defaults(options
, {
5445 save: function() { },
5446 prepare: function() {
5447 return _luci2
.uci
.writable(function(writable
) {
5448 self
.options
.readonly
= !writable
;
5454 _load_cb: function(packages
)
5456 for (var i
= 0; i
< packages
.length
; i
++)
5458 this.uci
.values
[packages
[i
]['.package']] = packages
[i
];
5459 delete packages
[i
]['.package'];
5462 var deferreds
= [ _luci2
.deferrable(this.options
.prepare()) ];
5464 for (var i
= 0; i
< this.sections
.length
; i
++)
5466 for (var f
in this.sections
[i
].fields
)
5468 if (typeof(this.sections
[i
].fields
[f
].load
) != 'function')
5471 var s
= this.sections
[i
].sections();
5472 for (var j
= 0; j
< s
.length
; j
++)
5474 var rv
= this.sections
[i
].fields
[f
].load(s
[j
]['.name']);
5475 if (_luci2
.isDeferred(rv
))
5481 return $.when
.apply($, deferreds
);
5499 for (var i
= 0; i
< this.sections
.length
; i
++)
5500 this.sections
[i
].ucipackages(packages
);
5502 packages
[this.uci_package
] = true;
5506 for (var pkg
in packages
)
5507 _luci2
.uci
.get_all(pkg
);
5509 return _luci2
.rpc
.flush().then(function(packages
) {
5510 return self
._load_cb(packages
);
5514 _ev_tab: function(ev
)
5516 var self
= ev
.data
.self
;
5519 self
.active_tab
= parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
5522 _render_tab_head: function(tab_index
)
5524 var section
= this.sections
[tab_index
];
5525 var cur
= this.active_tab
|| 0;
5527 var tabh
= $('<li />')
5529 .attr('id', section
.id('sectiontab'))
5530 .attr('href', '#' + section
.id('section'))
5531 .attr('data-toggle', 'tab')
5532 .attr('data-luci2-tab-index', tab_index
)
5533 .text(section
.label('caption') + ' ')
5534 .append($('<span />')
5536 .on('shown.bs.tab', { self
: this }, this._ev_tab
));
5538 if (cur
== tab_index
)
5539 tabh
.addClass('active');
5544 _render_tab_body: function(tab_index
)
5546 var section
= this.sections
[tab_index
];
5547 var desc
= section
.label('description');
5548 var cur
= this.active_tab
|| 0;
5550 var tabb
= $('<div />')
5551 .addClass('tab-pane')
5552 .attr('id', section
.id('section'))
5553 .attr('data-luci2-tab-index', tab_index
);
5555 if (cur
== tab_index
)
5556 tabb
.addClass('active');
5559 tabb
.append($('<p />')
5562 var s
= section
.render(this.options
.tabbed
);
5564 if (this.options
.readonly
|| section
.options
.readonly
)
5565 s
.find('input, select, button, img.cbi-button').attr('disabled', true);
5572 _render_body: function()
5574 var tabs
= $('<ul />')
5575 .addClass('nav nav-tabs');
5577 var body
= $('<div />')
5580 for (var i
= 0; i
< this.sections
.length
; i
++)
5582 tabs
.append(this._render_tab_head(i
));
5583 body
.append(this._render_tab_body(i
));
5586 if (this.options
.tabbed
)
5587 body
.addClass('tab-content');
5596 var map
= $('<form />');
5598 if (typeof(this.options
.caption
) == 'string')
5599 map
.append($('<h2 />')
5600 .text(this.options
.caption
));
5602 if (typeof(this.options
.description
) == 'string')
5603 map
.append($('<p />')
5604 .text(this.options
.description
));
5606 map
.append(this._render_body());
5608 if (this.options
.pageaction
!== false)
5610 map
.append($('<div />')
5611 .addClass('panel panel-default panel-body text-right')
5612 .append($('<div />')
5613 .addClass('btn-group')
5614 .append(_luci2
.ui
.button(_luci2
.tr('Save & Apply'), 'primary')
5615 .click({ self
: this }, function(ev
) { }))
5616 .append(_luci2
.ui
.button(_luci2
.tr('Save'), 'default')
5617 .click({ self
: this }, function(ev
) { ev
.data
.self
.send(); }))
5618 .append(_luci2
.ui
.button(_luci2
.tr('Reset'), 'default')
5619 .click({ self
: this }, function(ev
) { ev
.data
.self
.insertInto(ev
.data
.self
.target
); }))));
5627 for (var i
= 0; i
< this.sections
.length
; i
++)
5628 this.sections
[i
].finish();
5635 this.target
.hide().empty().append(this.render());
5640 section: function(widget
, uci_type
, options
)
5642 var w
= widget
? new widget(uci_type
, options
) : null;
5644 if (!(w
instanceof _luci2
.cbi
.AbstractSection
))
5645 throw 'Widget must be an instance of AbstractSection';
5648 w
.index
= this.sections
.length
;
5650 this.sections
.push(w
);
5654 formvalue: function()
5658 for (var i
= 0; i
< this.sections
.length
; i
++)
5660 var sids
= this.sections
[i
].formvalue();
5661 for (var sid
in sids
)
5663 var s
= rv
[sid
] || (rv
[sid
] = { });
5664 $.extend(s
, sids
[sid
]);
5671 add: function(conf
, type
, name
)
5673 var c
= this.uci
.creates
;
5674 var s
= '.new.%d'.format(this.uci
.newid
++);
5683 '.anonymous': !name
,
5684 '.index': 1000 + this.uci
.newid
5690 remove: function(conf
, sid
)
5692 var n
= this.uci
.creates
;
5693 var c
= this.uci
.changes
;
5694 var d
= this.uci
.deletes
;
5696 /* requested deletion of a just created section */
5697 if (sid
.indexOf('.new.') == 0)
5700 delete n
[conf
][sid
];
5705 delete c
[conf
][sid
];
5710 d
[conf
][sid
] = true;
5714 ucisections: function(conf
, cb
)
5717 var pkg
= this.uci
.values
[conf
];
5718 var crt
= this.uci
.creates
[conf
];
5719 var del
= this.uci
.deletes
[conf
];
5725 if (!del
|| del
[s
] !== true)
5732 sa
.sort(function(a
, b
) {
5733 return a
['.index'] - b
['.index'];
5736 for (var i
= 0; i
< sa
.length
; i
++)
5737 sa
[i
]['.index'] = i
;
5739 if (typeof(cb
) == 'function')
5740 for (var i
= 0; i
< sa
.length
; i
++)
5741 cb
.apply(this, [ sa
[i
] ]);
5746 get: function(conf
, sid
, opt
)
5748 var v
= this.uci
.values
;
5749 var n
= this.uci
.creates
;
5750 var c
= this.uci
.changes
;
5751 var d
= this.uci
.deletes
;
5753 /* requested option in a just created section */
5754 if (sid
.indexOf('.new.') == 0)
5759 if (typeof(opt
) == 'undefined')
5760 return (n
[conf
][sid
] || { });
5762 return n
[conf
][sid
][opt
];
5765 /* requested an option value */
5766 if (typeof(opt
) != 'undefined')
5768 /* check whether option was deleted */
5769 if (d
[conf
] && d
[conf
][sid
])
5771 if (d
[conf
][sid
] === true)
5774 for (var i
= 0; i
< d
[conf
][sid
].length
; i
++)
5775 if (d
[conf
][sid
][i
] == opt
)
5779 /* check whether option was changed */
5780 if (c
[conf
] && c
[conf
][sid
] && typeof(c
[conf
][sid
][opt
]) != 'undefined')
5781 return c
[conf
][sid
][opt
];
5783 /* return base value */
5784 if (v
[conf
] && v
[conf
][sid
])
5785 return v
[conf
][sid
][opt
];
5790 /* requested an entire section */
5792 return (v
[conf
][sid
] || { });
5797 set: function(conf
, sid
, opt
, val
)
5799 var n
= this.uci
.creates
;
5800 var c
= this.uci
.changes
;
5801 var d
= this.uci
.deletes
;
5803 if (sid
.indexOf('.new.') == 0)
5805 if (n
[conf
] && n
[conf
][sid
])
5807 if (typeof(val
) != 'undefined')
5808 n
[conf
][sid
][opt
] = val
;
5810 delete n
[conf
][sid
][opt
];
5813 else if (typeof(val
) != 'undefined')
5821 c
[conf
][sid
][opt
] = val
;
5831 d
[conf
][sid
].push(opt
);
5835 validate: function()
5839 for (var i
= 0; i
< this.sections
.length
; i
++)
5841 if (!this.sections
[i
].validate())
5850 if (this.options
.readonly
)
5851 return _luci2
.deferrable();
5853 var deferreds
= [ _luci2
.deferrable(this.options
.save()) ];
5855 for (var i
= 0; i
< this.sections
.length
; i
++)
5857 if (this.sections
[i
].options
.readonly
)
5860 for (var f
in this.sections
[i
].fields
)
5862 if (typeof(this.sections
[i
].fields
[f
].save
) != 'function')
5865 var s
= this.sections
[i
].sections();
5866 for (var j
= 0; j
< s
.length
; j
++)
5868 var rv
= this.sections
[i
].fields
[f
].save(s
[j
]['.name']);
5869 if (_luci2
.isDeferred(rv
))
5875 return $.when
.apply($, deferreds
);
5878 _send_uci_reorder: function()
5880 if (!this.uci
.reorder
)
5881 return _luci2
.deferrable();
5886 gather all created and existing sections, sort them according
5887 to their index value and issue an uci order call
5889 for (var c
in this.uci
.values
)
5893 if (this.uci
.creates
&& this.uci
.creates
[c
])
5894 for (var s
in this.uci
.creates
[c
])
5895 o
.push(this.uci
.creates
[c
][s
]);
5897 for (var s
in this.uci
.values
[c
])
5898 o
.push(this.uci
.values
[c
][s
]);
5902 o
.sort(function(a
, b
) {
5903 return (a
['.index'] - b
['.index']);
5908 for (var i
= 0; i
< o
.length
; i
++)
5909 sids
.push(o
[i
]['.name']);
5911 _luci2
.uci
.order(c
, sids
);
5915 return _luci2
.rpc
.flush();
5918 _send_uci: function()
5925 if (this.uci
.creates
)
5926 for (var c
in this.uci
.creates
)
5927 for (var s
in this.uci
.creates
[c
])
5934 for (var k
in this.uci
.creates
[c
][s
])
5937 r
.type
= this.uci
.creates
[c
][s
][k
];
5938 else if (k
== '.create')
5939 r
.name
= this.uci
.creates
[c
][s
][k
];
5940 else if (k
.charAt(0) != '.')
5941 r
.values
[k
] = this.uci
.creates
[c
][s
][k
];
5944 snew
.push(this.uci
.creates
[c
][s
]);
5946 _luci2
.uci
.add(r
.config
, r
.type
, r
.name
, r
.values
);
5949 if (this.uci
.changes
)
5950 for (var c
in this.uci
.changes
)
5951 for (var s
in this.uci
.changes
[c
])
5952 _luci2
.uci
.set(c
, s
, this.uci
.changes
[c
][s
]);
5954 if (this.uci
.deletes
)
5955 for (var c
in this.uci
.deletes
)
5956 for (var s
in this.uci
.deletes
[c
])
5958 var o
= this.uci
.deletes
[c
][s
];
5959 _luci2
.uci
['delete'](c
, s
, (o
=== true) ? undefined : o
);
5962 return _luci2
.rpc
.flush().then(function(responses
) {
5964 array "snew" holds references to the created uci sections,
5965 use it to assign the returned names of the new sections
5967 for (var i
= 0; i
< snew
.length
; i
++)
5968 snew
[i
]['.name'] = responses
[i
];
5970 return self
._send_uci_reorder();
5976 if (!this.validate())
5977 return _luci2
.deferrable();
5981 _luci2
.ui
.saveScrollTop();
5982 _luci2
.ui
.loading(true);
5984 return this.save().then(function() {
5985 return self
._send_uci();
5986 }).then(function() {
5987 return _luci2
.ui
.updateChanges();
5988 }).then(function() {
5990 }).then(function() {
5994 _luci2
.ui
.loading(false);
5995 _luci2
.ui
.restoreScrollTop();
5999 insertInto: function(id
)
6002 self
.target
= $(id
);
6004 _luci2
.ui
.loading(true);
6007 return self
.load().then(function() {
6008 self
.target
.empty().append(self
.render());
6012 _luci2
.ui
.loading(false);