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
512 _list_cb: function(msg
)
514 /* verify message frame */
515 if (typeof(msg
) != 'object' || msg
.jsonrpc
!= '2.0' || !msg
.id
)
516 throw 'Invalid JSON response';
521 _call_cb: function(msg
)
524 var type
= Object
.prototype.toString
;
529 for (var i
= 0; i
< msg
.length
; i
++)
531 /* verify message frame */
532 if (typeof(msg
[i
]) != 'object' || msg
[i
].jsonrpc
!= '2.0' || !msg
[i
].id
)
533 throw 'Invalid JSON response';
535 /* fetch related request info */
536 var req
= _luci2
.rpc
._requests
[msg
[i
].id
];
537 if (typeof(req
) != 'object')
538 throw 'No related request for JSON response';
540 /* fetch response attribute and verify returned type */
543 if ($.isArray(msg
[i
].result
) && msg
[i
].result
[0] == 0)
544 ret
= (msg
[i
].result
.length
> 1) ? msg
[i
].result
[1] : msg
[i
].result
[0];
548 for (var key
in req
.expect
)
550 if (typeof(ret
) != 'undefined' && key
!= '')
553 if (typeof(ret
) == 'undefined' || type
.call(ret
) != type
.call(req
.expect
[key
]))
554 ret
= req
.expect
[key
];
561 if (typeof(req
.filter
) == 'function')
564 req
.priv
[1] = req
.params
;
565 ret
= req
.filter
.apply(_luci2
.rpc
, req
.priv
);
568 /* store response data */
569 if (typeof(req
.index
) == 'number')
570 data
[req
.index
] = ret
;
574 /* delete request object */
575 delete _luci2
.rpc
._requests
[msg
[i
].id
];
584 for (var i
= 0; i
< arguments
.length
; i
++)
585 params
[i
] = arguments
[i
];
591 params
: (params
.length
> 0) ? params
: undefined
594 return this._call(msg
, this._list_cb
);
599 if (!$.isArray(this._batch
))
605 if (!$.isArray(this._batch
))
606 return _luci2
.deferrable([ ]);
608 var req
= this._batch
;
612 return this._call(req
, this._call_cb
);
615 declare: function(options
)
620 /* build parameter object */
623 if ($.isArray(options
.params
))
624 for (p_off
= 0; p_off
< options
.params
.length
; p_off
++)
625 params
[options
.params
[p_off
]] = arguments
[p_off
];
627 /* all remaining arguments are private args */
628 var priv
= [ undefined, undefined ];
629 for (; p_off
< arguments
.length
; p_off
++)
630 priv
.push(arguments
[p_off
]);
632 /* store request info */
633 var req
= _rpc
._requests
[_rpc
._id
] = {
634 expect
: options
.expect
,
635 filter
: options
.filter
,
640 /* build message object */
653 /* when a batch is in progress then store index in request data
654 * and push message object onto the stack */
655 if ($.isArray(_rpc
._batch
))
657 req
.index
= _rpc
._batch
.push(msg
) - 1;
658 return _luci2
.deferrable(msg
);
662 return _rpc
._call(msg
, _rpc
._call_cb
);
671 return _luci2
.session
.access('ubus', 'uci', 'commit');
674 add
: _luci2
.rpc
.declare({
677 params
: [ 'config', 'type', 'name', 'values' ],
678 expect
: { section
: '' }
686 configs
: _luci2
.rpc
.declare({
689 expect
: { configs
: [ ] }
692 _changes
: _luci2
.rpc
.declare({
695 params
: [ 'config' ],
696 expect
: { changes
: [ ] }
699 changes: function(config
)
701 if (typeof(config
) == 'string')
702 return this._changes(config
);
705 return this.configs().then(function(configs
) {
707 configlist
= configs
;
709 for (var i
= 0; i
< configs
.length
; i
++)
710 _luci2
.uci
._changes(configs
[i
]);
712 return _luci2
.rpc
.flush();
713 }).then(function(changes
) {
716 for (var i
= 0; i
< configlist
.length
; i
++)
717 if (changes
[i
].length
)
718 rv
[configlist
[i
]] = changes
[i
];
724 commit
: _luci2
.rpc
.declare({
730 _delete_one
: _luci2
.rpc
.declare({
733 params
: [ 'config', 'section', 'option' ]
736 _delete_multiple
: _luci2
.rpc
.declare({
739 params
: [ 'config', 'section', 'options' ]
742 'delete': function(config
, section
, option
)
744 if ($.isArray(option
))
745 return this._delete_multiple(config
, section
, option
);
747 return this._delete_one(config
, section
, option
);
750 delete_all
: _luci2
.rpc
.declare({
753 params
: [ 'config', 'type', 'match' ]
756 _foreach
: _luci2
.rpc
.declare({
759 params
: [ 'config', 'type' ],
760 expect
: { values
: { } }
763 foreach: function(config
, type
, cb
)
765 return this._foreach(config
, type
).then(function(sections
) {
766 for (var s
in sections
)
771 get: _luci2
.rpc
.declare({
774 params
: [ 'config', 'section', 'option' ],
776 filter: function(data
, params
) {
777 if (typeof(params
.option
) == 'undefined')
778 return data
.values
? data
.values
['.type'] : undefined;
784 get_all
: _luci2
.rpc
.declare({
787 params
: [ 'config', 'section' ],
788 expect
: { values
: { } },
789 filter: function(data
, params
) {
790 if (typeof(params
.section
) == 'string')
791 data
['.section'] = params
.section
;
792 else if (typeof(params
.config
) == 'string')
793 data
['.package'] = params
.config
;
798 get_first: function(config
, type
, option
)
800 return this._foreach(config
, type
).then(function(sections
) {
801 for (var s
in sections
)
803 var val
= (typeof(option
) == 'string') ? sections
[s
][option
] : sections
[s
]['.name'];
805 if (typeof(val
) != 'undefined')
813 section
: _luci2
.rpc
.declare({
816 params
: [ 'config', 'type', 'name', 'values' ],
817 expect
: { section
: '' }
820 _set
: _luci2
.rpc
.declare({
823 params
: [ 'config', 'section', 'values' ]
826 set: function(config
, section
, option
, value
)
828 if (typeof(value
) == 'undefined' && typeof(option
) == 'string')
829 return this.section(config
, section
, option
); /* option -> type */
830 else if ($.isPlainObject(option
))
831 return this._set(config
, section
, option
); /* option -> values */
834 values
[option
] = value
;
836 return this._set(config
, section
, values
);
839 order
: _luci2
.rpc
.declare({
842 params
: [ 'config', 'sections' ]
847 listNetworkNames: function() {
848 return _luci2
.rpc
.list('network.interface.*').then(function(list
) {
850 for (var name
in list
)
851 if (name
!= 'network.interface.loopback')
852 names
.push(name
.substring(18));
858 listDeviceNames
: _luci2
.rpc
.declare({
859 object
: 'network.device',
862 filter: function(data
) {
864 for (var name
in data
)
872 getNetworkStatus: function()
877 return this.listNetworkNames().then(function(names
) {
880 for (var i
= 0; i
< names
.length
; i
++)
881 _luci2
.network
.getInterfaceStatus(names
[i
]);
883 return _luci2
.rpc
.flush();
884 }).then(function(networks
) {
885 for (var i
= 0; i
< networks
.length
; i
++)
887 var net
= nets
[i
] = networks
[i
];
888 var dev
= net
.l3_device
|| net
.l2_device
;
890 net
.device
= devs
[dev
] || (devs
[dev
] = { });
895 for (var dev
in devs
)
896 _luci2
.network
.getDeviceStatus(dev
);
898 return _luci2
.rpc
.flush();
899 }).then(function(devices
) {
902 for (var i
= 0; i
< devices
.length
; i
++)
904 var brm
= devices
[i
]['bridge-members'];
905 delete devices
[i
]['bridge-members'];
907 $.extend(devs
[devices
[i
]['device']], devices
[i
]);
912 devs
[devices
[i
]['device']].subdevices
= [ ];
914 for (var j
= 0; j
< brm
.length
; j
++)
919 _luci2
.network
.getDeviceStatus(brm
[j
]);
922 devs
[devices
[i
]['device']].subdevices
[j
] = devs
[brm
[j
]];
926 return _luci2
.rpc
.flush();
927 }).then(function(subdevices
) {
928 for (var i
= 0; i
< subdevices
.length
; i
++)
929 $.extend(devs
[subdevices
[i
]['device']], subdevices
[i
]);
933 for (var dev
in devs
)
934 _luci2
.wireless
.getDeviceStatus(dev
);
936 return _luci2
.rpc
.flush();
937 }).then(function(wifidevices
) {
938 for (var i
= 0; i
< wifidevices
.length
; i
++)
940 devs
[wifidevices
[i
]['device']].wireless
= wifidevices
[i
];
942 nets
.sort(function(a
, b
) {
943 if (a
['interface'] < b
['interface'])
945 else if (a
['interface'] > b
['interface'])
955 findWanInterfaces: function(cb
)
957 return this.listNetworkNames().then(function(names
) {
960 for (var i
= 0; i
< names
.length
; i
++)
961 _luci2
.network
.getInterfaceStatus(names
[i
]);
963 return _luci2
.rpc
.flush();
964 }).then(function(interfaces
) {
965 var rv
= [ undefined, undefined ];
967 for (var i
= 0; i
< interfaces
.length
; i
++)
969 if (!interfaces
[i
].route
)
972 for (var j
= 0; j
< interfaces
[i
].route
.length
; j
++)
974 var rt
= interfaces
[i
].route
[j
];
976 if (typeof(rt
.table
) != 'undefined')
979 if (rt
.target
== '0.0.0.0' && rt
.mask
== 0)
980 rv
[0] = interfaces
[i
];
981 else if (rt
.target
== '::' && rt
.mask
== 0)
982 rv
[1] = interfaces
[i
];
990 getDHCPLeases
: _luci2
.rpc
.declare({
991 object
: 'luci2.network',
992 method
: 'dhcp_leases',
993 expect
: { leases
: [ ] }
996 getDHCPv6Leases
: _luci2
.rpc
.declare({
997 object
: 'luci2.network',
998 method
: 'dhcp6_leases',
999 expect
: { leases
: [ ] }
1002 getRoutes
: _luci2
.rpc
.declare({
1003 object
: 'luci2.network',
1005 expect
: { routes
: [ ] }
1008 getIPv6Routes
: _luci2
.rpc
.declare({
1009 object
: 'luci2.network',
1011 expect
: { routes
: [ ] }
1014 getARPTable
: _luci2
.rpc
.declare({
1015 object
: 'luci2.network',
1016 method
: 'arp_table',
1017 expect
: { entries
: [ ] }
1020 getInterfaceStatus
: _luci2
.rpc
.declare({
1021 object
: 'network.interface',
1023 params
: [ 'interface' ],
1024 expect
: { '': { } },
1025 filter: function(data
, params
) {
1026 data
['interface'] = params
['interface'];
1027 data
['l2_device'] = data
['device'];
1028 delete data
['device'];
1033 getDeviceStatus
: _luci2
.rpc
.declare({
1034 object
: 'network.device',
1037 expect
: { '': { } },
1038 filter: function(data
, params
) {
1039 data
['device'] = params
['name'];
1044 getConntrackCount
: _luci2
.rpc
.declare({
1045 object
: 'luci2.network',
1046 method
: 'conntrack_count',
1047 expect
: { '': { count
: 0, limit
: 0 } }
1050 listSwitchNames
: _luci2
.rpc
.declare({
1051 object
: 'luci2.network',
1052 method
: 'switch_list',
1053 expect
: { switches
: [ ] }
1056 getSwitchInfo
: _luci2
.rpc
.declare({
1057 object
: 'luci2.network',
1058 method
: 'switch_info',
1059 params
: [ 'switch' ],
1060 expect
: { info
: { } },
1061 filter: function(data
, params
) {
1062 data
['attrs'] = data
['switch'];
1063 data
['vlan_attrs'] = data
['vlan'];
1064 data
['port_attrs'] = data
['port'];
1065 data
['switch'] = params
['switch'];
1074 getSwitchStatus
: _luci2
.rpc
.declare({
1075 object
: 'luci2.network',
1076 method
: 'switch_status',
1077 params
: [ 'switch' ],
1078 expect
: { ports
: [ ] }
1082 runPing
: _luci2
.rpc
.declare({
1083 object
: 'luci2.network',
1086 expect
: { '': { code
: -1 } }
1089 runPing6
: _luci2
.rpc
.declare({
1090 object
: 'luci2.network',
1093 expect
: { '': { code
: -1 } }
1096 runTraceroute
: _luci2
.rpc
.declare({
1097 object
: 'luci2.network',
1098 method
: 'traceroute',
1100 expect
: { '': { code
: -1 } }
1103 runTraceroute6
: _luci2
.rpc
.declare({
1104 object
: 'luci2.network',
1105 method
: 'traceroute6',
1107 expect
: { '': { code
: -1 } }
1110 runNslookup
: _luci2
.rpc
.declare({
1111 object
: 'luci2.network',
1114 expect
: { '': { code
: -1 } }
1118 setUp
: _luci2
.rpc
.declare({
1119 object
: 'luci2.network',
1122 expect
: { '': { code
: -1 } }
1125 setDown
: _luci2
.rpc
.declare({
1126 object
: 'luci2.network',
1129 expect
: { '': { code
: -1 } }
1134 listDeviceNames
: _luci2
.rpc
.declare({
1137 expect
: { 'devices': [ ] },
1138 filter: function(data
) {
1144 getDeviceStatus
: _luci2
.rpc
.declare({
1147 params
: [ 'device' ],
1148 expect
: { '': { } },
1149 filter: function(data
, params
) {
1150 if (!$.isEmptyObject(data
))
1152 data
['device'] = params
['device'];
1159 getAssocList
: _luci2
.rpc
.declare({
1161 method
: 'assoclist',
1162 params
: [ 'device' ],
1163 expect
: { results
: [ ] },
1164 filter: function(data
, params
) {
1165 for (var i
= 0; i
< data
.length
; i
++)
1166 data
[i
]['device'] = params
['device'];
1168 data
.sort(function(a
, b
) {
1169 if (a
.bssid
< b
.bssid
)
1171 else if (a
.bssid
> b
.bssid
)
1181 getWirelessStatus: function() {
1182 return this.listDeviceNames().then(function(names
) {
1185 for (var i
= 0; i
< names
.length
; i
++)
1186 _luci2
.wireless
.getDeviceStatus(names
[i
]);
1188 return _luci2
.rpc
.flush();
1189 }).then(function(networks
) {
1193 'country', 'channel', 'frequency', 'frequency_offset',
1194 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1198 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1199 'signal', 'noise', 'bitrate', 'encryption'
1202 for (var i
= 0; i
< networks
.length
; i
++)
1204 var phy
= rv
[networks
[i
].phy
] || (
1205 rv
[networks
[i
].phy
] = { networks
: [ ] }
1209 device
: networks
[i
].device
1212 for (var j
= 0; j
< phy_attrs
.length
; j
++)
1213 phy
[phy_attrs
[j
]] = networks
[i
][phy_attrs
[j
]];
1215 for (var j
= 0; j
< net_attrs
.length
; j
++)
1216 net
[net_attrs
[j
]] = networks
[i
][net_attrs
[j
]];
1218 phy
.networks
.push(net
);
1225 getAssocLists: function()
1227 return this.listDeviceNames().then(function(names
) {
1230 for (var i
= 0; i
< names
.length
; i
++)
1231 _luci2
.wireless
.getAssocList(names
[i
]);
1233 return _luci2
.rpc
.flush();
1234 }).then(function(assoclists
) {
1237 for (var i
= 0; i
< assoclists
.length
; i
++)
1238 for (var j
= 0; j
< assoclists
[i
].length
; j
++)
1239 rv
.push(assoclists
[i
][j
]);
1245 formatEncryption: function(enc
)
1247 var format_list = function(l
, s
)
1250 for (var i
= 0; i
< l
.length
; i
++)
1251 rv
.push(l
[i
].toUpperCase());
1252 return rv
.join(s
? s
: ', ');
1255 if (!enc
|| !enc
.enabled
)
1256 return _luci2
.tr('None');
1260 if (enc
.wep
.length
== 2)
1261 return _luci2
.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1262 else if (enc
.wep
[0] == 'shared')
1263 return _luci2
.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1265 return _luci2
.tr('WEP Open System') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1269 if (enc
.wpa
.length
== 2)
1270 return _luci2
.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1271 format_list(enc
.authentication
, '/'),
1272 format_list(enc
.ciphers
, ', ')
1274 else if (enc
.wpa
[0] == 2)
1275 return 'WPA2 %s (%s)'.format(
1276 format_list(enc
.authentication
, '/'),
1277 format_list(enc
.ciphers
, ', ')
1280 return 'WPA %s (%s)'.format(
1281 format_list(enc
.authentication
, '/'),
1282 format_list(enc
.ciphers
, ', ')
1286 return _luci2
.tr('Unknown');
1291 getZoneColor: function(zone
)
1293 if ($.isPlainObject(zone
))
1298 else if (zone
== 'wan')
1301 for (var i
= 0, hash
= 0;
1303 hash
= zone
.charCodeAt(i
++) + ((hash
<< 5) - hash
));
1305 for (var i
= 0, color
= '#';
1307 color
+= ('00' + ((hash
>> i
++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1312 findZoneByNetwork: function(network
)
1315 var zone
= undefined;
1317 return _luci2
.uci
.foreach('firewall', 'zone', function(z
) {
1318 if (!z
.name
|| !z
.network
)
1321 if (!$.isArray(z
.network
))
1322 z
.network
= z
.network
.split(/\s+/);
1324 for (var i
= 0; i
< z
.network
.length
; i
++)
1326 if (z
.network
[i
] == network
)
1332 }).then(function() {
1334 zone
.color
= self
.getZoneColor(zone
);
1342 getSystemInfo
: _luci2
.rpc
.declare({
1348 getBoardInfo
: _luci2
.rpc
.declare({
1354 getDiskInfo
: _luci2
.rpc
.declare({
1355 object
: 'luci2.system',
1360 getInfo: function(cb
)
1364 this.getSystemInfo();
1365 this.getBoardInfo();
1368 return _luci2
.rpc
.flush().then(function(info
) {
1371 $.extend(rv
, info
[0]);
1372 $.extend(rv
, info
[1]);
1373 $.extend(rv
, info
[2]);
1379 getProcessList
: _luci2
.rpc
.declare({
1380 object
: 'luci2.system',
1381 method
: 'process_list',
1382 expect
: { processes
: [ ] },
1383 filter: function(data
) {
1384 data
.sort(function(a
, b
) { return a
.pid
- b
.pid
});
1389 getSystemLog
: _luci2
.rpc
.declare({
1390 object
: 'luci2.system',
1395 getKernelLog
: _luci2
.rpc
.declare({
1396 object
: 'luci2.system',
1401 getZoneInfo: function(cb
)
1403 return $.getJSON(_luci2
.globals
.resource
+ '/zoneinfo.json', cb
);
1406 sendSignal
: _luci2
.rpc
.declare({
1407 object
: 'luci2.system',
1408 method
: 'process_signal',
1409 params
: [ 'pid', 'signal' ],
1410 filter: function(data
) {
1415 initList
: _luci2
.rpc
.declare({
1416 object
: 'luci2.system',
1417 method
: 'init_list',
1418 expect
: { initscripts
: [ ] },
1419 filter: function(data
) {
1420 data
.sort(function(a
, b
) { return (a
.start
|| 0) - (b
.start
|| 0) });
1425 initEnabled: function(init
, cb
)
1427 return this.initList().then(function(list
) {
1428 for (var i
= 0; i
< list
.length
; i
++)
1429 if (list
[i
].name
== init
)
1430 return !!list
[i
].enabled
;
1436 initRun
: _luci2
.rpc
.declare({
1437 object
: 'luci2.system',
1438 method
: 'init_action',
1439 params
: [ 'name', 'action' ],
1440 filter: function(data
) {
1445 initStart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'start', cb
) },
1446 initStop: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'stop', cb
) },
1447 initRestart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'restart', cb
) },
1448 initReload: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'reload', cb
) },
1449 initEnable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'enable', cb
) },
1450 initDisable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'disable', cb
) },
1453 getRcLocal
: _luci2
.rpc
.declare({
1454 object
: 'luci2.system',
1455 method
: 'rclocal_get',
1456 expect
: { data
: '' }
1459 setRcLocal
: _luci2
.rpc
.declare({
1460 object
: 'luci2.system',
1461 method
: 'rclocal_set',
1466 getCrontab
: _luci2
.rpc
.declare({
1467 object
: 'luci2.system',
1468 method
: 'crontab_get',
1469 expect
: { data
: '' }
1472 setCrontab
: _luci2
.rpc
.declare({
1473 object
: 'luci2.system',
1474 method
: 'crontab_set',
1479 getSSHKeys
: _luci2
.rpc
.declare({
1480 object
: 'luci2.system',
1481 method
: 'sshkeys_get',
1482 expect
: { keys
: [ ] }
1485 setSSHKeys
: _luci2
.rpc
.declare({
1486 object
: 'luci2.system',
1487 method
: 'sshkeys_set',
1492 setPassword
: _luci2
.rpc
.declare({
1493 object
: 'luci2.system',
1494 method
: 'password_set',
1495 params
: [ 'user', 'password' ]
1499 listLEDs
: _luci2
.rpc
.declare({
1500 object
: 'luci2.system',
1502 expect
: { leds
: [ ] }
1505 listUSBDevices
: _luci2
.rpc
.declare({
1506 object
: 'luci2.system',
1508 expect
: { devices
: [ ] }
1512 testUpgrade
: _luci2
.rpc
.declare({
1513 object
: 'luci2.system',
1514 method
: 'upgrade_test',
1518 startUpgrade
: _luci2
.rpc
.declare({
1519 object
: 'luci2.system',
1520 method
: 'upgrade_start',
1524 cleanUpgrade
: _luci2
.rpc
.declare({
1525 object
: 'luci2.system',
1526 method
: 'upgrade_clean'
1530 restoreBackup
: _luci2
.rpc
.declare({
1531 object
: 'luci2.system',
1532 method
: 'backup_restore'
1535 cleanBackup
: _luci2
.rpc
.declare({
1536 object
: 'luci2.system',
1537 method
: 'backup_clean'
1541 getBackupConfig
: _luci2
.rpc
.declare({
1542 object
: 'luci2.system',
1543 method
: 'backup_config_get',
1544 expect
: { config
: '' }
1547 setBackupConfig
: _luci2
.rpc
.declare({
1548 object
: 'luci2.system',
1549 method
: 'backup_config_set',
1554 listBackup
: _luci2
.rpc
.declare({
1555 object
: 'luci2.system',
1556 method
: 'backup_list',
1557 expect
: { files
: [ ] }
1561 testReset
: _luci2
.rpc
.declare({
1562 object
: 'luci2.system',
1563 method
: 'reset_test',
1564 expect
: { supported
: false }
1567 startReset
: _luci2
.rpc
.declare({
1568 object
: 'luci2.system',
1569 method
: 'reset_start'
1573 performReboot
: _luci2
.rpc
.declare({
1574 object
: 'luci2.system',
1580 updateLists
: _luci2
.rpc
.declare({
1581 object
: 'luci2.opkg',
1586 _allPackages
: _luci2
.rpc
.declare({
1587 object
: 'luci2.opkg',
1589 params
: [ 'offset', 'limit', 'pattern' ],
1593 _installedPackages
: _luci2
.rpc
.declare({
1594 object
: 'luci2.opkg',
1595 method
: 'list_installed',
1596 params
: [ 'offset', 'limit', 'pattern' ],
1600 _findPackages
: _luci2
.rpc
.declare({
1601 object
: 'luci2.opkg',
1603 params
: [ 'offset', 'limit', 'pattern' ],
1607 _fetchPackages: function(action
, offset
, limit
, pattern
)
1611 return action(offset
, limit
, pattern
).then(function(list
) {
1612 if (!list
.total
|| !list
.packages
)
1613 return { length
: 0, total
: 0 };
1615 packages
.push
.apply(packages
, list
.packages
);
1616 packages
.total
= list
.total
;
1621 if (packages
.length
>= limit
)
1626 for (var i
= offset
+ packages
.length
; i
< limit
; i
+= 100)
1627 action(i
, (Math
.min(i
+ 100, limit
) % 100) || 100, pattern
);
1629 return _luci2
.rpc
.flush();
1630 }).then(function(lists
) {
1631 for (var i
= 0; i
< lists
.length
; i
++)
1633 if (!lists
[i
].total
|| !lists
[i
].packages
)
1636 packages
.push
.apply(packages
, lists
[i
].packages
);
1637 packages
.total
= lists
[i
].total
;
1644 listPackages: function(offset
, limit
, pattern
)
1646 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._allPackages
, offset
, limit
, pattern
);
1649 installedPackages: function(offset
, limit
, pattern
)
1651 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._installedPackages
, offset
, limit
, pattern
);
1654 findPackages: function(offset
, limit
, pattern
)
1656 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._findPackages
, offset
, limit
, pattern
);
1659 installPackage
: _luci2
.rpc
.declare({
1660 object
: 'luci2.opkg',
1662 params
: [ 'package' ],
1666 removePackage
: _luci2
.rpc
.declare({
1667 object
: 'luci2.opkg',
1669 params
: [ 'package' ],
1673 getConfig
: _luci2
.rpc
.declare({
1674 object
: 'luci2.opkg',
1675 method
: 'config_get',
1676 expect
: { config
: '' }
1679 setConfig
: _luci2
.rpc
.declare({
1680 object
: 'luci2.opkg',
1681 method
: 'config_set',
1688 login
: _luci2
.rpc
.declare({
1691 params
: [ 'username', 'password' ],
1695 access
: _luci2
.rpc
.declare({
1698 params
: [ 'scope', 'object', 'function' ],
1699 expect
: { access
: false }
1704 return _luci2
.session
.access('ubus', 'session', 'access');
1707 startHeartbeat: function()
1709 this._hearbeatInterval
= window
.setInterval(function() {
1710 _luci2
.session
.isAlive().then(function(alive
) {
1713 _luci2
.session
.stopHeartbeat();
1714 _luci2
.ui
.login(true);
1718 }, _luci2
.globals
.timeout
* 2);
1721 stopHeartbeat: function()
1723 if (typeof(this._hearbeatInterval
) != 'undefined')
1725 window
.clearInterval(this._hearbeatInterval
);
1726 delete this._hearbeatInterval
;
1733 saveScrollTop: function()
1735 this._scroll_top
= $(document
).scrollTop();
1738 restoreScrollTop: function()
1740 if (typeof(this._scroll_top
) == 'undefined')
1743 $(document
).scrollTop(this._scroll_top
);
1745 delete this._scroll_top
;
1748 loading: function(enable
)
1750 var win
= $(window
);
1751 var body
= $('body');
1753 var state
= _luci2
.ui
._loading
|| (_luci2
.ui
._loading
= {
1755 .addClass('modal fade')
1756 .append($('<div />')
1757 .addClass('modal-dialog')
1758 .append($('<div />')
1759 .addClass('modal-content luci2-modal-loader')
1760 .append($('<div />')
1761 .addClass('modal-body')
1762 .text(_luci2
.tr('Loading data…')))))
1770 state
.modal
.modal(enable
? 'show' : 'hide');
1773 dialog: function(title
, content
, options
)
1775 var win
= $(window
);
1776 var body
= $('body');
1778 var state
= _luci2
.ui
._dialog
|| (_luci2
.ui
._dialog
= {
1779 dialog
: $('<div />')
1780 .addClass('modal fade')
1781 .append($('<div />')
1782 .addClass('modal-dialog')
1783 .append($('<div />')
1784 .addClass('modal-content')
1785 .append($('<div />')
1786 .addClass('modal-header')
1788 .addClass('modal-title'))
1789 .append($('<div />')
1790 .addClass('modal-body'))
1791 .append($('<div />')
1792 .addClass('modal-footer')
1793 .append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
1795 $(this).parents('div.modal').modal('hide');
1800 if (typeof(options
) != 'object')
1803 if (title
=== false)
1805 state
.dialog
.modal('hide');
1810 var cnt
= state
.dialog
.children().children().children('div.modal-body');
1811 var ftr
= state
.dialog
.children().children().children('div.modal-footer');
1815 if (options
.style
== 'confirm')
1817 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Ok'), 'primary')
1818 .click(options
.confirm
|| function() { _luci2
.ui
.dialog(false) }));
1820 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Cancel'), 'default')
1821 .click(options
.cancel
|| function() { _luci2
.ui
.dialog(false) }));
1823 else if (options
.style
== 'close')
1825 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
1826 .click(options
.close
|| function() { _luci2
.ui
.dialog(false) }));
1828 else if (options
.style
== 'wait')
1830 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
1831 .attr('disabled', true));
1834 state
.dialog
.find('h4:first').text(title
);
1835 state
.dialog
.modal('show');
1837 cnt
.empty().append(content
);
1840 upload: function(title
, content
, options
)
1842 var state
= _luci2
.ui
._upload
|| (_luci2
.ui
._upload
= {
1844 .attr('method', 'post')
1845 .attr('action', '/cgi-bin/luci-upload')
1846 .attr('enctype', 'multipart/form-data')
1847 .attr('target', 'cbi-fileupload-frame')
1849 .append($('<input />')
1850 .attr('type', 'hidden')
1851 .attr('name', 'sessionid'))
1852 .append($('<input />')
1853 .attr('type', 'hidden')
1854 .attr('name', 'filename'))
1855 .append($('<input />')
1856 .attr('type', 'file')
1857 .attr('name', 'filedata')
1858 .addClass('cbi-input-file'))
1859 .append($('<div />')
1860 .css('width', '100%')
1861 .addClass('progress progress-striped active')
1862 .append($('<div />')
1863 .addClass('progress-bar')
1864 .css('width', '100%')))
1865 .append($('<iframe />')
1866 .addClass('pull-right')
1867 .attr('name', 'cbi-fileupload-frame')
1868 .css('width', '1px')
1869 .css('height', '1px')
1870 .css('visibility', 'hidden')),
1872 finish_cb: function(ev
) {
1873 $(this).off('load');
1875 var body
= (this.contentDocument
|| this.contentWindow
.document
).body
;
1876 if (body
.firstChild
.tagName
.toLowerCase() == 'pre')
1877 body
= body
.firstChild
;
1881 json
= $.parseJSON(body
.innerHTML
);
1884 message
: _luci2
.tr('Invalid server response received'),
1885 error
: [ -1, _luci2
.tr('Invalid data') ]
1891 L
.ui
.dialog(L
.tr('File upload'), [
1892 $('<p />').text(_luci2
.tr('The file upload failed with the server response below:')),
1893 $('<pre />').addClass('alert-message').text(json
.message
|| json
.error
[1]),
1894 $('<p />').text(_luci2
.tr('In case of network problems try uploading the file again.'))
1895 ], { style
: 'close' });
1897 else if (typeof(state
.success_cb
) == 'function')
1899 state
.success_cb(json
);
1903 confirm_cb: function() {
1904 var f
= state
.form
.find('.cbi-input-file');
1905 var b
= state
.form
.find('.progress');
1906 var p
= state
.form
.find('p');
1911 state
.form
.find('iframe').on('load', state
.finish_cb
);
1912 state
.form
.submit();
1916 p
.text(_luci2
.tr('File upload in progress …'));
1918 state
.form
.parent().parent().find('button').prop('disabled', true);
1922 state
.form
.find('.progress').hide();
1923 state
.form
.find('.cbi-input-file').val('').show();
1924 state
.form
.find('p').text(content
|| _luci2
.tr('Select the file to upload and press "%s" to proceed.').format(_luci2
.tr('Ok')));
1926 state
.form
.find('[name=sessionid]').val(_luci2
.globals
.sid
);
1927 state
.form
.find('[name=filename]').val(options
.filename
);
1929 state
.success_cb
= options
.success
;
1931 _luci2
.ui
.dialog(title
|| _luci2
.tr('File upload'), state
.form
, {
1933 confirm
: state
.confirm_cb
1937 reconnect: function()
1939 var protocols
= (location
.protocol
== 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1940 var ports
= (location
.protocol
== 'https:') ? [ 80, location
.port
|| 443 ] : [ location
.port
|| 80 ];
1941 var address
= location
.hostname
.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location
.hostname
+ ']' : location
.hostname
;
1943 var interval
, timeout
;
1946 _luci2
.tr('Waiting for device'), [
1947 $('<p />').text(_luci2
.tr('Please stand by while the device is reconfiguring …')),
1949 .css('width', '100%')
1950 .addClass('progressbar')
1951 .addClass('intermediate')
1952 .append($('<div />')
1953 .css('width', '100%'))
1954 ], { style
: 'wait' }
1957 for (var i
= 0; i
< protocols
.length
; i
++)
1958 images
= images
.add($('<img />').attr('url', protocols
[i
] + '://' + address
+ ':' + ports
[i
]));
1960 //_luci2.network.getNetworkStatus(function(s) {
1961 // for (var i = 0; i < protocols.length; i++)
1963 // for (var j = 0; j < s.length; j++)
1965 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1966 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1968 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1969 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1972 //}).then(function() {
1973 images
.on('load', function() {
1974 var url
= this.getAttribute('url');
1975 _luci2
.session
.isAlive().then(function(access
) {
1978 window
.clearTimeout(timeout
);
1979 window
.clearInterval(interval
);
1980 _luci2
.ui
.dialog(false);
1985 location
.href
= url
;
1990 interval
= window
.setInterval(function() {
1991 images
.each(function() {
1992 this.setAttribute('src', this.getAttribute('url') + _luci2
.globals
.resource
+ '/icons/loading.gif?r=' + Math
.random());
1996 timeout
= window
.setTimeout(function() {
1997 window
.clearInterval(interval
);
2001 _luci2
.tr('Device not responding'),
2002 _luci2
.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2009 login: function(invalid
)
2011 var state
= _luci2
.ui
._login
|| (_luci2
.ui
._login
= {
2014 .attr('method', 'post')
2016 .addClass('alert-message')
2017 .text(_luci2
.tr('Wrong username or password given!')))
2019 .append($('<label />')
2020 .text(_luci2
.tr('Username'))
2021 .append($('<br />'))
2022 .append($('<input />')
2023 .attr('type', 'text')
2024 .attr('name', 'username')
2025 .attr('value', 'root')
2026 .addClass('form-control')
2027 .keypress(function(ev
) {
2028 if (ev
.which
== 10 || ev
.which
== 13)
2032 .append($('<label />')
2033 .text(_luci2
.tr('Password'))
2034 .append($('<br />'))
2035 .append($('<input />')
2036 .attr('type', 'password')
2037 .attr('name', 'password')
2038 .addClass('form-control')
2039 .keypress(function(ev
) {
2040 if (ev
.which
== 10 || ev
.which
== 13)
2044 .text(_luci2
.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2
.tr('Ok')))),
2046 response_cb: function(response
) {
2047 if (!response
.ubus_rpc_session
)
2049 _luci2
.ui
.login(true);
2053 _luci2
.globals
.sid
= response
.ubus_rpc_session
;
2054 _luci2
.setHash('id', _luci2
.globals
.sid
);
2055 _luci2
.session
.startHeartbeat();
2056 _luci2
.ui
.dialog(false);
2057 state
.deferred
.resolve();
2061 confirm_cb: function() {
2062 var u
= state
.form
.find('[name=username]').val();
2063 var p
= state
.form
.find('[name=password]').val();
2069 _luci2
.tr('Logging in'), [
2070 $('<p />').text(_luci2
.tr('Log in in progress …')),
2072 .css('width', '100%')
2073 .addClass('progressbar')
2074 .addClass('intermediate')
2075 .append($('<div />')
2076 .css('width', '100%'))
2077 ], { style
: 'wait' }
2080 _luci2
.globals
.sid
= '00000000000000000000000000000000';
2081 _luci2
.session
.login(u
, p
).then(state
.response_cb
);
2085 if (!state
.deferred
|| state
.deferred
.state() != 'pending')
2086 state
.deferred
= $.Deferred();
2088 /* try to find sid from hash */
2089 var sid
= _luci2
.getHash('id');
2090 if (sid
&& sid
.match(/^[a-f0-9]{32}$/))
2092 _luci2
.globals
.sid
= sid
;
2093 _luci2
.session
.isAlive().then(function(access
) {
2096 _luci2
.session
.startHeartbeat();
2097 state
.deferred
.resolve();
2101 _luci2
.setHash('id', undefined);
2106 return state
.deferred
;
2110 state
.form
.find('.alert-message').show();
2112 state
.form
.find('.alert-message').hide();
2114 _luci2
.ui
.dialog(_luci2
.tr('Authorization Required'), state
.form
, {
2116 confirm
: state
.confirm_cb
2119 state
.form
.find('[name=password]').focus();
2121 return state
.deferred
;
2124 cryptPassword
: _luci2
.rpc
.declare({
2128 expect
: { crypt
: '' }
2132 _acl_merge_scope: function(acl_scope
, scope
)
2134 if ($.isArray(scope
))
2136 for (var i
= 0; i
< scope
.length
; i
++)
2137 acl_scope
[scope
[i
]] = true;
2139 else if ($.isPlainObject(scope
))
2141 for (var object_name
in scope
)
2143 if (!$.isArray(scope
[object_name
]))
2146 var acl_object
= acl_scope
[object_name
] || (acl_scope
[object_name
] = { });
2148 for (var i
= 0; i
< scope
[object_name
].length
; i
++)
2149 acl_object
[scope
[object_name
][i
]] = true;
2154 _acl_merge_permission: function(acl_perm
, perm
)
2156 if ($.isPlainObject(perm
))
2158 for (var scope_name
in perm
)
2160 var acl_scope
= acl_perm
[scope_name
] || (acl_perm
[scope_name
] = { });
2161 this._acl_merge_scope(acl_scope
, perm
[scope_name
]);
2166 _acl_merge_group: function(acl_group
, group
)
2168 if ($.isPlainObject(group
))
2170 if (!acl_group
.description
)
2171 acl_group
.description
= group
.description
;
2175 var acl_perm
= acl_group
.read
|| (acl_group
.read
= { });
2176 this._acl_merge_permission(acl_perm
, group
.read
);
2181 var acl_perm
= acl_group
.write
|| (acl_group
.write
= { });
2182 this._acl_merge_permission(acl_perm
, group
.write
);
2187 _acl_merge_tree: function(acl_tree
, tree
)
2189 if ($.isPlainObject(tree
))
2191 for (var group_name
in tree
)
2193 var acl_group
= acl_tree
[group_name
] || (acl_tree
[group_name
] = { });
2194 this._acl_merge_group(acl_group
, tree
[group_name
]);
2199 listAvailableACLs
: _luci2
.rpc
.declare({
2202 expect
: { acls
: [ ] },
2203 filter: function(trees
) {
2205 for (var i
= 0; i
< trees
.length
; i
++)
2206 _luci2
.ui
._acl_merge_tree(acl_tree
, trees
[i
]);
2211 renderMainMenu
: _luci2
.rpc
.declare({
2214 expect
: { menu
: { } },
2215 filter: function(entries
) {
2216 _luci2
.globals
.mainMenu
= new _luci2
.ui
.menu();
2217 _luci2
.globals
.mainMenu
.entries(entries
);
2221 .append(_luci2
.globals
.mainMenu
.render(0, 1));
2225 renderViewMenu: function()
2229 .append(_luci2
.globals
.mainMenu
.render(2, 900));
2232 renderView: function()
2234 var node
= arguments
[0];
2235 var name
= node
.view
.split(/\//).join('.');
2238 for (var i
= 1; i
< arguments
.length
; i
++)
2239 args
.push(arguments
[i
]);
2241 if (_luci2
.globals
.currentView
)
2242 _luci2
.globals
.currentView
.finish();
2244 _luci2
.ui
.renderViewMenu();
2247 _luci2
._views
= { };
2249 _luci2
.setHash('view', node
.view
);
2251 if (_luci2
._views
[name
] instanceof _luci2
.ui
.view
)
2253 _luci2
.globals
.currentView
= _luci2
._views
[name
];
2254 return _luci2
._views
[name
].render
.apply(_luci2
._views
[name
], args
);
2257 var url
= _luci2
.globals
.resource
+ '/view/' + name
+ '.js';
2259 return $.ajax(url
, {
2263 }).then(function(data
) {
2265 var viewConstructorSource
= (
2266 '(function(L, $) { ' +
2268 '})(_luci2, $);\n\n' +
2270 ).format(data
, url
);
2272 var viewConstructor
= eval(viewConstructorSource
);
2274 _luci2
._views
[name
] = new viewConstructor({
2276 acls
: node
.write
|| { }
2279 _luci2
.globals
.currentView
= _luci2
._views
[name
];
2280 return _luci2
._views
[name
].render
.apply(_luci2
._views
[name
], args
);
2283 alert('Unable to instantiate view "%s": %s'.format(url
, e
));
2286 return $.Deferred().resolve();
2290 updateHostname: function()
2292 return _luci2
.system
.getBoardInfo().then(function(info
) {
2294 $('#hostname').text(info
.hostname
);
2298 updateChanges: function()
2300 return _luci2
.uci
.changes().then(function(changes
) {
2304 for (var config
in changes
)
2308 for (var i
= 0; i
< changes
[config
].length
; i
++)
2310 var c
= changes
[config
][i
];
2319 log
.push('uci delete %s.<del>%s</del>'.format(config
, c
[1]));
2321 log
.push('uci delete %s.%s.<del>%s</del>'.format(config
, c
[1], c
[2]));
2326 log
.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3]));
2328 log
.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2332 log
.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config
, c
[2], c
[1]));
2336 log
.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2340 log
.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2345 log
.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
2347 log
.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2352 html
+= '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config
, log
.join('\n'));
2353 n
+= changes
[config
].length
;
2364 .text(_luci2
.trcp('Pending configuration changes', '1 change', '%d changes', n
).format(n
))
2365 .click(function(ev
) {
2366 _luci2
.ui
.dialog(_luci2
.tr('Staged configuration changes'), html
, { style
: 'close' });
2367 ev
.preventDefault();
2377 _luci2
.ui
.loading(true);
2380 _luci2
.ui
.updateHostname(),
2381 _luci2
.ui
.updateChanges(),
2382 _luci2
.ui
.renderMainMenu()
2384 _luci2
.ui
.renderView(_luci2
.globals
.defaultNode
).then(function() {
2385 _luci2
.ui
.loading(false);
2390 button: function(label
, style
, title
)
2392 style
= style
|| 'default';
2394 return $('<button />')
2395 .attr('type', 'button')
2396 .attr('title', title
? title
: '')
2397 .addClass('btn btn-' + style
)
2402 this.ui
.AbstractWidget
= Class
.extend({
2403 i18n: function(text
) {
2408 var key
= arguments
[0];
2411 for (var i
= 1; i
< arguments
.length
; i
++)
2412 args
.push(arguments
[i
]);
2414 switch (typeof(this.options
[key
]))
2420 return this.options
[key
].apply(this, args
);
2423 return ''.format
.apply('' + this.options
[key
], args
);
2427 toString: function() {
2428 return $('<div />').append(this.render()).html();
2431 insertInto: function(id
) {
2432 return $(id
).empty().append(this.render());
2435 appendTo: function(id
) {
2436 return $(id
).append(this.render());
2440 this.ui
.view
= this.ui
.AbstractWidget
.extend({
2441 _fetch_template: function()
2443 return $.ajax(_luci2
.globals
.resource
+ '/template/' + this.options
.name
+ '.htm', {
2447 success: function(data
) {
2448 data
= data
.replace(/<%([#:=])?(.+?)%>/g, function(match
, p1
, p2
) {
2449 p2
= p2
.replace(/^\s+/, '').replace(/\s+$/, '');
2456 return _luci2
.tr(p2
);
2459 return _luci2
.globals
[p2
] || '';
2462 return '(?' + match
+ ')';
2466 $('#maincontent').append(data
);
2473 throw "Not implemented";
2478 var container
= $('#maincontent');
2483 container
.append($('<h2 />').append(this.title
));
2485 if (this.description
)
2486 container
.append($('<p />').append(this.description
));
2491 for (var i
= 0; i
< arguments
.length
; i
++)
2492 args
.push(arguments
[i
]);
2494 return this._fetch_template().then(function() {
2495 return _luci2
.deferrable(self
.execute
.apply(self
, args
));
2499 repeat: function(func
, interval
)
2503 if (!self
._timeouts
)
2504 self
._timeouts
= [ ];
2506 var index
= self
._timeouts
.length
;
2508 if (typeof(interval
) != 'number')
2511 var setTimer
, runTimer
;
2513 setTimer = function() {
2515 self
._timeouts
[index
] = window
.setTimeout(runTimer
, interval
);
2518 runTimer = function() {
2519 _luci2
.deferrable(func
.call(self
)).then(setTimer
, setTimer
);
2527 if ($.isArray(this._timeouts
))
2529 for (var i
= 0; i
< this._timeouts
.length
; i
++)
2530 window
.clearTimeout(this._timeouts
[i
]);
2532 delete this._timeouts
;
2537 this.ui
.menu
= this.ui
.AbstractWidget
.extend({
2542 entries: function(entries
)
2544 for (var entry
in entries
)
2546 var path
= entry
.split(/\//);
2547 var node
= this._nodes
;
2549 for (i
= 0; i
< path
.length
; i
++)
2554 if (!node
.childs
[path
[i
]])
2555 node
.childs
[path
[i
]] = { };
2557 node
= node
.childs
[path
[i
]];
2560 $.extend(node
, entries
[entry
]);
2564 _indexcmp: function(a
, b
)
2566 var x
= a
.index
|| 0;
2567 var y
= b
.index
|| 0;
2571 firstChildView: function(node
)
2577 for (var child
in (node
.childs
|| { }))
2578 nodes
.push(node
.childs
[child
]);
2580 nodes
.sort(this._indexcmp
);
2582 for (var i
= 0; i
< nodes
.length
; i
++)
2584 var child
= this.firstChildView(nodes
[i
]);
2587 for (var key
in child
)
2588 if (!node
.hasOwnProperty(key
) && child
.hasOwnProperty(key
))
2589 node
[key
] = child
[key
];
2598 _onclick: function(ev
)
2600 _luci2
.ui
.loading(true);
2601 _luci2
.ui
.renderView(ev
.data
).then(function() {
2602 _luci2
.ui
.loading(false);
2605 ev
.preventDefault();
2609 _render: function(childs
, level
, min
, max
)
2612 for (var node
in childs
)
2614 var child
= this.firstChildView(childs
[node
]);
2616 nodes
.push(childs
[node
]);
2619 nodes
.sort(this._indexcmp
);
2621 var list
= $('<ul />');
2624 list
.addClass('nav').addClass('navbar-nav');
2625 else if (level
== 1)
2626 list
.addClass('dropdown-menu').addClass('navbar-inverse');
2628 for (var i
= 0; i
< nodes
.length
; i
++)
2630 if (!_luci2
.globals
.defaultNode
)
2632 var v
= _luci2
.getHash('view');
2633 if (!v
|| v
== nodes
[i
].view
)
2634 _luci2
.globals
.defaultNode
= nodes
[i
];
2637 var item
= $('<li />')
2640 .text(_luci2
.tr(nodes
[i
].title
)))
2643 if (nodes
[i
].childs
&& level
< max
)
2645 item
.addClass('dropdown');
2648 .addClass('dropdown-toggle')
2649 .attr('data-toggle', 'dropdown')
2650 .append('<b class="caret"></b>');
2652 item
.append(this._render(nodes
[i
].childs
, level
+ 1));
2656 item
.find('a').click(nodes
[i
], this._onclick
);
2663 render: function(min
, max
)
2665 var top
= min
? this.getNode(_luci2
.globals
.defaultNode
.view
, min
) : this._nodes
;
2666 return this._render(top
.childs
, 0, min
, max
);
2669 getNode: function(path
, max
)
2671 var p
= path
.split(/\//);
2672 var n
= this._nodes
;
2674 if (typeof(max
) == 'undefined')
2677 for (var i
= 0; i
< max
; i
++)
2679 if (!n
.childs
[p
[i
]])
2689 this.ui
.table
= this.ui
.AbstractWidget
.extend({
2695 row: function(values
)
2697 if ($.isArray(values
))
2699 this._rows
.push(values
);
2701 else if ($.isPlainObject(values
))
2704 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2706 var col
= this.options
.columns
[i
];
2708 if (typeof col
.key
== 'string')
2709 v
.push(values
[col
.key
]);
2717 rows: function(rows
)
2719 for (var i
= 0; i
< rows
.length
; i
++)
2723 render: function(id
)
2725 var fieldset
= document
.createElement('fieldset');
2726 fieldset
.className
= 'cbi-section';
2728 if (this.options
.caption
)
2730 var legend
= document
.createElement('legend');
2731 $(legend
).append(this.options
.caption
);
2732 fieldset
.appendChild(legend
);
2735 var table
= document
.createElement('table');
2736 table
.className
= 'table table-condensed table-hover';
2738 var has_caption
= false;
2739 var has_description
= false;
2741 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2742 if (this.options
.columns
[i
].caption
)
2747 else if (this.options
.columns
[i
].description
)
2749 has_description
= true;
2755 var tr
= table
.insertRow(-1);
2756 tr
.className
= 'cbi-section-table-titles';
2758 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2760 var col
= this.options
.columns
[i
];
2761 var th
= document
.createElement('th');
2762 th
.className
= 'cbi-section-table-cell';
2767 th
.style
.width
= col
.width
;
2770 th
.style
.textAlign
= col
.align
;
2773 $(th
).append(col
.caption
);
2777 if (has_description
)
2779 var tr
= table
.insertRow(-1);
2780 tr
.className
= 'cbi-section-table-descr';
2782 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2784 var col
= this.options
.columns
[i
];
2785 var th
= document
.createElement('th');
2786 th
.className
= 'cbi-section-table-cell';
2791 th
.style
.width
= col
.width
;
2794 th
.style
.textAlign
= col
.align
;
2796 if (col
.description
)
2797 $(th
).append(col
.description
);
2801 if (this._rows
.length
== 0)
2803 if (this.options
.placeholder
)
2805 var tr
= table
.insertRow(-1);
2806 var td
= tr
.insertCell(-1);
2807 td
.className
= 'cbi-section-table-cell';
2809 td
.colSpan
= this.options
.columns
.length
;
2810 $(td
).append(this.options
.placeholder
);
2815 for (var i
= 0; i
< this._rows
.length
; i
++)
2817 var tr
= table
.insertRow(-1);
2819 for (var j
= 0; j
< this.options
.columns
.length
; j
++)
2821 var col
= this.options
.columns
[j
];
2822 var td
= tr
.insertCell(-1);
2824 var val
= this._rows
[i
][j
];
2826 if (typeof(val
) == 'undefined')
2827 val
= col
.placeholder
;
2829 if (typeof(val
) == 'undefined')
2833 td
.style
.width
= col
.width
;
2836 td
.style
.textAlign
= col
.align
;
2838 if (typeof col
.format
== 'string')
2839 $(td
).append(col
.format
.format(val
));
2840 else if (typeof col
.format
== 'function')
2841 $(td
).append(col
.format(val
, i
));
2849 fieldset
.appendChild(table
);
2855 this.ui
.progress
= this.ui
.AbstractWidget
.extend({
2858 var vn
= parseInt(this.options
.value
) || 0;
2859 var mn
= parseInt(this.options
.max
) || 100;
2860 var pc
= Math
.floor((100 / mn
) * vn
);
2864 if (typeof(this.options
.format
) == 'string')
2865 text
= this.options
.format
.format(this.options
.value
, this.options
.max
, pc
);
2866 else if (typeof(this.options
.format
) == 'function')
2867 text
= this.options
.format(pc
);
2869 text
= '%.2f%%'.format(pc
);
2872 .addClass('progress')
2873 .append($('<div />')
2874 .addClass('progress-bar')
2875 .addClass('progress-bar-info')
2876 .css('width', pc
+ '%'))
2877 .append($('<small />')
2882 this.ui
.devicebadge
= this.ui
.AbstractWidget
.extend({
2885 var l2dev
= this.options
.l2_device
|| this.options
.device
;
2886 var l3dev
= this.options
.l3_device
;
2887 var dev
= l3dev
|| l2dev
|| '?';
2889 var span
= document
.createElement('span');
2890 span
.className
= 'badge';
2892 if (typeof(this.options
.signal
) == 'number' ||
2893 typeof(this.options
.noise
) == 'number')
2896 if (typeof(this.options
.signal
) != 'undefined' &&
2897 typeof(this.options
.noise
) != 'undefined')
2899 var q
= (-1 * (this.options
.noise
- this.options
.signal
)) / 5;
2912 span
.appendChild(document
.createElement('img'));
2913 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/signal-' + r
+ '.png';
2916 span
.title
= _luci2
.tr('No signal');
2918 span
.title
= '%s: %d %s / %s: %d %s'.format(
2919 _luci2
.tr('Signal'), this.options
.signal
, _luci2
.tr('dBm'),
2920 _luci2
.tr('Noise'), this.options
.noise
, _luci2
.tr('dBm')
2925 var type
= 'ethernet';
2926 var desc
= _luci2
.tr('Ethernet device');
2931 desc
= _luci2
.tr('Tunnel interface');
2933 else if (dev
.indexOf('br-') == 0)
2936 desc
= _luci2
.tr('Bridge');
2938 else if (dev
.indexOf('.') > 0)
2941 desc
= _luci2
.tr('VLAN interface');
2943 else if (dev
.indexOf('wlan') == 0 ||
2944 dev
.indexOf('ath') == 0 ||
2945 dev
.indexOf('wl') == 0)
2948 desc
= _luci2
.tr('Wireless Network');
2951 span
.appendChild(document
.createElement('img'));
2952 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/' + type
+ (this.options
.up
? '' : '_disabled') + '.png';
2956 $(span
).append(' ');
2957 $(span
).append(dev
);
2963 var type = function(f
, l
)
2973 _luci2
.cbi
.validation
.message
= _luci2
.tr(msg
);
2976 compile: function(code
)
2981 var types
= _luci2
.cbi
.validation
.types
;
2986 for (var i
= 0; i
< code
.length
; i
++)
2994 switch (code
.charCodeAt(i
))
3006 var label
= code
.substring(pos
, i
);
3007 label
= label
.replace(/\\(.)/g, '$1');
3008 label
= label
.replace(/^[ \t]+/g, '');
3009 label
= label
.replace(/[ \t]+$/g, '');
3011 if (label
&& !isNaN(label
))
3013 stack
.push(parseFloat(label
));
3015 else if (label
.match(/^(['"]).*\1$/))
3017 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
3019 else if (typeof types
[label
] == 'function')
3021 stack
.push(types
[label
]);
3026 throw "Syntax error, unhandled token '"+label
+"'";
3031 depth
+= (code
.charCodeAt(i
) == 40);
3037 if (typeof stack
[stack
.length
-2] != 'function')
3038 throw "Syntax error, argument list follows non-function";
3040 stack
[stack
.length
-1] =
3041 _luci2
.cbi
.validation
.compile(code
.substring(pos
, i
));
3054 var validation
= this.cbi
.validation
;
3056 validation
.types
= {
3057 'integer': function()
3059 if (this.match(/^-?[0-9]+$/) != null)
3062 validation
.i18n('Must be a valid integer');
3066 'uinteger': function()
3068 if (validation
.types
['integer'].apply(this) && (this >= 0))
3071 validation
.i18n('Must be a positive integer');
3077 if (!isNaN(parseFloat(this)))
3080 validation
.i18n('Must be a valid number');
3084 'ufloat': function()
3086 if (validation
.types
['float'].apply(this) && (this >= 0))
3089 validation
.i18n('Must be a positive number');
3093 'ipaddr': function()
3095 if (validation
.types
['ip4addr'].apply(this) ||
3096 validation
.types
['ip6addr'].apply(this))
3099 validation
.i18n('Must be a valid IP address');
3103 'ip4addr': function()
3105 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
3107 if ((RegExp
.$1 >= 0) && (RegExp
.$1 <= 255) &&
3108 (RegExp
.$2 >= 0) && (RegExp
.$2 <= 255) &&
3109 (RegExp
.$3 >= 0) && (RegExp
.$3 <= 255) &&
3110 (RegExp
.$4 >= 0) && (RegExp
.$4 <= 255) &&
3111 ((RegExp
.$6.indexOf('.') < 0)
3112 ? ((RegExp
.$6 >= 0) && (RegExp
.$6 <= 32))
3113 : (validation
.types
['ip4addr'].apply(RegExp
.$6))))
3117 validation
.i18n('Must be a valid IPv4 address');
3121 'ip6addr': function()
3123 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
3125 if (!RegExp
.$2 || ((RegExp
.$3 >= 0) && (RegExp
.$3 <= 128)))
3127 var addr
= RegExp
.$1;
3134 if (addr
.indexOf('.') > 0)
3136 var off
= addr
.lastIndexOf(':');
3138 if (!(off
&& validation
.types
['ip4addr'].apply(addr
.substr(off
+1))))
3140 validation
.i18n('Must be a valid IPv6 address');
3144 addr
= addr
.substr(0, off
) + ':0:0';
3147 if (addr
.indexOf('::') >= 0)
3152 for (var i
= 1; i
< (addr
.length
-1); i
++)
3153 if (addr
.charAt(i
) == ':')
3158 validation
.i18n('Must be a valid IPv6 address');
3162 for (var i
= 0; i
< (7 - colons
); i
++)
3165 if (addr
.match(/^(.*?)::(.*?)$/))
3166 addr
= (RegExp
.$1 ? RegExp
.$1 + ':' : '') + fill
+
3167 (RegExp
.$2 ? ':' + RegExp
.$2 : '');
3170 if (addr
.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
3173 validation
.i18n('Must be a valid IPv6 address');
3178 validation
.i18n('Must be a valid IPv6 address');
3184 if (validation
.types
['integer'].apply(this) &&
3185 (this >= 0) && (this <= 65535))
3188 validation
.i18n('Must be a valid port number');
3192 'portrange': function()
3194 if (this.match(/^(\d+)-(\d+)$/))
3199 if (validation
.types
['port'].apply(p1
) &&
3200 validation
.types
['port'].apply(p2
) &&
3201 (parseInt(p1
) <= parseInt(p2
)))
3204 else if (validation
.types
['port'].apply(this))
3209 validation
.i18n('Must be a valid port range');
3213 'macaddr': function()
3215 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
3218 validation
.i18n('Must be a valid MAC address');
3224 if (validation
.types
['hostname'].apply(this) ||
3225 validation
.types
['ipaddr'].apply(this))
3228 validation
.i18n('Must be a valid hostname or IP address');
3232 'hostname': function()
3234 if ((this.length
<= 253) &&
3235 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
3236 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
3237 this.match(/[^0-9.]/)))))
3240 validation
.i18n('Must be a valid host name');
3244 'network': function()
3246 if (validation
.types
['uciname'].apply(this) ||
3247 validation
.types
['host'].apply(this))
3250 validation
.i18n('Must be a valid network name');
3254 'wpakey': function()
3258 if ((v
.length
== 64)
3259 ? (v
.match(/^[a-fA-F0-9]{64}$/) != null)
3260 : ((v
.length
>= 8) && (v
.length
<= 63)))
3263 validation
.i18n('Must be a valid WPA key');
3267 'wepkey': function()
3271 if (v
.substr(0,2) == 's:')
3274 if (((v
.length
== 10) || (v
.length
== 26))
3275 ? (v
.match(/^[a-fA-F0-9]{10,26}$/) != null)
3276 : ((v
.length
== 5) || (v
.length
== 13)))
3279 validation
.i18n('Must be a valid WEP key');
3283 'uciname': function()
3285 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
3288 validation
.i18n('Must be a valid UCI identifier');
3292 'range': function(min
, max
)
3294 var val
= parseFloat(this);
3296 if (validation
.types
['integer'].apply(this) &&
3297 !isNaN(min
) && !isNaN(max
) && ((val
>= min
) && (val
<= max
)))
3300 validation
.i18n('Must be a number between %d and %d');
3304 'min': function(min
)
3306 var val
= parseFloat(this);
3308 if (validation
.types
['integer'].apply(this) &&
3309 !isNaN(min
) && !isNaN(val
) && (val
>= min
))
3312 validation
.i18n('Must be a number greater or equal to %d');
3316 'max': function(max
)
3318 var val
= parseFloat(this);
3320 if (validation
.types
['integer'].apply(this) &&
3321 !isNaN(max
) && !isNaN(val
) && (val
<= max
))
3324 validation
.i18n('Must be a number lower or equal to %d');
3328 'rangelength': function(min
, max
)
3330 var val
= '' + this;
3332 if (!isNaN(min
) && !isNaN(max
) &&
3333 (val
.length
>= min
) && (val
.length
<= max
))
3336 validation
.i18n('Must be between %d and %d characters');
3340 'minlength': function(min
)
3342 var val
= '' + this;
3344 if (!isNaN(min
) && (val
.length
>= min
))
3347 validation
.i18n('Must be at least %d characters');
3351 'maxlength': function(max
)
3353 var val
= '' + this;
3355 if (!isNaN(max
) && (val
.length
<= max
))
3358 validation
.i18n('Must be at most %d characters');
3366 for (var i
= 0; i
< arguments
.length
; i
+= 2)
3368 delete validation
.message
;
3370 if (typeof(arguments
[i
]) != 'function')
3372 if (arguments
[i
] == this)
3376 else if (arguments
[i
].apply(this, arguments
[i
+1]))
3381 if (validation
.message
)
3382 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
3385 validation
.message
= msgs
.join( _luci2
.tr(' - or - '));
3393 for (var i
= 0; i
< arguments
.length
; i
+= 2)
3395 delete validation
.message
;
3397 if (typeof arguments
[i
] != 'function')
3399 if (arguments
[i
] != this)
3403 else if (!arguments
[i
].apply(this, arguments
[i
+1]))
3408 if (validation
.message
)
3409 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
3412 validation
.message
= msgs
.join(', ');
3418 return validation
.types
['or'].apply(
3419 this.replace(/^[ \t]*![ \t]*/, ''), arguments
);
3422 'list': function(subvalidator
, subargs
)
3424 if (typeof subvalidator
!= 'function')
3427 var tokens
= this.match(/[^ \t]+/g);
3428 for (var i
= 0; i
< tokens
.length
; i
++)
3429 if (!subvalidator
.apply(tokens
[i
], subargs
))
3435 'phonedigit': function()
3437 if (this.match(/^[0-9\*#!\.]+$/) != null)
3440 validation
.i18n('Must be a valid phone number digit');
3444 'string': function()
3451 this.cbi
.AbstractValue
= this.ui
.AbstractWidget
.extend({
3452 init: function(name
, options
)
3455 this.instance
= { };
3456 this.dependencies
= [ ];
3457 this.rdependency
= { };
3459 this.options
= _luci2
.defaults(options
, {
3469 return this.section
.id('field', sid
|| '__unknown__', this.name
);
3472 render: function(sid
, condensed
)
3474 var i
= this.instance
[sid
] = { };
3476 i
.top
= $('<div />');
3480 i
.top
.addClass('form-group');
3482 if (typeof(this.options
.caption
) == 'string')
3484 .addClass('col-lg-2 control-label')
3485 .attr('for', this.id(sid
))
3486 .text(this.options
.caption
)
3490 i
.error
= $('<div />')
3492 .addClass('label label-danger');
3494 i
.widget
= $('<div />')
3496 .append(this.widget(sid
))
3502 i
.widget
.addClass('col-lg-5');
3505 .addClass('col-lg-5')
3506 .text((typeof(this.options
.description
) == 'string') ? this.options
.description
: '')
3513 ucipath: function(sid
)
3516 config
: (this.options
.uci_package
|| this.map
.uci_package
),
3517 section
: (this.options
.uci_section
|| sid
),
3518 option
: (this.options
.uci_option
|| this.name
)
3522 ucivalue: function(sid
)
3524 var uci
= this.ucipath(sid
);
3525 var val
= this.map
.get(uci
.config
, uci
.section
, uci
.option
);
3527 if (typeof(val
) == 'undefined')
3528 return this.options
.initial
;
3533 formvalue: function(sid
)
3535 var v
= $('#' + this.id(sid
)).val();
3536 return (v
=== '') ? undefined : v
;
3539 textvalue: function(sid
)
3541 var v
= this.formvalue(sid
);
3543 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
3544 v
= this.ucivalue(sid
);
3546 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
3547 v
= this.options
.placeholder
;
3549 if (typeof(v
) == 'undefined' || v
=== '')
3552 if (typeof(v
) == 'string' && $.isArray(this.choices
))
3554 for (var i
= 0; i
< this.choices
.length
; i
++)
3555 if (v
=== this.choices
[i
][0])
3556 return this.choices
[i
][1];
3558 else if (v
=== true)
3559 return _luci2
.tr('yes');
3560 else if (v
=== false)
3561 return _luci2
.tr('no');
3562 else if ($.isArray(v
))
3563 return v
.join(', ');
3568 changed: function(sid
)
3570 var a
= this.ucivalue(sid
);
3571 var b
= this.formvalue(sid
);
3573 if (typeof(a
) != typeof(b
))
3576 if (typeof(a
) == 'object')
3578 if (a
.length
!= b
.length
)
3581 for (var i
= 0; i
< a
.length
; i
++)
3593 var uci
= this.ucipath(sid
);
3595 if (this.instance
[sid
].disabled
)
3597 if (!this.options
.keep
)
3598 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3603 var chg
= this.changed(sid
);
3604 var val
= this.formvalue(sid
);
3607 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
);
3612 _ev_validate: function(ev
)
3616 var val
= d
.elem
.val();
3617 var vstack
= d
.vstack
;
3619 if (vstack
&& typeof(vstack
[0]) == 'function')
3621 delete validation
.message
;
3623 if ((val
.length
== 0 && !d
.opt
))
3625 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
3626 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
3628 d
.inst
.error
.text(_luci2
.tr('Field must not be empty')).show();
3631 else if (val
.length
> 0 && !vstack
[0].apply(val
, vstack
[1]))
3633 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
3634 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
3636 d
.inst
.error
.text(validation
.message
.format
.apply(validation
.message
, vstack
[1])).show();
3641 d
.elem
.parents('div.form-group, td').first().removeClass('luci2-form-error');
3642 d
.elem
.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
3644 if (d
.multi
&& d
.inst
.widget
&& d
.inst
.widget
.find('input.error, select.error').length
> 0)
3647 d
.inst
.error
.text('').hide();
3652 for (var field
in d
.self
.rdependency
)
3653 d
.self
.rdependency
[field
].toggle(d
.sid
);
3658 validator: function(sid
, elem
, multi
)
3660 if (typeof(this.options
.datatype
) == 'undefined' && $.isEmptyObject(this.rdependency
))
3664 if (typeof(this.options
.datatype
) == 'string')
3667 vstack
= _luci2
.cbi
.validation
.compile(this.options
.datatype
);
3670 else if (typeof(this.options
.datatype
) == 'function')
3672 var vfunc
= this.options
.datatype
;
3673 vstack
= [ function(elem
) {
3674 var rv
= vfunc(this, elem
);
3676 validation
.message
= rv
;
3677 return (rv
=== true);
3687 inst
: this.instance
[sid
],
3688 opt
: this.options
.optional
3691 if (elem
.prop('tagName') == 'SELECT')
3693 elem
.change(evdata
, this._ev_validate
);
3695 else if (elem
.prop('tagName') == 'INPUT' && elem
.attr('type') == 'checkbox')
3697 elem
.click(evdata
, this._ev_validate
);
3698 elem
.blur(evdata
, this._ev_validate
);
3702 elem
.keyup(evdata
, this._ev_validate
);
3703 elem
.blur(evdata
, this._ev_validate
);
3706 elem
.attr('cbi-validate', true).on('validate', evdata
, this._ev_validate
);
3711 validate: function(sid
)
3713 var i
= this.instance
[sid
];
3715 i
.widget
.find('[cbi-validate]').trigger('validate');
3717 return (i
.disabled
|| i
.error
.text() == '');
3720 depends: function(d
, v
)
3727 for (var i
= 0; i
< d
.length
; i
++)
3729 if (typeof(d
[i
]) == 'string')
3731 else if (d
[i
] instanceof _luci2
.cbi
.AbstractValue
)
3732 dep
[d
[i
].name
] = true;
3735 else if (d
instanceof _luci2
.cbi
.AbstractValue
)
3738 dep
[d
.name
] = (typeof(v
) == 'undefined') ? true : v
;
3740 else if (typeof(d
) == 'object')
3744 else if (typeof(d
) == 'string')
3747 dep
[d
] = (typeof(v
) == 'undefined') ? true : v
;
3750 if (!dep
|| $.isEmptyObject(dep
))
3753 for (var field
in dep
)
3755 var f
= this.section
.fields
[field
];
3757 f
.rdependency
[this.name
] = this;
3762 if ($.isEmptyObject(dep
))
3765 this.dependencies
.push(dep
);
3770 toggle: function(sid
)
3772 var d
= this.dependencies
;
3773 var i
= this.instance
[sid
];
3778 for (var n
= 0; n
< d
.length
; n
++)
3782 for (var field
in d
[n
])
3784 var val
= this.section
.fields
[field
].formvalue(sid
);
3785 var cmp
= d
[n
][field
];
3787 if (typeof(cmp
) == 'boolean')
3789 if (cmp
== (typeof(val
) == 'undefined' || val
=== '' || val
=== false))
3795 else if (typeof(cmp
) == 'string')
3803 else if (typeof(cmp
) == 'function')
3811 else if (cmp
instanceof RegExp
)
3836 i
.top
.is(':visible') ? i
.top
.fadeOut() : i
.top
.hide();
3843 this.cbi
.CheckboxValue
= this.cbi
.AbstractValue
.extend({
3844 widget: function(sid
)
3846 var o
= this.options
;
3848 if (typeof(o
.enabled
) == 'undefined') o
.enabled
= '1';
3849 if (typeof(o
.disabled
) == 'undefined') o
.disabled
= '0';
3851 var i
= $('<input />')
3852 .attr('id', this.id(sid
))
3853 .attr('type', 'checkbox')
3854 .prop('checked', this.ucivalue(sid
));
3857 .addClass('checkbox')
3858 .append(this.validator(sid
, i
));
3861 ucivalue: function(sid
)
3863 var v
= this.callSuper('ucivalue', sid
);
3865 if (typeof(v
) == 'boolean')
3868 return (v
== this.options
.enabled
);
3871 formvalue: function(sid
)
3873 var v
= $('#' + this.id(sid
)).prop('checked');
3875 if (typeof(v
) == 'undefined')
3876 return !!this.options
.initial
;
3883 var uci
= this.ucipath(sid
);
3885 if (this.instance
[sid
].disabled
)
3887 if (!this.options
.keep
)
3888 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3893 var chg
= this.changed(sid
);
3894 var val
= this.formvalue(sid
);
3898 if (this.options
.optional
&& val
== this.options
.initial
)
3899 this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3901 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
? this.options
.enabled
: this.options
.disabled
);
3908 this.cbi
.InputValue
= this.cbi
.AbstractValue
.extend({
3909 widget: function(sid
)
3911 var i
= $('<input />')
3912 .addClass('form-control')
3913 .attr('id', this.id(sid
))
3914 .attr('type', 'text')
3915 .attr('placeholder', this.options
.placeholder
)
3916 .val(this.ucivalue(sid
));
3918 return this.validator(sid
, i
);
3922 this.cbi
.PasswordValue
= this.cbi
.AbstractValue
.extend({
3923 widget: function(sid
)
3925 var i
= $('<input />')
3926 .addClass('form-control')
3927 .attr('id', this.id(sid
))
3928 .attr('type', 'password')
3929 .attr('placeholder', this.options
.placeholder
)
3930 .val(this.ucivalue(sid
));
3932 var t
= $('<span />')
3933 .addClass('input-group-btn')
3934 .append(_luci2
.ui
.button(_luci2
.tr('Reveal'), 'default')
3935 .click(function(ev
) {
3937 var i
= b
.parent().prev();
3938 var t
= i
.attr('type');
3939 b
.text(t
== 'password' ? _luci2
.tr('Hide') : _luci2
.tr('Reveal'));
3940 i
.attr('type', (t
== 'password') ? 'text' : 'password');
3944 this.validator(sid
, i
);
3947 .addClass('input-group')
3953 this.cbi
.ListValue
= this.cbi
.AbstractValue
.extend({
3954 widget: function(sid
)
3956 var s
= $('<select />')
3957 .addClass('form-control');
3959 if (this.options
.optional
)
3962 .text(_luci2
.tr('-- Please choose --'))
3966 for (var i
= 0; i
< this.choices
.length
; i
++)
3968 .attr('value', this.choices
[i
][0])
3969 .text(this.choices
[i
][1])
3972 s
.attr('id', this.id(sid
)).val(this.ucivalue(sid
));
3974 return this.validator(sid
, s
);
3977 value: function(k
, v
)
3982 this.choices
.push([k
, v
|| k
]);
3987 this.cbi
.MultiValue
= this.cbi
.ListValue
.extend({
3988 widget: function(sid
)
3990 var v
= this.ucivalue(sid
);
3991 var t
= $('<div />').attr('id', this.id(sid
));
3994 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
3997 for (var i
= 0; i
< v
.length
; i
++)
4001 for (var i
= 0; i
< this.choices
.length
; i
++)
4004 .addClass('checkbox')
4005 .append($('<input />')
4006 .attr('type', 'checkbox')
4007 .attr('value', this.choices
[i
][0])
4008 .prop('checked', s
[this.choices
[i
][0]]))
4009 .append(this.choices
[i
][1])
4016 formvalue: function(sid
)
4019 var fields
= $('#' + this.id(sid
) + ' > label > input');
4021 for (var i
= 0; i
< fields
.length
; i
++)
4022 if (fields
[i
].checked
)
4023 rv
.push(fields
[i
].getAttribute('value'));
4028 textvalue: function(sid
)
4030 var v
= this.formvalue(sid
);
4034 for (var i
= 0; i
< this.choices
.length
; i
++)
4035 c
[this.choices
[i
][0]] = this.choices
[i
][1];
4039 for (var i
= 0; i
< v
.length
; i
++)
4040 t
.push(c
[v
[i
]] || v
[i
]);
4042 return t
.join(', ');
4046 this.cbi
.ComboBox
= this.cbi
.AbstractValue
.extend({
4047 _change: function(ev
)
4050 var self
= ev
.data
.self
;
4052 if (s
.selectedIndex
== (s
.options
.length
- 1))
4054 ev
.data
.select
.hide();
4055 ev
.data
.input
.show().focus();
4057 var v
= ev
.data
.input
.val();
4058 ev
.data
.input
.val(' ');
4059 ev
.data
.input
.val(v
);
4061 else if (self
.options
.optional
&& s
.selectedIndex
== 0)
4063 ev
.data
.input
.val('');
4067 ev
.data
.input
.val(ev
.data
.select
.val());
4074 var val
= this.value
;
4075 var self
= ev
.data
.self
;
4077 ev
.data
.select
.empty();
4079 if (self
.options
.optional
)
4082 .text(_luci2
.tr('-- please choose --'))
4083 .appendTo(ev
.data
.select
);
4086 for (var i
= 0; i
< self
.choices
.length
; i
++)
4088 if (self
.choices
[i
][0] == val
)
4092 .attr('value', self
.choices
[i
][0])
4093 .text(self
.choices
[i
][1])
4094 .appendTo(ev
.data
.select
);
4097 if (!seen
&& val
!= '')
4101 .appendTo(ev
.data
.select
);
4105 .text(_luci2
.tr('-- custom --'))
4106 .appendTo(ev
.data
.select
);
4108 ev
.data
.input
.hide();
4109 ev
.data
.select
.val(val
).show().focus();
4112 _enter: function(ev
)
4117 ev
.preventDefault();
4118 ev
.data
.self
._blur(ev
);
4122 widget: function(sid
)
4124 var d
= $('<div />')
4125 .attr('id', this.id(sid
));
4127 var t
= $('<input />')
4128 .attr('type', 'text')
4132 var s
= $('<select />')
4137 input
: this.validator(sid
, t
),
4138 select
: this.validator(sid
, s
)
4141 s
.change(evdata
, this._change
);
4142 t
.blur(evdata
, this._blur
);
4143 t
.keydown(evdata
, this._enter
);
4145 t
.val(this.ucivalue(sid
));
4151 value: function(k
, v
)
4156 this.choices
.push([k
, v
|| k
]);
4160 formvalue: function(sid
)
4162 var v
= $('#' + this.id(sid
)).children('input').val();
4163 return (v
== '') ? undefined : v
;
4167 this.cbi
.DynamicList
= this.cbi
.ComboBox
.extend({
4168 _redraw: function(focus
, add
, del
, s
)
4170 var v
= s
.values
|| [ ];
4173 $(s
.parent
).children('div.input-group').children('input').each(function(i
) {
4175 v
.push(this.value
|| '');
4178 $(s
.parent
).empty();
4183 v
.splice(focus
, 0, '');
4185 else if (v
.length
== 0)
4191 for (var i
= 0; i
< v
.length
; i
++)
4198 remove
: ((i
+1) < v
.length
)
4203 btn
= _luci2
.ui
.button('–', 'danger').click(evdata
, this._btnclick
);
4205 btn
= _luci2
.ui
.button('+', 'success').click(evdata
, this._btnclick
);
4209 var txt
= $('<input />')
4210 .addClass('form-control')
4211 .attr('type', 'text')
4214 var sel
= $('<select />')
4215 .addClass('form-control');
4218 .addClass('input-group')
4221 .append($('<span />')
4222 .addClass('input-group-btn')
4224 .appendTo(s
.parent
);
4226 evdata
.input
= this.validator(s
.sid
, txt
, true);
4227 evdata
.select
= this.validator(s
.sid
, sel
, true);
4229 sel
.change(evdata
, this._change
);
4230 txt
.blur(evdata
, this._blur
);
4231 txt
.keydown(evdata
, this._keydown
);
4236 if (i
== focus
|| -(i
+1) == focus
)
4243 var f
= $('<input />')
4244 .attr('type', 'text')
4246 .attr('placeholder', (i
== 0) ? this.options
.placeholder
: '')
4247 .addClass('form-control')
4248 .keydown(evdata
, this._keydown
)
4249 .keypress(evdata
, this._keypress
)
4253 .addClass('input-group')
4255 .append($('<span />')
4256 .addClass('input-group-btn')
4258 .appendTo(s
.parent
);
4264 else if (-(i
+1) == focus
)
4268 /* force cursor to end */
4274 evdata
.input
= this.validator(s
.sid
, f
, true);
4285 _keypress: function(ev
)
4289 /* backspace, delete */
4292 if (ev
.data
.input
.val() == '')
4294 ev
.preventDefault();
4300 /* enter, arrow up, arrow down */
4304 ev
.preventDefault();
4311 _keydown: function(ev
)
4313 var input
= ev
.data
.input
;
4317 /* backspace, delete */
4320 if (input
.val().length
== 0)
4322 ev
.preventDefault();
4324 var index
= ev
.data
.index
;
4330 ev
.data
.self
._redraw(focus
, -1, index
, ev
.data
);
4338 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
4343 var prev
= input
.parent().prevAll('div.input-group:first').children('input');
4344 if (prev
.is(':visible'))
4347 prev
.next('select').focus();
4352 var next
= input
.parent().nextAll('div.input-group:first').children('input');
4353 if (next
.is(':visible'))
4356 next
.next('select').focus();
4363 _btnclick: function(ev
)
4365 if (!this.getAttribute('disabled'))
4369 var index
= ev
.data
.index
;
4370 ev
.data
.self
._redraw(-index
, -1, index
, ev
.data
);
4374 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
4381 widget: function(sid
)
4383 this.options
.optional
= true;
4385 var v
= this.ucivalue(sid
);
4388 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
4390 var d
= $('<div />')
4391 .attr('id', this.id(sid
))
4392 .addClass('cbi-input-dynlist');
4394 this._redraw(NaN
, -1, -1, {
4404 ucivalue: function(sid
)
4406 var v
= this.callSuper('ucivalue', sid
);
4409 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
4414 formvalue: function(sid
)
4417 var fields
= $('#' + this.id(sid
) + ' > input');
4419 for (var i
= 0; i
< fields
.length
; i
++)
4420 if (typeof(fields
[i
].value
) == 'string' && fields
[i
].value
.length
)
4421 rv
.push(fields
[i
].value
);
4427 this.cbi
.DummyValue
= this.cbi
.AbstractValue
.extend({
4428 widget: function(sid
)
4431 .addClass('form-control-static')
4432 .attr('id', this.id(sid
))
4433 .html(this.ucivalue(sid
));
4436 formvalue: function(sid
)
4438 return this.ucivalue(sid
);
4442 this.cbi
.NetworkList
= this.cbi
.AbstractValue
.extend({
4447 if (!self
.interfaces
)
4449 self
.interfaces
= [ ];
4450 return _luci2
.network
.getNetworkStatus().then(function(ifaces
) {
4451 self
.interfaces
= ifaces
;
4459 _device_icon: function(dev
)
4461 var type
= 'ethernet';
4462 var desc
= _luci2
.tr('Ethernet device');
4464 if (dev
.type
== 'IP tunnel')
4467 desc
= _luci2
.tr('Tunnel interface');
4469 else if (dev
['bridge-members'])
4472 desc
= _luci2
.tr('Bridge');
4474 else if (dev
.wireless
)
4477 desc
= _luci2
.tr('Wireless Network');
4479 else if (dev
.device
.indexOf('.') > 0)
4482 desc
= _luci2
.tr('VLAN interface');
4486 .attr('src', _luci2
.globals
.resource
+ '/icons/' + type
+ (dev
.up
? '' : '_disabled') + '.png')
4487 .attr('title', '%s (%s)'.format(desc
, dev
.device
));
4490 widget: function(sid
)
4492 var id
= this.id(sid
);
4493 var ul
= $('<ul />')
4495 .addClass('list-unstyled');
4497 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
4498 var value
= this.ucivalue(sid
);
4501 if (!this.options
.multiple
)
4502 check
[value
] = true;
4504 for (var i
= 0; i
< value
.length
; i
++)
4505 check
[value
[i
]] = true;
4507 if (this.interfaces
)
4509 for (var i
= 0; i
< this.interfaces
.length
; i
++)
4511 var iface
= this.interfaces
[i
];
4512 var badge
= $('<span />')
4514 .text('%s: '.format(iface
['interface']));
4516 if (iface
.device
&& iface
.device
.subdevices
)
4517 for (var j
= 0; j
< iface
.device
.subdevices
.length
; j
++)
4518 badge
.append(this._device_icon(iface
.device
.subdevices
[j
]));
4519 else if (iface
.device
)
4520 badge
.append(this._device_icon(iface
.device
));
4522 badge
.append($('<em />').text(_luci2
.tr('(No devices attached)')));
4525 .append($('<label />')
4526 .addClass(itype
+ ' inline')
4527 .append($('<input />')
4528 .attr('name', itype
+ id
)
4529 .attr('type', itype
)
4530 .attr('value', iface
['interface'])
4531 .prop('checked', !!check
[iface
['interface']]))
4537 if (!this.options
.multiple
)
4540 .append($('<label />')
4541 .addClass(itype
+ ' inline text-muted')
4542 .append($('<input />')
4543 .attr('name', itype
+ id
)
4544 .attr('type', itype
)
4546 .prop('checked', !value
))
4547 .append(_luci2
.tr('unspecified')))
4554 ucivalue: function(sid
)
4556 var v
= this.callSuper('ucivalue', sid
);
4558 if (!this.options
.multiple
)
4564 else if (typeof(v
) == 'string')
4567 return v
? v
[0] : undefined;
4574 if (typeof(v
) == 'string')
4575 v
= v
.match(/\S+/g);
4581 formvalue: function(sid
)
4583 var inputs
= $('#' + this.id(sid
) + ' input');
4585 if (!this.options
.multiple
)
4587 for (var i
= 0; i
< inputs
.length
; i
++)
4588 if (inputs
[i
].checked
&& inputs
[i
].value
!== '')
4589 return inputs
[i
].value
;
4596 for (var i
= 0; i
< inputs
.length
; i
++)
4597 if (inputs
[i
].checked
)
4598 rv
.push(inputs
[i
].value
);
4600 return rv
.length
? rv
: undefined;
4605 this.cbi
.AbstractSection
= this.ui
.AbstractWidget
.extend({
4608 var s
= [ arguments
[0], this.map
.uci_package
, this.uci_type
];
4610 for (var i
= 1; i
< arguments
.length
; i
++)
4611 s
.push(arguments
[i
].replace(/\./g, '_'));
4616 option: function(widget
, name
, options
)
4618 if (this.tabs
.length
== 0)
4619 this.tab({ id
: '__default__', selected
: true });
4621 return this.taboption('__default__', widget
, name
, options
);
4624 tab: function(options
)
4626 if (options
.selected
)
4627 this.tabs
.selected
= this.tabs
.length
;
4631 caption
: options
.caption
,
4632 description
: options
.description
,
4638 taboption: function(tabid
, widget
, name
, options
)
4641 for (var i
= 0; i
< this.tabs
.length
; i
++)
4643 if (this.tabs
[i
].id
== tabid
)
4651 throw 'Cannot append to unknown tab ' + tabid
;
4653 var w
= widget
? new widget(name
, options
) : null;
4655 if (!(w
instanceof _luci2
.cbi
.AbstractValue
))
4656 throw 'Widget must be an instance of AbstractValue';
4661 this.fields
[name
] = w
;
4667 ucipackages: function(pkg
)
4669 for (var i
= 0; i
< this.tabs
.length
; i
++)
4670 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4671 if (this.tabs
[i
].fields
[j
].options
.uci_package
)
4672 pkg
[this.tabs
[i
].fields
[j
].options
.uci_package
] = true;
4675 formvalue: function()
4679 this.sections(function(s
) {
4680 var sid
= s
['.name'];
4681 var sv
= rv
[sid
] || (rv
[sid
] = { });
4683 for (var i
= 0; i
< this.tabs
.length
; i
++)
4684 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4686 var val
= this.tabs
[i
].fields
[j
].formvalue(sid
);
4687 sv
[this.tabs
[i
].fields
[j
].name
] = val
;
4694 validate_section: function(sid
)
4696 var inst
= this.instance
[sid
];
4699 var badge
= $('#' + this.id('teaser', sid
)).children('span:first');
4701 for (var i
= 0; i
< this.tabs
.length
; i
++)
4704 var stbadge
= $('#' + this.id('nodetab', sid
, this.tabs
[i
].id
)).children('span:first');
4706 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4707 if (!this.tabs
[i
].fields
[j
].validate(sid
))
4713 .attr('title', _luci2
.trp('1 Error', '%d Errors', inval
).format(inval
));
4723 .attr('title', _luci2
.trp('1 Error', '%d Errors', invals
).format(invals
));
4730 validate: function()
4732 this.error_count
= 0;
4734 var as
= this.sections();
4736 for (var i
= 0; i
< as
.length
; i
++)
4738 var invals
= this.validate_section(as
[i
]['.name']);
4741 this.error_count
+= invals
;
4744 var badge
= $('#' + this.id('sectiontab')).children('span:first');
4746 if (this.error_count
> 0)
4748 .text(this.error_count
)
4749 .attr('title', _luci2
.trp('1 Error', '%d Errors', this.error_count
).format(this.error_count
));
4753 return (this.error_count
== 0);
4757 this.cbi
.TypedSection
= this.cbi
.AbstractSection
.extend({
4758 init: function(uci_type
, options
)
4760 this.uci_type
= uci_type
;
4761 this.options
= options
;
4764 this.error_count
= 0;
4765 this.active_panel
= 0;
4766 this.active_tab
= { };
4769 filter: function(section
)
4774 sections: function(cb
)
4776 var s1
= this.map
.ucisections(this.map
.uci_package
);
4779 for (var i
= 0; i
< s1
.length
; i
++)
4780 if (s1
[i
]['.type'] == this.uci_type
)
4781 if (this.filter(s1
[i
]))
4784 if (typeof(cb
) == 'function')
4785 for (var i
= 0; i
< s2
.length
; i
++)
4786 cb
.apply(this, [ s2
[i
] ]);
4793 this.map
.add(this.map
.uci_package
, this.uci_type
, name
);
4796 remove: function(sid
)
4798 this.map
.remove(this.map
.uci_package
, sid
);
4801 _ev_add: function(ev
)
4804 var name
= undefined;
4805 var self
= ev
.data
.self
;
4807 if (addb
.prev().prop('nodeName') == 'INPUT')
4808 name
= addb
.prev().val();
4810 if (addb
.prop('disabled') || name
=== '')
4813 _luci2
.ui
.saveScrollTop();
4815 self
.active_panel
= -1;
4820 _luci2
.ui
.restoreScrollTop();
4823 _ev_remove: function(ev
)
4825 var self
= ev
.data
.self
;
4826 var sid
= ev
.data
.sid
;
4828 _luci2
.ui
.saveScrollTop();
4834 _luci2
.ui
.restoreScrollTop();
4836 ev
.stopPropagation();
4839 _ev_sid: function(ev
)
4841 var self
= ev
.data
.self
;
4843 var addb
= text
.next();
4844 var errt
= addb
.next();
4845 var name
= text
.val();
4848 if (!/^[a-zA-Z0-9_]*$/.test(name
))
4850 errt
.text(_luci2
.tr('Invalid section name')).show();
4851 text
.addClass('error');
4852 addb
.prop('disabled', true);
4856 for (var sid
in self
.map
.uci
.values
[self
.map
.uci_package
])
4863 for (var sid
in self
.map
.uci
.creates
[self
.map
.uci_package
])
4872 errt
.text(_luci2
.tr('Name already used')).show();
4873 text
.addClass('error');
4874 addb
.prop('disabled', true);
4878 errt
.text('').hide();
4879 text
.removeClass('error');
4880 addb
.prop('disabled', false);
4884 _ev_tab: function(ev
)
4886 var self
= ev
.data
.self
;
4887 var sid
= ev
.data
.sid
;
4890 self
.active_tab
[sid
] = parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
4893 _ev_panel_collapse: function(ev
)
4895 var self
= ev
.data
.self
;
4897 var this_panel
= $(ev
.target
);
4898 var this_toggle
= this_panel
.prevAll('[data-toggle="collapse"]:first');
4900 var prev_toggle
= $($(ev
.delegateTarget
).find('[data-toggle="collapse"]:eq(%d)'.format(self
.active_panel
)));
4901 var prev_panel
= $(prev_toggle
.attr('data-target'));
4905 .addClass('collapse');
4907 prev_toggle
.find('.luci2-section-teaser')
4909 .children('span:last')
4911 .append(self
.teaser(prev_panel
.attr('data-luci2-sid')));
4913 this_toggle
.find('.luci2-section-teaser')
4916 self
.active_panel
= parseInt(this_panel
.attr('data-luci2-panel-index'));
4920 _ev_panel_open: function(ev
)
4922 var self
= ev
.data
.self
;
4923 var panel
= $($(this).attr('data-target'));
4924 var index
= parseInt(panel
.attr('data-luci2-panel-index'));
4926 if (index
== self
.active_panel
)
4927 ev
.stopPropagation();
4930 _ev_sort: function(ev
)
4932 var self
= ev
.data
.self
;
4933 var cur_idx
= ev
.data
.index
;
4934 var new_idx
= cur_idx
+ (ev
.data
.up
? -1 : 1);
4935 var s
= self
.sections();
4937 if (new_idx
>= 0 && new_idx
< s
.length
)
4939 var tmp
= s
[cur_idx
]['.index'];
4941 s
[cur_idx
]['.index'] = s
[new_idx
]['.index'];
4942 s
[new_idx
]['.index'] = tmp
;
4944 if (self
.active_panel
== cur_idx
)
4945 self
.active_panel
= new_idx
;
4946 else if (self
.active_panel
== new_idx
)
4947 self
.active_panel
= cur_idx
;
4949 self
.map
.uci
.reorder
= true;
4955 ev
.stopPropagation();
4958 teaser: function(sid
)
4960 var tf
= this.teaser_fields
;
4964 tf
= this.teaser_fields
= [ ];
4966 if ($.isArray(this.options
.teasers
))
4968 for (var i
= 0; i
< this.options
.teasers
.length
; i
++)
4970 var f
= this.options
.teasers
[i
];
4971 if (f
instanceof _luci2
.cbi
.AbstractValue
)
4973 else if (typeof(f
) == 'string' && this.fields
[f
] instanceof _luci2
.cbi
.AbstractValue
)
4974 tf
.push(this.fields
[f
]);
4979 for (var i
= 0; tf
.length
<= 5 && i
< this.tabs
.length
; i
++)
4980 for (var j
= 0; tf
.length
<= 5 && j
< this.tabs
[i
].fields
.length
; j
++)
4981 tf
.push(this.tabs
[i
].fields
[j
]);
4987 for (var i
= 0; i
< tf
.length
; i
++)
4989 if (tf
[i
].instance
[sid
] && tf
[i
].instance
[sid
].disabled
)
4992 var n
= tf
[i
].options
.caption
|| tf
[i
].name
;
4993 var v
= tf
[i
].textvalue(sid
);
4995 if (typeof(v
) == 'undefined')
4998 t
= t
+ '%s%s: <strong>%s</strong>'.format(t
? ' | ' : '', n
, v
);
5004 _render_add: function()
5006 if (!this.options
.addremove
)
5009 var text
= _luci2
.tr('Add section');
5010 var ttip
= _luci2
.tr('Create new section...');
5012 if ($.isArray(this.options
.add_caption
))
5013 text
= this.options
.add_caption
[0], ttip
= this.options
.add_caption
[1];
5014 else if (typeof(this.options
.add_caption
) == 'string')
5015 text
= this.options
.add_caption
, ttip
= '';
5017 var add
= $('<div />');
5019 if (this.options
.anonymous
=== false)
5022 .addClass('cbi-input-text')
5023 .attr('type', 'text')
5024 .attr('placeholder', ttip
)
5025 .blur({ self
: this }, this._ev_sid
)
5026 .keyup({ self
: this }, this._ev_sid
)
5030 .attr('src', _luci2
.globals
.resource
+ '/icons/cbi/add.gif')
5031 .attr('title', text
)
5032 .addClass('cbi-button')
5033 .click({ self
: this }, this._ev_add
)
5037 .addClass('cbi-value-error')
5043 _luci2
.ui
.button(text
, 'success', ttip
)
5044 .click({ self
: this }, this._ev_add
)
5051 _render_remove: function(sid
, index
)
5053 if (!this.options
.addremove
)
5056 var text
= _luci2
.tr('Remove');
5057 var ttip
= _luci2
.tr('Remove this section');
5059 if ($.isArray(this.options
.remove_caption
))
5060 text
= this.options
.remove_caption
[0], ttip
= this.options
.remove_caption
[1];
5061 else if (typeof(this.options
.remove_caption
) == 'string')
5062 text
= this.options
.remove_caption
, ttip
= '';
5064 return _luci2
.ui
.button(text
, 'danger', ttip
)
5065 .click({ self
: this, sid
: sid
, index
: index
}, this._ev_remove
);
5068 _render_sort: function(sid
, index
)
5070 if (!this.options
.sortable
)
5073 var b1
= _luci2
.ui
.button('↑', 'info', _luci2
.tr('Move up'))
5074 .click({ self
: this, index
: index
, up
: true }, this._ev_sort
);
5076 var b2
= _luci2
.ui
.button('↓', 'info', _luci2
.tr('Move down'))
5077 .click({ self
: this, index
: index
, up
: false }, this._ev_sort
);
5082 _render_caption: function()
5085 .addClass('panel-title')
5086 .append(this.label('caption') || this.uci_type
);
5089 _render_description: function()
5091 var text
= this.label('description');
5095 .addClass('luci2-section-description')
5101 _render_teaser: function(sid
, index
)
5103 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
5106 .attr('id', this.id('teaser', sid
))
5107 .addClass('luci2-section-teaser well well-sm')
5108 .append($('<span />')
5110 .append($('<span />'));
5116 _render_head: function(condensed
)
5122 .addClass('panel-heading')
5123 .append(this._render_caption())
5124 .append(this._render_description());
5127 _render_tab_description: function(sid
, index
, tab_index
)
5129 var tab
= this.tabs
[tab_index
];
5131 if (typeof(tab
.description
) == 'string')
5134 .addClass('cbi-tab-descr')
5135 .text(tab
.description
);
5141 _render_tab_head: function(sid
, index
, tab_index
)
5143 var tab
= this.tabs
[tab_index
];
5144 var cur
= this.active_tab
[sid
] || 0;
5146 var tabh
= $('<li />')
5148 .attr('id', this.id('nodetab', sid
, tab
.id
))
5149 .attr('href', '#' + this.id('node', sid
, tab
.id
))
5150 .attr('data-toggle', 'tab')
5151 .attr('data-luci2-tab-index', tab_index
)
5152 .text((tab
.caption
? tab
.caption
.format(tab
.id
) : tab
.id
) + ' ')
5153 .append($('<span />')
5155 .on('shown.bs.tab', { self
: this, sid
: sid
}, this._ev_tab
));
5157 if (cur
== tab_index
)
5158 tabh
.addClass('active');
5163 _render_tab_body: function(sid
, index
, tab_index
)
5165 var tab
= this.tabs
[tab_index
];
5166 var cur
= this.active_tab
[sid
] || 0;
5168 var tabb
= $('<div />')
5169 .addClass('tab-pane')
5170 .attr('id', this.id('node', sid
, tab
.id
))
5171 .attr('data-luci2-tab-index', tab_index
)
5172 .append(this._render_tab_description(sid
, index
, tab_index
));
5174 if (cur
== tab_index
)
5175 tabb
.addClass('active');
5177 for (var i
= 0; i
< tab
.fields
.length
; i
++)
5178 tabb
.append(tab
.fields
[i
].render(sid
));
5183 _render_section_head: function(sid
, index
)
5185 var head
= $('<div />')
5186 .addClass('luci2-section-header')
5187 .append(this._render_teaser(sid
, index
))
5188 .append($('<div />')
5189 .addClass('btn-group')
5190 .append(this._render_sort(sid
, index
))
5191 .append(this._render_remove(sid
, index
)));
5193 if (this.options
.collabsible
)
5195 head
.attr('data-toggle', 'collapse')
5196 .attr('data-parent', this.id('sectiongroup'))
5197 .attr('data-target', '#' + this.id('panel', sid
))
5198 .on('click', { self
: this }, this._ev_panel_open
);
5204 _render_section_body: function(sid
, index
)
5206 var body
= $('<div />')
5207 .attr('id', this.id('panel', sid
))
5208 .attr('data-luci2-panel-index', index
)
5209 .attr('data-luci2-sid', sid
);
5211 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
5213 body
.addClass('panel-collapse collapse');
5215 if (index
== this.active_panel
)
5216 body
.addClass('in');
5219 var tab_heads
= $('<ul />')
5220 .addClass('nav nav-tabs');
5222 var tab_bodies
= $('<div />')
5223 .addClass('form-horizontal tab-content')
5226 for (var j
= 0; j
< this.tabs
.length
; j
++)
5228 tab_heads
.append(this._render_tab_head(sid
, index
, j
));
5229 tab_bodies
.append(this._render_tab_body(sid
, index
, j
));
5232 body
.append(tab_bodies
);
5234 if (this.tabs
.length
<= 1)
5240 _render_body: function(condensed
)
5242 var s
= this.sections();
5244 if (this.active_panel
< 0)
5245 this.active_panel
+= s
.length
;
5246 else if (this.active_panel
>= s
.length
)
5247 this.active_panel
= s
.length
- 1;
5249 var body
= $('<ul />')
5250 .addClass('list-group');
5252 if (this.options
.collabsible
)
5254 body
.attr('id', this.id('sectiongroup'))
5255 .on('show.bs.collapse', { self
: this }, this._ev_panel_collapse
);
5260 body
.append($('<li />')
5261 .addClass('list-group-item text-muted')
5262 .text(this.label('placeholder') || _luci2
.tr('There are no entries defined yet.')))
5265 for (var i
= 0; i
< s
.length
; i
++)
5267 var sid
= s
[i
]['.name'];
5268 var inst
= this.instance
[sid
] = { tabs
: [ ] };
5270 body
.append($('<li />')
5271 .addClass('list-group-item')
5272 .append(this._render_section_head(sid
, i
))
5273 .append(this._render_section_body(sid
, i
)));
5279 render: function(condensed
)
5281 this.instance
= { };
5283 var panel
= $('<div />')
5284 .addClass('panel panel-default')
5285 .append(this._render_head(condensed
))
5286 .append(this._render_body(condensed
));
5288 if (this.options
.addremove
)
5289 panel
.append($('<div />')
5290 .addClass('panel-footer')
5291 .append(this._render_add()));
5298 var s
= this.sections();
5300 for (var i
= 0; i
< s
.length
; i
++)
5302 var sid
= s
[i
]['.name'];
5304 this.validate_section(sid
);
5306 if (i
!= this.active_panel
)
5307 $('#' + this.id('teaser', sid
)).children('span:last')
5308 .append(this.teaser(sid
));
5310 $('#' + this.id('teaser', sid
))
5316 this.cbi
.TableSection
= this.cbi
.TypedSection
.extend({
5317 _render_table_head: function()
5319 var thead
= $('<thead />')
5321 .addClass('cbi-section-table-titles'));
5323 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
5324 thead
.children().append($('<th />')
5325 .addClass('cbi-section-table-cell')
5326 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
5327 .append(this.tabs
[0].fields
[j
].label('caption')));
5329 if (this.options
.addremove
!== false || this.options
.sortable
)
5330 thead
.children().append($('<th />')
5331 .addClass('cbi-section-table-cell')
5337 _render_table_row: function(sid
, index
)
5339 var row
= $('<tr />')
5340 .attr('data-luci2-sid', sid
);
5342 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
5344 row
.append($('<td />')
5345 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
5346 .append(this.tabs
[0].fields
[j
].render(sid
, true)));
5349 if (this.options
.addremove
!== false || this.options
.sortable
)
5351 row
.append($('<td />')
5352 .addClass('text-right')
5353 .append($('<div />')
5354 .addClass('btn-group')
5355 .append(this._render_sort(sid
, index
))
5356 .append(this._render_remove(sid
, index
))));
5362 _render_table_body: function()
5364 var s
= this.sections();
5366 var tbody
= $('<tbody />');
5370 var cols
= this.tabs
[0].fields
.length
;
5372 if (this.options
.addremove
!== false || this.options
.sortable
)
5375 tbody
.append($('<tr />')
5377 .addClass('text-muted')
5378 .attr('colspan', cols
)
5379 .text(this.label('placeholder') || _luci2
.tr('There are no entries defined yet.'))));
5382 for (var i
= 0; i
< s
.length
; i
++)
5384 var sid
= s
[i
]['.name'];
5385 var inst
= this.instance
[sid
] = { tabs
: [ ] };
5387 tbody
.append(this._render_table_row(sid
, i
));
5393 _render_body: function(condensed
)
5395 return $('<table />')
5396 .addClass('table table-condensed table-hover')
5397 .append(this._render_table_head())
5398 .append(this._render_table_body());
5402 this.cbi
.NamedSection
= this.cbi
.TypedSection
.extend({
5403 sections: function(cb
)
5406 var pkg
= this.map
.uci
.values
[this.map
.uci_package
];
5409 if (pkg
[s
]['.name'] == this.uci_type
)
5415 if (typeof(cb
) == 'function' && sa
.length
> 0)
5416 cb
.apply(this, [ sa
[0] ]);
5422 this.cbi
.DummySection
= this.cbi
.TypedSection
.extend({
5423 sections: function(cb
)
5425 if (typeof(cb
) == 'function')
5426 cb
.apply(this, [ { '.name': this.uci_type
} ]);
5428 return [ { '.name': this.uci_type
} ];
5432 this.cbi
.Map
= this.ui
.AbstractWidget
.extend({
5433 init: function(uci_package
, options
)
5437 this.uci_package
= uci_package
;
5438 this.sections
= [ ];
5439 this.options
= _luci2
.defaults(options
, {
5440 save: function() { },
5441 prepare: function() {
5442 return _luci2
.uci
.writable(function(writable
) {
5443 self
.options
.readonly
= !writable
;
5449 _load_cb: function(packages
)
5451 for (var i
= 0; i
< packages
.length
; i
++)
5453 this.uci
.values
[packages
[i
]['.package']] = packages
[i
];
5454 delete packages
[i
]['.package'];
5457 var deferreds
= [ _luci2
.deferrable(this.options
.prepare()) ];
5459 for (var i
= 0; i
< this.sections
.length
; i
++)
5461 for (var f
in this.sections
[i
].fields
)
5463 if (typeof(this.sections
[i
].fields
[f
].load
) != 'function')
5466 var s
= this.sections
[i
].sections();
5467 for (var j
= 0; j
< s
.length
; j
++)
5469 var rv
= this.sections
[i
].fields
[f
].load(s
[j
]['.name']);
5470 if (_luci2
.isDeferred(rv
))
5476 return $.when
.apply($, deferreds
);
5494 for (var i
= 0; i
< this.sections
.length
; i
++)
5495 this.sections
[i
].ucipackages(packages
);
5497 packages
[this.uci_package
] = true;
5501 for (var pkg
in packages
)
5502 _luci2
.uci
.get_all(pkg
);
5504 return _luci2
.rpc
.flush().then(function(packages
) {
5505 return self
._load_cb(packages
);
5509 _ev_tab: function(ev
)
5511 var self
= ev
.data
.self
;
5514 self
.active_tab
= parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
5517 _render_tab_head: function(tab_index
)
5519 var section
= this.sections
[tab_index
];
5520 var cur
= this.active_tab
|| 0;
5522 var tabh
= $('<li />')
5524 .attr('id', section
.id('sectiontab'))
5525 .attr('href', '#' + section
.id('section'))
5526 .attr('data-toggle', 'tab')
5527 .attr('data-luci2-tab-index', tab_index
)
5528 .text(section
.label('caption') + ' ')
5529 .append($('<span />')
5531 .on('shown.bs.tab', { self
: this }, this._ev_tab
));
5533 if (cur
== tab_index
)
5534 tabh
.addClass('active');
5539 _render_tab_body: function(tab_index
)
5541 var section
= this.sections
[tab_index
];
5542 var desc
= section
.label('description');
5543 var cur
= this.active_tab
|| 0;
5545 var tabb
= $('<div />')
5546 .addClass('tab-pane')
5547 .attr('id', section
.id('section'))
5548 .attr('data-luci2-tab-index', tab_index
);
5550 if (cur
== tab_index
)
5551 tabb
.addClass('active');
5554 tabb
.append($('<p />')
5557 var s
= section
.render(this.options
.tabbed
);
5559 if (this.options
.readonly
|| section
.options
.readonly
)
5560 s
.find('input, select, button, img.cbi-button').attr('disabled', true);
5567 _render_body: function()
5569 var tabs
= $('<ul />')
5570 .addClass('nav nav-tabs');
5572 var body
= $('<div />')
5575 for (var i
= 0; i
< this.sections
.length
; i
++)
5577 tabs
.append(this._render_tab_head(i
));
5578 body
.append(this._render_tab_body(i
));
5581 if (this.options
.tabbed
)
5582 body
.addClass('tab-content');
5591 var map
= $('<form />');
5593 if (typeof(this.options
.caption
) == 'string')
5594 map
.append($('<h2 />')
5595 .text(this.options
.caption
));
5597 if (typeof(this.options
.description
) == 'string')
5598 map
.append($('<p />')
5599 .text(this.options
.description
));
5601 map
.append(this._render_body());
5603 if (this.options
.pageaction
!== false)
5605 map
.append($('<div />')
5606 .addClass('panel panel-default panel-body text-right')
5607 .append($('<div />')
5608 .addClass('btn-group')
5609 .append(_luci2
.ui
.button(_luci2
.tr('Save & Apply'), 'primary')
5610 .click({ self
: this }, function(ev
) { }))
5611 .append(_luci2
.ui
.button(_luci2
.tr('Save'), 'default')
5612 .click({ self
: this }, function(ev
) { ev
.data
.self
.send(); }))
5613 .append(_luci2
.ui
.button(_luci2
.tr('Reset'), 'default')
5614 .click({ self
: this }, function(ev
) { ev
.data
.self
.insertInto(ev
.data
.self
.target
); }))));
5622 for (var i
= 0; i
< this.sections
.length
; i
++)
5623 this.sections
[i
].finish();
5630 this.target
.hide().empty().append(this.render());
5635 section: function(widget
, uci_type
, options
)
5637 var w
= widget
? new widget(uci_type
, options
) : null;
5639 if (!(w
instanceof _luci2
.cbi
.AbstractSection
))
5640 throw 'Widget must be an instance of AbstractSection';
5643 w
.index
= this.sections
.length
;
5645 this.sections
.push(w
);
5649 formvalue: function()
5653 for (var i
= 0; i
< this.sections
.length
; i
++)
5655 var sids
= this.sections
[i
].formvalue();
5656 for (var sid
in sids
)
5658 var s
= rv
[sid
] || (rv
[sid
] = { });
5659 $.extend(s
, sids
[sid
]);
5666 add: function(conf
, type
, name
)
5668 var c
= this.uci
.creates
;
5669 var s
= '.new.%d'.format(this.uci
.newid
++);
5678 '.anonymous': !name
,
5679 '.index': 1000 + this.uci
.newid
5685 remove: function(conf
, sid
)
5687 var n
= this.uci
.creates
;
5688 var c
= this.uci
.changes
;
5689 var d
= this.uci
.deletes
;
5691 /* requested deletion of a just created section */
5692 if (sid
.indexOf('.new.') == 0)
5695 delete n
[conf
][sid
];
5700 delete c
[conf
][sid
];
5705 d
[conf
][sid
] = true;
5709 ucisections: function(conf
, cb
)
5712 var pkg
= this.uci
.values
[conf
];
5713 var crt
= this.uci
.creates
[conf
];
5714 var del
= this.uci
.deletes
[conf
];
5720 if (!del
|| del
[s
] !== true)
5727 sa
.sort(function(a
, b
) {
5728 return a
['.index'] - b
['.index'];
5731 for (var i
= 0; i
< sa
.length
; i
++)
5732 sa
[i
]['.index'] = i
;
5734 if (typeof(cb
) == 'function')
5735 for (var i
= 0; i
< sa
.length
; i
++)
5736 cb
.apply(this, [ sa
[i
] ]);
5741 get: function(conf
, sid
, opt
)
5743 var v
= this.uci
.values
;
5744 var n
= this.uci
.creates
;
5745 var c
= this.uci
.changes
;
5746 var d
= this.uci
.deletes
;
5748 /* requested option in a just created section */
5749 if (sid
.indexOf('.new.') == 0)
5754 if (typeof(opt
) == 'undefined')
5755 return (n
[conf
][sid
] || { });
5757 return n
[conf
][sid
][opt
];
5760 /* requested an option value */
5761 if (typeof(opt
) != 'undefined')
5763 /* check whether option was deleted */
5764 if (d
[conf
] && d
[conf
][sid
])
5766 if (d
[conf
][sid
] === true)
5769 for (var i
= 0; i
< d
[conf
][sid
].length
; i
++)
5770 if (d
[conf
][sid
][i
] == opt
)
5774 /* check whether option was changed */
5775 if (c
[conf
] && c
[conf
][sid
] && typeof(c
[conf
][sid
][opt
]) != 'undefined')
5776 return c
[conf
][sid
][opt
];
5778 /* return base value */
5779 if (v
[conf
] && v
[conf
][sid
])
5780 return v
[conf
][sid
][opt
];
5785 /* requested an entire section */
5787 return (v
[conf
][sid
] || { });
5792 set: function(conf
, sid
, opt
, val
)
5794 var n
= this.uci
.creates
;
5795 var c
= this.uci
.changes
;
5796 var d
= this.uci
.deletes
;
5798 if (sid
.indexOf('.new.') == 0)
5800 if (n
[conf
] && n
[conf
][sid
])
5802 if (typeof(val
) != 'undefined')
5803 n
[conf
][sid
][opt
] = val
;
5805 delete n
[conf
][sid
][opt
];
5808 else if (typeof(val
) != 'undefined')
5816 c
[conf
][sid
][opt
] = val
;
5826 d
[conf
][sid
].push(opt
);
5830 validate: function()
5834 for (var i
= 0; i
< this.sections
.length
; i
++)
5836 if (!this.sections
[i
].validate())
5845 if (this.options
.readonly
)
5846 return _luci2
.deferrable();
5848 var deferreds
= [ _luci2
.deferrable(this.options
.save()) ];
5850 for (var i
= 0; i
< this.sections
.length
; i
++)
5852 if (this.sections
[i
].options
.readonly
)
5855 for (var f
in this.sections
[i
].fields
)
5857 if (typeof(this.sections
[i
].fields
[f
].save
) != 'function')
5860 var s
= this.sections
[i
].sections();
5861 for (var j
= 0; j
< s
.length
; j
++)
5863 var rv
= this.sections
[i
].fields
[f
].save(s
[j
]['.name']);
5864 if (_luci2
.isDeferred(rv
))
5870 return $.when
.apply($, deferreds
);
5873 _send_uci_reorder: function()
5875 if (!this.uci
.reorder
)
5876 return _luci2
.deferrable();
5881 gather all created and existing sections, sort them according
5882 to their index value and issue an uci order call
5884 for (var c
in this.uci
.values
)
5888 if (this.uci
.creates
&& this.uci
.creates
[c
])
5889 for (var s
in this.uci
.creates
[c
])
5890 o
.push(this.uci
.creates
[c
][s
]);
5892 for (var s
in this.uci
.values
[c
])
5893 o
.push(this.uci
.values
[c
][s
]);
5897 o
.sort(function(a
, b
) {
5898 return (a
['.index'] - b
['.index']);
5903 for (var i
= 0; i
< o
.length
; i
++)
5904 sids
.push(o
[i
]['.name']);
5906 _luci2
.uci
.order(c
, sids
);
5910 return _luci2
.rpc
.flush();
5913 _send_uci: function()
5920 if (this.uci
.creates
)
5921 for (var c
in this.uci
.creates
)
5922 for (var s
in this.uci
.creates
[c
])
5929 for (var k
in this.uci
.creates
[c
][s
])
5932 r
.type
= this.uci
.creates
[c
][s
][k
];
5933 else if (k
== '.create')
5934 r
.name
= this.uci
.creates
[c
][s
][k
];
5935 else if (k
.charAt(0) != '.')
5936 r
.values
[k
] = this.uci
.creates
[c
][s
][k
];
5939 snew
.push(this.uci
.creates
[c
][s
]);
5941 _luci2
.uci
.add(r
.config
, r
.type
, r
.name
, r
.values
);
5944 if (this.uci
.changes
)
5945 for (var c
in this.uci
.changes
)
5946 for (var s
in this.uci
.changes
[c
])
5947 _luci2
.uci
.set(c
, s
, this.uci
.changes
[c
][s
]);
5949 if (this.uci
.deletes
)
5950 for (var c
in this.uci
.deletes
)
5951 for (var s
in this.uci
.deletes
[c
])
5953 var o
= this.uci
.deletes
[c
][s
];
5954 _luci2
.uci
['delete'](c
, s
, (o
=== true) ? undefined : o
);
5957 return _luci2
.rpc
.flush().then(function(responses
) {
5959 array "snew" holds references to the created uci sections,
5960 use it to assign the returned names of the new sections
5962 for (var i
= 0; i
< snew
.length
; i
++)
5963 snew
[i
]['.name'] = responses
[i
];
5965 return self
._send_uci_reorder();
5971 if (!this.validate())
5972 return _luci2
.deferrable();
5976 _luci2
.ui
.saveScrollTop();
5977 _luci2
.ui
.loading(true);
5979 return this.save().then(function() {
5980 return self
._send_uci();
5981 }).then(function() {
5982 return _luci2
.ui
.updateChanges();
5983 }).then(function() {
5985 }).then(function() {
5989 _luci2
.ui
.loading(false);
5990 _luci2
.ui
.restoreScrollTop();
5994 insertInto: function(id
)
5997 self
.target
= $(id
);
5999 _luci2
.ui
.loading(true);
6002 return self
.load().then(function() {
6003 self
.target
.empty().append(self
.render());
6007 _luci2
.ui
.loading(false);