b&&(h=b.toFixed(e),b=parseFloat(h));else{g=(g.split(od)[1]||
+"").length;x(e)&&(e=Math.min(Math.max(a.minFrac,g),a.maxFrac));b=+(Math.round(+(b.toString()+"e"+e)).toString()+"e"+-e);var g=(""+b).split(od),k=g[0],g=g[1]||"",p=0,q=a.lgSize,u=a.gSize;if(k.length>=q+u)for(p=k.length-q,n=0;nb&&(d="-",b=-b);for(b=""+b;b.length-c)e+=c;0===e&&-12==c&&(e=12);return Ib(e,a,d)}}function Jb(b,a){return function(c,d){var e=c["get"+b](),f=ub(a?"SHORT"+b:b);return d[f][e]}}function pd(b){var a=(new Date(b,0,1)).getDay();return new Date(b,0,(4>=a?5:12)-a)}function qd(b){return function(a){var c=pd(a.getFullYear());a=+new Date(a.getFullYear(),a.getMonth(),a.getDate()+
+(4-a.getDay()))-+c;a=1+Math.round(a/6048E5);return Ib(a,b)}}function ic(b,a){return 0>=b.getFullYear()?a.ERAS[0]:a.ERAS[1]}function kd(b){function a(a){var b;if(b=a.match(c)){a=new Date(0);var f=0,g=0,h=b[8]?a.setUTCFullYear:a.setFullYear,l=b[8]?a.setUTCHours:a.setHours;b[9]&&(f=aa(b[9]+b[10]),g=aa(b[9]+b[11]));h.call(a,aa(b[1]),aa(b[2])-1,aa(b[3]));f=aa(b[4]||0)-f;g=aa(b[5]||0)-g;h=aa(b[6]||0);b=Math.round(1E3*parseFloat("0."+(b[7]||0)));l.call(a,f,g,h,b)}return a}var c=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
+return function(c,e,f){var g="",h=[],l,k;e=e||"mediumDate";e=b.DATETIME_FORMATS[e]||e;C(c)&&(c=Kf.test(c)?aa(c):a(c));Y(c)&&(c=new Date(c));if(!ga(c))return c;for(;e;)(k=Lf.exec(e))?(h=Ya(h,k,1),e=h.pop()):(h.push(e),e=null);f&&"UTC"===f&&(c=new Date(c.getTime()),c.setMinutes(c.getMinutes()+c.getTimezoneOffset()));r(h,function(a){l=Mf[a];g+=l?l(c,b.DATETIME_FORMATS):a.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return g}}function Ff(){return function(b,a){x(a)&&(a=2);return $a(b,a)}}function Gf(){return function(b,
+a){Y(b)&&(b=b.toString());return H(b)||C(b)?(a=Infinity===Math.abs(Number(a))?Number(a):aa(a))?0b||37<=b&&40>=b||n(a,this,this.value)});if(e.hasEvent("paste"))a.on("paste cut",n)}a.on("change",l);d.$render=function(){a.val(d.$isEmpty(d.$viewValue)?"":d.$viewValue)}}function Mb(b,a){return function(c,d){var e,f;if(ga(c))return c;if(C(c)){'"'==c.charAt(0)&&'"'==c.charAt(c.length-1)&&(c=c.substring(1,c.length-1));if(Nf.test(c))return new Date(c);b.lastIndex=
+0;if(e=b.exec(c))return e.shift(),f=d?{yyyy:d.getFullYear(),MM:d.getMonth()+1,dd:d.getDate(),HH:d.getHours(),mm:d.getMinutes(),ss:d.getSeconds(),sss:d.getMilliseconds()/1E3}:{yyyy:1970,MM:1,dd:1,HH:0,mm:0,ss:0,sss:0},r(e,function(b,c){c=r};
+g.$observe("min",function(a){r=q(a);h.$validate()})}if(y(g.max)||g.ngMax){var v;h.$validators.max=function(a){return!p(a)||x(v)||c(a)<=v};g.$observe("max",function(a){v=q(a);h.$validate()})}}}function td(b,a,c,d){(d.$$hasNativeValidators=J(a[0].validity))&&d.$parsers.push(function(b){var c=a.prop("validity")||{};return c.badInput&&!c.typeMismatch?t:b})}function ud(b,a,c,d,e){if(y(d)){b=b(d);if(!b.constant)throw R("ngModel")("constexpr",c,d);return b(a)}return e}function kc(b,a){b="ngClass"+b;return["$animate",
+function(c){function d(a,b){var c=[],d=0;a:for(;d(?:<\/\1>|)$/,Sb=/<|?\w+;/,ef=/<([\w:]+)/,ff=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja={option:[1,'"],thead:[1,""],col:[2,""],tr:[2,""],td:[3,""],_default:[0,"",""]};ja.optgroup=ja.option;ja.tbody=ja.tfoot=ja.colgroup=ja.caption=ja.thead;ja.th=ja.td;var Ka=T.prototype={ready:function(b){function a(){c||(c=!0,b())}var c=!1;"complete"===W.readyState?setTimeout(a):(this.on("DOMContentLoaded",a),T(Q).on("load",a))},toString:function(){var b=[];r(this,function(a){b.push(""+a)});return"["+b.join(", ")+"]"},eq:function(b){return 0<=
+b?A(this[b]):A(this[this.length+b])},length:0,push:Pf,sort:[].sort,splice:[].splice},Eb={};r("multiple selected checked disabled readOnly required open".split(" "),function(b){Eb[z(b)]=b});var Oc={};r("input select option textarea button form details".split(" "),function(b){Oc[b]=!0});var Pc={ngMinlength:"minlength",ngMaxlength:"maxlength",ngMin:"min",ngMax:"max",ngPattern:"pattern"};r({data:Vb,removeData:xb},function(b,a){T[a]=b});r({data:Vb,inheritedData:Db,scope:function(b){return A.data(b,"$scope")||
+Db(b.parentNode||b,["$isolateScope","$scope"])},isolateScope:function(b){return A.data(b,"$isolateScope")||A.data(b,"$isolateScopeNoTemplate")},controller:Kc,injector:function(b){return Db(b,"$injector")},removeAttr:function(b,a){b.removeAttribute(a)},hasClass:Ab,css:function(b,a,c){a=db(a);if(y(c))b.style[a]=c;else return b.style[a]},attr:function(b,a,c){var d=z(a);if(Eb[d])if(y(c))c?(b[a]=!0,b.setAttribute(a,d)):(b[a]=!1,b.removeAttribute(d));else return b[a]||(b.attributes.getNamedItem(a)||E).specified?
+d:t;else if(y(c))b.setAttribute(a,c);else if(b.getAttribute)return b=b.getAttribute(a,2),null===b?t:b},prop:function(b,a,c){if(y(c))b[a]=c;else return b[a]},text:function(){function b(a,b){if(x(b)){var d=a.nodeType;return d===qa||d===pb?a.textContent:""}a.textContent=b}b.$dv="";return b}(),val:function(b,a){if(x(a)){if(b.multiple&&"select"===va(b)){var c=[];r(b.options,function(a){a.selected&&c.push(a.value||a.text)});return 0===c.length?null:c}return b.value}b.value=a},html:function(b,a){if(x(a))return b.innerHTML;
+wb(b,!0);b.innerHTML=a},empty:Lc},function(b,a){T.prototype[a]=function(a,d){var e,f,g=this.length;if(b!==Lc&&(2==b.length&&b!==Ab&&b!==Kc?a:d)===t){if(J(a)){for(e=0;e":function(a,c,d,e){return d(a,c)>e(a,c)},"<=":function(a,c,d,e){return d(a,c)<=e(a,c)},">=":function(a,c,d,e){return d(a,c)>=e(a,c)},"&&":function(a,c,d,e){return d(a,c)&&e(a,c)},
+"||":function(a,c,d,e){return d(a,c)||e(a,c)},"!":function(a,c,d){return!d(a,c)},"=":!0,"|":!0}),Zf={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'},hc=function(a){this.options=a};hc.prototype={constructor:hc,lex:function(a){this.text=a;this.index=0;for(this.tokens=[];this.index=a&&"string"===typeof a},isWhitespace:function(a){return" "===a||"\r"===a||"\t"===a||"\n"===a||"\v"===a||"\u00a0"===a},isIdent:function(a){return"a"<=a&&"z">=a||"A"<=a&&"Z">=a||"_"===a||"$"===a},isExpOperator:function(a){return"-"===a||"+"===a||this.isNumber(a)},throwError:function(a,c,d){d=d||this.index;c=y(c)?"s "+c+"-"+this.index+" ["+this.text.substring(c,d)+"]":" "+d;throw na("lexerr",a,c,this.text);},readNumber:function(){for(var a="",c=this.index;this.index<
+this.text.length;){var d=z(this.text.charAt(this.index));if("."==d||this.isNumber(d))a+=d;else{var e=this.peek();if("e"==d&&this.isExpOperator(e))a+=d;else if(this.isExpOperator(d)&&e&&this.isNumber(e)&&"e"==a.charAt(a.length-1))a+=d;else if(!this.isExpOperator(d)||e&&this.isNumber(e)||"e"!=a.charAt(a.length-1))break;else this.throwError("Invalid exponent")}this.index++}this.tokens.push({index:c,text:a,constant:!0,value:Number(a)})},readIdent:function(){for(var a=this.index;this.indexa){a=this.tokens[a];var g=a.text;if(g===c||g===d||g===e||g===
+f||!(c||d||e||f))return a}return!1},expect:function(a,c,d,e){return(a=this.peek(a,c,d,e))?(this.tokens.shift(),a):!1},consume:function(a){if(0===this.tokens.length)throw na("ueoe",this.text);var c=this.expect(a);c||this.throwError("is unexpected, expecting ["+a+"]",this.peek());return c},unaryFn:function(a,c){var d=nb[a];return w(function(a,f){return d(a,f,c)},{constant:c.constant,inputs:[c]})},binaryFn:function(a,c,d,e){var f=nb[c];return w(function(c,e){return f(c,e,a,d)},{constant:a.constant&&
+d.constant,inputs:!e&&[a,d]})},identifier:function(){for(var a=this.consume().text;this.peek(".")&&this.peekAhead(1).identifier&&!this.peekAhead(2,"(");)a+=this.consume().text+this.consume().text;return zf(a,this.options,this.text)},constant:function(){var a=this.consume().value;return w(function(){return a},{constant:!0,literal:!0})},statements:function(){for(var a=[];;)if(0","<=",">=");)a=this.binaryFn(a,c.text,
+this.additive());return a},additive:function(){for(var a=this.multiplicative(),c;c=this.expect("+","-");)a=this.binaryFn(a,c.text,this.multiplicative());return a},multiplicative:function(){for(var a=this.unary(),c;c=this.expect("*","/","%");)a=this.binaryFn(a,c.text,this.unary());return a},unary:function(){var a;return this.expect("+")?this.primary():(a=this.expect("-"))?this.binaryFn(ib.ZERO,a.text,this.unary()):(a=this.expect("!"))?this.unaryFn(a.text,this.unary()):this.primary()},fieldAccess:function(a){var c=
+this.identifier();return w(function(d,e,f){d=f||a(d,e);return null==d?t:c(d)},{assign:function(d,e,f){var g=a(d,f);g||a.assign(d,g={},f);return c.assign(g,e)}})},objectIndex:function(a){var c=this.text,d=this.expression();this.consume("]");return w(function(e,f){var g=a(e,f),h=d(e,f);ua(h,c);return g?oa(g[h],c):t},{assign:function(e,f,g){var h=ua(d(e,g),c),l=oa(a(e,g),c);l||a.assign(e,l={},g);return l[h]=f}})},functionCall:function(a,c){var d=[];if(")"!==this.peekToken().text){do d.push(this.expression());
+while(this.expect(","))}this.consume(")");var e=this.text,f=d.length?[]:null;return function(g,h){var l=c?c(g,h):y(c)?t:g,k=a(g,h,l)||E;if(f)for(var n=d.length;n--;)f[n]=oa(d[n](g,h),e);oa(l,e);if(k){if(k.constructor===k)throw na("isecfn",e);if(k===Wf||k===Xf||k===Yf)throw na("isecff",e);}l=k.apply?k.apply(l,f):k(f[0],f[1],f[2],f[3],f[4]);f&&(f.length=0);return oa(l,e)}},arrayDeclaration:function(){var a=[];if("]"!==this.peekToken().text){do{if(this.peek("]"))break;a.push(this.expression())}while(this.expect(","))
+}this.consume("]");return w(function(c,d){for(var e=[],f=0,g=a.length;fa.getHours()?c.AMPMS[0]:c.AMPMS[1]},Z:function(a){a=-1*a.getTimezoneOffset();return a=(0<=a?"+":"")+(Ib(Math[0=a.getFullYear()?c.ERANAMES[0]:c.ERANAMES[1]}},Lf=/((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
+Kf=/^\-?\d+$/;kd.$inject=["$locale"];var Hf=ea(z),If=ea(ub);md.$inject=["$parse"];var Td=ea({restrict:"E",compile:function(a,c){if(!c.href&&!c.xlinkHref&&!c.name)return function(a,c){if("a"===c[0].nodeName.toLowerCase()){var f="[object SVGAnimatedString]"===Ca.call(c.prop("href"))?"xlink:href":"href";c.on("click",function(a){c.attr(f)||a.preventDefault()})}}}}),vb={};r(Eb,function(a,c){if("multiple"!=a){var d=xa("ng-"+c);vb[d]=function(){return{restrict:"A",priority:100,link:function(a,f,g){a.$watch(g[d],
+function(a){g.$set(c,!!a)})}}}}});r(Pc,function(a,c){vb[c]=function(){return{priority:100,link:function(a,e,f){if("ngPattern"===c&&"/"==f.ngPattern.charAt(0)&&(e=f.ngPattern.match(Of))){f.$set("ngPattern",new RegExp(e[1],e[2]));return}a.$watch(f[c],function(a){f.$set(c,a)})}}}});r(["src","srcset","href"],function(a){var c=xa("ng-"+a);vb[c]=function(){return{priority:99,link:function(d,e,f){var g=a,h=a;"href"===a&&"[object SVGAnimatedString]"===Ca.call(e.prop("href"))&&(h="xlinkHref",f.$attr[h]="xlink:href",
+g=null);f.$observe(c,function(c){c?(f.$set(h,c),Qa&&g&&e.prop(g,f[h])):"href"===a&&f.$set(h,null)})}}}});var Kb={$addControl:E,$$renameControl:function(a,c){a.$name=c},$removeControl:E,$setValidity:E,$setDirty:E,$setPristine:E,$setSubmitted:E};rd.$inject=["$element","$attrs","$scope","$animate","$interpolate"];var yd=function(a){return["$timeout",function(c){return{name:"form",restrict:a?"EAC":"E",controller:rd,compile:function(d,e){d.addClass(Ra).addClass(lb);var f=e.name?"name":a&&e.ngForm?"ngForm":
+!1;return{pre:function(a,d,e,k){if(!("action"in e)){var n=function(c){a.$apply(function(){k.$commitViewValue();k.$setSubmitted()});c.preventDefault()};d[0].addEventListener("submit",n,!1);d.on("$destroy",function(){c(function(){d[0].removeEventListener("submit",n,!1)},0,!1)})}var p=k.$$parentForm;f&&(hb(a,null,k.$name,k,k.$name),e.$observe(f,function(c){k.$name!==c&&(hb(a,null,k.$name,t,k.$name),p.$$renameControl(k,c),hb(a,null,k.$name,k,k.$name))}));d.on("$destroy",function(){p.$removeControl(k);
+f&&hb(a,null,e[f],t,k.$name);w(k,Kb)})}}}}}]},Ud=yd(),ge=yd(!0),Nf=/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/,$f=/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,ag=/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i,bg=/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/,zd=/^(\d{4})-(\d{2})-(\d{2})$/,Ad=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,lc=/^(\d{4})-W(\d\d)$/,Bd=/^(\d{4})-(\d\d)$/,
+Cd=/^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,Dd={text:function(a,c,d,e,f,g){jb(a,c,d,e,f,g);jc(e)},date:kb("date",zd,Mb(zd,["yyyy","MM","dd"]),"yyyy-MM-dd"),"datetime-local":kb("datetimelocal",Ad,Mb(Ad,"yyyy MM dd HH mm ss sss".split(" ")),"yyyy-MM-ddTHH:mm:ss.sss"),time:kb("time",Cd,Mb(Cd,["HH","mm","ss","sss"]),"HH:mm:ss.sss"),week:kb("week",lc,function(a,c){if(ga(a))return a;if(C(a)){lc.lastIndex=0;var d=lc.exec(a);if(d){var e=+d[1],f=+d[2],g=d=0,h=0,l=0,k=pd(e),f=7*(f-1);c&&(d=c.getHours(),g=
+c.getMinutes(),h=c.getSeconds(),l=c.getMilliseconds());return new Date(e,0,k.getDate()+f,d,g,h,l)}}return NaN},"yyyy-Www"),month:kb("month",Bd,Mb(Bd,["yyyy","MM"]),"yyyy-MM"),number:function(a,c,d,e,f,g){td(a,c,d,e);jb(a,c,d,e,f,g);e.$$parserName="number";e.$parsers.push(function(a){return e.$isEmpty(a)?null:bg.test(a)?parseFloat(a):t});e.$formatters.push(function(a){if(!e.$isEmpty(a)){if(!Y(a))throw Nb("numfmt",a);a=a.toString()}return a});if(y(d.min)||d.ngMin){var h;e.$validators.min=function(a){return e.$isEmpty(a)||
+x(h)||a>=h};d.$observe("min",function(a){y(a)&&!Y(a)&&(a=parseFloat(a,10));h=Y(a)&&!isNaN(a)?a:t;e.$validate()})}if(y(d.max)||d.ngMax){var l;e.$validators.max=function(a){return e.$isEmpty(a)||x(l)||a<=l};d.$observe("max",function(a){y(a)&&!Y(a)&&(a=parseFloat(a,10));l=Y(a)&&!isNaN(a)?a:t;e.$validate()})}},url:function(a,c,d,e,f,g){jb(a,c,d,e,f,g);jc(e);e.$$parserName="url";e.$validators.url=function(a,c){var d=a||c;return e.$isEmpty(d)||$f.test(d)}},email:function(a,c,d,e,f,g){jb(a,c,d,e,f,g);jc(e);
+e.$$parserName="email";e.$validators.email=function(a,c){var d=a||c;return e.$isEmpty(d)||ag.test(d)}},radio:function(a,c,d,e){x(d.name)&&c.attr("name",++ob);c.on("click",function(a){c[0].checked&&e.$setViewValue(d.value,a&&a.type)});e.$render=function(){c[0].checked=d.value==e.$viewValue};d.$observe("value",e.$render)},checkbox:function(a,c,d,e,f,g,h,l){var k=ud(l,a,"ngTrueValue",d.ngTrueValue,!0),n=ud(l,a,"ngFalseValue",d.ngFalseValue,!1);c.on("click",function(a){e.$setViewValue(c[0].checked,a&&
+a.type)});e.$render=function(){c[0].checked=e.$viewValue};e.$isEmpty=function(a){return!1===a};e.$formatters.push(function(a){return ha(a,k)});e.$parsers.push(function(a){return a?k:n})},hidden:E,button:E,submit:E,reset:E,file:E},zc=["$browser","$sniffer","$filter","$parse",function(a,c,d,e){return{restrict:"E",require:["?ngModel"],link:{pre:function(f,g,h,l){l[0]&&(Dd[z(h.type)]||Dd.text)(f,g,h,l[0],c,a,d,e)}}}}],cg=/^(true|false|\d+)$/,ye=function(){return{restrict:"A",priority:100,compile:function(a,
+c){return cg.test(c.ngValue)?function(a,c,f){f.$set("value",a.$eval(f.ngValue))}:function(a,c,f){a.$watch(f.ngValue,function(a){f.$set("value",a)})}}}},Zd=["$compile",function(a){return{restrict:"AC",compile:function(c){a.$$addBindingClass(c);return function(c,e,f){a.$$addBindingInfo(e,f.ngBind);e=e[0];c.$watch(f.ngBind,function(a){e.textContent=a===t?"":a})}}}}],ae=["$interpolate","$compile",function(a,c){return{compile:function(d){c.$$addBindingClass(d);return function(d,f,g){d=a(f.attr(g.$attr.ngBindTemplate));
+c.$$addBindingInfo(f,d.expressions);f=f[0];g.$observe("ngBindTemplate",function(a){f.textContent=a===t?"":a})}}}}],$d=["$sce","$parse","$compile",function(a,c,d){return{restrict:"A",compile:function(e,f){var g=c(f.ngBindHtml),h=c(f.ngBindHtml,function(a){return(a||"").toString()});d.$$addBindingClass(e);return function(c,e,f){d.$$addBindingInfo(e,f.ngBindHtml);c.$watch(h,function(){e.html(a.getTrustedHtml(g(c))||"")})}}}}],xe=ea({restrict:"A",require:"ngModel",link:function(a,c,d,e){e.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),
+be=kc("",!0),de=kc("Odd",0),ce=kc("Even",1),ee=Ia({compile:function(a,c){c.$set("ngCloak",t);a.removeClass("ng-cloak")}}),fe=[function(){return{restrict:"A",scope:!0,controller:"@",priority:500}}],Ec={},dg={blur:!0,focus:!0};r("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "),function(a){var c=xa("ng-"+a);Ec[c]=["$parse","$rootScope",function(d,e){return{restrict:"A",compile:function(f,g){var h=
+d(g[c],null,!0);return function(c,d){d.on(a,function(d){var f=function(){h(c,{$event:d})};dg[a]&&e.$$phase?c.$evalAsync(f):c.$apply(f)})}}}}]});var ie=["$animate",function(a){return{multiElement:!0,transclude:"element",priority:600,terminal:!0,restrict:"A",$$tlb:!0,link:function(c,d,e,f,g){var h,l,k;c.$watch(e.ngIf,function(c){c?l||g(function(c,f){l=f;c[c.length++]=W.createComment(" end ngIf: "+e.ngIf+" ");h={clone:c};a.enter(c,d.parent(),d)}):(k&&(k.remove(),k=null),l&&(l.$destroy(),l=null),h&&(k=
+tb(h.clone),a.leave(k).then(function(){k=null}),h=null))})}}}],je=["$templateRequest","$anchorScroll","$animate","$sce",function(a,c,d,e){return{restrict:"ECA",priority:400,terminal:!0,transclude:"element",controller:ca.noop,compile:function(f,g){var h=g.ngInclude||g.src,l=g.onload||"",k=g.autoscroll;return function(f,g,q,r,s){var t=0,v,m,F,w=function(){m&&(m.remove(),m=null);v&&(v.$destroy(),v=null);F&&(d.leave(F).then(function(){m=null}),m=F,F=null)};f.$watch(e.parseAsResourceUrl(h),function(e){var h=
+function(){!y(k)||k&&!f.$eval(k)||c()},m=++t;e?(a(e,!0).then(function(a){if(m===t){var c=f.$new();r.template=a;a=s(c,function(a){w();d.enter(a,null,g).then(h)});v=c;F=a;v.$emit("$includeContentLoaded",e);f.$eval(l)}},function(){m===t&&(w(),f.$emit("$includeContentError",e))}),f.$emit("$includeContentRequested",e)):(w(),r.template=null)})}}}}],Ae=["$compile",function(a){return{restrict:"ECA",priority:-400,require:"ngInclude",link:function(c,d,e,f){/SVG/.test(d[0].toString())?(d.empty(),a(Hc(f.template,
+W).childNodes)(c,function(a){d.append(a)},{futureParentElement:d})):(d.html(f.template),a(d.contents())(c))}}}],ke=Ia({priority:450,compile:function(){return{pre:function(a,c,d){a.$eval(d.ngInit)}}}}),we=function(){return{restrict:"A",priority:100,require:"ngModel",link:function(a,c,d,e){var f=c.attr(d.$attr.ngList)||", ",g="false"!==d.ngTrim,h=g?N(f):f;e.$parsers.push(function(a){if(!x(a)){var c=[];a&&r(a.split(h),function(a){a&&c.push(g?N(a):a)});return c}});e.$formatters.push(function(a){return H(a)?
+a.join(f):t});e.$isEmpty=function(a){return!a||!a.length}}}},lb="ng-valid",vd="ng-invalid",Ra="ng-pristine",Lb="ng-dirty",xd="ng-pending",Nb=new R("ngModel"),eg=["$scope","$exceptionHandler","$attrs","$element","$parse","$animate","$timeout","$rootScope","$q","$interpolate",function(a,c,d,e,f,g,h,l,k,n){this.$modelValue=this.$viewValue=Number.NaN;this.$$rawModelValue=t;this.$validators={};this.$asyncValidators={};this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$untouched=!0;
+this.$touched=!1;this.$pristine=!0;this.$dirty=!1;this.$valid=!0;this.$invalid=!1;this.$error={};this.$$success={};this.$pending=t;this.$name=n(d.name||"",!1)(a);var p=f(d.ngModel),q=p.assign,u=p,s=q,M=null,v,m=this;this.$$setOptions=function(a){if((m.$options=a)&&a.getterSetter){var c=f(d.ngModel+"()"),g=f(d.ngModel+"($$$p)");u=function(a){var d=p(a);G(d)&&(d=c(a));return d};s=function(a,c){G(p(a))?g(a,{$$$p:m.$modelValue}):q(a,m.$modelValue)}}else if(!p.assign)throw Nb("nonassign",d.ngModel,wa(e));
+};this.$render=E;this.$isEmpty=function(a){return x(a)||""===a||null===a||a!==a};var F=e.inheritedData("$formController")||Kb,w=0;sd({ctrl:this,$element:e,set:function(a,c){a[c]=!0},unset:function(a,c){delete a[c]},parentForm:F,$animate:g});this.$setPristine=function(){m.$dirty=!1;m.$pristine=!0;g.removeClass(e,Lb);g.addClass(e,Ra)};this.$setDirty=function(){m.$dirty=!0;m.$pristine=!1;g.removeClass(e,Ra);g.addClass(e,Lb);F.$setDirty()};this.$setUntouched=function(){m.$touched=!1;m.$untouched=!0;g.setClass(e,
+"ng-untouched","ng-touched")};this.$setTouched=function(){m.$touched=!0;m.$untouched=!1;g.setClass(e,"ng-touched","ng-untouched")};this.$rollbackViewValue=function(){h.cancel(M);m.$viewValue=m.$$lastCommittedViewValue;m.$render()};this.$validate=function(){if(!Y(m.$modelValue)||!isNaN(m.$modelValue)){var a=m.$$rawModelValue,c=m.$valid,d=m.$modelValue,e=m.$options&&m.$options.allowInvalid;m.$$runValidators(a,m.$$lastCommittedViewValue,function(f){e||c===f||(m.$modelValue=f?a:t,m.$modelValue!==d&&m.$$writeModelToScope())})}};
+this.$$runValidators=function(a,c,d){function e(){var d=!0;r(m.$validators,function(e,f){var h=e(a,c);d=d&&h;g(f,h)});return d?!0:(r(m.$asyncValidators,function(a,c){g(c,null)}),!1)}function f(){var d=[],e=!0;r(m.$asyncValidators,function(f,h){var k=f(a,c);if(!k||!G(k.then))throw Nb("$asyncValidators",k);g(h,t);d.push(k.then(function(){g(h,!0)},function(a){e=!1;g(h,!1)}))});d.length?k.all(d).then(function(){h(e)},E):h(!0)}function g(a,c){l===w&&m.$setValidity(a,c)}function h(a){l===w&&d(a)}w++;var l=
+w;(function(){var a=m.$$parserName||"parse";if(v===t)g(a,null);else return v||(r(m.$validators,function(a,c){g(c,null)}),r(m.$asyncValidators,function(a,c){g(c,null)})),g(a,v),v;return!0})()?e()?f():h(!1):h(!1)};this.$commitViewValue=function(){var a=m.$viewValue;h.cancel(M);if(m.$$lastCommittedViewValue!==a||""===a&&m.$$hasNativeValidators)m.$$lastCommittedViewValue=a,m.$pristine&&this.$setDirty(),this.$$parseAndValidate()};this.$$parseAndValidate=function(){var c=m.$$lastCommittedViewValue;if(v=
+x(c)?t:!0)for(var d=0;dz;)d=t.pop(),n(O,d.label,!1),d.element.remove()}for(;R.length>
+x;){l=R.pop();for(z=1;za&&q.removeOption(c)})}var v;if(!(v=s.match(d)))throw gg("iexp",s,wa(f));var C=c(v[2]||v[1]),x=v[4]||v[6],A=/ as /.test(v[0])&&v[1],B=A?c(A):null,G=v[5],J=c(v[3]||""),z=c(v[2]?v[1]:x),L=c(v[7]),I=v[8]?c(v[8]):null,Q={},R=[[{element:f,label:""}]],T={};w&&(a(w)(e),w.removeClass("ng-scope"),w.remove());f.empty();f.on("change",function(){e.$apply(function(){var a=L(e)||[],c;if(u)c=[],r(f.val(),
+function(d){d=I?Q[d]:d;c.push("?"===d?t:""===d?null:h(B?B:z,d,a[d]))});else{var d=I?Q[f.val()]:f.val();c="?"===d?t:""===d?null:h(B?B:z,d,a[d])}g.$setViewValue(c);p()})});g.$render=p;e.$watchCollection(L,l);e.$watchCollection(function(){var a=L(e),c;if(a&&H(a)){c=Array(a.length);for(var d=0,f=a.length;df||e.$isEmpty(c)||c.length<=f}}}}},Cc=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){if(e){var f=0;d.$observe("minlength",function(a){f=aa(a)||0;e.$validate()});e.$validators.minlength=function(a,c){return e.$isEmpty(c)||c.length>=f}}}}};Q.angular.bootstrap?console.log("WARNING: Tried to load angular more than once."):(Nd(),Pd(ca),A(W).ready(function(){Jd(W,uc)}))})(window,document);!window.angular.$$csp()&&window.angular.element(document).find("head").prepend('');
diff --git a/apps/static/js/bootstrap-dialog.js b/apps/static/js/bootstrap-dialog.js
new file mode 100644
index 000000000..2cbdcc4b7
--- /dev/null
+++ b/apps/static/js/bootstrap-dialog.js
@@ -0,0 +1,1089 @@
+/* global define */
+
+/* ================================================
+ * Make use of Bootstrap's modal more monkey-friendly.
+ *
+ * For Bootstrap 3.
+ *
+ * javanoob@hotmail.com
+ *
+ * https://github.com/nakupanda/bootstrap3-dialog
+ *
+ * Licensed under The MIT License.
+ * ================================================ */
+(function(root, factory) {
+
+ "use strict";
+
+ // CommonJS module is defined
+ if (typeof module !== 'undefined' && module.exports) {
+ module.exports = factory(require('jquery')(root));
+ }
+ // AMD module is defined
+ else if (typeof define === "function" && define.amd) {
+ define("bootstrap-dialog", ["jquery"], function($) {
+ return factory($);
+ });
+ } else {
+ // planted over the root!
+ root.BootstrapDialog = factory(root.jQuery);
+ }
+
+}(this, function($) {
+
+ "use strict";
+
+ var BootstrapDialog = function(options) {
+ this.defaultOptions = $.extend(true, {
+ id: BootstrapDialog.newGuid(),
+ buttons: [],
+ data: {},
+ onshow: null,
+ onshown: null,
+ onhide: null,
+ onhidden: null
+ }, BootstrapDialog.defaultOptions);
+ this.indexedButtons = {};
+ this.registeredButtonHotkeys = {};
+ this.draggableData = {
+ isMouseDown: false,
+ mouseOffset: {}
+ };
+ this.realized = false;
+ this.opened = false;
+ this.initOptions(options);
+ this.holdThisInstance();
+ };
+
+ /**
+ * Some constants.
+ */
+ BootstrapDialog.NAMESPACE = 'bootstrap-dialog';
+
+ BootstrapDialog.TYPE_DEFAULT = 'type-default';
+ BootstrapDialog.TYPE_INFO = 'type-info';
+ BootstrapDialog.TYPE_PRIMARY = 'type-primary';
+ BootstrapDialog.TYPE_SUCCESS = 'type-success';
+ BootstrapDialog.TYPE_WARNING = 'type-warning';
+ BootstrapDialog.TYPE_DANGER = 'type-danger';
+
+ BootstrapDialog.DEFAULT_TEXTS = {};
+ BootstrapDialog.DEFAULT_TEXTS[BootstrapDialog.TYPE_DEFAULT] = 'Information';
+ BootstrapDialog.DEFAULT_TEXTS[BootstrapDialog.TYPE_INFO] = 'Information';
+ BootstrapDialog.DEFAULT_TEXTS[BootstrapDialog.TYPE_PRIMARY] = 'Information';
+ BootstrapDialog.DEFAULT_TEXTS[BootstrapDialog.TYPE_SUCCESS] = 'Success';
+ BootstrapDialog.DEFAULT_TEXTS[BootstrapDialog.TYPE_WARNING] = 'Warning';
+ BootstrapDialog.DEFAULT_TEXTS[BootstrapDialog.TYPE_DANGER] = 'Danger';
+ BootstrapDialog.DEFAULT_TEXTS['OK'] = 'OK';
+ BootstrapDialog.DEFAULT_TEXTS['CANCEL'] = 'Cancel';
+
+ BootstrapDialog.SIZE_NORMAL = 'size-normal';
+ BootstrapDialog.SIZE_WIDE = 'size-wide'; // size-wide is equal to modal-lg
+ BootstrapDialog.SIZE_LARGE = 'size-large';
+
+ BootstrapDialog.BUTTON_SIZES = {};
+ BootstrapDialog.BUTTON_SIZES[BootstrapDialog.SIZE_NORMAL] = '';
+ BootstrapDialog.BUTTON_SIZES[BootstrapDialog.SIZE_WIDE] = '';
+ BootstrapDialog.BUTTON_SIZES[BootstrapDialog.SIZE_LARGE] = 'btn-lg';
+
+ BootstrapDialog.ICON_SPINNER = 'glyphicon glyphicon-asterisk';
+
+ BootstrapDialog.ZINDEX_BACKDROP = 1040;
+ BootstrapDialog.ZINDEX_MODAL = 1050;
+
+ /**
+ * Default options.
+ */
+ BootstrapDialog.defaultOptions = {
+ type: BootstrapDialog.TYPE_PRIMARY,
+ size: BootstrapDialog.SIZE_NORMAL,
+ cssClass: '',
+ title: null,
+ message: null,
+ nl2br: true,
+ closable: true,
+ closeByBackdrop: true,
+ closeByKeyboard: true,
+ spinicon: BootstrapDialog.ICON_SPINNER,
+ autodestroy: true,
+ draggable: false,
+ animate: true,
+ description: ''
+ };
+
+ /**
+ * Config default options.
+ */
+ BootstrapDialog.configDefaultOptions = function(options) {
+ BootstrapDialog.defaultOptions = $.extend(true, BootstrapDialog.defaultOptions, options);
+ };
+
+ /**
+ * Open / Close all created dialogs all at once.
+ */
+ BootstrapDialog.dialogs = {};
+ BootstrapDialog.openAll = function() {
+ $.each(BootstrapDialog.dialogs, function(id, dialogInstance) {
+ dialogInstance.open();
+ });
+ };
+ BootstrapDialog.closeAll = function() {
+ $.each(BootstrapDialog.dialogs, function(id, dialogInstance) {
+ dialogInstance.close();
+ });
+ };
+
+ /**
+ * Move focus to next visible dialog.
+ */
+ BootstrapDialog.moveFocus = function() {
+ var lastDialogInstance = null;
+ $.each(BootstrapDialog.dialogs, function(id, dialogInstance) {
+ lastDialogInstance = dialogInstance;
+ });
+ if (lastDialogInstance !== null && lastDialogInstance.isRealized()) {
+ lastDialogInstance.getModal().focus();
+ }
+ };
+
+ /**
+ * Show scrollbar if the last visible dialog needs one.
+ */
+ BootstrapDialog.showScrollbar = function() {
+ var lastDialogInstance = null;
+ $.each(BootstrapDialog.dialogs, function(id, dialogInstance) {
+ lastDialogInstance = dialogInstance;
+ });
+ if (lastDialogInstance !== null && lastDialogInstance.isRealized() && lastDialogInstance.isOpened()) {
+ var bsModal = lastDialogInstance.getModal().data('bs.modal');
+ bsModal.checkScrollbar();
+ $('body').addClass('modal-open');
+ bsModal.setScrollbar();
+ }
+ };
+
+ BootstrapDialog.prototype = {
+ constructor: BootstrapDialog,
+ initOptions: function(options) {
+ this.options = $.extend(true, this.defaultOptions, options);
+
+ return this;
+ },
+ holdThisInstance: function() {
+ BootstrapDialog.dialogs[this.getId()] = this;
+
+ return this;
+ },
+ initModalStuff: function() {
+ this.setModal(this.createModal())
+ .setModalDialog(this.createModalDialog())
+ .setModalContent(this.createModalContent())
+ .setModalHeader(this.createModalHeader())
+ .setModalBody(this.createModalBody())
+ .setModalFooter(this.createModalFooter());
+
+ this.getModal().append(this.getModalDialog());
+ this.getModalDialog().append(this.getModalContent());
+ this.getModalContent()
+ .append(this.getModalHeader())
+ .append(this.getModalBody())
+ .append(this.getModalFooter());
+
+ return this;
+ },
+ createModal: function() {
+ var $modal = $('');
+ $modal.prop('id', this.getId()).attr('aria-labelledby', this.getId() + '_title');
+
+ return $modal;
+ },
+ getModal: function() {
+ return this.$modal;
+ },
+ setModal: function($modal) {
+ this.$modal = $modal;
+
+ return this;
+ },
+ createModalDialog: function() {
+ return $('');
+ },
+ getModalDialog: function() {
+ return this.$modalDialog;
+ },
+ setModalDialog: function($modalDialog) {
+ this.$modalDialog = $modalDialog;
+
+ return this;
+ },
+ createModalContent: function() {
+ return $('');
+ },
+ getModalContent: function() {
+ return this.$modalContent;
+ },
+ setModalContent: function($modalContent) {
+ this.$modalContent = $modalContent;
+
+ return this;
+ },
+ createModalHeader: function() {
+ return $('');
+ },
+ getModalHeader: function() {
+ return this.$modalHeader;
+ },
+ setModalHeader: function($modalHeader) {
+ this.$modalHeader = $modalHeader;
+
+ return this;
+ },
+ createModalBody: function() {
+ return $('');
+ },
+ getModalBody: function() {
+ return this.$modalBody;
+ },
+ setModalBody: function($modalBody) {
+ this.$modalBody = $modalBody;
+
+ return this;
+ },
+ createModalFooter: function() {
+ return $('');
+ },
+ getModalFooter: function() {
+ return this.$modalFooter;
+ },
+ setModalFooter: function($modalFooter) {
+ this.$modalFooter = $modalFooter;
+
+ return this;
+ },
+ createDynamicContent: function(rawContent) {
+ var content = null;
+ if (typeof rawContent === 'function') {
+ content = rawContent.call(rawContent, this);
+ } else {
+ content = rawContent;
+ }
+ if (typeof content === 'string') {
+ content = this.formatStringContent(content);
+ }
+
+ return content;
+ },
+ formatStringContent: function(content) {
+ if (this.options.nl2br) {
+ return content.replace(/\r\n/g, '
').replace(/[\r\n]/g, '
');
+ }
+
+ return content;
+ },
+ setData: function(key, value) {
+ this.options.data[key] = value;
+
+ return this;
+ },
+ getData: function(key) {
+ return this.options.data[key];
+ },
+ setId: function(id) {
+ this.options.id = id;
+
+ return this;
+ },
+ getId: function() {
+ return this.options.id;
+ },
+ getType: function() {
+ return this.options.type;
+ },
+ setType: function(type) {
+ this.options.type = type;
+ this.updateType();
+
+ return this;
+ },
+ updateType: function() {
+ if (this.isRealized()) {
+ var types = [BootstrapDialog.TYPE_DEFAULT,
+ BootstrapDialog.TYPE_INFO,
+ BootstrapDialog.TYPE_PRIMARY,
+ BootstrapDialog.TYPE_SUCCESS,
+ BootstrapDialog.TYPE_WARNING,
+ BootstrapDialog.TYPE_DANGER];
+
+ this.getModal().removeClass(types.join(' ')).addClass(this.getType());
+ }
+
+ return this;
+ },
+ getSize: function() {
+ return this.options.size;
+ },
+ setSize: function(size) {
+ this.options.size = size;
+ this.updateSize();
+
+ return this;
+ },
+ updateSize: function() {
+ if (this.isRealized()) {
+ var dialog = this;
+
+ // Dialog size
+ this.getModal().removeClass(BootstrapDialog.SIZE_NORMAL)
+ .removeClass(BootstrapDialog.SIZE_WIDE)
+ .removeClass(BootstrapDialog.SIZE_LARGE);
+ this.getModal().addClass(this.getSize());
+
+ // Wider dialog.
+ this.getModalDialog().removeClass('modal-lg');
+ if (this.getSize() === BootstrapDialog.SIZE_WIDE) {
+ this.getModalDialog().addClass('modal-lg');
+ }
+
+ // Button size
+ $.each(this.options.buttons, function(index, button) {
+ var $button = dialog.getButton(button.id);
+ var buttonSizes = ['btn-lg', 'btn-sm', 'btn-xs'];
+ var sizeClassSpecified = false;
+ if (typeof button['cssClass'] === 'string') {
+ var btnClasses = button['cssClass'].split(' ');
+ $.each(btnClasses, function(index, btnClass) {
+ if ($.inArray(btnClass, buttonSizes) !== -1) {
+ sizeClassSpecified = true;
+ }
+ });
+ }
+ if (!sizeClassSpecified) {
+ $button.removeClass(buttonSizes.join(' '));
+ $button.addClass(dialog.getButtonSize());
+ }
+ });
+ }
+
+ return this;
+ },
+ getCssClass: function() {
+ return this.options.cssClass;
+ },
+ setCssClass: function(cssClass) {
+ this.options.cssClass = cssClass;
+
+ return this;
+ },
+ getTitle: function() {
+ return this.options.title;
+ },
+ setTitle: function(title) {
+ this.options.title = title;
+ this.updateTitle();
+
+ return this;
+ },
+ updateTitle: function() {
+ if (this.isRealized()) {
+ var title = this.getTitle() !== null ? this.createDynamicContent(this.getTitle()) : this.getDefaultText();
+ this.getModalHeader().find('.' + this.getNamespace('title')).html('').append(title).prop('id', this.getId() + '_title');
+ }
+
+ return this;
+ },
+ getMessage: function() {
+ return this.options.message;
+ },
+ setMessage: function(message) {
+ this.options.message = message;
+ this.updateMessage();
+
+ return this;
+ },
+ updateMessage: function() {
+ if (this.isRealized()) {
+ var message = this.createDynamicContent(this.getMessage());
+ this.getModalBody().find('.' + this.getNamespace('message')).html('').append(message);
+ }
+
+ return this;
+ },
+ isClosable: function() {
+ return this.options.closable;
+ },
+ setClosable: function(closable) {
+ this.options.closable = closable;
+ this.updateClosable();
+
+ return this;
+ },
+ setCloseByBackdrop: function(closeByBackdrop) {
+ this.options.closeByBackdrop = closeByBackdrop;
+
+ return this;
+ },
+ canCloseByBackdrop: function() {
+ return this.options.closeByBackdrop;
+ },
+ setCloseByKeyboard: function(closeByKeyboard) {
+ this.options.closeByKeyboard = closeByKeyboard;
+
+ return this;
+ },
+ canCloseByKeyboard: function() {
+ return this.options.closeByKeyboard;
+ },
+ isAnimate: function() {
+ return this.options.animate;
+ },
+ setAnimate: function(animate) {
+ this.options.animate = animate;
+
+ return this;
+ },
+ updateAnimate: function() {
+ if (this.isRealized()) {
+ this.getModal().toggleClass('fade', this.isAnimate());
+ }
+
+ return this;
+ },
+ getSpinicon: function() {
+ return this.options.spinicon;
+ },
+ setSpinicon: function(spinicon) {
+ this.options.spinicon = spinicon;
+
+ return this;
+ },
+ addButton: function(button) {
+ this.options.buttons.push(button);
+
+ return this;
+ },
+ addButtons: function(buttons) {
+ var that = this;
+ $.each(buttons, function(index, button) {
+ that.addButton(button);
+ });
+
+ return this;
+ },
+ getButtons: function() {
+ return this.options.buttons;
+ },
+ setButtons: function(buttons) {
+ this.options.buttons = buttons;
+ this.updateButtons();
+
+ return this;
+ },
+ /**
+ * If there is id provided for a button option, it will be in dialog.indexedButtons list.
+ *
+ * In that case you can use dialog.getButton(id) to find the button.
+ *
+ * @param {type} id
+ * @returns {undefined}
+ */
+ getButton: function(id) {
+ if (typeof this.indexedButtons[id] !== 'undefined') {
+ return this.indexedButtons[id];
+ }
+
+ return null;
+ },
+ getButtonSize: function() {
+ if (typeof BootstrapDialog.BUTTON_SIZES[this.getSize()] !== 'undefined') {
+ return BootstrapDialog.BUTTON_SIZES[this.getSize()];
+ }
+
+ return '';
+ },
+ updateButtons: function() {
+ if (this.isRealized()) {
+ if (this.getButtons().length === 0) {
+ this.getModalFooter().hide();
+ } else {
+ this.getModalFooter().find('.' + this.getNamespace('footer')).html('').append(this.createFooterButtons());
+ }
+ }
+
+ return this;
+ },
+ isAutodestroy: function() {
+ return this.options.autodestroy;
+ },
+ setAutodestroy: function(autodestroy) {
+ this.options.autodestroy = autodestroy;
+ },
+ getDescription: function() {
+ return this.options.description;
+ },
+ setDescription: function(description) {
+ this.options.description = description;
+
+ return this;
+ },
+ getDefaultText: function() {
+ return BootstrapDialog.DEFAULT_TEXTS[this.getType()];
+ },
+ getNamespace: function(name) {
+ return BootstrapDialog.NAMESPACE + '-' + name;
+ },
+ createHeaderContent: function() {
+ var $container = $('');
+ $container.addClass(this.getNamespace('header'));
+
+ // title
+ $container.append(this.createTitleContent());
+
+ // Close button
+ $container.prepend(this.createCloseButton());
+
+ return $container;
+ },
+ createTitleContent: function() {
+ var $title = $('');
+ $title.addClass(this.getNamespace('title'));
+
+ return $title;
+ },
+ createCloseButton: function() {
+ var $container = $('');
+ $container.addClass(this.getNamespace('close-button'));
+ var $icon = $('');
+ $container.append($icon);
+ $container.on('click', {dialog: this}, function(event) {
+ event.data.dialog.close();
+ });
+
+ return $container;
+ },
+ createBodyContent: function() {
+ var $container = $('');
+ $container.addClass(this.getNamespace('body'));
+
+ // Message
+ $container.append(this.createMessageContent());
+
+ return $container;
+ },
+ createMessageContent: function() {
+ var $message = $('');
+ $message.addClass(this.getNamespace('message'));
+
+ return $message;
+ },
+ createFooterContent: function() {
+ var $container = $('');
+ $container.addClass(this.getNamespace('footer'));
+
+ return $container;
+ },
+ createFooterButtons: function() {
+ var that = this;
+ var $container = $('');
+ $container.addClass(this.getNamespace('footer-buttons'));
+ this.indexedButtons = {};
+ $.each(this.options.buttons, function(index, button) {
+ if (!button.id) {
+ button.id = BootstrapDialog.newGuid();
+ }
+ var $button = that.createButton(button);
+ that.indexedButtons[button.id] = $button;
+ $container.append($button);
+ });
+
+ return $container;
+ },
+ createButton: function(button) {
+ var $button = $('');
+ $button.prop('id', button.id);
+
+ // Icon
+ if (typeof button.icon !== 'undefined' && $.trim(button.icon) !== '') {
+ $button.append(this.createButtonIcon(button.icon));
+ }
+
+ // Label
+ if (typeof button.label !== 'undefined') {
+ $button.append(button.label);
+ }
+
+ // Css class
+ if (typeof button.cssClass !== 'undefined' && $.trim(button.cssClass) !== '') {
+ $button.addClass(button.cssClass);
+ } else {
+ $button.addClass('btn-default');
+ }
+
+ // Hotkey
+ if (typeof button.hotkey !== 'undefined') {
+ this.registeredButtonHotkeys[button.hotkey] = $button;
+ }
+
+ // Button on click
+ $button.on('click', {dialog: this, $button: $button, button: button}, function(event) {
+ var dialog = event.data.dialog;
+ var $button = event.data.$button;
+ var button = event.data.button;
+ if (typeof button.action === 'function') {
+ button.action.call($button, dialog);
+ }
+
+ if (button.autospin) {
+ $button.toggleSpin(true);
+ }
+ });
+
+ // Dynamically add extra functions to $button
+ this.enhanceButton($button);
+
+ return $button;
+ },
+ /**
+ * Dynamically add extra functions to $button
+ *
+ * Using '$this' to reference 'this' is just for better readability.
+ *
+ * @param {type} $button
+ * @returns {_L13.BootstrapDialog.prototype}
+ */
+ enhanceButton: function($button) {
+ $button.dialog = this;
+
+ // Enable / Disable
+ $button.toggleEnable = function(enable) {
+ var $this = this;
+ if (typeof enable !== 'undefined') {
+ $this.prop("disabled", !enable).toggleClass('disabled', !enable);
+ } else {
+ $this.prop("disabled", !$this.prop("disabled"));
+ }
+
+ return $this;
+ };
+ $button.enable = function() {
+ var $this = this;
+ $this.toggleEnable(true);
+
+ return $this;
+ };
+ $button.disable = function() {
+ var $this = this;
+ $this.toggleEnable(false);
+
+ return $this;
+ };
+
+ // Icon spinning, helpful for indicating ajax loading status.
+ $button.toggleSpin = function(spin) {
+ var $this = this;
+ var dialog = $this.dialog;
+ var $icon = $this.find('.' + dialog.getNamespace('button-icon'));
+ if (typeof spin === 'undefined') {
+ spin = !($button.find('.icon-spin').length > 0);
+ }
+ if (spin) {
+ $icon.hide();
+ $button.prepend(dialog.createButtonIcon(dialog.getSpinicon()).addClass('icon-spin'));
+ } else {
+ $icon.show();
+ $button.find('.icon-spin').remove();
+ }
+
+ return $this;
+ };
+ $button.spin = function() {
+ var $this = this;
+ $this.toggleSpin(true);
+
+ return $this;
+ };
+ $button.stopSpin = function() {
+ var $this = this;
+ $this.toggleSpin(false);
+
+ return $this;
+ };
+
+ return this;
+ },
+ createButtonIcon: function(icon) {
+ var $icon = $('');
+ $icon.addClass(this.getNamespace('button-icon')).addClass(icon);
+
+ return $icon;
+ },
+ /**
+ * Invoke this only after the dialog is realized.
+ *
+ * @param {type} enable
+ * @returns {undefined}
+ */
+ enableButtons: function(enable) {
+ $.each(this.indexedButtons, function(id, $button) {
+ $button.toggleEnable(enable);
+ });
+
+ return this;
+ },
+ /**
+ * Invoke this only after the dialog is realized.
+ *
+ * @returns {undefined}
+ */
+ updateClosable: function() {
+ if (this.isRealized()) {
+ // Close button
+ this.getModalHeader().find('.' + this.getNamespace('close-button')).toggle(this.isClosable());
+ }
+
+ return this;
+ },
+ /**
+ * Set handler for modal event 'show.bs.modal'.
+ * This is a setter!
+ */
+ onShow: function(onshow) {
+ this.options.onshow = onshow;
+
+ return this;
+ },
+ /**
+ * Set handler for modal event 'shown.bs.modal'.
+ * This is a setter!
+ */
+ onShown: function(onshown) {
+ this.options.onshown = onshown;
+
+ return this;
+ },
+ /**
+ * Set handler for modal event 'hide.bs.modal'.
+ * This is a setter!
+ */
+ onHide: function(onhide) {
+ this.options.onhide = onhide;
+
+ return this;
+ },
+ /**
+ * Set handler for modal event 'hidden.bs.modal'.
+ * This is a setter!
+ */
+ onHidden: function(onhidden) {
+ this.options.onhidden = onhidden;
+
+ return this;
+ },
+ isRealized: function() {
+ return this.realized;
+ },
+ setRealized: function(realized) {
+ this.realized = realized;
+
+ return this;
+ },
+ isOpened: function() {
+ return this.opened;
+ },
+ setOpened: function(opened) {
+ this.opened = opened;
+
+ return this;
+ },
+ handleModalEvents: function() {
+ this.getModal().on('show.bs.modal', {dialog: this}, function(event) {
+ var dialog = event.data.dialog;
+ if (dialog.isModalEvent(event) && typeof dialog.options.onshow === 'function') {
+ return dialog.options.onshow(dialog);
+ }
+ });
+ this.getModal().on('shown.bs.modal', {dialog: this}, function(event) {
+ var dialog = event.data.dialog;
+ dialog.isModalEvent(event) && typeof dialog.options.onshown === 'function' && dialog.options.onshown(dialog);
+ });
+ this.getModal().on('hide.bs.modal', {dialog: this}, function(event) {
+ var dialog = event.data.dialog;
+ if (dialog.isModalEvent(event) && typeof dialog.options.onhide === 'function') {
+ return dialog.options.onhide(dialog);
+ }
+ });
+ this.getModal().on('hidden.bs.modal', {dialog: this}, function(event) {
+ var dialog = event.data.dialog;
+ dialog.isModalEvent(event) && typeof dialog.options.onhidden === 'function' && dialog.options.onhidden(dialog);
+ dialog.isAutodestroy() && $(this).remove();
+ BootstrapDialog.moveFocus();
+ });
+
+ // Backdrop, I did't find a way to change bs3 backdrop option after the dialog is popped up, so here's a new wheel.
+ this.getModal().on('click', {dialog: this}, function(event) {
+ event.target === this && event.data.dialog.isClosable() && event.data.dialog.canCloseByBackdrop() && event.data.dialog.close();
+ });
+
+ // ESC key support
+ this.getModal().on('keyup', {dialog: this}, function(event) {
+ event.which === 27 && event.data.dialog.isClosable() && event.data.dialog.canCloseByKeyboard() && event.data.dialog.close();
+ });
+
+ // Button hotkey
+ this.getModal().on('keyup', {dialog: this}, function(event) {
+ var dialog = event.data.dialog;
+ if (typeof dialog.registeredButtonHotkeys[event.which] !== 'undefined') {
+ var $button = $(dialog.registeredButtonHotkeys[event.which]);
+ !$button.prop('disabled') && $button.focus().trigger('click');
+ }
+ });
+
+ return this;
+ },
+ isModalEvent: function(event) {
+ return typeof event.namespace !== 'undefined' && event.namespace === 'bs.modal';
+ },
+ makeModalDraggable: function() {
+ if (this.options.draggable) {
+ this.getModalHeader().addClass(this.getNamespace('draggable')).on('mousedown', {dialog: this}, function(event) {
+ var dialog = event.data.dialog;
+ dialog.draggableData.isMouseDown = true;
+ var dialogOffset = dialog.getModalDialog().offset();
+ dialog.draggableData.mouseOffset = {
+ top: event.clientY - dialogOffset.top,
+ left: event.clientX - dialogOffset.left
+ };
+ });
+ this.getModal().on('mouseup mouseleave', {dialog: this}, function(event) {
+ event.data.dialog.draggableData.isMouseDown = false;
+ });
+ $('body').on('mousemove', {dialog: this}, function(event) {
+ var dialog = event.data.dialog;
+ if (!dialog.draggableData.isMouseDown) {
+ return;
+ }
+ dialog.getModalDialog().offset({
+ top: event.clientY - dialog.draggableData.mouseOffset.top,
+ left: event.clientX - dialog.draggableData.mouseOffset.left
+ });
+ });
+ }
+
+ return this;
+ },
+ /**
+ * To make multiple opened dialogs look better.
+ */
+ updateZIndex: function() {
+ var dialogCount = 0;
+ $.each(BootstrapDialog.dialogs, function(dialogId, dialogInstance) {
+ dialogCount++;
+ });
+ var $modal = this.getModal();
+ var $backdrop = $modal.data('bs.modal').$backdrop;
+ $modal.css('z-index', BootstrapDialog.ZINDEX_MODAL + (dialogCount - 1) * 20);
+ $backdrop.css('z-index', BootstrapDialog.ZINDEX_BACKDROP + (dialogCount - 1) * 20);
+
+ return this;
+ },
+ realize: function() {
+ this.initModalStuff();
+ this.getModal().addClass(BootstrapDialog.NAMESPACE)
+ .addClass(this.getCssClass());
+ this.updateSize();
+ if (this.getDescription()) {
+ this.getModal().attr('aria-describedby', this.getDescription());
+ }
+ this.getModalFooter().append(this.createFooterContent());
+ this.getModalHeader().append(this.createHeaderContent());
+ this.getModalBody().append(this.createBodyContent());
+ this.getModal().modal({
+ backdrop: 'static',
+ keyboard: false,
+ show: false
+ });
+ this.makeModalDraggable();
+ this.handleModalEvents();
+ this.setRealized(true);
+ this.updateButtons();
+ this.updateType();
+ this.updateTitle();
+ this.updateMessage();
+ this.updateClosable();
+ this.updateAnimate();
+ this.updateSize();
+
+ return this;
+ },
+ open: function() {
+ !this.isRealized() && this.realize();
+ this.getModal().modal('show');
+ this.updateZIndex();
+ this.setOpened(true);
+
+ return this;
+ },
+ close: function() {
+ this.getModal().modal('hide');
+ if (this.isAutodestroy()) {
+ delete BootstrapDialog.dialogs[this.getId()];
+ }
+ this.setOpened(false);
+
+ // Show scrollbar if the last visible dialog needs one.
+ BootstrapDialog.showScrollbar();
+
+ return this;
+ }
+ };
+
+ /**
+ * RFC4122 version 4 compliant unique id creator.
+ *
+ * Added by https://github.com/tufanbarisyildirim/
+ *
+ * @returns {String}
+ */
+ BootstrapDialog.newGuid = function() {
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
+ var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
+ return v.toString(16);
+ });
+ };
+
+ /* ================================================
+ * For lazy people
+ * ================================================ */
+
+ /**
+ * Shortcut function: show
+ *
+ * @param {type} options
+ * @returns the created dialog instance
+ */
+ BootstrapDialog.show = function(options) {
+ return new BootstrapDialog(options).open();
+ };
+
+ /**
+ * Alert window
+ *
+ * @returns the created dialog instance
+ */
+ BootstrapDialog.alert = function() {
+ var options = {};
+ var defaultOptions = {
+ type: BootstrapDialog.TYPE_PRIMARY,
+ title: null,
+ message: null,
+ closable: true,
+ buttonLabel: BootstrapDialog.DEFAULT_TEXTS.OK,
+ callback: null
+ };
+
+ if (typeof arguments[0] === 'object' && arguments[0].constructor === {}.constructor) {
+ options = $.extend(true, defaultOptions, arguments[0]);
+ } else {
+ options = $.extend(true, defaultOptions, {
+ message: arguments[0],
+ closable: false,
+ buttonLabel: BootstrapDialog.DEFAULT_TEXTS.OK,
+ callback: typeof arguments[1] !== 'undefined' ? arguments[1] : null
+ });
+ }
+
+ return new BootstrapDialog({
+ type: options.type,
+ title: options.title,
+ message: options.message,
+ closable: options.closable,
+ data: {
+ callback: options.callback
+ },
+ onhide: function(dialog) {
+ !dialog.getData('btnClicked') && dialog.isClosable() && typeof dialog.getData('callback') === 'function' && dialog.getData('callback')(false);
+ },
+ buttons: [{
+ label: options.buttonLabel,
+ action: function(dialog) {
+ dialog.setData('btnClicked', true);
+ typeof dialog.getData('callback') === 'function' && dialog.getData('callback')(true);
+ dialog.close();
+ }
+ }]
+ }).open();
+ };
+
+ /**
+ * Confirm window
+ *
+ * @param {type} message
+ * @param {type} callback
+ * @returns the created dialog instance
+ */
+ BootstrapDialog.confirm = function(message, callback) {
+ return new BootstrapDialog({
+ title: 'Confirmation',
+ message: message,
+ closable: false,
+ data: {
+ 'callback': callback
+ },
+ buttons: [{
+ label: BootstrapDialog.DEFAULT_TEXTS.CANCEL,
+ action: function(dialog) {
+ typeof dialog.getData('callback') === 'function' && dialog.getData('callback')(false);
+ dialog.close();
+ }
+ }, {
+ label: BootstrapDialog.DEFAULT_TEXTS.OK,
+ cssClass: 'btn-primary',
+ action: function(dialog) {
+ typeof dialog.getData('callback') === 'function' && dialog.getData('callback')(true);
+ dialog.close();
+ }
+ }]
+ }).open();
+ };
+
+ /**
+ * Warning window
+ *
+ * @param {type} message
+ * @returns the created dialog instance
+ */
+ BootstrapDialog.warning = function(message, callback) {
+ return new BootstrapDialog({
+ type: BootstrapDialog.TYPE_WARNING,
+ message: message
+ }).open();
+ };
+
+ /**
+ * Danger window
+ *
+ * @param {type} message
+ * @returns the created dialog instance
+ */
+ BootstrapDialog.danger = function(message, callback) {
+ return new BootstrapDialog({
+ type: BootstrapDialog.TYPE_DANGER,
+ message: message
+ }).open();
+ };
+
+ /**
+ * Success window
+ *
+ * @param {type} message
+ * @returns the created dialog instance
+ */
+ BootstrapDialog.success = function(message, callback) {
+ return new BootstrapDialog({
+ type: BootstrapDialog.TYPE_SUCCESS,
+ message: message
+ }).open();
+ };
+
+ return BootstrapDialog;
+
+}));
diff --git a/apps/static/js/bootstrap.min.js b/apps/static/js/bootstrap.min.js
new file mode 100644
index 000000000..63866bcb4
--- /dev/null
+++ b/apps/static/js/bootstrap.min.js
@@ -0,0 +1,7 @@
+/*!
+ * Bootstrap v3.3.0 (http://getbootstrap.com)
+ * Copyright 2011-2014 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ */
+if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.0",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.0",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active"));a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus","focus"==b.type)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.0",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c="prev"==a?-1:1,d=this.getItemIndex(b),e=(d+c)%this.$items.length;return this.$items.eq(e)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i="next"==b?"first":"last",j=this;if(!f.length){if(!this.options.wrap)return;f=this.$element.find(".item")[i]()}if(f.hasClass("active"))return this.sliding=!1;var k=f[0],l=a.Event("slide.bs.carousel",{relatedTarget:k,direction:h});if(this.$element.trigger(l),!l.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var m=a(this.$indicators.children()[this.getItemIndex(f)]);m&&m.addClass("active")}var n=a.Event("slid.bs.carousel",{relatedTarget:k,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),j.sliding=!1,setTimeout(function(){j.$element.trigger(n)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(n)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&"show"==b&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a(this.options.trigger).filter('[href="#'+b.id+'"], [data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.0",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0,trigger:'[data-toggle="collapse"]'},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.find("> .panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":a.extend({},e.data(),{trigger:this});c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=c(d),f={relatedTarget:this};e.hasClass("open")&&(e.trigger(b=a.Event("hide.bs.dropdown",f)),b.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f)))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.0",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(b){if(/(38|40|27|32)/.test(b.which)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var e=c(d),g=e.hasClass("open");if(!g&&27!=b.which||g&&27==b.which)return 27==b.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.divider):visible a",i=e.find('[role="menu"]'+h+', [role="listbox"]'+h);if(i.length){var j=i.index(b.target);38==b.which&&j>0&&j--,40==b.which&&j').prependTo(this.$element).on("click.dismiss.bs.modal",a.proxy(function(a){a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus.call(this.$element[0]):this.hide.call(this))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.checkScrollbar=function(){this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.scrollbarWidth&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right","")},c.prototype.measureScrollbar=function(){if(document.body.clientWidth>=window.innerWidth)return 0;var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b,g=f&&f.selector;(e||"destroy"!=b)&&(g?(e||d.data("bs.tooltip",e={}),e[g]||(e[g]=new c(this,f))):e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};c.VERSION="3.3.0",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport);for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c&&c.$tip&&c.$tip.is(":visible")?void(c.hoverState="in"):(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.options.container?a(this.options.container):this.$element.parent(),p=this.getPosition(o);h="bottom"==h&&k.bottom+m>p.bottom?"top":"top"==h&&k.top-mp.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type)})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b,g=f&&f.selector;(e||"destroy"!=b)&&(g?(e||d.data("bs.popover",e={}),e[g]||(e[g]=new c(this,f))):e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.0",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},c.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){var e=a.proxy(this.process,this);this.$body=a("body"),this.$scrollElement=a(a(c).is("body")?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",e),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.0",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b="offset",c=0;a.isWindow(this.$scrollElement[0])||(b="position",c=this.$scrollElement.scrollTop()),this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight();var d=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[b]().top+c,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){d.offsets.push(this[0]),d.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.0",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)
+}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=this.unpin=this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.0",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=i?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=a("body").height();"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);
\ No newline at end of file
diff --git a/apps/static/js/inspinia.js b/apps/static/js/inspinia.js
new file mode 100644
index 000000000..ed8c1c6ba
--- /dev/null
+++ b/apps/static/js/inspinia.js
@@ -0,0 +1,167 @@
+// Custom scripts
+$(document).ready(function () {
+
+ // MetsiMenu
+ $('#side-menu').metisMenu();
+
+ // Collapse ibox function
+ $('.collapse-link').click( function() {
+ var ibox = $(this).closest('div.ibox');
+ var button = $(this).find('i');
+ var content = ibox.find('div.ibox-content');
+ content.slideToggle(200);
+ button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
+ ibox.toggleClass('').toggleClass('border-bottom');
+ setTimeout(function () {
+ ibox.resize();
+ ibox.find('[id^=map-]').resize();
+ }, 50);
+ });
+
+ // Close ibox function
+ $('.close-link').click( function() {
+ var content = $(this).closest('div.ibox');
+ content.remove();
+ });
+
+ // Small todo handler
+ $('.check-link').click( function(){
+ var button = $(this).find('i');
+ var label = $(this).next('span');
+ button.toggleClass('fa-check-square').toggleClass('fa-square-o');
+ label.toggleClass('todo-completed');
+ return false;
+ });
+
+ // Append config box / Only for demo purpose
+ //$.get("/skin_config/", function (data) {
+ // $('body').append(data);
+ //});
+
+ // minimalize menu
+ $('.navbar-minimalize').click(function () {
+ $("body").toggleClass("mini-navbar");
+ SmoothlyMenu();
+ })
+
+ // tooltips
+ $('.tooltip-demo').tooltip({
+ selector: "[data-toggle=tooltip]",
+ container: "body"
+ })
+
+ // Move modal to body
+ // Fix Bootstrap backdrop issu with animation.css
+ $('.modal').appendTo("body")
+
+ // Full height of sidebar
+ function fix_height() {
+ var heightWithoutNavbar = $("body > #wrapper").height() - 61;
+ $(".sidebard-panel").css("min-height", heightWithoutNavbar + "px");
+ }
+ fix_height();
+
+ // Fixed Sidebar
+ // unComment this only whe you have a fixed-sidebar
+ // $(window).bind("load", function() {
+ // if($("body").hasClass('fixed-sidebar')) {
+ // $('.sidebar-collapse').slimScroll({
+ // height: 'auto',
+ // railOpacity: 0.9,
+ // });
+ // }
+ // })
+
+ $(window).bind("load resize click scroll", function() {
+ if(!$("body").hasClass('body-small')) {
+ fix_height();
+ }
+ })
+
+ $("[data-toggle=popover]")
+ .popover();
+});
+
+
+// For demo purpose - animation css script
+function animationHover(element, animation){
+ element = $(element);
+ element.hover(
+ function() {
+ element.addClass('animated ' + animation);
+ },
+ function(){
+ //wait for animation to finish before removing classes
+ window.setTimeout( function(){
+ element.removeClass('animated ' + animation);
+ }, 2000);
+ });
+}
+
+// Minimalize menu when screen is less than 768px
+$(function() {
+ $(window).bind("load resize", function() {
+ if ($(this).width() < 769) {
+ $('body').addClass('body-small')
+ } else {
+ $('body').removeClass('body-small')
+ }
+ })
+})
+
+function SmoothlyMenu() {
+ if (!$('body').hasClass('mini-navbar') || $('body').hasClass('body-small')) {
+ // Hide menu in order to smoothly turn on when maximize menu
+ $('#side-menu').hide();
+ // For smoothly turn on menu
+ setTimeout(
+ function () {
+ $('#side-menu').fadeIn(500);
+ }, 100);
+ } else if ($('body').hasClass('fixed-sidebar')){
+ $('#side-menu').hide();
+ setTimeout(
+ function () {
+ $('#side-menu').fadeIn(500);
+ }, 300);
+ } else {
+ // Remove all inline style from jquery fadeIn function to reset menu state
+ $('#side-menu').removeAttr('style');
+ }
+}
+
+// Dragable panels
+function WinMove() {
+ var element = "[class*=col]";
+ var handle = ".ibox-title";
+ var connect = "[class*=col]";
+ $(element).sortable(
+ {
+ handle: handle,
+ connectWith: connect,
+ tolerance: 'pointer',
+ forcePlaceholderSize: true,
+ opacity: 0.8,
+ })
+ .disableSelection();
+}
+
+// Checkbox select all
+function selectAll(){
+ var checklist = document.getElementsByName ("selected");
+ if(document.getElementById("select_all").checked)
+ {
+ for(var i=0;ia?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+Math.random()}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)
+},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthx",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*\s*$/g,ib={option:[1,""],thead:[1,""],col:[2,""],tr:[2,""],td:[3,""],_default:[0,"",""]};ib.optgroup=ib.option,ib.tbody=ib.tfoot=ib.colgroup=ib.caption=ib.thead,ib.th=ib.td;function jb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=ob(h),f=ob(a),d=0,e=f.length;e>d;d++)pb(f[d],g[d]);if(b)if(c)for(f=f||ob(a),g=g||ob(h),d=0,e=f.length;e>d;d++)nb(f[d],g[d]);else nb(a,h);return g=ob(h,"script"),g.length>0&&mb(g,!i&&ob(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(cb.test(e)){f=f||k.appendChild(b.createElement("div")),g=(bb.exec(e)||["",""])[1].toLowerCase(),h=ib[g]||ib._default,f.innerHTML=h[1]+e.replace(ab,"<$1>$2>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=ob(k.appendChild(e),"script"),i&&mb(f),c)){j=0;while(e=f[j++])fb.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(ob(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&mb(ob(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(ob(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!db.test(a)&&!ib[(bb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ab,"<$1>$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ob(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(ob(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&eb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(ob(c,"script"),kb),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,ob(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,lb),j=0;g>j;j++)h=f[j],fb.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(hb,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qb,rb={};function sb(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function tb(a){var b=l,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||n("")).appendTo(b.documentElement),b=qb[0].contentDocument,b.write(),b.close(),c=sb(a,b),qb.detach()),rb[a]=c),c}var ub=/^margin/,vb=new RegExp("^("+Q+")(?!px)[a-z%]+$","i"),wb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)};function xb(a,b,c){var d,e,f,g,h=a.style;return c=c||wb(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),vb.test(g)&&ub.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function yb(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d=l.documentElement,e=l.createElement("div"),f=l.createElement("div");if(f.style){f.style.backgroundClip="content-box",f.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===f.style.backgroundClip,e.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute",e.appendChild(f);function g(){f.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",f.innerHTML="",d.appendChild(e);var g=a.getComputedStyle(f,null);b="1%"!==g.top,c="4px"===g.width,d.removeChild(e)}a.getComputedStyle&&n.extend(k,{pixelPosition:function(){return g(),b},boxSizingReliable:function(){return null==c&&g(),c},reliableMarginRight:function(){var b,c=f.appendChild(l.createElement("div"));return c.style.cssText=f.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",f.style.width="1px",d.appendChild(e),b=!parseFloat(a.getComputedStyle(c,null).marginRight),d.removeChild(e),b}})}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var zb=/^(none|table(?!-c[ea]).+)/,Ab=new RegExp("^("+Q+")(.*)$","i"),Bb=new RegExp("^([+-])=("+Q+")","i"),Cb={position:"absolute",visibility:"hidden",display:"block"},Db={letterSpacing:"0",fontWeight:"400"},Eb=["Webkit","O","Moz","ms"];function Fb(a,b){if(b in a)return b;var c=b[0].toUpperCase()+b.slice(1),d=b,e=Eb.length;while(e--)if(b=Eb[e]+c,b in a)return b;return d}function Gb(a,b,c){var d=Ab.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Hb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+R[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+R[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+R[f]+"Width",!0,e))):(g+=n.css(a,"padding"+R[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+R[f]+"Width",!0,e)));return g}function Ib(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wb(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xb(a,b,f),(0>e||null==e)&&(e=a.style[b]),vb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Hb(a,b,c||(g?"border":"content"),d,f)+"px"}function Jb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=L.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&S(d)&&(f[g]=L.access(d,"olddisplay",tb(d.nodeName)))):(e=S(d),"none"===c&&e||L.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=xb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Fb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=Bb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Fb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=xb(a,b,d)),"normal"===e&&b in Db&&(e=Db[b]),""===c||c?(f=parseFloat(e),c===!0||n.isNumeric(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?zb.test(n.css(a,"display"))&&0===a.offsetWidth?n.swap(a,Cb,function(){return Ib(a,b,d)}):Ib(a,b,d):void 0},set:function(a,c,d){var e=d&&wb(a);return Gb(a,c,d?Hb(a,b,d,"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),n.cssHooks.marginRight=yb(k.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},xb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+R[d]+b]=f[d]||f[d-2]||f[0];return e}},ub.test(a)||(n.cssHooks[a+b].set=Gb)}),n.fn.extend({css:function(a,b){return J(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=wb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Jb(this,!0)},hide:function(){return Jb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){S(this)?n(this).show():n(this).hide()})}});function Kb(a,b,c,d,e){return new Kb.prototype.init(a,b,c,d,e)}n.Tween=Kb,Kb.prototype={constructor:Kb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Kb.propHooks[this.prop];return a&&a.get?a.get(this):Kb.propHooks._default.get(this)},run:function(a){var b,c=Kb.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Kb.propHooks._default.set(this),this}},Kb.prototype.init.prototype=Kb.prototype,Kb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Kb.propHooks.scrollTop=Kb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=Kb.prototype.init,n.fx.step={};var Lb,Mb,Nb=/^(?:toggle|show|hide)$/,Ob=new RegExp("^(?:([+-])=|)("+Q+")([a-z%]*)$","i"),Pb=/queueHooks$/,Qb=[Vb],Rb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Ob.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&Ob.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function Sb(){return setTimeout(function(){Lb=void 0}),Lb=n.now()}function Tb(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=R[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ub(a,b,c){for(var d,e=(Rb[b]||[]).concat(Rb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Vb(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&S(a),q=L.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?L.get(a,"olddisplay")||tb(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Nb.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?tb(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=L.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;L.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ub(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Wb(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function Xb(a,b,c){var d,e,f=0,g=Qb.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Lb||Sb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:Lb||Sb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(Wb(k,j.opts.specialEasing);g>f;f++)if(d=Qb[f].call(j,a,k,j.opts))return d;return n.map(k,Ub,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(Xb,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],Rb[c]=Rb[c]||[],Rb[c].unshift(b)},prefilter:function(a,b){b?Qb.unshift(a):Qb.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(S).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=Xb(this,n.extend({},a),f);(e||L.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=L.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Pb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=L.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Tb(b,!0),a,d,e)}}),n.each({slideDown:Tb("show"),slideUp:Tb("hide"),slideToggle:Tb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(Lb=n.now();b1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===U?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?Zb:Yb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))
+},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Zb={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=$b[b]||n.find.attr;$b[b]=function(a,b,d){var e,f;return d||(f=$b[b],$b[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$b[b]=f),e}});var _b=/^(?:input|select|textarea|button)$/i;n.fn.extend({prop:function(a,b){return J(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){return a.hasAttribute("tabindex")||_b.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),k.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var ac=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ac," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ac," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===U||"boolean"===c)&&(this.className&&L.set(this,"__className__",this.className),this.className=this.className||a===!1?"":L.get(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ac," ").indexOf(b)>=0)return!0;return!1}});var bc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(bc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(d.value,f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},k.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var cc=n.now(),dc=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){var b,c;if(!a||"string"!=typeof a)return null;try{c=new DOMParser,b=c.parseFromString(a,"text/xml")}catch(d){b=void 0}return(!b||b.getElementsByTagName("parsererror").length)&&n.error("Invalid XML: "+a),b};var ec,fc,gc=/#.*$/,hc=/([?&])_=[^&]*/,ic=/^(.*?):[ \t]*([^\r\n]*)$/gm,jc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,kc=/^(?:GET|HEAD)$/,lc=/^\/\//,mc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,nc={},oc={},pc="*/".concat("*");try{fc=location.href}catch(qc){fc=l.createElement("a"),fc.href="",fc=fc.href}ec=mc.exec(fc.toLowerCase())||[];function rc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function sc(a,b,c,d){var e={},f=a===oc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function tc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function uc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function vc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:fc,type:"GET",isLocal:jc.test(ec[1]),global:!0,processData:!0,async:!0,contentType:"applications/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":pc,text:"text/plain",html:"text/html",xml:"applications/xml, text/xml",json:"applications/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?tc(tc(a,n.ajaxSettings),b):tc(n.ajaxSettings,a)},ajaxPrefilter:rc(nc),ajaxTransport:rc(oc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!f){f={};while(b=ic.exec(e))f[b[1].toLowerCase()]=b[2]}b=f[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?e:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return c&&c.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||fc)+"").replace(gc,"").replace(lc,ec[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(h=mc.exec(k.url.toLowerCase()),k.crossDomain=!(!h||h[1]===ec[1]&&h[2]===ec[2]&&(h[3]||("http:"===h[1]?"80":"443"))===(ec[3]||("http:"===ec[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),sc(nc,k,b,v),2===t)return v;i=k.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!kc.test(k.type),d=k.url,k.hasContent||(k.data&&(d=k.url+=(dc.test(d)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=hc.test(d)?d.replace(hc,"$1_="+cc++):d+(dc.test(d)?"&":"?")+"_="+cc++)),k.ifModified&&(n.lastModified[d]&&v.setRequestHeader("If-Modified-Since",n.lastModified[d]),n.etag[d]&&v.setRequestHeader("If-None-Match",n.etag[d])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+pc+"; q=0.01":""):k.accepts["*"]);for(j in k.headers)v.setRequestHeader(j,k.headers[j]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(j in{success:1,error:1,complete:1})v[j](k[j]);if(c=sc(oc,k,b,v)){v.readyState=1,i&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,c.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,f,h){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),c=void 0,e=h||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,f&&(u=uc(k,v,f)),u=vc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[d]=w),w=v.getResponseHeader("etag"),w&&(n.etag[d]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,i&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),i&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var wc=/%20/g,xc=/\[\]$/,yc=/\r?\n/g,zc=/^(?:submit|button|image|reset|file)$/i,Ac=/^(?:input|select|textarea|keygen)/i;function Bc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||xc.test(a)?d(a,e):Bc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Bc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Bc(c,a[c],b,e);return d.join("&").replace(wc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Ac.test(this.nodeName)&&!zc.test(a)&&(this.checked||!T.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(yc,"\r\n")}}):{name:b.name,value:c.replace(yc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Cc=0,Dc={},Ec={0:200,1223:204},Fc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Dc)Dc[a]()}),k.cors=!!Fc&&"withCredentials"in Fc,k.ajax=Fc=!!Fc,n.ajaxTransport(function(a){var b;return k.cors||Fc&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Cc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)f.setRequestHeader(e,c[e]);b=function(a){return function(){b&&(delete Dc[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Ec[f.status]||f.status,f.statusText,"string"==typeof f.responseText?{text:f.responseText}:void 0,f.getAllResponseHeaders()))}},f.onload=b(),f.onerror=b("error"),b=Dc[g]=b("abort");try{f.send(a.hasContent&&a.data||null)}catch(h){if(b)throw h}},abort:function(){b&&b()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, applications/javascript, applications/ecmascript, applications/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(d,e){b=n("
+ {% block custom_head_css_js_create %} {% endblock %}
+{% endblock %}
+
+{% block content %}
+
+
+
+
+
+
+ {% if form.errors.all %}
+
+ {{ form.errors.all }}
+
+ {% endif %}
+ {% block form %}
+ {% endblock %}
+
+
+
+
+
+{% endblock %}
+
diff --git a/apps/templates/_base_list.html b/apps/templates/_base_list.html
new file mode 100644
index 000000000..f88abd9ac
--- /dev/null
+++ b/apps/templates/_base_list.html
@@ -0,0 +1,78 @@
+{% extends 'base.html' %}
+{% load static %}
+{% block custom_head_css_js %}
+
+
+
+
+
+{% endblock %}
+{% block content %}
+
+
+
+
+
+
+
+ {% block content_left_head %} {% endblock %}
+ {% block table_search %}
+
+ {% endblock %}
+ {% block tags_list %}{% endblock %}
+
+ {% block table_container %}
+
+
+
+ {% block table_head %} {% endblock %}
+
+
+
+ {% block table_body %} {% endblock %}
+
+
+ {% endblock %}
+
+
+ {# Update batch #}
+ {% block content_bottom_left %} {% endblock %}
+
+ {% block table_pagination %}
+ {% include '_pagination.html' %}
+ {% endblock %}
+
+
+
+
+
+
+{% endblock %}
diff --git a/apps/templates/_foot_js.html b/apps/templates/_foot_js.html
new file mode 100644
index 000000000..660e6c434
--- /dev/null
+++ b/apps/templates/_foot_js.html
@@ -0,0 +1,19 @@
+{% load i18n %}
+{% load static %}
+
+
+
+
+
+
+
+
diff --git a/apps/templates/_footer.html b/apps/templates/_footer.html
new file mode 100644
index 000000000..c43bda248
--- /dev/null
+++ b/apps/templates/_footer.html
@@ -0,0 +1,8 @@
+
\ No newline at end of file
diff --git a/apps/templates/_head_css_js.html b/apps/templates/_head_css_js.html
new file mode 100644
index 000000000..fbde7e9cd
--- /dev/null
+++ b/apps/templates/_head_css_js.html
@@ -0,0 +1,15 @@
+{% load static %}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apps/templates/_header_bar.html b/apps/templates/_header_bar.html
new file mode 100644
index 000000000..419ca717f
--- /dev/null
+++ b/apps/templates/_header_bar.html
@@ -0,0 +1,57 @@
+{% load i18n %}
+
+
+
diff --git a/apps/templates/_left_side_bar.html b/apps/templates/_left_side_bar.html
new file mode 100644
index 000000000..0d58e79a2
--- /dev/null
+++ b/apps/templates/_left_side_bar.html
@@ -0,0 +1,12 @@
+
diff --git a/apps/templates/_message.html b/apps/templates/_message.html
new file mode 100644
index 000000000..8eb061661
--- /dev/null
+++ b/apps/templates/_message.html
@@ -0,0 +1,7 @@
+{% if messages %}
+ {% for message in messages %}
+
+ {{ message|safe }}
+
+ {% endfor %}
+{% endif %}
diff --git a/apps/templates/_modal.html b/apps/templates/_modal.html
new file mode 100644
index 000000000..ad7f21ccc
--- /dev/null
+++ b/apps/templates/_modal.html
@@ -0,0 +1,20 @@
+{% load i18n %}
+
+
+
+
+
+ {% block modal_body %}
+ {% endblock %}
+
+
+
+
+
diff --git a/apps/templates/_nav.html b/apps/templates/_nav.html
new file mode 100644
index 000000000..92b9c5894
--- /dev/null
+++ b/apps/templates/_nav.html
@@ -0,0 +1,94 @@
+{% load i18n %}
+
+
+ {% trans 'Home' %}
+
+
+
+
+ {% trans 'Users' %}
+
+
+
+
+
+ {% trans 'Assets' %}
+
+
+
+
+ {% trans 'Perms' %}
+
+
+
+
+
+ {% trans 'Applications' %}
+
+
+
+
+
+
+ {% trans 'Job Center' %}
+
+
+
+
+
+ {% trans 'Audits' %}
+
+
+
+
+ {% trans 'File' %}
+
+
+
+
+
+ {% trans 'Settings' %}
+
+
+
+
+ {% trans 'Visit us' %}
+
+
\ No newline at end of file
diff --git a/apps/templates/_nav_user.html b/apps/templates/_nav_user.html
new file mode 100644
index 000000000..3c9f48f95
--- /dev/null
+++ b/apps/templates/_nav_user.html
@@ -0,0 +1,29 @@
+
+
+ 仪表盘
+
+
+
+
+ 我的资产
+
+
+
+
+ 上传下载
+
+
+
+
+
+ 用户信息
+
+
+
+
+ 访问官网
+
+
\ No newline at end of file
diff --git a/apps/templates/_pagination.html b/apps/templates/_pagination.html
new file mode 100644
index 000000000..c5f4ccb0c
--- /dev/null
+++ b/apps/templates/_pagination.html
@@ -0,0 +1,58 @@
+{% load common_tags %}
+ {% if is_paginated %}
+
+
+ 显示第 {{ page_obj.start_index }} 至 {{ page_obj.end_index }} 项结果,共 {{ paginator.count }} 项
+
+
+
+ {% endif %}
+
diff --git a/apps/templates/_user_profile.html b/apps/templates/_user_profile.html
new file mode 100644
index 000000000..d47ba6537
--- /dev/null
+++ b/apps/templates/_user_profile.html
@@ -0,0 +1,27 @@
+{% load static %}
+{% load i18n %}
+
diff --git a/apps/templates/base.html b/apps/templates/base.html
new file mode 100644
index 000000000..2cead306e
--- /dev/null
+++ b/apps/templates/base.html
@@ -0,0 +1,52 @@
+{% load static i18n %}
+
+
+
+
+
+
+
+ Jumpserver
+
+
+ {% include '_head_css_js.html' %}
+
+ {% block custom_head_css_js %} {% endblock %}
+
+
+
+
+
+ {% include '_left_side_bar.html' %}
+
+ {% include '_header_bar.html' %}
+ {% include '_message.html' %}
+ {% block first_login_message %}
+ {% if user.is_authenticated and user.is_first_login %}
+
+ {% url 'users:user-first-login' as first_login_url %}
+ {% blocktrans %}
+ Your information was incomplete. Please click
this link to complete your information.
+ {% endblocktrans %}
+
+ {% endif %}
+ {% endblock %}
+ {% block update_public_key_message %}
+ {% if user.is_authenticated and not user.is_public_key_valid %}
+
+ {% url 'users:user-profile' as profile_url %}
+ {% blocktrans %}
+ Your ssh-public-key has been expired. Please click
this link to update your ssh-public-key.
+ {% endblocktrans %}
+
+ {% endif %}
+ {% endblock %}
+ {% block content %}{% endblock %}
+ {% include '_footer.html' %}
+
+
+
+
+{% include '_foot_js.html' %}
+{% block custom_foot_js %} {% endblock %}
+
diff --git a/apps/templates/captcha/field.html b/apps/templates/captcha/field.html
new file mode 100644
index 000000000..6979e870c
--- /dev/null
+++ b/apps/templates/captcha/field.html
@@ -0,0 +1,12 @@
+{{image}}{{hidden_field}}{{text_field}}
+
+
\ No newline at end of file
diff --git a/apps/templates/captcha/hidden_field.html b/apps/templates/captcha/hidden_field.html
new file mode 100644
index 000000000..36d7490a3
--- /dev/null
+++ b/apps/templates/captcha/hidden_field.html
@@ -0,0 +1 @@
+
diff --git a/apps/templates/captcha/image.html b/apps/templates/captcha/image.html
new file mode 100644
index 000000000..b4a415536
--- /dev/null
+++ b/apps/templates/captcha/image.html
@@ -0,0 +1,4 @@
+{% load i18n %}
+{% spaceless %}
+ {% if audio %}{% endif %}{% if audio %}{% endif %}
+{% endspaceless %}
\ No newline at end of file
diff --git a/apps/templates/captcha/text_field.html b/apps/templates/captcha/text_field.html
new file mode 100644
index 000000000..413eb1893
--- /dev/null
+++ b/apps/templates/captcha/text_field.html
@@ -0,0 +1,7 @@
+{% load i18n %}
+
+
diff --git a/apps/templates/flash_message_standalone.html b/apps/templates/flash_message_standalone.html
new file mode 100644
index 000000000..e7cb481f7
--- /dev/null
+++ b/apps/templates/flash_message_standalone.html
@@ -0,0 +1,77 @@
+{% load static %}
+
+
+
+
+
+
+
+ {{ title }}
+
+ {% include '_head_css_js.html' %}
+
+
+
+
+
+
+
+
+
+
+
+
+
Jumpserver
+
+ {% if errors %}
+
+
+ {{ errors }}
+
+
+ {% endif %}
+
+ {% if messages %}
+
+
+ {{ messages }}
+
+
+ {% endif %}
+
+
+
+
+
+
+
+ Copyright Jumpserver.org
+
+
+ 2014-2016
+
+
+
+
+
+
diff --git a/apps/templates/index.html b/apps/templates/index.html
new file mode 100644
index 000000000..e69de29bb
diff --git a/apps/templates/rest_framework/base.html b/apps/templates/rest_framework/base.html
new file mode 100644
index 000000000..7f5170a62
--- /dev/null
+++ b/apps/templates/rest_framework/base.html
@@ -0,0 +1,285 @@
+{% load staticfiles %}
+{% load i18n %}
+{% load rest_framework %}
+
+
+
+
+ {% block head %}
+
+ {% block meta %}
+
+
+ {% endblock %}
+
+ {% block title %}{% if name %}{{ name }} – {% endif %}Django REST framework{% endblock %}
+
+ {% block style %}
+ {% block bootstrap_theme %}
+
+
+ {% endblock %}
+
+
+
+ {% endblock %}
+
+ {% endblock %}
+
+
+ {% block body %}
+
+
+
+ {% block navbar %}
+
+
+
+ {% block branding %}
+
+ Django REST framework
+
+ {% endblock %}
+
+
+ {% block userlinks %}
+ {% if user.is_authenticated %}
+ {% optional_logout request user %}
+ {% else %}
+ {% optional_login request %}
+ {% endif %}
+ {% endblock %}
+
+
+
+ {% endblock %}
+
+
+ {% block breadcrumbs %}
+
+ {% endblock %}
+
+
+
+
+ {% if 'GET' in allowed_methods %}
+
+ {% endif %}
+
+ {% if options_form %}
+
+ {% endif %}
+
+ {% if delete_form %}
+
+
+
+
+
+
+
+
Are you sure you want to delete this {{ name }}?
+
+
+
+
+
+ {% endif %}
+
+ {% if filter_form %}
+
+ {% endif %}
+
+
+
+
+ {% block description %}
+ {{ description }}
+ {% endblock %}
+
+
+ {% if paginator %}
+
+ {% endif %}
+
+
+
{{ request.method }} {{ request.get_full_path }}
+
+
+
+
HTTP {{ response.status_code }} {{ response.status_text }}{% autoescape off %}
+ {% for key, val in response_headers.items %}{{ key }}: {{ val|break_long_headers|urlize_quoted_links }}
+ {% endfor %}
+ {{ content|urlize_quoted_links }}
{% endautoescape %}
+
+
+
+ {% if display_edit_forms %}
+ {% if post_form or raw_data_post_form %}
+
+ {% if post_form %}
+
+ {% endif %}
+
+
+ {% if post_form %}
+
+ {% with form=post_form %}
+
+ {% endwith %}
+
+ {% endif %}
+
+
+ {% with form=raw_data_post_form %}
+
+ {% endwith %}
+
+
+
+ {% endif %}
+
+ {% if put_form or raw_data_put_form or raw_data_patch_form %}
+
+ {% if put_form %}
+
+ {% endif %}
+
+
+ {% if put_form %}
+
+ {% endif %}
+
+
+ {% with form=raw_data_put_or_patch_form %}
+
+ {% endwith %}
+
+
+
+ {% endif %}
+ {% endif %}
+
+
+
+
+ {% if filter_form %}
+ {{ filter_form }}
+ {% endif %}
+
+ {% block script %}
+
+
+
+
+
+
+
+
+ {% endblock %}
+
+
+ {% endblock %}
+
diff --git a/apps/users/__init__.py b/apps/users/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/apps/users/api.py b/apps/users/api.py
new file mode 100644
index 000000000..895cba9fa
--- /dev/null
+++ b/apps/users/api.py
@@ -0,0 +1,140 @@
+# ~*~ coding: utf-8 ~*~
+
+from rest_framework import generics
+from rest_framework.permissions import AllowAny
+from rest_framework.response import Response
+from rest_framework.views import APIView
+from rest_framework_bulk import BulkModelViewSet
+
+from . import serializers
+from .hands import write_login_log_async
+from .models import User, UserGroup
+from .permissions import IsSuperUser, IsValidUser, IsCurrentUserOrReadOnly
+from .utils import check_user_valid, generate_token
+from common.mixins import IDInFilterMixin
+from common.utils import get_logger
+
+
+logger = get_logger(__name__)
+
+
+class UserViewSet(IDInFilterMixin, BulkModelViewSet):
+ queryset = User.objects.all()
+ serializer_class = serializers.UserSerializer
+ permission_classes = (IsSuperUser,)
+ # filter_backends = (DjangoFilterBackend,)
+ filter_fields = ('username', 'email', 'name', 'id')
+
+
+class UserUpdateGroupApi(generics.RetrieveUpdateAPIView):
+ queryset = User.objects.all()
+ serializer_class = serializers.UserUpdateGroupSerializer
+ permission_classes = (IsSuperUser,)
+
+
+class UserResetPasswordApi(generics.UpdateAPIView):
+ queryset = User.objects.all()
+ serializer_class = serializers.UserSerializer
+
+ def perform_update(self, serializer):
+ # Note: we are not updating the user object here.
+ # We just do the reset-password stuff.
+ import uuid
+ from .utils import send_reset_password_mail
+ user = self.get_object()
+ user.password_raw = str(uuid.uuid4())
+ user.save()
+ send_reset_password_mail(user)
+
+
+class UserResetPKApi(generics.UpdateAPIView):
+ queryset = User.objects.all()
+ serializer_class = serializers.UserSerializer
+
+ def perform_update(self, serializer):
+ from .utils import send_reset_ssh_key_mail
+ user = self.get_object()
+ user.is_public_key_valid = False
+ user.save()
+ send_reset_ssh_key_mail(user)
+
+
+class UserUpdatePKApi(generics.UpdateAPIView):
+ queryset = User.objects.all()
+ serializer_class = serializers.UserPKUpdateSerializer
+ permission_classes = (IsCurrentUserOrReadOnly,)
+
+ def perform_update(self, serializer):
+ user = self.get_object()
+ user.public_key = serializer.validated_data['_public_key']
+ user.save()
+
+
+class UserGroupViewSet(IDInFilterMixin, BulkModelViewSet):
+ queryset = UserGroup.objects.all()
+ serializer_class = serializers.UserGroupSerializer
+
+
+class UserGroupUpdateUserApi(generics.RetrieveUpdateAPIView):
+ queryset = UserGroup.objects.all()
+ serializer_class = serializers.UserGroupUpdateMemeberSerializer
+ permission_classes = (IsSuperUser,)
+
+
+class UserToken(APIView):
+ permission_classes = (AllowAny,)
+
+ def post(self, request):
+ if not request.user:
+ username = request.data.get('username', '')
+ email = request.data.get('email', '')
+ password = request.data.get('password', '')
+ public_key = request.data.get('public_key', '')
+
+ user, msg = check_user_valid(
+ username=username, email=email,
+ password=password, public_key=public_key)
+ else:
+ user = request.user
+ msg = None
+ if user:
+ token = generate_token(request, user)
+ return Response({'Token': token, 'Keyword': 'Bearer'}, status=200)
+ else:
+ return Response({'error': msg}, status=406)
+
+
+class UserProfile(APIView):
+ permission_classes = (IsValidUser,)
+
+ def get(self, request):
+ return Response(request.user.to_json())
+
+ def post(self, request):
+ return Response(request.user.to_json())
+
+
+class UserAuthApi(APIView):
+ permission_classes = (AllowAny,)
+
+ def post(self, request):
+ username = request.data.get('username', '')
+ password = request.data.get('password', '')
+ public_key = request.data.get('public_key', '')
+ login_type = request.data.get('login_type', '')
+ login_ip = request.data.get('remote_addr', None)
+ user_agent = request.data.get('HTTP_USER_AGENT', '')
+
+ user, msg = check_user_valid(
+ username=username, password=password,
+ public_key=public_key)
+
+ if user:
+ token = generate_token(request, user)
+ write_login_log_async.delay(
+ user.username, name=user.name,
+ user_agent=user_agent, login_ip=login_ip,
+ login_type=login_type)
+ return Response({'token': token, 'user': user.to_json()})
+ else:
+ return Response({'msg': msg}, status=401)
diff --git a/apps/users/apps.py b/apps/users/apps.py
new file mode 100644
index 000000000..af3dddf8e
--- /dev/null
+++ b/apps/users/apps.py
@@ -0,0 +1,8 @@
+from __future__ import unicode_literals
+
+from django.apps import AppConfig
+
+
+class UsersConfig(AppConfig):
+ name = 'users'
+
diff --git a/apps/users/authentication.py b/apps/users/authentication.py
new file mode 100644
index 000000000..b8e2601e6
--- /dev/null
+++ b/apps/users/authentication.py
@@ -0,0 +1,159 @@
+# -*- coding: utf-8 -*-
+#
+
+import base64
+import uuid
+import hashlib
+import time
+
+from django.core.cache import cache
+from django.conf import settings
+from django.utils.translation import ugettext as _
+from django.utils.six import text_type
+from django.utils.translation import ugettext_lazy as _
+from rest_framework import HTTP_HEADER_ENCODING
+from rest_framework import authentication, exceptions, permissions
+from rest_framework.authentication import CSRFCheck
+
+from common.utils import get_object_or_none, make_signature, http_to_unixtime
+from .utils import refresh_token
+from .models import User, AccessKey, PrivateToken
+
+
+def get_request_date_header(request):
+ date = request.META.get('HTTP_DATE', b'')
+ if isinstance(date, text_type):
+ # Work around django test client oddness
+ date = date.encode(HTTP_HEADER_ENCODING)
+ return date
+
+
+class AccessKeyAuthentication(authentication.BaseAuthentication):
+ """App使用Access key进行签名认证, 目前签名算法比较简单,
+ app注册或者手动建立后,会生成 access_key_id 和 access_key_secret,
+ 然后使用 如下算法生成签名:
+ Signature = md5(access_key_secret + '\n' + Date)
+ example: Signature = md5('d32d2b8b-9a10-4b8d-85bb-1a66976f6fdc' + '\n' +
+ 'Thu, 12 Jan 2017 08:19:41 GMT')
+ 请求时设置请求header
+ header['Authorization'] = 'Sign access_key_id:Signature' 如:
+ header['Authorization'] =
+ 'Sign d32d2b8b-9a10-4b8d-85bb-1a66976f6fdc:OKOlmdxgYPZ9+SddnUUDbQ=='
+
+ 验证时根据相同算法进行验证, 取到access_key_id对应的access_key_id, 从request
+ headers取到Date, 然后进行md5, 判断得到的结果是否相同, 如果是认证通过, 否则 认证
+ 失败
+ """
+ keyword = 'Sign'
+ model = AccessKey
+
+ def authenticate(self, request):
+ auth = authentication.get_authorization_header(request).split()
+
+ if not auth or auth[0].lower() != self.keyword.lower().encode():
+ return None
+
+ if len(auth) == 1:
+ msg = _('Invalid signature header. No credentials provided.')
+ raise exceptions.AuthenticationFailed(msg)
+ elif len(auth) > 2:
+ msg = _('Invalid signature header. Signature '
+ 'string should not contain spaces.')
+ raise exceptions.AuthenticationFailed(msg)
+
+ try:
+ sign = auth[1].decode().split(':')
+ if len(sign) != 2:
+ msg = _('Invalid signature header. '
+ 'Format like AccessKeyId:Signature')
+ raise exceptions.AuthenticationFailed(msg)
+ except UnicodeError:
+ msg = _('Invalid signature header. '
+ 'Signature string should not contain invalid characters.')
+ raise exceptions.AuthenticationFailed(msg)
+
+ access_key_id = sign[0]
+ try:
+ uuid.UUID(access_key_id)
+ except ValueError:
+ raise exceptions.AuthenticationFailed('Access key id invalid')
+ request_signature = sign[1]
+
+ return self.authenticate_credentials(
+ request, access_key_id, request_signature)
+
+ @staticmethod
+ def authenticate_credentials(request, access_key_id, request_signature):
+ access_key = get_object_or_none(AccessKey, id=access_key_id)
+ request_date = get_request_date_header(request)
+ if access_key is None or not access_key.user:
+ raise exceptions.AuthenticationFailed(_('Invalid signature.'))
+ access_key_secret = access_key.secret
+
+ try:
+ request_unix_time = http_to_unixtime(request_date)
+ except ValueError:
+ raise exceptions.AuthenticationFailed(
+ _('HTTP header: Date not provide '
+ 'or not %a, %d %b %Y %H:%M:%S GMT'))
+
+ if int(time.time()) - request_unix_time > 15 * 60:
+ raise exceptions.AuthenticationFailed(
+ _('Expired, more than 15 minutes'))
+
+ signature = make_signature(access_key_secret, request_date)
+ if not signature == request_signature:
+ raise exceptions.AuthenticationFailed(_('Invalid signature.'))
+
+ if not access_key.user.is_active:
+ raise exceptions.AuthenticationFailed(_('User disabled.'))
+ return access_key.user, None
+
+
+class AccessTokenAuthentication(authentication.BaseAuthentication):
+ keyword = 'Bearer'
+ model = User
+ expiration = settings.CONFIG.TOKEN_EXPIRATION or 3600
+
+ def authenticate(self, request):
+ auth = authentication.get_authorization_header(request).split()
+ if not auth or auth[0].lower() != self.keyword.lower().encode():
+ return None
+
+ if len(auth) == 1:
+ msg = _('Invalid token header. No credentials provided.')
+ raise exceptions.AuthenticationFailed(msg)
+ elif len(auth) > 2:
+ msg = _('Invalid token header. Sign string '
+ 'should not contain spaces.')
+ raise exceptions.AuthenticationFailed(msg)
+
+ try:
+ token = auth[1].decode()
+ except UnicodeError:
+ msg = _('Invalid token header. Sign string '
+ 'should not contain invalid characters.')
+ raise exceptions.AuthenticationFailed(msg)
+ return self.authenticate_credentials(token)
+
+ @staticmethod
+ def authenticate_credentials(token):
+ user_id = cache.get(token)
+ user = get_object_or_none(User, id=user_id)
+
+ if not user:
+ msg = _('Invalid token or cache refreshed.')
+ raise exceptions.AuthenticationFailed(msg)
+ refresh_token(token, user)
+ return user, None
+
+
+class PrivateTokenAuthentication(authentication.TokenAuthentication):
+ model = PrivateToken
+
+
+class SessionAuthentication(authentication.SessionAuthentication):
+ def enforce_csrf(self, request):
+ reason = CSRFCheck().process_view(request, None, (), {})
+ if reason:
+ raise exceptions.AuthenticationFailed(reason)
diff --git a/apps/users/forms.py b/apps/users/forms.py
new file mode 100644
index 000000000..5521713fc
--- /dev/null
+++ b/apps/users/forms.py
@@ -0,0 +1,137 @@
+# ~*~ coding: utf-8 ~*~
+
+from django import forms
+from django.contrib.auth.forms import AuthenticationForm
+from django.utils.translation import gettext_lazy as _
+from captcha.fields import CaptchaField
+
+from common.utils import validate_ssh_public_key
+from perms.models import AssetPermission
+from .models import User, UserGroup
+
+
+class UserLoginForm(AuthenticationForm):
+ username = forms.CharField(label=_('Username'), max_length=100)
+ password = forms.CharField(
+ label=_('Password'), widget=forms.PasswordInput, max_length=100,
+ strip=False)
+ captcha = CaptchaField()
+
+
+class UserCreateUpdateForm(forms.ModelForm):
+ class Meta:
+ model = User
+ fields = [
+ 'username', 'name', 'email', 'groups', 'wechat',
+ 'phone', 'enable_otp', 'role', 'date_expired', 'comment',
+ ]
+ help_texts = {
+ 'username': '* required',
+ 'name': '* required',
+ 'email': '* required',
+ }
+ widgets = {
+ 'groups': forms.SelectMultiple(
+ attrs={'class': 'select2',
+ 'data-placeholder': _('Join user groups')}),
+ }
+
+
+class UserBulkImportForm(forms.ModelForm):
+ class Meta:
+ model = User
+ fields = ['username', 'email', 'enable_otp', 'role']
+
+
+class UserGroupForm(forms.ModelForm):
+ class Meta:
+ model = UserGroup
+ fields = [
+ 'name', 'comment'
+ ]
+ help_texts = {
+ 'name': '* required'
+ }
+
+
+class UserInfoForm(forms.Form):
+ name = forms.CharField(max_length=20, label=_('name'))
+ avatar = forms.ImageField(label=_('avatar'), required=False)
+ wechat = forms.CharField(max_length=30, label=_('wechat'), required=False)
+ phone = forms.CharField(max_length=20, label=_('phone'), required=False)
+ enable_otp = forms.BooleanField(required=False, label=_('enable otp'))
+
+
+class UserKeyForm(forms.Form):
+ public_key = forms.CharField(
+ label=_('ssh public key'), max_length=5000,
+ widget=forms.Textarea(attrs={'placeholder': _('ssh-rsa AAAA...')}),
+ help_text=_('Paste your id_rsa.pub here.'))
+
+ def clean_public_key(self):
+ public_key = self.cleaned_data['public_key']
+ if self.user.public_key and public_key == self.user.public_key:
+ raise forms.ValidationError(_('Public key should not be the '
+ 'same as your old one.'))
+
+ if not validate_ssh_public_key(public_key):
+ raise forms.ValidationError(_('Not a valid ssh public key'))
+ return public_key
+
+
+class UserPrivateAssetPermissionForm(forms.ModelForm):
+
+ def save(self, commit=True):
+ self.instance = super(UserPrivateAssetPermissionForm, self)\
+ .save(commit=commit)
+ self.instance.users = [self.user]
+ self.instance.save()
+ return self.instance
+
+ class Meta:
+ model = AssetPermission
+ fields = [
+ 'assets', 'asset_groups', 'system_users', 'name',
+ ]
+ widgets = {
+ 'assets': forms.SelectMultiple(
+ attrs={'class': 'select2',
+ 'data-placeholder': _('Select assets')}),
+ 'asset_groups': forms.SelectMultiple(
+ attrs={'class': 'select2',
+ 'data-placeholder': _('Select asset groups')}),
+ 'system_users': forms.SelectMultiple(
+ attrs={'class': 'select2',
+ 'data-placeholder': _('Select system users')}),
+ }
+
+
+class UserGroupPrivateAssetPermissionForm(forms.ModelForm):
+
+ def save(self, commit=True):
+ self.instance = super(UserGroupPrivateAssetPermissionForm, self)\
+ .save(commit=commit)
+ self.instance.user_groups = [self.user_group]
+ self.instance.save()
+ return self.instance
+
+ class Meta:
+ model = AssetPermission
+ fields = [
+ 'assets', 'asset_groups', 'system_users', 'name',
+ ]
+ widgets = {
+ 'assets': forms.SelectMultiple(
+ attrs={'class': 'select2',
+ 'data-placeholder': _('Select assets')}),
+ 'asset_groups': forms.SelectMultiple(
+ attrs={'class': 'select2',
+ 'data-placeholder': _('Select asset groups')}),
+ 'system_users': forms.SelectMultiple(
+ attrs={'class': 'select2',
+ 'data-placeholder': _('Select system users')}),
+ }
+
+
+class FileForm(forms.Form):
+ file = forms.FileField()
diff --git a/apps/users/hands.py b/apps/users/hands.py
new file mode 100644
index 000000000..825f41f33
--- /dev/null
+++ b/apps/users/hands.py
@@ -0,0 +1,17 @@
+"""
+ jumpserver.__app__.hands.py
+ ~~~~~~~~~~~~~~~~~
+
+ This app depends other apps api, function .. should be import or write mack here.
+
+ Other module of this app shouldn't connect with other app.
+
+ :copyright: (c) 2014-2016 by Jumpserver Team.
+ :license: GPL v2, see LICENSE for more details.
+"""
+
+from applications.models import Terminal
+from audits.tasks import write_login_log_async
+from users.models import User
+# from perms.models import AssetPermission
+# from perms.utils import get_user_granted_assets, get_user_granted_asset_groups
diff --git a/apps/users/migrations/__init__.py b/apps/users/migrations/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/apps/users/models/__init__.py b/apps/users/models/__init__.py
new file mode 100644
index 000000000..9cdf1d61d
--- /dev/null
+++ b/apps/users/models/__init__.py
@@ -0,0 +1,7 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+
+from .group import *
+from .user import *
+from .authentication import *
diff --git a/apps/users/models/authentication.py b/apps/users/models/authentication.py
new file mode 100644
index 000000000..917bc1114
--- /dev/null
+++ b/apps/users/models/authentication.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+
+import uuid
+from django.db import models
+from django.utils.translation import ugettext_lazy as _
+from rest_framework.authtoken.models import Token
+from . import User
+
+__all__ = ['AccessKey', 'PrivateToken']
+
+
+class AccessKey(models.Model):
+ id = models.UUIDField(verbose_name='AccessKeyID', primary_key=True,
+ default=uuid.uuid4, editable=False)
+ secret = models.UUIDField(verbose_name='AccessKeySecret',
+ default=uuid.uuid4, editable=False)
+ user = models.ForeignKey(User, verbose_name='User',
+ related_name='access_key')
+
+ def get_id(self):
+ return str(self.id)
+
+ def get_secret(self):
+ return str(self.secret)
+
+ def __unicode__(self):
+ return str(self.id)
+
+ __str__ = __unicode__
+
+
+class PrivateToken(Token):
+ """Inherit from auth token, otherwise migration is boring"""
+
+ class Meta:
+ verbose_name = _('Private Token')
diff --git a/apps/users/models/group.py b/apps/users/models/group.py
new file mode 100644
index 000000000..939ddeaf8
--- /dev/null
+++ b/apps/users/models/group.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+
+from __future__ import unicode_literals
+
+from django.db import models, IntegrityError
+from django.contrib.auth.models import Group
+from django.utils.translation import ugettext_lazy as _
+
+from common.utils import signer, date_expired_default
+from common.mixins import NoDeleteModelMixin
+
+__all__ = ['UserGroup']
+
+
+class UserGroup(NoDeleteModelMixin, Group):
+ comment = models.TextField(blank=True, verbose_name=_('Comment'))
+ date_created = models.DateTimeField(auto_now_add=True, null=True)
+ created_by = models.CharField(max_length=100)
+
+ def __unicode__(self):
+ return self.name
+
+ def delete(self, using=None, keep_parents=False):
+ self.group_ptr.delete()
+ if self.name != 'Default':
+ self.users.clear()
+ return super(UserGroup, self).delete()
+ return True
+
+ class Meta:
+ ordering = ['name']
+
+ @classmethod
+ def initial(cls):
+ group, created = cls.objects.get_or_create(
+ name='Default', created_by='System',
+ comment='Default user group for all user')
+ return group
+
+ @classmethod
+ def generate_fake(cls, count=100):
+ from random import seed, choice
+ import forgery_py
+ from . import User
+
+ seed()
+ for i in range(count):
+ group = cls(name=forgery_py.name.full_name(),
+ comment=forgery_py.lorem_ipsum.sentence(),
+ created_by=choice(User.objects.all()).username)
+ try:
+ group.save()
+ except IntegrityError:
+ print('Error continue')
+ continue
diff --git a/apps/users/models/user.py b/apps/users/models/user.py
new file mode 100644
index 000000000..8b079fe5c
--- /dev/null
+++ b/apps/users/models/user.py
@@ -0,0 +1,268 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+import os
+
+from collections import OrderedDict
+
+from django.conf import settings
+from django.contrib.auth.hashers import make_password
+from django.contrib.auth.models import AbstractUser
+from django.core import signing
+from django.db import models
+from django.utils.translation import ugettext_lazy as _
+from django.utils import timezone
+from django.shortcuts import reverse
+
+from . import UserGroup
+from common.utils import signer, date_expired_default
+
+
+__all__ = ['User']
+
+
+class User(AbstractUser):
+ ROLE_CHOICES = (
+ ('Admin', _('Administrator')),
+ ('User', _('User')),
+ ('App', _('Application'))
+ )
+
+ username = models.CharField(max_length=20, unique=True, verbose_name=_('Username'))
+ name = models.CharField(max_length=20, verbose_name=_('Name'))
+ email = models.EmailField(max_length=30, unique=True, verbose_name=_('Email'))
+ groups = models.ManyToManyField(UserGroup, related_name='users', blank=True, verbose_name=_('User group'))
+ role = models.CharField(choices=ROLE_CHOICES, default='User', max_length=10, blank=True, verbose_name=_('Role'))
+ avatar = models.ImageField(upload_to="avatar", verbose_name=_('Avatar'))
+ wechat = models.CharField(max_length=30, blank=True, verbose_name=_('Wechat'))
+ phone = models.CharField(max_length=20, blank=True, null=True, verbose_name=_('Phone'))
+ enable_otp = models.BooleanField(default=False, verbose_name=_('Enable OTP'))
+ secret_key_otp = models.CharField(max_length=16, blank=True)
+ _private_key = models.CharField(max_length=5000, blank=True, verbose_name=_('ssh private key'))
+ _public_key = models.CharField(max_length=1000, blank=True, verbose_name=_('ssh public key'))
+ comment = models.TextField(max_length=200, blank=True, verbose_name=_('Comment'))
+ is_first_login = models.BooleanField(default=False)
+ date_expired = models.DateTimeField(default=date_expired_default, blank=True, null=True,
+ verbose_name=_('Date expired'))
+ created_by = models.CharField(max_length=30, default='', verbose_name=_('Created by'))
+
+ @property
+ def password_raw(self):
+ raise AttributeError('Password raw is not a readable attribute')
+
+ #: Use this attr to set user object password, example
+ #: user = User(username='example', password_raw='password', ...)
+ #: It's equal:
+ #: user = User(username='example', ...)
+ #: user.set_password('password')
+ @password_raw.setter
+ def password_raw(self, password_raw_):
+ self.set_password(password_raw_)
+
+ def get_absolute_url(self):
+ return reverse('users:user-detail', args=(self.id,))
+
+ def is_public_key_valid(self):
+ """
+ Check if the user's ssh public key is valid.
+ This function is used in base.html.
+ """
+ if self._public_key:
+ return True
+ return False
+
+ @property
+ def is_expired(self):
+ if self.date_expired < timezone.now():
+ return True
+ else:
+ return False
+
+ @property
+ def is_valid(self):
+ if self.is_active and not self.is_expired:
+ return True
+ return False
+
+ @property
+ def private_key(self):
+ return signer.unsign(self._private_key)
+
+ @private_key.setter
+ def private_key(self, private_key_raw):
+ self._private_key = signer.sign(private_key_raw)
+
+ @property
+ def public_key(self):
+ return signer.unsign(self._public_key)
+
+ @public_key.setter
+ def public_key(self, public_key_raw):
+ self._public_key = signer.sign(public_key_raw)
+
+ @property
+ def is_superuser(self):
+ if self.role == 'Admin':
+ return True
+ else:
+ return False
+
+ @is_superuser.setter
+ def is_superuser(self, value):
+ if value is True:
+ self.role = 'Admin'
+ else:
+ self.role = 'User'
+
+ @property
+ def is_app(self):
+ return self.role == 'App'
+
+ @property
+ def is_staff(self):
+ if self.is_authenticated and self.is_valid:
+ return True
+ else:
+ return False
+
+ @is_staff.setter
+ def is_staff(self, value):
+ pass
+
+ def save(self, *args, **kwargs):
+ if not self.name:
+ self.name = self.username
+
+ super(User, self).save(*args, **kwargs)
+ # Add the current user to the default group.
+ if not self.groups.count():
+ group = UserGroup.initial()
+ self.groups.add(group)
+
+ @property
+ def private_token(self):
+ return self.create_private_token()
+
+ def create_private_token(self):
+ from .authentication import PrivateToken
+ try:
+ token = PrivateToken.objects.get(user=self)
+ except PrivateToken.DoesNotExist:
+ token = PrivateToken.objects.create(user=self)
+ return token.key
+
+ def refresh_private_token(self):
+ from .authentication import PrivateToken
+ PrivateToken.objects.filter(user=self).delete()
+ return PrivateToken.objects.create(user=self)
+
+ def is_member_of(self, user_group):
+ if user_group in self.groups.all():
+ return True
+ return False
+
+ def check_public_key(self, public_key):
+ if self.ssH_public_key == public_key:
+ return True
+ return False
+
+ def avatar_url(self):
+ if self.avatar:
+ return self.avatar.url
+ else:
+ default_dir = os.path.join(settings.MEDIA_ROOT, 'avatar', 'default')
+ if os.path.isdir(default_dir):
+ default_avatar_list = os.listdir(default_dir)
+ default_avatar = default_avatar_list[len(self.username) % len(default_avatar_list)]
+ return os.path.join(settings.MEDIA_URL, 'avatar', 'default', default_avatar)
+ return 'https://www.gravatar.com/avatar/c6812ab450230979465d7bf288eadce2a?s=120&d=identicon'
+
+ def generate_reset_token(self):
+ return signer.sign_t({'reset': self.id, 'email': self.email}, expires_in=3600)
+
+ def to_json(self):
+ return OrderedDict({
+ 'id': self.id,
+ 'username': self.username,
+ 'name': self.name,
+ 'email': self.email,
+ 'is_active': self.is_active,
+ 'is_superuser': self.is_superuser,
+ 'role': self.get_role_display(),
+ 'groups': [group.name for group in self.groups.all()],
+ 'wechat': self.wechat,
+ 'phone': self.phone,
+ 'comment': self.comment,
+ 'date_expired': self.date_expired.strftime('%Y-%m-%d %H:%M:%S')
+ })
+
+ @classmethod
+ def create_app_user(cls, name, comment):
+ from . import AccessKey
+ domain_name = settings.CONFIG.DOMAIN_NAME or 'jumpserver.org'
+ app = cls.objects.create(username=name, name=name, email='%s@%s' % (name, domain_name), is_active=False,
+ role='App', enable_otp=False, comment=comment, is_first_login=False,
+ created_by='System')
+ access_key = AccessKey.objects.create(user=app)
+ return app, access_key
+
+ @classmethod
+ def validate_reset_token(cls, token):
+ try:
+ data = signer.unsign_t(token)
+ user_id = data.get('reset', None)
+ user_email = data.get('email', '')
+ user = cls.objects.get(id=user_id, email=user_email)
+
+ except (signing.BadSignature, cls.DoesNotExist):
+ user = None
+ return user
+
+ def reset_password(self, new_password):
+ self.set_password(new_password)
+ self.save()
+
+ def delete(self):
+ if self.pk == 1 or self.username == 'admin':
+ return
+ return super(User, self).delete()
+
+ class Meta:
+ ordering = ['username']
+
+ #: Use this method initial user
+ @classmethod
+ def initial(cls):
+ user = cls(username='admin',
+ email='admin@jumpserver.org',
+ name=_('Administrator'),
+ password_raw='admin',
+ role='Admin',
+ comment=_('Administrator is the super user of system'),
+ created_by=_('System'))
+ user.save()
+ user.groups.add(UserGroup.initial())
+
+ @classmethod
+ def generate_fake(cls, count=100):
+ from random import seed, choice
+ import forgery_py
+ from django.db import IntegrityError
+
+ seed()
+ for i in range(count):
+ user = cls(username=forgery_py.internet.user_name(True),
+ email=forgery_py.internet.email_address(),
+ name=forgery_py.name.full_name(),
+ password=make_password(forgery_py.lorem_ipsum.word()),
+ role=choice(dict(User.ROLE_CHOICES).keys()),
+ wechat=forgery_py.internet.user_name(True),
+ comment=forgery_py.lorem_ipsum.sentence(),
+ created_by=choice(cls.objects.all()).username)
+ try:
+ user.save()
+ except IntegrityError:
+ print('Duplicate Error, continue ...')
+ continue
+ user.groups.add(choice(UserGroup.objects.all()))
+ user.save()
diff --git a/apps/users/models/utils.py b/apps/users/models/utils.py
new file mode 100644
index 000000000..8a9b6c370
--- /dev/null
+++ b/apps/users/models/utils.py
@@ -0,0 +1,17 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+
+from . import User, UserGroup
+
+
+def initial_model():
+ for cls in [User, UserGroup]:
+ if getattr(cls, 'initial'):
+ cls.initial()
+
+
+def generate_fake():
+ for cls in [User, UserGroup]:
+ if getattr(cls, 'generate_fake'):
+ cls.generate_fake()
diff --git a/apps/users/permissions.py b/apps/users/permissions.py
new file mode 100644
index 000000000..d543b9a45
--- /dev/null
+++ b/apps/users/permissions.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from rest_framework import permissions
+
+
+class IsValidUser(permissions.IsAuthenticated, permissions.BasePermission):
+ """Allows access to valid user, is active and not expired"""
+
+ def has_permission(self, request, view):
+ return super(IsValidUser, self).has_permission(request, view) \
+ and request.user.is_valid
+
+
+class IsAppUser(IsValidUser, permissions.BasePermission):
+ """Allows access only to app user """
+
+ def has_permission(self, request, view):
+ return super(IsAppUser, self).has_permission(request, view) \
+ and request.user.is_app
+
+
+class IsSuperUser(IsValidUser, permissions.BasePermission):
+ """Allows access only to superuser"""
+
+ def has_permission(self, request, view):
+ return super(IsSuperUser, self).has_permission(request, view) \
+ and request.user.is_superuser
+
+
+class IsSuperUserOrAppUser(IsValidUser, permissions.BasePermission):
+ """Allows access between superuser and app user"""
+
+ def has_permission(self, request, view):
+ return super(IsSuperUserOrAppUser, self).has_permission(request, view) \
+ and (request.user.is_superuser or request.user.is_app)
+
+
+class IsCurrentUserOrReadOnly(permissions.BasePermission):
+
+ def has_object_permission(self, request, view, obj):
+ if request.method in permissions.SAFE_METHODS:
+ return True
+ return obj == request.user
diff --git a/apps/users/serializers.py b/apps/users/serializers.py
new file mode 100644
index 000000000..880d3b21e
--- /dev/null
+++ b/apps/users/serializers.py
@@ -0,0 +1,113 @@
+# -*- coding: utf-8 -*-
+#
+from django.utils.translation import ugettext_lazy as _
+
+from rest_framework import serializers
+from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin
+
+from common.utils import signer, validate_ssh_public_key
+from .models import User, UserGroup
+
+
+class UserSerializer(BulkSerializerMixin, serializers.ModelSerializer):
+ groups_display = serializers.SerializerMethodField()
+ groups = serializers.PrimaryKeyRelatedField(many=True, queryset=UserGroup.objects.all())
+
+ class Meta:
+ model = User
+ list_serializer_class = BulkListSerializer
+ exclude = ['first_name', 'last_name', 'password', '_private_key', '_public_key']
+
+ def get_field_names(self, declared_fields, info):
+ fields = super(UserSerializer, self).get_field_names(declared_fields, info)
+ fields.extend(['groups_display', 'get_role_display', 'is_valid'])
+ return fields
+
+ @staticmethod
+ def get_groups_display(obj):
+ return " ".join([group.name for group in obj.groups.all()])
+
+
+class UserPKUpdateSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = User
+ fields = ['id', '_public_key']
+
+ @staticmethod
+ def validate__public_key(value):
+ if not validate_ssh_public_key(value):
+ print('Not a valid key')
+ print(value)
+ raise serializers.ValidationError(_('Not a valid ssh public key'))
+ return value
+
+
+class UserUpdateGroupSerializer(serializers.ModelSerializer):
+ groups = serializers.PrimaryKeyRelatedField(many=True, queryset=UserGroup.objects.all())
+
+ class Meta:
+ model = User
+ fields = ['id', 'groups']
+
+
+class UserGroupSerializer(BulkSerializerMixin, serializers.ModelSerializer):
+ user_amount = serializers.SerializerMethodField()
+
+ class Meta:
+ model = UserGroup
+ list_serializer_class = BulkListSerializer
+ fields = '__all__'
+
+ @staticmethod
+ def get_user_amount(obj):
+ return obj.users.count()
+
+
+class UserGroupUpdateMemeberSerializer(serializers.ModelSerializer):
+ users = serializers.PrimaryKeyRelatedField(many=True, queryset=User.objects.all())
+
+ class Meta:
+ model = UserGroup
+ fields = ['id', 'users']
+
+
+# class GroupDetailSerializer(serializers.ModelSerializer):
+# class Meta:
+# model = UserGroup
+# fields = ['id', 'name', 'comment', 'date_created', 'created_by', 'users']
+
+
+# class UserBulkUpdateSerializer(BulkSerializerMixin, serializers.ModelSerializer):
+# group_display = serializers.SerializerMethodField()
+# active_display = serializers.SerializerMethodField()
+# groups = serializers.PrimaryKeyRelatedField(many=True, queryset=UserGroup.objects.all())
+#
+# class Meta(object):
+# model = User
+# list_serializer_class = BulkListSerializer
+# fields = ['id', 'is_active', 'username', 'name', 'email', 'role', 'avatar',
+# 'enable_otp', 'comment', 'groups', 'get_role_display',
+# 'group_display', 'active_display']
+#
+# @staticmethod
+# def get_group_display(obj):
+# return " ".join([group.name for group in obj.groups.all()])
+#
+# @staticmethod
+# def get_active_display(obj):
+# TODO: user active state
+ # return not (obj.is_expired and obj.is_active)
+#
+#
+# class GroupBulkUpdateSerializer(BulkSerializerMixin, serializers.ModelSerializer):
+# user_amount = serializers.SerializerMethodField()
+#
+# class Meta:
+# model = UserGroup
+# list_serializer_class = BulkListSerializer
+# fields = ['id', 'name', 'comment', 'user_amount']
+#
+# @staticmethod
+# def get_user_amount(obj):
+# return obj.users.count()
+#
diff --git a/apps/users/templates/users/_select_user_modal.html b/apps/users/templates/users/_select_user_modal.html
new file mode 100644
index 000000000..5395b0a05
--- /dev/null
+++ b/apps/users/templates/users/_select_user_modal.html
@@ -0,0 +1,23 @@
+{% extends '_modal.html' %}
+{% load i18n %}
+{% block modal_class %}modal-lg{% endblock %}
+{% block modal_id %}select_user_modal{% endblock %}
+{% block modal_title%}{% trans "Please Select User" %}{% endblock %}
+{% block modal_body %}
+
+{% endblock %}
+{% block modal_confirm_id %}btn_select_user{% endblock %}
diff --git a/apps/users/templates/users/_user.html b/apps/users/templates/users/_user.html
new file mode 100644
index 000000000..118ab8d2e
--- /dev/null
+++ b/apps/users/templates/users/_user.html
@@ -0,0 +1,71 @@
+{% extends '_base_create_update.html' %}
+{% load i18n %}
+{% load static %}
+{% load bootstrap %}
+{% block form %}
+ {% if form.non_field_errors %}
+
+ {{ form.non_field_errors }}
+
+ {% endif %}
+
+{% endblock %}
+{% block custom_foot_js %}
+
+
+{% endblock %}
diff --git a/apps/users/templates/users/_user_bulk_update_modal.html b/apps/users/templates/users/_user_bulk_update_modal.html
new file mode 100644
index 000000000..40ab6efb1
--- /dev/null
+++ b/apps/users/templates/users/_user_bulk_update_modal.html
@@ -0,0 +1,37 @@
+{% extends '_modal.html' %}
+{% load i18n %}
+{% block modal_id %}user_bulk_update_modal{% endblock %}
+{% block modal_title%}{% trans "Update User" %}{% endblock %}
+{% block modal_body %}
+{% trans "Hint: only change the field you want to update." %}
+
+{% endblock %}
+{% block modal_confirm_id %}btn_user_bulk_update{% endblock %}
diff --git a/apps/users/templates/users/_user_import_modal.html b/apps/users/templates/users/_user_import_modal.html
new file mode 100644
index 000000000..3e56c6a47
--- /dev/null
+++ b/apps/users/templates/users/_user_import_modal.html
@@ -0,0 +1,27 @@
+{% extends '_modal.html' %}
+{% load i18n %}
+{% block modal_id %}user_import_modal{% endblock %}
+{% block modal_title%}{% trans "Import user" %}{% endblock %}
+{% block modal_body %}
+{% trans "Download template or use export excel format" %}
+
+
+
+
+
+
+
+
+
+{% endblock %}
+{% block modal_confirm_id %}btn_user_import{% endblock %}
diff --git a/apps/users/templates/users/_user_update_pk_modal.html b/apps/users/templates/users/_user_update_pk_modal.html
new file mode 100644
index 000000000..a7ed525c4
--- /dev/null
+++ b/apps/users/templates/users/_user_update_pk_modal.html
@@ -0,0 +1,8 @@
+{% extends '_modal.html' %}
+{% load i18n %}
+{% block modal_id %}user_update_pk_modal{% endblock %}
+{% block modal_title%}{% trans "Update User SSH Public Key" %}{% endblock %}
+{% block modal_body %}
+
+{% endblock %}
+{% block modal_confirm_id %}btn_user_update_pk{% endblock %}
diff --git a/apps/users/templates/users/first_login.html b/apps/users/templates/users/first_login.html
new file mode 100644
index 000000000..80b13cec2
--- /dev/null
+++ b/apps/users/templates/users/first_login.html
@@ -0,0 +1,82 @@
+{% extends 'base.html' %}
+{% load static %}
+{% load i18n %}
+{% load bootstrap %}
+
+
+{% block custom_head_css_js %}
+{{ wizard.form.media }}
+
+{% endblock %}
+{% block first_login_message %}{% endblock %}
+{% block content %}
+
+
+
+
+
+
{% trans 'First Login' %}
+
+
+
+
+
+
+
+{% endblock %}
+{% block custom_foot_js %}
+
+{% endblock %}
diff --git a/apps/users/templates/users/forgot_password.html b/apps/users/templates/users/forgot_password.html
new file mode 100644
index 000000000..e435485da
--- /dev/null
+++ b/apps/users/templates/users/forgot_password.html
@@ -0,0 +1,65 @@
+{% load static %}
+{% load i18n %}
+
+
+
+
+
+
+
+
+ 忘记密码
+
+ {% include '_head_css_js.html' %}
+
+
+
+
+
+
+
+
+
+
+
+
+
{% trans 'Forgot password' %} ?
+
+
+ {% if errors %}
+
{{ errors }}
+ {% endif %}
+
+ {% trans 'Input your email, that will send a mail to your' %}
+
+
+
+
+
+
+
+
+
+ Copyright Jumpserver.org
+
+
+ © 2014-2016
+
+
+
+
+
+
+
diff --git a/apps/users/templates/users/login.html b/apps/users/templates/users/login.html
new file mode 100644
index 000000000..455e15eb7
--- /dev/null
+++ b/apps/users/templates/users/login.html
@@ -0,0 +1,86 @@
+{% load static %}
+{% load i18n %}
+
+
+
+
+
+
+ JumpServer
+
+ {% include '_head_css_js.html' %}
+
+
+
+
+
+
+
+
+
+
欢迎使用Jumpserver开源跳板机
+
+ Jumpserver是一款使用Python, Django开发的开源跳板机系统, 助力互联网企业高效 用户、资产、权限、审计 管理
+
+
+ 我们自五湖四海,我们对开源精神无比敬仰和崇拜,我们对完美、整洁、优雅 无止境的追求
+
+
+ 专注自动化运维,努力打造 易用、稳定、安全、自动化 的跳板机, 这是我们的不懈的追求和动力
+
+
+ 永远年轻,永远热泪盈眶 stay foolish stay hungry
+
+
+
+
+
+
{% trans 'Login' %}
+
+
+
+
+
+
+
+
+
+ Copyright Jumpserver.org
+
+
+ © 2014-2016
+
+
+
+
+
diff --git a/apps/users/templates/users/reset_password.html b/apps/users/templates/users/reset_password.html
new file mode 100644
index 000000000..50a1443e2
--- /dev/null
+++ b/apps/users/templates/users/reset_password.html
@@ -0,0 +1,85 @@
+{% load static %}
+{% load i18n %}
+
+
+
+
+
+
+ JumpServer
+
+ {% include '_head_css_js.html' %}
+
+
+
+
+
+
+
+
+
+
+
+
+
欢迎使用Jumpserver开源跳板机
+
+
+ Jumpserver是一款使用Python, Django开发的开源跳板机系统, 助力互联网企业高效 用户、资产、权限、审计 管理
+
+
+
+ 我们自五湖四海,我们对开源精神无比敬仰和崇拜,我们对完美、整洁、优雅 无止境的追求
+
+
+
+ 专注自动化运维,努力打造 易用、稳定、安全、自动化 的跳板机, 这是我们的不懈的追求和动力
+
+
+
+ 永远年轻,永远热泪盈眶 stay foolish stay hungry
+
+
+
+
+
+
{% trans 'Reset password' %}
+
+
+
+
+
+
+
+
+
+ Copyright Jumpserver.org
+
+
+ © 2014-2016
+
+
+
+
+
+
+
+
diff --git a/apps/users/templates/users/user_asset_permission.html b/apps/users/templates/users/user_asset_permission.html
new file mode 100644
index 000000000..8b2f469b4
--- /dev/null
+++ b/apps/users/templates/users/user_asset_permission.html
@@ -0,0 +1,183 @@
+{% extends 'base.html' %}
+{% load bootstrap %}
+{% load static %}
+{% load i18n %}
+
+{% block custom_head_css_js %}
+
+
+{% endblock %}
+{% block content %}
+
+
+
+
+
+
+
+
+
+
{% trans 'Asset permission of ' %} {{ user.name }}
+
+
+
+
+
+
+
+
+ {% trans 'Quick create permission for user' %}
+
+
+
+
+
+
+
+
+
+
+{% endblock %}
+{% block custom_foot_js %}
+
+{% endblock %}
diff --git a/apps/users/templates/users/user_create.html b/apps/users/templates/users/user_create.html
new file mode 100644
index 000000000..9f3cba36e
--- /dev/null
+++ b/apps/users/templates/users/user_create.html
@@ -0,0 +1,16 @@
+{% extends 'users/_user.html' %}
+{% load i18n %}
+{% load bootstrap %}
+{% block user_template_title %}{% trans "Create user" %}{% endblock %}
+{#{% block username %}#}
+{# {{ form.username|bootstrap_horizontal }}#}
+{#{% endblock %}#}
+{% block password %}
+ {% trans 'Password' %}
+
+{% endblock %}
\ No newline at end of file
diff --git a/apps/users/templates/users/user_delete_confirm.html b/apps/users/templates/users/user_delete_confirm.html
new file mode 100644
index 000000000..777d1dbf9
--- /dev/null
+++ b/apps/users/templates/users/user_delete_confirm.html
@@ -0,0 +1,15 @@
+{% load i18n %}
+
+
+
+
+ {% trans 'Confirm delete' %}
+
+
+
+
+
\ No newline at end of file
diff --git a/apps/users/templates/users/user_detail.html b/apps/users/templates/users/user_detail.html
new file mode 100644
index 000000000..a459dac7f
--- /dev/null
+++ b/apps/users/templates/users/user_detail.html
@@ -0,0 +1,402 @@
+{% extends 'base.html' %}
+{% load static %}
+{% load i18n %}
+
+{% block custom_head_css_js %}
+
+
+
+
+{% endblock %}
+{% block content %}
+
+
+
+
+
+
+
+
+
+
{{ user_object.name }}
+
+
+
+
+
+
+
+
+ |
+
+
+ {% trans 'Name' %}: |
+ {{ user_object.name }} |
+
+
+ {% trans 'Username' %}: |
+ {{ user_object.username }} |
+
+
+ {% trans 'Email' %}: |
+ {{ user_object.email }} |
+
+ {% if user.phone %}
+
+ {% trans 'Phone' %}: |
+ {{ user_object.phone }} |
+
+ {% endif %}
+ {% if user_object.wechat %}
+
+ {% trans 'Wechat' %}: |
+ {{ user_object.wechat }} |
+
+ {% endif %}
+
+ {% trans 'Role' %}: |
+ {{ user_object.get_role_display }} |
+
+
+ {% trans 'Date expired' %}: |
+ {{ user_object.date_expired|date:"Y-m-j H:i:s" }} |
+
+
+ {% trans 'Created by' %}: |
+ {{ user_object.created_by }} |
+
+
+ {% trans 'Date joined' %}: |
+ {{ user_object.date_joined|date:"Y-m-j H:i:s" }} |
+
+
+ {% trans 'Last login' %}: |
+ {{ user_object.last_login|date:"Y-m-j H:i:s" }} |
+
+
+ {% trans 'Comment' %}: |
+ {{ user_object.comment }} |
+
+
+
+
+
+
+
+
+
+ {% trans 'Quick modify' %}
+
+
+
+
+
+ {% trans 'Active' %}: |
+
+
+ |
+
+
+ {% trans 'Enable OTP' %}: |
+
+
+ |
+
+
+ {% trans 'Reset password' %}: |
+
+
+
+
+ |
+
+
+ {% trans 'Reset ssh key' %}: |
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ {% trans 'User group' %}
+
+
+
+
+
+
+ {% for group in user_object.groups.all %}
+
+
+ {{ group.name }}
+ |
+
+
+ |
+
+ {% endfor %}
+
+
+
+
+
+
+
+
+
+
+ {% include 'users/_user_update_pk_modal.html' %}
+{% endblock %}
+{% block custom_foot_js %}
+
+{% endblock %}
diff --git a/apps/users/templates/users/user_granted_asset.html b/apps/users/templates/users/user_granted_asset.html
new file mode 100644
index 000000000..fbe02b4b2
--- /dev/null
+++ b/apps/users/templates/users/user_granted_asset.html
@@ -0,0 +1,156 @@
+{% extends 'base.html' %}
+{% load bootstrap %}
+{% load static %}
+{% load i18n %}
+
+{% block custom_head_css_js %}
+
+
+{% endblock %}
+{% block content %}
+
+
+
+
+
+
+
+
+
+
{% trans 'Assets granted of ' %} {{ user.name }}
+
+
+
+
+
+
+ |
+ {% trans 'Hostname' %} |
+ {% trans 'IP' %} |
+ {% trans 'Port' %} |
+ {% trans 'System user' %} |
+ {% trans 'Valid' %} |
+
+
+
+
+
+
+
+
+
+
+
+
{% trans 'Asset groups granted of ' %} {{ user.name }}
+
+
+
+
+
+
+ |
+ {% trans 'Name' %} |
+ {% trans 'Asset' %} |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+{% endblock %}
+{% block custom_foot_js %}
+
+{% endblock %}
diff --git a/apps/users/templates/users/user_group_asset_permission.html b/apps/users/templates/users/user_group_asset_permission.html
new file mode 100644
index 000000000..269f3fe91
--- /dev/null
+++ b/apps/users/templates/users/user_group_asset_permission.html
@@ -0,0 +1,181 @@
+{% extends 'base.html' %}
+{% load bootstrap %}
+{% load static %}
+{% load i18n %}
+
+{% block custom_head_css_js %}
+
+
+{% endblock %}
+{% block content %}
+
+
+
+
+
+
+
+
+
+
{% trans 'Asset permission of ' %} {{ user_group.name }}
+
+
+
+
+
+
+
+
+ {% trans 'Quick create permission for user group' %}
+
+
+
+
+
+
+
+
+
+
+{% endblock %}
+{% block custom_foot_js %}
+
+{% endblock %}
diff --git a/apps/users/templates/users/user_group_create_update.html b/apps/users/templates/users/user_group_create_update.html
new file mode 100644
index 000000000..3b6814860
--- /dev/null
+++ b/apps/users/templates/users/user_group_create_update.html
@@ -0,0 +1,62 @@
+{% extends 'base.html' %}
+{% load static %}
+{% load i18n %}
+{% load bootstrap %}
+{% block custom_head_css_js %}
+
+
+{% endblock %}
+
+{% block content %}
+
+
+
+
+
+
{{ action }}
+
+
+ {% if form.non_field_errors %}
+
+ {{ form.non_field_errors }}
+
+ {% endif %}
+
+
+
+
+
+
+ {% include "users/_select_user_modal.html" %}
+{% endblock %}
+{% block custom_foot_js %}
+
+{% endblock %}
diff --git a/apps/users/templates/users/user_group_detail.html b/apps/users/templates/users/user_group_detail.html
new file mode 100644
index 000000000..a27c4f91f
--- /dev/null
+++ b/apps/users/templates/users/user_group_detail.html
@@ -0,0 +1,201 @@
+{% extends 'base.html' %}
+{% load static %}
+{% load i18n %}
+
+{% block custom_head_css_js %}
+
+
+
+
+
+
+
+{% endblock %}
+{% block content %}
+
+
+
+
+
+
+
+
+
+
{{ user_group.name }}
+
+
+
+
+
+
+ {% trans 'Name' %}: |
+ {{ user_group.name }} |
+
+
+ {% trans 'Create by' %}: |
+ {{ user_group.created_by }} |
+
+
+ {% trans 'Date created' %}: |
+ {{ user_group.date_created }} |
+
+
+ {% trans 'Comment' %}: |
+ {{ user_group.comment }} |
+
+
+
+
+
+
+
+
+
+ {% trans 'User' %}
+
+
+
+
+
+
+ {% for user in user_group.users.all %}
+
+ {{ user.name }} |
+
+
+ |
+
+ {% endfor %}
+
+
+
+
+
+
+
+
+
+
+{% endblock %}
+{% block custom_foot_js %}
+
+{% endblock %}
diff --git a/apps/users/templates/users/user_group_granted_asset.html b/apps/users/templates/users/user_group_granted_asset.html
new file mode 100644
index 000000000..7c23dd0a6
--- /dev/null
+++ b/apps/users/templates/users/user_group_granted_asset.html
@@ -0,0 +1,156 @@
+{% extends 'base.html' %}
+{% load bootstrap %}
+{% load static %}
+{% load i18n %}
+
+{% block custom_head_css_js %}
+
+
+{% endblock %}
+{% block content %}
+
+
+
+
+
+
+
+
+
+
{% trans 'Assets granted of ' %} {{ user_group.name }}
+
+
+
+
+
+
+ |
+ {% trans 'Hostname' %} |
+ {% trans 'IP' %} |
+ {% trans 'Port' %} |
+ {% trans 'System user' %} |
+ {% trans 'Valid' %} |
+
+
+
+
+
+
+
+
+
+
+
+
{% trans 'Asset groups granted of ' %} {{ user_group.name }}
+
+
+
+
+
+
+ |
+ {% trans 'Name' %} |
+ {% trans 'Asset' %} |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+{% endblock %}
+{% block custom_foot_js %}
+
+{% endblock %}
diff --git a/apps/users/templates/users/user_group_list.html b/apps/users/templates/users/user_group_list.html
new file mode 100644
index 000000000..407ec3b5d
--- /dev/null
+++ b/apps/users/templates/users/user_group_list.html
@@ -0,0 +1,117 @@
+{% extends '_base_list.html' %}
+{% load i18n static %}
+{% block table_search %}{% endblock %}
+{% block table_container %}
+
+
+
+{% endblock %}
+
+{% block content_bottom_left %}{% endblock %}
+{% block custom_foot_js %}
+
+{% endblock %}
diff --git a/apps/users/templates/users/user_list.html b/apps/users/templates/users/user_list.html
new file mode 100644
index 000000000..f4a353bbd
--- /dev/null
+++ b/apps/users/templates/users/user_list.html
@@ -0,0 +1,250 @@
+{% extends '_base_list.html' %}
+{% load i18n static %}
+{% block table_search %}
+
+{% endblock %}
+{% block table_container %}
+
+{##}
+
+
+{% include "users/_user_bulk_update_modal.html" %}
+{% include "users/_user_import_modal.html" %}
+{% endblock %}
+{% block content_bottom_left %}{% endblock %}
+{% block custom_foot_js %}
+
+
+{% endblock %}
+
diff --git a/apps/users/templates/users/user_profile.html b/apps/users/templates/users/user_profile.html
new file mode 100644
index 000000000..8591c9078
--- /dev/null
+++ b/apps/users/templates/users/user_profile.html
@@ -0,0 +1,148 @@
+{% extends 'base.html' %}
+{% load static %}
+{% load i18n %}
+
+{% block custom_head_css_js %}
+
+
+{% endblock %}
+{% block content %}
+
+
+
+
+
+
+
+
+
+ 用户名 |
+ {{ user.username }} |
+
+
+ 姓名 |
+ {{ user.name }} |
+
+
+ 权限 |
+ {{ user.get_role_display }} |
+
+
+ Email |
+ {{ user.email }} |
+
+
+ 激活 |
+ {{ user.is_active }} |
+
+
+ 添加日期 |
+ {{ user.date_joined|date:"Y-m-d H:i:s" }} |
+
+
+ 最后登录 |
+ {{ user.last_login|date:"Y-m-d H:i:s" }} |
+
+
+ 所在用户组 |
+
+ {% for group in user.groups.all %}
+
+ {{ group.name }}
+
+ {% endfor %}
+ |
+
+
+ 授权主机数量 |
+ {{ assets | length }} |
+
+
+ 授权主机组 |
+
+ {% for group in asset_groups %}
+
+ {{ group.name }}
+
+ {% endfor %}
+ |
+
+
+ 授权规则 |
+
+ {% for perm in permissions %}
+
+ {{ perm.name }}
+
+ {% endfor %}
+ |
+
+
+
+
+
+
+
+
+
+
{% trans "Update Public Key" %}
+
+
+
+
{% trans "Paste your SSH Public Key here" %}
+
+
+
+
+
+
+
+{% endblock %}
+{% block custom_foot_js %}
+
+{% endblock %}
diff --git a/apps/users/templates/users/user_update.html b/apps/users/templates/users/user_update.html
new file mode 100644
index 000000000..95dbb680f
--- /dev/null
+++ b/apps/users/templates/users/user_update.html
@@ -0,0 +1,12 @@
+{% extends 'users/_user.html' %}
+{% load i18n %}
+{% block user_template_title %}{% trans "Update user" %}{% endblock %}
+{% block password %}
+ {% trans 'Password' %}
+
+{% endblock %}
diff --git a/apps/users/tests/__init__.py b/apps/users/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/apps/users/tests/base.py b/apps/users/tests/base.py
new file mode 100644
index 000000000..ff342f49a
--- /dev/null
+++ b/apps/users/tests/base.py
@@ -0,0 +1,24 @@
+# ~*~ coding: utf-8 ~*~
+
+
+from random import choice
+import forgery_py
+
+from users.models import User, UserGroup, init_all_models
+
+
+def gen_username():
+ return forgery_py.internet.user_name(True)
+
+
+def gen_email():
+ return forgery_py.internet.email_address()
+
+
+def gen_name():
+ return forgery_py.name.full_name()
+
+
+def get_role():
+ role = choice(dict(User.ROLE_CHOICES).keys())
+ return role
\ No newline at end of file
diff --git a/apps/users/tests/test_models.py b/apps/users/tests/test_models.py
new file mode 100644
index 000000000..e011aa209
--- /dev/null
+++ b/apps/users/tests/test_models.py
@@ -0,0 +1,95 @@
+# ~*~ coding: utf-8 ~*~
+
+
+from django.utils import timezone
+from django.shortcuts import reverse
+from django.test import TestCase, TransactionTestCase
+from django.db import IntegrityError
+from users.models import User, UserGroup, init_all_models
+from django.contrib.auth.models import Permission
+
+from .base import gen_name, gen_username, gen_email, get_role
+
+
+class UserModelTest(TransactionTestCase):
+ def setUp(self):
+ init_all_models()
+
+ # 创建一个用户用于测试
+ role = get_role()
+ user = User(name='test', username='test', email='test@email.org', role=role)
+ user.save()
+
+ def test_initial(self):
+ self.assertEqual(User.objects.all().count(), 2)
+
+ @property
+ def role(self):
+ return get_role()
+
+ # 创建一个姓名一致的用户, 应该创建成功
+ def test_user_name_duplicate(self):
+ user1 = User(name='test', username=gen_username(), password_raw=gen_username(),
+ email=gen_email())
+ try:
+ user1.save()
+ user1.delete()
+ except IntegrityError:
+ self.assertTrue(0, 'Duplicate not allowed.')
+
+ # 创建一个用户名一致的用户, 应该创建不成功
+ def test_user_username_duplicate(self):
+ user2 = User(username='test', email=gen_email(), role=self.role)
+
+ with self.assertRaises(IntegrityError):
+ user2.save()
+
+ # 创建一个Email一致的用户,应该创建不成功
+ def test_user_email_duplicate(self):
+ user3 = User(username=gen_username(), email='test@email.org', role=self.role)
+
+ with self.assertRaises(IntegrityError):
+ user3.save()
+
+ # 用户过期测试
+ def test_user_was_expired(self):
+ date = timezone.now() - timezone.timedelta(days=1)
+ user = User(name=gen_name(), username=gen_username(),
+ email=gen_email(), role=self.role, date_expired=date)
+
+ self.assertTrue(user.is_expired)
+
+ # 测试用户默认会输入All用户组
+ def test_user_with_default_group(self):
+ role = get_role()
+ user = User(username=gen_username(), email=gen_email(), role=role)
+ user.save()
+
+ self.assertEqual(user.groups.count(), 1)
+ self.assertEqual(user.groups.first().name, 'Default')
+
+ def test_user_password_authenticated(self):
+ password = gen_username() * 3
+ user = User(username=gen_username(), password_raw=password, role=self.role)
+ user.save()
+ self.assertTrue(user.check_password(password))
+ self.assertFalse(user.check_password(password*2))
+
+ def test_user_reset_password(self):
+ user = User.objects.first()
+ token = User.generate_reset_token(user.email)
+ new_password = gen_username()
+ User.reset_password(token, new_password)
+ user_ = User.objects.get(id=user.id)
+ self.assertTrue(user_.check_password(new_password))
+
+ def tearDown(self):
+ User.objects.all().delete()
+ UserGroup.objects.all().delete()
+
+
+class UserGroupModelTestCase(TransactionTestCase):
+ pass
+
+
+
diff --git a/apps/users/tests/test_views.py b/apps/users/tests/test_views.py
new file mode 100644
index 000000000..5fc2a062e
--- /dev/null
+++ b/apps/users/tests/test_views.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+
+from users.models import User, UserGroup, init_all_models
+from django.shortcuts import reverse
+from django.test import TestCase, Client, TransactionTestCase
+
+from .base import gen_username, gen_name, gen_email, get_role
+
+
+class UserListViewTests(TransactionTestCase):
+ def setUp(self):
+ init_all_models()
+ self.client.login(username='admin', password='admin')
+
+ def test_a_new_user_in_list(self):
+ username = gen_username()
+ user = User(username=username, email=gen_email(), role=get_role())
+ user.save()
+ response = self.client.get(reverse('users:user-list'))
+
+ self.assertContains(response, username)
+
+ def test_list_view_with_admin_user(self):
+ response = self.client.get(reverse('users:user-list'))
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, 'Admin')
+ self.assertEqual(response.context['user_list'].count(), User.objects.all().count())
+
+ def test_pagination(self):
+ User.generate_fake(count=20)
+ response = self.client.get(reverse('users:user-list'))
+ self.assertEqual(response.context['is_paginated'], True)
+
+ def tearDown(self):
+ self.client.logout()
+
+
+class UserAddTests(TestCase):
+ def setUp(self):
+ init_all_models()
+ self.client.login(username='admin', password='admin')
+
+ def test_add_a_new_user(self):
+ username = gen_username()
+ data = {
+ 'username': username,
+ 'comment': '',
+ 'name': gen_name(),
+ 'email': gen_email(),
+ 'groups': [UserGroup.objects.first().id, ],
+ 'role': get_role(),
+ 'date_expired': '2086-08-06 19:12:22',
+ }
+
+ response = self.client.post(reverse('users:user-create'), data)
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response['location'], reverse('users:user-list'))
+
+ response = self.client.get(reverse('users:user-list'))
+ self.assertContains(response, username)
+
+ def tearDown(self):
+ self.client.logout()
+
diff --git a/apps/users/urls/__init__.py b/apps/users/urls/__init__.py
new file mode 100644
index 000000000..8b1378917
--- /dev/null
+++ b/apps/users/urls/__init__.py
@@ -0,0 +1 @@
+
diff --git a/apps/users/urls/api_urls.py b/apps/users/urls/api_urls.py
new file mode 100644
index 000000000..eaae47556
--- /dev/null
+++ b/apps/users/urls/api_urls.py
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+# ~*~ coding: utf-8 ~*~
+#
+from __future__ import absolute_import
+
+from django.conf.urls import url
+from rest_framework_bulk.routes import BulkRouter
+from .. import api
+
+app_name = 'users'
+
+router = BulkRouter()
+router.register(r'v1/users', api.UserViewSet, 'user')
+router.register(r'v1/user-groups', api.UserGroupViewSet, 'user-group')
+
+
+urlpatterns = [
+ url(r'^v1/token/$', api.UserToken.as_view(), name='user-token'),
+ url(r'^v1/profile/$', api.UserProfile.as_view(), name='user-profile'),
+ url(r'^v1/auth/$', api.UserAuthApi.as_view(), name='user-auth'),
+ url(r'^v1/users/(?P\d+)/password/reset/$',
+ api.UserResetPasswordApi.as_view(), name='user-reset-password'),
+ url(r'^v1/users/(?P\d+)/public-key/reset/$',
+ api.UserResetPKApi.as_view(), name='user-public-key-reset'),
+ url(r'^v1/users/(?P\d+)/public-key/update/$',
+ api.UserUpdatePKApi.as_view(), name='user-public-key-update'),
+ url(r'^v1/users/(?P\d+)/groups/$',
+ api.UserUpdateGroupApi.as_view(), name='user-update-group'),
+ url(r'^v1/user-groups/(?P\d+)/users/$',
+ api.UserGroupUpdateUserApi.as_view(), name='user-group-update-user'),
+]
+
+urlpatterns += router.urls
diff --git a/apps/users/urls/views_urls.py b/apps/users/urls/views_urls.py
new file mode 100644
index 000000000..9ec2fecf6
--- /dev/null
+++ b/apps/users/urls/views_urls.py
@@ -0,0 +1,83 @@
+from __future__ import absolute_import
+
+from django.conf.urls import url
+
+from .. import views
+
+app_name = 'users'
+
+urlpatterns = [
+ # Login view
+ url(r'^login$', views.UserLoginView.as_view(), name='login'),
+ url(r'^logout$', views.UserLogoutView.as_view(), name='logout'),
+ url(r'^password/forgot$', views.UserForgotPasswordView.as_view(),
+ name='forgot-password'),
+ url(r'^password/forgot/sendmail-success$',
+ views.UserForgotPasswordSendmailSuccessView.as_view(),
+ name='forgot-password-sendmail-success'),
+ url(r'^password/reset$', views.UserResetPasswordView.as_view(),
+ name='reset-password'),
+ url(r'^password/reset/success$',
+ views.UserResetPasswordSuccessView.as_view(),
+ name='reset-password-success'),
+
+ # Profile
+ url(r'^profile/$',
+ views.UserProfileView.as_view(),
+ name='user-profile'),
+
+ # User view
+ url(r'^user$', views.UserListView.as_view(), name='user-list'),
+ url(r'^user/(?P[0-9]+)$', views.UserDetailView.as_view(),
+ name='user-detail'),
+ url(r'^user/(?P[0-9]+)/asset-permission$',
+ views.UserAssetPermissionView.as_view(),
+ name='user-asset-permission'),
+ url(r'^user/(?P[0-9]+)/asset-permission/create$',
+ views.UserAssetPermissionCreateView.as_view(),
+ name='user-asset-permission-create'),
+ url(r'^user/(?P[0-9]+)/assets',
+ views.UserGrantedAssetView.as_view(),
+ name='user-granted-asset'),
+ url(r'^user/(?P[0-9]+)/login-history',
+ views.UserDetailView.as_view(),
+ name='user-login-history'),
+ url(r'^user/export/',
+ views.UserExportView.as_view(),
+ name='user-export'),
+ url(r'^first-login/$',
+ views.UserFirstLoginView.as_view(),
+ name='user-first-login'),
+ url(r'^user/import/$',
+ views.UserBulkImportView.as_view(),
+ name='user-import'),
+ url(r'^user/create$',
+ views.UserCreateView.as_view(),
+ name='user-create'),
+ url(r'^user/(?P[0-9]+)/update$',
+ views.UserUpdateView.as_view(),
+ name='user-update'),
+
+ # User group view
+ url(r'^user-group$',
+ views.UserGroupListView.as_view(),
+ name='user-group-list'),
+ url(r'^user-group/(?P[0-9]+)$',
+ views.UserGroupDetailView.as_view(),
+ name='user-group-detail'),
+ url(r'^user-group/create$',
+ views.UserGroupCreateView.as_view(),
+ name='user-group-create'),
+ url(r'^user-group/(?P[0-9]+)/update$',
+ views.UserGroupUpdateView.as_view(),
+ name='user-group-update'),
+ url(r'^user-group/(?P[0-9]+)/asset-permission$',
+ views.UserGroupAssetPermissionView.as_view(),
+ name='user-group-asset-permission'),
+ url(r'^user-group/(?P[0-9]+)/asset-permission/create$',
+ views.UserGroupAssetPermissionCreateView.as_view(),
+ name='user-group-asset-permission-create'),
+ url(r'^user-group/(?P[0-9]+)/assets',
+ views.UserGroupGrantedAssetView.as_view(),
+ name='user-group-granted-asset'),
+]
diff --git a/apps/users/utils.py b/apps/users/utils.py
new file mode 100644
index 000000000..fdff529d5
--- /dev/null
+++ b/apps/users/utils.py
@@ -0,0 +1,173 @@
+# ~*~ coding: utf-8 ~*~
+#
+from __future__ import unicode_literals
+import base64
+import logging
+import os
+import re
+import uuid
+
+from django.conf import settings
+from django.contrib.auth.mixins import UserPassesTestMixin
+from django.urls import reverse_lazy
+from django.utils.translation import ugettext as _
+from django.core.cache import cache
+
+from paramiko.rsakey import RSAKey
+
+from common.tasks import send_mail_async
+from common.utils import reverse, get_object_or_none
+from .models import User
+
+
+try:
+ import cStringIO as StringIO
+except ImportError:
+ import StringIO
+
+
+logger = logging.getLogger('jumpserver')
+
+
+class AdminUserRequiredMixin(UserPassesTestMixin):
+ login_url = reverse_lazy('users:login')
+
+ def test_func(self):
+ return self.request.user.is_superuser
+
+
+def user_add_success_next(user):
+ subject = _('Create account successfully')
+ recipient_list = [user.email]
+ message = _("""
+ Hello %(name)s:
+
+ Your account has been created successfully
+
+ click here to set your password
+
+ This link is valid for 1 hour. After it expires, request new one
+
+
+ ---
+
+
+ Login direct
+
+
+ """) % {
+ 'name': user.name,
+ 'rest_password_url': reverse('users:reset-password', external=True),
+ 'rest_password_token': user.generate_reset_token(),
+ 'forget_password_url': reverse('users:forgot-password', external=True),
+ 'email': user.email,
+ 'login_url': reverse('users:login', external=True),
+ }
+
+ send_mail_async.delay(subject, message, recipient_list, html_message=message)
+
+
+def send_reset_password_mail(user):
+ subject = _('Reset password')
+ recipient_list = [user.email]
+ message = _("""
+ Hello %(name)s:
+
+ Please click the link below to reset your password, if not your request, concern your account security
+
+ Click here reset password
+
+ This link is valid for 1 hour. After it expires, request new one
+
+
+ ---
+
+
+ Login direct
+
+
+ """) % {
+ 'name': user.name,
+ 'rest_password_url': reverse('users:reset-password', external=True),
+ 'rest_password_token': user.generate_reset_token(),
+ 'forget_password_url': reverse('users:forgot-password', external=True),
+ 'email': user.email,
+ 'login_url': reverse('users:login', external=True),
+ }
+ if settings.DEBUG:
+ logger.debug(message)
+
+ send_mail_async.delay(subject, message, recipient_list, html_message=message)
+
+
+def send_reset_ssh_key_mail(user):
+ subject = _('SSH Key Reset')
+ recipient_list = [user.email]
+ message = _("""
+ Hello %(name)s:
+
+ Your ssh public key has been reset by site administrator.
+ Please login and reset your ssh public key.
+
+ Login direct
+
+
+ """) % {
+ 'name': user.name,
+ 'login_url': reverse('users:login', external=True),
+ }
+ if settings.DEBUG:
+ logger.debug(message)
+
+ send_mail_async.delay(subject, message, recipient_list, html_message=message)
+
+
+def check_user_valid(**kwargs):
+ password = kwargs.pop('password', None)
+ public_key = kwargs.pop('public_key', None)
+ email = kwargs.pop('email', None)
+ username = kwargs.pop('username', None)
+
+ if username:
+ user = get_object_or_none(User, username=username)
+ elif email:
+ user = get_object_or_none(User, email=email)
+ else:
+ user = None
+
+ if user is None:
+ return None, _('User not exist')
+ elif not user.is_valid:
+ return None, _('Disabled or expired')
+
+ if password and user.password and user.check_password(password):
+ return user, ''
+
+ if public_key and user.public_key:
+ public_key_saved = user.public_key.split()
+ if len(public_key_saved) == 1:
+ if public_key == public_key_saved[0]:
+ return user, ''
+ elif len(public_key_saved) > 1:
+ if public_key == public_key_saved[1]:
+ return user, ''
+ return None, _('Password or SSH public key invalid')
+
+
+def refresh_token(token, user, expiration=3600):
+ cache.set(token, user.id, expiration)
+
+
+def generate_token(request, user):
+ expiration = settings.CONFIG.TOKEN_EXPIRATION or 3600
+ remote_addr = request.META.get('REMOTE_ADDR', '')
+ remote_addr = base64.b16encode(remote_addr).replace('=', '')
+ token = cache.get('%s_%s' % (user.id, remote_addr))
+ if not token:
+ token = uuid.uuid4().get_hex()
+ print('Set cache: %s' % token)
+ cache.set(token, user.id, expiration)
+ cache.set('%s_%s' % (user.id, remote_addr), token, expiration)
+ return token
+
+
diff --git a/apps/users/views/__init__.py b/apps/users/views/__init__.py
new file mode 100644
index 000000000..b178ac710
--- /dev/null
+++ b/apps/users/views/__init__.py
@@ -0,0 +1,5 @@
+# ~*~ coding: utf-8 ~*~
+
+from .login import *
+from .user import *
+from .group import *
diff --git a/apps/users/views/group.py b/apps/users/views/group.py
new file mode 100644
index 000000000..fe04987a4
--- /dev/null
+++ b/apps/users/views/group.py
@@ -0,0 +1,170 @@
+# ~*~ coding: utf-8 ~*~
+
+from __future__ import unicode_literals
+from django import forms
+from django.shortcuts import reverse, redirect
+from django.utils.translation import ugettext as _
+from django.urls import reverse_lazy
+from django.views.generic import ListView
+from django.views.generic.base import TemplateView
+from django.views.generic.edit import CreateView, UpdateView, FormMixin
+from django.views.generic.detail import DetailView, SingleObjectMixin
+
+from common.utils import get_logger
+from perms.models import AssetPermission
+from ..models import User, UserGroup
+from ..utils import AdminUserRequiredMixin
+from .. import forms
+
+__all__ = ['UserGroupListView', 'UserGroupCreateView', 'UserGroupDetailView',
+ 'UserGroupUpdateView', 'UserGroupAssetPermissionCreateView',
+ 'UserGroupAssetPermissionView', 'UserGroupGrantedAssetView']
+logger = get_logger(__name__)
+
+
+class UserGroupListView(AdminUserRequiredMixin, TemplateView):
+ template_name = 'users/user_group_list.html'
+
+ def get_context_data(self, **kwargs):
+ context = super(UserGroupListView, self).get_context_data(**kwargs)
+ context.update({'app': _('Users'), 'action': _('User group list')})
+ return context
+
+
+class UserGroupCreateView(AdminUserRequiredMixin, CreateView):
+ model = UserGroup
+ form_class = forms.UserGroupForm
+ template_name = 'users/user_group_create_update.html'
+ success_url = reverse_lazy('users:user-group-list')
+
+ def get_context_data(self, **kwargs):
+ context = super(UserGroupCreateView, self).get_context_data(**kwargs)
+ users = User.objects.all()
+ context.update({'app': _('Users'), 'action': _('Create user group'),
+ 'users': users})
+ return context
+
+ # 需要添加组下用户, 而user并不是group的多对多,所以需要手动建立关系
+ def form_valid(self, form):
+ user_group = form.save()
+ users_id_list = self.request.POST.getlist('users', [])
+ users = User.objects.filter(id__in=users_id_list)
+ user_group.created_by = self.request.user.username or 'Admin'
+ user_group.users.add(*users)
+ user_group.save()
+ return super(UserGroupCreateView, self).form_valid(form)
+
+
+class UserGroupUpdateView(AdminUserRequiredMixin, UpdateView):
+ model = UserGroup
+ form_class = forms.UserGroupForm
+ template_name = 'users/user_group_create_update.html'
+ success_url = reverse_lazy('users:user-group-list')
+
+ def get_context_data(self, **kwargs):
+ # self.object = self.get_object()
+ context = super(UserGroupUpdateView, self).get_context_data(**kwargs)
+ users = User.objects.all()
+ group_users = [user.id for user in self.object.users.all()]
+ context.update({
+ 'app': _('Users'),
+ 'action': _('Update User Group'),
+ 'users': users,
+ 'group_users': group_users
+ })
+ return context
+
+ def form_valid(self, form):
+ user_group = form.save()
+ users_id_list = self.request.POST.getlist('users', [])
+ users = User.objects.filter(id__in=users_id_list)
+ user_group.users.clear()
+ user_group.users.add(*users)
+ user_group.save()
+ return super(UserGroupUpdateView, self).form_valid(form)
+
+
+class UserGroupDetailView(AdminUserRequiredMixin, DetailView):
+ model = UserGroup
+ context_object_name = 'user_group'
+ template_name = 'users/user_group_detail.html'
+
+ def get_context_data(self, **kwargs):
+ users = User.objects.exclude(id__in=self.object.users.all())
+ context = {
+ 'app': _('Users'),
+ 'action': _('User Group Detail'),
+ 'users': users,
+ }
+ kwargs.update(context)
+ return super(UserGroupDetailView, self).get_context_data(**kwargs)
+
+
+class UserGroupAssetPermissionView(AdminUserRequiredMixin, FormMixin,
+ SingleObjectMixin, ListView):
+ model = UserGroup
+ template_name = 'users/user_group_asset_permission.html'
+ context_object_name = 'user_group'
+ form_class = forms.UserPrivateAssetPermissionForm
+
+ def get(self, request, *args, **kwargs):
+ self.object = self.get_object(queryset=UserGroup.objects.all())
+ return super(UserGroupAssetPermissionView, self)\
+ .get(request, *args, **kwargs)
+
+ def get_context_data(self, **kwargs):
+ context = {
+ 'app': 'Users',
+ 'action': 'User group asset permissions',
+ }
+ kwargs.update(context)
+ return super(UserGroupAssetPermissionView, self)\
+ .get_context_data(**kwargs)
+
+
+class UserGroupAssetPermissionCreateView(AdminUserRequiredMixin, CreateView):
+ form_class = forms.UserGroupPrivateAssetPermissionForm
+ model = AssetPermission
+
+ def get(self, request, *args, **kwargs):
+ user_group = self.get_object(queryset=UserGroup.objects.all())
+ return redirect(reverse('users:user-group-asset-permission',
+ kwargs={'pk': user_group.id}))
+
+ def post(self, request, *args, **kwargs):
+ self.user_group = self.get_object(queryset=UserGroup.objects.all())
+ return super(UserGroupAssetPermissionCreateView, self)\
+ .post(request, *args, **kwargs)
+
+ def get_form(self, form_class=None):
+ form = super(UserGroupAssetPermissionCreateView, self)\
+ .get_form(form_class=form_class)
+ form.user_group = self.user_group
+ return form
+
+ def form_invalid(self, form):
+ return redirect(reverse('users:user-group-asset-permission',
+ kwargs={'pk': self.user_group.id}))
+
+ def get_success_url(self):
+ return reverse('users:user-group-asset-permission',
+ kwargs={'pk': self.user_group.id})
+
+
+class UserGroupGrantedAssetView(AdminUserRequiredMixin, DetailView):
+ model = User
+ template_name = 'users/user_group_granted_asset.html'
+ context_object_name = 'user_group'
+
+ def get(self, request, *args, **kwargs):
+ self.object = self.get_object(queryset=UserGroup.objects.all())
+ return super(UserGroupGrantedAssetView, self)\
+ .get(request, *args, **kwargs)
+
+ def get_context_data(self, **kwargs):
+ context = {
+ 'app': 'User',
+ 'action': 'User group granted asset',
+ }
+ kwargs.update(context)
+ return super(UserGroupGrantedAssetView, self).get_context_data(**kwargs)
diff --git a/apps/users/views/login.py b/apps/users/views/login.py
new file mode 100644
index 000000000..364a13946
--- /dev/null
+++ b/apps/users/views/login.py
@@ -0,0 +1,202 @@
+# ~*~ coding: utf-8 ~*~
+
+from __future__ import unicode_literals
+from django import forms
+from django.contrib.auth import login as auth_login, logout as auth_logout
+from django.contrib.auth.mixins import LoginRequiredMixin
+from django.core.files.storage import default_storage
+from django.http import HttpResponseRedirect
+from django.shortcuts import reverse, redirect
+from django.utils.decorators import method_decorator
+from django.utils.translation import ugettext as _
+from django.views.decorators.cache import never_cache
+from django.views.decorators.csrf import csrf_protect
+from django.views.decorators.debug import sensitive_post_parameters
+from django.views.generic.base import TemplateView
+from django.views.generic.edit import FormView
+from formtools.wizard.views import SessionWizardView
+
+from common.utils import get_object_or_none
+from ..models import User
+from ..utils import send_reset_password_mail
+from ..hands import write_login_log_async
+from .. import forms
+
+
+__all__ = ['UserLoginView', 'UserLogoutView',
+ 'UserForgotPasswordView', 'UserForgotPasswordSendmailSuccessView',
+ 'UserResetPasswordView', 'UserResetPasswordSuccessView',
+ 'UserFirstLoginView']
+
+
+@method_decorator(sensitive_post_parameters(), name='dispatch')
+@method_decorator(csrf_protect, name='dispatch')
+@method_decorator(never_cache, name='dispatch')
+class UserLoginView(FormView):
+ template_name = 'users/login.html'
+ form_class = forms.UserLoginForm
+ redirect_field_name = 'next'
+
+ def get(self, request, *args, **kwargs):
+ if request.user.is_staff:
+ return redirect(self.get_success_url())
+ return super(UserLoginView, self).get(request, *args, **kwargs)
+
+ def form_valid(self, form):
+ auth_login(self.request, form.get_user())
+ login_ip = self.request.META.get('REMOTE_ADDR', '')
+ user_agent = self.request.META.get('HTTP_USER_AGENT', '')
+ write_login_log_async.delay(self.request.user.username,
+ self.request.user.name,
+ login_type='W', login_ip=login_ip,
+ user_agent=user_agent)
+ return redirect(self.get_success_url())
+
+ def get_success_url(self):
+ if self.request.user.is_first_login:
+ return reverse('users:user-first-login')
+
+ return self.request.POST.get(
+ self.redirect_field_name,
+ self.request.GET.get(self.redirect_field_name, reverse('index')))
+
+
+@method_decorator(never_cache, name='dispatch')
+class UserLogoutView(TemplateView):
+ template_name = 'flash_message_standalone.html'
+
+ def get(self, request, *args, **kwargs):
+ auth_logout(request)
+ return super(UserLogoutView, self).get(request)
+
+ def get_context_data(self, **kwargs):
+ context = {
+ 'title': _('Logout success'),
+ 'messages': _('Logout success, return login page'),
+ 'redirect_url': reverse('users:login'),
+ 'auto_redirect': True,
+ }
+ kwargs.update(context)
+ return super(UserLogoutView, self).get_context_data(**kwargs)
+
+
+class UserForgotPasswordView(TemplateView):
+ template_name = 'users/forgot_password.html'
+
+ def post(self, request):
+ email = request.POST.get('email')
+ user = get_object_or_none(User, email=email)
+ if not user:
+ return self.get(request, errors=_('Email address invalid, '
+ 'please input again'))
+ else:
+ send_reset_password_mail(user)
+ return HttpResponseRedirect(
+ reverse('users:forgot-password-sendmail-success'))
+
+
+class UserForgotPasswordSendmailSuccessView(TemplateView):
+ template_name = 'flash_message_standalone.html'
+
+ def get_context_data(self, **kwargs):
+ context = {
+ 'title': _('Send reset password message'),
+ 'messages': _('Send reset password mail success, '
+ 'login your mail box and follow it '),
+ 'redirect_url': reverse('users:login'),
+ }
+ kwargs.update(context)
+ return super(UserForgotPasswordSendmailSuccessView, self)\
+ .get_context_data(**kwargs)
+
+
+class UserResetPasswordSuccessView(TemplateView):
+ template_name = 'flash_message_standalone.html'
+
+ def get_context_data(self, **kwargs):
+ context = {
+ 'title': _('Reset password success'),
+ 'messages': _('Reset password success, return to login page'),
+ 'redirect_url': reverse('users:login'),
+ 'auto_redirect': True,
+ }
+ kwargs.update(context)
+ return super(UserResetPasswordSuccessView, self)\
+ .get_context_data(**kwargs)
+
+
+class UserResetPasswordView(TemplateView):
+ template_name = 'users/reset_password.html'
+
+ def get(self, request, *args, **kwargs):
+ token = request.GET.get('token')
+ user = User.validate_reset_token(token)
+
+ if not user:
+ kwargs.update({'errors': _('Token invalid or expired')})
+ return super(UserResetPasswordView, self).get(request, *args, **kwargs)
+
+ def post(self, request, *args, **kwargs):
+ password = request.POST.get('password')
+ password_confirm = request.POST.get('password-confirm')
+ token = request.GET.get('token')
+
+ if password != password_confirm:
+ return self.get(request, errors=_('Password not same'))
+
+ user = User.validate_reset_token(token)
+ if not user:
+ return self.get(request, errors=_('Token invalid or expired'))
+
+ user.reset_password(password)
+ return HttpResponseRedirect(reverse('users:reset-password-success'))
+
+
+class UserFirstLoginView(LoginRequiredMixin, SessionWizardView):
+ template_name = 'users/first_login.html'
+ form_list = [forms.UserInfoForm, forms.UserKeyForm]
+ file_storage = default_storage
+
+ def dispatch(self, request, *args, **kwargs):
+ if request.user.is_authenticated() and not request.user.is_first_login:
+ return redirect(reverse('index'))
+ return super(UserFirstLoginView, self).dispatch(request, *args, **kwargs)
+
+ def done(self, form_list, form_dict, **kwargs):
+ user = self.request.user
+ for form in form_list:
+ for field in form:
+ if field.value():
+ setattr(user, field.name, field.value())
+ if field.name == 'enable_otp':
+ user.enable_otp = field.value()
+ user.is_first_login = False
+ user.is_public_key_valid = True
+ user.save()
+ return redirect(reverse('index'))
+
+ def get_context_data(self, **kwargs):
+ context = super(UserFirstLoginView, self).get_context_data(**kwargs)
+ context.update({'app': _('Users'), 'action': _('First Login')})
+ return context
+
+ def get_form_initial(self, step):
+ user = self.request.user
+ if step == '0':
+ return {
+ 'name': user.name or user.username,
+ 'enable_otp': user.enable_otp or True,
+ 'wechat': user.wechat or '',
+ 'phone': user.phone or ''
+ }
+ return super(UserFirstLoginView, self).get_form_initial(step)
+
+ def get_form(self, step=None, data=None, files=None):
+ form = super(UserFirstLoginView, self).get_form(step, data, files)
+
+ if step is None:
+ step = self.steps.current
+
+ if step == '1':
+ form.user = self.request.user
+ return form
diff --git a/apps/users/views/user.py b/apps/users/views/user.py
new file mode 100644
index 000000000..eaa9b26b4
--- /dev/null
+++ b/apps/users/views/user.py
@@ -0,0 +1,328 @@
+# ~*~ coding: utf-8 ~*~
+
+from __future__ import unicode_literals
+
+import json
+import uuid
+
+from openpyxl import load_workbook
+from openpyxl import Workbook
+from openpyxl.writer.excel import save_virtual_workbook
+
+from django.contrib.auth.mixins import LoginRequiredMixin
+from django.contrib.messages.views import SuccessMessageMixin
+from django.core.cache import cache
+from django.http import HttpResponse, JsonResponse
+from django.shortcuts import redirect
+from django.urls import reverse_lazy, reverse
+from django.utils import timezone
+from django.utils.translation import ugettext as _
+from django.utils.decorators import method_decorator
+from django.views import View
+from django.views.generic import ListView
+from django.views.generic.base import TemplateView
+from django.views.generic.edit import (CreateView, UpdateView, FormMixin,
+ FormView)
+from django.views.generic.detail import DetailView, SingleObjectMixin
+from django.views.decorators.csrf import csrf_exempt
+
+from .. import forms
+from ..models import User, UserGroup
+from ..utils import AdminUserRequiredMixin, user_add_success_next
+from common.mixins import JSONResponseMixin
+from common.utils import get_logger
+from perms.models import AssetPermission
+
+__all__ = ['UserListView', 'UserCreateView', 'UserDetailView',
+ 'UserUpdateView', 'UserAssetPermissionCreateView',
+ 'UserAssetPermissionView', 'UserGrantedAssetView',
+ 'UserExportView', 'UserBulkImportView', 'UserProfileView']
+
+logger = get_logger(__name__)
+
+
+class UserListView(AdminUserRequiredMixin, TemplateView):
+ template_name = 'users/user_list.html'
+
+ def get_context_data(self, **kwargs):
+ context = super(UserListView, self).get_context_data(**kwargs)
+ context.update({
+ 'app': _('Users'),
+ 'action': _('User list'),
+ 'groups': UserGroup.objects.all()
+ })
+ return context
+
+
+class UserCreateView(AdminUserRequiredMixin, SuccessMessageMixin, CreateView):
+ model = User
+ form_class = forms.UserCreateUpdateForm
+ template_name = 'users/user_create.html'
+ success_url = reverse_lazy('users:user-list')
+ success_message = _('Create user %s successfully.')
+
+ def get_context_data(self, **kwargs):
+ context = super(UserCreateView, self).get_context_data(**kwargs)
+ context.update({'app': _('Users'), 'action': _('Create user')})
+ return context
+
+ def form_valid(self, form):
+ user = form.save(commit=False)
+ user.created_by = self.request.user.username or 'System'
+ user.save()
+ user_add_success_next(user)
+ return super(UserCreateView, self).form_valid(form)
+
+ def get_success_message(self, cleaned_data):
+ return self.success_message % (
+ reverse_lazy('users:user-detail', kwargs={'pk': self.object.pk}),
+ self.object.name,
+ )
+
+
+class UserUpdateView(AdminUserRequiredMixin, UpdateView):
+ model = User
+ form_class = forms.UserCreateUpdateForm
+ template_name = 'users/user_update.html'
+ context_object_name = 'user_object'
+ success_url = reverse_lazy('users:user-list')
+
+ def form_valid(self, form):
+ username = self.object.username
+ user = form.save(commit=False)
+ user.username = username
+ user.save()
+ password = self.request.POST.get('password', '')
+ if password:
+ user.set_password(password)
+ return super(UserUpdateView, self).form_valid(form)
+
+ def get_context_data(self, **kwargs):
+ context = super(UserUpdateView, self).get_context_data(**kwargs)
+ context.update({'app': _('Users'), 'action': _('Update user')})
+ return context
+
+
+class UserDetailView(AdminUserRequiredMixin, DetailView):
+ model = User
+ template_name = 'users/user_detail.html'
+ context_object_name = "user_object"
+
+ def get_context_data(self, **kwargs):
+ groups = UserGroup.objects.exclude(id__in=self.object.groups.all())
+ context = {
+ 'app': _('Users'),
+ 'action': _('User detail'),
+ 'groups': groups
+ }
+ kwargs.update(context)
+ return super(UserDetailView, self).get_context_data(**kwargs)
+
+
+@method_decorator(csrf_exempt, name='dispatch')
+class UserExportView(View):
+ def get(self, request):
+ spm = request.GET.get('spm', '')
+ users_id = cache.get(spm)
+ if not users_id and not isinstance(users_id, list):
+ return HttpResponse('May be expired', status=404)
+
+ users = User.objects.filter(id__in=users_id)
+ print(users)
+ wb = Workbook()
+ ws = wb.active
+ ws.title = 'User'
+ header = ["name", 'username', 'email', 'groups',
+ "role", "phone", "wechat", "comment"]
+ ws.append(header)
+
+ for user in users:
+ ws.append([user.name, user.username, user.email,
+ ','.join([group.name for group in user.groups.all()]),
+ user.role, user.phone, user.wechat, user.comment])
+
+ filename = 'users-{}.xlsx'.format(
+ timezone.localtime(timezone.now()).strftime('%Y-%m-%d_%H-%M-%S'))
+ response = HttpResponse(save_virtual_workbook(wb),
+ content_type='applications/vnd.ms-excel')
+ response[
+ 'Content-Disposition'] = 'attachment; filename="%s"' % filename
+ return response
+
+ def post(self, request):
+ try:
+ users_id = json.loads(request.body).get('users_id', [])
+ except ValueError:
+ return HttpResponse('Json object not valid', status=400)
+ spm = uuid.uuid4().get_hex()
+ cache.set(spm, users_id, 300)
+ url = reverse('users:user-export') + '?spm=%s' % spm
+ return JsonResponse({'redirect': url})
+
+
+class UserBulkImportView(AdminUserRequiredMixin, JSONResponseMixin, FormView):
+ form_class = forms.FileForm
+
+ def form_invalid(self, form):
+ try:
+ error = form.errors.values()[-1][-1]
+ except Exception as e:
+ print e
+ error = _('Invalid file.')
+ data = {
+ 'success': False,
+ 'msg': error
+ }
+ return self.render_json_response(data)
+
+ def form_valid(self, form):
+ try:
+ wb = load_workbook(form.cleaned_data['file'])
+ ws = wb.get_active_sheet()
+ except Exception as e:
+ print(e)
+ data = {'valid': False, 'msg': 'Not a valid Excel file'}
+ return self.render_json_response(data)
+
+ rows = ws.rows
+ header_need = ["name", 'username', 'email', 'groups',
+ "role", "phone", "wechat", "comment"]
+ header = [col.value for col in next(rows)]
+ print(header)
+ if header != header_need:
+ data = {'valid': False, 'msg': 'Must be same format as '
+ 'template or export file'}
+ return self.render_json_response(data)
+
+ created = []
+ updated = []
+ failed = []
+ for row in rows:
+ user_dict = dict(zip(header, [col.value for col in row]))
+ groups_name = user_dict.pop('groups')
+ if groups_name:
+ groups_name = groups_name.split(',')
+ groups = UserGroup.objects.filter(name__in=groups_name)
+ else:
+ groups = None
+ try:
+ user = User.objects.create(**user_dict)
+ user_add_success_next(user)
+ created.append(user_dict['username'])
+ except User.IntegrityError as e:
+ user = User.objects.filter(username=user_dict['username'])
+ if not user:
+ failed.append(user_dict['username'])
+ continue
+ user.update(**user_dict)
+ user = user[0]
+ updated.append(user_dict['username'])
+ except TypeError as e:
+ print(e)
+ failed.append(user_dict['username'])
+ user = None
+
+ if user and groups:
+ user.groups.add(*tuple(groups))
+ user.save()
+
+ data = {
+ 'created': created,
+ 'created_info': 'Created {}'.format(len(created)),
+ 'updated': updated,
+ 'updated_info': 'Updated {}'.format(len(updated)),
+ 'failed': failed,
+ 'failed_info': 'Failed {}'.format(len(failed)),
+ 'valid': True,
+ 'msg': 'Created: {}. Updated: {}, Error: {}'.format(
+ len(created), len(updated), len(failed))
+ }
+ return self.render_json_response(data)
+
+
+class UserAssetPermissionView(AdminUserRequiredMixin, FormMixin,
+ SingleObjectMixin, ListView):
+ model = User
+ template_name = 'users/user_asset_permission.html'
+ context_object_name = 'user'
+ form_class = forms.UserPrivateAssetPermissionForm
+
+ def get(self, request, *args, **kwargs):
+ self.object = self.get_object(queryset=User.objects.all())
+ return super(UserAssetPermissionView, self).get(request, *args, **kwargs)
+
+ def get_context_data(self, **kwargs):
+ context = {
+ 'app': 'Users',
+ 'action': 'User asset permissions',
+ }
+ kwargs.update(context)
+ return super(UserAssetPermissionView, self).get_context_data(**kwargs)
+
+
+class UserAssetPermissionCreateView(AdminUserRequiredMixin, CreateView):
+ form_class = forms.UserPrivateAssetPermissionForm
+ model = AssetPermission
+
+ def get(self, request, *args, **kwargs):
+ user = self.get_object(queryset=User.objects.all())
+ return redirect(reverse('users:user-asset-permission',
+ kwargs={'pk': user.id}))
+
+ def post(self, request, *args, **kwargs):
+ self.user = self.get_object(queryset=User.objects.all())
+ return super(UserAssetPermissionCreateView, self)\
+ .post(request, *args, **kwargs)
+
+ def get_form(self, form_class=None):
+ form = super(UserAssetPermissionCreateView, self)\
+ .get_form(form_class=form_class)
+ form.user = self.user
+ return form
+
+ def form_invalid(self, form):
+ return redirect(reverse('users:user-asset-permission',
+ kwargs={'pk': self.user.id}))
+
+ def get_success_url(self):
+ return reverse('users:user-asset-permission',
+ kwargs={'pk': self.user.id})
+
+
+class UserGrantedAssetView(AdminUserRequiredMixin, DetailView):
+ model = User
+ template_name = 'users/user_granted_asset.html'
+ context_object_name = 'user'
+
+ def get(self, request, *args, **kwargs):
+ self.object = self.get_object(queryset=User.objects.all())
+ return super(UserGrantedAssetView, self).get(request, *args, **kwargs)
+
+ def get_context_data(self, **kwargs):
+ context = {
+ 'app': 'User',
+ 'action': 'User granted asset',
+ }
+ kwargs.update(context)
+ return super(UserGrantedAssetView, self).get_context_data(**kwargs)
+
+
+class UserProfileView(LoginRequiredMixin, TemplateView):
+ template_name = 'users/user_profile.html'
+
+ def get_context_data(self, **kwargs):
+ from perms.utils import (get_user_granted_assets,
+ get_user_granted_asset_groups,
+ get_user_asset_permissions)
+ assets = get_user_granted_assets(self.request.user)
+ asset_groups = get_user_granted_asset_groups(self.request.user)
+ permissions = get_user_asset_permissions(self.request.user)
+ context = {
+ 'app': 'User',
+ 'action': 'User Profile',
+ 'assets': assets,
+ 'asset_groups': asset_groups,
+ 'permissions': permissions
+ }
+ kwargs.update(context)
+ return super(UserProfileView, self).get_context_data(**kwargs)
diff --git a/config_example.py b/config_example.py
new file mode 100644
index 000000000..71b9ab8bc
--- /dev/null
+++ b/config_example.py
@@ -0,0 +1,125 @@
+"""
+ jumpserver.config
+ ~~~~~~~~~~~~~~~~~
+
+ Jumpserver project setting file
+
+ :copyright: (c) 2014-2016 by Jumpserver Team.
+ :license: GPL v2, see LICENSE for more details.
+"""
+import os
+
+BASE_DIR = os.path.dirname(os.path.abspath(__file__))
+LOG_DIR = os.path.join(BASE_DIR, 'logs')
+
+
+class Config:
+ # Use it to encrypt or decrypt data
+ # SECURITY WARNING: keep the secret key used in production secret!
+ SECRET_KEY = os.environ.get('SECRET_KEY') or '2vym+ky!997d5kkcc64mnz06y1mmui3lut#(^wd=%s_qj$1%x'
+
+ # How many line display every page, default 25
+ DISPLAY_PER_PAGE = 25
+
+ # It's used to identify your site, When we send a create mail to user, we only know login url is /login/
+ # But we should know the absolute url like: http://jms.jumpserver.org/login/, so SITE_URL is
+ # HTTP_PROTOCOL://HOST[:PORT]
+ SITE_URL = 'http://localhost'
+
+ # Domain name, If set app email will set as it
+ DOMAIN_NAME = 'jumpserver.org'
+
+ # Django security setting, if your disable debug model, you should setting that
+ ALLOWED_HOSTS = ['*']
+
+ # Development env open this, when error occur display the full process track, Production disable it
+ DEBUG = True
+
+ # DEBUG, INFO, WARNING, ERROR, CRITICAL can set. See https://docs.djangoproject.com/en/1.10/topics/logging/
+ LOG_LEVEL = 'DEBUG'
+
+ # Database setting, Support sqlite3, mysql, postgres ....
+ # See https://docs.djangoproject.com/en/1.10/ref/settings/#databases
+
+ # Sqlite setting:
+ DATABASE_ENGINE = 'sqlite3'
+ DB_NAME = os.path.join(BASE_DIR, 'db.sqlite3')
+
+ # Mysql or postgres setting like:
+ # DB_ENGINE = 'mysql'
+ # DB_HOST = '127.0.0.1'
+ # DB_PORT = 3306
+ # DB_USER = 'root'
+ # DB_PASSWORD = ''
+ # DB_NAME = 'jumpserver'
+
+ # When Django start it will bind this host and port
+ # ./manage.py runserver 127.0.0.1:8080
+ # Todo: Gunicorn or uwsgi run may be use it
+ HTTP_BIND_HOST = '0.0.0.0'
+ HTTP_LISTEN_PORT = 8080
+
+ # Use Redis as broker for celery and web socket
+ REDIS_HOST = '127.0.0.1'
+ REDIS_PORT = 6379
+ REDIS_PASSWORD = ''
+ BROKER_URL = 'redis://%(password)s%(host)s:%(port)s/3' % {
+ 'password': REDIS_PASSWORD,
+ 'host': REDIS_HOST,
+ 'port': REDIS_PORT,
+ }
+
+ # Api token expiration when create
+ TOKEN_EXPIRATION = 3600
+
+ # Email SMTP setting, we only support smtp send mail
+ # EMAIL_HOST = 'smtp.qq.com'
+ # EMAIL_PORT = 25
+ # EMAIL_HOST_USER = ''
+ # EMAIL_HOST_PASSWORD = ''
+ # EMAIL_USE_SSL = False # If port is 465, set True
+ # EMAIL_USE_TLS = False # If port is 587, set True
+ # EMAIL_SUBJECT_PREFIX = '[Jumpserver] '
+
+ CAPTCHA_TEST_MODE = False
+
+ def __init__(self):
+ pass
+
+ def __getattr__(self, item):
+ return None
+
+
+class DevelopmentConfig(Config):
+ DEBUG = True
+ DISPLAY_PER_PAGE = 20
+ DB_ENGINE = 'sqlite'
+ DB_NAME = os.path.join(BASE_DIR, 'db.sqlite3')
+ EMAIL_HOST = 'smtp.exmail.qq.com'
+ EMAIL_PORT = 465
+ EMAIL_HOST_USER = 'ask@jumpserver.org'
+ EMAIL_HOST_PASSWORD = 'xfDf4x1n'
+ EMAIL_USE_SSL = True # If port is 465, set True
+ EMAIL_USE_TLS = False # If port is 587, set True
+ EMAIL_SUBJECT_PREFIX = '[Jumpserver] '
+ SITE_URL = 'http://localhost:8080'
+
+
+class ProductionConfig(Config):
+ DEBUG = False
+ DB_ENGINE = 'mysql'
+ DB_HOST = '127.0.0.1'
+ DB_PORT = 3306
+ DB_USER = 'root'
+ DB_PASSWORD = ''
+ DB_NAME = 'jumpserver'
+
+
+config = {
+ 'development': DevelopmentConfig,
+ 'production': ProductionConfig,
+
+ 'default': DevelopmentConfig,
+}
+
+env = 'development'
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 000000000..a3698f4c9
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,4 @@
+#### [项目结构描述](https://code.simcu.com/jumpserver/jumpserver/blob/master/docs/project_structure.md)
+#### [Python代码规范](https://code.simcu.com/jumpserver/jumpserver/blob/master/docs/python_style_guide.md)
+#### [API设计规范](https://code.simcu.com/jumpserver/jumpserver/blob/master/docs/api_style_guide.md)
+#### [表结构](https://code.simcu.com/jumpserver/jumpserver/wikis/table_structure_image)
\ No newline at end of file
diff --git a/docs/api_style_guide.md b/docs/api_style_guide.md
new file mode 100644
index 000000000..928b02a98
--- /dev/null
+++ b/docs/api_style_guide.md
@@ -0,0 +1,148 @@
+## REST API规范约定
+
+这里仅考虑REST API的基本情况。参考
+
+[RESTful API 设计指南](http://www.ruanyifeng.com/blog/2014/05/restful_api.html)
+
+[github api文档](https://developer.github.com/v3/)
+
+### 协议
+
+API与用户的通信协议,总是使用HTTPs协议。
+
+
+### 域名
+
+这版api相对简单, 没有前后端分离, 没有独立app, 所以放在主域名下
+
+```
+https://example.org/api/
+```
+
+### 版本
+
+将API的版本号放入URL中, 由于一个项目多个app所以Jumpserver使用以下风格,
+将版本号放到app后面
+
+```
+https://example.com/api/:app:/:version:/:resource:
+https://example.com/api/assets/v1.0/assets [GET, POST]
+https://example.com/api/assets/v1.0/assets/1 [GET, PUT, DELETE]
+```
+
+
+### 路径
+
+路径又称"终点"(endpoint),表示API的具体网址。
+在RESTful架构中,每个网址代表一种资源(resource),所以网址中不能有动词,只能有名词,而且所用的名词往往与数据库的表格名对应。一般来说,数据库中的表都是同种记录的"集合"(collection),所以API中的名词也应该使用复数。
+举例来说 cmdb中的assets列表, idc列表
+
+```
+https://example.com/api/:app:/:version:/:resource:
+
+https://example.com/api/assets/v1.0/assets [GET, POST]
+https://example.com/api/assets/v1.0/assets/1 [GET, PUT, DELETE]
+https://example.com/api/assets/v1.0/idcs [GET, POST]
+```
+
+一般性的增删查改(CRUD)API,完全使用HTTP method加上url提供的语义,url中的可变部分(比如上面提到的)
+一般用来传递该API操作的核心实体对象的唯一ID,如果有更多的参数需要提供,GET方法请使用url parameter
+(例如:"?client_id=xxxxx&app_id=xxxxxx"),PUT/POST/DELETE方法请使用请求体传递参数。
+
+
+### HTTP Method
+
+对于资源的具体操作类型,由HTTP动词表示。
+
+常用的HTTP动词有下面五个(括号里是对应的SQL命令)。
+
+- GET(SELECT):从服务器取出资源(一项或多项)。
+- POST(CREATE):在服务器新建一个资源。
+- PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源, 幂等
+- PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)。
+- DELETE(DELETE):从服务器删除资源。
+
+
+### 过滤信息
+
+常见参数约定
+
+```
+?keyword=localhost 模糊搜索
+?limit=10:指定返回记录的数量
+?offset=10:指定返回记录的开始位置。
+?page=2&per_page=100:指定第几页,以及每页的记录数。
+?sort=name&order=asc:指定返回结果按照哪个属性排序,以及排序顺序。
+?asset_id=1:指定筛选条件
+```
+
+
+### 状态码
+
+服务器向用户返回的状态码和提示信息,常见的有以下一些(方括号中是该状态码对应的HTTP动词)。
+
+- 200 OK - [GET]:服务器成功返回用户请求的数据,该操作是幂等的(Idempotent)。
+- 201 CREATED - [POST/PUT/PATCH]:用户新建或修改数据成功。
+- 202 Accepted - [*]:表示一个请求已经进入后台排队(异步任务)
+- 204 NO CONTENT - [DELETE]:用户删除数据成功。
+- 400 INVALID REQUEST - [POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操作,该操作是幂等的。
+- 401 Unauthorized - [*]:表示用户没有权限(令牌、用户名、密码错误)。
+- 403 Forbidden - [*] 表示用户得到授权(与401错误相对),但是访问是被禁止的。
+- 404 NOT FOUND - [*]:用户发出的请求针对的是不存在的记录,服务器没有进行操作,该操作是幂等的。
+- 406 Not Acceptable - [GET]:用户请求的格式不可得(比如用户请求JSON格式,但是只有XML格式)。
+- 410 Gone -[GET]:用户请求的资源被永久删除,且不会再得到的。
+- 422 Unprocesable entity - [POST/PUT/PATCH] 当创建一个对象时,发生一个验证错误。
+- 500 INTERNAL SERVER ERROR - [*]:服务器发生错误,用户将无法判断发出的请求是否成功。
+
+
+### 错误处理
+
+如果状态码是4xx,就应该向用户返回出错信息。一般来说,返回的信息中将error作为键名,出错信息作为键值即可。
+
+```
+{
+ error: "Invalid API key"
+}
+```
+
+### 返回结果
+
+针对不同操作,服务器向用户返回的结果应该符合以下规范。
+
+```
+GET /collection:返回资源对象的列表(数组)
+GET /collection/resource:返回单个资源对象
+POST /collection:返回新生成的资源对象
+PUT /collection/resource:返回完整的资源对象
+PATCH /collection/resource:返回完整的资源对象
+DELETE /collection/resource:返回一个空文档
+```
+
+### Hypermedia API
+
+RESTful API最好做到Hypermedia,即返回结果中提供链接,连向其他API方法,使得用户不查文档,也知道下一步应该做什么。
+比如,当用户向api.example.com的根目录发出请求,会得到这样一个文档。
+
+```
+{"link": {
+ "rel": "collection https://www.example.com/zoos",
+ "href": "https://api.example.com/zoos",
+ "title": "List of zoos",
+ "type": "application/vnd.yourformat+json"
+}}
+```
+
+上面代码表示,文档中有一个link属性,用户读取这个属性就知道下一步该调用什么API了。
+
+rel表示这个API与当前网址的关系(collection关系,并给出该collection的网址),
+
+href表示API的路径,title表示API的标题,type表示返回类型。
+Hypermedia API的设计被称为HATEOAS。
+Github的API就是这种设计.
+
+
+### 其它
+
+(1)API的身份认证应该使用OAuth 2.0框架。
+(2)服务器返回的数据格式,应该尽量使用JSON
+
diff --git a/docs/django_class_base_view_inheritance.py b/docs/django_class_base_view_inheritance.py
new file mode 100644
index 000000000..434c28af6
--- /dev/null
+++ b/docs/django_class_base_view_inheritance.py
@@ -0,0 +1,295 @@
+#!/usr/bin/env python
+# ~*~ coding: utf-8 ~*~
+#
+
+from django.core.paginator import InvalidPage, Paginator
+
+
+class View(object):
+
+ http_method_names = []
+
+ def __init__(self, **kwargs):
+ pass
+
+ @classmethod
+ def as_view(cls, **initkwargs):
+ pass
+
+ def dispatch(self, request, *args, **kwargs):
+ pass
+
+ def http_method_not_allowed(self, request, *args, **kwargs):
+ pass
+
+ def options(self, request, *args, **kwargs):
+ pass
+
+ def _allowed_method(self):
+ pass
+
+
+class TemplateResponseMixin(object):
+ template_name = None
+ template_engine = None
+ response_class = None
+ content_type = None
+
+ def render_to_response(self, context, **response_kwargs):
+ pass
+
+ def get_template_name(self):
+ pass
+
+
+class ContextMixin(object):
+ def get_context_data(self, **kwargs):
+ pass
+
+
+class RedirectView(View):
+ permanent = False
+ url = None
+ pattern_name = None
+ query_string = False
+
+ def get_redirect_url(self, *args, **kwargs):
+ pass
+
+ def get(self, request, *args, **kwargs):
+ pass
+
+ def head(self, request, *args, **kwargs):
+ pass
+
+ def post(self, request, *args, **kwargs):
+ pass
+
+ def options(self, request, *args, **kwargs):
+ pass
+
+ def delete(self, request, *args, **kwargs):
+ pass
+
+ def put(self, request, *args, **kwargs):
+ pass
+
+ def patch(self, request, *args, **kwargs):
+ pass
+
+
+class TemplateView(TemplateResponseMixin, ContextMixin, View):
+ def get(self, request, *args, **kwargs):
+ pass
+
+
+class SingleObjectMixin(ContextMixin):
+ model = None
+ queryset = None
+ slug_field = 'slug'
+ context_object_name = None
+ slug_url_kwarg = 'slug'
+ pk_url_kwarg = 'pk'
+ query_pk_and_slug = False
+
+ def get_object(self):
+ pass
+
+ def get_queryset(self):
+ pass
+
+ def get_slug_field(self):
+ pass
+
+ def get_context_object_name(self, obj):
+ pass
+
+ def get_context_data(self, **kwargs):
+ pass
+
+
+class BaseDetailView(SingleObjectMixin, View):
+ def get(self, request, *args, **kwargs):
+ pass
+
+
+class SingleObjectTemplateResponseMixin(TemplateResponseMixin):
+ template_name_field = None
+ template_name_suffix = '_detail'
+
+ def get_template_name(self):
+ pass
+
+
+class DetailView(SingleObjectTemplateResponseMixin, BaseDetailView):
+ pass
+
+
+class FormMixin(ContextMixin):
+ initial = {}
+ form_class = None
+ success_url = None
+ prefix = None
+
+ def get_initial(self):
+ pass
+
+ def get_prefix(self):
+ pass
+
+ def get_form_class(self):
+ pass
+
+ def get_form(self, form_class):
+ pass
+
+ def get_form_kwargs(self):
+ pass
+
+ def get_success_url(self):
+ pass
+
+ def form_valid(self, form):
+ pass
+
+ def form_invalid(self, form):
+ pass
+
+ def get_context_data(self, **kwargs):
+ pass
+
+
+class ModelFormMixin(FormMixin, SingleObjectMixin):
+ fields = None
+
+ def get_form_class(self):
+ pass
+
+ def get_form_kwargs(self):
+ pass
+
+ def get_success_url(self):
+ pass
+
+ def form_valid(self, form):
+ pass
+
+
+class ProcessFormView(View):
+ def get(self, request, *args, **kwargs):
+ pass
+
+ def post(self, request, *args, **kwargs):
+ pass
+
+ def put(self, request, *args, **kwargs):
+ pass
+
+
+class BaseFormView(FormMixin, ProcessFormView):
+ pass
+
+
+class FormView(TemplateResponseMixin, BaseFormView):
+ pass
+
+
+class BaseCreateView(ModelFormMixin, ProcessFormView):
+ def get(self, request, *args, **kwargs):
+ pass
+
+ def post(self, request, *args, **kwargs):
+ pass
+
+
+class CreateView(SingleObjectTemplateResponseMixin, BaseCreateView):
+ template_name_suffix = '_form'
+
+
+class BaseUpdateView(ModelFormMixin, ProcessFormView):
+ def get(self, request, *args, **kwargs):
+ pass
+
+ def post(self, request, *args, **kwargs):
+ pass
+
+
+class UpdateView(SingleObjectTemplateResponseMixin, BaseUpdateView):
+ template_name_suffix = '_form'
+
+
+class DeletionMixin(object):
+ success_url = None
+
+ def delete(self, request, *args, **kwargs):
+ pass
+
+ def post(self, request, *args, **kwargs):
+ pass
+
+ def get_success_url(self):
+ pass
+
+
+class BaseDeleteView(DeletionMixin, BaseDetailView):
+ pass
+
+
+class DeleteView(SingleObjectTemplateResponseMixin, BaseDeleteView):
+ pass
+
+
+class MultipleObjectMixin(ContextMixin):
+ allow_empty = True
+ queryset = None
+ model = None
+ paginate_by = None
+ paginate_orphans = 0
+ context_object_name = None
+ paginator_class = Paginator
+ page_kwarg = 'page'
+ ordering = None
+
+ def get_queryset(self):
+ pass
+
+ def get_ordering(self):
+ pass
+
+ def paginate_queryset(self, queryset, page_size):
+ pass
+
+ def get_paginate_by(self, queryset):
+ pass
+
+ def get_paginator(self, queryset, per_page, orphans=0,
+ allow_empty_first_page=True, **kwargs):
+ pass
+
+ def get_paginate_orphans(self):
+ pass
+
+ def get_allow_empty(self):
+ pass
+
+ def get_context_object_name(self, object_list):
+ pass
+
+ def get_context_data(self, **kwargs):
+ pass
+
+
+class BaseListView(MultipleObjectMixin, View):
+ def get(self, request, *args, **kwargs):
+ pass
+
+
+class MultipleObjectTemplateResponseMixin(TemplateResponseMixin):
+ template_name_suffix = '_list'
+
+ def get_template_name(self):
+ pass
+
+
+class ListView(MultipleObjectTemplateResponseMixin, BaseListView):
+ pass
diff --git a/docs/project_structure.md b/docs/project_structure.md
new file mode 100644
index 000000000..d66f043f9
--- /dev/null
+++ b/docs/project_structure.md
@@ -0,0 +1,50 @@
+## 项目骨架
+
+说明如下:
+
+```
+.
+├── config-example.py // 配置文件样例
+├── docs // 所有doc文件放到该目录
+│ └── README.md
+├── LICENSE
+├── README.md
+├── install // 安装说明
+├── logs // 日志目录
+├── apps // 管理后台目录,也是各app所在目录
+│ └── assets // app目录
+│ │ ├── admin.py
+│ │ ├── apps.py // 新版本django app设置文件
+│ │ ├── api.py // api文件
+│ │ ├── __init__.py // 对外暴露的接口,放到该文件中,方便别的app引用
+│ │ ├── migrations // models Migrations版本控制目录
+│ │ │ └── __init__.py
+│ │ ├── models.py // 数据模型目录
+│ │ ├── static // app下静态资源目录,如果需要
+│ │ │ └── assets // 多一层目录,防止资源重名
+│ │ │ └── some_image.png
+│ │ ├── templates // app下模板目录
+│ │ │ └── assets // 多一层目录,防止资源重名
+│ │ │ └── asset_list.html
+│ │ ├── templatetags // 模板标签目录
+│ │ ├── tests.py // 测试用例文件
+│ │ ├── urls.py // urlconf文件
+│ │ ├── utils.py // 将views和api可复用的代码放在这里, api和views只是请求和返回不同
+│ │ └── views.py // views文件
+│ ├── common
+│ │ ├── templatetags // 通用template tag
+│ │ ├── utils.py // 通用的函数方法
+│ │ └── views.py
+│ ├── fixtures // 初始化数据目录
+│ │ ├── init.json // 初始化项目数据库
+│ │ └── fake.json // 生成大量测试数据
+│ ├── jumpserver // 项目设置目录
+│ │ ├── __init__.py
+│ │ ├── settings.py // 项目设置文件
+│ │ ├── urls.py // 项目入口urlconf
+│ │ └── wsgi.py
+│ ├── manage.py
+│ ├── static // 项目静态资源目录
+│ ├── static // 项目多语言目录
+│ └── templates // 项目模板目录
+```
diff --git a/docs/python_style_guide.md b/docs/python_style_guide.md
new file mode 100644
index 000000000..dd91900b6
--- /dev/null
+++ b/docs/python_style_guide.md
@@ -0,0 +1,194 @@
+# Jumpserver 项目规范(Draft)
+
+## 语言框架
+1. Python 2.7 由于ansible目前不支持python3
+2. Django 1.10 (最新版本)
+3. Terminal Websocket使用go实现 (未来)
+
+
+## Django规范
+1. 尽量使用Class Base View编程,更少代码
+2. 使用Django Form
+3. 每个url独立命名,不要硬编码,同理static也是
+4. 数据库表名手动指定,不要使用默认
+5. 代码优雅简洁
+6. 注释明确优美
+7. 测试案例尽可能完整
+8. 尽可能利用Django造好的轮子
+
+
+## 代码风格
+
+Python方面大致的风格,我们采用pocoo的[Style Guidance](http://www.pocoo.org/internal/styleguide/),但是有些细节部分会尽量放开
+参考国内翻译
+
+### 基本的代码布局
+
+#### 缩进
+
+1. Python严格采用4个空格的缩进,任何python代码都都必须遵守此规定。
+2. web部分代码(HTML, CSS, JavaScript),Node.js采用2空格缩进,同样不使用tab (\t)。
+之所以与Python不同,是因为js中有大量回调式的写法,2空格可以显著降低视觉上的负担。
+
+#### 最大行长度
+
+按PEP8规范,Python一般限制最大79个字符, 但是Django的命名,url等通常比较长,
+而且21世纪都是宽屏了,所以我们限制最大120字符
+
+**补充说明:HTML代码不受此规范约束。**
+
+#### 长语句缩进
+
+编写长语句时,可以使用换行符(\)换行。在这种情况下,下一行应该与上一行的最后
+一个“.”句点或“=”对齐,或者是缩进4个空格符
+
+```
+this_is_a_very_long(function_call, 'with many parameters') \
+ .that_returns_an_object_with_an_attribute
+
+MyModel.query.filter(MyModel.scalar > 120) \
+ .order_by(MyModel.name.desc()) \
+ .limit(10)
+```
+
+如果你使用括号“()”或花括号“{}”为长语句换行,那么下一行应与括号或花括号对齐:
+```
+this_is_a_very_long(function_call, 'with many parameters',
+ 23, 42, 'and even more')
+```
+
+对于元素众多的列表或元组,在第一个“[”或“(”之后马上换行:
+
+```
+items = [
+ 'this is the first', 'set of items', 'with more items',
+ 'to come in this line', 'like this'
+]
+```
+
+#### 空行
+
+顶层函数与类之间空两行,此外都只空一行。不要在代码中使用太多的空行来区分不同的逻辑模块。
+
+```
+def hello(name):
+ print 'Hello %s!' % name
+
+
+def goodbye(name):
+ print 'See you %s.' % name
+
+
+class MyClass(object):
+ """This is a simple docstring."""
+
+ def __init__(self, name):
+ self.name = name
+
+ def get_annoying_name(self):
+ return self.name.upper() + '!!!!111'
+```
+
+
+### 语句和表达式
+
+#### 一般空格规则
+
+1. 单目运算符与运算对象之间不空格(例如,-,~等),即使单目运算符位于括号内部也一样。
+2. 双目运算符与运算对象之间要空格。
+
+```
+exp = -1.05
+value = (item_value / item_count) * offset / exp
+value = my_list[index]
+value = my_dict['key']
+```
+
+#### 比较
+
+1. 任意类型之间的比较,使用“==”和“!=”。
+2. 与单例(singletons)进行比较时,使用is和is not。
+3. 永远不要与True或False进行比较(例如,不要这样写:foo == False,而应该这样写:not foo)。
+
+#### 否定成员关系检查
+
+使用foo not in bar,而不是not foo in bar。
+
+
+### 命名约定
+
+1. 类名称:采用骆驼拼写法(CamelCase),首字母缩略词保持大写不变(HTTPWriter,而不是HttpWriter)。
+2. 变量名:小写_以及_下划线(lowercase_with_underscores)。
+3. 方法与函数名:小写_以及_下划线(lowercase_with_underscores)。
+4. 常量:大写_以及_下划线(UPPERCASE_WITH_UNDERSCORES)。
+5. 预编译的正则表达式:name_re。
+6. 受保护的元素以一个下划线为前缀。双下划线前缀只有定义混入类(mixin classes)时才使用。
+7. 如果使用关键词(keywords)作为类名称,应在名称后添加后置下划线(trailing underscore)。
+允许与内建变量重名,不要在变量名后添加下划线进行区分。如果函数需要访问重名的内建变量,请将内建变量重新绑定为其他名称。
+8. 命名要有寓意, 不使用拼音,不使用无意义简单字母命名 (循环中计数例外 for i in)
+9. 命名缩写要谨慎, 尽量是大家认可的缩写
+
+
+#### 函数和方法的参数:
+
+1. 类方法:cls为第一个参数。
+2. 实例方法:self为第一个参数。
+3. property函数中使用匿名函数(lambdas)时,匿名函数的第一个参数可以用x替代,
+例如:display_name = property(lambda x: x.real_name or x.username)。
+
+
+
+### 文档注释(Docstring,即各方法,类的说明文档注释)
+
+所有文档字符串均以reStructuredText格式编写,方便Sphinx处理。文档字符串的行数不同,布局也不一样。
+如果只有一行,代表字符串结束的三个引号与代表字符串开始的三个引号在同一行。
+如果为多行,文档字符串中的文本紧接着代表字符串开始的三个引号编写,代表字符串结束的三个引号则自己独立成一行。
+(有能力尽可能用英文, 否则请中文优雅注释)
+
+
+```
+def foo():
+ """This is a simple docstring."""
+
+
+def bar():
+ """This is a longer docstring with so much information in there
+ that it spans three lines. In this case, the closing triple quote
+ is on its own line.
+ """
+```
+
+文档字符串应分成简短摘要(尽量一行)和详细介绍。如果必要的话,摘要与详细介绍之间空一行。
+
+### 模块头部
+
+模块文件的头部包含有utf-8编码声明(如果模块中使用了非ASCII编码的字符,建议进行声明),以及标准的文档字符串。
+
+```
+# -*- coding: utf-8 -*-
+"""
+ package.module
+ ~~~~~~~~~~~~~~
+
+ A brief description goes here.
+
+ :copyright: (c) YEAR by AUTHOR.
+ :license: LICENSE_NAME, see LICENSE_FILE for more details.
+"""
+```
+
+
+### 注释(comment)
+
+注释的规范与文档字符串编写规范类似。二者均以reStructuredText格式编写。
+如果使用注释来编写类属性的文档,请在#符号后添加一个冒号":"。
+(有能力尽可能用英文, 否则请中文优雅注释)
+
+```
+class User(object):
+ #: the name of the user as unicode string
+ name = Column(String)
+ #: the sha1 hash of the password + inline salt
+ pw_hash = Column(String)
+```
+
diff --git a/docs/table_design.xml b/docs/table_design.xml
new file mode 100644
index 000000000..acc1fe395
--- /dev/null
+++ b/docs/table_design.xml
@@ -0,0 +1,795 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+INTEGER
+NULL
+
+VARCHAR(20)
+'NULL'
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR(30)
+
+
+BINARY
+NULL
+
+VARCHAR(20)
+NULL
+
+VARBINARY
+NULL
+
+INTEGER
+0
+
+INTEGER
+0
+
+INTEGER
+0
+
+INTEGER
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+CHAR
+NULL
+
+DATETIME
+'now()'
+
+DATETIME
+NULL
+
+DATETIME
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+DATETIME
+NULL
+
+VARCHAR
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+INTEGER
+NULL
+
+
+id
+
+
+
+
+INTEGER
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+INTEGER
+NULL
+
+
+id
+
+
+
+
+INTEGER
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+INTEGER
+NULL
+
+
+id
+
+
+
+
+INTEGER
+NULL
+
+VARCHAR
+NULL
+
+CHAR
+NULL
+
+INTEGER
+NULL
+
+VARCHAR
+NULL
+
+VARBINARY
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+INTEGER
+NULL
+
+
+INTEGER
+NULL
+
+
+VARCHAR
+NULL
+
+INTEGER
+NULL
+
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+INTEGER
+NULL
+
+CHAR
+NULL
+
+VARCHAR
+NULL
+
+DATETIME
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+DATETIME
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+DATETIME
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+INTEGER
+NULL
+
+
+id
+
+
+
+
+INTEGER
+NULL
+
+CHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+DATETIME
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+INTEGER
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+DATETIME
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+INTEGER
+NULL
+
+
+id
+
+
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+CHAR
+NULL
+
+DATETIME
+NULL
+
+DATETIME
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+CHAR
+NULL
+
+INTEGER
+NULL
+
+DATETIME
+NULL
+
+DATE
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+VARCHAR
+NULL
+
+TIME
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+INTEGER
+NULL
+
+
+id
+
+
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+INTEGER
+NULL
+
+
+id
+
+
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+INTEGER
+NULL
+
+
+id
+
+
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+INTEGER
+NULL
+
+
+id
+
+
+
+
+INTEGER
+NULL
+
+CHAR
+NULL
+
+VARCHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+DATE
+NULL
+
+DATE
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+DATETIME
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+VARCHAR
+NULL
+
+CHAR
+NULL
+
+VARCHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+CHAR
+NULL
+
+INTEGER
+NULL
+
+DATETIME
+NULL
+
+DATETIME
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+CHAR
+NULL
+
+VARCHAR
+NULL
+
+DATE
+NULL
+
+DATE
+NULL
+
+id
+
+
+
+
+INTEGER
+NULL
+
+INTEGER
+NULL
+
+
+INTEGER
+NULL
+
+
+CHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+VARCHAR
+NULL
+
+INTEGER
+NULL
+
+DATETIME
+NULL
+
+TIME
+NULL
+
+id
+
+
+
+
diff --git a/install/example.sh b/install/example.sh
new file mode 100644
index 000000000..e69de29bb
diff --git a/logs/.gitkeep b/logs/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/requirements/deb_requirements.txt b/requirements/deb_requirements.txt
new file mode 100644
index 000000000..75a85672b
--- /dev/null
+++ b/requirements/deb_requirements.txt
@@ -0,0 +1 @@
+ibtiff4-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk
\ No newline at end of file
diff --git a/requirements/mac_requirements.py b/requirements/mac_requirements.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/requirements/requirements.txt b/requirements/requirements.txt
new file mode 100644
index 000000000..e3700f963
--- /dev/null
+++ b/requirements/requirements.txt
@@ -0,0 +1,21 @@
+Django==1.10
+django-bootstrap-form==3.2.1
+logging==0.4.9.6
+Pillow==4.0.0
+djangorestframework==3.5.3
+ForgeryPy==0.1
+openpyxl==2.4.0
+celery==3.1.23
+paramiko==2.1.1
+ansible==2.1.2.0
+django-simple-captcha==0.5.2
+django-formtools==1.0
+sshpubkeys==2.2.0
+djangorestframework-bulk==0.2.1
+django-redis-cache==1.7.1
+requests==2.11.1
+itsdangerous==0.24
+#python-gssapi==0.6.4
+tornado==4.4.2
+eventlet==0.20.1
+django-filter==1.0.0
diff --git a/requirements/rpm_requirements.txt b/requirements/rpm_requirements.txt
new file mode 100644
index 000000000..3853d8419
--- /dev/null
+++ b/requirements/rpm_requirements.txt
@@ -0,0 +1 @@
+libtiff-devel libjpeg-devel libzip-devel freetype-devel lcms2-devel libwebp-devel tcl-devel tk-devel
\ No newline at end of file
diff --git a/run_server.py b/run_server.py
new file mode 100644
index 000000000..fc730ae51
--- /dev/null
+++ b/run_server.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+# ~*~ coding: utf-8 ~*~
+
+from threading import Thread
+import os
+import subprocess
+
+try:
+ from config import config as env_config, env
+
+ CONFIG = env_config.get(env, 'default')()
+except ImportError:
+ CONFIG = type('_', (), {'__getattr__': None})()
+
+
+BASE_DIR = os.path.dirname(os.path.abspath(__file__))
+
+apps_dir = os.path.join(BASE_DIR, 'apps')
+
+
+def start_django():
+ http_host = CONFIG.HTTP_BIND_HOST or '127.0.0.1'
+ http_port = CONFIG.HTTP_LISTEN_PORT or '8080'
+ os.chdir(apps_dir)
+ print('start django')
+ subprocess.call('python ./manage.py runserver %s:%s' % (http_host, http_port), shell=True)
+
+
+def start_celery():
+ os.chdir(apps_dir)
+ os.environ.setdefault('C_FORCE_ROOT', '1')
+ print('start celery')
+ subprocess.call('celery -A common worker -P eventlet -s /tmp/celerybeat-schedule -l info ', shell=True)
+
+
+def main():
+ t1 = Thread(target=start_django, args=())
+ t2 = Thread(target=start_celery, args=())
+
+ t1.start()
+ t2.start()
+
+ t1.join()
+ t2.join()
+
+
+if __name__ == '__main__':
+ main()
+
+
+
+
+
+
diff --git a/utils/clean_migrations.sh b/utils/clean_migrations.sh
new file mode 100755
index 000000000..c1c8e6e09
--- /dev/null
+++ b/utils/clean_migrations.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+#
+
+for app in users assets perms audits ops applications;do
+ rm -f ../apps/$app/migrations/000*
+done
diff --git a/utils/generate_fake.sh b/utils/generate_fake.sh
new file mode 100644
index 000000000..c5577798e
--- /dev/null
+++ b/utils/generate_fake.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+#
+
+python ../apps/manage.py loaddata fake
diff --git a/utils/init_db.sh b/utils/init_db.sh
new file mode 100755
index 000000000..4073ad001
--- /dev/null
+++ b/utils/init_db.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+#
+
+python ../apps/manage.py loaddata init
diff --git a/utils/make_fake_json.sh b/utils/make_fake_json.sh
new file mode 100644
index 000000000..cd4b462d5
--- /dev/null
+++ b/utils/make_fake_json.sh
@@ -0,0 +1,17 @@
+#!/bin/bash
+#
+
+python ../apps/manage.py shell << EOF
+from users.models.utils import *
+generate_fake()
+from assets.models.utils import *
+generate_fake()
+EOF
+
+python ../apps/manage.py dbshell << EOF
+delete from django_content_type;
+delete from auth_permission;
+EOF
+
+
+python ../apps/manage.py dumpdata > ../apps/fixtures/fake.json
diff --git a/utils/make_init_json.sh b/utils/make_init_json.sh
new file mode 100644
index 000000000..0f3fb659f
--- /dev/null
+++ b/utils/make_init_json.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+#
+
+python ../apps/manage.py shell << EOF
+from users.models import *
+init_all_models()
+
+from assets.models import *
+init_all_models()
+EOF
+
+
+python ../apps/manage.py dbshell << EOF
+delete from django_content_type;
+delete from auth_permission;
+EOF
+
+python ../apps/manage.py dumpdata > ../apps/fixtures/init.json
diff --git a/utils/make_migrations.sh b/utils/make_migrations.sh
new file mode 100755
index 000000000..0704b9cc9
--- /dev/null
+++ b/utils/make_migrations.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+#
+
+python ../apps/manage.py makemigrations
+
+python ../apps/manage.py migrate
diff --git a/utils/redis.conf b/utils/redis.conf
new file mode 100644
index 000000000..0621db3bf
--- /dev/null
+++ b/utils/redis.conf
@@ -0,0 +1,4 @@
+daemonize yes
+port 6379
+logfile "/opt/jumpserver/logs/redis.log"
+dir /opt/jumpserver/
\ No newline at end of file