98cd4411df400b785b093a5e8966ec9eae6cb467
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
= arguments
.callee
;
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
;
371 this.getHash = function(key
)
374 var tuples
= (location
.hash
|| '#').substring(1).split(/,/);
376 for (var i
= 0; i
< tuples
.length
; i
++)
378 var tuple
= tuples
[i
].split(/:/);
379 if (tuple
.length
== 2)
380 data
[tuple
[0]] = tuple
[1];
383 if (typeof(key
) != 'undefined')
392 sid
: '00000000000000000000000000000000'
401 _call: function(req
, cb
)
403 return $.ajax('/ubus', {
405 contentType
: 'application/json',
406 data
: JSON
.stringify(req
),
409 timeout
: _luci2
.globals
.timeout
413 _list_cb: function(msg
)
415 /* verify message frame */
416 if (typeof(msg
) != 'object' || msg
.jsonrpc
!= '2.0' || !msg
.id
)
417 throw 'Invalid JSON response';
422 _call_cb: function(msg
)
425 var type
= Object
.prototype.toString
;
430 for (var i
= 0; i
< msg
.length
; i
++)
432 /* verify message frame */
433 if (typeof(msg
[i
]) != 'object' || msg
[i
].jsonrpc
!= '2.0' || !msg
[i
].id
)
434 throw 'Invalid JSON response';
436 /* fetch related request info */
437 var req
= _luci2
.rpc
._requests
[msg
[i
].id
];
438 if (typeof(req
) != 'object')
439 throw 'No related request for JSON response';
441 /* fetch response attribute and verify returned type */
444 if ($.isArray(msg
[i
].result
) && msg
[i
].result
[0] == 0)
445 ret
= (msg
[i
].result
.length
> 1) ? msg
[i
].result
[1] : msg
[i
].result
[0];
449 for (var key
in req
.expect
)
451 if (typeof(ret
) != 'undefined' && key
!= '')
454 if (type
.call(ret
) != type
.call(req
.expect
[key
]))
455 ret
= req
.expect
[key
];
462 if (typeof(req
.filter
) == 'function')
465 req
.priv
[1] = req
.params
;
466 ret
= req
.filter
.apply(_luci2
.rpc
, req
.priv
);
469 /* store response data */
470 if (typeof(req
.index
) == 'number')
471 data
[req
.index
] = ret
;
475 /* delete request object */
476 delete _luci2
.rpc
._requests
[msg
[i
].id
];
485 for (var i
= 0; i
< arguments
.length
; i
++)
486 params
[i
] = arguments
[i
];
492 params
: (params
.length
> 0) ? params
: undefined
495 return this._call(msg
, this._list_cb
);
500 if (!$.isArray(this._batch
))
506 if (!$.isArray(this._batch
))
507 return _luci2
.deferrable([ ]);
509 var req
= this._batch
;
513 return this._call(req
, this._call_cb
);
516 declare: function(options
)
521 /* build parameter object */
524 if ($.isArray(options
.params
))
525 for (p_off
= 0; p_off
< options
.params
.length
; p_off
++)
526 params
[options
.params
[p_off
]] = arguments
[p_off
];
528 /* all remaining arguments are private args */
529 var priv
= [ undefined, undefined ];
530 for (; p_off
< arguments
.length
; p_off
++)
531 priv
.push(arguments
[p_off
]);
533 /* store request info */
534 var req
= _rpc
._requests
[_rpc
._id
] = {
535 expect
: options
.expect
,
536 filter
: options
.filter
,
541 /* build message object */
554 /* when a batch is in progress then store index in request data
555 * and push message object onto the stack */
556 if ($.isArray(_rpc
._batch
))
558 req
.index
= _rpc
._batch
.push(msg
) - 1;
559 return _luci2
.deferrable(msg
);
563 return _rpc
._call(msg
, _rpc
._call_cb
);
572 return _luci2
.session
.access('ubus', 'uci', 'commit');
575 add
: _luci2
.rpc
.declare({
578 params
: [ 'config', 'type', 'name', 'values' ],
579 expect
: { section
: '' }
587 configs
: _luci2
.rpc
.declare({
590 expect
: { configs
: [ ] }
593 _changes
: _luci2
.rpc
.declare({
596 params
: [ 'config' ],
597 expect
: { changes
: [ ] }
600 changes: function(config
)
602 if (typeof(config
) == 'string')
603 return this._changes(config
);
606 return this.configs().then(function(configs
) {
608 configlist
= configs
;
610 for (var i
= 0; i
< configs
.length
; i
++)
611 _luci2
.uci
._changes(configs
[i
]);
613 return _luci2
.rpc
.flush();
614 }).then(function(changes
) {
617 for (var i
= 0; i
< configlist
.length
; i
++)
618 if (changes
[i
].length
)
619 rv
[configlist
[i
]] = changes
[i
];
625 commit
: _luci2
.rpc
.declare({
631 _delete_one
: _luci2
.rpc
.declare({
634 params
: [ 'config', 'section', 'option' ]
637 _delete_multiple
: _luci2
.rpc
.declare({
640 params
: [ 'config', 'section', 'options' ]
643 'delete': function(config
, section
, option
)
645 if ($.isArray(option
))
646 return this._delete_multiple(config
, section
, option
);
648 return this._delete_one(config
, section
, option
);
651 delete_all
: _luci2
.rpc
.declare({
654 params
: [ 'config', 'type', 'match' ]
657 _foreach
: _luci2
.rpc
.declare({
660 params
: [ 'config', 'type' ],
661 expect
: { values
: { } }
664 foreach: function(config
, type
, cb
)
666 return this._foreach(config
, type
).then(function(sections
) {
667 for (var s
in sections
)
672 get: _luci2
.rpc
.declare({
675 params
: [ 'config', 'section', 'option' ],
677 filter: function(data
, params
) {
678 if (typeof(params
.option
) == 'undefined')
679 return data
.values
? data
.values
['.type'] : undefined;
685 get_all
: _luci2
.rpc
.declare({
688 params
: [ 'config', 'section' ],
689 expect
: { values
: { } },
690 filter: function(data
, params
) {
691 if (typeof(params
.section
) == 'string')
692 data
['.section'] = params
.section
;
693 else if (typeof(params
.config
) == 'string')
694 data
['.package'] = params
.config
;
699 get_first: function(config
, type
, option
)
701 return this._foreach(config
, type
).then(function(sections
) {
702 for (var s
in sections
)
704 var val
= (typeof(option
) == 'string') ? sections
[s
][option
] : sections
[s
]['.name'];
706 if (typeof(val
) != 'undefined')
714 section
: _luci2
.rpc
.declare({
717 params
: [ 'config', 'type', 'name', 'values' ],
718 expect
: { section
: '' }
721 _set
: _luci2
.rpc
.declare({
724 params
: [ 'config', 'section', 'values' ]
727 set: function(config
, section
, option
, value
)
729 if (typeof(value
) == 'undefined' && typeof(option
) == 'string')
730 return this.section(config
, section
, option
); /* option -> type */
731 else if ($.isPlainObject(option
))
732 return this._set(config
, section
, option
); /* option -> values */
735 values
[option
] = value
;
737 return this._set(config
, section
, values
);
740 order
: _luci2
.rpc
.declare({
743 params
: [ 'config', 'sections' ]
748 listNetworkNames: function() {
749 return _luci2
.rpc
.list('network.interface.*').then(function(list
) {
751 for (var name
in list
)
752 if (name
!= 'network.interface.loopback')
753 names
.push(name
.substring(18));
759 listDeviceNames
: _luci2
.rpc
.declare({
760 object
: 'network.device',
763 filter: function(data
) {
765 for (var name
in data
)
773 getNetworkStatus: function()
778 return this.listNetworkNames().then(function(names
) {
781 for (var i
= 0; i
< names
.length
; i
++)
782 _luci2
.network
.getInterfaceStatus(names
[i
]);
784 return _luci2
.rpc
.flush();
785 }).then(function(networks
) {
786 for (var i
= 0; i
< networks
.length
; i
++)
788 var net
= nets
[i
] = networks
[i
];
789 var dev
= net
.l3_device
|| net
.l2_device
;
791 net
.device
= devs
[dev
] || (devs
[dev
] = { });
796 for (var dev
in devs
)
797 _luci2
.network
.getDeviceStatus(dev
);
799 return _luci2
.rpc
.flush();
800 }).then(function(devices
) {
803 for (var i
= 0; i
< devices
.length
; i
++)
805 var brm
= devices
[i
]['bridge-members'];
806 delete devices
[i
]['bridge-members'];
808 $.extend(devs
[devices
[i
]['device']], devices
[i
]);
813 devs
[devices
[i
]['device']].subdevices
= [ ];
815 for (var j
= 0; j
< brm
.length
; j
++)
820 _luci2
.network
.getDeviceStatus(brm
[j
]);
823 devs
[devices
[i
]['device']].subdevices
[j
] = devs
[brm
[j
]];
827 return _luci2
.rpc
.flush();
828 }).then(function(subdevices
) {
829 for (var i
= 0; i
< subdevices
.length
; i
++)
830 $.extend(devs
[subdevices
[i
]['device']], subdevices
[i
]);
834 for (var dev
in devs
)
835 _luci2
.wireless
.getDeviceStatus(dev
);
837 return _luci2
.rpc
.flush();
838 }).then(function(wifidevices
) {
839 for (var i
= 0; i
< wifidevices
.length
; i
++)
841 devs
[wifidevices
[i
]['device']].wireless
= wifidevices
[i
];
843 nets
.sort(function(a
, b
) {
844 if (a
['interface'] < b
['interface'])
846 else if (a
['interface'] > b
['interface'])
856 findWanInterfaces: function(cb
)
858 return this.listNetworkNames().then(function(names
) {
861 for (var i
= 0; i
< names
.length
; i
++)
862 _luci2
.network
.getInterfaceStatus(names
[i
]);
864 return _luci2
.rpc
.flush();
865 }).then(function(interfaces
) {
866 var rv
= [ undefined, undefined ];
868 for (var i
= 0; i
< interfaces
.length
; i
++)
870 if (!interfaces
[i
].route
)
873 for (var j
= 0; j
< interfaces
[i
].route
.length
; j
++)
875 var rt
= interfaces
[i
].route
[j
];
877 if (typeof(rt
.table
) != 'undefined')
880 if (rt
.target
== '0.0.0.0' && rt
.mask
== 0)
881 rv
[0] = interfaces
[i
];
882 else if (rt
.target
== '::' && rt
.mask
== 0)
883 rv
[1] = interfaces
[i
];
891 getDHCPLeases
: _luci2
.rpc
.declare({
892 object
: 'luci2.network',
893 method
: 'dhcp_leases',
894 expect
: { leases
: [ ] }
897 getDHCPv6Leases
: _luci2
.rpc
.declare({
898 object
: 'luci2.network',
899 method
: 'dhcp6_leases',
900 expect
: { leases
: [ ] }
903 getRoutes
: _luci2
.rpc
.declare({
904 object
: 'luci2.network',
906 expect
: { routes
: [ ] }
909 getIPv6Routes
: _luci2
.rpc
.declare({
910 object
: 'luci2.network',
912 expect
: { routes
: [ ] }
915 getARPTable
: _luci2
.rpc
.declare({
916 object
: 'luci2.network',
918 expect
: { entries
: [ ] }
921 getInterfaceStatus
: _luci2
.rpc
.declare({
922 object
: 'network.interface',
924 params
: [ 'interface' ],
926 filter: function(data
, params
) {
927 data
['interface'] = params
['interface'];
928 data
['l2_device'] = data
['device'];
929 delete data
['device'];
934 getDeviceStatus
: _luci2
.rpc
.declare({
935 object
: 'network.device',
939 filter: function(data
, params
) {
940 data
['device'] = params
['name'];
945 getConntrackCount
: _luci2
.rpc
.declare({
946 object
: 'luci2.network',
947 method
: 'conntrack_count',
948 expect
: { '': { count
: 0, limit
: 0 } }
951 listSwitchNames
: _luci2
.rpc
.declare({
952 object
: 'luci2.network',
953 method
: 'switch_list',
954 expect
: { switches
: [ ] }
957 getSwitchInfo
: _luci2
.rpc
.declare({
958 object
: 'luci2.network',
959 method
: 'switch_info',
960 params
: [ 'switch' ],
961 expect
: { info
: { } },
962 filter: function(data
, params
) {
963 data
['attrs'] = data
['switch'];
964 data
['vlan_attrs'] = data
['vlan'];
965 data
['port_attrs'] = data
['port'];
966 data
['switch'] = params
['switch'];
975 getSwitchStatus
: _luci2
.rpc
.declare({
976 object
: 'luci2.network',
977 method
: 'switch_status',
978 params
: [ 'switch' ],
979 expect
: { ports
: [ ] }
983 runPing
: _luci2
.rpc
.declare({
984 object
: 'luci2.network',
987 expect
: { '': { code
: -1 } }
990 runPing6
: _luci2
.rpc
.declare({
991 object
: 'luci2.network',
994 expect
: { '': { code
: -1 } }
997 runTraceroute
: _luci2
.rpc
.declare({
998 object
: 'luci2.network',
999 method
: 'traceroute',
1001 expect
: { '': { code
: -1 } }
1004 runTraceroute6
: _luci2
.rpc
.declare({
1005 object
: 'luci2.network',
1006 method
: 'traceroute6',
1008 expect
: { '': { code
: -1 } }
1011 runNslookup
: _luci2
.rpc
.declare({
1012 object
: 'luci2.network',
1015 expect
: { '': { code
: -1 } }
1019 setUp
: _luci2
.rpc
.declare({
1020 object
: 'luci2.network',
1023 expect
: { '': { code
: -1 } }
1026 setDown
: _luci2
.rpc
.declare({
1027 object
: 'luci2.network',
1030 expect
: { '': { code
: -1 } }
1035 listDeviceNames
: _luci2
.rpc
.declare({
1038 expect
: { 'devices': [ ] },
1039 filter: function(data
) {
1045 getDeviceStatus
: _luci2
.rpc
.declare({
1048 params
: [ 'device' ],
1049 expect
: { '': { } },
1050 filter: function(data
, params
) {
1051 if (!$.isEmptyObject(data
))
1053 data
['device'] = params
['device'];
1060 getAssocList
: _luci2
.rpc
.declare({
1062 method
: 'assoclist',
1063 params
: [ 'device' ],
1064 expect
: { results
: [ ] },
1065 filter: function(data
, params
) {
1066 for (var i
= 0; i
< data
.length
; i
++)
1067 data
[i
]['device'] = params
['device'];
1069 data
.sort(function(a
, b
) {
1070 if (a
.bssid
< b
.bssid
)
1072 else if (a
.bssid
> b
.bssid
)
1082 getWirelessStatus: function() {
1083 return this.listDeviceNames().then(function(names
) {
1086 for (var i
= 0; i
< names
.length
; i
++)
1087 _luci2
.wireless
.getDeviceStatus(names
[i
]);
1089 return _luci2
.rpc
.flush();
1090 }).then(function(networks
) {
1094 'country', 'channel', 'frequency', 'frequency_offset',
1095 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1099 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1100 'signal', 'noise', 'bitrate', 'encryption'
1103 for (var i
= 0; i
< networks
.length
; i
++)
1105 var phy
= rv
[networks
[i
].phy
] || (
1106 rv
[networks
[i
].phy
] = { networks
: [ ] }
1110 device
: networks
[i
].device
1113 for (var j
= 0; j
< phy_attrs
.length
; j
++)
1114 phy
[phy_attrs
[j
]] = networks
[i
][phy_attrs
[j
]];
1116 for (var j
= 0; j
< net_attrs
.length
; j
++)
1117 net
[net_attrs
[j
]] = networks
[i
][net_attrs
[j
]];
1119 phy
.networks
.push(net
);
1126 getAssocLists: function()
1128 return this.listDeviceNames().then(function(names
) {
1131 for (var i
= 0; i
< names
.length
; i
++)
1132 _luci2
.wireless
.getAssocList(names
[i
]);
1134 return _luci2
.rpc
.flush();
1135 }).then(function(assoclists
) {
1138 for (var i
= 0; i
< assoclists
.length
; i
++)
1139 for (var j
= 0; j
< assoclists
[i
].length
; j
++)
1140 rv
.push(assoclists
[i
][j
]);
1146 formatEncryption: function(enc
)
1148 var format_list = function(l
, s
)
1151 for (var i
= 0; i
< l
.length
; i
++)
1152 rv
.push(l
[i
].toUpperCase());
1153 return rv
.join(s
? s
: ', ');
1156 if (!enc
|| !enc
.enabled
)
1157 return _luci2
.tr('None');
1161 if (enc
.wep
.length
== 2)
1162 return _luci2
.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1163 else if (enc
.wep
[0] == 'shared')
1164 return _luci2
.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1166 return _luci2
.tr('WEP Open System') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1170 if (enc
.wpa
.length
== 2)
1171 return _luci2
.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1172 format_list(enc
.authentication
, '/'),
1173 format_list(enc
.ciphers
, ', ')
1175 else if (enc
.wpa
[0] == 2)
1176 return 'WPA2 %s (%s)'.format(
1177 format_list(enc
.authentication
, '/'),
1178 format_list(enc
.ciphers
, ', ')
1181 return 'WPA %s (%s)'.format(
1182 format_list(enc
.authentication
, '/'),
1183 format_list(enc
.ciphers
, ', ')
1187 return _luci2
.tr('Unknown');
1192 getZoneColor: function(zone
)
1194 if ($.isPlainObject(zone
))
1199 else if (zone
== 'wan')
1202 for (var i
= 0, hash
= 0;
1204 hash
= zone
.charCodeAt(i
++) + ((hash
<< 5) - hash
));
1206 for (var i
= 0, color
= '#';
1208 color
+= ('00' + ((hash
>> i
++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1213 findZoneByNetwork: function(network
)
1216 var zone
= undefined;
1218 return _luci2
.uci
.foreach('firewall', 'zone', function(z
) {
1219 if (!z
.name
|| !z
.network
)
1222 if (!$.isArray(z
.network
))
1223 z
.network
= z
.network
.split(/\s+/);
1225 for (var i
= 0; i
< z
.network
.length
; i
++)
1227 if (z
.network
[i
] == network
)
1233 }).then(function() {
1235 zone
.color
= self
.getZoneColor(zone
);
1243 getSystemInfo
: _luci2
.rpc
.declare({
1249 getBoardInfo
: _luci2
.rpc
.declare({
1255 getDiskInfo
: _luci2
.rpc
.declare({
1256 object
: 'luci2.system',
1261 getInfo: function(cb
)
1265 this.getSystemInfo();
1266 this.getBoardInfo();
1269 return _luci2
.rpc
.flush().then(function(info
) {
1272 $.extend(rv
, info
[0]);
1273 $.extend(rv
, info
[1]);
1274 $.extend(rv
, info
[2]);
1280 getProcessList
: _luci2
.rpc
.declare({
1281 object
: 'luci2.system',
1282 method
: 'process_list',
1283 expect
: { processes
: [ ] },
1284 filter: function(data
) {
1285 data
.sort(function(a
, b
) { return a
.pid
- b
.pid
});
1290 getSystemLog
: _luci2
.rpc
.declare({
1291 object
: 'luci2.system',
1296 getKernelLog
: _luci2
.rpc
.declare({
1297 object
: 'luci2.system',
1302 getZoneInfo: function(cb
)
1304 return $.getJSON(_luci2
.globals
.resource
+ '/zoneinfo.json', cb
);
1307 sendSignal
: _luci2
.rpc
.declare({
1308 object
: 'luci2.system',
1309 method
: 'process_signal',
1310 params
: [ 'pid', 'signal' ],
1311 filter: function(data
) {
1316 initList
: _luci2
.rpc
.declare({
1317 object
: 'luci2.system',
1318 method
: 'init_list',
1319 expect
: { initscripts
: [ ] },
1320 filter: function(data
) {
1321 data
.sort(function(a
, b
) { return (a
.start
|| 0) - (b
.start
|| 0) });
1326 initEnabled: function(init
, cb
)
1328 return this.initList().then(function(list
) {
1329 for (var i
= 0; i
< list
.length
; i
++)
1330 if (list
[i
].name
== init
)
1331 return !!list
[i
].enabled
;
1337 initRun
: _luci2
.rpc
.declare({
1338 object
: 'luci2.system',
1339 method
: 'init_action',
1340 params
: [ 'name', 'action' ],
1341 filter: function(data
) {
1346 initStart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'start', cb
) },
1347 initStop: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'stop', cb
) },
1348 initRestart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'restart', cb
) },
1349 initReload: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'reload', cb
) },
1350 initEnable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'enable', cb
) },
1351 initDisable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'disable', cb
) },
1354 getRcLocal
: _luci2
.rpc
.declare({
1355 object
: 'luci2.system',
1356 method
: 'rclocal_get',
1357 expect
: { data
: '' }
1360 setRcLocal
: _luci2
.rpc
.declare({
1361 object
: 'luci2.system',
1362 method
: 'rclocal_set',
1367 getCrontab
: _luci2
.rpc
.declare({
1368 object
: 'luci2.system',
1369 method
: 'crontab_get',
1370 expect
: { data
: '' }
1373 setCrontab
: _luci2
.rpc
.declare({
1374 object
: 'luci2.system',
1375 method
: 'crontab_set',
1380 getSSHKeys
: _luci2
.rpc
.declare({
1381 object
: 'luci2.system',
1382 method
: 'sshkeys_get',
1383 expect
: { keys
: [ ] }
1386 setSSHKeys
: _luci2
.rpc
.declare({
1387 object
: 'luci2.system',
1388 method
: 'sshkeys_set',
1393 setPassword
: _luci2
.rpc
.declare({
1394 object
: 'luci2.system',
1395 method
: 'password_set',
1396 params
: [ 'user', 'password' ]
1400 listLEDs
: _luci2
.rpc
.declare({
1401 object
: 'luci2.system',
1403 expect
: { leds
: [ ] }
1406 listUSBDevices
: _luci2
.rpc
.declare({
1407 object
: 'luci2.system',
1409 expect
: { devices
: [ ] }
1413 testUpgrade
: _luci2
.rpc
.declare({
1414 object
: 'luci2.system',
1415 method
: 'upgrade_test',
1419 startUpgrade
: _luci2
.rpc
.declare({
1420 object
: 'luci2.system',
1421 method
: 'upgrade_start',
1425 cleanUpgrade
: _luci2
.rpc
.declare({
1426 object
: 'luci2.system',
1427 method
: 'upgrade_clean'
1431 restoreBackup
: _luci2
.rpc
.declare({
1432 object
: 'luci2.system',
1433 method
: 'backup_restore'
1436 cleanBackup
: _luci2
.rpc
.declare({
1437 object
: 'luci2.system',
1438 method
: 'backup_clean'
1442 getBackupConfig
: _luci2
.rpc
.declare({
1443 object
: 'luci2.system',
1444 method
: 'backup_config_get',
1445 expect
: { config
: '' }
1448 setBackupConfig
: _luci2
.rpc
.declare({
1449 object
: 'luci2.system',
1450 method
: 'backup_config_set',
1455 listBackup
: _luci2
.rpc
.declare({
1456 object
: 'luci2.system',
1457 method
: 'backup_list',
1458 expect
: { files
: [ ] }
1462 testReset
: _luci2
.rpc
.declare({
1463 object
: 'luci2.system',
1464 method
: 'reset_test',
1465 expect
: { supported
: false }
1468 startReset
: _luci2
.rpc
.declare({
1469 object
: 'luci2.system',
1470 method
: 'reset_start'
1474 performReboot
: _luci2
.rpc
.declare({
1475 object
: 'luci2.system',
1481 updateLists
: _luci2
.rpc
.declare({
1482 object
: 'luci2.opkg',
1487 _allPackages
: _luci2
.rpc
.declare({
1488 object
: 'luci2.opkg',
1490 params
: [ 'offset', 'limit', 'pattern' ],
1494 _installedPackages
: _luci2
.rpc
.declare({
1495 object
: 'luci2.opkg',
1496 method
: 'list_installed',
1497 params
: [ 'offset', 'limit', 'pattern' ],
1501 _findPackages
: _luci2
.rpc
.declare({
1502 object
: 'luci2.opkg',
1504 params
: [ 'offset', 'limit', 'pattern' ],
1508 _fetchPackages: function(action
, offset
, limit
, pattern
)
1512 return action(offset
, limit
, pattern
).then(function(list
) {
1513 if (!list
.total
|| !list
.packages
)
1514 return { length
: 0, total
: 0 };
1516 packages
.push
.apply(packages
, list
.packages
);
1517 packages
.total
= list
.total
;
1522 if (packages
.length
>= limit
)
1527 for (var i
= offset
+ packages
.length
; i
< limit
; i
+= 100)
1528 action(i
, (Math
.min(i
+ 100, limit
) % 100) || 100, pattern
);
1530 return _luci2
.rpc
.flush();
1531 }).then(function(lists
) {
1532 for (var i
= 0; i
< lists
.length
; i
++)
1534 if (!lists
[i
].total
|| !lists
[i
].packages
)
1537 packages
.push
.apply(packages
, lists
[i
].packages
);
1538 packages
.total
= lists
[i
].total
;
1545 listPackages: function(offset
, limit
, pattern
)
1547 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._allPackages
, offset
, limit
, pattern
);
1550 installedPackages: function(offset
, limit
, pattern
)
1552 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._installedPackages
, offset
, limit
, pattern
);
1555 findPackages: function(offset
, limit
, pattern
)
1557 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._findPackages
, offset
, limit
, pattern
);
1560 installPackage
: _luci2
.rpc
.declare({
1561 object
: 'luci2.opkg',
1563 params
: [ 'package' ],
1567 removePackage
: _luci2
.rpc
.declare({
1568 object
: 'luci2.opkg',
1570 params
: [ 'package' ],
1574 getConfig
: _luci2
.rpc
.declare({
1575 object
: 'luci2.opkg',
1576 method
: 'config_get',
1577 expect
: { config
: '' }
1580 setConfig
: _luci2
.rpc
.declare({
1581 object
: 'luci2.opkg',
1582 method
: 'config_set',
1589 login
: _luci2
.rpc
.declare({
1592 params
: [ 'username', 'password' ],
1596 access
: _luci2
.rpc
.declare({
1599 params
: [ 'scope', 'object', 'function' ],
1600 expect
: { access
: false }
1605 return _luci2
.session
.access('ubus', 'session', 'access');
1608 startHeartbeat: function()
1610 this._hearbeatInterval
= window
.setInterval(function() {
1611 _luci2
.session
.isAlive().then(function(alive
) {
1614 _luci2
.session
.stopHeartbeat();
1615 _luci2
.ui
.login(true);
1619 }, _luci2
.globals
.timeout
* 2);
1622 stopHeartbeat: function()
1624 if (typeof(this._hearbeatInterval
) != 'undefined')
1626 window
.clearInterval(this._hearbeatInterval
);
1627 delete this._hearbeatInterval
;
1634 saveScrollTop: function()
1636 this._scroll_top
= $(document
).scrollTop();
1639 restoreScrollTop: function()
1641 if (typeof(this._scroll_top
) == 'undefined')
1644 $(document
).scrollTop(this._scroll_top
);
1646 delete this._scroll_top
;
1649 loading: function(enable
)
1651 var win
= $(window
);
1652 var body
= $('body');
1654 var state
= _luci2
.ui
._loading
|| (_luci2
.ui
._loading
= {
1656 .addClass('modal fade')
1657 .append($('<div />')
1658 .addClass('modal-dialog')
1659 .append($('<div />')
1660 .addClass('modal-content luci2-modal-loader')
1661 .append($('<div />')
1662 .addClass('modal-body')
1663 .text(_luci2
.tr('Loading data…')))))
1671 state
.modal
.modal(enable
? 'show' : 'hide');
1674 dialog: function(title
, content
, options
)
1676 var win
= $(window
);
1677 var body
= $('body');
1679 var state
= _luci2
.ui
._dialog
|| (_luci2
.ui
._dialog
= {
1680 dialog
: $('<div />')
1681 .addClass('modal fade')
1682 .append($('<div />')
1683 .addClass('modal-dialog')
1684 .append($('<div />')
1685 .addClass('modal-content')
1686 .append($('<div />')
1687 .addClass('modal-header')
1689 .addClass('modal-title'))
1690 .append($('<div />')
1691 .addClass('modal-body'))
1692 .append($('<div />')
1693 .addClass('modal-footer')
1694 .append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
1696 $(this).parents('div.modal').modal('hide');
1701 if (typeof(options
) != 'object')
1704 if (title
=== false)
1706 state
.dialog
.modal('hide');
1711 var cnt
= state
.dialog
.children().children().children('div.modal-body');
1712 var ftr
= state
.dialog
.children().children().children('div.modal-footer');
1716 if (options
.style
== 'confirm')
1718 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Ok'), 'primary')
1719 .click(options
.confirm
|| function() { _luci2
.ui
.dialog(false) }));
1721 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Cancel'), 'default')
1722 .click(options
.cancel
|| function() { _luci2
.ui
.dialog(false) }));
1724 else if (options
.style
== 'close')
1726 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
1727 .click(options
.close
|| function() { _luci2
.ui
.dialog(false) }));
1729 else if (options
.style
== 'wait')
1731 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
1732 .attr('disabled', true));
1735 state
.dialog
.find('h4:first').text(title
);
1736 state
.dialog
.modal('show');
1738 cnt
.empty().append(content
);
1741 upload: function(title
, content
, options
)
1743 var state
= _luci2
.ui
._upload
|| (_luci2
.ui
._upload
= {
1745 .attr('method', 'post')
1746 .attr('action', '/cgi-bin/luci-upload')
1747 .attr('enctype', 'multipart/form-data')
1748 .attr('target', 'cbi-fileupload-frame')
1750 .append($('<input />')
1751 .attr('type', 'hidden')
1752 .attr('name', 'sessionid'))
1753 .append($('<input />')
1754 .attr('type', 'hidden')
1755 .attr('name', 'filename'))
1756 .append($('<input />')
1757 .attr('type', 'file')
1758 .attr('name', 'filedata')
1759 .addClass('cbi-input-file'))
1760 .append($('<div />')
1761 .css('width', '100%')
1762 .addClass('progress progress-striped active')
1763 .append($('<div />')
1764 .addClass('progress-bar')
1765 .css('width', '100%')))
1766 .append($('<iframe />')
1767 .addClass('pull-right')
1768 .attr('name', 'cbi-fileupload-frame')
1769 .css('width', '1px')
1770 .css('height', '1px')
1771 .css('visibility', 'hidden')),
1773 finish_cb: function(ev
) {
1774 $(this).off('load');
1776 var body
= (this.contentDocument
|| this.contentWindow
.document
).body
;
1777 if (body
.firstChild
.tagName
.toLowerCase() == 'pre')
1778 body
= body
.firstChild
;
1782 json
= $.parseJSON(body
.innerHTML
);
1785 message
: _luci2
.tr('Invalid server response received'),
1786 error
: [ -1, _luci2
.tr('Invalid data') ]
1792 L
.ui
.dialog(L
.tr('File upload'), [
1793 $('<p />').text(_luci2
.tr('The file upload failed with the server response below:')),
1794 $('<pre />').addClass('alert-message').text(json
.message
|| json
.error
[1]),
1795 $('<p />').text(_luci2
.tr('In case of network problems try uploading the file again.'))
1796 ], { style
: 'close' });
1798 else if (typeof(state
.success_cb
) == 'function')
1800 state
.success_cb(json
);
1804 confirm_cb: function() {
1805 var f
= state
.form
.find('.cbi-input-file');
1806 var b
= state
.form
.find('.progress');
1807 var p
= state
.form
.find('p');
1812 state
.form
.find('iframe').on('load', state
.finish_cb
);
1813 state
.form
.submit();
1817 p
.text(_luci2
.tr('File upload in progress …'));
1819 state
.form
.parent().parent().find('button').prop('disabled', true);
1823 state
.form
.find('.progress').hide();
1824 state
.form
.find('.cbi-input-file').val('').show();
1825 state
.form
.find('p').text(content
|| _luci2
.tr('Select the file to upload and press "%s" to proceed.').format(_luci2
.tr('Ok')));
1827 state
.form
.find('[name=sessionid]').val(_luci2
.globals
.sid
);
1828 state
.form
.find('[name=filename]').val(options
.filename
);
1830 state
.success_cb
= options
.success
;
1832 _luci2
.ui
.dialog(title
|| _luci2
.tr('File upload'), state
.form
, {
1834 confirm
: state
.confirm_cb
1838 reconnect: function()
1840 var protocols
= (location
.protocol
== 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1841 var ports
= (location
.protocol
== 'https:') ? [ 80, location
.port
|| 443 ] : [ location
.port
|| 80 ];
1842 var address
= location
.hostname
.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location
.hostname
+ ']' : location
.hostname
;
1844 var interval
, timeout
;
1847 _luci2
.tr('Waiting for device'), [
1848 $('<p />').text(_luci2
.tr('Please stand by while the device is reconfiguring …')),
1850 .css('width', '100%')
1851 .addClass('progressbar')
1852 .addClass('intermediate')
1853 .append($('<div />')
1854 .css('width', '100%'))
1855 ], { style
: 'wait' }
1858 for (var i
= 0; i
< protocols
.length
; i
++)
1859 images
= images
.add($('<img />').attr('url', protocols
[i
] + '://' + address
+ ':' + ports
[i
]));
1861 //_luci2.network.getNetworkStatus(function(s) {
1862 // for (var i = 0; i < protocols.length; i++)
1864 // for (var j = 0; j < s.length; j++)
1866 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1867 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1869 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1870 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1873 //}).then(function() {
1874 images
.on('load', function() {
1875 var url
= this.getAttribute('url');
1876 _luci2
.session
.isAlive().then(function(access
) {
1879 window
.clearTimeout(timeout
);
1880 window
.clearInterval(interval
);
1881 _luci2
.ui
.dialog(false);
1886 location
.href
= url
;
1891 interval
= window
.setInterval(function() {
1892 images
.each(function() {
1893 this.setAttribute('src', this.getAttribute('url') + _luci2
.globals
.resource
+ '/icons/loading.gif?r=' + Math
.random());
1897 timeout
= window
.setTimeout(function() {
1898 window
.clearInterval(interval
);
1902 _luci2
.tr('Device not responding'),
1903 _luci2
.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1910 login: function(invalid
)
1912 var state
= _luci2
.ui
._login
|| (_luci2
.ui
._login
= {
1915 .attr('method', 'post')
1917 .addClass('alert-message')
1918 .text(_luci2
.tr('Wrong username or password given!')))
1920 .append($('<label />')
1921 .text(_luci2
.tr('Username'))
1922 .append($('<br />'))
1923 .append($('<input />')
1924 .attr('type', 'text')
1925 .attr('name', 'username')
1926 .attr('value', 'root')
1927 .addClass('form-control')
1928 .keypress(function(ev
) {
1929 if (ev
.which
== 10 || ev
.which
== 13)
1933 .append($('<label />')
1934 .text(_luci2
.tr('Password'))
1935 .append($('<br />'))
1936 .append($('<input />')
1937 .attr('type', 'password')
1938 .attr('name', 'password')
1939 .addClass('form-control')
1940 .keypress(function(ev
) {
1941 if (ev
.which
== 10 || ev
.which
== 13)
1945 .text(_luci2
.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2
.tr('Ok')))),
1947 response_cb: function(response
) {
1948 if (!response
.ubus_rpc_session
)
1950 _luci2
.ui
.login(true);
1954 _luci2
.globals
.sid
= response
.ubus_rpc_session
;
1955 _luci2
.setHash('id', _luci2
.globals
.sid
);
1956 _luci2
.session
.startHeartbeat();
1957 _luci2
.ui
.dialog(false);
1958 state
.deferred
.resolve();
1962 confirm_cb: function() {
1963 var u
= state
.form
.find('[name=username]').val();
1964 var p
= state
.form
.find('[name=password]').val();
1970 _luci2
.tr('Logging in'), [
1971 $('<p />').text(_luci2
.tr('Log in in progress …')),
1973 .css('width', '100%')
1974 .addClass('progressbar')
1975 .addClass('intermediate')
1976 .append($('<div />')
1977 .css('width', '100%'))
1978 ], { style
: 'wait' }
1981 _luci2
.globals
.sid
= '00000000000000000000000000000000';
1982 _luci2
.session
.login(u
, p
).then(state
.response_cb
);
1986 if (!state
.deferred
|| state
.deferred
.state() != 'pending')
1987 state
.deferred
= $.Deferred();
1989 /* try to find sid from hash */
1990 var sid
= _luci2
.getHash('id');
1991 if (sid
&& sid
.match(/^[a-f0-9]{32}$/))
1993 _luci2
.globals
.sid
= sid
;
1994 _luci2
.session
.isAlive().then(function(access
) {
1997 _luci2
.session
.startHeartbeat();
1998 state
.deferred
.resolve();
2002 _luci2
.setHash('id', undefined);
2007 return state
.deferred
;
2011 state
.form
.find('.alert-message').show();
2013 state
.form
.find('.alert-message').hide();
2015 _luci2
.ui
.dialog(_luci2
.tr('Authorization Required'), state
.form
, {
2017 confirm
: state
.confirm_cb
2020 state
.form
.find('[name=password]').focus();
2022 return state
.deferred
;
2025 cryptPassword
: _luci2
.rpc
.declare({
2029 expect
: { crypt
: '' }
2033 _acl_merge_scope: function(acl_scope
, scope
)
2035 if ($.isArray(scope
))
2037 for (var i
= 0; i
< scope
.length
; i
++)
2038 acl_scope
[scope
[i
]] = true;
2040 else if ($.isPlainObject(scope
))
2042 for (var object_name
in scope
)
2044 if (!$.isArray(scope
[object_name
]))
2047 var acl_object
= acl_scope
[object_name
] || (acl_scope
[object_name
] = { });
2049 for (var i
= 0; i
< scope
[object_name
].length
; i
++)
2050 acl_object
[scope
[object_name
][i
]] = true;
2055 _acl_merge_permission: function(acl_perm
, perm
)
2057 if ($.isPlainObject(perm
))
2059 for (var scope_name
in perm
)
2061 var acl_scope
= acl_perm
[scope_name
] || (acl_perm
[scope_name
] = { });
2062 this._acl_merge_scope(acl_scope
, perm
[scope_name
]);
2067 _acl_merge_group: function(acl_group
, group
)
2069 if ($.isPlainObject(group
))
2071 if (!acl_group
.description
)
2072 acl_group
.description
= group
.description
;
2076 var acl_perm
= acl_group
.read
|| (acl_group
.read
= { });
2077 this._acl_merge_permission(acl_perm
, group
.read
);
2082 var acl_perm
= acl_group
.write
|| (acl_group
.write
= { });
2083 this._acl_merge_permission(acl_perm
, group
.write
);
2088 _acl_merge_tree: function(acl_tree
, tree
)
2090 if ($.isPlainObject(tree
))
2092 for (var group_name
in tree
)
2094 var acl_group
= acl_tree
[group_name
] || (acl_tree
[group_name
] = { });
2095 this._acl_merge_group(acl_group
, tree
[group_name
]);
2100 listAvailableACLs
: _luci2
.rpc
.declare({
2103 expect
: { acls
: [ ] },
2104 filter: function(trees
) {
2106 for (var i
= 0; i
< trees
.length
; i
++)
2107 _luci2
.ui
._acl_merge_tree(acl_tree
, trees
[i
]);
2112 renderMainMenu
: _luci2
.rpc
.declare({
2115 expect
: { menu
: { } },
2116 filter: function(entries
) {
2117 _luci2
.globals
.mainMenu
= new _luci2
.ui
.menu();
2118 _luci2
.globals
.mainMenu
.entries(entries
);
2122 .append(_luci2
.globals
.mainMenu
.render(0, 1));
2126 renderViewMenu: function()
2130 .append(_luci2
.globals
.mainMenu
.render(2, 900));
2133 renderView: function()
2135 var node
= arguments
[0];
2136 var name
= node
.view
.split(/\//).join('.');
2139 for (var i
= 1; i
< arguments
.length
; i
++)
2140 args
.push(arguments
[i
]);
2142 if (_luci2
.globals
.currentView
)
2143 _luci2
.globals
.currentView
.finish();
2145 _luci2
.ui
.renderViewMenu();
2148 _luci2
._views
= { };
2150 _luci2
.setHash('view', node
.view
);
2152 if (_luci2
._views
[name
] instanceof _luci2
.ui
.view
)
2154 _luci2
.globals
.currentView
= _luci2
._views
[name
];
2155 return _luci2
._views
[name
].render
.apply(_luci2
._views
[name
], args
);
2158 var url
= _luci2
.globals
.resource
+ '/view/' + name
+ '.js';
2160 return $.ajax(url
, {
2164 }).then(function(data
) {
2166 var viewConstructorSource
= (
2167 '(function(L, $) { ' +
2169 '})(_luci2, $);\n\n' +
2171 ).format(data
, url
);
2173 var viewConstructor
= eval(viewConstructorSource
);
2175 _luci2
._views
[name
] = new viewConstructor({
2177 acls
: node
.write
|| { }
2180 _luci2
.globals
.currentView
= _luci2
._views
[name
];
2181 return _luci2
._views
[name
].render
.apply(_luci2
._views
[name
], args
);
2184 alert('Unable to instantiate view "%s": %s'.format(url
, e
));
2187 return $.Deferred().resolve();
2191 updateHostname: function()
2193 return _luci2
.system
.getBoardInfo().then(function(info
) {
2195 $('#hostname').text(info
.hostname
);
2199 updateChanges: function()
2201 return _luci2
.uci
.changes().then(function(changes
) {
2205 for (var config
in changes
)
2209 for (var i
= 0; i
< changes
[config
].length
; i
++)
2211 var c
= changes
[config
][i
];
2220 log
.push('uci delete %s.<del>%s</del>'.format(config
, c
[1]));
2222 log
.push('uci delete %s.%s.<del>%s</del>'.format(config
, c
[1], c
[2]));
2227 log
.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3]));
2229 log
.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2233 log
.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config
, c
[2], c
[1]));
2237 log
.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2241 log
.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2246 log
.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
2248 log
.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2253 html
+= '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config
, log
.join('\n'));
2254 n
+= changes
[config
].length
;
2265 .text(_luci2
.trcp('Pending configuration changes', '1 change', '%d changes', n
).format(n
))
2266 .click(function(ev
) {
2267 _luci2
.ui
.dialog(_luci2
.tr('Staged configuration changes'), html
, { style
: 'close' });
2268 ev
.preventDefault();
2278 _luci2
.ui
.loading(true);
2281 _luci2
.ui
.updateHostname(),
2282 _luci2
.ui
.updateChanges(),
2283 _luci2
.ui
.renderMainMenu()
2285 _luci2
.ui
.renderView(_luci2
.globals
.defaultNode
).then(function() {
2286 _luci2
.ui
.loading(false);
2291 button: function(label
, style
, title
)
2293 style
= style
|| 'default';
2295 return $('<button />')
2296 .attr('type', 'button')
2297 .attr('title', title
? title
: '')
2298 .addClass('btn btn-' + style
)
2303 this.ui
.AbstractWidget
= Class
.extend({
2304 i18n: function(text
) {
2309 var key
= arguments
[0];
2312 for (var i
= 1; i
< arguments
.length
; i
++)
2313 args
.push(arguments
[i
]);
2315 switch (typeof(this.options
[key
]))
2321 return this.options
[key
].apply(this, args
);
2324 return ''.format
.apply('' + this.options
[key
], args
);
2328 toString: function() {
2329 return $('<div />').append(this.render()).html();
2332 insertInto: function(id
) {
2333 return $(id
).empty().append(this.render());
2336 appendTo: function(id
) {
2337 return $(id
).append(this.render());
2341 this.ui
.view
= this.ui
.AbstractWidget
.extend({
2342 _fetch_template: function()
2344 return $.ajax(_luci2
.globals
.resource
+ '/template/' + this.options
.name
+ '.htm', {
2348 success: function(data
) {
2349 data
= data
.replace(/<%([#:=])?(.+?)%>/g, function(match
, p1
, p2
) {
2350 p2
= p2
.replace(/^\s+/, '').replace(/\s+$/, '');
2357 return _luci2
.tr(p2
);
2360 return _luci2
.globals
[p2
] || '';
2363 return '(?' + match
+ ')';
2367 $('#maincontent').append(data
);
2374 throw "Not implemented";
2379 var container
= $('#maincontent');
2384 container
.append($('<h2 />').append(this.title
));
2386 if (this.description
)
2387 container
.append($('<p />').append(this.description
));
2392 for (var i
= 0; i
< arguments
.length
; i
++)
2393 args
.push(arguments
[i
]);
2395 return this._fetch_template().then(function() {
2396 return _luci2
.deferrable(self
.execute
.apply(self
, args
));
2400 repeat: function(func
, interval
)
2404 if (!self
._timeouts
)
2405 self
._timeouts
= [ ];
2407 var index
= self
._timeouts
.length
;
2409 if (typeof(interval
) != 'number')
2412 var setTimer
, runTimer
;
2414 setTimer = function() {
2416 self
._timeouts
[index
] = window
.setTimeout(runTimer
, interval
);
2419 runTimer = function() {
2420 _luci2
.deferrable(func
.call(self
)).then(setTimer
, setTimer
);
2428 if ($.isArray(this._timeouts
))
2430 for (var i
= 0; i
< this._timeouts
.length
; i
++)
2431 window
.clearTimeout(this._timeouts
[i
]);
2433 delete this._timeouts
;
2438 this.ui
.menu
= this.ui
.AbstractWidget
.extend({
2443 entries: function(entries
)
2445 for (var entry
in entries
)
2447 var path
= entry
.split(/\//);
2448 var node
= this._nodes
;
2450 for (i
= 0; i
< path
.length
; i
++)
2455 if (!node
.childs
[path
[i
]])
2456 node
.childs
[path
[i
]] = { };
2458 node
= node
.childs
[path
[i
]];
2461 $.extend(node
, entries
[entry
]);
2465 _indexcmp: function(a
, b
)
2467 var x
= a
.index
|| 0;
2468 var y
= b
.index
|| 0;
2472 firstChildView: function(node
)
2478 for (var child
in (node
.childs
|| { }))
2479 nodes
.push(node
.childs
[child
]);
2481 nodes
.sort(this._indexcmp
);
2483 for (var i
= 0; i
< nodes
.length
; i
++)
2485 var child
= this.firstChildView(nodes
[i
]);
2488 for (var key
in child
)
2489 if (!node
.hasOwnProperty(key
) && child
.hasOwnProperty(key
))
2490 node
[key
] = child
[key
];
2499 _onclick: function(ev
)
2501 _luci2
.ui
.loading(true);
2502 _luci2
.ui
.renderView(ev
.data
).then(function() {
2503 _luci2
.ui
.loading(false);
2506 ev
.preventDefault();
2510 _render: function(childs
, level
, min
, max
)
2513 for (var node
in childs
)
2515 var child
= this.firstChildView(childs
[node
]);
2517 nodes
.push(childs
[node
]);
2520 nodes
.sort(this._indexcmp
);
2522 var list
= $('<ul />');
2525 list
.addClass('nav').addClass('navbar-nav');
2526 else if (level
== 1)
2527 list
.addClass('dropdown-menu').addClass('navbar-inverse');
2529 for (var i
= 0; i
< nodes
.length
; i
++)
2531 if (!_luci2
.globals
.defaultNode
)
2533 var v
= _luci2
.getHash('view');
2534 if (!v
|| v
== nodes
[i
].view
)
2535 _luci2
.globals
.defaultNode
= nodes
[i
];
2538 var item
= $('<li />')
2541 .text(_luci2
.tr(nodes
[i
].title
)))
2544 if (nodes
[i
].childs
&& level
< max
)
2546 item
.addClass('dropdown');
2549 .addClass('dropdown-toggle')
2550 .attr('data-toggle', 'dropdown')
2551 .append('<b class="caret"></b>');
2553 item
.append(this._render(nodes
[i
].childs
, level
+ 1));
2557 item
.find('a').click(nodes
[i
], this._onclick
);
2564 render: function(min
, max
)
2566 var top
= min
? this.getNode(_luci2
.globals
.defaultNode
.view
, min
) : this._nodes
;
2567 return this._render(top
.childs
, 0, min
, max
);
2570 getNode: function(path
, max
)
2572 var p
= path
.split(/\//);
2573 var n
= this._nodes
;
2575 if (typeof(max
) == 'undefined')
2578 for (var i
= 0; i
< max
; i
++)
2580 if (!n
.childs
[p
[i
]])
2590 this.ui
.table
= this.ui
.AbstractWidget
.extend({
2596 row: function(values
)
2598 if ($.isArray(values
))
2600 this._rows
.push(values
);
2602 else if ($.isPlainObject(values
))
2605 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2607 var col
= this.options
.columns
[i
];
2609 if (typeof col
.key
== 'string')
2610 v
.push(values
[col
.key
]);
2618 rows: function(rows
)
2620 for (var i
= 0; i
< rows
.length
; i
++)
2624 render: function(id
)
2626 var fieldset
= document
.createElement('fieldset');
2627 fieldset
.className
= 'cbi-section';
2629 if (this.options
.caption
)
2631 var legend
= document
.createElement('legend');
2632 $(legend
).append(this.options
.caption
);
2633 fieldset
.appendChild(legend
);
2636 var table
= document
.createElement('table');
2637 table
.className
= 'table table-condensed table-hover';
2639 var has_caption
= false;
2640 var has_description
= false;
2642 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2643 if (this.options
.columns
[i
].caption
)
2648 else if (this.options
.columns
[i
].description
)
2650 has_description
= true;
2656 var tr
= table
.insertRow(-1);
2657 tr
.className
= 'cbi-section-table-titles';
2659 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2661 var col
= this.options
.columns
[i
];
2662 var th
= document
.createElement('th');
2663 th
.className
= 'cbi-section-table-cell';
2668 th
.style
.width
= col
.width
;
2671 th
.style
.textAlign
= col
.align
;
2674 $(th
).append(col
.caption
);
2678 if (has_description
)
2680 var tr
= table
.insertRow(-1);
2681 tr
.className
= 'cbi-section-table-descr';
2683 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2685 var col
= this.options
.columns
[i
];
2686 var th
= document
.createElement('th');
2687 th
.className
= 'cbi-section-table-cell';
2692 th
.style
.width
= col
.width
;
2695 th
.style
.textAlign
= col
.align
;
2697 if (col
.description
)
2698 $(th
).append(col
.description
);
2702 if (this._rows
.length
== 0)
2704 if (this.options
.placeholder
)
2706 var tr
= table
.insertRow(-1);
2707 var td
= tr
.insertCell(-1);
2708 td
.className
= 'cbi-section-table-cell';
2710 td
.colSpan
= this.options
.columns
.length
;
2711 $(td
).append(this.options
.placeholder
);
2716 for (var i
= 0; i
< this._rows
.length
; i
++)
2718 var tr
= table
.insertRow(-1);
2720 for (var j
= 0; j
< this.options
.columns
.length
; j
++)
2722 var col
= this.options
.columns
[j
];
2723 var td
= tr
.insertCell(-1);
2725 var val
= this._rows
[i
][j
];
2727 if (typeof(val
) == 'undefined')
2728 val
= col
.placeholder
;
2730 if (typeof(val
) == 'undefined')
2734 td
.style
.width
= col
.width
;
2737 td
.style
.textAlign
= col
.align
;
2739 if (typeof col
.format
== 'string')
2740 $(td
).append(col
.format
.format(val
));
2741 else if (typeof col
.format
== 'function')
2742 $(td
).append(col
.format(val
, i
));
2750 fieldset
.appendChild(table
);
2756 this.ui
.progress
= this.ui
.AbstractWidget
.extend({
2759 var vn
= parseInt(this.options
.value
) || 0;
2760 var mn
= parseInt(this.options
.max
) || 100;
2761 var pc
= Math
.floor((100 / mn
) * vn
);
2765 if (typeof(this.options
.format
) == 'string')
2766 text
= this.options
.format
.format(this.options
.value
, this.options
.max
, pc
);
2767 else if (typeof(this.options
.format
) == 'function')
2768 text
= this.options
.format(pc
);
2770 text
= '%.2f%%'.format(pc
);
2773 .addClass('progress')
2774 .append($('<div />')
2775 .addClass('progress-bar')
2776 .addClass('progress-bar-info')
2777 .css('width', pc
+ '%'))
2778 .append($('<small />')
2783 this.ui
.devicebadge
= this.ui
.AbstractWidget
.extend({
2786 var l2dev
= this.options
.l2_device
|| this.options
.device
;
2787 var l3dev
= this.options
.l3_device
;
2788 var dev
= l3dev
|| l2dev
|| '?';
2790 var span
= document
.createElement('span');
2791 span
.className
= 'badge';
2793 if (typeof(this.options
.signal
) == 'number' ||
2794 typeof(this.options
.noise
) == 'number')
2797 if (typeof(this.options
.signal
) != 'undefined' &&
2798 typeof(this.options
.noise
) != 'undefined')
2800 var q
= (-1 * (this.options
.noise
- this.options
.signal
)) / 5;
2813 span
.appendChild(document
.createElement('img'));
2814 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/signal-' + r
+ '.png';
2817 span
.title
= _luci2
.tr('No signal');
2819 span
.title
= '%s: %d %s / %s: %d %s'.format(
2820 _luci2
.tr('Signal'), this.options
.signal
, _luci2
.tr('dBm'),
2821 _luci2
.tr('Noise'), this.options
.noise
, _luci2
.tr('dBm')
2826 var type
= 'ethernet';
2827 var desc
= _luci2
.tr('Ethernet device');
2832 desc
= _luci2
.tr('Tunnel interface');
2834 else if (dev
.indexOf('br-') == 0)
2837 desc
= _luci2
.tr('Bridge');
2839 else if (dev
.indexOf('.') > 0)
2842 desc
= _luci2
.tr('VLAN interface');
2844 else if (dev
.indexOf('wlan') == 0 ||
2845 dev
.indexOf('ath') == 0 ||
2846 dev
.indexOf('wl') == 0)
2849 desc
= _luci2
.tr('Wireless Network');
2852 span
.appendChild(document
.createElement('img'));
2853 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/' + type
+ (this.options
.up
? '' : '_disabled') + '.png';
2857 $(span
).append(' ');
2858 $(span
).append(dev
);
2864 var type = function(f
, l
)
2874 _luci2
.cbi
.validation
.message
= _luci2
.tr(msg
);
2877 compile: function(code
)
2882 var types
= _luci2
.cbi
.validation
.types
;
2887 for (var i
= 0; i
< code
.length
; i
++)
2895 switch (code
.charCodeAt(i
))
2907 var label
= code
.substring(pos
, i
);
2908 label
= label
.replace(/\\(.)/g, '$1');
2909 label
= label
.replace(/^[ \t]+/g, '');
2910 label
= label
.replace(/[ \t]+$/g, '');
2912 if (label
&& !isNaN(label
))
2914 stack
.push(parseFloat(label
));
2916 else if (label
.match(/^(['"]).*\1$/))
2918 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
2920 else if (typeof types
[label
] == 'function')
2922 stack
.push(types
[label
]);
2927 throw "Syntax error, unhandled token '"+label
+"'";
2932 depth
+= (code
.charCodeAt(i
) == 40);
2938 if (typeof stack
[stack
.length
-2] != 'function')
2939 throw "Syntax error, argument list follows non-function";
2941 stack
[stack
.length
-1] =
2942 arguments
.callee(code
.substring(pos
, i
));
2955 var validation
= this.cbi
.validation
;
2957 validation
.types
= {
2958 'integer': function()
2960 if (this.match(/^-?[0-9]+$/) != null)
2963 validation
.i18n('Must be a valid integer');
2967 'uinteger': function()
2969 if (validation
.types
['integer'].apply(this) && (this >= 0))
2972 validation
.i18n('Must be a positive integer');
2978 if (!isNaN(parseFloat(this)))
2981 validation
.i18n('Must be a valid number');
2985 'ufloat': function()
2987 if (validation
.types
['float'].apply(this) && (this >= 0))
2990 validation
.i18n('Must be a positive number');
2994 'ipaddr': function()
2996 if (validation
.types
['ip4addr'].apply(this) ||
2997 validation
.types
['ip6addr'].apply(this))
3000 validation
.i18n('Must be a valid IP address');
3004 'ip4addr': function()
3006 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
3008 if ((RegExp
.$1 >= 0) && (RegExp
.$1 <= 255) &&
3009 (RegExp
.$2 >= 0) && (RegExp
.$2 <= 255) &&
3010 (RegExp
.$3 >= 0) && (RegExp
.$3 <= 255) &&
3011 (RegExp
.$4 >= 0) && (RegExp
.$4 <= 255) &&
3012 ((RegExp
.$6.indexOf('.') < 0)
3013 ? ((RegExp
.$6 >= 0) && (RegExp
.$6 <= 32))
3014 : (validation
.types
['ip4addr'].apply(RegExp
.$6))))
3018 validation
.i18n('Must be a valid IPv4 address');
3022 'ip6addr': function()
3024 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
3026 if (!RegExp
.$2 || ((RegExp
.$3 >= 0) && (RegExp
.$3 <= 128)))
3028 var addr
= RegExp
.$1;
3035 if (addr
.indexOf('.') > 0)
3037 var off
= addr
.lastIndexOf(':');
3039 if (!(off
&& validation
.types
['ip4addr'].apply(addr
.substr(off
+1))))
3041 validation
.i18n('Must be a valid IPv6 address');
3045 addr
= addr
.substr(0, off
) + ':0:0';
3048 if (addr
.indexOf('::') >= 0)
3053 for (var i
= 1; i
< (addr
.length
-1); i
++)
3054 if (addr
.charAt(i
) == ':')
3059 validation
.i18n('Must be a valid IPv6 address');
3063 for (var i
= 0; i
< (7 - colons
); i
++)
3066 if (addr
.match(/^(.*?)::(.*?)$/))
3067 addr
= (RegExp
.$1 ? RegExp
.$1 + ':' : '') + fill
+
3068 (RegExp
.$2 ? ':' + RegExp
.$2 : '');
3071 if (addr
.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
3074 validation
.i18n('Must be a valid IPv6 address');
3079 validation
.i18n('Must be a valid IPv6 address');
3085 if (validation
.types
['integer'].apply(this) &&
3086 (this >= 0) && (this <= 65535))
3089 validation
.i18n('Must be a valid port number');
3093 'portrange': function()
3095 if (this.match(/^(\d+)-(\d+)$/))
3100 if (validation
.types
['port'].apply(p1
) &&
3101 validation
.types
['port'].apply(p2
) &&
3102 (parseInt(p1
) <= parseInt(p2
)))
3105 else if (validation
.types
['port'].apply(this))
3110 validation
.i18n('Must be a valid port range');
3114 'macaddr': function()
3116 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
3119 validation
.i18n('Must be a valid MAC address');
3125 if (validation
.types
['hostname'].apply(this) ||
3126 validation
.types
['ipaddr'].apply(this))
3129 validation
.i18n('Must be a valid hostname or IP address');
3133 'hostname': function()
3135 if ((this.length
<= 253) &&
3136 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
3137 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
3138 this.match(/[^0-9.]/)))))
3141 validation
.i18n('Must be a valid host name');
3145 'network': function()
3147 if (validation
.types
['uciname'].apply(this) ||
3148 validation
.types
['host'].apply(this))
3151 validation
.i18n('Must be a valid network name');
3155 'wpakey': function()
3159 if ((v
.length
== 64)
3160 ? (v
.match(/^[a-fA-F0-9]{64}$/) != null)
3161 : ((v
.length
>= 8) && (v
.length
<= 63)))
3164 validation
.i18n('Must be a valid WPA key');
3168 'wepkey': function()
3172 if (v
.substr(0,2) == 's:')
3175 if (((v
.length
== 10) || (v
.length
== 26))
3176 ? (v
.match(/^[a-fA-F0-9]{10,26}$/) != null)
3177 : ((v
.length
== 5) || (v
.length
== 13)))
3180 validation
.i18n('Must be a valid WEP key');
3184 'uciname': function()
3186 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
3189 validation
.i18n('Must be a valid UCI identifier');
3193 'range': function(min
, max
)
3195 var val
= parseFloat(this);
3197 if (validation
.types
['integer'].apply(this) &&
3198 !isNaN(min
) && !isNaN(max
) && ((val
>= min
) && (val
<= max
)))
3201 validation
.i18n('Must be a number between %d and %d');
3205 'min': function(min
)
3207 var val
= parseFloat(this);
3209 if (validation
.types
['integer'].apply(this) &&
3210 !isNaN(min
) && !isNaN(val
) && (val
>= min
))
3213 validation
.i18n('Must be a number greater or equal to %d');
3217 'max': function(max
)
3219 var val
= parseFloat(this);
3221 if (validation
.types
['integer'].apply(this) &&
3222 !isNaN(max
) && !isNaN(val
) && (val
<= max
))
3225 validation
.i18n('Must be a number lower or equal to %d');
3229 'rangelength': function(min
, max
)
3231 var val
= '' + this;
3233 if (!isNaN(min
) && !isNaN(max
) &&
3234 (val
.length
>= min
) && (val
.length
<= max
))
3237 validation
.i18n('Must be between %d and %d characters');
3241 'minlength': function(min
)
3243 var val
= '' + this;
3245 if (!isNaN(min
) && (val
.length
>= min
))
3248 validation
.i18n('Must be at least %d characters');
3252 'maxlength': function(max
)
3254 var val
= '' + this;
3256 if (!isNaN(max
) && (val
.length
<= max
))
3259 validation
.i18n('Must be at most %d characters');
3267 for (var i
= 0; i
< arguments
.length
; i
+= 2)
3269 delete validation
.message
;
3271 if (typeof(arguments
[i
]) != 'function')
3273 if (arguments
[i
] == this)
3277 else if (arguments
[i
].apply(this, arguments
[i
+1]))
3282 if (validation
.message
)
3283 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
3286 validation
.message
= msgs
.join( _luci2
.tr(' - or - '));
3294 for (var i
= 0; i
< arguments
.length
; i
+= 2)
3296 delete validation
.message
;
3298 if (typeof arguments
[i
] != 'function')
3300 if (arguments
[i
] != this)
3304 else if (!arguments
[i
].apply(this, arguments
[i
+1]))
3309 if (validation
.message
)
3310 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
3313 validation
.message
= msgs
.join(', ');
3319 return validation
.types
['or'].apply(
3320 this.replace(/^[ \t]*![ \t]*/, ''), arguments
);
3323 'list': function(subvalidator
, subargs
)
3325 if (typeof subvalidator
!= 'function')
3328 var tokens
= this.match(/[^ \t]+/g);
3329 for (var i
= 0; i
< tokens
.length
; i
++)
3330 if (!subvalidator
.apply(tokens
[i
], subargs
))
3336 'phonedigit': function()
3338 if (this.match(/^[0-9\*#!\.]+$/) != null)
3341 validation
.i18n('Must be a valid phone number digit');
3345 'string': function()
3352 this.cbi
.AbstractValue
= this.ui
.AbstractWidget
.extend({
3353 init: function(name
, options
)
3356 this.instance
= { };
3357 this.dependencies
= [ ];
3358 this.rdependency
= { };
3360 this.options
= _luci2
.defaults(options
, {
3370 return this.section
.id('field', sid
|| '__unknown__', this.name
);
3373 render: function(sid
, condensed
)
3375 var i
= this.instance
[sid
] = { };
3377 i
.top
= $('<div />');
3381 i
.top
.addClass('form-group');
3383 if (typeof(this.options
.caption
) == 'string')
3385 .addClass('col-lg-2 control-label')
3386 .attr('for', this.id(sid
))
3387 .text(this.options
.caption
)
3391 i
.error
= $('<div />')
3392 .addClass('label label-danger');
3394 i
.widget
= $('<div />')
3396 .append(this.widget(sid
))
3402 i
.widget
.addClass('col-lg-5');
3405 .addClass('col-lg-5')
3406 .text((typeof(this.options
.description
) == 'string') ? this.options
.description
: '')
3413 ucipath: function(sid
)
3416 config
: (this.options
.uci_package
|| this.map
.uci_package
),
3417 section
: (this.options
.uci_section
|| sid
),
3418 option
: (this.options
.uci_option
|| this.name
)
3422 ucivalue: function(sid
)
3424 var uci
= this.ucipath(sid
);
3425 var val
= this.map
.get(uci
.config
, uci
.section
, uci
.option
);
3427 if (typeof(val
) == 'undefined')
3428 return this.options
.initial
;
3433 formvalue: function(sid
)
3435 var v
= $('#' + this.id(sid
)).val();
3436 return (v
=== '') ? undefined : v
;
3439 textvalue: function(sid
)
3441 var v
= this.formvalue(sid
);
3443 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
3444 v
= this.ucivalue(sid
);
3446 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
3447 v
= this.options
.placeholder
;
3449 if (typeof(v
) == 'undefined' || v
=== '')
3452 if (typeof(v
) == 'string' && $.isArray(this.choices
))
3454 for (var i
= 0; i
< this.choices
.length
; i
++)
3455 if (v
=== this.choices
[i
][0])
3456 return this.choices
[i
][1];
3458 else if (v
=== true)
3459 return _luci2
.tr('yes');
3460 else if (v
=== false)
3461 return _luci2
.tr('no');
3462 else if ($.isArray(v
))
3463 return v
.join(', ');
3468 changed: function(sid
)
3470 var a
= this.ucivalue(sid
);
3471 var b
= this.formvalue(sid
);
3473 if (typeof(a
) != typeof(b
))
3476 if (typeof(a
) == 'object')
3478 if (a
.length
!= b
.length
)
3481 for (var i
= 0; i
< a
.length
; i
++)
3493 var uci
= this.ucipath(sid
);
3495 if (this.instance
[sid
].disabled
)
3497 if (!this.options
.keep
)
3498 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3503 var chg
= this.changed(sid
);
3504 var val
= this.formvalue(sid
);
3507 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
);
3512 _ev_validate: function(ev
)
3516 var val
= d
.elem
.val();
3517 var vstack
= d
.vstack
;
3519 if (vstack
&& typeof(vstack
[0]) == 'function')
3521 delete validation
.message
;
3523 if ((val
.length
== 0 && !d
.opt
))
3525 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
3526 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
3528 d
.inst
.error
.text(_luci2
.tr('Field must not be empty'));
3531 else if (val
.length
> 0 && !vstack
[0].apply(val
, vstack
[1]))
3533 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
3534 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
3536 d
.inst
.error
.text(validation
.message
.format
.apply(validation
.message
, vstack
[1]));
3541 d
.elem
.parents('div.form-group, td').first().removeClass('luci2-form-error');
3542 d
.elem
.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
3544 if (d
.multi
&& d
.inst
.widget
&& d
.inst
.widget
.find('input.error, select.error').length
> 0)
3547 d
.inst
.error
.text('');
3552 for (var field
in d
.self
.rdependency
)
3553 d
.self
.rdependency
[field
].toggle(d
.sid
);
3558 validator: function(sid
, elem
, multi
)
3560 if (typeof(this.options
.datatype
) == 'undefined' && $.isEmptyObject(this.rdependency
))
3564 if (typeof(this.options
.datatype
) == 'string')
3567 vstack
= _luci2
.cbi
.validation
.compile(this.options
.datatype
);
3570 else if (typeof(this.options
.datatype
) == 'function')
3572 var vfunc
= this.options
.datatype
;
3573 vstack
= [ function(elem
) {
3574 var rv
= vfunc(this, elem
);
3576 validation
.message
= rv
;
3577 return (rv
=== true);
3587 inst
: this.instance
[sid
],
3588 opt
: this.options
.optional
3591 if (elem
.prop('tagName') == 'SELECT')
3593 elem
.change(evdata
, this._ev_validate
);
3595 else if (elem
.prop('tagName') == 'INPUT' && elem
.attr('type') == 'checkbox')
3597 elem
.click(evdata
, this._ev_validate
);
3598 elem
.blur(evdata
, this._ev_validate
);
3602 elem
.keyup(evdata
, this._ev_validate
);
3603 elem
.blur(evdata
, this._ev_validate
);
3606 elem
.attr('cbi-validate', true).on('validate', evdata
, this._ev_validate
);
3611 validate: function(sid
)
3613 var i
= this.instance
[sid
];
3615 i
.widget
.find('[cbi-validate]').trigger('validate');
3617 return (i
.disabled
|| i
.error
.text() == '');
3620 depends: function(d
, v
)
3627 for (var i
= 0; i
< d
.length
; i
++)
3629 if (typeof(d
[i
]) == 'string')
3631 else if (d
[i
] instanceof _luci2
.cbi
.AbstractValue
)
3632 dep
[d
[i
].name
] = true;
3635 else if (d
instanceof _luci2
.cbi
.AbstractValue
)
3638 dep
[d
.name
] = (typeof(v
) == 'undefined') ? true : v
;
3640 else if (typeof(d
) == 'object')
3644 else if (typeof(d
) == 'string')
3647 dep
[d
] = (typeof(v
) == 'undefined') ? true : v
;
3650 if (!dep
|| $.isEmptyObject(dep
))
3653 for (var field
in dep
)
3655 var f
= this.section
.fields
[field
];
3657 f
.rdependency
[this.name
] = this;
3662 if ($.isEmptyObject(dep
))
3665 this.dependencies
.push(dep
);
3670 toggle: function(sid
)
3672 var d
= this.dependencies
;
3673 var i
= this.instance
[sid
];
3678 for (var n
= 0; n
< d
.length
; n
++)
3682 for (var field
in d
[n
])
3684 var val
= this.section
.fields
[field
].formvalue(sid
);
3685 var cmp
= d
[n
][field
];
3687 if (typeof(cmp
) == 'boolean')
3689 if (cmp
== (typeof(val
) == 'undefined' || val
=== '' || val
=== false))
3695 else if (typeof(cmp
) == 'string')
3703 else if (typeof(cmp
) == 'function')
3711 else if (cmp
instanceof RegExp
)
3736 i
.top
.is(':visible') ? i
.top
.fadeOut() : i
.top
.hide();
3743 this.cbi
.CheckboxValue
= this.cbi
.AbstractValue
.extend({
3744 widget: function(sid
)
3746 var o
= this.options
;
3748 if (typeof(o
.enabled
) == 'undefined') o
.enabled
= '1';
3749 if (typeof(o
.disabled
) == 'undefined') o
.disabled
= '0';
3751 var i
= $('<input />')
3752 .addClass('form-control')
3753 .attr('id', this.id(sid
))
3754 .attr('type', 'checkbox')
3755 .prop('checked', this.ucivalue(sid
));
3758 .addClass('checkbox')
3759 .append(this.validator(sid
, i
));
3762 ucivalue: function(sid
)
3764 var v
= this.callSuper('ucivalue', sid
);
3766 if (typeof(v
) == 'boolean')
3769 return (v
== this.options
.enabled
);
3772 formvalue: function(sid
)
3774 var v
= $('#' + this.id(sid
)).prop('checked');
3776 if (typeof(v
) == 'undefined')
3777 return !!this.options
.initial
;
3784 var uci
= this.ucipath(sid
);
3786 if (this.instance
[sid
].disabled
)
3788 if (!this.options
.keep
)
3789 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3794 var chg
= this.changed(sid
);
3795 var val
= this.formvalue(sid
);
3799 if (this.options
.optional
&& val
== this.options
.initial
)
3800 this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3802 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
? this.options
.enabled
: this.options
.disabled
);
3809 this.cbi
.InputValue
= this.cbi
.AbstractValue
.extend({
3810 widget: function(sid
)
3812 var i
= $('<input />')
3813 .addClass('form-control')
3814 .attr('id', this.id(sid
))
3815 .attr('type', 'text')
3816 .attr('placeholder', this.options
.placeholder
)
3817 .val(this.ucivalue(sid
));
3819 return this.validator(sid
, i
);
3823 this.cbi
.PasswordValue
= this.cbi
.AbstractValue
.extend({
3824 widget: function(sid
)
3826 var i
= $('<input />')
3827 .addClass('form-control')
3828 .attr('id', this.id(sid
))
3829 .attr('type', 'password')
3830 .attr('placeholder', this.options
.placeholder
)
3831 .val(this.ucivalue(sid
));
3833 var t
= $('<span />')
3834 .addClass('input-group-btn')
3835 .append(_luci2
.ui
.button(_luci2
.tr('Reveal'), 'default')
3836 .click(function(ev
) {
3838 var i
= b
.parent().prev();
3839 var t
= i
.attr('type');
3840 b
.text(t
== 'password' ? _luci2
.tr('Hide') : _luci2
.tr('Reveal'));
3841 i
.attr('type', (t
== 'password') ? 'text' : 'password');
3845 this.validator(sid
, i
);
3848 .addClass('input-group')
3854 this.cbi
.ListValue
= this.cbi
.AbstractValue
.extend({
3855 widget: function(sid
)
3857 var s
= $('<select />')
3858 .addClass('form-control');
3860 if (this.options
.optional
)
3863 .text(_luci2
.tr('-- Please choose --'))
3867 for (var i
= 0; i
< this.choices
.length
; i
++)
3869 .attr('value', this.choices
[i
][0])
3870 .text(this.choices
[i
][1])
3873 s
.attr('id', this.id(sid
)).val(this.ucivalue(sid
));
3875 return this.validator(sid
, s
);
3878 value: function(k
, v
)
3883 this.choices
.push([k
, v
|| k
]);
3888 this.cbi
.MultiValue
= this.cbi
.ListValue
.extend({
3889 widget: function(sid
)
3891 var v
= this.ucivalue(sid
);
3892 var t
= $('<div />').attr('id', this.id(sid
));
3895 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
3898 for (var i
= 0; i
< v
.length
; i
++)
3902 for (var i
= 0; i
< this.choices
.length
; i
++)
3905 .append($('<input />')
3906 .addClass('cbi-input-checkbox')
3907 .attr('type', 'checkbox')
3908 .attr('value', this.choices
[i
][0])
3909 .prop('checked', s
[this.choices
[i
][0]]))
3910 .append(this.choices
[i
][1])
3920 formvalue: function(sid
)
3923 var fields
= $('#' + this.id(sid
) + ' > label > input');
3925 for (var i
= 0; i
< fields
.length
; i
++)
3926 if (fields
[i
].checked
)
3927 rv
.push(fields
[i
].getAttribute('value'));
3932 textvalue: function(sid
)
3934 var v
= this.formvalue(sid
);
3938 for (var i
= 0; i
< this.choices
.length
; i
++)
3939 c
[this.choices
[i
][0]] = this.choices
[i
][1];
3943 for (var i
= 0; i
< v
.length
; i
++)
3944 t
.push(c
[v
[i
]] || v
[i
]);
3946 return t
.join(', ');
3950 this.cbi
.ComboBox
= this.cbi
.AbstractValue
.extend({
3951 _change: function(ev
)
3954 var self
= ev
.data
.self
;
3956 if (s
.selectedIndex
== (s
.options
.length
- 1))
3958 ev
.data
.select
.hide();
3959 ev
.data
.input
.show().focus();
3961 var v
= ev
.data
.input
.val();
3962 ev
.data
.input
.val(' ');
3963 ev
.data
.input
.val(v
);
3965 else if (self
.options
.optional
&& s
.selectedIndex
== 0)
3967 ev
.data
.input
.val('');
3971 ev
.data
.input
.val(ev
.data
.select
.val());
3978 var val
= this.value
;
3979 var self
= ev
.data
.self
;
3981 ev
.data
.select
.empty();
3983 if (self
.options
.optional
)
3986 .text(_luci2
.tr('-- please choose --'))
3987 .appendTo(ev
.data
.select
);
3990 for (var i
= 0; i
< self
.choices
.length
; i
++)
3992 if (self
.choices
[i
][0] == val
)
3996 .attr('value', self
.choices
[i
][0])
3997 .text(self
.choices
[i
][1])
3998 .appendTo(ev
.data
.select
);
4001 if (!seen
&& val
!= '')
4005 .appendTo(ev
.data
.select
);
4009 .text(_luci2
.tr('-- custom --'))
4010 .appendTo(ev
.data
.select
);
4012 ev
.data
.input
.hide();
4013 ev
.data
.select
.val(val
).show().focus();
4016 _enter: function(ev
)
4021 ev
.preventDefault();
4022 ev
.data
.self
._blur(ev
);
4026 widget: function(sid
)
4028 var d
= $('<div />')
4029 .attr('id', this.id(sid
));
4031 var t
= $('<input />')
4032 .attr('type', 'text')
4036 var s
= $('<select />')
4041 input
: this.validator(sid
, t
),
4042 select
: this.validator(sid
, s
)
4045 s
.change(evdata
, this._change
);
4046 t
.blur(evdata
, this._blur
);
4047 t
.keydown(evdata
, this._enter
);
4049 t
.val(this.ucivalue(sid
));
4055 value: function(k
, v
)
4060 this.choices
.push([k
, v
|| k
]);
4064 formvalue: function(sid
)
4066 var v
= $('#' + this.id(sid
)).children('input').val();
4067 return (v
== '') ? undefined : v
;
4071 this.cbi
.DynamicList
= this.cbi
.ComboBox
.extend({
4072 _redraw: function(focus
, add
, del
, s
)
4074 var v
= s
.values
|| [ ];
4077 $(s
.parent
).children('div.input-group').children('input').each(function(i
) {
4079 v
.push(this.value
|| '');
4082 $(s
.parent
).empty();
4087 v
.splice(focus
, 0, '');
4089 else if (v
.length
== 0)
4095 for (var i
= 0; i
< v
.length
; i
++)
4102 remove
: ((i
+1) < v
.length
)
4107 btn
= _luci2
.ui
.button('–', 'danger').click(evdata
, this._btnclick
);
4109 btn
= _luci2
.ui
.button('+', 'success').click(evdata
, this._btnclick
);
4113 var txt
= $('<input />')
4114 .addClass('form-control')
4115 .attr('type', 'text')
4118 var sel
= $('<select />')
4119 .addClass('form-control');
4122 .addClass('input-group')
4125 .append($('<span />')
4126 .addClass('input-group-btn')
4128 .appendTo(s
.parent
);
4130 evdata
.input
= this.validator(s
.sid
, txt
, true);
4131 evdata
.select
= this.validator(s
.sid
, sel
, true);
4133 sel
.change(evdata
, this._change
);
4134 txt
.blur(evdata
, this._blur
);
4135 txt
.keydown(evdata
, this._keydown
);
4140 if (i
== focus
|| -(i
+1) == focus
)
4147 var f
= $('<input />')
4148 .attr('type', 'text')
4150 .attr('placeholder', (i
== 0) ? this.options
.placeholder
: '')
4151 .addClass('form-control')
4152 .keydown(evdata
, this._keydown
)
4153 .keypress(evdata
, this._keypress
)
4157 .addClass('input-group')
4159 .append($('<span />')
4160 .addClass('input-group-btn')
4162 .appendTo(s
.parent
);
4168 else if (-(i
+1) == focus
)
4172 /* force cursor to end */
4178 evdata
.input
= this.validator(s
.sid
, f
, true);
4189 _keypress: function(ev
)
4193 /* backspace, delete */
4196 if (ev
.data
.input
.val() == '')
4198 ev
.preventDefault();
4204 /* enter, arrow up, arrow down */
4208 ev
.preventDefault();
4215 _keydown: function(ev
)
4217 var input
= ev
.data
.input
;
4221 /* backspace, delete */
4224 if (input
.val().length
== 0)
4226 ev
.preventDefault();
4228 var index
= ev
.data
.index
;
4234 ev
.data
.self
._redraw(focus
, -1, index
, ev
.data
);
4242 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
4247 var prev
= input
.parent().prevAll('div.input-group:first').children('input');
4248 if (prev
.is(':visible'))
4251 prev
.next('select').focus();
4256 var next
= input
.parent().nextAll('div.input-group:first').children('input');
4257 if (next
.is(':visible'))
4260 next
.next('select').focus();
4267 _btnclick: function(ev
)
4269 if (!this.getAttribute('disabled'))
4273 var index
= ev
.data
.index
;
4274 ev
.data
.self
._redraw(-index
, -1, index
, ev
.data
);
4278 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
4285 widget: function(sid
)
4287 this.options
.optional
= true;
4289 var v
= this.ucivalue(sid
);
4292 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
4294 var d
= $('<div />')
4295 .attr('id', this.id(sid
))
4296 .addClass('cbi-input-dynlist');
4298 this._redraw(NaN
, -1, -1, {
4308 ucivalue: function(sid
)
4310 var v
= this.callSuper('ucivalue', sid
);
4313 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
4318 formvalue: function(sid
)
4321 var fields
= $('#' + this.id(sid
) + ' > input');
4323 for (var i
= 0; i
< fields
.length
; i
++)
4324 if (typeof(fields
[i
].value
) == 'string' && fields
[i
].value
.length
)
4325 rv
.push(fields
[i
].value
);
4331 this.cbi
.DummyValue
= this.cbi
.AbstractValue
.extend({
4332 widget: function(sid
)
4335 .addClass('form-control-static')
4336 .attr('id', this.id(sid
))
4337 .html(this.ucivalue(sid
));
4340 formvalue: function(sid
)
4342 return this.ucivalue(sid
);
4346 this.cbi
.NetworkList
= this.cbi
.AbstractValue
.extend({
4351 if (!self
.interfaces
)
4353 self
.interfaces
= [ ];
4354 return _luci2
.network
.getNetworkStatus().then(function(ifaces
) {
4355 self
.interfaces
= ifaces
;
4363 _device_icon: function(dev
)
4365 var type
= 'ethernet';
4366 var desc
= _luci2
.tr('Ethernet device');
4368 if (dev
.type
== 'IP tunnel')
4371 desc
= _luci2
.tr('Tunnel interface');
4373 else if (dev
['bridge-members'])
4376 desc
= _luci2
.tr('Bridge');
4378 else if (dev
.wireless
)
4381 desc
= _luci2
.tr('Wireless Network');
4383 else if (dev
.device
.indexOf('.') > 0)
4386 desc
= _luci2
.tr('VLAN interface');
4390 .attr('src', _luci2
.globals
.resource
+ '/icons/' + type
+ (dev
.up
? '' : '_disabled') + '.png')
4391 .attr('title', '%s (%s)'.format(desc
, dev
.device
));
4394 widget: function(sid
)
4396 var id
= this.id(sid
);
4397 var ul
= $('<ul />')
4399 .addClass('list-unstyled');
4401 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
4402 var value
= this.ucivalue(sid
);
4405 if (!this.options
.multiple
)
4406 check
[value
] = true;
4408 for (var i
= 0; i
< value
.length
; i
++)
4409 check
[value
[i
]] = true;
4411 if (this.interfaces
)
4413 for (var i
= 0; i
< this.interfaces
.length
; i
++)
4415 var iface
= this.interfaces
[i
];
4416 var badge
= $('<span />')
4418 .text('%s: '.format(iface
['interface']));
4420 if (iface
.device
&& iface
.device
.subdevices
)
4421 for (var j
= 0; j
< iface
.device
.subdevices
.length
; j
++)
4422 badge
.append(this._device_icon(iface
.device
.subdevices
[j
]));
4423 else if (iface
.device
)
4424 badge
.append(this._device_icon(iface
.device
));
4426 badge
.append($('<em />').text(_luci2
.tr('(No devices attached)')));
4429 .append($('<label />')
4430 .addClass('radio inline')
4431 .append($('<input />')
4432 .attr('name', itype
+ id
)
4433 .attr('type', itype
)
4434 .attr('value', iface
['interface'])
4435 .prop('checked', !!check
[iface
['interface']])
4436 .addClass('form-control'))
4442 if (!this.options
.multiple
)
4445 .append($('<label />')
4446 .addClass('radio inline text-muted')
4447 .append($('<input />')
4448 .attr('name', itype
+ id
)
4449 .attr('type', itype
)
4451 .prop('checked', !value
)
4452 .addClass('form-control'))
4453 .append(_luci2
.tr('unspecified')))
4460 ucivalue: function(sid
)
4462 var v
= this.callSuper('ucivalue', sid
);
4464 if (!this.options
.multiple
)
4470 else if (typeof(v
) == 'string')
4473 return v
? v
[0] : undefined;
4480 if (typeof(v
) == 'string')
4481 v
= v
.match(/\S+/g);
4487 formvalue: function(sid
)
4489 var inputs
= $('#' + this.id(sid
) + ' input');
4491 if (!this.options
.multiple
)
4493 for (var i
= 0; i
< inputs
.length
; i
++)
4494 if (inputs
[i
].checked
&& inputs
[i
].value
!== '')
4495 return inputs
[i
].value
;
4502 for (var i
= 0; i
< inputs
.length
; i
++)
4503 if (inputs
[i
].checked
)
4504 rv
.push(inputs
[i
].value
);
4506 return rv
.length
? rv
: undefined;
4511 this.cbi
.AbstractSection
= this.ui
.AbstractWidget
.extend({
4514 var s
= [ arguments
[0], this.map
.uci_package
, this.uci_type
];
4516 for (var i
= 1; i
< arguments
.length
; i
++)
4517 s
.push(arguments
[i
].replace(/\./g, '_'));
4522 option: function(widget
, name
, options
)
4524 if (this.tabs
.length
== 0)
4525 this.tab({ id
: '__default__', selected
: true });
4527 return this.taboption('__default__', widget
, name
, options
);
4530 tab: function(options
)
4532 if (options
.selected
)
4533 this.tabs
.selected
= this.tabs
.length
;
4537 caption
: options
.caption
,
4538 description
: options
.description
,
4544 taboption: function(tabid
, widget
, name
, options
)
4547 for (var i
= 0; i
< this.tabs
.length
; i
++)
4549 if (this.tabs
[i
].id
== tabid
)
4557 throw 'Cannot append to unknown tab ' + tabid
;
4559 var w
= widget
? new widget(name
, options
) : null;
4561 if (!(w
instanceof _luci2
.cbi
.AbstractValue
))
4562 throw 'Widget must be an instance of AbstractValue';
4567 this.fields
[name
] = w
;
4573 ucipackages: function(pkg
)
4575 for (var i
= 0; i
< this.tabs
.length
; i
++)
4576 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4577 if (this.tabs
[i
].fields
[j
].options
.uci_package
)
4578 pkg
[this.tabs
[i
].fields
[j
].options
.uci_package
] = true;
4581 formvalue: function()
4585 this.sections(function(s
) {
4586 var sid
= s
['.name'];
4587 var sv
= rv
[sid
] || (rv
[sid
] = { });
4589 for (var i
= 0; i
< this.tabs
.length
; i
++)
4590 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4592 var val
= this.tabs
[i
].fields
[j
].formvalue(sid
);
4593 sv
[this.tabs
[i
].fields
[j
].name
] = val
;
4600 validate_section: function(sid
)
4602 var inst
= this.instance
[sid
];
4605 var badge
= $('#' + this.id('teaser', sid
)).children('span:first');
4607 for (var i
= 0; i
< this.tabs
.length
; i
++)
4610 var stbadge
= $('#' + this.id('nodetab', sid
, this.tabs
[i
].id
)).children('span:first');
4612 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4613 if (!this.tabs
[i
].fields
[j
].validate(sid
))
4618 .attr('title', _luci2
.trp('1 Error', '%d Errors', inval
).format(inval
));
4627 .attr('title', _luci2
.trp('1 Error', '%d Errors', invals
).format(invals
));
4634 validate: function()
4636 this.error_count
= 0;
4638 var as
= this.sections();
4640 for (var i
= 0; i
< as
.length
; i
++)
4642 var invals
= this.validate_section(as
[i
]['.name']);
4645 this.error_count
+= invals
;
4648 var badge
= $('#' + this.id('sectiontab')).children('span:first');
4650 if (this.error_count
> 0)
4651 badge
.text(this.error_count
)
4652 .attr('title', _luci2
.trp('1 Error', '%d Errors', this.error_count
).format(this.error_count
));
4656 return (this.error_count
== 0);
4660 this.cbi
.TypedSection
= this.cbi
.AbstractSection
.extend({
4661 init: function(uci_type
, options
)
4663 this.uci_type
= uci_type
;
4664 this.options
= options
;
4667 this.error_count
= 0;
4668 this.active_panel
= 0;
4669 this.active_tab
= { };
4672 filter: function(section
)
4677 sections: function(cb
)
4679 var s1
= this.map
.ucisections(this.map
.uci_package
);
4682 for (var i
= 0; i
< s1
.length
; i
++)
4683 if (s1
[i
]['.type'] == this.uci_type
)
4684 if (this.filter(s1
[i
]))
4687 if (typeof(cb
) == 'function')
4688 for (var i
= 0; i
< s2
.length
; i
++)
4689 cb
.apply(this, [ s2
[i
] ]);
4696 this.map
.add(this.map
.uci_package
, this.uci_type
, name
);
4699 remove: function(sid
)
4701 this.map
.remove(this.map
.uci_package
, sid
);
4704 _ev_add: function(ev
)
4707 var name
= undefined;
4708 var self
= ev
.data
.self
;
4710 if (addb
.prev().prop('nodeName') == 'INPUT')
4711 name
= addb
.prev().val();
4713 if (addb
.prop('disabled') || name
=== '')
4716 _luci2
.ui
.saveScrollTop();
4718 self
.active_panel
= -1;
4723 _luci2
.ui
.restoreScrollTop();
4726 _ev_remove: function(ev
)
4728 var self
= ev
.data
.self
;
4729 var sid
= ev
.data
.sid
;
4731 _luci2
.ui
.saveScrollTop();
4737 _luci2
.ui
.restoreScrollTop();
4739 ev
.stopPropagation();
4742 _ev_sid: function(ev
)
4744 var self
= ev
.data
.self
;
4746 var addb
= text
.next();
4747 var errt
= addb
.next();
4748 var name
= text
.val();
4751 if (!/^[a-zA-Z0-9_]*$/.test(name
))
4753 errt
.text(_luci2
.tr('Invalid section name')).show();
4754 text
.addClass('error');
4755 addb
.prop('disabled', true);
4759 for (var sid
in self
.map
.uci
.values
[self
.map
.uci_package
])
4766 for (var sid
in self
.map
.uci
.creates
[self
.map
.uci_package
])
4775 errt
.text(_luci2
.tr('Name already used')).show();
4776 text
.addClass('error');
4777 addb
.prop('disabled', true);
4781 errt
.text('').hide();
4782 text
.removeClass('error');
4783 addb
.prop('disabled', false);
4787 _ev_tab: function(ev
)
4789 var self
= ev
.data
.self
;
4790 var sid
= ev
.data
.sid
;
4793 self
.active_tab
[sid
] = parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
4796 _ev_panel_collapse: function(ev
)
4798 var self
= ev
.data
.self
;
4800 var this_panel
= $(ev
.target
);
4801 var this_toggle
= this_panel
.prevAll('[data-toggle="collapse"]:first');
4803 var prev_toggle
= $($(ev
.delegateTarget
).find('[data-toggle="collapse"]:eq(%d)'.format(self
.active_panel
)));
4804 var prev_panel
= $(prev_toggle
.attr('data-target'));
4808 .addClass('collapse');
4810 prev_toggle
.find('.luci2-section-teaser')
4812 .children('span:last')
4814 .append(self
.teaser(prev_panel
.attr('data-luci2-sid')));
4816 this_toggle
.find('.luci2-section-teaser')
4819 self
.active_panel
= parseInt(this_panel
.attr('data-luci2-panel-index'));
4823 _ev_panel_open: function(ev
)
4825 var self
= ev
.data
.self
;
4826 var panel
= $($(this).attr('data-target'));
4827 var index
= parseInt(panel
.attr('data-luci2-panel-index'));
4829 if (index
== self
.active_panel
)
4830 ev
.stopPropagation();
4833 _ev_sort: function(ev
)
4835 var self
= ev
.data
.self
;
4836 var cur_idx
= ev
.data
.index
;
4837 var new_idx
= cur_idx
+ (ev
.data
.up
? -1 : 1);
4838 var s
= self
.sections();
4840 if (new_idx
>= 0 && new_idx
< s
.length
)
4842 var tmp
= s
[cur_idx
]['.index'];
4844 s
[cur_idx
]['.index'] = s
[new_idx
]['.index'];
4845 s
[new_idx
]['.index'] = tmp
;
4847 if (self
.active_panel
== cur_idx
)
4848 self
.active_panel
= new_idx
;
4849 else if (self
.active_panel
== new_idx
)
4850 self
.active_panel
= cur_idx
;
4852 self
.map
.uci
.reorder
= true;
4858 ev
.stopPropagation();
4861 teaser: function(sid
)
4863 var tf
= this.teaser_fields
;
4867 tf
= this.teaser_fields
= [ ];
4869 if ($.isArray(this.options
.teasers
))
4871 for (var i
= 0; i
< this.options
.teasers
.length
; i
++)
4873 var f
= this.options
.teasers
[i
];
4874 if (f
instanceof _luci2
.cbi
.AbstractValue
)
4876 else if (typeof(f
) == 'string' && this.fields
[f
] instanceof _luci2
.cbi
.AbstractValue
)
4877 tf
.push(this.fields
[f
]);
4882 for (var i
= 0; tf
.length
<= 5 && i
< this.tabs
.length
; i
++)
4883 for (var j
= 0; tf
.length
<= 5 && j
< this.tabs
[i
].fields
.length
; j
++)
4884 tf
.push(this.tabs
[i
].fields
[j
]);
4890 for (var i
= 0; i
< tf
.length
; i
++)
4892 if (tf
[i
].instance
[sid
] && tf
[i
].instance
[sid
].disabled
)
4895 var n
= tf
[i
].options
.caption
|| tf
[i
].name
;
4896 var v
= tf
[i
].textvalue(sid
);
4898 if (typeof(v
) == 'undefined')
4901 t
= t
+ '%s%s: <strong>%s</strong>'.format(t
? ' | ' : '', n
, v
);
4907 _render_add: function()
4909 if (!this.options
.addremove
)
4912 var text
= _luci2
.tr('Add section');
4913 var ttip
= _luci2
.tr('Create new section...');
4915 if ($.isArray(this.options
.add_caption
))
4916 text
= this.options
.add_caption
[0], ttip
= this.options
.add_caption
[1];
4917 else if (typeof(this.options
.add_caption
) == 'string')
4918 text
= this.options
.add_caption
, ttip
= '';
4920 var add
= $('<div />');
4922 if (this.options
.anonymous
=== false)
4925 .addClass('cbi-input-text')
4926 .attr('type', 'text')
4927 .attr('placeholder', ttip
)
4928 .blur({ self
: this }, this._ev_sid
)
4929 .keyup({ self
: this }, this._ev_sid
)
4933 .attr('src', _luci2
.globals
.resource
+ '/icons/cbi/add.gif')
4934 .attr('title', text
)
4935 .addClass('cbi-button')
4936 .click({ self
: this }, this._ev_add
)
4940 .addClass('cbi-value-error')
4946 _luci2
.ui
.button(text
, 'success', ttip
)
4947 .click({ self
: this }, this._ev_add
)
4954 _render_remove: function(sid
, index
)
4956 if (!this.options
.addremove
)
4959 var text
= _luci2
.tr('Remove');
4960 var ttip
= _luci2
.tr('Remove this section');
4962 if ($.isArray(this.options
.remove_caption
))
4963 text
= this.options
.remove_caption
[0], ttip
= this.options
.remove_caption
[1];
4964 else if (typeof(this.options
.remove_caption
) == 'string')
4965 text
= this.options
.remove_caption
, ttip
= '';
4967 return _luci2
.ui
.button(text
, 'danger', ttip
)
4968 .click({ self
: this, sid
: sid
, index
: index
}, this._ev_remove
);
4971 _render_sort: function(sid
, index
)
4973 if (!this.options
.sortable
)
4976 var b1
= _luci2
.ui
.button('↑', 'info', _luci2
.tr('Move up'))
4977 .click({ self
: this, index
: index
, up
: true }, this._ev_sort
);
4979 var b2
= _luci2
.ui
.button('↓', 'info', _luci2
.tr('Move down'))
4980 .click({ self
: this, index
: index
, up
: false }, this._ev_sort
);
4985 _render_caption: function()
4988 .addClass('panel-title')
4989 .append(this.label('caption') || this.uci_type
);
4992 _render_description: function()
4994 var text
= this.label('description');
4998 .addClass('luci2-section-description')
5004 _render_teaser: function(sid
, index
)
5006 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
5009 .attr('id', this.id('teaser', sid
))
5010 .addClass('luci2-section-teaser well well-sm')
5011 .append($('<span />')
5013 .append($('<span />'));
5019 _render_head: function(condensed
)
5025 .addClass('panel-heading')
5026 .append(this._render_caption())
5027 .append(this._render_description());
5030 _render_tab_description: function(sid
, index
, tab_index
)
5032 var tab
= this.tabs
[tab_index
];
5034 if (typeof(tab
.description
) == 'string')
5037 .addClass('cbi-tab-descr')
5038 .text(tab
.description
);
5044 _render_tab_head: function(sid
, index
, tab_index
)
5046 var tab
= this.tabs
[tab_index
];
5047 var cur
= this.active_tab
[sid
] || 0;
5049 var tabh
= $('<li />')
5051 .attr('id', this.id('nodetab', sid
, tab
.id
))
5052 .attr('href', '#' + this.id('node', sid
, tab
.id
))
5053 .attr('data-toggle', 'tab')
5054 .attr('data-luci2-tab-index', tab_index
)
5055 .text((tab
.caption
? tab
.caption
.format(tab
.id
) : tab
.id
) + ' ')
5056 .append($('<span />')
5058 .on('shown.bs.tab', { self
: this, sid
: sid
}, this._ev_tab
));
5060 if (cur
== tab_index
)
5061 tabh
.addClass('active');
5066 _render_tab_body: function(sid
, index
, tab_index
)
5068 var tab
= this.tabs
[tab_index
];
5069 var cur
= this.active_tab
[sid
] || 0;
5071 var tabb
= $('<div />')
5072 .addClass('tab-pane')
5073 .attr('id', this.id('node', sid
, tab
.id
))
5074 .attr('data-luci2-tab-index', tab_index
)
5075 .append(this._render_tab_description(sid
, index
, tab_index
));
5077 if (cur
== tab_index
)
5078 tabb
.addClass('active');
5080 for (var i
= 0; i
< tab
.fields
.length
; i
++)
5081 tabb
.append(tab
.fields
[i
].render(sid
));
5086 _render_section_head: function(sid
, index
)
5088 var head
= $('<div />')
5089 .addClass('luci2-section-header')
5090 .append(this._render_teaser(sid
, index
))
5091 .append($('<div />')
5092 .addClass('btn-group')
5093 .append(this._render_sort(sid
, index
))
5094 .append(this._render_remove(sid
, index
)));
5096 if (this.options
.collabsible
)
5098 head
.attr('data-toggle', 'collapse')
5099 .attr('data-parent', this.id('sectiongroup'))
5100 .attr('data-target', '#' + this.id('panel', sid
))
5101 .on('click', { self
: this }, this._ev_panel_open
);
5107 _render_section_body: function(sid
, index
)
5109 var body
= $('<div />')
5110 .attr('id', this.id('panel', sid
))
5111 .attr('data-luci2-panel-index', index
)
5112 .attr('data-luci2-sid', sid
);
5114 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
5116 body
.addClass('panel-collapse collapse');
5118 if (index
== this.active_panel
)
5119 body
.addClass('in');
5122 var tab_heads
= $('<ul />')
5123 .addClass('nav nav-tabs');
5125 var tab_bodies
= $('<div />')
5126 .addClass('form-horizontal tab-content')
5129 for (var j
= 0; j
< this.tabs
.length
; j
++)
5131 tab_heads
.append(this._render_tab_head(sid
, index
, j
));
5132 tab_bodies
.append(this._render_tab_body(sid
, index
, j
));
5135 body
.append(tab_bodies
);
5137 if (this.tabs
.length
<= 1)
5143 _render_body: function(condensed
)
5145 var s
= this.sections();
5147 if (this.active_panel
< 0)
5148 this.active_panel
+= s
.length
;
5149 else if (this.active_panel
>= s
.length
)
5150 this.active_panel
= s
.length
- 1;
5152 var body
= $('<ul />')
5153 .addClass('list-group');
5155 if (this.options
.collabsible
)
5157 body
.attr('id', this.id('sectiongroup'))
5158 .on('show.bs.collapse', { self
: this }, this._ev_panel_collapse
);
5163 body
.append($('<li />')
5164 .addClass('list-group-item text-muted')
5165 .text(this.label('placeholder') || _luci2
.tr('There are no entries defined yet.')))
5168 for (var i
= 0; i
< s
.length
; i
++)
5170 var sid
= s
[i
]['.name'];
5171 var inst
= this.instance
[sid
] = { tabs
: [ ] };
5173 body
.append($('<li />')
5174 .addClass('list-group-item')
5175 .append(this._render_section_head(sid
, i
))
5176 .append(this._render_section_body(sid
, i
)));
5182 render: function(condensed
)
5184 this.instance
= { };
5186 var panel
= $('<div />')
5187 .addClass('panel panel-default')
5188 .append(this._render_head(condensed
))
5189 .append(this._render_body(condensed
));
5191 if (this.options
.addremove
)
5192 panel
.append($('<div />')
5193 .addClass('panel-footer')
5194 .append(this._render_add()));
5201 var s
= this.sections();
5203 for (var i
= 0; i
< s
.length
; i
++)
5205 var sid
= s
[i
]['.name'];
5207 this.validate_section(sid
);
5209 if (i
!= this.active_panel
)
5210 $('#' + this.id('teaser', sid
)).children('span:last')
5211 .append(this.teaser(sid
));
5213 $('#' + this.id('teaser', sid
))
5219 this.cbi
.TableSection
= this.cbi
.TypedSection
.extend({
5220 _render_table_head: function()
5222 var thead
= $('<thead />')
5224 .addClass('cbi-section-table-titles'));
5226 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
5227 thead
.children().append($('<th />')
5228 .addClass('cbi-section-table-cell')
5229 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
5230 .append(this.tabs
[0].fields
[j
].label('caption')));
5232 if (this.options
.addremove
!== false || this.options
.sortable
)
5233 thead
.children().append($('<th />')
5234 .addClass('cbi-section-table-cell')
5240 _render_table_row: function(sid
, index
)
5242 var row
= $('<tr />')
5243 .attr('data-luci2-sid', sid
);
5245 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
5247 row
.append($('<td />')
5248 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
5249 .append(this.tabs
[0].fields
[j
].render(sid
, true)));
5252 if (this.options
.addremove
!== false || this.options
.sortable
)
5254 row
.append($('<td />')
5255 .addClass('text-right')
5256 .append($('<div />')
5257 .addClass('btn-group')
5258 .append(this._render_sort(sid
, index
))
5259 .append(this._render_remove(sid
, index
))));
5265 _render_table_body: function()
5267 var s
= this.sections();
5269 var tbody
= $('<tbody />');
5273 var cols
= this.tabs
[0].fields
.length
;
5275 if (this.options
.addremove
!== false || this.options
.sortable
)
5278 tbody
.append($('<tr />')
5280 .addClass('text-muted')
5281 .attr('colspan', cols
)
5282 .text(this.label('placeholder') || _luci2
.tr('There are no entries defined yet.'))));
5285 for (var i
= 0; i
< s
.length
; i
++)
5287 var sid
= s
[i
]['.name'];
5288 var inst
= this.instance
[sid
] = { tabs
: [ ] };
5290 tbody
.append(this._render_table_row(sid
, i
));
5296 _render_body: function(condensed
)
5298 return $('<table />')
5299 .addClass('table table-condensed table-hover')
5300 .append(this._render_table_head())
5301 .append(this._render_table_body());
5305 this.cbi
.NamedSection
= this.cbi
.TypedSection
.extend({
5306 sections: function(cb
)
5309 var pkg
= this.map
.uci
.values
[this.map
.uci_package
];
5312 if (pkg
[s
]['.name'] == this.uci_type
)
5318 if (typeof(cb
) == 'function' && sa
.length
> 0)
5319 cb
.apply(this, [ sa
[0] ]);
5325 this.cbi
.DummySection
= this.cbi
.TypedSection
.extend({
5326 sections: function(cb
)
5328 if (typeof(cb
) == 'function')
5329 cb
.apply(this, [ { '.name': this.uci_type
} ]);
5331 return [ { '.name': this.uci_type
} ];
5335 this.cbi
.Map
= this.ui
.AbstractWidget
.extend({
5336 init: function(uci_package
, options
)
5340 this.uci_package
= uci_package
;
5341 this.sections
= [ ];
5342 this.options
= _luci2
.defaults(options
, {
5343 save: function() { },
5344 prepare: function() {
5345 return _luci2
.uci
.writable(function(writable
) {
5346 self
.options
.readonly
= !writable
;
5352 _load_cb: function(packages
)
5354 for (var i
= 0; i
< packages
.length
; i
++)
5356 this.uci
.values
[packages
[i
]['.package']] = packages
[i
];
5357 delete packages
[i
]['.package'];
5360 var deferreds
= [ _luci2
.deferrable(this.options
.prepare()) ];
5362 for (var i
= 0; i
< this.sections
.length
; i
++)
5364 for (var f
in this.sections
[i
].fields
)
5366 if (typeof(this.sections
[i
].fields
[f
].load
) != 'function')
5369 var s
= this.sections
[i
].sections();
5370 for (var j
= 0; j
< s
.length
; j
++)
5372 var rv
= this.sections
[i
].fields
[f
].load(s
[j
]['.name']);
5373 if (_luci2
.isDeferred(rv
))
5379 return $.when
.apply($, deferreds
);
5397 for (var i
= 0; i
< this.sections
.length
; i
++)
5398 this.sections
[i
].ucipackages(packages
);
5400 packages
[this.uci_package
] = true;
5404 for (var pkg
in packages
)
5405 _luci2
.uci
.get_all(pkg
);
5407 return _luci2
.rpc
.flush().then(function(packages
) {
5408 return self
._load_cb(packages
);
5412 _ev_tab: function(ev
)
5414 var self
= ev
.data
.self
;
5417 self
.active_tab
= parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
5420 _render_tab_head: function(tab_index
)
5422 var section
= this.sections
[tab_index
];
5423 var cur
= this.active_tab
|| 0;
5425 var tabh
= $('<li />')
5427 .attr('id', section
.id('sectiontab'))
5428 .attr('href', '#' + section
.id('section'))
5429 .attr('data-toggle', 'tab')
5430 .attr('data-luci2-tab-index', tab_index
)
5431 .text(section
.label('caption') + ' ')
5432 .append($('<span />')
5434 .on('shown.bs.tab', { self
: this }, this._ev_tab
));
5436 if (cur
== tab_index
)
5437 tabh
.addClass('active');
5442 _render_tab_body: function(tab_index
)
5444 var section
= this.sections
[tab_index
];
5445 var desc
= section
.label('description');
5446 var cur
= this.active_tab
|| 0;
5448 var tabb
= $('<div />')
5449 .addClass('tab-pane')
5450 .attr('id', section
.id('section'))
5451 .attr('data-luci2-tab-index', tab_index
);
5453 if (cur
== tab_index
)
5454 tabb
.addClass('active');
5457 tabb
.append($('<p />')
5460 var s
= section
.render(this.options
.tabbed
);
5462 if (this.options
.readonly
|| section
.options
.readonly
)
5463 s
.find('input, select, button, img.cbi-button').attr('disabled', true);
5470 _render_body: function()
5472 var tabs
= $('<ul />')
5473 .addClass('nav nav-tabs');
5475 var body
= $('<div />')
5478 for (var i
= 0; i
< this.sections
.length
; i
++)
5480 tabs
.append(this._render_tab_head(i
));
5481 body
.append(this._render_tab_body(i
));
5484 if (this.options
.tabbed
)
5485 body
.addClass('tab-content');
5494 var map
= $('<form />');
5496 if (typeof(this.options
.caption
) == 'string')
5497 map
.append($('<h2 />')
5498 .text(this.options
.caption
));
5500 if (typeof(this.options
.description
) == 'string')
5501 map
.append($('<p />')
5502 .text(this.options
.description
));
5504 map
.append(this._render_body());
5506 if (this.options
.pageaction
!== false)
5508 map
.append($('<div />')
5509 .addClass('panel panel-default panel-body text-right')
5510 .append($('<div />')
5511 .addClass('btn-group')
5512 .append(_luci2
.ui
.button(_luci2
.tr('Save & Apply'), 'primary')
5513 .click({ self
: this }, function(ev
) { }))
5514 .append(_luci2
.ui
.button(_luci2
.tr('Save'), 'default')
5515 .click({ self
: this }, function(ev
) { ev
.data
.self
.send(); }))
5516 .append(_luci2
.ui
.button(_luci2
.tr('Reset'), 'default')
5517 .click({ self
: this }, function(ev
) { ev
.data
.self
.insertInto(ev
.data
.self
.target
); }))));
5525 for (var i
= 0; i
< this.sections
.length
; i
++)
5526 this.sections
[i
].finish();
5533 this.target
.hide().empty().append(this.render());
5538 section: function(widget
, uci_type
, options
)
5540 var w
= widget
? new widget(uci_type
, options
) : null;
5542 if (!(w
instanceof _luci2
.cbi
.AbstractSection
))
5543 throw 'Widget must be an instance of AbstractSection';
5546 w
.index
= this.sections
.length
;
5548 this.sections
.push(w
);
5552 formvalue: function()
5556 for (var i
= 0; i
< this.sections
.length
; i
++)
5558 var sids
= this.sections
[i
].formvalue();
5559 for (var sid
in sids
)
5561 var s
= rv
[sid
] || (rv
[sid
] = { });
5562 $.extend(s
, sids
[sid
]);
5569 add: function(conf
, type
, name
)
5571 var c
= this.uci
.creates
;
5572 var s
= '.new.%d'.format(this.uci
.newid
++);
5581 '.anonymous': !name
,
5582 '.index': 1000 + this.uci
.newid
5588 remove: function(conf
, sid
)
5590 var n
= this.uci
.creates
;
5591 var c
= this.uci
.changes
;
5592 var d
= this.uci
.deletes
;
5594 /* requested deletion of a just created section */
5595 if (sid
.indexOf('.new.') == 0)
5598 delete n
[conf
][sid
];
5603 delete c
[conf
][sid
];
5608 d
[conf
][sid
] = true;
5612 ucisections: function(conf
, cb
)
5615 var pkg
= this.uci
.values
[conf
];
5616 var crt
= this.uci
.creates
[conf
];
5617 var del
= this.uci
.deletes
[conf
];
5623 if (!del
|| del
[s
] !== true)
5630 sa
.sort(function(a
, b
) {
5631 return a
['.index'] - b
['.index'];
5634 for (var i
= 0; i
< sa
.length
; i
++)
5635 sa
[i
]['.index'] = i
;
5637 if (typeof(cb
) == 'function')
5638 for (var i
= 0; i
< sa
.length
; i
++)
5639 cb
.apply(this, [ sa
[i
] ]);
5644 get: function(conf
, sid
, opt
)
5646 var v
= this.uci
.values
;
5647 var n
= this.uci
.creates
;
5648 var c
= this.uci
.changes
;
5649 var d
= this.uci
.deletes
;
5651 /* requested option in a just created section */
5652 if (sid
.indexOf('.new.') == 0)
5657 if (typeof(opt
) == 'undefined')
5658 return (n
[conf
][sid
] || { });
5660 return n
[conf
][sid
][opt
];
5663 /* requested an option value */
5664 if (typeof(opt
) != 'undefined')
5666 /* check whether option was deleted */
5667 if (d
[conf
] && d
[conf
][sid
])
5669 if (d
[conf
][sid
] === true)
5672 for (var i
= 0; i
< d
[conf
][sid
].length
; i
++)
5673 if (d
[conf
][sid
][i
] == opt
)
5677 /* check whether option was changed */
5678 if (c
[conf
] && c
[conf
][sid
] && typeof(c
[conf
][sid
][opt
]) != 'undefined')
5679 return c
[conf
][sid
][opt
];
5681 /* return base value */
5682 if (v
[conf
] && v
[conf
][sid
])
5683 return v
[conf
][sid
][opt
];
5688 /* requested an entire section */
5690 return (v
[conf
][sid
] || { });
5695 set: function(conf
, sid
, opt
, val
)
5697 var n
= this.uci
.creates
;
5698 var c
= this.uci
.changes
;
5699 var d
= this.uci
.deletes
;
5701 if (sid
.indexOf('.new.') == 0)
5703 if (n
[conf
] && n
[conf
][sid
])
5705 if (typeof(val
) != 'undefined')
5706 n
[conf
][sid
][opt
] = val
;
5708 delete n
[conf
][sid
][opt
];
5711 else if (typeof(val
) != 'undefined')
5719 c
[conf
][sid
][opt
] = val
;
5729 d
[conf
][sid
].push(opt
);
5733 validate: function()
5737 for (var i
= 0; i
< this.sections
.length
; i
++)
5739 if (!this.sections
[i
].validate())
5748 if (this.options
.readonly
)
5749 return _luci2
.deferrable();
5751 var deferreds
= [ _luci2
.deferrable(this.options
.save()) ];
5753 for (var i
= 0; i
< this.sections
.length
; i
++)
5755 if (this.sections
[i
].options
.readonly
)
5758 for (var f
in this.sections
[i
].fields
)
5760 if (typeof(this.sections
[i
].fields
[f
].save
) != 'function')
5763 var s
= this.sections
[i
].sections();
5764 for (var j
= 0; j
< s
.length
; j
++)
5766 var rv
= this.sections
[i
].fields
[f
].save(s
[j
]['.name']);
5767 if (_luci2
.isDeferred(rv
))
5773 return $.when
.apply($, deferreds
);
5776 _send_uci_reorder: function()
5778 if (!this.uci
.reorder
)
5779 return _luci2
.deferrable();
5784 gather all created and existing sections, sort them according
5785 to their index value and issue an uci order call
5787 for (var c
in this.uci
.values
)
5791 if (this.uci
.creates
&& this.uci
.creates
[c
])
5792 for (var s
in this.uci
.creates
[c
])
5793 o
.push(this.uci
.creates
[c
][s
]);
5795 for (var s
in this.uci
.values
[c
])
5796 o
.push(this.uci
.values
[c
][s
]);
5800 o
.sort(function(a
, b
) {
5801 return (a
['.index'] - b
['.index']);
5806 for (var i
= 0; i
< o
.length
; i
++)
5807 sids
.push(o
[i
]['.name']);
5809 _luci2
.uci
.order(c
, sids
);
5813 return _luci2
.rpc
.flush();
5816 _send_uci: function()
5823 if (this.uci
.creates
)
5824 for (var c
in this.uci
.creates
)
5825 for (var s
in this.uci
.creates
[c
])
5832 for (var k
in this.uci
.creates
[c
][s
])
5835 r
.type
= this.uci
.creates
[c
][s
][k
];
5836 else if (k
== '.create')
5837 r
.name
= this.uci
.creates
[c
][s
][k
];
5838 else if (k
.charAt(0) != '.')
5839 r
.values
[k
] = this.uci
.creates
[c
][s
][k
];
5842 snew
.push(this.uci
.creates
[c
][s
]);
5844 _luci2
.uci
.add(r
.config
, r
.type
, r
.name
, r
.values
);
5847 if (this.uci
.changes
)
5848 for (var c
in this.uci
.changes
)
5849 for (var s
in this.uci
.changes
[c
])
5850 _luci2
.uci
.set(c
, s
, this.uci
.changes
[c
][s
]);
5852 if (this.uci
.deletes
)
5853 for (var c
in this.uci
.deletes
)
5854 for (var s
in this.uci
.deletes
[c
])
5856 var o
= this.uci
.deletes
[c
][s
];
5857 _luci2
.uci
['delete'](c
, s
, (o
=== true) ? undefined : o
);
5860 return _luci2
.rpc
.flush().then(function(responses
) {
5862 array "snew" holds references to the created uci sections,
5863 use it to assign the returned names of the new sections
5865 for (var i
= 0; i
< snew
.length
; i
++)
5866 snew
[i
]['.name'] = responses
[i
];
5868 return self
._send_uci_reorder();
5874 if (!this.validate())
5875 return _luci2
.deferrable();
5879 _luci2
.ui
.saveScrollTop();
5880 _luci2
.ui
.loading(true);
5882 return this.save().then(function() {
5883 return self
._send_uci();
5884 }).then(function() {
5885 return _luci2
.ui
.updateChanges();
5886 }).then(function() {
5888 }).then(function() {
5892 _luci2
.ui
.loading(false);
5893 _luci2
.ui
.restoreScrollTop();
5897 insertInto: function(id
)
5900 self
.target
= $(id
);
5902 _luci2
.ui
.loading(true);
5905 return self
.load().then(function() {
5906 self
.target
.empty().append(self
.render());
5910 _luci2
.ui
.loading(false);