From 0b9dd6c11f880679a23797d3c37cb902a4396e58 Mon Sep 17 00:00:00 2001 From: anas-srikou Date: Thu, 16 Feb 2023 18:03:07 +0900 Subject: [PATCH 1/3] Reboot intercom with new session when user log out --- app/index.html | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/app/index.html b/app/index.html index 687aacc5..7affb87c 100644 --- a/app/index.html +++ b/app/index.html @@ -140,42 +140,54 @@ \ No newline at end of file + }, 1000) + +function shutdownIntercom() { + window.Intercom('shutdown'); +} + +function startIntercom() { + window.Intercom('boot', { + app_id: "ymvqkyiw", + }); +} \ No newline at end of file diff --git a/dist/scripts/app.a969cdda.js b/dist/scripts/app.b36db56e.js similarity index 93% rename from dist/scripts/app.a969cdda.js rename to dist/scripts/app.b36db56e.js index 29247341..1f907942 100644 --- a/dist/scripts/app.a969cdda.js +++ b/dist/scripts/app.b36db56e.js @@ -1 +1 @@ -"use strict";function setLicenseExpiredRoute($routeProvider){$routeProvider.when("/license-expired",{templateUrl:"admin_components/adf-license-expired/license-expired.html"})}angular.module("dfUserManagement",["ngRoute","ngCookies","dfUtility"]).constant("MODUSRMNGR_ROUTER_PATH","/user-management").constant("MODUSRMNGR_ASSET_PATH","admin_components/adf-user-management/").run(["$cookies","UserDataService","SystemConfigDataService",function($cookies,UserDataService,SystemConfigDataService){var cookie=$cookies.getObject("CurrentUserObj");cookie&&(UserDataService.setCurrentUser(cookie),SystemConfigDataService.getSystemConfig()||UserDataService.unsetCurrentUser())}]).controller("UserManagementCtrl",["$scope",function($scope){}]).directive("modusrmngrNavigation",["MODUSRMNGR_ASSET_PATH",function(MODUSRMNGR_ASSET_PATH){return{restrict:"E",templateUrl:MODUSRMNGR_ASSET_PATH+"views/navigation.html",link:function(scope,elem,attrs){}}}]).directive("dreamfactoryUserLogin",["MODUSRMNGR_ASSET_PATH","INSTANCE_URL","$http","$location","UserEventsService","UserDataService","_dfObjectService","SystemConfigDataService",function(MODUSRMNGR_ASSET_PATH,INSTANCE_URL,$http,$location,UserEventsService,UserDataService,_dfObjectService,SystemConfigDataService){return{restrict:"E",replace:!0,scope:{options:"=?",inErrorMsg:"=?"},templateUrl:MODUSRMNGR_ASSET_PATH+"views/login.html",link:function(scope,elem,attrs){scope.es=UserEventsService.login;var defaults={showTemplate:!0};scope.options=_dfObjectService.mergeObjects(scope.options,defaults),scope.showTemplate=scope.options.showTemplate,scope.loginFormTitle="Login",scope.loginActive=!0,scope.creds={email:"",password:""},scope.errorMsg=scope.inErrorMsg||"",scope.successMsg="",scope.loginWaiting=!1,scope.showOAuth=!0,scope.loginForm={},scope.adldap=[],scope.loginAttribute="email",scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&(scope.systemConfig.authentication.hasOwnProperty("adldap")&&(scope.adldap=scope.systemConfig.authentication.adldap),scope.systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=scope.systemConfig.authentication.login_attribute)),scope.adldapAvailable=scope.adldap.length>0,scope.selectedService=null,scope.rememberMe=!1,"username"===scope.loginAttribute?scope.userField={icon:"fa-user",text:"Enter Username",type:"text"}:scope.userField={icon:"fa-envelope",text:"Enter Email",type:"email"},scope.rememberLogin=function(checked){scope.rememberMe=checked},scope.useAdLdapService=function(service){scope.selectedService=service,service?(scope.userField={icon:"fa-user",text:"Enter Username",type:"text"},scope.creds={username:"",password:"",service:service}):"username"===scope.loginAttribute?(scope.userField={icon:"fa-user",text:"Enter Username",type:"text"},scope.creds={username:"",password:""}):(scope.userField={icon:"fa-envelope",text:"Enter Email",type:"email"},scope.creds={email:"",password:""})},scope.getQueryParameter=function(key){key=key.replace(/[*+?^$.\[\]{}()|\\\/]/g,"\\$&");var match=window.location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)")),result=match&&decodeURIComponent(match[1].replace(/\+/g," "));return result||""};var token=scope.getQueryParameter("session_token"),oauth_code=scope.getQueryParameter("code"),oauth_state=scope.getQueryParameter("state"),oauth_token=scope.getQueryParameter("oauth_token"),baseUrl=$location.absUrl().split("?")[0];""!==token?(scope.loginWaiting=!0,scope.showOAuth=!1,scope.loginDirect=!0,$http.get(INSTANCE_URL.url+"/user/session?session_token="+token).then(function(result){UserDataService.setCurrentUser(result.data),scope.$emit(scope.es.loginSuccess,result.data),scope.loginDirect=!1},function(result){window.location.href=baseUrl+"#/login",scope.loginDirect=!1})):(oauth_code&&oauth_state||oauth_token)&&(scope.loginWaiting=!0,scope.showOAuth=!1,$http.post(INSTANCE_URL.url+"/user/session?oauth_callback=true&"+location.search.substring(1)).then(function(result){UserDataService.setCurrentUser(result.data),scope.$emit(scope.es.loginSuccess,result.data)})),scope.login=function(credsDataObj){scope.selectedService?(credsDataObj.username=$("#df-login-email").val(),credsDataObj.password=$("#df-login-password").val(),credsDataObj.service=scope.selectedService):"username"===scope.loginAttribute?(credsDataObj.username=$("#df-login-email").val(),credsDataObj.password=$("#df-login-password").val()):""!==credsDataObj.email&&""!==credsDataObj.password||(credsDataObj.email=$("#df-login-email").val(),credsDataObj.password=$("#df-login-password").val()),credsDataObj.remember_me=scope.rememberMe,scope._login(credsDataObj)},scope.forgotPassword=function(){scope._forgotPassword()},scope.skipLogin=function(){scope._skipLogin()},scope.showLoginForm=function(){scope._toggleForms()},scope.dismissError=function(){scope.errorMsg=""},scope.dismissSuccess=function(){scope.successMsg=""},scope._loginRequest=function(credsDataObj,admin){return admin?$http.post(INSTANCE_URL.url+"/system/admin/session",credsDataObj):$http.post(INSTANCE_URL.url+"/user/session",credsDataObj)},scope._toggleFormsState=function(){scope.loginActive=!scope.loginActive,scope.resetPasswordActive=!scope.resetPasswordActive},scope._login=function(credsDataObj){scope.loginWaiting=!0,scope._loginRequest(credsDataObj,!1).then(function(result){UserDataService.setCurrentUser(result.data),scope.$emit(scope.es.loginSuccess,result.data),scope.$root.$emit(scope.es.loginSuccess,result.data)},function(reject){"401"!=reject.status&&"404"!=reject.status||scope.selectedService?(scope.errorMsg=reject.data.error.message,scope.$emit(scope.es.loginError,reject)):(scope.loginWaiting=!0,scope._loginRequest(credsDataObj,!0).then(function(result){UserDataService.setCurrentUser(result.data),scope.$emit(scope.es.loginSuccess,result.data),scope.$root.$emit(scope.es.loginSuccess,result.data)},function(reject){scope.errorMsg=reject.data.error.message,scope.$emit(scope.es.loginError,reject)}).finally(function(){scope.loginWaiting=!1}))}).finally(function(){scope.loginWaiting=!1})},scope._toggleForms=function(){scope._toggleFormsState()},scope._forgotPassword=function(){scope.$broadcast(UserEventsService.password.passwordResetRequest,{email:scope.creds.email})},scope._skipLogin=function(){$location.url("/services")};scope.$watch("options",function(newValue,oldValue){newValue&&newValue.hasOwnProperty("showTemplate")&&(scope.showTemplate=newValue.showTemplate)},!0);scope.$on(scope.es.loginRequest,function(e,userDataObj){scope._login(userDataObj)})}}}]).directive("dreamfactoryForgotPwordEmail",["MODUSRMNGR_ASSET_PATH","INSTANCE_URL","$http","UserEventsService","SystemConfigDataService",function(MODUSRMNGR_ASSET_PATH,INSTANCE_URL,$http,UserEventsService,SystemConfigDataService){return{restrict:"E",replace:!0,scope:!1,templateUrl:MODUSRMNGR_ASSET_PATH+"views/fp-email-conf.html",link:function(scope,elem,attrs){scope.es=UserEventsService.password,scope.emailForm=!0,scope.emailError=!1,scope.securityQuestionForm=!1,scope.hidePasswordField=!1,scope.allowForeverSessions=!1,scope.loginAttribute="email",scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&(scope.systemConfig.authentication.hasOwnProperty("allow_forever_sessions")&&(scope.allowForeverSessions=scope.systemConfig.authentication.allow_forever_sessions),scope.systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=scope.systemConfig.authentication.login_attribute)),scope.resetByEmail=!0,scope.resetByUsername=!1,"username"===scope.loginAttribute&&(scope.resetByEmail=!1,scope.resetByUsername=!0),scope.sq={email:null,username:null,security_question:null,security_answer:null,new_password:null,verify_password:null},scope.identical=!0,scope.requestWaiting=!1,scope.questionWaiting=!1,scope.requestPasswordReset=function(emailDataObj){scope._requestPasswordReset(emailDataObj)},scope.securityQuestionSubmit=function(reset){scope.identical?scope._verifyPasswordLength(reset)?scope._securityQuestionSubmit(reset):scope.errorMsg="Password must be at least 5 characters.":scope.errorMsg="Passwords do not match."},scope.verifyPassword=function(user){scope._verifyPassword(user)},scope._resetPasswordRequest=function(requestDataObj,admin){return admin?$http.post(INSTANCE_URL.url+"/system/admin/password?reset=true",requestDataObj):$http.post(INSTANCE_URL.url+"/user/password?reset=true",requestDataObj)},scope._resetPasswordSQ=function(requestDataObj,admin){return admin?$http.post(INSTANCE_URL.url+"/system/admin/password?login=false",requestDataObj):$http.post(INSTANCE_URL.url+"/user/password?login=false",requestDataObj)},scope._verifyPassword=function(userDataObj){scope.identical=userDataObj.new_password===userDataObj.verify_password},scope._verifyPasswordLength=function(credsDataObj){return credsDataObj.new_password.length>=5},scope._requestPasswordReset=function(requestDataObj){requestDataObj.reset=!0,scope.requestWaiting=!0,scope._resetPasswordRequest(requestDataObj,!1).then(function(result){result.data.hasOwnProperty("security_question")?(scope.emailForm=!1,scope.securityQuestionForm=!0,scope.sq.email=requestDataObj.email,scope.sq.username=requestDataObj.username?requestDataObj.username:null,scope.sq.security_question=result.data.security_question):(scope.successMsg="A password reset email has been sent to the user's email address.",scope.$emit(scope.es.passwordResetRequestSuccess,requestDataObj.email))},function(reject){"401"==reject.status||"404"==reject.status?scope._resetPasswordRequest(requestDataObj,!0).then(function(result){result.data.hasOwnProperty("security_question")?(scope.emailForm=!1,scope.securityQuestionForm=!0,scope.sq.email=requestDataObj.email,scope.sq.security_question=result.data.security_question):(scope.successMsg="A password reset email has been sent to the user's email address.",scope.$emit(scope.es.passwordResetRequestSuccess,requestDataObj.email))},function(reject){scope.errorMsg=reject.data.error.message}).finally(function(){scope.requestWaiting=!1}):scope.errorMsg=reject.data.error.message}).finally(function(){scope.requestWaiting=!1})},scope._securityQuestionSubmit=function(reset){scope.questionWaiting=!0,scope._resetPasswordSQ(reset,!1).then(function(result){var userCredsObj={email:reset.email,username:reset.username?reset.username:null,password:reset.new_password};scope.$emit(UserEventsService.password.passwordSetSuccess,userCredsObj)},function(reject){"401"==reject.status||"404"==reject.status?scope._resetPasswordSQ(reset,!0).then(function(result){var userCredsObj={email:reset.email,password:reset.new_password};scope.$emit(UserEventsService.password.passwordSetSuccess,userCredsObj)},function(reject){scope.questionWaiting=!1,scope.errorMsg=reject.data.error.message,scope.$emit(UserEventsService.password.passwordSetError)}).finally(function(){}):(scope.questionWaiting=!1,scope.errorMsg=reject.data.error.message,scope.$emit(UserEventsService.password.passwordSetError))}).finally(function(){})},scope.$on(UserEventsService.password.passwordResetRequest,function(e,resetDataObj){scope._toggleForms()})}}}]).directive("dreamfactoryForgotPwordQuestion",["MODUSRMNGR_ASSET_PATH",function(MODUSRMNGR_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MODUSRMNGR_ASSET_PATH+"views/fp-security-question.html",link:function(scope,elem,attrs){}}}]).directive("dreamfactoryPasswordReset",["MODUSRMNGR_ASSET_PATH","INSTANCE_URL","$http","UserEventsService","_dfObjectService","dfNotify","$location","SystemConfigDataService",function(MODUSRMNGR_ASSET_PATH,INSTANCE_URL,$http,UserEventsService,_dfObjectService,dfNotify,$location,SystemConfigDataService){return{restrict:"E",scope:{options:"=?",inErrorMsg:"=?"},templateUrl:MODUSRMNGR_ASSET_PATH+"views/password-reset.html",link:function(scope,elem,attrs){scope.es=UserEventsService.password;var defaults={showTemplate:!0,login:!1};scope.options=_dfObjectService.mergeObjects(scope.options,defaults),scope.showTemplate=scope.options.showTemplate,scope.identical=!0,scope.successMsg="",scope.errorMsg="",scope.loginAttribute="email",scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&scope.systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=scope.systemConfig.authentication.login_attribute),scope.resetByEmail=!0,scope.resetByUsername=!1,"username"===scope.loginAttribute&&(scope.resetByEmail=!1,scope.resetByUsername=!0),scope.resetWaiting=!1,scope.user={};var UrlParams=$location.search();Object.keys(UrlParams).forEach(function(key,index){scope.user[key]=UrlParams[key]});var isAdmin="1"==scope.user.admin;scope.dismissError=function(){scope.errorMsg=""},scope.dismissSuccess=function(){scope.successMsg=""},scope.resetPassword=function(credsDataObj){scope.identical?scope._verifyPasswordLength(credsDataObj)?scope._resetPassword(credsDataObj):scope.errorMsg="Password must be at least 5 characters.":scope.errorMsg="Passwords do not match."},scope.verifyPassword=function(user){scope._verifyPassword(user)},scope._setPasswordRequest=function(requestDataObj,admin){var url=INSTANCE_URL.url+"/system/admin/password";return admin||(url=INSTANCE_URL.url+"/user/password"),$http({url:url,method:"POST",params:{login:scope.options.login},data:requestDataObj})},scope._verifyPassword=function(userDataObj){scope.identical=userDataObj.new_password===userDataObj.verify_password},scope._verifyPasswordLength=function(credsDataObj){return credsDataObj.new_password.length>=5},scope._resetPassword=function(credsDataObj){scope.resetWaiting=!0;var requestDataObj={email:credsDataObj.email,username:credsDataObj.username?credsDataObj.username:null,code:credsDataObj.code,new_password:credsDataObj.new_password};scope._setPasswordRequest(requestDataObj,isAdmin).then(function(result){var userCredsObj={email:credsDataObj.email,username:credsDataObj.username?credsDataObj.username:null,password:credsDataObj.new_password};scope.$emit(scope.es.passwordSetSuccess,userCredsObj),scope.showTemplate=!1},function(reject){"401"==reject.status||"404"==reject.status?scope._setPasswordRequest(requestDataObj,!0).then(function(result){var userCredsObj={email:credsDataObj.email,password:credsDataObj.new_password};scope.$emit(scope.es.passwordSetSuccess,userCredsObj),scope.showTemplate=!1},function(reject){scope.errorMsg=reject.data.error.message,scope.$emit(scope.es.passwordSetError),scope.resetWaiting=!1}).finally(function(){scope.resetWaiting=!1}):(scope.errorMsg=reject.data.error.message,scope.$emit(scope.es.passwordSetError),scope.resetWaiting=!1)}).finally(function(){scope.resetWaiting=!1})};var watchInErrorMsg=scope.$watch("inErrorMsg",function(n,o){scope.confirmWaiting=!1,scope.errorMsg=n});scope.$on(scope.es.passwordSetRequest,function(e,credsDataObj){scope._resetPassword(credsDataObj)}),scope.$on("$destroy",function(e){watchInErrorMsg()})}}}]).directive("dreamfactoryUserLogout",["INSTANCE_URL","$http","UserEventsService","UserDataService",function(INSTANCE_URL,$http,UserEventsService,UserDataService){return{restrict:"E",scope:{},link:function(scope,elem,attrs){scope.es=UserEventsService.logout,scope._logoutRequest=function(admin){var url=UserDataService.getCurrentUser().is_sys_admin?"/system/admin/session":"/user/session";return $http.delete(INSTANCE_URL.url+url)},scope._logout=function(){scope._logoutRequest(!1).then(function(){UserDataService.unsetCurrentUser(),scope.$emit(scope.es.logoutSuccess,!1)},function(reject){if("401"!=reject.status&&"401"!=reject.data.error.code)throw{module:"DreamFactory User Management",type:"error",provider:"dreamfactory",exception:reject};UserDataService.unsetCurrentUser(),scope.$emit(scope.es.logoutSuccess,!1)})},scope.$on(scope.es.logoutRequest,function(e){scope._logout()}),scope._logout()}}}]).directive("dreamfactoryRegisterUser",["MODUSRMNGR_ASSET_PATH","INSTANCE_URL","$http","$rootScope","$location","UserEventsService","_dfObjectService","dfXHRHelper","SystemConfigDataService",function(MODUSRMNGR_ASSET_PATH,INSTANCE_URL,$http,$rootScope,$location,UserEventsService,_dfObjectService,dfXHRHelper,SystemConfigDataService){return{restrict:"E",templateUrl:MODUSRMNGR_ASSET_PATH+"views/register.html",scope:{options:"=?"},link:function(scope,elem,attrs){scope.es=UserEventsService.register;var defaults={showTemplate:!0,login:!1};scope.options=_dfObjectService.mergeObjects(scope.options,defaults),scope.showTemplate=scope.options.showTemplate,scope.identical=!0,scope.errorMsg="",scope.loginAttribute="email",scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&scope.systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=scope.systemConfig.authentication.login_attribute),scope.user={};var UrlParams=$location.search();Object.keys(UrlParams).forEach(function(key,index){scope.user[key]=UrlParams[key]}),scope.dismissError=function(){scope.errorMsg=""},scope.register=function(registerDataObj){scope._register(registerDataObj)},scope.verifyPassword=function(user){scope._verifyPassword(user)},scope._registerRequest=function(registerDataObj){return $http({url:INSTANCE_URL.url+"/user/register",method:"POST",params:{login:scope.options.login},data:registerDataObj})},scope._getSystemConfig=function(){return $http.get(INSTANCE_URL.url+"/system/environment")},scope._register=function(registerDataObj){1==scope.identical?(scope._runRegister=function(registerDataObj){scope._registerRequest(registerDataObj).then(function(result){if(null==scope.options.confirmationRequired){var userCredsObj={email:registerDataObj.email,password:registerDataObj.new_password};scope.$emit(scope.es.registerSuccess,userCredsObj)}else scope.$emit(scope.es.registerConfirmation,result.data)},function(reject){var msg="Validation failed. ",context=reject.data.error.context;null==context?reject.data&&reject.data.error&&reject.data.error.message&&(msg+=reject.data.error.message):angular.forEach(context,function(value,key){msg=msg+key+": "+value+" "},msg),scope.errorMsg=msg})},null==scope.options.confirmationRequired?scope._getSystemConfig().then(function(result){var systemConfigDataObj=result.data;scope.options.confirmationRequired=systemConfigDataObj.authentication.open_reg_email_service_id,scope._runRegister(registerDataObj)},function(reject){throw{module:"DreamFactory User Management",type:"error",provider:"dreamfactory",exception:reject}}):scope._runRegister(registerDataObj)):scope.errorMsg="Password and confirm password do not match."},scope._verifyPassword=function(userDataObj){scope.identical=userDataObj.new_password===userDataObj.verify_password},scope.$watchCollection("options",function(newValue,oldValue){if(!newValue.hasOwnProperty("confirmationRequired")){var config=dfXHRHelper.get({url:"system/environment"});scope.options.confirmationRequired=!(!config.authentication.allow_open_registration||!config.authentication.open_reg_email_service_id)||null}}),scope.$on(scope.es.registerRequest,function(e,registerDataObj){scope._register(registerDataObj)})}}}]).directive("dreamfactoryUserProfile",["MODUSRMNGR_ASSET_PATH","_dfObjectService","UserDataService","UserEventsService",function(MODUSRMNGR_ASSET_PATH,_dfObjectService,UserDataService,UserEventsService){return{restrict:"E",replace:!0,templateUrl:MODUSRMNGR_ASSET_PATH+"views/edit-profile.html",scope:{options:"=?"},link:function(scope,elem,attrs){scope.es=UserEventsService.profile;var defaults={showTemplate:!0};scope.options=_dfObjectService.mergeObjects(scope.options,defaults)}}}]).directive("dreamfactoryRemoteAuthProviders",["MODUSRMNGR_ASSET_PATH","SystemConfigDataService","INSTANCE_URL",function(MODUSRMNGR_ASSET_PATH,SystemConfigDataService,INSTANCE_URL){return{restrict:"E",replace:!0,templateUrl:MODUSRMNGR_ASSET_PATH+"views/remote-auth-providers.html",scope:!1,link:function(scope,elem,attrs){scope.url=INSTANCE_URL.url,scope.oauths=[],scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&scope.systemConfig.authentication.hasOwnProperty("oauth")&&(scope.oauths=scope.systemConfig.authentication.oauth),scope.remoteAuthLogin=function(providerData){window.top.location.href=scope.url+"/"+providerData}}}}]).directive("dreamfactorySamlAuthProviders",["MODUSRMNGR_ASSET_PATH","SystemConfigDataService","INSTANCE_URL",function(MODUSRMNGR_ASSET_PATH,SystemConfigDataService,INSTANCE_URL){return{restrict:"E",replace:!0,templateUrl:MODUSRMNGR_ASSET_PATH+"views/saml-auth-providers.html",scope:!1,link:function(scope,elem,attrs){scope.url=INSTANCE_URL.url,scope.samls=[],scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&scope.systemConfig.authentication.hasOwnProperty("saml")&&(scope.samls=scope.systemConfig.authentication.saml),scope.samlAuthLogin=function(providerData){window.top.location.href=scope.url+"/"+providerData}}}}]).directive("dreamfactoryConfirmUser",["MODUSRMNGR_ASSET_PATH","INSTANCE_URL","$location","$http","_dfObjectService","UserDataService","UserEventsService","SystemConfigDataService",function(MODUSRMNGR_ASSET_PATH,INSTANCE_URL,$location,$http,_dfObjectService,UserDataService,UserEventsService,SystemConfigDataService){return{restrict:"E",replace:!0,templateUrl:MODUSRMNGR_ASSET_PATH+"views/confirmation-code.html",scope:{options:"=?",inErrorMsg:"=?",inviteType:"=?"},link:function(scope,elem,attrs){var defaults={showTemplate:!0,title:"User Confirmation"};scope.options=_dfObjectService.mergeObjects(scope.options,defaults),scope.showTemplate=scope.options.showTemplate,scope.identical=!0,scope.errorMsg="",scope.successMsg="",scope.confirmWaiting=!1,scope.submitLabel="Confirm "+scope.inviteType.charAt(0).toUpperCase()+scope.inviteType.slice(1),scope.loginAttribute="email",scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&scope.systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=scope.systemConfig.authentication.login_attribute),scope.useEmail=!0,scope.useUsername=!1,"username"===scope.loginAttribute&&(scope.useEmail=!1,scope.useUsername=!0),scope.user={};var UrlParams=$location.search();Object.keys(UrlParams).forEach(function(key,index){scope.user[key]=UrlParams[key]}),scope.dismissError=function(){scope.errorMsg=""},scope.dismissSuccess=function(){scope.successMsg=""},scope.confirm=function(userConfirmObj){scope.identical?scope._verifyPasswordLength(userConfirmObj)?scope._confirm(userConfirmObj):scope.errorMsg="Password must be at least 5 characters.":scope.errorMsg="Passwords do not match."},scope.verifyPassword=function(user){scope._verifyPassword(user)},scope._verifyPassword=function(userDataObj){scope.identical=userDataObj.new_password===userDataObj.verify_password},scope._verifyPasswordLength=function(user){return user.new_password.length>=5},scope._confirmUserToServer=function(requestDataObj){var api="user"===scope.inviteType?"user/password":"system/admin/password";return $http({url:INSTANCE_URL.url+"/"+api,method:"POST",params:{login:!1},data:requestDataObj})},scope._confirm=function(userConfirmObj){scope.confirmWaiting=!0;var requestDataObj=userConfirmObj;scope._confirmUserToServer(requestDataObj).then(function(result){var userCreds={email:requestDataObj.email,username:requestDataObj.username?requestDataObj.username:null,password:requestDataObj.new_password};scope.$emit(UserEventsService.confirm.confirmationSuccess,userCreds)},function(reject){scope.errorMsg=reject.data.error.message,scope.$emit(UserEventsService.confirm.confirmationError),scope.confirmWaiting=!1}).finally(function(){})};var watchInErrorMsg=scope.$watch("inErrorMsg",function(n,o){scope.confirmWaiting=!1,scope.errorMsg=n});scope.$on("$destroy",function(e){watchInErrorMsg()}),scope.$on(UserEventsService.confirm.confirmationRequest,function(e,confirmationObj){scope._confirm(confirmationObj)})}}}]).directive("dreamfactoryWaiting",["MODUSRMNGR_ASSET_PATH",function(MODUSRMNGR_ASSET_PATH){return{restrict:"E",scope:{show:"=?"},replace:!1,templateUrl:MODUSRMNGR_ASSET_PATH+"views/dreamfactory-waiting.html",link:function(scope,elem,attrs){function size(){h=el.parent(".panel-body").outerHeight(),w=el.parent(".panel-body").outerWidth(),t=el.parent(".panel-body").position().top,l=el.parent(".panel-body").position().left,container.css({height:h+"px",width:w+"px",position:"absolute",left:l,top:t}),container.children(".df-spinner").css({position:"absolute",top:(h-110)/2,left:(w-70)/2})}var el=$(elem),container=el.children(),h=el.parent(".panel-body").outerHeight(),w=el.parent(".panel-body").outerWidth(),t=el.position().top+parseInt(el.parent().css("padding-top"))+"px",l=el.position().left+parseInt(el.parent().css("padding-left"))+"px";scope._showWaiting=function(){size(),container.fadeIn("fast")},scope._hideWaiting=function(){container.hide()},scope.$watch("show",function(n,o){n?scope._showWaiting():scope._hideWaiting()}),$(window).on("resize load",function(){size()})}}}]).service("UserEventsService",[function(){return{login:{loginRequest:"user:login:request",loginSuccess:"user:login:success",loginError:"user:login:error"},logout:{logoutRequest:"user:logout:request",logoutSuccess:"user:logout:success",logoutError:"user:logout:error"},register:{registerRequest:"user:register:request",registerSuccess:"user:register:success",registerError:"user:register:error",registerConfirmation:"user:register:confirmation"},password:{passwordResetRequest:"user:passwordreset:request",passwordResetRequestSuccess:"user:passwordreset:requestsuccess",passwordSetRequest:"user:passwordset:request",passwordSetSuccess:"user:passwordset:success",passwordSetError:"user:passwordset:error"},profile:{},confirm:{confirmationSuccess:"user:confirmation:success",confirmationError:"user:confirmation:error",confirmationRequest:"user:confirmation:request"}}}]).service("UserDataService",["$cookies","$http",function($cookies,$http){function _getCurrentUser(){return currentUser}function _setCurrentUser(userDataObj){delete userDataObj.session_id,$cookies.putObject("CurrentUserObj",userDataObj),$http.defaults.headers.common["X-DreamFactory-Session-Token"]=userDataObj.session_token,currentUser=userDataObj}function _unsetCurrentUser(){$cookies.remove("CurrentUserObj"),delete $http.defaults.headers.common["X-DreamFactory-Session-Token"],currentUser=!1}var currentUser=!1;return{getCurrentUser:function(){return _getCurrentUser()},setCurrentUser:function(userDataObj){_setCurrentUser(userDataObj)},unsetCurrentUser:function(){_unsetCurrentUser()}}}]).service("_dfObjectService",[function(){return{self:this,mergeObjects:function(obj1,obj2){for(var key in obj1)obj2[key]=obj1[key];return obj2},deepMergeObjects:function(obj1,obj2){var self=this;for(var _key in obj1)obj2.hasOwnProperty(_key)&&("object"==typeof obj2[_key]?obj2[_key]=self.deepMergeObjects(obj1[_key],obj2[_key]):obj2[_key]=obj1[_key]);return obj2}}}]).service("dfXHRHelper",["INSTANCE_URL","APP_API_KEY","UserDataService",function(INSTANCE_URL,APP_API_KEY,UserDataService){function _isEmpty(obj){if(null==obj)return!0;if(obj.length>0)return!1;if(0===obj.length)return!0;for(var key in obj)if(hasOwnProperty.call(obj,key))return!1;return!0}function _setHeaders(_xhrObj,_headersDataObj){_xhrObj.setRequestHeader("X-DreamFactory-API-Key",APP_API_KEY);var currentUser=UserDataService.getCurrentUser();currentUser&¤tUser.session_tpken&&xhrObj.setRequestHeader("X-DreamFactory-Session-Token",currentUser.session_token);for(var _key in _headersDataObj)_xhrObj.setRequestHeader(_key,_headersDataObj[_key])}function _setParams(_paramsDataObj){var params="";if(!_isEmpty(_paramsDataObj)){params="?";for(var _key in _paramsDataObj)params+=_key+"="+_paramsDataObj[_key]+"&"}return""!==params&&(params=params.substring(0,params.length-1),encodeURI(params)),params}function _makeRequest(_method,_url,_async,_params,_headers,_mimeType){var xhr;xhr=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP");var params=_setParams(_params);return xhr.open(_method,INSTANCE_URL.url+"/"+_url+params,_async),_setHeaders(xhr,_headers),xhr.overrideMimeType(_mimeType),xhr.send(),4==xhr.readyState&&200==xhr.status?angular.fromJson(xhr.responseText):xhr.status}function _get(optionsDataObj){if(!optionsDataObj.url||""===optionsDataObj.url)throw{module:"DreamFactory System Config Module",type:"error",provider:"dreamfactory",exception:"XHRHelper Request Failure: No URL provided"};var defaults={method:"GET",url:"",async:!1,params:{},headers:{},mimeType:"application/json"};for(var _key in defaults)optionsDataObj.hasOwnProperty(_key)&&(defaults[_key]=optionsDataObj[_key]);return _makeRequest(defaults.method,defaults.url,defaults.async,defaults.params,defaults.headers,defaults.mimeType)}return{get:function(requestOptions){return _get(requestOptions)}}}]),angular.module("dfUtility",["dfApplication"]).constant("MOD_UTILITY_ASSET_PATH","admin_components/adf-utility/").directive("dfGithubModal",["MOD_UTILITY_ASSET_PATH","$http","dfApplicationData","$rootScope",function(MOD_UTILITY_ASSET_PATH,$http,dfApplicationData,$rootScope){return{restrict:"E",scope:{editorObj:"=?",accept:"=?",target:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-github-modal.html",link:function(scope,elem,attrs){scope.modalError={},scope.githubModal={},scope.githubUpload=function(){var url=angular.copy(scope.githubModal.url);if(url){var url_array=url.substr(url.indexOf(".com/")+5).split("/"),owner="",repo="",branch="",path="";url.indexOf("raw.github")>-1?(owner=url_array[0],repo=url_array[1],branch=url_array[2],path=url_array.splice(3,url_array.length-3).join("/")):(owner=url_array[0],repo=url_array[1],branch=url_array[3],path=url_array.splice(4,url_array.length-4).join("/"));var github_api_url="https://api.github.com/repos/"+owner+"/"+repo+"/contents/"+path+"?ref="+branch,username=angular.copy(scope.githubModal.username),password=angular.copy(scope.githubModal.password),authdata=btoa(username+":"+password);username&&($http.defaults.headers.common.Authorization="Basic "+authdata),$http.get(github_api_url,{headers:{"X-DreamFactory-API-Key":void 0,"X-DreamFactory-Session-Token":void 0},ignore401:!0}).then(function(response){switch(path.substr(path.lastIndexOf(".")+1,path.length-path.lastIndexOf("."))){case"js":"javascript";break;case"php":"php";break;case"py":"python";break;case"json":"json";break;default:"javascript"}if(scope.editorObj&&scope.editorObj.editor){var decodedString=atob(response.data.content);scope.editorObj.editor.session.setValue(decodedString),scope.editorObj.editor.focus()}var element=angular.element("#"+scope.target);element.on("hidden.bs.modal",function(){void 0!==$(this).find("form")[0]&&$(this).find("form")[0].reset()}),scope.githubModal={private:!1},scope.modalError={},element.appendTo("body").modal("hide")},function(response){401===response.status&&(scope.modalError={visible:!0,message:"Error: Authentication failed."}),404===response.status&&(scope.modalError={visible:!0,message:"Error: The file could not be found."})})}},scope.githubModalCancel=function(){scope.githubModal={private:!1},scope.modalError={};var element=angular.element("#"+scope.target);element.on("hidden.bs.modal",function(){void 0!==$(this).find("form")[0]&&$(this).find("form")[0].reset()}),element.appendTo("body").modal("hide")};scope.$watch("githubModal.username",function(newValue,oldValue){if(!newValue)return!1;scope.modalError={visible:!1,message:""}}),scope.$watch("githubModal.password",function(newValue,oldValue){if(!newValue)return!1;scope.modalError={visible:!1,message:""}}),scope.$watch("githubModal.url",function(newValue,oldValue){if(!newValue)return!1;scope.modalError={visible:!1,message:""};var file_ext=newValue.substring(newValue.lastIndexOf(".")+1,newValue.length);if(scope.accept.indexOf(file_ext)>-1){var url=angular.copy(scope.githubModal.url),url_array=url.substr(url.indexOf(".com/")+5).split("/"),github_api_url="https://api.github.com/repos/"+url_array[0]+"/"+url_array[1];$http.get(github_api_url,{headers:{"X-DreamFactory-API-Key":void 0,"X-DreamFactory-Session-Token":void 0}}).then(function(response){scope.githubModal.private=response.data.private},function(response){scope.githubModal.private=!0})}else{var formats=scope.accept.join(", ");scope.modalError={visible:!0,message:"Error: Invalid file format. Only "+formats+" file format(s) allowed"}}});scope.$on("githubShowModal",function(event,data){if(void 0!==data){var element=angular.element("#"+data);element.on("hidden.bs.modal",function(){void 0!==$(this).find("form")[0]&&$(this).find("form")[0].reset()}),element.appendTo("body").modal("show")}})}}}]).directive("dfComponentTitle",["MOD_UTILITY_ASSET_PATH","$location",function(MOD_UTILITY_ASSET_PATH,$location){return{restrict:"E",replace:!0,scope:!1,template:''}}]).directive("dfTopLevelNavStd",["MOD_UTILITY_ASSET_PATH","$location","UserDataService",function(MOD_UTILITY_ASSET_PATH,$location,UserDataService){return{restrict:"E",scope:{options:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-top-level-nav-std.html",link:function(scope,elem,attrs){scope.links=scope.options.links,scope.activeLink=null,scope.$watch(function(){return $location.path()},function(newValue,oldValue){switch(newValue){case"/home":case"/apps":case"/admins":case"/users":case"/roles":case"/services":case"/schema":case"/data":case"/file-manager":case"/scripts":case"/config":case"/package-manager":case"/apidocs":case"/downloads":case"/limits":case"/reports":case"/scheduler":scope.activeLink="admin";break;case"/launchpad":scope.activeLink="launchpad";break;case"/profile":scope.activeLink="user";break;case"/login":scope.activeLink="login";break;case"/register":case"/register-complete":case"/register-confirm":scope.activeLink="register"}})}}}]).directive("dfNavNotification",["MOD_UTILITY_ASSET_PATH","$http",function(MOD_UTILITY_ASSET_PATH,$http){return{replace:!0,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-nav-notification.html",link:function(scope,elem,attrs){$http.get("https://dreamfactory.com/in_product_v2/notifications.php").then(function(result){scope.notifications=result.data.notifications})}}}]).directive("dfComponentNav",["MOD_UTILITY_ASSET_PATH","$location","$route","$rootScope",function(MOD_UTILITY_ASSET_PATH,$location,$route,$rootScope){return{restrict:"E",scope:{options:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-component-nav.html",link:function(scope,elem,attrs){scope.activeLink=null,scope.toggleMenu=!1,scope.openMenu=function(){scope._openMenu()},scope.closeMenu=function(){scope._closeMenu()},scope.reloadRoute=function(path){scope._activeTabClicked(path)&&$route.reload()},scope._activeTabClicked=function(path){return $location.path()===path},scope._openMenu=function(){scope.toggleMenu=!0},scope._closeMenu=function(){scope.toggleMenu=!1},scope.$watch("toggleMenu",function(n,o){return 1==n?($("#component-nav-flyout-mask").fadeIn(250),$("#top-bar-mask").fadeIn(250),$("#dreamfactoryApp").css({position:"fixed",right:"0",left:"0"}).animate({right:"+=300",left:"-=300"},250,function(){}),void $("#component-nav-flyout-menu").animate({right:"+=300"},250,function(){})):!1===n&&o?($("#dreamfactoryApp").animate({right:"-=300",left:"+=300"},250,function(){}),$("#component-nav-flyout-menu").animate({right:"-=300"},250,function(){}),$("#dreamfactoryApp").css("position","relative"),$("#component-nav-flyout-mask").fadeOut(250),void $("#top-bar-mask").fadeOut(250)):void 0}),scope.$watch(function(){return $location.path()},function(newValue,oldValue){scope.activeLink=newValue?newValue.substr(1,newValue.length):null}),$rootScope.$on("$routeChangeSuccess",function(e){scope.$broadcast("component-nav:view:change"),scope._closeMenu()})}}}]).directive("dfSidebarNav",["MOD_UTILITY_ASSET_PATH","$rootScope","$location",function(MOD_UTILITY_ASSET_PATH,$rootScope,$location){return{restrict:"E",scope:!1,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-sidebar-nav.html",link:function(scope,elem,attrs){function setMargin(location){switch(location){case"/schema":case"/data":case"/file-manager":case"/scripts":case"/apidocs":case"/package-manager":case"/downloads":$(".df-component-nav-title").css({marginLeft:0});break;case"/home":case"/apps":case"/admins":case"/users":case"/roles":case"/services":case"/config":case"/reports":case"/scheduler":var _elem=$(document).find("#sidebar-open");_elem&&_elem.is(":visible")?$(".df-component-nav-title").css({marginLeft:"45px"}):$(".df-component-nav-title").css({marginLeft:0})}}scope.activeView=scope.links[0],scope.toggleMenu=!1,scope.setActiveView=function(linkObj){scope._setActiveView(linkObj)},scope.openMenu=function(){scope._openMenu()},scope.closeMenu=function(){scope._closeMenu()},scope._setActiveView=function(linkObj){scope.activeView=linkObj,scope._closeMenu(),scope.$broadcast("sidebar-nav:view:change")},scope._openMenu=function(){scope.toggleMenu=!0},scope._closeMenu=function(){scope.toggleMenu=!1},scope.$on("sidebar-nav:view:reset",function(event){angular.forEach(scope.links,function(link,id){0===id?scope.links[0].active=!0:scope.links[id].active=!1}),scope.setActiveView(scope.links[0])}),scope.$watch("toggleMenu",function(n,o){return 1==n?($("#sidebar-nav-flyout-mask").css("z-index",10).fadeIn(250),$("#top-bar-mask").fadeIn(250),$("#dreamfactoryApp").css({position:"fixed",right:"0",left:"0"}).animate({right:"-=300",left:"+=300"},250,function(){}),void $("#sidebar-nav-flyout-menu").animate({left:"+=300"},250,function(){})):!1===n&&o?($("#dreamfactoryApp").animate({right:"+=300",left:"-=300"},250,function(){}),$("#sidebar-nav-flyout-menu").animate({left:"-=300"},250,function(){}),$("#dreamfactoryApp").css("position","relative"),$("#sidebar-nav-flyout-mask").fadeOut(250),void $("#top-bar-mask").fadeOut(250)):void 0}),scope.$watch("activeView",function(newValue,oldValue){if(!newValue)return!1;oldValue.active=!1,newValue.active=!0}),$(window).resize(function(){setMargin($location.path())}),scope.$watch(function(){return $location.path()},function(newValue,oldValue){setMargin(newValue)}),"#/roles#create"===location.hash&&scope.setActiveView(scope.links[1])}}}]).directive("dreamfactoryAutoHeight",["$window","$route",function($window){return{restrict:"A",link:function(scope,elem,attrs){scope._getWindow=function(){return $(window)},scope._getDocument=function(){return $(document)},scope._getParent=function(parentStr){switch(parentStr){case"window":return scope._getWindow();case"document":return scope._getDocument();default:return $(parentStr)}},scope._setElementHeight=function(){angular.element(elem).css({height:scope._getParent(attrs.autoHeightParent).height()-200-attrs.autoHeightPadding})},scope._setElementHeight(),angular.element($window).on("resize",function(){scope._setElementHeight()})}}}]).directive("resize",[function($window){return function(scope,element){var w=angular.element($window);scope.getWindowDimensions=function(){return{h:w.height(),w:w.width()}},scope.$watch(scope.getWindowDimensions,function(newValue,oldValue){scope.windowHeight=newValue.h,scope.windowWidth=newValue.w,angular.element(element).css({width:newValue.w-angular.element("sidebar").css("width")+"px"})},!0)}}]).directive("dfFsHeight",["$window","$rootScope",function($window,$rootScope){var dfFsHeight={rules:[{comment:"If this is the swagger iframe",order:10,test:function(element,data){return element.is("#apidocs")},setSize:function(element,data){element.css({minHeight:data.windowInnerHeight-data.menuBottomPosition-26})}},{comment:"If this is the file manager iframe",order:20,test:function(element,data){return element.is("#file-manager")},setSize:function(element,data){element.css({minHeight:data.windowInnerHeight-data.menuBottomPosition-26}),$rootScope.$emit("filemanager:sized")}},{comment:"If this is the scripting sidebar list",order:30,test:function(element,data){return element.is("#scripting-sidebar-list")},setSize:function(element,data){element.css({height:data.windowInnerHeight-element.offset().top-26})}},{comment:"If this is the scripting IDE",order:40,test:function(element,data){return"ide"===element.attr("id")},setSize:function(element,data){element.css({height:data.winHeight-element.offset().top-26})}},{comment:"If any element on desktop screen",order:50,test:function(element,data){return data.winWidth>=992},setSize:function(element,data){element.css({minHeight:data.windowInnerHeight-data.menuBottomPosition})}}],default:{setSize:function(element,data){element.css({height:"auto"})}},rulesOrderComparator:function(a,b){return a.order-b.order}},setSize=function(elem){setTimeout(function(){var _elem=$(elem),dfMenu=$(".df-menu")[0],data={menuBottomPosition:dfMenu?dfMenu.getBoundingClientRect().bottom:0,windowInnerHeight:window.innerHeight,winWidth:$(document).width(),winHeight:$(document).height()},rule=dfFsHeight.rules.sort(dfFsHeight.rulesOrderComparator).find(function(value){return value.test(_elem,data)});rule?rule.setSize(_elem,data):dfFsHeight.default.setSize(_elem,data)},10)};return function(scope,elem,attrs){var eventHandler=function(e){setSize(elem)};scope.$on("apidocs:loaded",eventHandler),scope.$on("filemanager:loaded",eventHandler),scope.$on("script:loaded:success",eventHandler),scope.$on("sidebar-nav:view:change",eventHandler),scope.$on("sidebar-nav:view:change",eventHandler),$rootScope.$on("$routeChangeSuccess",eventHandler),$(document).ready(eventHandler),$(window).on("resize",eventHandler)}}]).directive("dfGroupedPicklist",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{selected:"=?",options:"=?"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-grouped-picklist.html",link:function(scope,elem,attrs){scope.selectedLabel=!1,scope.selectItem=function(item){scope.selected=item.name},scope.$watch("selected",function(n,o){if(null==n&&void 0==n)return!1;angular.forEach(scope.options,function(option){option.items&&angular.forEach(option.items,function(item){n===item.name&&(scope.selectedLabel=item.label)})})}),elem.css({display:"inline-block",position:"relative"})}}}]).directive("dfEventPicker",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{selected:"=?",options:"=?"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-event-picker.html",link:function(scope,elem,attrs){scope.selectItem=function(item){scope.selected=item.name},scope.events=[],scope.$watch("options",function(newValue,oldValue){var events=[];newValue&&(angular.forEach(newValue,function(e){e.items&&(events.length>0&&events.push({class:"divider"}),angular.forEach(e.items,function(item){item.class="",events.push(item)}))}),scope.events=events)})}}}]).directive("dfFileCertificate",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{selected:"=?"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-file-certificate.html",link:function(scope,elem,attrs){elem.find("input").bind("change",function(event){var file=event.target.files[0],reader=new FileReader;reader.onload=function(readerEvt){var string=readerEvt.target.result;scope.selected=string,scope.$apply()},reader.readAsBinaryString(file)}),elem.css({display:"inline-block",position:"relative"})}}}]).directive("dfMultiPicklist",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{options:"=?",selectedOptions:"=?",cols:"=?",legend:"=?"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-multi-picklist.html",link:function(scope,elem,attrs){angular.forEach(scope.options,function(option){option.active=!1}),scope.allSelected=!1,scope.cols||(scope.cols=3),scope.width=100/(1*scope.cols)-3,scope.toggleSelectAll=function(){var selected=[];scope.allSelected&&angular.forEach(scope.options,function(option){selected.push(option.name)}),scope.selectedOptions=selected},scope.setSelectedOptions=function(){var selected=[];angular.forEach(scope.options,function(option){option.active&&selected.push(option.name)}),scope.selectedOptions=selected},scope.$watch("selectedOptions",function(newValue,oldValue){newValue&&angular.forEach(scope.options,function(option){option.active=newValue.indexOf(option.name)>=0})}),elem.css({display:"inline-block",position:"relative"})}}}]).directive("dfVerbPicker",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{allowedVerbs:"=?",allowedVerbMask:"=?",description:"=?",size:"@"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-verb-picker.html",link:function(scope,elem,attrs){scope.verbs={GET:{name:"GET",active:!1,description:" (read)",mask:1},POST:{name:"POST",active:!1,description:" (create)",mask:2},PUT:{name:"PUT",active:!1,description:" (replace)",mask:4},PATCH:{name:"PATCH",active:!1,description:" (update)",mask:8},DELETE:{name:"DELETE",active:!1,description:" (remove)",mask:16}},scope.btnText="None Selected",scope.description=!0,scope.checkAll={checked:!1},scope._toggleSelectAll=function(event){void 0!==event&&event.stopPropagation();var verbsSet=[];Object.keys(scope.verbs).forEach(function(key,index){!0===scope.verbs[key].active&&verbsSet.push(key)}),verbsSet.length>0?angular.forEach(verbsSet,function(verb){scope._toggleVerbState(verb,event)}):Object.keys(scope.verbs).forEach(function(key,index){scope._toggleVerbState(key,event)})},scope._setVerbState=function(nameStr,stateBool){var verb=scope.verbs[nameStr];scope.verbs.hasOwnProperty(verb.name)&&(scope.verbs[verb.name].active=stateBool)},scope._toggleVerbState=function(nameStr,event){void 0!==event&&event.stopPropagation(),scope.verbs.hasOwnProperty(scope.verbs[nameStr].name)&&(scope.verbs[nameStr].active=!scope.verbs[nameStr].active,scope.allowedVerbMask=scope.allowedVerbMask^scope.verbs[nameStr].mask),scope.allowedVerbs=[],angular.forEach(scope.verbs,function(_obj){_obj.active&&scope.allowedVerbs.push(_obj.name)})},scope._isVerbActive=function(verbStr){return scope.verbs[verbStr].active},scope._setButtonText=function(){var verbs=[];angular.forEach(scope.verbs,function(verbObj){verbObj.active&&verbs.push(verbObj.name)}),scope.btnText="";0==verbs.length?scope.btnText="None Selected":verbs.length>0&&verbs.length<=1?angular.forEach(verbs,function(_value,_index){scope._isVerbActive(_value)&&(_index!=verbs.length-1?scope.btnText+=_value+", ":scope.btnText+=_value)}):verbs.length>1&&(scope.btnText=verbs.length+" Selected")},scope.$watch("allowedVerbs",function(newValue,oldValue){if(!newValue)return!1;Object.keys(scope.verbs).forEach(function(key){scope._setVerbState(key,!1)}),angular.forEach(scope.allowedVerbs,function(_value,_index){scope._setVerbState(_value,!0)}),scope._setButtonText()}),scope.$watch("allowedVerbMask",function(n,o){if(null==n&&void 0==n)return!1;angular.forEach(scope.verbs,function(verbObj){n&verbObj.mask&&(verbObj.active=!0)}),scope._setButtonText()}),elem.css({display:"inline-block",position:"relative"})}}}]).directive("dfRequestorPicker",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{allowedRequestors:"=?",allowedRequestorMask:"=?",size:"@"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-requestor-picker.html",link:function(scope,elem,attrs){scope.requestors={API:{name:"API",active:!1,mask:1},SCRIPT:{name:"SCRIPT",active:!1,mask:2}},scope.btnText="None Selected",scope._setRequestorState=function(nameStr,stateBool){var requestor=scope.requestors[nameStr];scope.requestors.hasOwnProperty(requestor.name)&&(scope.requestors[requestor.name].active=stateBool)},scope._toggleRequestorState=function(nameStr,event){event.stopPropagation(),scope.requestors.hasOwnProperty(scope.requestors[nameStr].name)&&(scope.requestors[nameStr].active=!scope.requestors[nameStr].active,scope.allowedRequestorMask=scope.allowedRequestorMask^scope.requestors[nameStr].mask),scope.allowedRequestors=[],angular.forEach(scope.requestors,function(_obj){_obj.active&&scope.allowedRequestors.push(_obj.name)})},scope._isRequestorActive=function(requestorStr){return scope.requestors[requestorStr].active},scope._setButtonText=function(){var requestors=[];angular.forEach(scope.requestors,function(rObj){rObj.active&&requestors.push(rObj.name)}),scope.btnText="",0==requestors.length?scope.btnText="None Selected":angular.forEach(requestors,function(_value,_index){scope._isRequestorActive(_value)&&(_index!=requestors.length-1?scope.btnText+=_value+", ":scope.btnText+=_value)})},scope.$watch("allowedRequestors",function(newValue,oldValue){if(!newValue)return!1;angular.forEach(scope.allowedRequestors,function(_value,_index){scope._setRequestorState(_value,!0)}),scope._setButtonText()}),scope.$watch("allowedRequestorMask",function(n,o){if(null==n&&void 0==n)return!1;angular.forEach(scope.requestors,function(requestorObj){n&requestorObj.mask&&(requestorObj.active=!0)}),scope._setButtonText()}),elem.css({display:"inline-block",position:"absolute"})}}}]).directive("dfDbFunctionUsePicker",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{allowedUses:"=?",description:"=?",size:"@"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-db-function-use-picker.html",link:function(scope,elem,attrs){scope.uses={SELECT:{name:"SELECT",active:!1,description:" (get)"},FILTER:{name:"FILTER",active:!1,description:" (get)"},INSERT:{name:"INSERT",active:!1,description:" (post)"},UPDATE:{name:"UPDATE",active:!1,description:" (patch)"}},scope.btnText="None Selected",scope.description=!0,scope._setDbFunctionUseState=function(nameStr,stateBool){scope.uses.hasOwnProperty(scope.uses[nameStr].name)&&(scope.uses[nameStr].active=stateBool)},scope._toggleDbFunctionUseState=function(nameStr,event){event.stopPropagation(),scope.uses.hasOwnProperty(scope.uses[nameStr].name)&&(scope.uses[nameStr].active=!scope.uses[nameStr].active),scope.allowedUses=[],angular.forEach(scope.uses,function(_obj){_obj.active&&scope.allowedUses.push(_obj.name)})},scope._isDbFunctionUseActive=function(nameStr){return scope.uses[nameStr].active},scope._setButtonText=function(){var uses=[];angular.forEach(scope.uses,function(useObj){useObj.active&&uses.push(useObj.name)}),scope.btnText="";0==uses.length?scope.btnText="None Selected":uses.length>0&&uses.length<=1?angular.forEach(uses,function(_value,_index){scope._isDbFunctionUseActive(_value)&&(_index!=uses.length-1?scope.btnText+=_value+", ":scope.btnText+=_value)}):uses.length>1&&(scope.btnText=uses.length+" Selected")},scope.$watch("allowedUses",function(newValue,oldValue){if(!newValue)return!1;Object.keys(scope.uses).forEach(function(key){scope._setDbFunctionUseState(key,!1)}),angular.forEach(scope.allowedUses,function(_value,_index){scope._setDbFunctionUseState(_value,!0)}),scope._setButtonText()}),elem.css({display:"inline-block",position:"relative"})}}}]).directive("dfServicePicker",["MOD_UTILITY_ASSET_PATH","INSTANCE_URL","$http",function(MOD_UTILITY_ASSET_PATH,INSTANCE_URL,$http){return{restrict:"E",scope:{services:"=?",selected:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-service-picker.html",link:function(scope,elem,attrs){scope.resources=[],scope.activeResource=null,scope.activeService=null,scope.setServiceAndResource=function(){scope._checkForActive()&&scope._setServiceAndResource()},scope._getResources=function(){return $http({method:"GET",url:INSTANCE_URL.url+"/"+scope.activeService})},scope._setServiceAndResource=function(){scope.selected={service:scope.activeService,resource:scope.activeResource}},scope._checkForActive=function(){return!!scope.activeResource&&scope.activeService},scope.$watch("activeService",function(newValue,oldValue){if(!newValue)return scope.resources=[],scope.activeResource=null,!1;scope.resources=[],scope._getResources().then(function(result){scope.resources=result.data.resource},function(reject){throw{module:"DreamFactory Utility Module",type:"error",provider:"dreamfactory",exception:reject}})})}}}]).directive("dfDbTablePicker",["MOD_UTILITY_ASSET_PATH","INSTANCE_URL","$http","dfApplicationData",function(MOD_UTILITY_ASSET_PATH,INSTANCE_URL,$http,dfApplicationData){return{restrict:"E",scope:{services:"=?",selected:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-db-table-picker.html",link:function(scope,elem,attrs){scope.resources=[],scope.activeResource=null,scope.activeService=null,scope.setServiceAndResource=function(){scope._checkForActive()&&scope._setServiceAndResource()},scope._getResources=function(){return dfApplicationData.getServiceComponents(scope.activeService,INSTANCE_URL.url+"/"+scope.activeService+"/_table/",{params:{fields:"name,label"}})},scope._setServiceAndResource=function(){scope.selected={service:scope.activeService,resource:scope.activeResource}},scope._checkForActive=function(){return!!scope.activeResource&&scope.activeService},scope.$watch("activeService",function(newValue,oldValue){if(!newValue)return scope.resources=[],scope.activeResource=null,!1;scope.resources=[],scope._getResources().then(function(result){scope.resources=result},function(reject){throw{module:"DreamFactory Utility Module",type:"error",provider:"dreamfactory",exception:reject}})})}}}]).directive("dfDbSchemaPicker",["MOD_UTILITY_ASSET_PATH","INSTANCE_URL","$http",function(MOD_UTILITY_ASSET_PATH,INSTANCE_URL,$http){return{restrict:"E",scope:{services:"=?",selected:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-db-schema-picker.html",link:function(scope,elem,attrs){scope.resources=[],scope.activeResource=null,scope.activeService=null,scope.setServiceAndResource=function(){scope._checkForActive()&&scope._setServiceAndResource()},scope._getResources=function(){return $http({method:"GET",url:INSTANCE_URL.url+"/"+scope.activeService+"/_schema/"})},scope._setServiceAndResource=function(){scope.selected={service:scope.activeService,resource:scope.activeResource}},scope._checkForActive=function(){return!!scope.activeResource&&scope.activeService},scope.$watch("activeService",function(newValue,oldValue){if(!newValue)return scope.resources=[],scope.activeResource=null,!1;scope.resources=[],scope._getResources().then(function(result){scope.resources=result.data.resource},function(reject){throw{module:"DreamFactory Utility Module",type:"error",provider:"dreamfactory",exception:reject}})})}}}]).directive("dfAceEditor",["MOD_UTILITY_ASSET_PATH","$compile",function(MOD_UTILITY_ASSET_PATH,$compile){return{restrict:"E",scope:{inputType:"=?",inputContent:"=?",inputUpdate:"=?",inputFormat:"=?",isEditable:"=?",editorObj:"=?",targetDiv:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-ace-editor.html",link:function(scope,elem,attrs){window.define=window.define||ace.define,$(elem).children(".ide-attach").append($compile('
')(scope)),scope.editor=null,scope.currentContent="",scope.verbose=!1,scope._setEditorInactive=function(inactive){scope.verbose&&console.log(scope.targetDiv,"_setEditorInactive",inactive),inactive?(scope.editor.setOptions({readOnly:!0,highlightActiveLine:!1,highlightGutterLine:!1}),scope.editor.container.style.opacity=.75,scope.editor.renderer.$cursorLayer.element.style.opacity=0):(scope.editor.setOptions({readOnly:!1,highlightActiveLine:!0,highlightGutterLine:!0}),scope.editor.container.style.opacity=1,scope.editor.renderer.$cursorLayer.element.style.opacity=100)},scope._setEditorMode=function(mode){scope.verbose&&console.log(scope.targetDiv,"_setEditorMode",mode),scope.editor.session.setMode({path:"ace/mode/"+mode,inline:!0,v:Date.now()})},scope._loadEditor=function(newValue){if(scope.verbose&&console.log(scope.targetDiv,"_loadEditor",newValue),null!==newValue&&void 0!==newValue){var content=newValue;"object"===scope.inputType&&(content=angular.toJson(content,!0)),scope.currentContent=content,scope.editor=ace.edit("ide_"+scope.targetDiv),scope.editorObj.editor=scope.editor,scope.editor.renderer.setShowGutter(!0),scope.editor.session.setValue(content)}},scope.$watch("inputContent",scope._loadEditor),scope.$watch("inputUpdate",function(newValue){scope.verbose&&console.log(scope.targetDiv,"inputUpdate",newValue),scope._loadEditor(scope.currentContent)}),scope.$watch("inputFormat",function(newValue){scope.verbose&&console.log(scope.targetDiv,"inputFormat",newValue),newValue&&("nodejs"===newValue?newValue="javascript":"python3"===newValue&&(newValue="python"),scope._setEditorMode(newValue))}),scope.$watch("isEditable",function(newValue){scope.verbose&&console.log(scope.targetDiv,"isEditable",newValue),scope._setEditorInactive(!newValue)}),scope.$on("$destroy",function(e){scope.verbose&&console.log(scope.targetDiv,"$destroy"),scope.editor.destroy()})}}}]).directive("fileModel",["$parse",function($parse){return{restrict:"A",scope:!1,link:function(scope,element,attrs){var modelSetter=$parse(attrs.fileModel).assign;element.on("change",function(){scope.$apply(function(){modelSetter(scope,element[0].files[0])})})}}}]).directive("fileModel2",["$parse",function($parse){return{restrict:"A",scope:!1,link:function(scope,element,attrs){var modelSetter=$parse(attrs.fileModel).assign;element.on("change",function(){scope.$apply(function(){modelSetter(scope,element[0].files[0])})})}}}]).directive("showtab",[function(){return{restrict:"A",link:function(scope,element,attrs){element.click(function(e){e.preventDefault(),$(element).tab("show")}),scope.activeTab=$(element).attr("id")}}}]).directive("dfSectionToolbar",["MOD_UTILITY_ASSET_PATH","$compile","dfApplicationData","$location","$timeout","$route",function(MOD_UTILITY_ASSET_PATH,$compile,dfApplicationData,$location,$timeout,$route){return{restrict:"E",scope:!1,transclude:!0,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-toolbar.html",link:function(scope,elem,attrs){scope.changeFilter=function(searchStr){$timeout(function(){if(searchStr===scope.filterText||!scope.filterText)return scope.filterText=scope.filterText||null,void $location.search("filter",scope.filterText)},1e3)},scope.filterText=$location.search()&&$location.search().filter?$location.search().filter:"",elem.find("input")[0]&&elem.find("input")[0].focus()}}}]).directive("dfToolbarHelp",["MOD_UTILITY_ASSET_PATH",function(MOD_UTILITY_ASSET_PATH){return{restrict:"E",scope:!1,replace:!0,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-toolbar-help.html",link:function(scope,elem,attrs){scope=scope.$parent}}}]).directive("dfToolbarPaginate",["MOD_UTILITY_ASSET_PATH","dfApplicationData","dfNotify","$location",function(MOD_UTILITY_ASSET_PATH,dfApplicationData,dfNotify,$location){return{restrict:"E",scope:{api:"=",type:"=?"},replace:!0,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-toolbar-paginate.html",link:function(scope,elem,attrs){scope.totalCount=dfApplicationData.getApiRecordCount(scope.api),scope.pagesArr=[],scope.currentPage={},scope.isInProgress=!1,scope.getPrevious=function(){if(scope._isFirstPage()||scope.isInProgress)return!1;scope._getPrevious()},scope.getNext=function(){if(scope._isLastPage()||scope.isInProgress)return!1;scope._getNext()},scope.getPage=function(pageObj){scope._getPage(pageObj)},scope._getDataFromServer=function(offset,filter){var params={offset:offset,include_count:!0};return filter&&(params.filter=filter),dfApplicationData.getDataSetFromServer(scope.api,{params:params}).$promise},scope._calcTotalPages=function(totalCount,numPerPage){return Math.ceil(totalCount/numPerPage)},scope._createPageObj=function(_pageNum){return{number:_pageNum+1,value:_pageNum,offset:_pageNum*dfApplicationData.getApiPrefs().data[scope.api].limit,stopPropagation:!1}},scope._createPagesArr=function(_totalCount){scope.pagesArr=[];for(var i=0;i<_totalCount;i++)scope.pagesArr.push(scope._createPageObj(i))},scope._setCurrentPage=function(pageDataObj){scope.currentPage=pageDataObj},scope._getCurrentPage=function(){return!scope.currentPage&&scope.pagesArr.length>0?scope.currentPage=scope.pagesArr[0]:scope.currentPage||scope.pagesArr.length||(scope.pagesArr.push(scope._createPageObj(0)),scope.currentPage=scope.pagesArr[0]),scope.currentPage},scope._isFirstPage=function(){return 0===scope._getCurrentPage().value},scope._isLastPage=function(){return scope.currentPage.value===scope.pagesArr.length-1},scope._previousPage=function(){scope.currentPage=scope.pagesArr[scope.currentPage.value-1]},scope._nextPage=function(){scope.currentPage=scope.pagesArr[scope.currentPage.value+1]},scope._calcPagination=function(api){if(scope.pagesArr=[],0==scope.totalCount)return scope.pagesArr.push(scope._createPageObj(0)),!1;scope._createPagesArr(scope._calcTotalPages(scope.totalCount,dfApplicationData.getApiPrefs().data[api].limit))};var detectFilter=function(){var filterText=$location.search()&&$location.search().filter?$location.search().filter:"";if(!filterText)return"";var arr=["first_name","last_name","name","email"];return $location.path().includes("apps")&&(arr=["name","description"]),$location.path().includes("roles")&&(arr=["name","description"]),$location.path().includes("services")&&(arr=["name","label","description","type"]),$location.path().includes("reports")?(arr=["id","service_id","service_name","user_email","action","request_verb"]).map(function(item){return item.includes("id")?Number.isNaN(parseInt(filterText))?"":"("+item+" like "+parseInt(filterText)+")":"("+item+' like "%'+filterText+'%")'}).filter(function(filter){return"string"==typeof filter&&filter.length>0}).join(" or "):arr.map(function(item){return"("+item+' like "%'+filterText+'%")'}).join(" or ")};scope._getPrevious=function(){if(scope.isInProgress)return!1;scope.isInProgress=!0;var offset=scope.pagesArr[scope.currentPage.value-1].offset;scope._getDataFromServer(offset,detectFilter()).then(function(result){scope._previousPage(),scope.$emit("toolbar:paginate:"+scope.api+":update")},function(reject){var messageOptions={module:"DreamFactory Paginate Table",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.isInProgress=!1})},scope._getNext=function(){if(scope.isInProgress)return!1;scope.isInProgress=!0;var offset=scope.pagesArr[scope.currentPage.value+1].offset;scope._getDataFromServer(offset,detectFilter()).then(function(result){scope._nextPage(),scope.$emit("toolbar:paginate:"+scope.api+":update")},function(reject){var messageOptions={module:"DreamFactory Paginate Table",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.isInProgress=!1})},scope._getPage=function(pageObj){if(scope.isInProgress)return!1;scope.isInProgress=!0,scope._getDataFromServer(pageObj.offset,detectFilter()).then(function(result){scope._setCurrentPage(pageObj),scope.$emit("toolbar:paginate:"+scope.api+":update")},function(reject){var messageOptions={module:"DreamFactory Paginate Table",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.isInProgress=!1})};scope.$watch("api",function(newValue,oldValue){if(!newValue)return!1;scope.totalCount=dfApplicationData.getApiRecordCount(newValue),scope._calcPagination(newValue),scope._setCurrentPage(scope.pagesArr[0])});scope.$on("toolbar:paginate:"+scope.api+":load",function(e){scope.totalCount=dfApplicationData.getApiRecordCount(scope.api),scope._calcPagination(scope.api),scope._setCurrentPage(scope.pagesArr[0])}),scope.$on("toolbar:paginate:"+scope.api+":destroy",function(e){1!==scope.currentPage.number&&(dfApplicationData.deleteApiDataFromCache(scope.api),scope.totalCount=0,scope._calcPagination(scope.api),scope._setCurrentPage(scope.pagesArr[0]))}),scope.$on("toolbar:paginate:"+scope.api+":reset",function(e){if("/logout"!==$location.path()&&void 0!==dfApplicationData.getApiDataFromCache(scope.api)){if(scope.isInProgress)return!1;scope.isInProgress=!0,scope._getDataFromServer(0,detectFilter()).then(function(result){scope.totalCount=dfApplicationData.getApiRecordCount(scope.api),scope._calcPagination(scope.api),scope._setCurrentPage(scope.pagesArr[0]),scope.$emit("toolbar:paginate:"+scope.api+":update")},function(reject){var messageOptions={module:"DreamFactory Paginate Table",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.isInProgress=!1})}}),scope.$on("toolbar:paginate:"+scope.api+":delete",function(e){if(!scope.isInProgress){var curOffset=scope.currentPage.offset,recalcPagination=!1;scope._isLastPage()&&!dfApplicationData.getApiDataFromCache(scope.api).length&&(recalcPagination=!0,1!==scope.currentPage.number&&(curOffset=scope.currentPage.offset-dfApplicationData.getApiPrefs().data[scope.api].limit)),scope.isInProgress=!0,scope._getDataFromServer(curOffset,detectFilter()).then(function(result){scope.totalCount=dfApplicationData.getApiRecordCount(scope.api),recalcPagination&&(scope._calcPagination(scope.api),scope._setCurrentPage(scope.pagesArr[scope.pagesArr.length-1])),scope.$emit("toolbar:paginate:"+scope.api+":update")},function(reject){var messageOptions={module:"DreamFactory Paginate Table",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.isInProgress=!1})}})}}}]).directive("dfDetailsHeader",["MOD_UTILITY_ASSET_PATH",function(MOD_UTILITY_ASSET_PATH){return{restrict:"E",scope:{new:"=",name:"=?",apiName:"=?"},template:'

Create {{apiName}}

Edit {{name}}

',link:function(scope,elem,attrs){}}}]).directive("dfSectionHeader",[function(){return{restrict:"E",scope:{title:"=?"},template:'

{{title}}

',link:function(scope,elem,attrs){}}}]).directive("dfSetUserPassword",["MOD_UTILITY_ASSET_PATH","$compile",function(MOD_USER_ASSET_PATH,$compile){return{restrict:"E",scope:!1,templateUrl:MOD_USER_ASSET_PATH+"views/df-input-manual-password.html",link:function(scope,elem,attrs){scope.requireOldPassword=!1,scope.password=null,scope.setPassword=!1,scope.identical=!0,scope._verifyPassword=function(){scope.identical=scope.password.new_password===scope.password.verify_password},scope._resetUserPasswordForm=function(){scope.password=null,scope.setPassword=!1,scope.identical=!0},scope.$watch("setPassword",function(newValue){if(newValue){var html="";html+='
';var el=$compile(html+='
')(scope);angular.element("#set-password").append(el)}}),scope.$on("reset:user:form",function(e){scope._resetUserPasswordForm()})}}}]).directive("dfSetSecurityQuestion",["MOD_UTILITY_ASSET_PATH","$compile",function(MOD_UTILITY_ASSET_PATH,$compile){return{restrict:"E",scope:!1,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-set-security-question.html",link:function(scope,elem,attrs){scope.setQuestion=!1,scope.$watch("setQuestion",function(newValue){if(newValue){var html="";html+='
',angular.element("#set-question").append($compile(html)(scope))}})}}}]).directive("dfDownloadSdk",["MOD_UTILITY_ASSET_PATH",function(MOD_UTILITY_ASSET_PATH){return{restrict:"E",scope:{btnSize:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-download-sdk.html",link:function(scope,elem,attrs){scope.sampleAppLinks=[{label:"Android",href:"https://github.com/dreamfactorysoftware/android-sdk",icon:""},{label:"iOS Objective-C",href:"https://github.com/dreamfactorysoftware/ios-sdk",icon:""},{label:"iOS Swift",href:"https://github.com/dreamfactorysoftware/ios-swift-sdk",icon:""},{label:"JavaScript",href:"https://github.com/dreamfactorysoftware/javascript-sdk",icon:""},{label:"AngularJS",href:"https://github.com/dreamfactorysoftware/angular-sdk",icon:""},{label:"Angular 2",href:"https://github.com/dreamfactorysoftware/angular2-sdk",icon:""},{label:"Ionic",href:"https://github.com/dreamfactorysoftware/ionic-sdk",icon:""},{label:"Titanium",href:"https://github.com/dreamfactorysoftware/titanium-sdk",icon:""},{label:"ReactJS",href:"https://github.com/dreamfactorysoftware/reactjs-sdk",icon:""},{label:".NET",href:"https://github.com/dreamfactorysoftware/.net-sdk",icon:""}]}}}]).directive("dfEmptySection",["MOD_UTILITY_ASSET_PATH",function(MOD_UTILITY_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-empty-section.html"}}]).directive("dfEmptySearchResult",["MOD_UTILITY_ASSET_PATH","$location",function(MOD_UTILITY_ASSET_PATH,$location){return{restrict:"E",scope:!1,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-empty-search-result.html",link:function(scope,elem,attrs){$location.search()&&$location.search().filter&&(scope.$parent.filterText=$location.search()&&$location.search().filter?$location.search().filter:null)}}}]).directive("dfPopupLogin",["MOD_UTILITY_ASSET_PATH","$compile","$location","UserEventsService",function(MOD_UTILITY_ASSET_PATH,$compile,$location,UserEventsService){return{restrict:"A",scope:!1,link:function(scope,elem,attrs){scope.popupLoginOptions={showTemplate:!0},scope.openLoginWindow=function(errormsg){scope._openLoginWindow(errormsg)},scope._openLoginWindow=function(errormsg){$("#popup-login-container").html($compile('
')(scope))},scope.$on(UserEventsService.login.loginSuccess,function(e,userDataObj){e.stopPropagation(),$("#df-login-frame").remove()}),scope.$on(UserEventsService.login.loginError,function(e,userDataObj){$("#df-login-frame").remove(),$location.url("/logout")})}}}]).directive("dfCopyrightFooter",["MOD_UTILITY_ASSET_PATH","APP_VERSION",function(MOD_UTILITY_ASSET_PATH,APP_VERSION){return{restrict:"E",scope:!1,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-copyright-footer.html",link:function(scope,elem,attrs){scope.version=APP_VERSION,scope.currentYear=(new Date).getFullYear()}}}]).directive("dfPaywall",["MOD_UTILITY_ASSET_PATH",function(MOD_UTILITY_ASSET_PATH){return{restrict:"E",scope:{serviceName:"=?",licenseType:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-paywall.html",link:function(scope,elem,attrs){scope.$watch("serviceName",function(newValue,oldValue){scope.serviceName&&scope.$emit("hitPaywall",newValue)}),Calendly.initInlineWidget({url:"https://calendly.com/dreamfactory-platform/unlock-all-features",parentElement:document.querySelector(".calendly-inline-widget"),autoLoad:!1})}}}]).service("dfObjectService",[function(){return{mergeDiff:function(obj1,obj2){for(var key in obj1)obj2.hasOwnProperty(key)||"$"===key.substr(0,1)||(obj2[key]=obj1[key]);return obj2},mergeObjects:function(obj1,obj2){for(var key in obj1)obj2[key]=obj1[key];return obj2},deepMergeObjects:function(obj1,obj2){var self=this;for(var _key in obj1)if(obj2.hasOwnProperty(_key))switch(Object.prototype.toString.call(obj2[_key])){case"[object Object]":obj2[_key]=self.deepMergeObjects(obj1[_key],obj2[_key]);break;case"[object Array]":obj2[_key]=obj1[_key];break;default:obj2[_key]=obj1[_key]}return obj2},compareObjectsAsJson:function(o,p){return angular.toJson(o)===angular.toJson(p)}}}]).service("XHRHelper",["INSTANCE_URL","APP_API_KEY","$cookies",function(INSTANCE_URL,APP_API_KEY,$cookies){function _isEmpty(obj){if(null==obj)return!0;if(obj.length>0)return!1;if(0===obj.length)return!0;for(var key in obj)if(hasOwnProperty.call(obj,key))return!1;return!0}function _setHeaders(_xhrObj,_headersDataObj){_xhrObj.setRequestHeader("X-DreamFactory-API-Key",APP_API_KEY);var currentUser=UserDataService.getCurrentUser();currentUser&¤tUser.session_tpken&&xhrObj.setRequestHeader("X-DreamFactory-Session-Token",currentUser.session_token);for(var _key in _headersDataObj)_xhrObj.setRequestHeader(_key,_headersDataObj[_key])}function _setParams(_paramsDataObj){var params="";if(!_isEmpty(_paramsDataObj)){params="?";for(var _key in _paramsDataObj)params+=_key+"="+_paramsDataObj[_key]+"&"}return""!==params&&(params=params.substring(0,params.length-1),encodeURI(params)),params}function _makeRequest(_method,_url,_async,_params,_headers,_mimeType){var xhr;xhr=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP");var params=_setParams(_params);if(xhr.open(_method,INSTANCE_URL.url+"/"+_url+params,_async),_setHeaders(xhr,_headers),xhr.overrideMimeType(_mimeType),xhr.send(),4===xhr.readyState)return xhr}function _ajax(optionsDataObj){if(!optionsDataObj.url||""===optionsDataObj.url)throw{module:"DreamFactory Utility Module",type:"error",provider:"dreamfactory",exception:"XHRHelper Request Failure: No URL provided"};var defaults={method:"GET",url:"",async:!1,params:{},headers:{},mimeType:"application/json"};for(var _key in defaults)optionsDataObj.hasOwnProperty(_key)&&(defaults[_key]=optionsDataObj[_key]);return _makeRequest(defaults.method,defaults.url,defaults.async,defaults.params,defaults.headers,defaults.mimeType)}return{ajax:function(requestOptions){return _ajax(requestOptions)}}}]).service("dfNotify",["dfApplicationData",function(dfApplicationData){function pnotify(messageOptions){function notificationExists(notification){return notification.options.tag===messageOptions.tag}var notificationCardStyle="",notificationIcon="";switch(messageOptions.type){case"success":notificationCardStyle="notification-card-success",notificationIcon="fa fa-check fa-lg fa-green";break;case"error":notificationCardStyle="notification-card-error",notificationIcon="fa fa-exclamation-triangle fa-lg fa-red";break;case"warn":notificationCardStyle="notification-card-warn",notificationIcon="fa fa-exclamation fa-lg fa-yellow";break;case"testing":notificationCardStyle="notification-card-success",notificationIcon="fa fa-refresh fa-spin fa-lg"}var notificationOptions={title:messageOptions.module,type:messageOptions.type,text:messageOptions.message,addclass:"stack-bottomleft "+notificationCardStyle,animate:{animate:!0,in_class:"animate__slideInLeft",out_class:"animate__slideOutLeft"},animate_speed:"normal",buttons:{closer:!0,sticker:!0,classes:{closer:"fa fa-times-circle",pin_up:"fa fa-pause",pin_down:"fa fa-play"}},icon:notificationIcon,tag:messageOptions.tag,hide:"testing"!==messageOptions.type,delay:"testing"===messageOptions.type?null:5e3,stack:stack_bar_bottom,mouse_reset:!0};if(messageOptions.tag&¬ifications.findIndex(notificationExists)>=0)var indexOfExistingNotice=notifications.findIndex(notificationExists);if(void 0!==indexOfExistingNotice){var updatedNotice=notifications[indexOfExistingNotice].update(notificationOptions);"closed"===updatedNotice.state&&updatedNotice.open(),notifications.splice(indexOfExistingNotice,1)}else{var notice=new PNotify(notificationOptions);notice.options.tag&¬ifications.push(notice)}}function parseDreamfactoryError(errorDataObj){var result,error,resource,message;return"[object String]"===Object.prototype.toString.call(errorDataObj)?result=errorDataObj:(result="The server returned an unknown error.",(error=errorDataObj.data?errorDataObj.data.error:errorDataObj.error)&&((message=error.message)&&(result=message),1e3===error.code&&error.context&&(resource=error.context.resource,error=error.context.error,resource&&error&&(result="",angular.forEach(error,function(index){result&&(result+="\n"),result+=resource[index].message}))))),result}var notifications=[],stack_bar_bottom={dir1:"up",dir2:"right",spacing1:10};return{success:function(options){pnotify(options)},error:function(options){options.message=parseDreamfactoryError(options.message),pnotify(options)},warn:function(options){pnotify(options)},confirmNoSave:function(){return confirm("Continue without saving?")},confirm:function(msg){return confirm(msg)}}}]).service("dfIconService",[function(){return function(){return{upgrade:"fa fa-fw fa-level-up",support:"fa fa-fw fa-support",launchpad:"fa fa-fw fa-bars",admin:"fa fa-fw fa-cog",login:"fa fa-fw fa-sign-in",register:"fa fa-fw fa-group",user:"fa fa-fw fa-user"}}}]).service("dfServerInfoService",["$window",function($window){return{currentServer:function(){return $window.location.origin}}}]).service("serviceTypeToGroup",[function(){return function(type,serviceTypes){var i,length,result=null;if(type&&serviceTypes)for(length=serviceTypes.length,i=0;iupB?1:0});break;default:filtered.sort(function(a,b){a.hasOwnProperty("record")&&b.hasOwnProperty("record")?(a=a.record[field],b=b.record[field]):(a=a[field],b=b[field]);var upA=a=null===a||void 0===a?"":a,upB=b=null===b||void 0===b?"":b;return upAupB?1:0})}return reverse&&filtered.reverse(),filtered}}]).filter("dfFilterBy",[function(){return function(items,options){if(!options.on)return items;var filtered=[];return options&&options.field&&options.value?(options.regex||(options.regex=new RegExp(options.value,"i")),angular.forEach(items,function(item){options.regex.test(item[options.field])&&filtered.push(item)}),filtered):items}}]).filter("dfOrderExplicit",[function(){return function(items,order){var filtered=[],i=0;return angular.forEach(items,function(value,index){value.name===order[i]&&filtered.push(value),i++}),filtered}}]),angular.module("dfSystemConfig",["ngRoute","dfUtility","dfApplication"]).constant("MODSYSCONFIG_ROUTER_PATH","/config").constant("MODSYSCONFIG_ASSET_PATH","admin_components/adf-system-config/").config(["$routeProvider","MODSYSCONFIG_ROUTER_PATH","MODSYSCONFIG_ASSET_PATH",function($routeProvider,MODSYSCONFIG_ROUTER_PATH,MODSYSCONFIG_ASSET_PATH){$routeProvider.when(MODSYSCONFIG_ROUTER_PATH,{templateUrl:MODSYSCONFIG_ASSET_PATH+"views/main.html",controller:"SystemConfigurationCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("SystemConfigurationCtrl",["$scope","dfApplicationData","SystemConfigEventsService","SystemConfigDataService","dfObjectService","dfNotify","UserDataService",function($scope,dfApplicationData,SystemConfigEventsService,SystemConfigDataService,dfObjectService,dfNotify,UserDataService){var currentUser=UserDataService.getCurrentUser();$scope.isSysAdmin=currentUser&¤tUser.is_sys_admin,$scope.$parent.title="Config",$scope.$parent.titleIcon="gear",$scope.es=SystemConfigEventsService.systemConfigController,$scope.buildLinks=function(checkData){var links=[];return checkData&&!$scope.apiData.environment||links.push({name:"system-info",label:"System Info",path:"system-info",active:0===links.length}),checkData&&!$scope.apiData.cache||links.push({name:"cache",label:"Cache",path:"cache",active:0===links.length}),checkData&&!$scope.apiData.cors||links.push({name:"cors",label:"CORS",path:"cors",active:0===links.length}),checkData&&!$scope.apiData.email_template||links.push({name:"email-templates",label:"Email Templates",path:"email-templates",active:0===links.length}),checkData&&!$scope.apiData.lookup||links.push({name:"global-lookup-keys",label:"Global Lookup Keys",path:"global-lookup-keys",active:0===links.length}),links},$scope.links=$scope.buildLinks(!1),$scope.$emit("sidebar-nav:view:reset"),$scope.$on("$locationChangeStart",function(e){$scope.hasOwnProperty("systemConfig")&&(dfObjectService.compareObjectsAsJson($scope.systemConfig.record,$scope.systemConfig.recordCopy)||dfNotify.confirmNoSave()||e.preventDefault())}),$scope.dfLargeHelp={systemInfo:{title:"System Info Overview",text:"Displays current system information."},cacheConfig:{title:"Cache Overview",text:"Flush system-wide cache or per-service caches. Use the cache clearing buttons below to refresh any changes made to your system configuration values."},corsConfig:{title:"CORS Overview",text:"Enter allowed hosts and HTTP verbs. You can enter * for all hosts. Use the * option for development to enable application code running locally on your computer to communicate directly with your DreamFactory instance."},emailTemplates:{title:"Email Templates Overview",text:"Create and edit email templates for User Registration, User Invite, Password Reset, and your custom email services."},globalLookupKeys:{title:"Global Lookup Keys Overview",text:'An administrator can create any number of "key value" pairs attached to DreamFactory. The key values are automatically substituted on the server. For example, you can use Lookup Keys in Email Templates, as parameters in external REST Services, and in the username and password fields to connect to a SQL or NoSQL database. Mark any Lookup Key as private to securely encrypt the key value on the server and hide it in the user interface. Note that Lookup Keys for REST service configuration and credentials must be private.'}},$scope.apiData={},$scope.loadTabData=function(){var apis=["cache","environment","cors","lookup","email_template","custom"];angular.forEach(apis,function(api){dfApplicationData.getApiData([api]).then(function(response){$scope.apiData[api]=response[0].resource?response[0].resource:response[0]},function(error){}).finally(function(){$scope.links=$scope.buildLinks(!0),$scope.$emit("sidebar-nav:view:reset")})})},$scope.loadTabData()}]).directive("dreamfactorySystemInfo",["MODSYSCONFIG_ASSET_PATH","LicenseDataService","SystemConfigDataService",function(MODSYSCONFIG_ASSET_PATH,LicenseDataService,SystemConfigDataService){return{restrict:"E",scope:!1,templateUrl:MODSYSCONFIG_ASSET_PATH+"views/system-info.html",link:function(scope,elem,attrs){scope.paidLicense=!1,scope.upgrade=function(){window.top.location="http://wiki.dreamfactory.com/"};var platform=SystemConfigDataService.getSystemConfig().platform;platform&&platform.hasOwnProperty("license")&&LicenseDataService.isLicenseRequiredSubscription(platform.license)?(scope.paidLicense=!0,LicenseDataService.getSubscriptionData().then(function(data){scope.subscriptionData=data})):scope.subscriptionData={};var watchEnvironment=scope.$watchCollection("apiData.environment",function(newValue,oldValue){newValue&&(scope.systemEnv=newValue)});scope.$on("$destroy",function(e){watchEnvironment()})}}}]).directive("dreamfactoryCacheConfig",["MODSYSCONFIG_ASSET_PATH","INSTANCE_URL","$http","dfNotify",function(MODSYSCONFIG_ASSET_PATH,INSTANCE_URL,$http,dfNotify){return{restrict:"E",scope:!1,templateUrl:MODSYSCONFIG_ASSET_PATH+"views/cache-config.html",link:function(scope,elem,attrs){scope.apiData.cache&&scope.apiData.cache.length>0&&scope.apiData.cache.sort(function(a,b){return a.label>b.label?1:a.label0?scope.adminRoleId=result.data.user_to_app_to_role_by_user_id[0].role_id:(scope.adminRoleId=null,scope.widgetDescription="Restricted admin. An auto-generated role will be created for this admin.")},function(result){scope.adminRoleId=null,console.error(result)})}}),watchPassword=scope.$watch("setPassword",function(newValue){newValue?scope.password={new_password:"",verify_password:""}:(scope.password=null,scope.identical=!0)});scope.$on("$destroy",function(e){watchAdminData(),watchPassword()}),scope.dfHelp={adminConfirmation:{title:"Admin Confirmation Info",text:"Is the admin confirmed? You can send an invite to unconfirmed admins."},adminLookupKeys:{title:"Admin Lookup Keys Info",text:'The DreamFactory administrator can create any number of "key value" pairs attached to a admin. The key values are automatically substituted on the server. For example, key names can be used in the username and password fields required to hook up a SQL or NoSQL database. They can also be used in Email Templates or as parameters for external REST services. Any Lookup Key can be marked as private, and in this case the key value is securely encrypted on the server and is no longer accessible through the platform interface. Lookup keys for service configuration and credentials must be made private.'}}}}}]).directive("dfConfirmAdmin",["INSTANCE_URL","MOD_ADMIN_ASSET_PATH","$http","SystemConfigDataService","dfNotify",function(INSTANCE_URL,MOD_ADMIN_ASSET_PATH,$http,SystemConfigDataService,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_ADMIN_ASSET_PATH+"views/df-input-confirm-admin.html",link:function(scope,elem,attrs){scope.sendEmailOnCreate=!1,scope.invite=function(){$http({url:INSTANCE_URL.url+"/system/admin/"+scope.admin.record.id,method:"PATCH",params:{send_invite:!0}}).then(function(result){var messageOptions={module:"Admins",type:"success",provider:"dreamfactory",message:"Admin invite has been sent."};dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Admins",type:"error",provider:"dreamfactory",exception:reject.data};dfNotify.error(messageOptions)})}}}}]).directive("dfAccessByTabs",["INSTANCE_URL","MOD_ADMIN_ASSET_PATH","$http","SystemConfigDataService","UserDataService","dfApplicationData",function(INSTANCE_URL,MOD_ADMIN_ASSET_PATH,$http,SystemConfigDataService,UserDataService,dfApplicationData){return{restrict:"E",scope:!1,templateUrl:MOD_ADMIN_ASSET_PATH+"views/df-access-by-tabs.html",link:function(scope,elem,attrs){var currentUser=UserDataService.getCurrentUser();scope.accessByTabsLoaded=!1,scope.subscription_required=!dfApplicationData.isGoldLicense(),scope.isRootAdmin=currentUser.is_root_admin,scope.widgetDescription="Restricted admin. An auto-generated role will be created for this admin.",scope.accessByTabs=[{name:"apps",title:"Apps",checked:!0},{name:"users",title:"Users",checked:!0},{name:"services",title:"Services",checked:!0},{name:"apidocs",title:"API Docs",checked:!0},{name:"schema/data",title:"Schema/Data",checked:!0},{name:"files",title:"Files",checked:!0},{name:"scripts",title:"Scripts",checked:!0},{name:"config",title:"Config",checked:!0},{name:"packages",title:"Packages",checked:!0},{name:"limits",title:"Limits",checked:!0},{name:"scheduler",title:"Scheduler",checked:!0}],scope.areAllTabsSelected=!0,scope.selectTab=function(){scope.areAllTabsSelected=scope.accessByTabs.every(function(tab){return tab.checked})},scope.selectAllTabs=function(isSelected){scope.areAllTabsSelected=isSelected,scope.areAllTabsSelected?scope.accessByTabs.forEach(function(tab){tab.checked=!0}):scope.accessByTabs.forEach(function(tab){tab.checked=!1})};var watchAccessTabsData=scope.$watch("adminRoleId",function(newValue,oldValue){newValue&&(scope.widgetDescription="Restricted admin. Role id: "+newValue,$http.get(INSTANCE_URL.url+"/system/role/"+newValue+"/?accessible_tabs=true").then(function(result){scope.accessByTabs.forEach(function(tab){result.data.accessible_tabs&&-1===result.data.accessible_tabs.indexOf(tab.name)&&(tab.checked=!1)}),scope.areAllTabsSelected=scope.accessByTabs.every(function(tab){return!0===tab.checked})},function(result){console.error(result)}))});scope.$on("$destroy",function(e){watchAccessTabsData()})}}}]).directive("dfAdminLookupKeys",["MOD_ADMIN_ASSET_PATH",function(MOD_ADMIN_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_ADMIN_ASSET_PATH+"views/df-input-lookup-keys.html",link:function(scope,elem,attrs){var LookupKey=function(lookupKeyData){var _new={name:"",value:"",private:!1,allow_admin_update:!1};return{__dfUI:{unique:!0},record:angular.copy(lookupKeyData||_new),recordCopy:angular.copy(lookupKeyData||_new)}};scope.lookupKeys=[],scope.sameKeys=[],scope.newKey=function(){scope._newKey()},scope.removeKey=function(index){scope._removeKey(index)},scope._isUniqueKey=function(){scope.sameKeys=[],angular.forEach(scope.lookupKeys,function(value,index){angular.forEach(scope.lookupKeys,function(_value,_index){index!==_index&&value.record.name===_value.record.name&&scope.sameKeys.push(value)})})},scope._preparePasswordData=function(){scope.setPassword?scope.admin.record.password=scope.password.new_password:scope.admin.record.password&&delete scope.admin.record.password},scope._prepareAccessByTabsData=function(){var accessByTabs=[];scope.accessByTabs.forEach(function(tab){tab.checked&&accessByTabs.push(tab.name)}),scope.admin.record.access_by_tabs=accessByTabs,scope.admin.record.is_restricted_admin=!scope.areAllTabsSelected||!!scope.adminRoleId},scope._prepareLookupKeyData=function(){var tempArr=[];angular.forEach(scope.lookupKeys,function(lk){tempArr.push(lk.record)}),scope.admin.record.lookup_by_user_id=tempArr},scope._newKey=function(){scope.lookupKeys.push(new LookupKey)},scope._removeKey=function(index){void 0!==scope.lookupKeys[index].record.user_id?scope.lookupKeys[index].record.user_id=null:scope.lookupKeys.splice(index,1)};var watchAdmin=scope.$watch("admin",function(newValue,oldValue){newValue&&(newValue.record.hasOwnProperty("lookup_by_user_id")&&newValue.record.lookup_by_user_id.length>0?(scope.lookupKeys=[],angular.forEach(newValue.record.lookup_by_user_id,function(lookupKeyData){scope.lookupKeys.push(new LookupKey(lookupKeyData))})):scope.lookupKeys=[])}),watchSameKeys=scope.$watch("sameKeys",function(newValue,oldValue){0!==newValue.length?angular.forEach(scope.lookupKeys,function(lk){angular.forEach(newValue,function(_lk){lk.record.name===_lk.record.name?lk.__dfUI.unique=!1:lk.__dfUI.unique=!0})}):angular.forEach(scope.lookupKeys,function(lk){lk.__dfUI.unique=!0})});scope.$watchCollection("lookupKeys",function(newValue,oldValue){newValue&&scope._isUniqueKey()});scope.$on("$destroy",function(e){watchAdmin(),watchSameKeys()})}}}]).directive("dfManageAdmins",["$rootScope","MOD_ADMIN_ASSET_PATH","dfApplicationData","dfNotify","$location",function($rootScope,MOD_ADMIN_ASSET_PATH,dfApplicationData,dfNotify,$location){return{restrict:"E",scope:!1,templateUrl:MOD_ADMIN_ASSET_PATH+"views/df-manage-admins.html",link:function(scope,elem,attrs){var ManagedAdmin=function(adminData){return adminData&&(adminData.confirm_msg="N/A",!0===adminData.confirmed?adminData.confirm_msg="Confirmed":!1===adminData.confirmed&&(adminData.confirm_msg="Pending"),!0===adminData.expired&&(adminData.confirm_msg="Expired")),{__dfUI:{selected:!1},record:adminData}};scope.uploadFile=null,scope.admins=null,scope.currentEditAdmin=null,scope.fields=[{name:"id",label:"ID",active:!0},{name:"email",label:"Email",active:!0},{name:"name",label:"Display Name",active:!0},{name:"first_name",label:"First Name",active:!0},{name:"last_name",label:"Last Name",active:!0},{name:"is_active",label:"Active",active:!0},{name:"confirmed",label:"Registration",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedAdmins=[],scope.editAdmin=function(admin){scope._editAdmin(admin)},scope.deleteAdmin=function(admin){dfNotify.confirm("Delete "+admin.record.name+"?")&&scope._deleteAdmin(admin)},scope.deleteSelectedAdmins=function(){dfNotify.confirm("Delete selected admins?")&&scope._deleteSelectedAdmins()},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setSelected=function(admin){scope._setSelected(admin)},scope._editAdmin=function(admin){scope.currentEditAdmin=admin},scope._deleteAdmin=function(admin){var requestDataObj={params:{id:admin.record.id}};dfApplicationData.deleteApiData("admin",requestDataObj).$promise.then(function(result){var messageOptions={module:"Admins",type:"success",provider:"dreamfactory",message:"Admin successfully deleted."};dfNotify.success(messageOptions),admin.__dfUI.selected&&scope.setSelected(admin),scope.$broadcast("toolbar:paginate:admin:delete")},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope._setSelected=function(admin){for(var i=0;i"}}]).directive("dfImportAdmins",["MOD_ADMIN_ASSET_PATH","INSTANCE_URL","$http","dfTableEventService","dfNotify",function(MOD_ADMIN_ASSET_PATH,INSTANCE_URL,$http,dfTableEventService,dfNotify){return{restrict:"A",scope:!1,replace:!0,link:function(scope,elem,attrs){scope.importType=null,scope.field=angular.element("#upload"),scope.importAdmins=function(){scope._importAdmins()},scope._importAdmins=function(){scope.field.trigger("click")},scope._uploadFile=function(fileObj){return $http({method:"POST",url:INSTANCE_URL.url+"/system/admin",headers:{"Content-Type":"csv"===scope.importType?"text/csv":"application/"+scope.importType},params:{},data:fileObj})},scope._checkFileType=function(fileObj){var extension=fileObj.name.split("."),value=!1;switch(extension=extension[extension.length-1]){case"csv":case"json":case"xml":scope.importType=extension,value=!0;break;default:value=!1}return value},scope.$watch("uploadFile",function(newValue,oldValue){if(!newValue)return!1;if(newValue=scope.uploadFile,!scope._checkFileType(newValue)){scope.uploadFile=null;var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:"Acceptable file formats are csv, json, and xml."};return dfNotify.error(messageOptions),!1}scope._uploadFile(newValue).then(function(result){scope.importType=null,scope.uploadFile=null,$("#upload").val("");var messageOptions={module:"Admins",type:"success",provider:"dreamfactory",message:"Admins imported successfully."};dfNotify.success(messageOptions),scope.$broadcast("toolbar:paginate:admin:reset")},function(reject){scope.importType=null,scope.uploadFile=null,$("#upload").val("");var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions),scope.$broadcast("toolbar:paginate:admin:reset")})})}}}]).directive("dfExportAdmins",["MOD_ADMIN_ASSET_PATH","INSTANCE_URL","UserDataService","$http","$window","APP_API_KEY",function(MOD_ADMIN_ASSET_PATH,INSTANCE_URL,UserDataService,$http,$window,APP_API_KEY){return{restrict:"A",scope:!1,replace:!0,link:function(scope,elem,attrs){scope.fileFormatStr=null,scope.exportAdmins=function(fileFormatStr){scope._exportAdmins(fileFormatStr)},scope._getFile=function(urlStr){return $http({method:"GET",url:urlStr})},scope._exportAdmins=function(fileFormatStr){if("csv"===fileFormatStr||"json"===fileFormatStr||"xml"===fileFormatStr){scope.fileFormatStr=fileFormatStr;var params="file=admin."+scope.fileFormatStr+"&api_key="+APP_API_KEY,currentUser=UserDataService.getCurrentUser();currentUser&¤tUser.session_token&&(params+="&session_token="+currentUser.session_token),$window.location.href=INSTANCE_URL.url+"/system/admin?"+params}}}}}]),angular.module("dfUsers",["ngRoute","dfUtility","dfApplication","dfHelp"]).constant("MOD_USER_ROUTER_PATH","/users").constant("MOD_USER_ASSET_PATH","admin_components/adf-users/").config(["$routeProvider","MOD_USER_ROUTER_PATH","MOD_USER_ASSET_PATH",function($routeProvider,MOD_USER_ROUTER_PATH,MOD_USER_ASSET_PATH){$routeProvider.when(MOD_USER_ROUTER_PATH,{templateUrl:MOD_USER_ASSET_PATH+"views/main.html",controller:"UsersCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("UsersCtrl",["$rootScope","$scope","dfApplicationData","dfNotify","$location",function($rootScope,$scope,dfApplicationData,dfNotify,$location){$scope.$parent.title="Users",$scope.$parent.titleIcon="users",$scope.links=[{name:"manage-users",label:"Manage",path:"manage-users"},{name:"create-user",label:"Create",path:"create-user"}],$scope.emptySectionOptions={title:"You have no Users!",text:"Click the button below to get started adding users. You can always create new users by clicking the tab located in the section menu to the left.",buttonText:"Create A User!",viewLink:$scope.links[1],active:!1},$scope.emptySearchResult={title:"You have no Users that match your search criteria!",text:""},$scope.apiData=null,$scope.loadTabData=function(){$scope.dataLoading=!0;var apis=["user","role","app"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData},function(error){var msg="There was an error loading data for the Users tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Users tab your role must allow GET access to system/user, system/role, and system/app. To create, update, or delete users you need POST, PUT, DELETE access to /system/user and/or /system/user/*.",$location.url("/home"));var messageOptions={module:"Users",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData()}]).directive("dfUserDetails",["MOD_USER_ASSET_PATH","dfApplicationData","dfNotify","dfObjectService","INSTANCE_URL","$http","$cookies","UserDataService","$rootScope","SystemConfigDataService",function(MOD_USER_ASSET_PATH,dfApplicationData,dfNotify,dfObjectService,INSTANCE_URL,$http,$cookies,UserDataService,$rootScope,SystemConfigDataService){return{restrict:"E",scope:{userData:"=?",newUser:"=?",apiData:"=?"},templateUrl:MOD_USER_ASSET_PATH+"views/df-user-details.html",link:function(scope,elem,attrs){var User=function(userData){var _user={name:null,first_name:null,last_name:null,email:null,phone:null,confirmed:!1,is_active:!0,default_app_id:null,user_source:0,user_data:[],password:null,lookup_by_user_id:[],user_to_app_to_role_by_user_id:[]};return userData=userData||_user,{__dfUI:{selected:!1},record:angular.copy(userData),recordCopy:angular.copy(userData)}};scope.loginAttribute="email";var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=systemConfig.authentication.login_attribute),scope.user=null,scope.newUser&&(scope.user=new User),scope.sendEmailOnCreate=!1,scope._validateData=function(){if(scope.newUser){if(!scope.setPassword&&!scope.sendEmailOnCreate)return dfNotify.error({module:"Users",type:"error",message:"Please select email invite or set password."}),!1;if(scope.setPassword&&scope.sendEmailOnCreate)return dfNotify.error({module:"Users",type:"error",message:"Please select email invite or set password, but not both."}),!1}return!scope.setPassword||scope.password.new_password===scope.password.verify_password||(dfNotify.error({module:"Users",type:"error",message:"Passwords do not match."}),!1)},scope.saveUser=function(){scope._validateData()&&(scope.newUser?scope._saveUser():scope._updateUser())},scope.cancelEditor=function(){scope._prepareUserData(),(dfObjectService.compareObjectsAsJson(scope.user.record,scope.user.recordCopy)||dfNotify.confirmNoSave())&&scope.closeEditor()},scope.closeEditor=function(){scope.userData=null,scope.user=new User,scope.roleToAppMap={},scope.lookupKeys=[],scope._resetUserPasswordForm(),scope.$emit("sidebar-nav:view:reset")},scope._prepareUserData=function(){scope._preparePasswordData(),scope._prepareLookupKeyData()},scope._saveUser=function(){scope._prepareUserData();var requestDataObj={params:{fields:"*",related:"user_to_app_to_role_by_user_id,lookup_by_user_id",send_invite:scope.sendEmailOnCreate},data:scope.user.record};dfApplicationData.saveApiData("user",requestDataObj).$promise.then(function(result){var messageOptions={module:"Users",provider:"dreamfactory",type:"success",message:"User saved successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._updateUser=function(){scope._prepareUserData();var requestDataObj={params:{fields:"*",related:"user_to_app_to_role_by_user_id,lookup_by_user_id"},data:scope.user.record};dfApplicationData.updateApiData("user",requestDataObj).$promise.then(function(result){if(result.session_token){var existingUser=UserDataService.getCurrentUser();existingUser.session_token=result.session_token,UserDataService.setCurrentUser(existingUser)}var messageOptions={module:"Users",provider:"dreamfactory",type:"success",message:"User updated successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})};var watchUserData=scope.$watch("userData",function(newValue,oldValue){newValue&&(scope.user=new User(newValue))}),watchPassword=scope.$watch("setPassword",function(newValue){newValue?scope.password={new_password:"",verify_password:""}:(scope.password=null,scope.identical=!0)});scope.$on("$destroy",function(e){watchUserData(),watchPassword()}),scope.dfHelp={userRole:{title:"User Role Info",text:"Roles provide a way to grant or deny access to specific applications and services on a per-user basis. Each user who is not a system admin must be assigned a role. Go to the Roles tab to create and manage roles."},userConfirmation:{title:"User Confirmation Info",text:"Is the user confirmed? You can send an invite to unconfirmed users."},userLookupKeys:{title:"User Lookup Keys Info",text:'The DreamFactory administrator can create any number of "key value" pairs attached to a user. The key values are automatically substituted on the server. For example, key names can be used in the username and password fields required to hook up a SQL or NoSQL database. They can also be used in Email Templates or as parameters for external REST services. Any Lookup Key can be marked as private, and in this case the key value is securely encrypted on the server and is no longer accessible through the platform interface. Lookup keys for service configuration and credentials must be made private.'}}}}}]).directive("dfConfirmUser",["INSTANCE_URL","MOD_USER_ASSET_PATH","$http","dfNotify",function(INSTANCE_URL,MOD_USER_ASSET_PATH,$http,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_USER_ASSET_PATH+"views/df-input-confirm-user.html",link:function(scope,elem,attrs){scope.sendEmailOnCreate=!1,scope.invite=function(){$http({url:INSTANCE_URL.url+"/system/user/"+scope.user.record.id,method:"PATCH",params:{send_invite:!0}}).then(function(result){var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"User invite has been sent."};dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Users",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)})}}}}]).directive("dfUserRoles",["MOD_USER_ASSET_PATH",function(MOD_USER_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_USER_ASSET_PATH+"views/df-user-roles.html",link:function(scope,elem,attrs){scope.roleToAppMap={},scope.$watch("user",function(){scope.user&&scope.user.record.user_to_app_to_role_by_user_id.forEach(function(item){scope.roleToAppMap[item.app_id]=item.role_id})}),scope.selectRole=function(){Object.keys(scope.roleToAppMap).forEach(function(item){scope.roleToAppMap[item]?scope._updateRoleApp(item,scope.roleToAppMap[item]):scope._removeRoleApp(item,scope.roleToAppMap[item])})},scope._removeRoleApp=function(appId){var existing=scope.user.record.user_to_app_to_role_by_user_id.filter(function(item){return item.app_id==appId})[0];existing&&(existing.user_id=null)},scope._updateRoleApp=function(appId,roleId){var existing=scope.user.record.user_to_app_to_role_by_user_id.filter(function(item){return item.app_id==appId})[0];existing?(existing.app_id=appId,existing.role_id=roleId):scope.user.record.user_to_app_to_role_by_user_id.push({app_id:appId,role_id:roleId,user_id:scope.user.record.id})}}}}]).directive("dfUserLookupKeys",["MOD_USER_ASSET_PATH",function(MOD_USER_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_USER_ASSET_PATH+"views/df-input-lookup-keys.html",link:function(scope,elem,attrs){var LookupKey=function(lookupKeyData){var _new={name:"",value:"",private:!1,allow_user_update:!1};return{__dfUI:{unique:!0},record:angular.copy(lookupKeyData||_new),recordCopy:angular.copy(lookupKeyData||_new)}};scope.lookupKeys=[],scope.sameKeys=[],scope.newKey=function(){scope._newKey()},scope.removeKey=function(index){scope._removeKey(index)},scope._isUniqueKey=function(){scope.sameKeys=[],angular.forEach(scope.lookupKeys,function(value,index){angular.forEach(scope.lookupKeys,function(_value,_index){index!==_index&&value.record.name===_value.record.name&&scope.sameKeys.push(value)})})},scope._preparePasswordData=function(){scope.setPassword?scope.user.record.password=scope.password.new_password:scope.user.record.password&&delete scope.user.record.password},scope._prepareLookupKeyData=function(){var tempArr=[];angular.forEach(scope.lookupKeys,function(lk){tempArr.push(lk.record)}),scope.user.record.lookup_by_user_id=tempArr},scope._newKey=function(){scope.lookupKeys.push(new LookupKey)},scope._removeKey=function(index){void 0!==scope.lookupKeys[index].record.user_id?scope.lookupKeys[index].record.user_id=null:scope.lookupKeys.splice(index,1)};var watchUser=scope.$watch("user",function(newValue,oldValue){newValue&&(newValue.record.hasOwnProperty("lookup_by_user_id")&&newValue.record.lookup_by_user_id.length>0?(scope.lookupKeys=[],angular.forEach(newValue.record.lookup_by_user_id,function(lookupKeyData){scope.lookupKeys.push(new LookupKey(lookupKeyData))})):scope.lookupKeys=[])}),watchSameKeys=scope.$watch("sameKeys",function(newValue,oldValue){0!==newValue.length?angular.forEach(scope.lookupKeys,function(lk){angular.forEach(newValue,function(_lk){lk.record.name===_lk.record.name?lk.__dfUI.unique=!1:lk.__dfUI.unique=!0})}):angular.forEach(scope.lookupKeys,function(lk){lk.__dfUI.unique=!0})}),watchLookupKeys=scope.$watchCollection("lookupKeys",function(newValue,oldValue){newValue&&scope._isUniqueKey()});scope.$on("$destroy",function(e){watchUser(),watchSameKeys(),watchLookupKeys()})}}}]).directive("dfManageUsers",["$rootScope","MOD_USER_ASSET_PATH","dfApplicationData","dfNotify",function($rootScope,MOD_USER_ASSET_PATH,dfApplicationData,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_USER_ASSET_PATH+"views/df-manage-users.html",link:function(scope,elem,attrs){var ManagedUser=function(userData){return userData&&(userData.confirm_msg="N/A",!0===userData.confirmed?userData.confirm_msg="Confirmed":!1===userData.confirmed&&(userData.confirm_msg="Pending"),!0===userData.expired&&(userData.confirm_msg="Expired")),{__dfUI:{selected:!1},record:userData}};scope.uploadFile={path:""},scope.users=null,scope.currentEditUser=null,scope.fields=[{name:"id",label:"ID",active:!0},{name:"email",label:"Email",active:!0},{name:"name",label:"Display Name",active:!0},{name:"first_name",label:"First Name",active:!0},{name:"last_name",label:"Last Name",active:!0},{name:"is_active",label:"Active",active:!0},{name:"confirmed",label:"Registration",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedUsers=[],scope.editUser=function(user){scope._editUser(user)},scope.deleteUser=function(user){dfNotify.confirm("Delete "+user.record.name+"?")&&scope._deleteUser(user)},scope.deleteSelectedUsers=function(){dfNotify.confirm("Delete selected users?")&&scope._deleteSelectedUsers()},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setSelected=function(user){scope._setSelected(user)},scope._editUser=function(user){scope.currentEditUser=user},scope._deleteUser=function(user){var requestDataObj={params:{id:user.record.id}};dfApplicationData.deleteApiData("user",requestDataObj).$promise.then(function(result){var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"User successfully deleted."};dfNotify.success(messageOptions),user.__dfUI.selected&&scope.setSelected(user),scope.$broadcast("toolbar:paginate:user:delete")},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope._setSelected=function(user){for(var i=0;i"}}]).directive("dfImportUsers",["MOD_USER_ASSET_PATH","INSTANCE_URL","$http","dfTableEventService","dfNotify",function(MOD_USER_ASSET_PATH,INSTANCE_URL,$http,dfTableEventService,dfNotify){return{restrict:"A",scope:!1,replace:!0,link:function(scope,elem,attrs){scope.importType=null,scope.field=angular.element("#upload"),scope.importUsers=function(){scope._importUsers()},scope._importUsers=function(){scope.field.trigger("click")},scope._uploadFile=function(fileObj){return $http({method:"POST",url:INSTANCE_URL.url+"/system/user",headers:{"Content-Type":"csv"===scope.importType?"text/csv":"application/"+scope.importType},params:{},data:fileObj})},scope._checkFileType=function(fileObj){var extension=fileObj.name.split("."),value=!1;switch(extension=extension[extension.length-1]){case"csv":case"json":case"xml":scope.importType=extension,value=!0;break;default:value=!1}return value},scope.$watch("uploadFile.path",function(newValue,oldValue){if(!newValue)return!1;if(newValue=scope.uploadFile.path,!scope._checkFileType(newValue)){scope.uploadFile.path="";var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:"Acceptable file formats are csv, json, and xml."};return dfNotify.error(messageOptions),!1}scope._uploadFile(newValue).then(function(result){scope.importType=null,scope.uploadFile.path="",$("#upload").val("");var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"Users imported successfully."};dfNotify.success(messageOptions),scope.$broadcast("toolbar:paginate:user:reset")},function(reject){scope.importType=null,scope.uploadFile.path="",$("#upload").val("");var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions),scope.$broadcast("toolbar:paginate:user:reset")})})}}}]).directive("dfExportUsers",["MOD_USER_ASSET_PATH","INSTANCE_URL","UserDataService","$http","$window","APP_API_KEY",function(MOD_USER_ASSET_PATH,INSTANCE_URL,UserDataService,$http,$window,APP_API_KEY){return{restrict:"A",scope:!1,replace:!0,link:function(scope,elem,attrs){scope.fileFormatStr=null,scope.exportUsers=function(fileFormatStr){scope._exportUsers(fileFormatStr)},scope._getFile=function(urlStr){return $http({method:"GET",url:urlStr})},scope._exportUsers=function(fileFormatStr){if("csv"===fileFormatStr||"json"===fileFormatStr||"xml"===fileFormatStr){scope.fileFormatStr=fileFormatStr;var params="file=user."+scope.fileFormatStr+"&api_key="+APP_API_KEY,currentUser=UserDataService.getCurrentUser();currentUser&¤tUser.session_token&&(params+="&session_token="+currentUser.session_token),$window.location.href=INSTANCE_URL.url+"/system/user?"+params}}}}}]),angular.module("dfApps",["ngRoute","dfUtility","dfApplication","dfHelp","dfTable"]).constant("MOD_APPS_ROUTER_PATH","/apps").constant("MOD_APPS_ASSET_PATH","admin_components/adf-apps/").config(["$routeProvider","MOD_APPS_ROUTER_PATH","MOD_APPS_ASSET_PATH",function($routeProvider,MOD_APPS_ROUTER_PATH,MOD_APPS_ASSET_PATH){$routeProvider.when(MOD_APPS_ROUTER_PATH,{templateUrl:MOD_APPS_ASSET_PATH+"views/main.html",controller:"AppsCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("AppsCtrl",["$rootScope","$scope","dfApplicationData","dfNotify","$location",function($rootScope,$scope,dfApplicationData,dfNotify,$location){$scope.$parent.title="Apps",$scope.$parent.titleIcon="desktop",$scope.links=[{name:"manage-apps",label:"Manage",path:"manage-apps"},{name:"create-app",label:"Create",path:"create-app"},{name:"import-app",label:"Import",path:"import-app"}],$scope.emptySectionOptions={title:"You have no Apps!",text:"Click the button below to get started building your first application. You can always create new applications by clicking the tab located in the section menu to the left.",buttonText:"Create An App!",viewLink:$scope.links[1],active:!1},$scope.emptySearchResult={title:"You have no Apps that match your search criteria!",text:""},$scope.$on("$destroy",function(e){$scope.$broadcast("toolbar:paginate:app:destroy")}),$scope.apiData=null,$scope.loadTabData=function(init){$scope.dataLoading=!0;var apis=["app","role","service"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index],"service"===value&&(newApiData[value]=newApiData[value].filter(function(obj){return["local_file","aws_s3","azure_blob","rackspace_cloud_files","openstack_object_storage","ftp_file","sftp_file","gridfs"].indexOf(obj.type)>=0}))}),$scope.apiData=newApiData,init&&$scope.$broadcast("toolbar:paginate:app:load")},function(error){var msg="There was an error loading data for the Apps tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Apps tab your role must allow GET access to system/app, system/role, and system/service. To create, update, or delete apps you need POST, PUT, DELETE access to /system/app and/or /system/app/*.",$location.url("/home"));var messageOptions={module:"Apps",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(!0)}]).directive("dfAppDetails",["MOD_APPS_ASSET_PATH","dfServerInfoService","dfApplicationData","dfNotify","dfObjectService",function(MOD_APPS_ASSET_PATH,dfServerInfoService,dfApplicationData,dfNotify,dfObjectService){return{restrict:"E",scope:{appData:"=?",newApp:"=?",apiData:"=?"},templateUrl:MOD_APPS_ASSET_PATH+"views/df-app-details.html",link:function(scope,elem,attrs){var getLocalFileStorageServiceId=function(){var localFileSvc=scope.apiData.service.filter(function(obj){return"local_file"===obj.type});return localFileSvc&&localFileSvc.length>0?localFileSvc[0].id:null},App=function(appData){var _app={name:"",description:"",type:0,storage_service_id:getLocalFileStorageServiceId(),storage_container:"applications",path:"",url:"",role_id:null};return appData=appData||_app,{__dfUI:{selected:!1},record:angular.copy(appData),recordCopy:angular.copy(appData)}};scope.currentServer=dfServerInfoService.currentServer(),scope.app=null,scope.locations=[{label:"No Storage Required - remote device, client, or desktop.",value:"0"},{label:"On a provisioned file storage service.",value:"1"},{label:"On this web server.",value:"3"},{label:"On a remote URL.",value:"2"}],scope.newApp&&(scope.app=new App),scope.saveApp=function(){scope.newApp?scope._saveApp():scope._updateApp()},scope.cancelEditor=function(){(dfObjectService.compareObjectsAsJson(scope.app.record,scope.app.recordCopy)||dfNotify.confirmNoSave())&&scope.closeEditor()},scope._prepareAppData=function(record){var _app=angular.copy(record);switch(parseInt(_app.record.type)){case 0:delete _app.record.storage_service_id,delete _app.record.storage_container,delete _app.record.path,delete _app.record.url;break;case 1:delete _app.record.url;break;case 2:delete _app.record.storage_service_id,delete _app.record.storage_container,delete _app.record.path;break;case 3:delete _app.record.storage_service_id,delete _app.record.storage_container,delete _app.record.url}return _app.record},scope.closeEditor=function(){scope.appData=null,scope.app=new App,scope.$emit("sidebar-nav:view:reset")},scope._saveApp=function(){var requestDataObj={params:{fields:"*",related:"role_by_role_id"},data:scope._prepareAppData(scope.app)};dfApplicationData.saveApiData("app",requestDataObj).$promise.then(function(result){var messageOptions={module:"Apps",type:"success",provider:"dreamfactory",message:scope.app.record.name+" saved successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._updateApp=function(){var requestDataObj={params:{fields:"*",related:"role_by_role_id"},data:scope._prepareAppData(scope.app)};dfApplicationData.updateApiData("app",requestDataObj).$promise.then(function(result){var messageOptions={module:"Apps",type:"success",provider:"dreamfactory",message:scope.app.record.name+" updated successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})};var watchAppStorageService=scope.$watch("app.record.storage_service_id",function(newValue,oldValue){scope.app&&scope.app.record&&scope.apiData.service&&(scope.selectedStorageService=scope.apiData.service.filter(function(item){return item.id==scope.app.record.storage_service_id})[0])}),watchAppData=scope.$watch("appData",function(newValue,oldValue){newValue&&(scope.app=new App(newValue))});scope.$on("$destroy",function(e){watchAppStorageService(),watchAppData()}),scope.dfHelp={applicationName:{title:"Application API Key",text:"This API KEY is unique per application and must be included with each API request as a query param (api_key=yourapikey) or a header (X-DreamFactory-API-Key: yourapikey)."},name:{title:"Display Name",text:"The display name or label for your app, seen by users of the app in the LaunchPad UI."},description:{title:"Description",text:"The app description, seen by users of the app in the LaunchPad UI."},appLocation:{title:"App Location",text:"Select File Storage if you want to store your app code on your DreamFactory instance or some other remote file storage. Select Native for native apps or running the app from code on your local machine (CORS required). Select URL to specify a URL for your app."},storageService:{title:"Storage Service",text:"Where to store the files for your app."},storageContainer:{title:"Storage Folder",text:"The folder on the selected storage service."},defaultPath:{title:"Default Path",text:"The is the file to load when your app is run. Default is index.html."},remoteUrl:{title:"Remote Url",text:"Applications can consist of only a URL. This could be an app on some other server or a web site URL."},assignRole:{title:"Assign a Default Role",text:"Unauthenticated or guest users of the app will have this role."}}}}}]).directive("dfManageApps",["$rootScope","MOD_APPS_ASSET_PATH","dfApplicationData","dfNotify","$window",function($rootScope,MOD_APPS_ASSET_PATH,dfApplicationData,dfNotify,$window){return{restrict:"E",scope:!1,templateUrl:MOD_APPS_ASSET_PATH+"views/df-manage-apps.html",link:function(scope,elem,attrs){var ManagedApp=function(appData){return{__dfUI:{selected:!1},record:appData}};scope.apps=null,scope.currentEditApp=null,scope.fields=[{name:"id",label:"ID",active:!0},{name:"name",label:"Name",active:!0},{name:"role_by_role_id",label:"Role",active:!0},{name:"api_key",label:"API Key",active:!0},{name:"description",label:"Description",active:!0},{name:"is_active",label:"Active",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedApps=[],scope.removeFilesOnDelete=!1,scope.launchApp=function(app){scope._launchApp(app)},scope.editApp=function(app){scope._editApp(app)},scope.deleteApp=function(app){dfNotify.confirm("Delete "+app.record.name+"?")&&(app.record.native||null==app.record.storage_service_id||(scope.removeFilesOnDelete=dfNotify.confirm("Delete application files? Pressing cancel will retain the files in storage.")),scope._deleteApp(app))},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setSelected=function(app){scope._setSelected(app)},scope.deleteSelectedApps=function(){dfNotify.confirm("Delete selected apps?")&&(scope.removeFilesOnDelete=dfNotify.confirm("Delete application files?"),scope._deleteSelectedApps())},scope._launchApp=function(app){$window.open(app.record.launch_url)},scope._editApp=function(app){scope.currentEditApp=app},scope._deleteApp=function(app){var requestDataObj={params:{delete_storage:scope.removeFilesOnDelete,related:"role_by_role_id",fields:"*"},data:app.record};dfApplicationData.deleteApiData("app",requestDataObj).$promise.then(function(result){var messageOptions={module:"Apps",type:"success",provider:"dreamfactory",message:"App successfully deleted."};dfNotify.success(messageOptions),scope.$broadcast("toolbar:paginate:app:delete")},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope._setSelected=function(app){for(var i=0;i"}}]).directive("dfImportApp",["MOD_APPS_ASSET_PATH","$http","dfApplicationData","dfNotify",function(MOD_APPS_ASSET_PATH,$http,dfApplicationData,dfNotify){return{restrict:"E",scope:{apiData:"=?"},templateUrl:MOD_APPS_ASSET_PATH+"views/df-import-app.html",link:function(scope,elem,attrs){scope.containers=[],scope.appPath=null,scope.storageService="",scope.storageContainer="",scope.field=angular.element("#upload"),scope.uploadFile=null,scope.sampleAppsFirstColumn=[{name:"Address Book for Android",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/android-sdk/master/package/add_android.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/android-sdk"},{name:"Address Book for iOS Objective-C",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/ios-sdk/master/example-ios/package/add_ios.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/ios-sdk"},{name:"Address Book for iOS Swift",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/ios-swift-sdk/master/SampleAppSwift/package/add_ios_swift.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/ios-swift-sdk"},{name:"Address Book for JavaScript",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/javascript-sdk/master/add_javascript.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/javascript-sdk"},{name:"Address Book for AngularJS",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/angular-sdk/master/add_angular.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/angular-sdk"}],scope.sampleAppsSecondColumn=[{name:"Address Book for Angular 2",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/angular2-sdk/master/add_angular2.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/angular2-sdk"},{name:"Address Book for Ionic",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/ionic-sdk/master/package/add_ionic.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/ionic-sdk"},{name:"Address Book for Titanium",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/titanium-sdk/master/add_titanium.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/titanium-sdk"},{name:"Address Book for ReactJS",description:"",package_url:"https://github.com/dreamfactorysoftware/df-react-example-application/raw/master/df-react-example-application.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/df-react-example-application"},{name:"Address Book for .NET",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/.net-sdk/master/DreamFactory.AddressBook/App_Package/add_dotnet.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/.net-sdk"}],scope.submitApp=function(){if(!scope.appPath)return!1;scope._submitApp()},scope.browseFileSystem=function(){scope._resetImportApp(),scope.field.trigger("click")},scope.loadSampleApp=function(appObj){scope._loadSampleApp(appObj)},scope._isAppPathUrl=function(appPathStr){return"http://"===appPathStr.substr(0,7)||"https://"===appPathStr.substr(0,8)},scope._importAppToServer=function(requestDataObj){var _options={params:{},data:requestDataObj,dontWrapData:!0};return scope._isAppPathUrl(scope.appPath)?_options.headers={"Content-Type":"application/json"}:(_options.headers={"Content-Type":void 0},$http.defaults.transformRequest=angular.identity),dfApplicationData.saveApiData("app",_options).$promise},scope._isDFPackage=function(appPathStr){return".dfpkg"===appPathStr.substr(appPathStr.lastIndexOf("."))},scope._resetImportApp=function(){scope.appPath=null,scope.storageService="",scope.storageContainer="",scope.uploadFile=null,scope.field.val("")},scope._loadSampleApp=function(appObj){scope.appPath=appObj.package_url},scope._submitApp=function(){var requestDataObj={};if(scope._isAppPathUrl(scope.appPath))requestDataObj={import_url:scope.appPath,storage_service_id:scope.storageService.id,storage_container:scope.storageContainer};else{var fd=new FormData,storageId=scope.storageService&&void 0!==scope.storageService.id?scope.storageService.id:0,storageContainer=scope.storageContainer;fd.append("file",scope.uploadFile),fd.append("storage_service_id",storageId),fd.append("storage_container",storageContainer),requestDataObj=fd}scope._importAppToServer(requestDataObj).then(function(result){var messageOptions={module:"Apps",type:"success",provider:"dreamfactory",message:"App successfully imported."};dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(success){scope._resetImportApp(),$http.defaults.transformRequest=function(d,headers){if(angular.isObject(d))return angular.toJson(d)}})};var watchUploadFile=scope.$watch("uploadFile",function(n,o){n&&(scope.appPath=n.name)});scope.$on("$destroy",function(e){watchUploadFile()}),scope.dfHelp={applicationName:{title:"Application Name",text:"This is some help text that will be displayed in the help window"}}}}}]),angular.module("dfData",["ngRoute","dfUtility","dfTable"]).constant("MOD_DATA_ROUTER_PATH","/data").constant("MOD_DATA_ASSET_PATH","admin_components/adf-data/").config(["$routeProvider","MOD_DATA_ROUTER_PATH","MOD_DATA_ASSET_PATH",function($routeProvider,MOD_DATA_ROUTER_PATH,MOD_DATA_ASSET_PATH){$routeProvider.when(MOD_DATA_ROUTER_PATH,{templateUrl:MOD_DATA_ASSET_PATH+"views/main.html",controller:"DataCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("DataCtrl",["$scope","INSTANCE_URL","dfApplicationData","dfNotify","$location",function($scope,INSTANCE_URL,dfApplicationData,dfNotify,$location){$scope.$parent.title="Data",$scope.$parent.titleIcon="database",$scope.links=[{name:"manage-data",label:"Manage",path:"manage-data"}],$scope.services=null,$scope.selected={service:null,resource:null},$scope.options={service:$scope.selected.service,table:$scope.selected.resource,url:INSTANCE_URL.url+"/"+$scope.selected.service+"/_table/"+$scope.selected.resource,allowChildTable:!0,childTableAttachPoint:"#child-table-attach"},$scope.$watchCollection("selected",function(newValue,oldValue){var options={service:newValue.service,table:newValue.resource,url:INSTANCE_URL.url+"/"+newValue.service+"/_table/"+newValue.resource,allowChildTable:!0,childTableAttachPoint:"#child-table-attach"};$scope.options=options}),$scope.$watchCollection("apiData.service_list",function(newValue,oldValue){newValue&&($scope.services=newValue.filter(function(obj){return["mysql","pgsql","sqlite","sqlsrv","memsql","sqlanywhere","oracle","ibmdb2","informix","firebird","aws_redshift_db","apache_hive","snowflake"].indexOf(obj.type)>=0}))}),$scope.apiData=null,$scope.loadTabData=function(){var apis=["service_list"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData},function(error){var messageOptions={module:"Data",provider:"dreamfactory",type:"error",message:"There was an error loading the Data tab. Please try refreshing your browser and logging in again."};dfNotify.error(messageOptions)})},$scope.loadTabData()}]),angular.module("dfServices",["ngRoute","dfUtility","dfApplication"]).constant("MOD_SERVICES_ROUTER_PATH","/services").constant("MOD_SERVICES_ASSET_PATH","admin_components/adf-services/").config(["$routeProvider","MOD_SERVICES_ROUTER_PATH","MOD_SERVICES_ASSET_PATH",function($routeProvider,MOD_SERVICES_ROUTER_PATH,MOD_SERVICES_ASSET_PATH){$routeProvider.when(MOD_SERVICES_ROUTER_PATH,{templateUrl:MOD_SERVICES_ASSET_PATH+"views/main.html",controller:"ServicesCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).factory("dfSelectedService",function(){return{currentServiceName:null,relatedRole:null,cleanCurrentService:function(){this.currentServiceName=null}}}).controller("ServicesCtrl",["$rootScope","$scope","dfApplicationData","dfNotify","$location",function($rootScope,$scope,dfApplicationData,dfNotify,$location){$scope.$parent.title="Services",$scope.$parent.titleIcon="cubes",$scope.relatedRoles=[],$scope.links=[{name:"manage-services",label:"Manage",path:"manage-services"},{name:"create-service",label:"Create",path:"create-service"}],$scope.emptySearchResult={title:"You have no Services that match your search criteria!",text:""},$scope.emptySectionOptions={title:"You have no Services!",text:'Click the button below to get started building your first Service. You can always create new services by clicking the "Create" tab located in the section menu to the left.',buttonText:"Create A Service!",viewLink:$scope.links[1]},$scope.$on("$destroy",function(e){$scope.$broadcast("toolbar:paginate:service:destroy")}),$scope.apiData=null,$scope.loadTabData=function(init){$scope.dataLoading=!0;var apis=["service","service_link","storage_service_link","service_type","role","environment"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData,init&&$scope.$broadcast("toolbar:paginate:service:load")},function(error){var msg="There was an error loading data for the Services tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Services tab your role must allow GET access to system/service and system/service_type. To create, update, or delete services you need POST, PUT, DELETE access to /system/service and/or /system/service/*.",$location.url("/home"));var messageOptions={module:"Services",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(!0)}]).directive("dfServiceLoading",[function(){return{restrict:"E",template:"
"}}]).directive("dfManageServices",["$rootScope","MOD_SERVICES_ASSET_PATH","dfApplicationData","dfNotify","$http","INSTANCE_URL","dfSelectedService",function($rootScope,MOD_SERVICES_ASSET_PATH,dfApplicationData,dfNotify,$http,INSTANCE_URL,dfSelectedService){return{restrict:"E",scope:!1,templateUrl:MOD_SERVICES_ASSET_PATH+"views/df-manage-services.html",link:function(scope,elem,attrs){var ManagedService=function(serviceData){return{__dfUI:{selected:!1},record:serviceData}};scope.services=[],scope.currentEditService=null,scope.selectedServices=[];var getRelatedRoles=function(){var currentServiceId=scope.currentEditService.id;return scope.apiData.role.filter(function(role){return role.role_service_access_by_role_id.some(function(service){return currentServiceId===service.service_id})})};scope.editService=function(service){scope.currentEditService=service,scope.$root.relatedRoles=getRelatedRoles()},scope.deleteService=function(service){if(dfNotify.confirm("Delete "+service.record.label+"?")){var requestDataObj={params:{id:service.record.id}};dfApplicationData.deleteApiData("service",requestDataObj).$promise.then(function(result){var messageOptions={module:"Services",type:"success",provider:"dreamfactory",message:"Service successfully deleted."};dfNotify.success(messageOptions),service.__dfUI.selected&&scope.setSelected(service),scope.$broadcast("toolbar:paginate:service:delete")},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})}},scope.deleteSelectedServices=function(){if(dfNotify.confirm("Delete selected services?")){var requestDataObj={params:{ids:scope.selectedServices.join(","),rollback:!0}};dfApplicationData.deleteApiData("service",requestDataObj).$promise.then(function(result){var messageOptions={module:"Services",type:"success",provider:"dreamfactory",message:"Services deleted successfully."};dfNotify.success(messageOptions),scope.selectedServices=[],scope.$broadcast("toolbar:paginate:service:reset")},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})}},scope.fields=[{name:"id",label:"ID",active:!0},{name:"name",label:"Name",active:!0},{name:"label",label:"Label",active:!0},{name:"description",label:"Description",active:!0},{name:"type",label:"Type",active:!0},{name:"is_active",label:"Active",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope.setSelected=function(service){for(var i=0;i-1&&data.config[item.name]&&data.config[item.name].length&&convert(item)}),data};scope.testServiceSchema=function(){var url=INSTANCE_URL.url+"/"+scope.serviceInfo.name+"/_schema",serviceName=scope.serviceInfo.name;return $http.get(url).then(function(response){return{type:"success",message:"Test connection succeeded.",serviceName:serviceName}},function(reject){if(!0===scope.apiData.environment.platform.app_debug)errorMessage="Test connection failed
Message: "+reject.data.error.message;else var errorMessage="Test connection failed, could just be a typo. Please check config credentials for Service Name: "+serviceName;return{type:"error",message:errorMessage,serviceName:serviceName}})},scope.isServiceTypeDatabase=function(){return"Database"===scope.selectedSchema.group},scope.notifyTestResults=function(testResult){var messageOptions={module:"Test Result for "+testResult.serviceName,type:testResult.type,message:testResult.message,tag:testResult.serviceName};"success"===messageOptions.type?dfNotify.success(messageOptions):dfNotify.error(messageOptions)},scope.saveService=function(){scope.prepareServiceData();var requestDataObj={params:{fields:"*",related:"service_doc_by_service_id"},data:normalizeKeyValuePairs()};dfApplicationData.saveApiData("service",requestDataObj).$promise.then(function(result){dfApplicationData.getApiData(["service_list"],!0);var messageOptions={module:"Services: "+scope.serviceInfo.name,type:scope.isServiceTypeDatabase()?"testing":"success",provider:"dreamfactory",message:scope.isServiceTypeDatabase()?"Service saved successfully. Now running connection test in the background.":"Service saved successfully.",tag:scope.isServiceTypeDatabase()?scope.serviceInfo.name:null};dfNotify.success(messageOptions),scope.closeEditor(),scope.isServiceTypeDatabase()&&scope.testServiceSchema().then(function(result){scope.notifyTestResults(result)})},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope.updateService=function(){scope.prepareServiceData();var requestDataObj={params:{fields:"*",related:"service_doc_by_service_id"},data:normalizeKeyValuePairs()};dfApplicationData.updateApiData("service",requestDataObj).$promise.then(function(result){var messageOptions={module:"Services: "+scope.serviceInfo.name,type:scope.isServiceTypeDatabase()?"testing":"success",provider:"dreamfactory",message:scope.isServiceTypeDatabase()?"Service updated successfully. Now running connection test in the background.":"Service updated successfully.",tag:scope.isServiceTypeDatabase()?scope.serviceInfo.name:null};scope.selections.saveAndClearCache&&(scope.clearCache(),messageOptions.message=scope.isServiceTypeDatabase()?"Service updated successfully and cache cleared. Now running connection test in the background.":"Service updated and cache successfully."),dfNotify.success(messageOptions),scope.selections.saveAndClose?scope.closeEditor():scope.serviceDetails=new ServiceDetails(result),scope.isServiceTypeDatabase()&&scope.testServiceSchema().then(function(result){scope.notifyTestResults(result)})},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope.refreshServiceConfigEditor=function(){$("#config-tab").tab("show"),scope.isInfoTab=!1;var editor=scope.serviceConfigEditorObj.editor;editor&&(editor.renderer.updateText(),editor.resize(!0),editor.focus())},scope.refreshServiceInfoEditor=function(){scope.isInfoTab=!0},scope.refreshServiceDefEditor=function(){scope.isInfoTab=!1;var editor=scope.serviceDefEditorObj.editor;editor&&(editor.renderer.updateText(),editor.resize(!0),editor.focus())},scope.serviceTypeToSchema=function(type){var schema=(scope.newService?scope.creatableServiceTypes:scope.editableServiceTypes).filter(function(item){return item.name===type});return schema.length>0?schema[0]:null};var watchServiceData=scope.$watch("serviceData",function(newValue,oldValue){scope.serviceDetails=new ServiceDetails(newValue),scope.updateHelpText(newValue)});scope.$on("$destroy",function(e){watchServiceData()}),scope.dfHelp={createService:{title:"Create Service Information",text:"Create Service information help text"}},scope.updateHelpText=function(record){var details,configText,serviceDefText,serviceDefReadOnlyText;details=" this service ",record&&record.label&&(details=" "+record.label+" "),configText="Specify any service-specific configuration for"+details+"below.",details="remote and script services",record&&record.label&&(details=" "+record.label+""),serviceDefText="For "+details+', you can specify a definition of the service below. Refer to the OpenAPI docs for details, or build and export your own from here.',details=" this service ",record&&record.label&&(details=" "+record.label+" "),serviceDefReadOnlyText="The service definition for "+details+"is pre-defined and can not be edited.",scope.dfLargeHelp={basic:{title:"Services Overview",text:"Services are where you set up REST API connections to databases, file storage, email, remote web services, and more."},config:{title:"Config Overview",text:configText},serviceDef:{title:"Service Definition Overview",text:serviceDefText},serviceDefReadOnly:{title:"Service Definition Overview",text:serviceDefReadOnlyText}}}}}}]).directive("dfServiceInfo",["MOD_SERVICES_ASSET_PATH","SystemConfigDataService","dfNotify","$location","dfSelectedService",function(MOD_SERVICES_ASSET_PATH,SystemConfigDataService,dfNotify,$location,dfSelectedService){return{restrict:"E",scope:!1,templateUrl:MOD_SERVICES_ASSET_PATH+"views/df-service-info.html",link:function(scope,elem,attrs){scope.serviceTypes=[],scope.serviceInfoError=!1,scope.serviceInfo={},scope.prepareServiceInfo=function(){return scope.serviceInfo},scope.sortArray=function(groupsArray,orderArray){var result=[];if(orderArray.forEach(function(group){-1!==groupsArray.indexOf(group)&&result.push(group)}),groupsArray.length>orderArray.length){var unsortedGroups=groupsArray.filter(function(i){return result.indexOf(i)<0});result.push.apply(result,unsortedGroups)}return result},scope.updateAffectedFields=function(fieldValue,field){if("driver"===field.name&&field.values){var foundValue=field.values.filter(function(item){return item.name===fieldValue})[0]||{};scope.serviceConfig.dsn=foundValue.dsn}},scope.validateServiceName=function(){var isNameValid=scope.serviceInfo.name.match(/^[a-z0-9_-]+$/);if(!isNameValid||0===isNameValid.length){var messageOptions={module:"Services",provider:"dreamfactory",type:"warn",message:"Be sure that service name is in lowercase and alphanumeric. It should only contain letters, numbers, underscores and dashes."};dfNotify.warn(messageOptions)}},scope.addMissingPaidServices=function(types){var silverServices=[{name:"adldap",label:"Active Directory",description:"A service for supporting Active Directory integration",group:"LDAP"},{name:"ldap",label:"Standard LDAP",description:"A service for supporting Open LDAP integration",group:"LDAP"},{name:"oidc",label:"OpenID Connect",description:"OpenID Connect service supporting SSO.",group:"OAuth"},{name:"oauth_azure_ad",label:"Azure Active Directory OAuth",description:"OAuth service for supporting Azure Active Directory authentication and API access.",group:"OAuth"},{name:"saml",label:"SAML 2.0",description:"SAML 2.0 service supporting SSO.",group:"SSO"},{name:"okta_saml",label:"Okta SAML",description:"Okta service supporting SSO.",group:"SSO"},{name:"auth0_sso",label:"Auth0 SSO",description:"Auth0 service supporting SSO.",group:"SSO"},{name:"ibmdb2",label:"IBM DB2",description:"Database service supporting IBM DB2 SQL connections.",group:"Database"},{name:"informix",label:"IBM Informix",description:"Database service supporting IBM Informix SQL connections.",group:"Database"},{name:"oracle",label:"Oracle",description:"Database service supporting SQL connections.",group:"Database"},{name:"salesforce_db",label:"Salesforce",description:"Database service with SOAP and/or OAuth authentication support for Salesforce connections.",group:"Database"},{name:"soap",label:"SOAP Service",description:"A service to handle SOAP Services",group:"Remote Service"},{name:"sqlanywhere",label:"SAP SQL Anywhere",description:"Database service supporting SAP SQL Anywhere connections.",group:"Database"},{name:"sqlsrv",label:"SQL Server",description:"Database service supporting SQL Server connections.",group:"Database"},{name:"memsql",label:"MemSQL",description:"Database service supporting MemSQL connections.",group:"Database"},{name:"apns",label:"Apple Push Notification",description:"Apple Push Notification Service Provider.",group:"Notification"},{name:"gcm",label:"GCM Push Notification",description:"GCM Push Notification Service Provider.",group:"Notification"},{name:"mqtt",label:"MQTT Client",description:"MQTT Client based on Mosquitto.",group:"IoT"},{name:"mysql",label:"MySQL",description:"Database service supporting MySLQ connections.",group:"Database"},{name:"mariadb",label:"MariaDB",description:"Database service supporting MariaDB connections.",group:"Database"},{name:"nodejs",label:"Node.js",description:"Service that allows client-callable scripts utilizing the system scripting.",group:"Script"},{name:"php",label:"PHP",description:"Service that allows client-callable scripts utilizing the system scripting.",group:"Script"},{name:"python",label:"Python",description:"Service that allows client-callable scripts utilizing the system scripting.",group:"Script"},{name:"python3",label:"Python3",description:"Service that allows client-callable scripts utilizing the system scripting.",group:"Script"},{name:"mongodb",label:"MongoDB",description:"Database service for MongoDB connections.",group:"Database"},{name:"gridfs",label:"GridFS",description:"GridFS File Storage services.",group:"File"}],goldServices=[{name:"logstash",label:"Logstash",description:"Logstash service.",group:"Log"},{name:"snowflake",label:"Snowflake",description:"Database service supporting Snowflake connections.",group:"Big Data"},{name:"apache_hive",label:"Apache Hive",description:"The Apache Hive data warehouse software facilitates reading, writing, and managing large datasets residing in distributed storage using SQL",group:"Big Data"},{name:"hadoop_hdfs",label:"Hadoop HDFS",description:"Hadoop Distributed File System",group:"File"}],add=[];return angular.forEach(silverServices,function(svc){0===types.filter(function(type){return svc.name===type.name}).length&&(svc.singleton=!1,svc.available=!1,svc.config_schema=null,svc.subscription_required="SILVER",add.push(svc))}),angular.forEach(goldServices,function(svc){0===types.filter(function(type){return svc.name===type.name}).length&&(svc.singleton=!1,svc.available=!1,svc.config_schema=null,svc.subscription_required="GOLD",add.push(svc))}),types=types.concat(add),angular.forEach(types,function(svc){svc.hasOwnProperty("available")||(svc.available=!0)}),types},scope.changeServiceType=function(type){scope.serviceInfo.type=type,scope.serviceConfig={},scope.selectedSchema=scope.serviceTypeToSchema(type),scope.selectedSchema&&scope.decorateSchema(),scope.resetServiceDef()};var watchServiceDetails=scope.$watch("serviceDetails",function(newValue,oldValue){if(!newValue)return!1;scope.serviceInfo=angular.copy(newValue.record)}),watchServiceTypes=scope.$watchCollection("apiData.service_type",function(newValue,oldValue){if(newValue){scope.editableServiceTypes=scope.addMissingPaidServices(newValue),scope.creatableServiceTypes=scope.editableServiceTypes.filter(function(el){return!el.singleton});var typeObj={},groups=scope.creatableServiceTypes.map(function(obj){return typeObj.hasOwnProperty(obj.group)||(typeObj[obj.group]=[]),typeObj[obj.group].push({name:obj.name,label:obj.label}),obj.group});groups=groups.filter(function(v,i){return groups.indexOf(v)===i});var sortingArray=["Database","Big Data","File","Email","Notification","Remote Service","Script","OAuth","LDAP"];groups=scope.sortArray(groups,sortingArray),scope.serviceTypesSingleColLimit=5;var newTypeObj={};angular.forEach(typeObj,function(types,group){var i,j,newTypes=angular.copy(types),limit=scope.serviceTypesSingleColLimit;if(types.length>limit){for(i=0,j=0;i=0&&(service=service.substr(0,index)),temp[service]||(temp[service]=[]),temp[service].push({label:event,name:event})}),angular.forEach(temp,function(items,service){items.unshift({label:"All "+service+" events",name:service+".*"}),serviceEvents.push({label:service,name:service,items:items})}),scope.eventList=serviceEvents)}),watchConfig=scope.$watchCollection("serviceConfig",function(newValue,oldValue){scope.disableServiceLinkRefresh=!scope.getRefreshEnable()}),watchSelections=scope.$watchCollection("selections",function(newValue,oldValue){scope.disableServiceLinkRefresh=!scope.getRefreshEnable(),newValue&&(scope.isServiceConfigEditable=null===newValue.service,null!==newValue.service&&(scope.serviceConfig.content="",scope.serviceConfigUpdateCounter++))}),watchUploadSpreadsheet=scope.$watch("uploadSpreadsheet",function(n,o){n&&(scope.spreadsheetUploadPath=n.name)});scope.$on("$destroy",function(e){watchServiceDetails(),watchSelectedSchema(),watchEventList(),watchConfig(),watchSelections(),watchUploadSpreadsheet()}),scope.prepareServiceConfig=function(){var config=scope.serviceConfig,type=scope.serviceInfo.type;return"nodejs"!==type&&"php"!==type&&"python"!==type&&"python3"!==type||(scope.selections.service?(config.content="",scope.serviceConfigUpdateCounter++):config.content=scope.serviceConfigEditorObj.editor.getValue(),config.storage_service_id=scope.selections.service?scope.selections.service.id:null,!scope.selections.service||"github"!==scope.selections.service.type&&"gitlab"!==scope.selections.service.type&&"bitbucket"!==scope.selections.service.type?config.scm_repository=null:config.scm_repository=config.scm_repository?config.scm_repository:null,!scope.selections.service||"github"!==scope.selections.service.type&&"gitlab"!==scope.selections.service.type&&"bitbucket"!==scope.selections.service.type?config.scm_reference=null:config.scm_reference=config.scm_reference?config.scm_reference:null,scope.selections.service?config.storage_path=config.storage_path?config.storage_path:null:config.storage_path=null),"excel"===type&&(config.storage_service_id=scope.selections.service?scope.selections.service.id:null,scope.selections.service?config.storage_container=config.storage_container?config.storage_container:null:config.storage_container=null),config},scope.isFieldsSeparated=function(schemaName){return"mysql"===schemaName||"sqlsrv"===schemaName||"oracle"===schemaName||"pgsql"===schemaName},scope.isBasic=function(fieldName){var basicFieldsNames=new Set(["host","port","database","username","password","schema"]);return("mysql"!==scope.selectedSchema.name||"schema"!==fieldName)&&basicFieldsNames.has(fieldName)},scope.isCaching=function(fieldName){return fieldName.includes("cache")||fieldName.includes("caching")},scope.showAdvancedSettings=!0,scope.showAdvancedFields=function(){var moreButton,lessButton,advancedFieldWrapper,advancedFieldContent,totalHeight;return totalHeight=0,moreButton=$(".advanced-fields .more-fields .button").parent(),lessButton=$(".advanced-fields .less-fields .button").parent(),advancedFieldWrapper=moreButton.parent(),advancedFieldContent=advancedFieldWrapper.find("#advanced-fields-wrapper:not('.more-fields')"),moreButton.fadeOut(),lessButton.fadeIn(),scope.showAdvancedSettings=!scope.showAdvancedSettings,totalHeight+=advancedFieldContent.outerHeight(),advancedFieldWrapper.css({height:advancedFieldWrapper.height(),"max-height":9999}).animate({height:totalHeight}),!1},scope.hideAdvancedFields=function(){var moreButton,lessButton,advancedFieldWrapper;return moreButton=$(".advanced-fields .more-fields .button").parent(),lessButton=$(".advanced-fields .less-fields .button").parent(),advancedFieldWrapper=moreButton.parent(),moreButton.fadeIn(),lessButton.fadeOut(),advancedFieldWrapper.animate({height:255}),!1}}}}]).directive("dfServiceDefinition",["MOD_SERVICES_ASSET_PATH","$timeout","$rootScope",function(MOD_SERVICES_ASSET_PATH,$timeout,$rootScope){return{restrict:"E",scope:!1,templateUrl:MOD_SERVICES_ASSET_PATH+"views/df-service-definition.html",link:function(scope,elem,attrs){scope.serviceDefEditorObj={editor:null},scope.allowedDefinitionFormats=["json","yml","yaml"],scope.serviceDefGitHubTarget="definition",scope.serviceDefUpdateCounter=0,scope.serviceDefinition={content:"",format:"json"},scope.isServiceDefEditable=!1,scope.resetServiceDef=function(){switch(scope.serviceDefinition={content:"",format:"json"},scope.serviceInfo.type){case"rws":case"nodejs":case"php":case"python":case"python3":scope.isServiceDefEditable=!0;break;default:scope.isServiceDefEditable=!1}},scope.prepareServiceDefinition=function(){var format,doc=null;switch(scope.serviceInfo.type){case"rws":case"nodejs":case"php":case"python":case"python3":var content=scope.serviceDefEditorObj.editor.getValue();""!==content&&((doc=scope.serviceDetails.record.service_doc_by_service_id||{}).content=content,format=scope.serviceDefinition.format,doc.format="yaml"===format?1:0)}return doc},scope.handleDefinitionFiles=function(files){if(files&&files[0]){var reader=new FileReader;reader.readAsText(files[0],"UTF-8"),reader.onload=function(evt){var format;scope.serviceDefinition.content=evt.target.result,scope.serviceDefUpdateCounter++,format=-1!==files[0].name.indexOf("yml")||-1!==files[0].name.indexOf("yaml")?"yaml":"json",scope.serviceDefinition.format=format,scope.$apply()},reader.onerror=function(evt){}}},scope.$watch("serviceDetails",function(newValue,oldValue){if(newValue){var content="",format="json",editable=!1;switch(newValue.record.type){case"rws":case"nodejs":case"php":case"python":case"python3":var doc=newValue.record.service_doc_by_service_id;doc&&(doc.hasOwnProperty("content")&&doc.content&&(content=doc.content),doc.hasOwnProperty("format")&&(format=1===doc.format?"yaml":"json")),editable=!0}scope.serviceDefinition={content:content,format:format},scope.isServiceDefEditable=editable}}),scope.githubModalShowDef=function(){$rootScope.$broadcast("githubShowModal",scope.serviceDefGitHubTarget)},$(window).on("resize",function(){var h=$(window).height();$('div[id^="ide_"]').css({height:h-400+"px"})})}}}]),angular.module("dfRoles",["ngRoute","dfUtility","dfApplication","dfTable"]).constant("MOD_ROLES_ROUTER_PATH","/roles").constant("MOD_ROLES_ASSET_PATH","admin_components/adf-roles/").config(["$routeProvider","MOD_ROLES_ROUTER_PATH","MOD_ROLES_ASSET_PATH",function($routeProvider,MOD_ROLES_ROUTER_PATH,MOD_ROLES_ASSET_PATH){$routeProvider.when(MOD_ROLES_ROUTER_PATH,{templateUrl:MOD_ROLES_ASSET_PATH+"views/main.html",controller:"RolesCtrl",resolve:{checkAdmin:["checkAdminService",function(checkAdminService){return checkAdminService.checkAdmin()}],checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("RolesCtrl",["$rootScope","$scope","$q","dfApplicationData","SystemConfigDataService","dfNotify","$location",function($rootScope,$scope,$q,dfApplicationData,SystemConfigDataService,dfNotify,$location){$scope.$parent.title="Roles",$scope.$parent.titleIcon="exclamation-circle",$scope.links=[{name:"manage-roles",label:"Manage",path:"manage-roles"},{name:"create-role",label:"Create",path:"create-role"}],$scope.emptySearchResult={title:"You have no Roles that match your search criteria!",text:""},$scope.adldap=0;var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("adldap")&&($scope.adldap=systemConfig.authentication.adldap.length),$scope.emptySectionOptions={title:"You have no Roles!",text:"Click the button below to get started creating your first role. You can always create new roles by clicking the tab located in the section menu to the left.",buttonText:"Create A Role!",viewLink:$scope.links[1],active:!1},$scope.$on("$destroy",function(e){$scope.$broadcast("toolbar:paginate:role:destroy")}),$scope.apiData=null,$scope.loadTabData=function(init){$scope.dataLoading=!0;var apis=["role","service_list","service_type_list"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData,init&&$scope.$broadcast("toolbar:paginate:role:load")},function(error){error&&error.error&&(401===error.error.code||403===error.error.code)&&$location.url("/home");var messageOptions={module:"Roles",provider:"dreamfactory",type:"error",message:"To use the Roles tab your role must allow GET access to service 'system' and system/role/*. To create, update, or delete roles you need POST, PUT, DELETE access to /system/role/*."};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(!0)}]).directive("dfRoleDetails",["MOD_ROLES_ASSET_PATH","dfApplicationData","dfNotify","dfObjectService","$q","SystemConfigDataService","dfSystemData","$timeout",function(MOD_ROLES_ASSET_PATH,dfApplicationData,dfNotify,dfObjectService,$q,SystemConfigDataService,dfSystemData,$timeout){return{restrict:"E",scope:{roleData:"=?",newRole:"=?",apiData:"=?"},templateUrl:MOD_ROLES_ASSET_PATH+"views/df-role-details.html",link:function(scope,elem,attrs){scope.adldap=0;var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("adldap")&&(scope.adldap=systemConfig.authentication.adldap.length);var Role=function(roleData){var newRole={name:null,description:null,is_active:!1,default_app_id:null,role_service_access_by_role_id:[],id:null,lookup_by_role_id:[]};return roleData=roleData||newRole,{__dfUI:{selected:!1},record:angular.copy(roleData),recordCopy:angular.copy(roleData)}};scope.basicInfoError=!1,scope.role=null,scope.isBasicTab=!0,scope.newRole&&(scope.role=new Role),scope.saveRole=function(){scope.newRole?scope._saveRole():scope._updateRole()},scope.deleteRole=function(){scope._deleteRole()},scope.cancelEditor=function(){scope._prepareRoleData(),(dfObjectService.compareObjectsAsJson(scope.role.record,scope.role.recordCopy)||dfNotify.confirmNoSave())&&scope.closeEditor()},scope._prepareRoleData=function(){scope.role.record.name?(scope.basicInfoError=!1,scope.adldap&&scope.role.record.dn&&(scope.role.record.role_adldap_by_role_id=scope.role.record.id?{role_id:scope.role.record.id,dn:scope.role.record.dn}:{dn:scope.role.record.dn},delete scope.role.record.dn),scope._prepareServiceAccessData(),scope._prepareRoleLookUpKeysData()):scope.basicInfoError=!0},scope.refreshRoleEditor=function($event){scope.isBasicTab="basic-tab"===$event.target.id},scope.refreshRoleAccessEditor=function(){$timeout(function(){angular.element("#access-tab").trigger("click")})},scope.closeEditor=function(){scope.roleData=null,scope.role=new Role,$timeout(function(){angular.element("#basic-tab").trigger("click")}),scope.lookupKeysError=!1,scope.basicInfoError=!1,scope.$emit("sidebar-nav:view:reset")},scope._prepareServiceAccessData=function(){var preppedArr=[];angular.forEach(scope.roleServiceAccesses,function(obj){var _obj=angular.copy(obj.record);delete _obj.service,preppedArr.push(_obj)}),scope.role.record.role_service_access_by_role_id=preppedArr},scope._saveRole=function(){scope._prepareRoleData();var requestDataObj={params:{fields:"*",related:"role_service_access_by_role_id,lookup_by_role_id"},data:scope.role.record};dfApplicationData.saveApiData("role",requestDataObj).$promise.then(function(result){var messageOptions={module:"Roles",type:"success",provider:"dreamfactory",message:"Role saved successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var msg=reject.data.message,messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._updateRole=function(){scope._prepareRoleData();var requestDataObj={params:{fields:"*",related:"role_service_access_by_role_id,lookup_by_role_id"},data:scope.role.record};dfApplicationData.updateApiData("role",requestDataObj).$promise.then(function(result){scope.adldap?dfSystemData.resource({params:{fields:"*",related:"role_adldap_by_role_id"}}).get({api:"role",id:result.id,related:"role_adldap_by_role_id"}).$promise.then(function(adResult){adResult.role_adldap_by_role_id&&(adResult.role_adldap_by_role_id.length>0||adResult.role_adldap_by_role_id.hasOwnProperty("dn"))&&(adResult.role_adldap_by_role_id.length>0?result.dn=adResult.role_adldap_by_role_id[0].dn:result.dn=adResult.role_adldap_by_role_id.dn),scope.role=new Role(result)},function(reject){scope.role=new Role(result)}):scope.role=new Role(result);var messageOptions={module:"Roles",type:"success",provider:"dreamfactory",message:"Role updated successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var msg=reject.data.message;scope.role.record.role_adldap_by_role_id&&(scope.role.record.role_adldap_by_role_id.length>0||scope.role.record.role_adldap_by_role_id.hasOwnProperty("dn"))&&(scope.role.record.role_adldap_by_role_id.length>0?scope.role.record.dn=scope.role.record.role_adldap_by_role_id[0].dn:scope.role.record.dn=scope.role.record.role_adldap_by_role_id.dn);var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._deleteRole=function(){var requestDataObj={params:{},data:scope.role.record};dfApplicationData.deleteApiData("role",requestDataObj).$promise.then(function(result){var messageOptions={module:"Roles",type:"success",provider:"dreamfactory",message:"Role successfully deleted."};dfNotify.success(messageOptions),scope.role=null},function(reject){var msg=reject.data.message,messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})};var watchRoleData=scope.$watch("roleData",function(newValue,oldValue){newValue&&!scope.newRole&&(scope.role=new Role(newValue))}),watchServiceData=scope.$watchCollection("apiData.service_list",function(newValue,oldValue){newValue&&(scope.services=angular.copy(newValue),scope.services.sort(function(a,b){return a.nameb.name?1:0}),"All"!==scope.services[0].name&&scope.services.unshift({id:null,name:"All"}),angular.forEach(scope.services,function(svc){svc.components||(svc.components=["","*"])}))});scope.$on("$destroy",function(e){watchRoleData(),watchServiceData()}),scope.dfSimpleHelp={serviceAccess:{title:"Role Service Access Information",text:"Access rules for DreamFactory services. Use caution when allowing system access."}},scope.dfLargeHelp={basic:{title:"Roles Overview",text:"Roles provide a way to grant or deny API access to specific services or apps."},access:{title:"Access Overview",text:"This section allows you set up rules for a role restricting what services and components users assigned to the role will have access to. Advanced Filters are for implementing additional server side filter logic on database transactions."},lookupkeys:{title:"Lookup Keys Overview",text:'The DreamFactory administrator can create any number of "key value" pairs attached to a role. The key values are automatically substituted on the server. For example, key names can be used in the username and password fields required to hook up a SQL or NoSQL database. They can also be used in Email Templates or as parameters for external REST services. Any Lookup Key can be marked as private, and in this case the key value is securely encrypted on the server and is no longer accessible through the platform interface. Lookup keys for service configuration and credentials must be made private.'}}}}}]).directive("assignServiceAccess",["MOD_ROLES_ASSET_PATH","dfNotify",function(MOD_ROLES_ASSET_PATH,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_ROLES_ASSET_PATH+"views/df-assign-service-access.html",link:function(scope,elem,attrs){var ServiceAccess=function(){return{__dfUI:{allowFilters:!1,showFilters:!1,hasError:!1},record:{verb_mask:0,requestor_mask:1,component:"*",service:scope.services[0]||null,service_id:scope.services[0].id||null,filters:[],filter_op:"AND"}}};scope.roleServiceAccesses=[],scope.addServiceAccess=function(){scope._addServiceAccess()},scope.removeServiceAccess=function(serviceAccessObjIndex){scope._removeServiceAccess(serviceAccessObjIndex)},scope._addServiceAccess=function(){scope.roleServiceAccesses.push(new ServiceAccess)},scope._removeServiceAccess=function(serviceAccessObjIndex){scope.roleServiceAccesses[serviceAccessObjIndex].record.id?scope.roleServiceAccesses[serviceAccessObjIndex].record.role_id=null:scope.roleServiceAccesses.splice(serviceAccessObjIndex,1)},scope._getService=function(serviceId){for(var i=0;i","<",">=","<=","in","not in","starts with","ends with","contains","is null","is not null"],scope.toggleServiceAccessFilters=function(){scope._toggleServiceAccessFilters()},scope.addServiceAccessFilter=function(){scope._addServiceAccessFilter()},scope.removeServiceAccessFilter=function(serviceAccessFilterIndex){scope._removeServiceAccessFilter(serviceAccessFilterIndex)},scope.toggleServiceFilterOp=function(){scope._toggleServiceFilterOp()},scope.allowFilters=function(){var type=scope.serviceAccess.record.service.type,group=serviceTypeToGroup(type,scope.apiData.service_type_list);scope.serviceAccess.__dfUI.allowFilters="Database"===group&&"couchdb"!==type},scope._toggleServiceAccessFilters=function(){scope.serviceAccess.__dfUI.show_filters=!scope.serviceAccess.__dfUI.show_filters},scope._addServiceAccessFilter=function(){scope.serviceAccess.record.filters.push(new ServiceAccessFilter)},scope._removeServiceAccessFilter=function(serviceAccessFilterIndex){scope.serviceAccess.record.filters.splice(serviceAccessFilterIndex,1)},scope._toggleServiceFilterOp=function(){scope.serviceAccess.record.filter_op="AND"===scope.serviceAccess.record.filter_op?"OR":"AND"},scope._getComponents=function(){var name=scope.serviceAccess.record.service.name;return $http.get(INSTANCE_URL.url+"/"+name+"/?as_access_list=true")};var watchServiceAccessRecordService=scope.$watch("serviceAccess.record.service",function(newValue,oldValue){if(!newValue)return!1;scope.serviceAccess.__dfUI.hasError=!1,scope.allowFilters(),scope.serviceAccess.record.service_id=newValue.id;var name=scope.serviceAccess.record.service.name,group=serviceTypeToGroup(scope.serviceAccess.record.service.type,scope.apiData.service_type_list);if("All"!==name&&null!==group&&"Email"!==group){var components=["","*"];scope._getComponents().then(function(result){components=result.data.resource},function(reject){scope.serviceAccess.__dfUI.hasError=!0,scope.serviceAccess.record.component=null;var messageOptions={module:"Roles",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.serviceAccess.record.service.components=components})}});scope.$on("$destroy",function(e){watchServiceAccessRecordService()})}}}]).directive("dfManageRoles",["$rootScope","MOD_ROLES_ASSET_PATH","dfApplicationData","dfNotify","dfSystemData","SystemConfigDataService","dfSelectedService",function($rootScope,MOD_ROLES_ASSET_PATH,dfApplicationData,dfNotify,dfSystemData,SystemConfigDataService,dfSelectedService){return{restrict:"E",scope:!1,templateUrl:MOD_ROLES_ASSET_PATH+"views/df-manage-roles.html",link:function(scope,elem,attrs){var ManagedRole=function(roleData){return{__dfUI:{selected:!1},record:roleData}};scope.adldap=0;var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("adldap")&&(scope.adldap=systemConfig.authentication.adldap.length),scope.roles=null,scope.currentEditRole=null,scope.fields=[{name:"id",label:"label",active:!0},{name:"name",label:"Name",active:!0},{name:"description",label:"Description",active:!0},{name:"is_active",label:"Active",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedRoles=[],scope.editRole=function(role){scope.adldap?dfSystemData.resource({params:{fields:"*",related:"role_adldap_by_role_id"}}).get({api:"role",id:role.id,related:"role_adldap_by_role_id"}).$promise.then(function(result){result.role_adldap_by_role_id&&(result.role_adldap_by_role_id.length>0||result.role_adldap_by_role_id.hasOwnProperty("dn"))&&(result.role_adldap_by_role_id.length>0?role.dn=result.role_adldap_by_role_id[0].dn:role.dn=result.role_adldap_by_role_id.dn),scope._editRole(role)},function(reject){scope._editRole(role)}):scope._editRole(role)},scope.deleteRole=function(role){dfNotify.confirm("Delete "+role.record.name+"?")&&scope._deleteRole(role)},scope.deleteSelectedRoles=function(){dfNotify.confirm("Delete selected roles?")&&scope._deleteSelectedRoles()},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setSelected=function(role){scope._setSelected(role)},scope._editRole=function(role){scope.currentEditRole=role},scope._deleteRole=function(role){var requestDataObj={params:{},data:role.record};dfApplicationData.deleteApiData("role",requestDataObj).$promise.then(function(result){var messageOptions={module:"Roles",type:"success",provider:"dreamfactory",message:"Role successfully deleted."};dfNotify.success(messageOptions),role.__dfUI.selected&&scope.setSelected(role),scope.$broadcast("toolbar:paginate:role:delete")},function(reject){var msg=reject.data.message,messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope._setSelected=function(role){for(var i=0;i"}}]).directive("dfAssignLookUpKeys",["MOD_ROLES_ASSET_PATH",function(MOD_ROLES_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_ROLES_ASSET_PATH+"views/df-assign-lookup-keys.html",link:function(scope,elem,attrs){var LookUpKey=function(lookupKeyData){var _new={name:"",value:"",private:!1,allow_user_update:!1};return{__dfUI:{unique:!0},record:angular.copy(lookupKeyData||_new),recordCopy:angular.copy(lookupKeyData||_new)}};scope.roleLookUpKeys=[],scope.sameKeys=[],scope.lookupKeysError=!1,scope.addLookUpKey=function(){scope._addLookUpKey()},scope.deleteLookUpKey=function(keyObjIndex){scope._deleteLookUpKey(keyObjIndex)},scope._prepareRoleLookUpKeysData=function(){var tempArr=[];angular.forEach(scope.roleLookUpKeys,function(lk){tempArr.push(lk.record)}),scope.role.record.lookup_by_role_id=tempArr},scope._isUniqueKey=function(){scope.sameKeys=[],angular.forEach(scope.roleLookUpKeys,function(value,index){angular.forEach(scope.roleLookUpKeys,function(_value,_index){index!==_index&&value.record.name===_value.record.name&&scope.sameKeys.push(value)})})},scope._addLookUpKey=function(){scope.roleLookUpKeys.push(new LookUpKey)},scope._deleteLookUpKey=function(keyObjIndex){void 0!==scope.roleLookUpKeys[keyObjIndex].record.role_id?scope.roleLookUpKeys[keyObjIndex].record.role_id=null:scope.roleLookUpKeys.splice(keyObjIndex,1)};var watchRole=scope.$watch("role",function(newValue,oldValue){if(!newValue)return!1;scope.roleLookUpKeys=null,scope.newRole?scope.roleLookUpKeys=[]:(scope.roleLookUpKeys=[],angular.forEach(newValue.record.lookup_by_role_id,function(lkObj){scope.roleLookUpKeys.push(new LookUpKey(lkObj))}))}),watchSameKeys=scope.$watch("sameKeys",function(newValue,oldValue){0!==newValue.length||0!==scope.roleLookUpKeys.length?0===newValue.length&&scope.roleLookUpKeys.length>0?angular.forEach(scope.roleLookUpKeys,function(lk){lk.__dfUI.unique=!0,scope.lookupKeysError=!1}):(angular.forEach(scope.roleLookUpKeys,function(lk){angular.forEach(newValue,function(_lk){lk.record.name===_lk.record.name?lk.__dfUI.unique=!1:lk.__dfUI.unique=!0})}),scope.lookupKeysError=!0):scope.lookupKeysError=!1}),watchLookupKeys=scope.$watchCollection("roleLookUpKeys",function(newValue,oldValue){newValue&&scope._isUniqueKey()});scope.$on("$destroy",function(e){watchRole(),watchSameKeys(),watchLookupKeys()})}}}]),angular.module("dfSchema",["ngRoute","dfUtility"]).constant("MOD_SCHEMA_ROUTER_PATH","/schema").constant("MOD_SCHEMA_ASSET_PATH","admin_components/adf-schema/").config(["$routeProvider","MOD_SCHEMA_ROUTER_PATH","MOD_SCHEMA_ASSET_PATH",function($routeProvider,MOD_SCHEMA_ROUTER_PATH,MOD_SCHEMA_ASSET_PATH){$routeProvider.when(MOD_SCHEMA_ROUTER_PATH,{templateUrl:MOD_SCHEMA_ASSET_PATH+"views/main.html",controller:"SchemaCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).factory("TableListService",["INSTANCE_URL","$q","$timeout","dfApplicationData","StateService","dfNotify",function(INSTANCE_URL,$q,$timeout,dfApplicationData,StateService,dfNotify){return{getTableList:function(forceRefresh){var deferred=$q.defer(),currentService=StateService.get("dfservice");if(currentService)return dfApplicationData.getServiceComponents(currentService.name,INSTANCE_URL.url+"/"+currentService.name+"/_schema",{params:{refresh:!0,fields:"name,label"}},forceRefresh).then(function(result){currentService.updateComponents(result),StateService.set("dfservice",currentService);var messageOptions={module:"Schema",type:"success",provider:"dreamfactory",message:currentService.label+" is refreshed."};forceRefresh&&dfNotify.success(messageOptions),deferred.resolve(currentService)},function(reject){var messageOptions={module:"Schema",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions),deferred.reject()}),deferred.promise}}}]).factory("Table",["$q","$http","INSTANCE_URL","dfNotify",function($q,$http,INSTANCE_URL,dfNotify){function Table(tableData){tableData&&this.setData(tableData)}return Table.prototype={setData:function(tableData){angular.extend(this,tableData)},delete:function(params){return $http.delete(INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table)},update:function(params){return $http({method:"PATCH",url:INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table,data:this})},_saveField:function(params,fieldData){var data={resource:[fieldData.record]},verb=fieldData.__dfUI.newField?"POST":"PATCH";return $http({method:verb,url:INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table+"/_field",data:data})},_updateRelations:function(params){}},Table}]).factory("tableManager",["INSTANCE_URL","$http","$q","Table","StateService","dfNotify","TableObj",function(INSTANCE_URL,$http,$q,Table,StateService,dfNotify,TableObj){return{_pool:{},_retrieveInstance:function(tableName,tableData){if(!tableName)return!1;var instance=this._pool[tableName];return instance?instance.setData(tableData):(instance=new Table(tableData),this._pool[tableName]=instance),instance},_search:function(tableName){return this._pool[tableName]},_load:function(params,deferred){var scope=this,url=INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table+"?refresh=true";$http.get(url).then(function(response){var tableData=response.data,table=scope._retrieveInstance(tableData.name,tableData);deferred.resolve(table)},function(reject){deferred.reject()})},_delete:function(params){return $http.delete(INSTANCE_URL.url+"/"+params.service.name+"/_schema/"+params.table)},_deleteField:function(params){return $http.delete(INSTANCE_URL.url+"/"+params.service.name+"/_schema/"+params.table+"/_field/"+params.field)},_clearPool:function(){this._pool={}},getTable:function(params){var deferred=$q.defer(),table=this._search(params.table);return table?deferred.resolve(table):this._load(params,deferred),deferred.promise},loadAllTables:function(params){var deferred=$q.defer(),scope=this,url=INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table;return $http.get(url).then(function(response){var tables,tablesArray=response.data;Array.isArray(tablesArray)?tablesArray.forEach(function(tableData){var table=scope._retrieveInstance(tableData.name,tableData);tables.push(table)}):tables=tablesArray,deferred.resolve(tables)},function(reject){deferred.reject()}),deferred.promise},setTable:function(tableData,saveToServer){var tableName="";tableName=tableData.hasOwnProperty("record")?tableData.__dfUI.newTable?"__new":tableData.record.name:tableData.name;var scope=this,table=this._search(tableName);if(!table&&saveToServer){var param={resource:[tableData]};return $http.post(INSTANCE_URL.url+"/"+StateService.get("dfservice").name+"/_schema?fields=*",param)}if(table){if(table.setData(tableData),saveToServer)return table.update({service:StateService.get("dfservice").name,table:tableName})}else table=scope._retrieveInstance(tableName,tableData.record);return table},setDat:function(tableData){scope._retrieveInstance(tableData)},setField:function(tableName,fieldData,saveToServer){var table=this._search(tableName);if(void 0!==table){var index=table.field.findIndex(function(obj){return obj.name==fieldData.record.name});if(index<0?table.field.push(fieldData.record):table.field[index]=fieldData.record,table.field[index]=fieldData.record,table.setData(table),saveToServer){var params={service:StateService.get("dfservice").name,table:tableName};return table._saveField(params,fieldData)}}},getField:function(fieldName,tableName){var table=this._search(tableName);if(table.hasOwnProperty("field")){var index=table.field.findIndex(function(obj){return obj.name==fieldName});return index>-1?table.field[index]:void 0}return null},deleteField:function(params){return this._deleteField(params)},deleteTable:function(params){return this._delete(params)},_saveRelation:function(params,relationData){var data={resource:[relationData.record]};return relationData.__dfUI.newRelation?$http.post(INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table+"/_related",data):$http({method:"PATCH",url:INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table+"/_related",data:data})},saveRelation:function(params,relationData){return this._saveRelation(params,relationData)},_deleteRelation:function(params){return $http.delete(INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table+"/_related/"+params.relation)},deleteRelation:function(params){return this._deleteRelation(params)},updateRelations:function(params){var table=this._search(params.table),url=INSTANCE_URL.url+"/"+params.service.name+"/_schema/"+params.table+"/_related";return $http.get(url).then(function(response){var relationData=response.data;table.related=relationData.resource,table.setData(table)},function(reject){})},clearPool:function(){this._clearPool()}}}]).service("StateService",function(){var selectedService={};return{get:function(state){if(selectedService.hasOwnProperty(state))return selectedService[state]},set:function(state,value){selectedService[state]=value}}}).service("ServiceModel",function(){function getSchemaComponents(array){var service=[];return angular.forEach(array,function(component){var componentObj={__dfUI:{newTable:!1},name:component.name,label:component.label};service.push(componentObj)}),service}return function(schemaData){return{__dfUI:{unfolded:!1},name:schemaData.name,label:schemaData.label,components:getSchemaComponents(schemaData.components),updateComponents:function(array){this.components=getSchemaComponents(array)}}}}).service("TableObj",function(){return function(tableObj,currentService){var _new={alias:null,description:null,name:null,label:null,plural:null,primary_key:null,name_field:null,is_view:!1,related:[],field:[]},newTable=!tableObj;return tableObj=tableObj||_new,{__dfUI:{newTable:newTable},record:tableObj,recordCopy:angular.copy(tableObj)}}}).service("FieldObj",function(){return function(fieldData1){var _new={allow_null:!1,auto_increment:!1,db_function:null,db_type:null,default:null,fixed_length:!1,is_aggregate:!1,is_foreign_key:!1,is_primary_key:!1,is_unique:!1,is_virtual:!1,label:null,length:null,name:null,picklist:null,precision:null,ref_field:"",ref_table:"",required:!1,scale:0,supports_multibyte:!1,type:null,validation:null,value:[]},_newField=!fieldData1;return fieldData1=fieldData1||_new,{__dfUI:{newField:_newField},record:fieldData1,recordCopy:angular.copy(fieldData1)}}}).service("RelationObj",function(){return function(RelationObj){var _new={alias:null,always_fetch:!1,description:null,field:null,is_virtual:!0,junction_field:null,junction_ref_field:null,junction_service_id:null,junction_table:null,label:null,name:null,ref_field:null,ref_service_id:null,ref_table:null,type:null},_newRelation=!RelationObj;return RelationObj=RelationObj||_new,{__dfUI:{newRelation:_newRelation},record:RelationObj,recordCopy:angular.copy(RelationObj)}}}).service("TableDataModel",function(){this.model=null,this.setTableModel=function(data){this.model=data},this.setTableModel=function(data){this.model=data},this.updateTableModel=function(data){this.model=data},this.deleteTableModel=function(){this.model=null}}).service("NavigationService",function(){return this.currentStep=null,{getStep:function(){return this.currentStep},setStep:function(step){this.currentStep=step},nextStep:function(){},previousStep:function(){}}}).service("FieldOptions",function(){this.typeOptions=[{name:"I will manually enter a type",value:""},{name:"id",value:"id"},{name:"string",value:"string"},{name:"integer",value:"integer"},{name:"text",value:"text"},{name:"boolean",value:"boolean"},{name:"binary",value:"binary"},{name:"float",value:"float"},{name:"double",value:"double"},{name:"decimal",value:"decimal"},{name:"datetime",value:"datetime"},{name:"date",value:"date"},{name:"time",value:"time"},{name:"reference",value:"reference"},{name:"user_id",value:"user_id"},{name:"user_id_on_create",value:"user_id_on_create"},{name:"user_id_on_update",value:"user_id_on_update"},{name:"timestamp",value:"timestamp"},{name:"timestamp_on_create",value:"timestamp_on_create"},{name:"timestamp_on_update",value:"timestamp_on_update"}],this.returnTypeOptions=[{name:"string",value:"string"},{name:"integer",value:"integer"},{name:"boolean",value:"boolean"},{name:"binary",value:"binary"},{name:"float",value:"float"},{name:"double",value:"double"},{name:"decimal",value:"decimal"}],this.helpText={name:{title:"Name",text:"The field name used by the API."},alias:{title:"Alias",text:"If set, the alias is used in table access instead of the name."},label:{title:"Label",text:"A displayable name used by clients."},type:{title:"Type",text:"This is a simplified DreamFactory type."},database_type:{title:"Database Type",text:"If necessary, enter a type acceptable to the underlying database."},db_function:{title:"DB Function",text:'Enter valid syntax for a database function supported by this database vendor, like upper(fieldname), max(fieldname) or concat(field1, \'.\', field2), to apply to this field for various operations. See here for more info.'},validation:{title:"Validation",text:'A JSON object detailing required validations, if any. See here for more info.'},aggregate_db_unction:{title:"Aggregate DB Function",text:'Supported DB functions to apply to this field. See here for more info.'}}}).service("SchemaJSONData",function(){this.schemaJSON={resource:[{name:"todo",label:"Todo",plural:"Todos",alias:null,field:[{name:"id",label:"Id",type:"id"},{name:"name",label:"Name",type:"string",size:80,allow_null:!1},{name:"complete",label:"Complete",type:"boolean",default:!1}]}]}}).controller("SchemaCtrl",["$scope","dfApplicationData","ServiceModel","dfNotify","$location",function($scope,dfApplicationData,ServiceModel,dfNotify,$location){$scope.$parent.title="Schema",$scope.$parent.titleIcon="table",$scope.links=[{name:"manage-schema",label:"Manage",path:"manage-schema"}],$scope.currentService=null,$scope.currentTable=null,$scope.lastTable="";var watchServices=$scope.$watchCollection("apiData.service_list",function(newValue,oldValue){if(newValue){var tempObj={};angular.forEach(newValue,function(service){tempObj[service.name]=new ServiceModel(service)}),$scope.schemaManagerData=tempObj}});$scope.$on("$destroy",function(e){watchServices()}),$scope.$on("refresh:table",function(e,resource){}),$scope.$on("update:components",function(e,resource){$scope.currentService.components.push({__dfUI:{newTable:!1},name:resource.name,label:resource.label}),$scope.currentTable=$scope.currentService.components[$scope.currentService.components.length-1].name}),$scope.dfLargeHelp={manageSchema:{title:"Schema Manager Overview",text:"Choose a database service from the list to view or edit the schema. You can create a new database service in the Services section of this Admin Console."}},$scope.apiData=null,$scope.loadTabData=function(){$scope.dataLoading=!0;var apis=["service_list"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index],"service_list"===value&&(newApiData[value]=newApiData[value].filter(function(obj){return["mysql","pgsql","sqlite","sqlsrv","memsql","sqlanywhere","oracle","ibmdb2","informix","firebird","aws_redshift_db","mongodb","apache_hive","snowflake"].indexOf(obj.type)>=0}))}),$scope.apiData=newApiData},function(error){var messageOptions={module:"Schema",provider:"dreamfactory",type:"error",message:"There was an error loading the Schema tab. Please try refreshing your browser and logging in again."};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData()}]).directive("dfSchemaLoading",[function(){return{restrict:"E",template:"
"}}]).directive("dfTableTemplate",["MOD_SCHEMA_ASSET_PATH","$q","$timeout","NavigationService","Table","TableDataModel","FieldObj","RelationObj","StateService","tableManager",function(MOD_SCHEMA_ASSET_PATH,$q,$timeout,NavigationService,Table,TableDataModel,FieldObj,RelationObj,StateService,tableManager){return{restrict:"E",scope:{tableData:"=",apiData:"="},templateUrl:MOD_SCHEMA_ASSET_PATH+"views/df-table-template.html",transclude:!0,controllerAs:"ctrl",controller:["$scope",function($scope){$scope.selView="empty",this.selectedView="empty";var ctrl=this;ctrl.childCtrl=[],ctrl.register=function(child,childCtrl){ctrl.childCtrl[child]=childCtrl},ctrl.$onDestroy=function(){ctrl.childCtrl.length=0}}],link:function(scope,elem,attrs,ctrl){scope.$on("reload",function(event,args){scope.selView="empty"}),scope.$on("table",function(event,args){switch(args.notify){case"delete":ctrl.childCtrl.table_edit.deleteTable(args).then(function(){scope.selView="empty"},function(){});break;case"create:form":scope.selView="create",ctrl.childCtrl.table_create.getEmpty(args);break;case"create:upload":scope.selView="upload",ctrl.childCtrl.table_upload.setDefault();break;case"edit":null!==args.table?(scope.selView="edit",ctrl.childCtrl.table_edit.getTable(args)):scope.selView="empty";break;case"close":scope.selView="empty"}}),scope.$on("field",function(event,args){switch(args.notify){case"new:create":args.value.newTable=!0,scope.newTable=!0,scope.selView="field",scope.fieldEditData=new FieldObj,scope.tableStatus=args.newTable;break;case"edit:create":args.value.newTable=!1,scope.newTable=!1,scope.selView="field",scope.fieldEditData=new FieldObj,scope.tableStatus=args.newTable;break;case"new:close":scope.selView="create";break;case"edit:close":scope.selView="edit",ctrl.childCtrl.table_create.getEmpty(),ctrl.childCtrl.table_edit.syncRecord();break;case"edit":scope.selView="field",scope.fieldEditData=args.value.field,scope.tableStatus=args.value.newTable}}),scope.$on("relation",function(event,args){switch(args.notify){case"create":scope.selView="relation",scope.relationEditData=new RelationObj;break;case"edit":NavigationService.setStep("relation"),scope.selView="relation",scope.relationEditData=args.value.relation;break;case"close":scope.selView="edit",ctrl.childCtrl.table_edit.updateRelations(args.selected)}}),scope.$on("table:navigation:close",function(event,args){scope.selView="empty"})}}}]).directive("dfTableCreateView",["MOD_SCHEMA_ASSET_PATH","NavigationService","Table","TableDataModel","$http","dfNotify","dfObjectService","StateService","dfApplicationData","TableObj","tableManager",function(MOD_SCHEMA_ASSET_PATH,NavigationService,Table,TableDataModel,$http,dfNotify,dfObjectService,StateService,dfApplicationData,TableObj,tableManager){return{restrict:"E",scope:{tableData:"=",selectedView:"="},require:["dfTableCreateView","^^dfTableTemplate"],templateUrl:MOD_SCHEMA_ASSET_PATH+"views/df-table-create-view.html",controller:function($scope){$scope.viewMode="table",$scope.table={};var ctrl=this;ctrl.getEmpty=function(){$scope.table=new TableObj,tableManager.setTable($scope.table,!1)},ctrl.getCached=function(service){var requestDataObj={service:service.service,table:service.table};tableManager.getTable(requestDataObj).then(function(tables){$scope.table={__dfUI:{newTable:!0},record:tables,recordCopy:angular.copy(tables),currentService:service.service}})}},link:function(scope,elem,attrs,ctrls){var childCtrl=ctrls[0];ctrls[1].register("table_create",childCtrl),scope.saveTable=function(){if(-1===StateService.get("dfservice").components.findIndex(function(element,index,array){return element.name===scope.table.record.name}))scope._saveTable();else{var messageOptions={module:"Validation Error",type:"error",provider:"dreamfactory",message:"The name already exists"};dfNotify.error(messageOptions)}},scope.cancelTable=function(){scope._cancelTable()},scope._saveTable=function(){tableManager.clearPool(),scope.currentService=StateService.get("dfservice"),scope.table.currentService={name:scope.currentService.name},tableManager.setTable(scope.table.record,!0).then(function(result){var messageOptions={module:"Schema",type:"success",provider:"dreamfactory",message:"Table saved successfully."},newTable=result.data.resource[0],component={__dfUI:{newTable:!1},name:scope.table.record.name,label:scope.table.record.label||result.data.resource[0].label};scope.currentService.components.push(component),dfApplicationData.updateServiceComponentsLocal(scope.currentService),scope.table.__dfUI.newTable=!1,scope.table.recordCopy=angular.copy(scope.table.record),StateService.set("dftable",scope.table.record.name),dfNotify.success(messageOptions);var naviObj={service:scope.currentService.name,table:scope.table.record.name,type:"form",data:newTable};scope.$emit("table:navigation:select",naviObj)},function(errMsg){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:errMsg.error.message};dfNotify.error(messageOptions)})},scope._cancelTable=function(){if(!dfObjectService.compareObjectsAsJson(scope.table.record,scope.table.recordCopy)&&!dfNotify.confirmNoSave())return!1;scope.table=null,scope.$emit("table",{notify:"close"})}}}}]).directive("dfTableEditView",["MOD_SCHEMA_ASSET_PATH","$q","NavigationService","Table","TableDataModel","$http","dfNotify","tableManager","TableObj","dfObjectService","dfApplicationData","StateService",function(MOD_SCHEMA_ASSET_PATH,$q,NavigationService,Table,TableDataModel,$http,dfNotify,tableManager,TableObj,dfObjectService,dfApplicationData,StateService){return{restrict:"E",scope:{tableData:"=",selectedView:"="},require:["dfTableEditView","^dfTableTemplate"],templateUrl:MOD_SCHEMA_ASSET_PATH+"views/df-table-edit-view.html",controller:function($scope){var ctrl=this;$scope.table=null,$scope.viewMode="table",$scope.schemaJsonEditorObj={editor:null},$scope.reset=function(){$scope.table=null,$scope.viewMode="table",$scope.table=null,$scope.currentTable=null},$scope.thisService=null,ctrl.syncRecord=function(){$scope.table.recordCopy=angular.copy($scope.table.record)},ctrl.getTable=function(service){var requestDataObj={service:service.service,table:service.table};tableManager.getTable(requestDataObj).then(function(tables){$scope.table={__dfUI:{newTable:!1},record:tables,recordCopy:angular.copy(tables),currentService:service.service}})},ctrl.updateRelations=function(obj){tableManager.updateRelations(obj).then(function(tables){})},ctrl.deleteTable=function(obj){if(dfNotify.confirm("Are you sure you want to drop table "+obj.table+"?"))return $scope._deleteTable(obj)},$scope._deleteTable=function(obj){var deferred=$q.defer(),requestDataObj={table:obj.table,service:obj.service};return tableManager.deleteTable(requestDataObj).then(function(result){for(var messageOptions={module:"Schema",type:"success",provider:"dreamfactory",message:"Table deleted successfully."},currentService=requestDataObj.service,i=0;ihere for more info.'}}}}}]).directive("dfSchemaNavigator",["MOD_SCHEMA_ASSET_PATH","dfApplicationData","StateService","TableListService","NavigationService","tableManager","dfNotify",function(MOD_SCHEMA_ASSET_PATH,dfApplicationData,StateService,TableListService,NavigationService,tableManager,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_SCHEMA_ASSET_PATH+"views/df-schema-navigator.html",link:function(scope,elem,attrs){scope.serviceSelect=function(){tableManager.clearPool(),scope.$broadcast("table",{notify:"close"}),scope.currentTable=null,StateService.set("dfservice",scope.currentService),TableListService.getTableList()},scope.navigationSelect=function(selected){var naviObj={type:selected,notify:"create:"+selected,value:{service:scope.currentService.name}};scope.currentTable=null,scope.$broadcast("table",naviObj)},scope.deleteTable=function(){var params={table:scope.currentTable,service:scope.currentService,notify:"delete"};scope.$broadcast("table",params)},scope.tableSelect=function(obj){var params={table:scope.currentTable,service:scope.currentService.name,notify:"edit"};StateService.set("dftable",scope.currentTable),scope.$broadcast("table",params)},scope.reload=function(){tableManager.clearPool(),TableListService.getTableList(!0).then(function(result){-1===result.components.findIndex(function(element,index,array){return element.name===scope.currentTable})?(scope.currentTable=null,StateService.set("dftable",scope.currentTable),scope.$broadcast("table",{notify:"close"})):scope.tableSelect()})},scope.$on("table:navigation:select",function(event,args){if(args.hasOwnProperty("service")&&args.hasOwnProperty("table")&&args.hasOwnProperty("type")){scope.currentTable=args.table;var params={table:args.table,service:args.service,notify:"edit"};scope.$broadcast("table",params)}}),scope.$on("table:navigation:close",function(event,args){scope.currentService=args.service,scope.currentTable=null})}}}]).directive("dfSchemaEditor",["MOD_SCHEMA_ASSET_PATH",function(MOD_SCHEMA_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_SCHEMA_ASSET_PATH+"views/df-schema-editor.html",link:function(scope,elem,attrs){}}}]).directive("dfSchemaResizable",[function(){return{restrict:"A",scope:{},link:function(scope,elem,attrs){$(function(){$("#schema-navigator-resizable").resizable({alsoResize:"#schema-navigator-resizable-also"}),$("#schema-navigator-resizable-also").resizable()})}}}]).directive("dfUploadSchema",["INSTANCE_URL","MOD_SCHEMA_ASSET_PATH","$http","dfNotify","$timeout","SchemaJSONData","StateService","dfApplicationData",function(INSTANCE_URL,MOD_SCHEMA_ASSET_PATH,$http,dfNotify,$timeout,SchemaJSONData,StateService,dfApplicationData){return{restrict:"E",scope:!1,require:["dfUploadSchema","^dfTableTemplate"],templateUrl:MOD_SCHEMA_ASSET_PATH+"views/df-upload-schema.html",controller:function($scope){this.setDefault=function(){$scope.uploadSchemaData=SchemaJSONData.schemaJSON}},link:function(scope,elem,attrs,ctrls){var childCtrl=ctrls[0];ctrls[1].register("table_upload",childCtrl),scope.uploadObj={record:null,recordCopy:null},scope.schemaUploadEditorObj={editor:null},scope.uploadSchema=function(){var messageOptions;try{var editorData=angular.fromJson(scope.schemaUploadEditorObj.editor.getValue())}catch(e){return messageOptions={module:"Validation Error",type:"error",provider:"dreamfactory",message:"The schema JSON is not valid."},void dfNotify.error(messageOptions)}if(-1!==StateService.get("dfservice").components.findIndex(function(element,index,array){return element.name===editorData.resource[0].name}))return messageOptions={module:"Validation Error",type:"error",provider:"dreamfactory",message:"The table name already exists."},void dfNotify.error(messageOptions);scope._uploadSchema()},scope.closeUploadSchema=function(){scope._closeUploadSchema()},scope._uploadSchema=function(){var requestDataObj={params:{include_schema:!0},data:angular.fromJson(scope.schemaUploadEditorObj.editor.getValue())};scope._saveSchemaToServer(requestDataObj).then(function(result){var messageOptions={module:"Schema",type:"success",provider:"dreamfactory",message:"Tables created successfully."};angular.forEach(result.data.table,function(dataObj){scope.currentService.components.push({__dfUI:{newTable:!1},name:dataObj.name,path:"_schema/"+dataObj.name})});var curService=StateService.get("dfservice"),component={__dfUI:{newTable:!1},name:requestDataObj.data.resource[0].name,label:requestDataObj.data.resource[0].label};curService.components.push(component),dfApplicationData.updateServiceComponentsLocal(curService),scope.uploadSchemaData=null;var naviObj={service:curService.name,table:requestDataObj.data.resource[0].name,type:"upload"};scope.$emit("table:navigation:select",naviObj),dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)})},scope._saveSchemaToServer=function(requestDataObj){return $http({method:"POST",url:INSTANCE_URL.url+"/"+StateService.get("dfservice").name+"/_schema",data:requestDataObj.data})},scope._closeUploadSchema=function(){scope.$emit("table",{notify:"close"})}}}}]).directive("jsonEdit",function(){return{restrict:"A",require:"ngModel",template:'',replace:!0,scope:{model:"=jsonEdit"},link:function(scope,element,attrs,ngModelCtrl){function setEditing(value){scope.jsonEditing=angular.copy(JSON2String(value))}function updateModel(value){scope.model=string2JSON(value)}function setValid(){ngModelCtrl.$setValidity("json",!0)}function setInvalid(){ngModelCtrl.$setValidity("json",!1)}function string2JSON(text){try{return angular.fromJson(text)}catch(err){return setInvalid(),text}}function JSON2String(object){return angular.toJson(object,!0)}function isValidJson(model){var flag=!0;try{angular.fromJson(model)}catch(err){flag=!1}return flag}setEditing(scope.model),scope.$watch("jsonEditing",function(newval,oldval){newval!=oldval&&(isValidJson(newval)?(setValid(),updateModel(newval)):setInvalid())},!0),scope.$watch("model",function(newval,oldval){newval!=oldval&&setEditing(newval)},!0)}}}),angular.module("dfScripts",["ngRoute","dfUtility"]).constant("MODSCRIPTING_ROUTER_PATH","/scripts").constant("MODSCRIPTING_ASSET_PATH","admin_components/adf-scripts/").constant("MODSCRIPTING_EXAMPLES_PATH","admin_components/adf-scripts/examples/").config(["$routeProvider","MODSCRIPTING_ROUTER_PATH","MODSCRIPTING_ASSET_PATH",function($routeProvider,MODSCRIPTING_ROUTER_PATH,MODSCRIPTING_ASSET_PATH){$routeProvider.when(MODSCRIPTING_ROUTER_PATH,{templateUrl:MODSCRIPTING_ASSET_PATH+"views/main.html",controller:"ScriptsCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("ScriptsCtrl",["INSTANCE_URL","SystemConfigDataService","$scope","$rootScope","$http","dfApplicationData","dfNotify","$location","dfSelectedService",function(INSTANCE_URL,SystemConfigDataService,$scope,$rootScope,$http,dfApplicationData,dfNotify,$location,dfSelectedService){$scope.$parent.title="Scripts",$scope.$parent.titleIcon="code",$scope.scriptGitHubTarget="scripts",$scope.newScript=!0,$scope.isEventScriptEditable=!0,$scope.eventScriptUpdateCounter=0,$scope.disableServiceLinkRefresh=!0,$scope.selections={service:null};var ScriptObj=function(name){return{name:name,type:"nodejs",content:"",is_active:!1,allow_event_modification:!1,storage_service_id:null,scm_repository:null,scm_reference:null,storage_path:null}};$scope.handleFiles=function(element){var file=element.files&&element.files[0];if(file){var reader=new FileReader;reader.readAsText(file,"UTF-8"),reader.onload=function(evt){$scope.$apply(function(){$scope.currentScriptObj.content=evt.target.result,$scope.eventScriptUpdateCounter++})},reader.onerror=function(evt){}}},$scope.githubModalShow=function(){$rootScope.$broadcast("githubShowModal",$scope.scriptGitHubTarget)},$scope.isHostedSystem=!1,$scope.apiData=null,$scope.subscription_required=!1,$scope.loadTabData=function(){$scope.dataLoading=!0;dfApplicationData.getApiData(["system"]).then(function(response){if(angular.forEach(response[0].resource,function(value){"script_type"!==value.name&&"event_script"!==value.name||($scope.scriptsEnabled=!0)}),$scope.scriptsEnabled){var primaryApis=["event_script"],secondaryApis=["service_list","script_type","service_link","environment"];dfApplicationData.getApiData(primaryApis,!0).then(function(response){var newApiData={};primaryApis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),dfApplicationData.getApiData(secondaryApis,null===$scope.apiData).then(function(response){secondaryApis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData,dfSelectedService.currentServiceName&&$scope.selectService(dfSelectedService.currentServiceName)},function(error){var msg="There was an error loading data for the Scripts tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Scripts tab your role must allow GET access to system/event_script, system/event, and system/script_type. To create, update, or delete scripts you need POST and DELETE access to /system/event_script.",$location.url("/home"));var messageOptions={module:"Scripts",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},function(error){var msg="There was an error loading data for the Scripts tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Scripts tab your role must allow GET access to system/event_script, system/event, and system/script_type. To create, update, or delete scripts you need POST and DELETE access to /system/event_script.",$location.url("/home"));var messageOptions={module:"Scripts",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions),$scope.dataLoading=!1})}else $scope.subscription_required=!0},function(error){var messageOptions={module:"Limits",provider:"dreamfactory",type:"error",message:"There was an error loading data for the Limits tab. Please try refreshing your browser and logging in again."};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.getRefreshEnable=function(){var type,enable=!1;return $scope.currentScriptObj&&$scope.selections.service&&("github"===(type=$scope.selections.service.type)||"gitlab"===type||"bitbucket"===type?$scope.currentScriptObj.scm_repository&&$scope.currentScriptObj.scm_reference&&$scope.currentScriptObj.storage_path&&(enable=!0):$scope.currentScriptObj.storage_path&&(enable=!0)),enable},$scope.resetServiceLink=function(){$scope.currentScriptObj.scm_repository=null,$scope.currentScriptObj.scm_reference=null,$scope.currentScriptObj.storage_path=null},$scope.pullLatestScript=function(){var serviceName=$scope.selections.service.name,serviceRepo=$scope.currentScriptObj.scm_repository,serviceRef=$scope.currentScriptObj.scm_reference,servicePath=$scope.currentScriptObj.storage_path,url=INSTANCE_URL.url+"/"+serviceName;if(!$scope.selections.service||"github"!==$scope.selections.service.type&&"gitlab"!==$scope.selections.service.type&&"bitbucket"!==$scope.selections.service.type)url=url+"/"+servicePath;else{var params={path:servicePath,branch:serviceRef,content:1};url=url+"/_repo/"+serviceRepo}$http({method:"GET",url:url,params:params}).then(function(result){$scope.currentScriptObj.content=result.data,$scope.eventScriptUpdateCounter++;var messageOptions={module:"Scripts",provider:"dreamfactory",type:"success",message:"Successfully pulled the latest script from source."};dfNotify.error(messageOptions)},function(error){var messageOptions={module:"Scripts",provider:"dreamfactory",type:"error",message:"There was an error pulling the latest script from source. Please make sure your service, path and permissions are correct and try again."};dfNotify.error(messageOptions)}).finally(function(){})},$scope.deleteScriptFromCache=function(){$http({method:"DELETE",url:INSTANCE_URL.url+"/system/cache/_event/"+$scope.currentScriptObj.name}).then(function(result){var messageOptions={module:"Scripts",provider:"dreamfactory",type:"success",message:"Successfully cleared script from cache."};dfNotify.error(messageOptions)},function(error){var messageOptions={module:"Scripts",provider:"dreamfactory",type:"error",message:"Failed to cleared script from cache."};dfNotify.error(messageOptions)}).finally(function(){})},$scope.loadTabData(),$scope.allowedScriptFormats=["js","php","py","txt"],$scope.currentServiceObj=null,$scope.currentResourceObj=null,$scope.currentEndpointObj=null,$scope.currentScriptObj=null,$scope.menuPathArr=[],$scope.eventLookup={},$scope.eventsLoading=!1,$scope.eventScriptEditorObj={editor:null},$scope.explodeEndpoint=function(endpointName,parameter){var endpoints=[endpointName];return null!==parameter&&endpointName.indexOf("{")>=0&&endpointName.indexOf("}")>=0&&angular.forEach(parameter,function(paramArray,paramName){angular.forEach(paramArray,function(itemName){endpoints.push(endpointName.replace("{"+paramName+"}",itemName))})}),endpoints},$scope.buildEventLookup=function(eventData){var lookupObj,newData=angular.copy(eventData),lookupData={};return angular.forEach(newData,function(resources,serviceName){angular.forEach(resources,function(resourceData,resourceName){angular.forEach(resourceData.endpoints,function(endpointName){lookupObj={service:serviceName,resource:resourceName,endpoint:endpointName},lookupData[endpointName]=lookupObj,null!==resourceData.parameter&&endpointName.indexOf("{")>=0&&endpointName.indexOf("}")>=0&&angular.forEach(resourceData.parameter,function(paramArray,paramName){angular.forEach(paramArray,function(itemName){lookupData[endpointName.replace("{"+paramName+"}",itemName)]=lookupObj})})})})}),lookupData},$scope.highlightService=function(serviceName){return $scope.apiData.event_script.some(function(scriptName){return 0===scriptName.indexOf(serviceName+".")})},$scope.highlightResource=function(resourceName){return $scope.apiData.event_script.some(function(scriptName){var event=$scope.eventLookup[scriptName];return!!event&&event.resource===resourceName})},$scope.highlightEndpoint=function(endpointName){return $scope.apiData.event_script.some(function(scriptName){var event=$scope.eventLookup[scriptName];return!!event&&event.endpoint===endpointName})},$scope.highlightExplodedEndpoint=function(endpointName){return $scope.apiData.event_script.some(function(scriptName){return scriptName===endpointName})},$scope.selectService=function(service){if(!$scope.eventsLoading){$scope.eventsLoading=!0;var serviceName=service.name;$http({method:"GET",url:INSTANCE_URL.url+"/system/event",params:{service:serviceName,scriptable:!0}}).then(function(result){$scope.menuPathArr.push(serviceName);var resources=result.data[serviceName];$scope.currentServiceObj={name:serviceName,resources:resources},$scope.eventLookup=$scope.buildEventLookup(result.data)},function(reject){var messageOptions={module:"Scripts",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){$scope.eventsLoading=!1})}},$scope.selectResource=function(resourceName,resource){$scope.menuPathArr.push(resourceName),$scope.currentResourceObj={name:resourceName,endpoints:resource.endpoints,parameter:resource.parameter}},$scope.selectEndpoint=function(endpointName){var endpoints;$scope.menuPathArr.push(endpointName),endpoints=$scope.explodeEndpoint(endpointName,$scope.currentResourceObj.parameter),$scope.currentEndpointObj={name:endpointName,endpoints:endpoints}},$scope.getServiceById=function(id){var matches=$scope.apiData.service_link.filter(function(service){return service.id===id});return 0===matches.length?null:matches[0]},$scope.getScript=function(scriptName){$scope.menuPathArr.push(scriptName);var requestDataObj={name:scriptName,params:{}};$http({method:"GET",url:INSTANCE_URL.url+"/system/event_script/"+requestDataObj.name,params:requestDataObj.params}).then(function(result){var obj=result.data;$scope.selections.service=$scope.getServiceById(obj.storage_service_id),$scope.selections.service&&(obj.content=""),$scope.currentScriptObj=obj,$scope.newScript=!1},function(reject){if(reject.data&&reject.data.error&&404===reject.data.error.code)$scope.currentScriptObj=new ScriptObj(scriptName),$scope.newScript=!0,$scope.selections.service=null;else{var messageOptions={module:"Scripts",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions),$scope.menuBack()}}).finally(function(){})},$scope.saveScript=function(){if($scope.currentScriptObj.name){$scope.currentScriptObj.storage_service_id=$scope.selections.service?$scope.selections.service.id:null,!$scope.selections.service||"github"!==$scope.selections.service.type&&"gitlab"!==$scope.selections.service.type&&"bitbucket"!==$scope.selections.service.type?$scope.currentScriptObj.scm_repository=null:$scope.currentScriptObj.scm_repository=$scope.currentScriptObj.scm_repository?$scope.currentScriptObj.scm_repository:null,!$scope.selections.service||"github"!==$scope.selections.service.type&&"gitlab"!==$scope.selections.service.type&&"bitbucket"!==$scope.selections.service.type?$scope.currentScriptObj.scm_reference=null:$scope.currentScriptObj.scm_reference=$scope.currentScriptObj.scm_reference?$scope.currentScriptObj.scm_reference:null,$scope.selections.service?$scope.currentScriptObj.storage_path=$scope.currentScriptObj.storage_path?$scope.currentScriptObj.storage_path:null:$scope.currentScriptObj.storage_path=null,$scope.selections.service?($scope.currentScriptObj.content="",$scope.eventScriptUpdateCounter++):$scope.currentScriptObj.content=$scope.eventScriptEditorObj.editor.getValue();var requestDataObj={name:$scope.currentScriptObj.name,params:{},data:$scope.currentScriptObj};$http({method:"POST",url:INSTANCE_URL.url+"/system/event_script/"+requestDataObj.name,params:requestDataObj.params,data:requestDataObj.data}).then(function(result){$scope.newScript=!1;var messageOptions={module:"Scripts",type:"success",provider:"dreamfactory",message:'Script "'+$scope.currentScriptObj.name+'" saved successfully.'};dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Scripts",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){$scope.loadTabData()})}},$scope.deleteScript=function(){if(dfNotify.confirm("Delete "+$scope.currentScriptObj.name+"?")){var requestDataObj={name:$scope.currentScriptObj.name,params:{}};$http({method:"DELETE",url:INSTANCE_URL.url+"/system/event_script/"+requestDataObj.name,params:requestDataObj.params}).then(function(result){var messageOptions={module:"Scripts",type:"success",provider:"dreamfactory",message:"Script deleted successfully."};dfNotify.success(messageOptions),$scope.menuPathArr.pop(),$scope.currentScriptObj=null},function(reject){var messageOptions={module:"Scripts",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){$scope.loadTabData()})}},$scope.menuOpen=!0,$scope.toggleMenu=function(){$scope.menuOpen=!$scope.menuOpen},$scope.menuBack=function(){$scope.menuPathArr.length>0&&($scope.menuPathArr.pop(),$scope.currentScriptObj=null,$scope.eventScriptEditorObj.editor.setValue(""))},$scope.jumpTo=function(index){for(;$scope.menuPathArr.length-1!==index;)$scope.menuBack()},$scope.$broadcast("script:loaded:success");var watchGithubCredUser=$scope.$watch("githubModal.username",function(newValue,oldValue){if(!newValue)return!1;$scope.modalError={visible:!1,message:""}}),watchGithubCredPass=$scope.$watch("githubModal.password",function(newValue,oldValue){if(!newValue)return!1;$scope.modalError={visible:!1,message:""}}),watchGithubURL=$scope.$watch("githubModal.url",function(newValue,oldValue){if(!newValue)return!1;if($scope.modalError={visible:!1,message:""},newValue.indexOf(".js")>0||newValue.indexOf(".py")>0||newValue.indexOf(".php")>0||newValue.indexOf(".txt")>0){var url=angular.copy($scope.githubModal.url),url_array=url.substr(url.indexOf(".com/")+5).split("/"),github_api_url="https://api.github.com/repos/"+url_array[0]+"/"+url_array[1];$http.get(github_api_url,{headers:{"X-DreamFactory-API-Key":void 0,"X-DreamFactory-Session-Token":void 0}}).then(function(response){$scope.githubModal.private=response.data.private,$scope.modalError={visible:!1,message:""}},function(response){404===response.status&&($scope.modalError={visible:!0,message:"Error: The repository could not be found."})})}}),watchCurrentScriptObj=$scope.$watchCollection("currentScriptObj",function(newValue,oldValue){newValue&&($scope.disableServiceLinkRefresh=!$scope.getRefreshEnable())}),watchSelections=$scope.$watchCollection("selections",function(newValue,oldValue){$scope.disableServiceLinkRefresh=!$scope.getRefreshEnable(),newValue&&($scope.isEventScriptEditable=null===newValue.service,null!==newValue.service&&($scope.currentScriptObj.content="",$scope.eventScriptUpdateCounter++))}),watchApiData=$scope.$watchCollection("apiData",function(newValue,oldValue){newValue&&newValue.environment&&newValue.environment.platform&&newValue.environment.platform.is_hosted&&($scope.isHostedSystem=!0)});$scope.$on("$destroy",function(e){watchGithubURL(),watchGithubCredUser(),watchGithubCredPass(),watchCurrentScriptObj(),watchSelections(),watchApiData(),dfSelectedService.cleanCurrentService()})}]).directive("scriptSidebarMenu",["MODSCRIPTING_ASSET_PATH",function(MODSCRIPTING_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MODSCRIPTING_ASSET_PATH+"views/script-sidebar-menu.html",link:function(scope,elem,attrs){}}}]).directive("dfAceSamplesSelect",["MODSCRIPTING_ASSET_PATH","MODSCRIPTING_EXAMPLES_PATH","$http",function(MODSCRIPTING_ASSET_PATH,MODSCRIPTING_EXAMPLES_PATH,$http){return{restrict:"E",scope:!1,templateUrl:MODSCRIPTING_ASSET_PATH+"views/df-ace-samples.html",link:function(scope,elem,attrs){scope.eventScriptSamplesEditorObj={editor:null},scope.eventScriptSamplesType="nodejs",scope.eventScriptSamplesContent="",scope.scriptSamplesSelect=function(type){var fileExt;switch(type){case"nodejs":fileExt="node.js";break;case"php":fileExt="php";break;case"python":fileExt="py";break;case"python3":fileExt="python3.py";break;default:return}scope.eventScriptSamplesType=type,$http.get(MODSCRIPTING_EXAMPLES_PATH+"example.scripts."+fileExt).then(function(result){scope.eventScriptSamplesContent=result.data},function(reject){})},scope.scriptSamplesSelect("nodejs")}}}]).directive("dfScriptingLoading",[function(){return{restrict:"E",template:"
"}}]),angular.module("dfProfile",["ngRoute","dfUtility","dfUserManagement","dfApplication"]).constant("MOD_PROFILE_ROUTER_PATH","/profile").constant("MOD_PROFILE_ASSET_PATH","admin_components/adf-profile/").config(["$routeProvider","MOD_PROFILE_ROUTER_PATH","MOD_PROFILE_ASSET_PATH",function($routeProvider,MOD_PROFILE_ROUTER_PATH,MOD_PROFILE_ASSET_PATH){$routeProvider.when(MOD_PROFILE_ROUTER_PATH,{templateUrl:MOD_PROFILE_ASSET_PATH+"views/main.html",controller:"ProfileCtrl",resolve:{checkProfileRoute:["UserDataService","$location",function(UserDataService,$location){UserDataService.getCurrentUser()||$location.url("/login")}]}})}]).run([function(){}]).controller("ProfileCtrl",["$scope","UserDataService","dfApplicationData","dfNotify","$http","INSTANCE_URL",function($scope,UserDataService,dfApplicationData,dfNotify,$http,INSTANCE_URL){$scope.user=null,$scope.isAdminUser=UserDataService.getCurrentUser().is_sys_admin,$scope.resource=$scope.isAdminUser?"system/admin":"user",$http({method:"GET",url:INSTANCE_URL.url+"/"+$scope.resource+"/profile"}).then(function(result){$scope.user=result.data,($scope.user.adldap||$scope.user.oauth_provider)&&(angular.element("#set-password-section").hide(),angular.element("#set-security-question-section").hide())},function(error){var messageOptions={module:"Profile",provider:"dreamfactory",type:"error",message:"There was an error loading User Profile data. Please try refreshing your browser and logging in again."};dfNotify.error(messageOptions)}),$scope.$parent.title="",$scope.links=[{name:"edit-profile",label:"Profile",path:"edit-profile"}]}]).directive("dfEditProfile",["MOD_PROFILE_ASSET_PATH","INSTANCE_URL","dfNotify","dfApplicationData","UserDataService","dfObjectService","$http","$cookies","SystemConfigDataService",function(MOD_APPS_ASSET_PATH,INSTANCE_URL,dfNotify,dfApplicationData,UserDataService,dfObjectService,$http,$cookies,SystemConfigDataService){return{restrict:"E",scope:!1,templateUrl:MOD_APPS_ASSET_PATH+"views/df-edit-profile.html",link:function(scope,elem,attrs){var messageOptions,requestDataObj,session_token,existingUser;scope.loginAttribute="email",scope.bitnami_demo=!1;var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=systemConfig.authentication.login_attribute),systemConfig&&systemConfig.platform&&systemConfig.platform.hasOwnProperty("bitnami_demo")&&(scope.bitnami_demo=systemConfig.platform.bitnami_demo),scope.requireCurrentPassword=!1,scope.emailChange=function(){scope.requireCurrentPassword=!0},scope.updateUser=function(){scope.setPassword?scope.updatePassword():scope.updateProfile(!1)},scope.updatePassword=function(){if(scope.password.old_password&&scope.password.new_password&&scope.password.verify_password){if(scope.password.new_password!==scope.password.verify_password)return messageOptions={module:"Profile",type:"error",provider:"dreamfactory",message:"Passwords do not match."},void dfNotify.error(messageOptions);requestDataObj={params:{reset:!1,login:!0},data:{old_password:scope.password.old_password,new_password:scope.password.new_password}},scope.updateUserPasswordToServer(requestDataObj).then(function(result){(session_token=result.data.session_token)&&((existingUser=UserDataService.getCurrentUser()).session_token=session_token,UserDataService.setCurrentUser(existingUser)),scope.requireCurrentPassword&&(scope.user.current_password=scope.password.new_password),scope.updateProfile(!0)},function(reject){var messageOptions={module:"Profile",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)})}},scope.updateProfile=function(passwordUpdated){requestDataObj={params:{fields:"*"},data:scope.user,url:INSTANCE_URL.url+"/"+scope.resource+"/profile"},scope.updateUserToServer(requestDataObj).then(function(result){(session_token=result.data.session_token)&&((existingUser=UserDataService.getCurrentUser()).session_token=session_token,UserDataService.setCurrentUser(existingUser)),scope.user.hasOwnProperty("security_question")&&delete scope.user.security_question,scope.user.hasOwnProperty("security_answer")&&delete scope.user.security_answer,UserDataService.setCurrentUser(dfObjectService.mergeObjects(scope.user,UserDataService.getCurrentUser())),scope.isAdminUser&&dfApplicationData.deleteApiDataFromCache("admin"),scope.setPassword=!1,scope.setQuestion=!1,messageOptions={module:"Profile",type:"success",provider:"dreamfactory",message:(passwordUpdated?"Profile and password":"Profile")+" updated successfully."},scope.requireCurrentPassword=!1,dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Profile",type:"error",provider:"dreamfactory",message:passwordUpdated?"Password updated successfully but Profile could not be saved.":reject};dfNotify.error(messageOptions)}).finally(function(){scope.user.current_password=""})},scope.updateUserToServer=function(requestDataObj){return $http({method:"PUT",url:INSTANCE_URL.url+"/"+scope.resource+"/profile",data:requestDataObj.data})},scope.updateUserPasswordToServer=function(requestDataObj){return $http({method:"POST",url:INSTANCE_URL.url+"/"+scope.resource+"/password",params:requestDataObj.params,data:requestDataObj.data})},scope.$watch("setPassword",function(newValue){newValue?(scope.user.current_password="",scope.requireOldPassword=!0,scope.password={old_password:"",new_password:"",verify_password:""}):(scope.password=null,scope.identical=!0)})}}}]),angular.module("dfApplication",["dfUtility","dfUserManagement","ngResource"]).run([function(){}]).service("dfApplicationData",["$q","$http","INSTANCE_URL","dfObjectService","UserDataService","dfSystemData","dfDataWrapper","$rootScope","$location",function($q,$http,INSTANCE_URL,dfObjectService,UserDataService,dfSystemData,dfDataWrapper,$rootScope,$location){function _checkParams(options){options.params?angular.forEach(options.params,function(value,key){null==value&&delete options.params[key]}):options.params={}}function _getApiData(apis,forceRefresh){var deferred=$q.defer(),promises=apis.map(function(api){return _loadOne(api,forceRefresh)});return $q.all(promises).then(function(response){deferred.resolve(response)},function(response){deferred.reject(response)}),deferred.promise}function _loadOne(api,forceRefresh){var params,options,deferred=$q.defer();if(!0===forceRefresh&&delete dfApplicationObj.apis[api],dfApplicationObj.apis.hasOwnProperty(api))deferred.resolve(dfApplicationObj.apis[api]);else{switch((params=_getApiPrefs().data[api])||(params={}),options=null,api){case"system":params.api="";break;case"event_list":params.api="event";break;case"service_link":case"storage_service_link":case"service_list":case"service_type_list":options={url:INSTANCE_URL.url};break;default:params.api=api}dfSystemData.resource(options).get(params).$promise.then(function(response){dfApplicationObj.apis[api]="service_link"===api||"service_list"===api||"storage_service_link"===api?{resource:response.services}:"service_type_list"===api?{resource:response.service_types}:response,deferred.resolve(dfApplicationObj.apis[api])},function(error){deferred.reject(error.data)})}return deferred.promise}function _getApiDataSync(api,forceRefresh){if(!0===forceRefresh&&delete dfApplicationObj.apis[api],dfApplicationObj.apis.hasOwnProperty(api));else{var xhr,currentUser=UserDataService.getCurrentUser();xhr=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP");var url=INSTANCE_URL.url+"/system/"+("system"===api?"":api);xhr.open("GET",url,!1),xhr.setRequestHeader("X-DreamFactory-API-Key","6498a8ad1beb9d84d63035c5d1120c007fad6de706734db9689f8996707e0f7d"),currentUser&¤tUser.session_token&&xhr.setRequestHeader("X-DreamFactory-Session-Token",currentUser.session_token),xhr.setRequestHeader("Content-Type","application/json"),xhr.send(),4==xhr.readyState&&200==xhr.status&&(Array.isArray(angular.fromJson(xhr.responseText))?dfApplicationObj.apis[api]=dfDataWrapper.wrapArrayResponse(xhr.responseText):dfApplicationObj.apis[api]=angular.fromJson(xhr.responseText))}return dfApplicationObj.apis[api]}function _isGoldLicense(){var systemList=_getApiDataSync("system"),limitsEnabled=!1,serviceReportsEnabled=!1;return angular.forEach(systemList.resource,function(value){"limit"===value.name?limitsEnabled=!0:"service_report"===value.name&&(serviceReportsEnabled=!0)}),limitsEnabled&&serviceReportsEnabled}function _resetApplicationObj(){dfApplicationObj={apis:{}}}function _saveApiData(api,options){_checkParams(options);var params=options.params;return params.api=api,options.dontWrapData||(options.data={resource:[options.data]}),dfSystemData.resource(options).post(params,options.data,function(result){result&&result.resource&&"[object Array]"===Object.prototype.toString.call(result.resource)&&result.resource.length>0&&(result=result.resource[0]),__insertApiData(api,result)})}function _updateApiData(api,options){_checkParams(options);var params=options.params;return params.api=api,dfSystemData.resource({url:options.url})[options.method||"put"](params,options.data,function(result){__updateApiData(api,result)})}function _deleteApiData(api,options){_checkParams(options);var params=options.params;return params.api=api,params.rollback=_getApiPrefs().data[api].rollback,dfSystemData.resource().delete(params,options.data,function(result){__deleteApiData(api,result)})}function _getDataSetFromServer(api,options){options=options||{params:{}};var defaults=_getApiPrefs().data[api];options.params=dfObjectService.mergeObjects(defaults,options.params);var params=options.params;return params.api=api,dfSystemData.resource(options).get(params,function(result){__replaceApiData(api,result)})}function _getApiPrefs(){return{data:{app:{include_count:!0,limit:100,related:"role_by_role_id"},role:{include_count:!0,related:"role_service_access_by_role_id,lookup_by_role_id",limit:1e4},admin:{include_count:!0,limit:100,related:"lookup_by_user_id"},user:{include_count:!0,limit:100,related:"lookup_by_user_id,user_to_app_to_role_by_user_id"},service:{include_count:!0,limit:100,related:"service_doc_by_service_id"},service_link:{group:"source control,file"},storage_service_link:{group:"file"},service_list:{},service_type_list:{},cache:{fields:"*"},email_template:{include_count:!0},lookup:{include_count:!0},cors:{include_count:!0},event_list:{as_list:!0},event_script:{as_list:!0},limit:{include_count:!0,limit:100,related:"service_by_service_id,role_by_role_id,user_by_user_id,limit_cache_by_limit_id"},service_report:{include_count:!0,limit:100},scheduler:{include_count:!0,limit:100,related:"task_log_by_task_id"}}}}function __insertApiData(api,dataObj){dfApplicationObj.apis.hasOwnProperty(api)&&"[object Array]"===Object.prototype.toString.call(dfApplicationObj.apis[api].resource)&&dfApplicationObj.apis[api].resource.push(dataObj),dfApplicationObj.apis.hasOwnProperty(api)&&dfApplicationObj.apis[api].hasOwnProperty("meta")&&"[object Object]"===Object.prototype.toString.call(dfApplicationObj.apis[api].meta)&&(dfApplicationObj.apis[api].meta.hasOwnProperty("count")?dfApplicationObj.apis[api].meta.count++:dfApplicationObj.apis[api].meta.count=1)}function __updateApiData(api,dataObj){if(dataObj.resource&&(dataObj=dataObj.resource),dfApplicationObj.apis.hasOwnProperty(api)&&"[object Array]"===Object.prototype.toString.call(dfApplicationObj.apis[api].resource))for(var found=!1,i=0;!found&&i<=dfApplicationObj.apis[api].resource.length-1;)dataObj.id===dfApplicationObj.apis[api].resource[i].id&&(found=!0,dfApplicationObj.apis[api].resource.splice(i,1,dataObj)),i++}function __deleteApiData(api,result){function removeRecord(record){for(var found=!1,i=0;!found&&i=0)&&reject.data.error)return reject.data.error.message.indexOf("Token has expired")>=0||-1!==reject.config.url.indexOf("/profile")?refreshSession(reject):newSession(reject)}return $q.reject(reject)}}}]),angular.module("dfHelp",[]).constant("MOD_HELP_ASSET_PATH","admin_components/adf-help/").directive("dfSimpleHelp",["MOD_HELP_ASSET_PATH",function(MOD_HELP_ASSET_PATH){return{restrict:"E",replace:!0,scope:{options:"=?"},templateUrl:MOD_HELP_ASSET_PATH+"views/simple-help.html",link:function(scope,elem,attrs){var helpDiv=$(elem).children(".help-box");scope.showHelp=function(){scope._showHelp()},scope.closeHelp=function(){scope._closeHelp()},scope._setVisible=function(){helpDiv.is(":hidden")&&helpDiv.show()},scope._setHidden=function(){helpDiv.is(":visible")&&helpDiv.hide()},scope._setWidth=function(){helpDiv.css({width:$(window).outerWidth()/6})},scope._showHelp=function(){if(helpDiv.is(":visible"))return scope.closeHelp(),!1;helpDiv.addClass("dfp-right-bottom"),scope._setWidth(),scope._setVisible()},scope._closeHelp=function(){if(helpDiv.is(":hidden"))return!1;helpDiv.removeClass("dfp-right-bottom"),scope._setHidden()}}}}]).directive("dfLargeHelp",["MOD_HELP_ASSET_PATH","$compile",function(MOD_HELP_ASSET_PATH,$compile){return{restrict:"E",replace:!0,scope:{options:"="},templateUrl:MOD_HELP_ASSET_PATH+"views/df-large-help.html",link:function(scope,elem,attrs){scope.$watch("options",function(newValue,oldValue){newValue&&(newValue.hasOwnProperty("title")&&$(elem).children(".df-large-help-title").html(newValue.title),newValue.hasOwnProperty("text")&&$(elem).children(".df-large-help-text").html(newValue.text))})}}}]),angular.module("dfLaunchPad",["ngRoute","dfUtility","dfTable"]).constant("MOD_LAUNCHPAD_ROUTER_PATH","/launchpad").constant("MOD_LAUNCHPAD_ASSET_PATH","admin_components/adf-launchpad/").config(["$routeProvider","MOD_LAUNCHPAD_ROUTER_PATH","MOD_LAUNCHPAD_ASSET_PATH",function($routeProvider,MOD_LAUNCHPAD_ROUTER_PATH,MOD_LAUNCHPAD_ASSET_PATH){$routeProvider.when(MOD_LAUNCHPAD_ROUTER_PATH,{templateUrl:MOD_LAUNCHPAD_ASSET_PATH+"views/main.html",controller:"LaunchpadCtrl",resolve:{loadApps:["SystemConfigDataService","UserDataService","$location","$q",function(SystemConfigDataService,UserDataService,$location,$q){var defer=$q.defer(),systemConfig=SystemConfigDataService.getSystemConfig();return location.search.substring(1)?($location.url("/login"),defer.reject()):systemConfig&&systemConfig.apps&&0!==systemConfig.apps.length||UserDataService.getCurrentUser()?defer.resolve(systemConfig):($location.url("/login"),defer.reject()),defer.promise}]}})}]).run([function(){}]).controller("LaunchpadCtrl",["$scope","UserDataService","SystemConfigDataService","loadApps",function($scope,UserDataService,SystemConfigDataService,loadApps){$scope.apps=[],$scope.error=!1,$scope.$watch(function(){return loadApps},function(newValue,oldValue){var apps=[],error=!0;newValue&&newValue.hasOwnProperty("apps")&&(error=!1,angular.forEach(newValue.apps,function(app){app.url&&apps.push(app)})),$scope.apps=apps,$scope.error=error},!0)}]).directive("dfApp",["MOD_LAUNCHPAD_ASSET_PATH","$window",function(MOD_LAUNCHPAD_ASSET_PATH,$window){return{restrict:"E",scope:{app:"="},replace:!0,templateUrl:MOD_LAUNCHPAD_ASSET_PATH+"views/df-app.html",link:function(scope,elem,attrs){scope.launchApp=function(app){scope._launchApp(app)},scope._launchApp=function(app){"admin"===app.name&&(app.url+="#/home"),$window.open(app.url)}}}}]),angular.module("dfApiDocs",["ngRoute","dfUtility"]).constant("MOD_APIDOCS_ROUTER_PATH","/apidocs").constant("MOD_APIDOCS_ASSET_PATH","admin_components/adf-apidocs/").config(["$routeProvider","MOD_APIDOCS_ROUTER_PATH","MOD_APIDOCS_ASSET_PATH",function($routeProvider,MOD_APIDOCS_ROUTER_PATH,MOD_APIDOCS_ASSET_PATH){$routeProvider.when(MOD_APIDOCS_ROUTER_PATH,{templateUrl:MOD_APIDOCS_ASSET_PATH+"views/main.html",controller:"ApiDocsCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("ApiDocsCtrl",["$scope",function($scope){$scope.$parent.title="API Docs",$scope.$parent.titleIcon="book",$scope.links=[{name:"apidocs",label:"View",path:"apidocs"}]}]).directive("apiDocs",["MOD_APIDOCS_ASSET_PATH","INSTANCE_BASE_URL",function(MOD_APIDOCS_ASSET_PATH,INSTANCE_BASE_URL){return{restrict:"E",scope:{},templateUrl:MOD_APIDOCS_ASSET_PATH+"views/apidocs.html",link:function(scope,elem,attrs){scope.server=INSTANCE_BASE_URL+"/df-api-docs-ui/dist/index.html?admin_app=1",scope.$broadcast("apidocs:loaded")}}}]),angular.module("dfFileManager",["ngRoute","dfUtility"]).constant("MOD_FILE_MANAGER_ROUTER_PATH","/file-manager").constant("MOD_FILE_MANAGER_ASSET_PATH","admin_components/adf-file-manager/").config(["$routeProvider","MOD_FILE_MANAGER_ROUTER_PATH","MOD_FILE_MANAGER_ASSET_PATH",function($routeProvider,MOD_FILE_MANAGER_ROUTER_PATH,MOD_FILE_MANAGER_ASSET_PATH){$routeProvider.when(MOD_FILE_MANAGER_ROUTER_PATH,{templateUrl:MOD_FILE_MANAGER_ASSET_PATH+"views/main.html",controller:"FileCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("FileCtrl",["$scope",function($scope){$scope.$parent.title="Files",$scope.$parent.titleIcon="file-o",$scope.links=[{name:"manage-files",label:"Manage",path:"manage-files"}]}]).directive("dfFileManager",["MOD_FILE_MANAGER_ASSET_PATH","INSTANCE_BASE_URL",function(MOD_FILE_MANAGER_ASSET_PATH,INSTANCE_BASE_URL){return{restrict:"E",scope:!1,templateUrl:MOD_FILE_MANAGER_ASSET_PATH+"views/df-file-manager.html",link:function(scope,elem,attrs){$("#root-file-manager iframe").attr("src",INSTANCE_BASE_URL+"/filemanager/index.html?path=/&allowroot=true").show(),scope.$broadcast("filemanager:loaded")}}}]),angular.module("dfPackageManager",["ngRoute","dfUtility","ngclipboard"]).constant("MOD_PACKAGE_MANAGER_ROUTER_PATH","/package-manager").constant("MOD_PACKAGE_MANAGER_ASSET_PATH","admin_components/adf-package-manager/").config(["$routeProvider","MOD_PACKAGE_MANAGER_ROUTER_PATH","MOD_PACKAGE_MANAGER_ASSET_PATH",function($routeProvider,MOD_PACKAGE_MANAGER_ROUTER_PATH,MOD_PACKAGE_MANAGER_ASSET_PATH){$routeProvider.when(MOD_PACKAGE_MANAGER_ROUTER_PATH,{templateUrl:MOD_PACKAGE_MANAGER_ASSET_PATH+"views/main.html",controller:"PackageCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).directive("tabs",function(){return{restrict:"E",transclude:!0,scope:{},controller:["$scope",function($scope){var panes=$scope.panes=[];$scope.select=function(pane){angular.forEach(panes,function(pane){pane.selected=!1}),pane.selected=!0},this.addPane=function(pane){0==panes.length&&$scope.select(pane),panes.push(pane)}}],template:'',replace:!0}}).directive("pane",function(){return{require:"^tabs",restrict:"E",transclude:!0,scope:{title:"@"},link:function(scope,element,attrs,tabsCtrl){tabsCtrl.addPane(scope)},template:'
',replace:!0}}).controller("PackageCtrl",["$scope","$rootScope","dfApplicationData","dfNotify","$location",function($scope,$rootScope,dfApplicationData,dfNotify,$location){$scope.$parent.title="Packages",$scope.$parent.titleIcon="plus-square",$scope.apiData=null,$scope.loadTabData=function(){$scope.dataLoading=!0;var primaryApis=["service_list","service_type_list","environment","package"],secondaryApis=["app"],errorFunc=function(error){var msg="There was an error loading data for the Packages tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Packages tab your role must allow GET and POST access to system/package.",$location.url("/home"));var messageOptions={module:"Packages",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions),$scope.dataLoading=!1};dfApplicationData.getApiData(["system"]).then(function(response){angular.forEach(response[0].resource,function(value){"event_script"===value.name&&($scope.eventScriptEnabled=!0)}),dfApplicationData.getApiData(primaryApis,!0).then(function(response){var newApiData={};primaryApis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),dfApplicationData.getApiData(secondaryApis,!0).then(function(response){secondaryApis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]})},function(error){newApiData.app=[]}).finally(function(){$scope.apiData=newApiData,$scope.dataLoading=!1})},errorFunc)},errorFunc).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(),$scope.dfLargeHelp={packageManager:{title:"Packages Overview",text:"Import and export users, apps, files, database schemas and more."},packageExport:{title:"",text:"To create a DreamFactory package export file, follow these instructions.
  • Use the UI below to build a list of items to export.
  • You should enter a password if you'd like exported user passwords and service credentials to be encrypted. This password will be required if you decide to import this package file later.
  • Select a file service to store the exported zip file. Folder name is optional.
  • Click the Export button to save the zip file to the file storage location you selected.
"}}}]).directive("file",function(){return{scope:{file:"="},link:function(scope,el,attrs){el.bind("change",function(event){var file=event.target.files[0];scope.file=file||void 0,scope.$apply()})}}}).directive("dfImportPackage",["MOD_PACKAGE_MANAGER_ASSET_PATH","INSTANCE_URL","UserDataService","dfApplicationData","dfNotify","$timeout","$http",function(MOD_PACKAGE_MANAGER_ASSET_PATH,INSTANCE_URL,UserDataService,dfApplicationData,dfNotify,$timeout,$http){return{restrict:"E",scope:!1,templateUrl:MOD_PACKAGE_MANAGER_ASSET_PATH+"views/df-import-package.html",link:function(scope,elem,attrs){scope.packageImportPassword="",scope.overwrite=!1,scope.fileSelector=angular.element("#fileSelect"),scope.fileImportPath=null,scope.uploadFile=null,scope.browseFileSystem=function(){scope.fileSelector.trigger("click")},scope.importPackageFile=function(){var file=scope.file;if(void 0===file&&(file=scope.fileImportPath),file){var currentUser=UserDataService.getCurrentUser();$http({method:"POST",url:INSTANCE_URL.url+"/system/package?password="+scope.packageImportPassword+"&overwrite="+scope.overwrite,headers:{"X-DreamFactory-Session-Token":currentUser.session_token,"Content-Type":void 0},data:{files:file,import_url:file},transformRequest:function(data){var formData=new FormData;return angular.forEach(data,function(value,key){formData.append(key,value)}),formData}}).then(function(result){if(result&&result.data)if(!0===result.data.success){var messageOptions={module:"Packages",provider:"dreamfactory",type:"success",message:"Package was imported successfully."};dfNotify.success(messageOptions),scope.importClear(),scope.loadTabData()}else{var notice="";angular.forEach(result.data.log.notice,function(value,key){notice+="* "+value+"\n"});var msg="Package import failed.\n\nReason:\n"+notice;$timeout(function(){alert(msg)})}},function(reject){var messageOptions={module:"Packages",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}),scope.packageImportPassword=""}else{var messageOptions={module:"Packages",provider:"dreamfactory",type:"error",message:"No package file selected."};dfNotify.error(messageOptions)}},scope.importClear=function(){scope.file&&delete scope.file,angular.element("input[type='file']").val(null),scope.packageImportPassword="",scope.fileImportPath=null};var watchUploadFile=scope.$watch("uploadFile",function(n,o){n&&(scope.fileImportPath=n.name)});scope.$on("$destroy",function(e){watchUploadFile()})}}}]).directive("dfViewContent",["MOD_PACKAGE_MANAGER_ASSET_PATH",function(MOD_PACKAGE_MANAGER_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_PACKAGE_MANAGER_ASSET_PATH+"views/df-view-content.html",link:function(scope,elem,attrs){}}}]).directive("dfSelectContent",["$http","$timeout","MOD_PACKAGE_MANAGER_ASSET_PATH","dfApplicationData","dfNotify",function($http,$timeout,MOD_PACKAGE_MANAGER_ASSET_PATH,dfApplicationData,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_PACKAGE_MANAGER_ASSET_PATH+"views/df-select-content.html",link:function(scope,elem,attrs){scope.initVars=function(){scope.types=[],scope.selectedType=null,scope.names=[],scope.selectedName=null,scope.selectedNameData=[],scope.tableData=[],scope.search={}},scope.resetVars=function(){scope.selectedType=null,scope.selectedName=null,scope.selectedNameData=[],scope.tableData=[],scope.search={}},scope.initVars();var filterTextTimeout,tempFilterText=null,TableData=function(tableData){return{__dfUI:{selected:!1},record:tableData}};scope.init=function(){scope.initVars();var env=scope.apiData.environment;scope.enablePassword=env.platform.secured_package_export;var _serviceTypes=scope.apiData.service_type_list,_services=scope.apiData.service_list;angular.forEach(scope.apiData.package.service,function(manifestValue,manifestKey){var _service=_services.filter(function(obj){return obj.name===manifestKey}),type=_serviceTypes.filter(function(obj){return obj.name==_service[0].type}),_typeObj={name:type[0].name,label:type[0].label,group:type[0].group};"Database"===_typeObj.group&&(_typeObj.label+=" Schema"),0===scope.types.filter(function(obj){return obj.name==_typeObj.name}).length&&scope.types.push(_typeObj)})},scope.anySelected=function(){return scope.selectedNameData.map(function(d){return d.__dfUI.selected}).indexOf(!0)>=0},scope.getAllNames=function(){return scope.selectedNameData.map(function(d){return d.record.display_label})},scope.getSelectedNames=function(){var selected;return selected=[],angular.forEach(scope.selectedNameData,function(value){!0===value.__dfUI.selected&&selected.push(value.record.display_label)}),selected},scope.removeRow=function(row){scope.tableData.splice(row,1)},scope.addToPackage=function(selectAll){var selectAllExists=!1;if(angular.forEach(scope.tableData,function(value){value.type.name===scope.selectedType.name&&value.name===scope.selectedName&&!0===value.selectAll&&(selectAllExists=!0)}),!selectAllExists||scope.addAppFiles(scope.getAllNames())){if(!0===selectAll){var tableRemoveArray=[];angular.forEach(scope.tableData,function(value,index){value.name===scope.selectedName&&value.type.name===scope.selectedType.name&&tableRemoveArray.push(index)}),tableRemoveArray.reverse(),angular.forEach(tableRemoveArray,function(value){scope.removeRow(value)});var allNames=scope.getAllNames();scope.tableData.push({type:scope.selectedType,name:scope.selectedName,selectAll:!0,selected:allNames,descr:"All"}),"system"===scope.selectedType.name&&"app"===scope.selectedName&&scope.addAppFiles(allNames)}else{var newSelected=scope.getSelectedNames();angular.forEach(newSelected,function(sel){0===scope.tableData.filter(function(obj){return obj.type.name===scope.selectedType.name&&obj.name===scope.selectedName&&obj.selected[0]===sel}).length&&scope.tableData.push({type:scope.selectedType,name:scope.selectedName,selectAll:!1,selected:[sel],descr:sel}),"system"===scope.selectedType.name&&"app"===scope.selectedName&&scope.addAppFiles([sel])})}angular.forEach(scope.selectedNameData,function(value){value.__dfUI.selected=!1}),console.log("tableData",scope.tableData)}else{var messageOptions={module:"Packages",provider:"dreamfactory",type:"error",message:"You have already selected all items for "+scope.selectedType.label+" / "+scope.selectedName+"."};dfNotify.error(messageOptions)}},scope.addAppFiles=function(appNames){var services,serviceId,serviceName,container,retVal=!1,apps=scope.apiData.app;return angular.forEach(appNames,function(value){if(1===(matches=apps.filter(function(obj){return obj.name===value})).length&&(serviceId=matches[0].storage_service_id,container=matches[0].storage_container+"/",services=scope.apiData.service_list,1===(matches=services.filter(function(obj){return obj.id===serviceId})).length)){var type={group:"File",label:matches[0].label,name:matches[0].type};serviceName=matches[0].name;var matches=scope.tableData.filter(function(obj){return obj.type.name===type.name&&obj.name===serviceName&&obj.selected.indexOf(container)>=0});0===matches.length&&(retVal=!0,scope.tableData.push({type:type,name:serviceName,selectAll:!1,selected:[container],descr:container}))}}),retVal},scope.loadTable=function(newValue,filter){var record,nameData=[],values=[];switch(newValue&&-1!==newValue.indexOf("[unavailable]")&&(alert("You have selected a service that is currently unavailable/unreachable. Please check DreamFactory log or client console for error details."),newValue=newValue.replace(" [unavailable]","")),scope.selectedType.group){case"System":values=scope.apiData.package.service.system[newValue];break;case"Database":values=scope.apiData.package.service[newValue]._schema;break;case"File":values=scope.apiData.package.service[newValue].filter(function(obj){return obj.indexOf("/")>0})}angular.forEach(values,function(value){record="System"!==scope.selectedType.group||"admin"!==scope.selectedName&&"user"!==scope.selectedName?{display_label:value}:{display_label:value.email,first_name:value.first_name,last_name:value.last_name},(!filter||value.indexOf(filter)>=0)&&nameData.push(new TableData(record))}),scope.selectedNameData=nameData},scope.$watch("search.text",function(newValue,oldValue){null!==newValue&&void 0!==newValue&&(filterTextTimeout&&$timeout.cancel(filterTextTimeout),tempFilterText=newValue,filterTextTimeout=$timeout(function(){scope.loadTable(scope.selectedName,tempFilterText)},500))},!0),scope.$watch("selectedType",function(newValue){var _type,_name,_services,_service,_names=[];scope.names=[],scope.selectedName=null,scope.selectedNameData=[],newValue&&newValue.name&&("system"===(_type=newValue.name)?angular.forEach(scope.apiData.package.service.system,function(manifestValue,manifestKey){_names.push(manifestKey)}):(_services=scope.apiData.service_list,angular.forEach(scope.apiData.package.service,function(manifestValue,manifestKey){(_service=_services.filter(function(obj){return obj.name===manifestKey}))[0].type===_type&&(_name=_service[0].name,!1===manifestValue.reachable&&(_name+=" [unavailable]"),_names.push(_name))})),scope.names=_names)}),scope.$watch("selectedName",function(newValue){newValue&&scope.loadTable(newValue,null)}),scope.$watchCollection("apiData",function(newValue){newValue&&scope.init()})}}}]).directive("dfSelectFolder",["MOD_PACKAGE_MANAGER_ASSET_PATH",function(MOD_PACKAGE_MANAGER_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_PACKAGE_MANAGER_ASSET_PATH+"views/df-select-folder.html",link:function(scope,elem,attrs){}}}]).directive("dfExportPackage",["INSTANCE_URL","INSTANCE_API_PREFIX","APP_API_KEY","dfNotify","$http","$window","$timeout","UserDataService",function(INSTANCE_URL,INSTANCE_API_PREFIX,APP_API_KEY,dfNotify,$http,$window,$timeout,UserDataService){return{restrict:"A",scope:!1,replace:!0,link:function(scope,elem,attrs){scope.availableFileServices=null,scope.selectedFileService=null,scope.folderName="",scope.fileName="",scope.packagePassword="",scope.showFilePath=!1,scope.publicFilePath="N/A",scope.publicPathNote="";var exportPath="",payload={};scope.folderInit=function(){var _services=scope.apiData.service_list,_searchTypes=scope.apiData.service_type_list.filter(function(obj){return"File"===obj.group}).map(function(type){return type.name}),_fileServices=[];angular.forEach(_services,function(value){_searchTypes.indexOf(value.type)>-1&&_fileServices.push(value)}),scope.selectedFileService=null,scope.availableFileServices=_fileServices},scope.exportPackage=function(){var name,type,group,selected;if(0===scope.tableData.length){messageOptions={module:"Packages",provider:"dreamfactory",type:"error",message:"No package content is selected."};dfNotify.error(messageOptions)}else if(scope.selectedFileService){payload={secured:scope.packagePassword.length>0,password:scope.packagePassword,storage:{name:scope.selectedFileService.name,folder:scope.folderName,filename:scope.fileName},service:{}};var tableData=scope.tableData;angular.forEach(tableData,function(value){switch(selected=value.selected,type=value.type.name,name=value.name,group=value.type.group){case"System":void 0===payload.service[type]&&(payload.service[type]={}),void 0===payload.service[type][name]&&(payload.service[type][name]=[]),payload.service[type][name]=payload.service[type][name].concat(selected);break;case"Database":void 0===payload.service[name]&&(payload.service[name]={}),void 0===payload.service[name]._schema&&(payload.service[name]._schema=[]),payload.service[name]._schema=payload.service[name]._schema.concat(selected);break;case"File":void 0===payload.service[name]&&(payload.service[name]=[]),payload.service[name]=payload.service[name].concat(selected)}}),console.log("manifest",payload),$http({method:"POST",url:INSTANCE_URL.url+"/system/package",data:payload}).then(function(response){exportPath=response.data.path;var path=response.data.path;path=path.replace(INSTANCE_API_PREFIX,""),scope.publicFilePath=path,scope.showFilePath=!0;var msg="The package has been exported. Click the Download button to download the file.\n\nThe path to the exported package is: \n"+path+"\n";if(!1===response.data.is_public){var subFolder=""===scope.folderName?"__EXPORTS":scope.folderName,pathNote='\nTo make your exported file publicly accessible/downloadable, edit your "'+scope.selectedFileService.label+'" service configuration to add "'+subFolder+'" under "Public Path".';msg+=pathNote,scope.publicPathNote=pathNote}$timeout(function(){alert(msg)})},function(response){var msg="An error occurred!\n\nReason:\n"+response.data.error.message+"\n";$timeout(function(){alert(msg)})})}else{var messageOptions={module:"Packages",provider:"dreamfactory",type:"error",message:"No file service is selected."};dfNotify.error(messageOptions)}},scope.exportDownload=function(){if(""!==exportPath){var params="?api_key="+APP_API_KEY,currentUser=UserDataService.getCurrentUser();currentUser&¤tUser.session_token&&(params+="&session_token="+currentUser.session_token),window.location.href=exportPath+params}},scope.exportClear=function(){scope.resetVars(),exportPath="",scope.folderName="",scope.fileName="",scope.packagePassword="",scope.showFilePath=!1,scope.publicFilePath="N/A",scope.publicPathNote=""},scope.$watchCollection("apiData",function(newValue){newValue&&scope.folderInit()})}}}]).directive("dfPackageLoading",[function(){return{restrict:"E",template:"
"}}]),angular.module("dfTable",["dfUtility"]).constant("DF_TABLE_ASSET_PATH","admin_components/adf-table/").run(["$templateCache",function($templateCache){$templateCache.put("df-input-text.html",''),$templateCache.put("df-input-ref-text.html",''),$templateCache.put("df-input-number.html",''),$templateCache.put("df-input-int.html",''),$templateCache.put("df-input-textarea.html",''),$templateCache.put("df-input-binary.html","

BINARY DATA

"),$templateCache.put("df-input-datetime.html","

DATETIME

"),$templateCache.put("df-input-reference.html",'
'),$templateCache.put("df-input-checkbox.html",''),$templateCache.put("df-input-bool-picklist.html",'
'),$templateCache.put("df-input-select.html",''),$templateCache.put("df-input-values-picklist.html",'
\x3c!-- /btn-group --\x3e
\x3c!-- /input-group --\x3e
\x3c!-- /.col-lg-6 --\x3e
'),$templateCache.put("df-input-values-only-picklist.html",'
'),$templateCache.put("df-input-date-time-picker.html",'
\n
\n\n\n\n
\n
\n\n
\n
')}]).filter("typeFilter",[function(){return function(object){var array=[];return angular.forEach(object,function(option){"boolean"!=option.type&&"integer"!=option.type&&"string"!=option.type&&"text"!=option.type&&"float"!=option.type&&"double"!=option.type&&"decimal"!=option.type||array.push(option)}),array}}]).directive("dfTable",["DF_TABLE_ASSET_PATH","$http","$q","$filter","$compile","dfObjectService","dfTableEventService","dfTableCallbacksService",function(DF_TABLE_ASSET_PATH,$http,$q,$filter,$compile,dfObjectService,dfTableEventService,dfTableCallbacksService){return{restrict:"E",scope:{userOptions:"=options",parentRecord:"=?",exportField:"=?"},templateUrl:DF_TABLE_ASSET_PATH+"views/dreamfactory-table.html",link:function(scope,elem,attrs){scope.es=dfTableEventService,scope.defaults={service:"",table:"",url:"",normalizeData:!1,normalizeSchema:!0,autoClose:!0,params:{filter:null,limit:50,offset:0,fields:"*",include_schema:!0,include_count:!0},defaultFields:null,overrideFields:[],extendFieldTypes:[],extendData:[],extendSchema:[],relatedData:[],excludeFields:[],groupFields:[],exportValueOn:!1,allowChildTable:!1,childTableAttachPoint:null,isChildTable:!1},scope.options={},scope.disableTableBtns=!1,scope.record=null,scope.schema=null,scope.overrideFields={},scope.tableFields={onStartTotalActiveFields:0},scope.tableFieldsAll=!1,scope.tableFilterOn=!0,scope.defaultFieldsShown={},scope.numAutoSelectFields=8,scope.selectedAll=!1,scope.filterOn=!1,scope.filter={viewBy:"",prop:"",props:"",type:"",value:null},scope.operators={integer:["<",">","="],boolean:[],string:[],text:[],float:["<",">","="],double:["<",">","="],decimal:["<",">","="]},scope.filterType={operator:null},scope.order={orderBy:"",orderByReverse:!1},scope.filteredRecords=!1,scope.orderedRecords=!1,scope.activeTab=null,scope.activeView="table",scope.pagesArr=[],scope.currentPage={},scope.currentEditRecord=null,scope.extendFieldTypes={},scope.inProgress=!1,scope.count=0,scope._exportValue=null,scope.newRecord=null,scope.relatedExpand=!1,scope.extendedData={},scope.extendedSchema={},scope.excludedFields={},scope.filteredSchema=[],scope.groupedSchema=[],scope.childTableActive=!1,scope.childTableOptions={},scope.childTableParentRecord=null,scope.setTab=function(tabStr){scope._setTab(tabStr)},scope.toggleSelected=function(dataObj){if(scope.childTableActive)return!1;scope._toggleSelected(dataObj)},scope.getPrevious=function(){if(scope._isFirstPage()||scope._isInProgress())return!1;scope._checkForUnsavedRecords(scope.record)?scope._confirmAction("You have Unsaved records. Continue without saving?",scope._getPrevious):scope._getPrevious()},scope.getNext=function(){if(scope._isLastPage()||scope._isInProgress())return!1;scope._checkForUnsavedRecords(scope.record)?scope._confirmAction("You have Unsaved records. Continue without saving?",scope._getNext):scope._getNext()},scope.editRecord=function(dataObj){scope._editRecord(dataObj)},scope.createRecord=function(){scope._createRecord()},scope.saveRecords=function(){scope._saveRecords()},scope.revertRecords=function(){scope._revertRecords()},scope.deleteRecords=function(){scope._confirmAction("You are about to delete records. Continue?",scope._deleteRecords)},scope.applyFilter=function(){scope._applyFilter()},scope.removeFilter=function(){scope._removeFilter()},scope.refreshResults=function(){scope._refreshResults()},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setExportValue=function(dataObj){scope._setExportValue(dataObj)},scope.toggleExpandEditor=function(){scope._toggleExpandEditor()},scope.editExportRecord=function(dataObj){scope._editExportRecord(dataObj)},scope.filterRecords=function(){scope._filterRecords()},scope.toggleAllFields=function(){scope._toggleAllFields()},scope.resetAllFields=function(){scope._resetAllFields()},scope.toggleAllRecords=function(){scope._toggleAllRecords()},scope.showChildTable=function(parentRecordObj){scope._showChildTable(parentRecordObj)},scope._addSelectedProp=function(dataObj){dataObj.__dfUI.hasOwnProperty("selected")||(dataObj.__dfUI.selected=!1)},scope._addUnsavedProp=function(dataObj){dataObj.__dfUI.hasOwnProperty("unsaved")||(dataObj.__dfUI.unsaved=!1)},scope._addExportProp=function(dataObj){dataObj.__dfUI.hasOwnProperty("export")||(dataObj.__dfUI.export=!1)},scope._addHideProp=function(dataObj){dataObj.__dfUI.hasOwnProperty("hide")||(dataObj.__dfUI.hide=!1)},scope._addStateProps=function(dataObj){dataObj.hasOwnProperty.__dfUI||(dataObj.__dfUI={}),scope._addSelectedProp(dataObj),scope._addUnsavedProp(dataObj),scope._addExportProp(dataObj),scope._addHideProp(dataObj)},scope._removeStateProps=function(dataObj){dataObj.hasOwnProperty.__dfUI&&delete dataObj.__dfUI},scope._toggleSelectedState=function(dataObj){dataObj.__dfUI.selected=!dataObj.__dfUI.selected},scope._toggleUnsavedState=function(dataObj){dataObj.__dfUI.unsaved=!dataObj.__dfUI.unsaved},scope._setSelectedState=function(dataObj,stateBool){dataObj.__dfUI.selected=stateBool},scope._setUnsavedState=function(dataObj,stateBool){dataObj.__dfUI.unsaved=stateBool},scope._setExportState=function(dataObj,stateBool){dataObj&&(dataObj.__dfUI.export=stateBool)},scope._setHideState=function(dataObj,stateBool){dataObj&&(dataObj.__dfUI.hide=stateBool)},scope._isUnsaved=function(dataObj){return dataObj.__dfUI.unsaved},scope._isSelected=function(dataObj){return dataObj.__dfUI.selected},scope._isExport=function(dataObj){return dataObj.__dfUI.export},scope._checkForUnsavedRecords=function(data){if(!data)return!1;var unsavedRecords=!1,i=0;do{if(i>=data.length)break;data[i].__dfUI.unsaved&&(unsavedRecords=!0),i++}while(0==unsavedRecords);return unsavedRecords},scope._checkForParams=function(){return scope.options.hasOwnProperty("params")?scope.options.params:scope.defaults.params},scope._getRecordsFromServer=function(requestDataObj){var params=scope._checkForParams();return(requestDataObj=requestDataObj||null)&&(params=dfObjectService.mergeObjects(requestDataObj.params,params)),scope.options.relatedData.length>0&&(params.related=scope.options.relatedData.join(",")),$http({method:"GET",url:scope.options.url,params:params})},scope._getRecordsFromData=function(dataObj){var limit=scope._checkForParams().limit,records=[];return dataObj.hasOwnProperty("resource")?records=dataObj.resource:dataObj.hasOwnProperty("data")&&(records=dataObj.data.hasOwnProperty("resource")?dataObj.data.resource:dataObj.data.data.resource),records.length>limit?records.slice(0,limit):records},scope._getMetaFromData=function(dataObj){var meta={};return dataObj.hasOwnProperty("meta")?meta=dataObj.meta:dataObj.hasOwnProperty("data")&&(meta=dataObj.data.hasOwnProperty("meta")?dataObj.data.meta:dataObj.data.data.meta),meta},scope._getSchemaFromData=function(dataObj){return scope._getMetaFromData(dataObj).schema},scope._getCountFromMeta=function(dataObj){var count=scope._getMetaFromData(dataObj).count;return scope._setCount(count),count},scope._setCount=function(countInt){scope.count=countInt},scope._getOptionFromParams=function(keyStr){return scope._checkForParams()[keyStr]},scope._setOptionFromParams=function(keyStr,valueStr){},scope._buildField=function(fieldNameStr){console.log(fieldNameStr)},scope._createRevertCopy=function(dataObj){dataObj.__dfData={},dataObj.__dfData.revert=angular.copy(dataObj),dataObj.__dfData.revert.hasOwnProperty("_exportValue")||(dataObj.__dfData.revert._exportValue={})},scope._getRevertCopy=function(dataObj){return dataObj.__dfData.revert},scope._hasRevertCopy=function(dataObj){return!!dataObj.hasOwnProperty("__dfData")&&!!dataObj.__dfData.hasOwnProperty("revert")},scope._removeRevertCopy=function(dataObj){dataObj.__dfData.revert&&delete dataObj.__dfData.revert},scope._removeAllDFData=function(dataObj){dataObj.__dfData&&delete dataObj.__dfData},scope._removeAllUIData=function(dataObj){delete dataObj.__dfUI},scope._compareObjects=function(dataObj1,dataObj2){for(var key in dataObj1)if("dfUISelected"!==key&&"dfUIUnsaved"!==key&&"__dfUI"!==key&&"__dfData"!=key&&"created_date"!=key&&"last_modified_date"!=key&&"$$hashKey"!==key&&dataObj1[key]!==dataObj2[key])return(null!=dataObj1[key]&&""!=dataObj1[key]||null!=dataObj2[key]&&""!=dataObj2[key])&&!(dataObj1[key]instanceof Array&&dataObj2[key]instanceof Array&&dataObj1[key].length==dataObj2[key].length);return!1},scope._getRecordsWithState=function(recordsDataArr,stateStr,removeDFDataBool,removeUIDataBool){var records=[];return removeDFDataBool=void 0!==removeDFDataBool&&removeDFDataBool,removeUIDataBool=void 0!==removeUIDataBool&&removeUIDataBool,angular.forEach(recordsDataArr,function(_obj){_obj.__dfUI[stateStr]&&(removeDFDataBool&&scope._removeAllDFData(_obj),removeUIDataBool&&scope._removeAllUIData(_obj),records.push(_obj))}),records},scope._saveRecordsToServer=function(recordsDataArr){if(0==recordsDataArr.length){var defer=$q.defer();return defer.reject("No records selected for save."),defer.promise}return $http({method:"PATCH",url:scope.options.url,data:{resource:recordsDataArr}})},scope._deleteRecordsFromServer=function(recordsDataArr){if(0==recordsDataArr.length){var defer=$q.defer();return defer.reject("No records selected for delete."),defer.promise}return $http({method:"DELETE",url:scope.options.url,data:{resource:recordsDataArr}})},scope._isInProgress=function(){return scope.inProgress},scope._setInProgress=function(stateBool){scope.inProgress=stateBool},scope._createNewRecordObj=function(){var newRecord={};return angular.forEach(scope.schema.field,function(_obj){scope.excludedFields.hasOwnProperty(_obj.name)&&scope.excludedFields[_obj.name].fields.create||(newRecord[_obj.name]=_obj.default)}),scope._addStateProps(newRecord),newRecord},scope._setCurrentEditRecord=function(dataObj){scope.currentEditRecord=dataObj},scope._setNewRecordObj=function(){scope.newRecord=scope._createNewRecordObj()},scope._confirmAction=function(_message,_action){confirm(_message)&&_action.call()},scope._filterFormSchema=function(formNameStr){if(0==scope.excludedFields.length)return!1;angular.forEach(scope.schema.field,function(_obj){scope.excludedFields.hasOwnProperty(_obj.name)&&scope.excludedFields[_obj.name].fields[formNameStr]||scope.filteredSchema.push(_obj)})},scope._buildSchemaGroups=function(){if(0==scope.options.groupFields.length)return!1;var _schema=scope.filteredSchema.length>0?scope.filteredSchema:scope.schema.field;angular.forEach(scope.options.groupFields,function(fobj){var group={};group.name=fobj.name,group.fields=[],group.dividers=fobj.dividers,angular.forEach(_schema,function(item){angular.forEach(fobj.fields,function(field,index){item.name===field&&(group.fields[index]=item)})}),scope.groupedSchema.push(group)})},scope._checkForGroupedSchema=function(groupNameStr){0==scope.groupedSchema.length&&scope.groupedSchema.push({name:groupNameStr,fields:scope.schema.field})},scope._clearFilteredSchema=function(){scope.filteredSchema=[]},scope._clearGroupedSchema=function(){scope.groupedSchema=[]},scope._getDefaultFields=function(dataObj){return dataObj.hasOwnProperty("defaultFields")?dataObj.defaultFields:null},scope._removePrivateFields=function(dataObj){dataObj&&angular.forEach(scope.record,function(_obj){for(var _key in _obj)dataObj[_key]&&"private"==dataObj[_key]&&delete _obj[_key]})},scope._setElementActive=function(tabStr){scope.activeTab=tabStr},scope._setDisableTableBtnsState=function(stateBool){scope.disableTableBtns=stateBool},scope._createFieldsObj=function(schemaDataObj){if(scope.tableFields={onStartTotalActiveFields:0},!scope.defaultFieldsShown){var allKeys=Object.keys(schemaDataObj);return allKeys.length0&&(scope.schema=scope._normalizeSchema(scope.schema,scope.record)),angular.forEach(scope.extendedSchema,function(_obj){scope.schema.field.push(_obj)})},scope._prepareExtendedSchema=function(data){if(null==data.extendSchema)return!1;angular.forEach(data.extendSchema,function(_obj){scope.extendedSchema[_obj.name]={},scope.extendedSchema[_obj.name].name=_obj.name,scope.extendedSchema[_obj.name].type=_obj.type,scope.extendedSchema[_obj.name].label=_obj.label})},scope._prepareOverrideFields=function(data){if(null==data.overrideFields)return!1;angular.forEach(data.overrideFields,function(_obj){scope.overrideFields[_obj.field]={},_obj.hasOwnProperty("record")&&(scope.overrideFields[_obj.field].records=scope._getRecordsFromData(_obj.record)),scope.overrideFields[_obj.field].display=_obj.display})},scope._prepareExtendedFieldTypes=function(data){if(null==data.extendFieldTypes)return!1;angular.forEach(data.extendFieldTypes,function(_obj){scope.extendFieldTypes[_obj.db_type]={};for(var _key in _obj)scope.extendFieldTypes[_obj.db_type][_key]=_obj[_key]})},scope._prepareExtendedData=function(data){if(null==data.extendData)return!1;angular.forEach(data.extendData,function(_obj){scope.extendedData[_obj.name]={},scope.extendedData[_obj.name].name=_obj.name,scope.extendedData[_obj.name].value=_obj.value||null})},scope._addExtendedData=function(dataObj){angular.forEach(scope.extendedData,function(_obj){dataObj[_obj.name]=_obj.value})},scope._setActiveView=function(viewStr){scope.activeView=viewStr},scope._setExportValueToParent=function(dataObj){scope._exportValue=dataObj||null},scope._prepareExcludedFields=function(data){if(null==data.extendSchema)return!1;angular.forEach(data.excludeFields,function(_obj){scope.excludedFields[_obj.name]={},scope.excludedFields[_obj.name].fields=_obj.fields})},scope._calcTotalPages=function(totalCount,numPerPage){return Math.ceil(totalCount/numPerPage)},scope._createPageObj=function(_pageNum){return{number:_pageNum+1,value:_pageNum,offset:_pageNum*scope._getOptionFromParams("limit"),stopPropagation:!1}},scope._createPagesArr=function(_totalCount){scope.pagesArr=[];for(var i=0;i<_totalCount;i++)scope.pagesArr.push(scope._createPageObj(i))},scope._setCurrentPage=function(pageDataObj){scope.currentPage=pageDataObj},scope._getCurrentPage=function(){return!scope.currentPage&&scope.pagesArr.length>0?scope.currentPage=scope.pagesArr[0]:scope.currentPage||scope.pagesArr.length||(scope.pagesArr.push(scope._createPageObj(0)),scope.currentPage=scope.pagesArr[0]),scope.currentPage},scope._isFirstPage=function(){return 0===scope._getCurrentPage().value},scope._isLastPage=function(){return scope.currentPage.value===scope.pagesArr.length-1},scope._previousPage=function(){scope.currentPage=scope.pagesArr[scope.currentPage.value-1]},scope._nextPage=function(){scope.currentPage=scope.pagesArr[scope.currentPage.value+1]},scope._calcPagination=function(newValue){scope.pagesArr=[];var count=scope._getCountFromMeta(newValue);if(0==count)return scope.pagesArr.push(scope._createPageObj(0)),!1;scope._createPagesArr(scope._calcTotalPages(count,scope._getOptionFromParams("limit")))},scope._resetFilter=function(schemaDataObj){if(!schemaDataObj)return!1;scope.filter={viewBy:schemaDataObj.field[0].name||"",prop:schemaDataObj.field[0].name||"",type:schemaDataObj.field[0].type||"",props:schemaDataObj.field[0],value:null}},scope._isFiltered=function(){return scope.filteredRecords},scope._createFilterParams=function(){var param="";switch(scope.filter.prop.type){case"boolean":param=scope.filter.prop.name+" = "+scope.filter.value;break;case"text":case"string":param=scope.filter.prop.name+' like "%'+scope.filter.value+'%"';break;case"integer":case"float":case"double":case"decimal":param=scope.filter.prop.name+" "+scope.filterType.operator+" "+scope.filter.value}return param},scope._unsetFilterInOptions=function(){scope.options.params.hasOwnProperty("filter")&&delete scope.options.params.filter},scope._setFilterInOptions=function(){return!!scope._checkForFilterValue()&&(scope.options.params.hasOwnProperty("filter"),scope.options.params.filter=scope._createFilterParams(),!0)},scope._checkForFilterValue=function(){return!!scope.filter.value},scope._resetOrder=function(schemaDataObj){if(!schemaDataObj)return!1;scope.order={orderBy:schemaDataObj.field[0].name||"",orderByReverse:!1}},scope._isOrdered=function(){return scope.orderedRecords},scope._createOrderParams=function(){var orderStr=scope.order.orderBy+" ";return orderStr+=scope.order.orderByReverse?"DESC":"ASC"},scope._unsetOrderInOptions=function(){scope.options.params.hasOwnProperty("order")&&delete scope.options.params.order},scope._setOrderInOptions=function(){scope.options.params.hasOwnProperty("order"),scope.options.params.order=scope._createOrderParams()},scope._setChildTableActive=function(stateBool){scope.childTableActive=stateBool},scope._setChildTableParentRecord=function(recordObj){scope.childTableParentRecord=recordObj},scope._buildChildTableOptions=function(){scope.childTableOptions={isChildTable:!0,allowChildTable:!1},scope.childTableOptions=dfObjectService.deepMergeObjects(scope.childTableOptions,angular.copy(scope.defaults))},scope._addChildTable=function(){angular.element(scope.options.childTableAttachPoint).append($compile('')(scope))},scope._setTab=function(tabStr){scope._setElementActive(tabStr)},scope._toggleSelected=function(dataObj){scope._toggleSelectedState(dataObj)},scope._normalizeData=function(dataObj){return angular.forEach(dataObj,function(_obj){for(var _key in _obj)null==_obj[_key]&&(_obj[_key]="NULL")}),dataObj},scope._normalizeSchema=function(schemaDataObj,recordsDataArr){var normalizedSchema=[];for(var _key in schemaDataObj.field)recordsDataArr[0].hasOwnProperty(schemaDataObj.field[_key].name)&&normalizedSchema.push(schemaDataObj.field[_key]);return delete schemaDataObj.field,schemaDataObj.field=normalizedSchema,schemaDataObj},scope._getPrevious=function(){scope._previousPage()},scope._getNext=function(){scope._nextPage()},scope._editRecord=function(dataObj){scope._setCurrentEditRecord(dataObj)},scope._saveRecords=function(){scope._setInProgress(!0);var recordsToSave=scope._getRecordsWithState(scope.record,"unsaved",!0);scope._saveRecordsToServer(recordsToSave).then(function(result){angular.forEach(scope.record,function(_obj){scope._isUnsaved(_obj)&&scope._toggleUnsavedState(_obj),scope._isSelected(_obj)&&scope._toggleSelectedState(_obj),scope._hasRevertCopy(_obj)&&scope._removeRevertCopy(_obj)}),scope.$emit(scope.es.alertSuccess,{message:"Records saved."})},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._revertRecords=function(){angular.forEach(scope.record,function(_obj,_index){scope._isUnsaved(_obj)&&scope._hasRevertCopy(scope.record[_index])&&(scope.record[_index]=scope._getRevertCopy(_obj))}),scope.$emit(scope.es.alertSuccess,{message:"Records reverted."})},scope._deleteRecords=function(){var recordsToDelete=scope._getRecordsWithState(scope.record,"selected");scope._deleteRecordsFromServer(recordsToDelete).then(function(result){var requestDataObj={},curPage=scope._getCurrentPage().value,curOffset=scope._getCurrentPage().offset;scope._isLastPage()&&scope.record.length===scope._getRecordsFromData(result).length&&(curOffset-=scope._getOptionFromParams("limit")),requestDataObj.params=dfObjectService.mergeObjects({offset:curOffset},scope.options.params),scope._getRecordsFromServer(requestDataObj).then(function(_result){scope.$emit(scope.es.alertSuccess,{message:"Records deleted."}),scope._prepareRecords(_result),scope._createPagesArr(scope._calcTotalPages(scope._getCountFromMeta(_result),scope._getOptionFromParams("limit"))),curPage>scope.pagesArr.length-1&&0!==curPage&&(curPage-=1,scope.pagesArr[curPage].stopPropagation=!0),scope._setCurrentPage(scope.pagesArr[curPage])},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}})},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._getRecordsWithFilter=function(){var requestDataObj={};requestDataObj.params=dfObjectService.mergeObjects({filter:scope._createFilterParams()},scope.options.params),scope._setInProgress(!0),scope._getRecordsFromServer(requestDataObj).then(function(result){scope._init(dfObjectService.mergeObjects({data:result},scope.options))},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._refreshResults=function(checkUnsavedBool){if((checkUnsavedBool=checkUnsavedBool||!0)&&scope._checkForUnsavedRecords(scope.record)&&!confirm("You have Unsaved records. Continue without saving?"))return!1;var requestDataObj={};requestDataObj.params={offset:0},scope._setInProgress(!0),scope._getRecordsFromServer(requestDataObj).then(function(result){scope._prepareRecords(result),scope._calcPagination(result),scope._setCurrentPage(scope.pagesArr[0])},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._applyFilter=function(){if(scope._checkForUnsavedRecords(scope.record)&&!confirm("You have Unsaved records. Continue without saving?"))return!1;scope._setFilterInOptions()&&(scope.filteredRecords=!0),scope._setOrderInOptions(),scope.orderedRecords=!0;var requestDataObj={};requestDataObj.params={offset:0},scope._setInProgress(!0),scope._getRecordsFromServer(requestDataObj).then(function(result){scope._prepareRecords(result),scope._calcPagination(result),scope._setCurrentPage(scope.pagesArr[0])},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._removeFilter=function(){if(scope._checkForUnsavedRecords(scope.record)&&!confirm("You have Unsaved records. Continue without saving?"))return!1;scope._unsetFilterInOptions(),scope._unsetOrderInOptions(),scope._resetFilter(scope.schema),scope._resetOrder(scope.schema),scope.filteredRecords=!1,scope.orderedRecords=!1;var requestDataObj={};requestDataObj.params={offset:0},scope._setInProgress(!0),scope._getRecordsFromServer(requestDataObj).then(function(result){scope._prepareRecords(result),scope._calcPagination(result),scope._setCurrentPage(scope.pagesArr[0]),scope.filter.prop=scope.schema.field[0]},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope._createRecord=function(){scope._setNewRecordObj()},scope._setExportValue=function(dataObj){scope._setExportValueToParent(dataObj)},scope._toggleExpandEditor=function(){scope.relatedExpand=!scope.relatedExpand},scope._editExportRecord=function(dataObj){scope.options.exportValueOn&&scope.parentRecord&&(scope.relatedExpand?scope.relatedExpand&&!scope.currentEditRecord&&scope._setCurrentEditRecord(dataObj):(scope._setCurrentEditRecord(dataObj),scope._toggleExpandEditor()))},scope._filterRecords=function(){scope.filterOn=!scope.filterOn},scope._toggleAllFields=function(){scope.tableFieldsAll=!scope.tableFieldsAll,angular.forEach(scope.tableFields,function(_obj){"[object Object]"===Object.prototype.toString.call(_obj)&&_obj.hasOwnProperty("active")&&(_obj.active=scope.tableFieldsAll)})},scope._resetAllFields=function(){scope._createFieldsObj(scope.schema.field)},scope._toggleAllRecords=function(){scope.selectedAll=!scope.selectedAll,angular.forEach(scope.record,function(_obj){scope._setSelectedState(_obj,scope.selectedAll)})},scope._showChildTable=function(parentRecordObj){if(scope.childTableActive)return!1;scope._setChildTableActive(!0),scope._setChildTableParentRecord(parentRecordObj),scope._buildChildTableOptions(),scope._addChildTable(),scope._setDisableTableBtnsState(!0)};var watchUserOptions=scope.$watchCollection("userOptions",function(newValue,oldValue){if(!newValue)return!1;scope.options=dfObjectService.deepMergeObjects(newValue,scope.defaults),scope._setActiveView("table"),dfTableCallbacksService.reset()}),watchOptions=scope.$watchCollection("options",function(newValue,oldValue){if(!newValue)return!1;if(!newValue.service)return!1;if(scope.options.exportValueOn&&!scope._exportValue&&scope.parentRecord[scope.exportField.name]){var requestDataObj={};requestDataObj.params={filter:scope.exportField.ref_field+" = "+scope.parentRecord[scope.exportField.name]},scope._getRecordsFromServer(requestDataObj).then(function(result){var record=scope._getRecordsFromData(result)[0];scope._addStateProps(record),scope._exportValue=record,scope.options.params.filter&&delete scope.options.params.filter,newValue.data?(scope._init(newValue),scope._resetFilter(scope.schema),scope._resetOrder(scope.schema)):scope._getRecordsFromServer().then(function(_result){scope._init(_result),scope._resetFilter(scope.schema),scope._resetOrder(scope.schema)},function(_reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:_reject}})},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}})}else newValue.data?(scope._init(newValue),scope._resetFilter(scope.schema),scope._resetOrder(scope.schema)):(scope.options.params.offset=newValue.table!==oldValue.table?0:scope.options.params.offset,scope._getRecordsFromServer().then(function(_result){scope._init(_result),scope._resetFilter(scope.schema),scope._resetOrder(scope.schema)},function(_reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:_reject}}))}),watchCurrentPage=scope.$watch("currentPage",function(newValue,oldValue){if(newValue.value==oldValue.value)return!1;if(newValue.stopPropagation)return newValue.stopPropagation=!1,!1;if(scope._checkForUnsavedRecords(scope.record)&&!confirm("You have Unsaved records. Continue without saving?"))return oldValue.stopPropagation=!0,scope._setCurrentPage(oldValue),!1;var requestDataObj={};requestDataObj.params={offset:newValue.offset},scope._setInProgress(!0),scope._getRecordsFromServer(requestDataObj).then(function(result){scope._prepareRecords(result)},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})}),watchCurrentEditRecord=scope.$watch("currentEditRecord",function(newValue,oldValue){newValue?(scope._hasRevertCopy(newValue)||scope._createRevertCopy(newValue),scope._filterFormSchema("edit"),scope._buildSchemaGroups(),scope._checkForGroupedSchema("Edit "+scope.schema.name.charAt(0).toUpperCase()+scope.schema.name.slice(1)),scope._setActiveView("edit")):(scope._setActiveView("table"),scope._clearGroupedSchema(),scope._clearFilteredSchema())}),watchCurrentEditRecordState=scope.$watchCollection("currentEditRecord",function(newValue,oldValue){oldValue&&null==newValue&&scope._hasRevertCopy(oldValue)&&(scope._compareObjects(oldValue,oldValue.__dfData.revert)?scope._setUnsavedState(oldValue,!0):scope._setUnsavedState(oldValue,!1))}),watchParentRecord=scope.$watchCollection("parentRecord",function(newValue,oldValue){if(!newValue)return!1;if(!newValue&&!scope._exportValue)return!1;if(null==(!scope._exportValue&&newValue[scope.exportField.name]))return!1;if(!newValue[scope.exportField.name])return scope._exportValue=null,!1;if(!scope._exportValue&&newValue[scope.exportField.name]||scope._exportValue[scope.exportField.ref_field]!==newValue[scope.exportField.name]){var requestDataObj={};return requestDataObj.params={filter:scope.exportField.ref_field+" = "+newValue[scope.exportField.name],offset:0},scope._getRecordsFromServer(requestDataObj).then(function(result){var record=scope._getRecordsFromData(result);if(!record)throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:"Revert related data record not found."};scope._addStateProps(record[0]),scope._exportValue=record[0],scope.options.params.filter&&delete scope.options.params.filter},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}),!1}}),watchExportValue=scope.$watch("_exportValue",function(newValue,oldValue){if(!newValue&&!oldValue)return!1;if(!newValue&&oldValue){scope._setExportState(oldValue,!1);var found=!1,i=0;if(scope.record)for(;!found&&iscope.pagesArr.length-1&&0!==curPage&&(curPage-=1,scope.pagesArr[curPage].stopPropagation=!0),scope._setCurrentPage(scope.pagesArr[curPage]),scope._setCurrentEditRecord(null)},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}})},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._saveRecord=function(){scope._setInProgress(!0),dfTableCallbacksService.run("onUpdate","pre",scope.currentEditRecord),scope._saveRecordToServer(scope.currentEditRecord).then(function(result){scope._removeRevertCopy(scope.currentEditRecord),scope._setUnsavedState(scope.currentEditRecord,!1),dfTableCallbacksService.run("onUpdate","pre",result),scope.$emit(scope.es.alertSuccess,{message:"Record saved."}),scope.options.autoClose?scope._closeEdit():scope._createRevertCopy(scope.currentEditRecord)},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})}}}}]).directive("createRecord",["DF_TABLE_ASSET_PATH","$http","dfTableEventService","dfTableCallbacksService",function(DF_TABLE_ASSET_PATH,$http,dfTableEventService,dfTableCallbacksService){return{restrict:"E",scope:!1,templateUrl:DF_TABLE_ASSET_PATH+"views/create-record.html",link:function(scope,elem,attrs){scope.es=dfTableEventService,scope.closeCreateRecord=function(){scope._closeCreateRecord()},scope.saveNewRecord=function(){scope._saveNewRecord()},scope._setCreateNewRecordNull=function(){scope.newRecord=null},scope._saveNewRecordToServer=function(){return $http({method:"POST",url:scope.options.url,data:{resource:[scope.newRecord]},params:{fields:"*"}})},scope._closeCreateRecord=function(){scope._setCreateNewRecordNull()},scope._saveNewRecord=function(){var dataField,schemaField;for(dataField in scope.newRecord)if(scope.newRecord.hasOwnProperty(dataField)&&null===scope.newRecord[dataField])for(schemaField in scope.tableFields)scope.tableFields.hasOwnProperty(schemaField)&&dataField===schemaField&&scope.tableFields[schemaField].hasOwnProperty("allow_null")&&!scope.tableFields[schemaField].allow_null&&scope.tableFields[schemaField].hasOwnProperty("auto_increment")&&scope.tableFields[schemaField].auto_increment&&delete scope.newRecord[dataField];scope._setInProgress(!0),dfTableCallbacksService.run("onCreate","pre",scope.newRecord),scope._saveNewRecordToServer().then(function(result){dfTableCallbacksService.run("onCreate","post",result),0===scope.record.length?scope._refreshResults():scope.record.length0&&(scope.field.hasOwnProperty("validation")&&null!==scope.field.validation&&scope.field.validation.hasOwnProperty("picklist")?scope.templateData.template="df-input-values-only-picklist.html":scope.templateData.template="df-input-values-picklist.html",scope.data=scope.field.picklist,scope.assignValue=function(itemStr){scope.currentEditRecord[scope.field.name]=itemStr});break;case"boolean":scope.templateData.template="df-input-bool-picklist.html",scope.__dfBools=[{value:!0,name:"TRUE"},{value:!1,name:"FALSE"}],scope.field.allow_null&&scope.__dfBools.unshift({value:"",name:"NULL"});break;case"reference":scope._parseSystemTableName=function(tableNameStr){return"df_sys_"===tableNameStr.substr(0,"df_sys_".length)?tableNameStr.substr("df_sys_".length):tableNameStr},scope._buildURL=function(serviceNameStr,tableNameStr){return INSTANCE_URL.url+"/"+serviceNameStr+"/_table/"+tableNameStr},scope.relatedOptions={service:scope.service,table:scope._parseSystemTableName(scope.field.ref_table),url:scope._buildURL(scope.service,scope._parseSystemTableName(scope.field.ref_table)),params:{filter:null,limit:10,offset:0,fields:"*",include_schema:!0,include_count:!0},defaultFields:{},exportValueOn:!0},scope.relatedOptions.defaultFields[scope.field.ref_field]=!0}elem.append($compile($templateCache.get(scope.templateData.template))(scope))}}}]).directive("dfChildTable",["DF_TABLE_ASSET_PATH","INSTANCE_URL","dfObjectService","dfTableEventService",function(DF_TABLE_ASSET_PATH,INSTANCE_URL,dfObjectService,dfTableEventService){return{restrict:"E",scope:{childOptions:"=",parentSchema:"=",childTableParentRecord:"="},templateUrl:DF_TABLE_ASSET_PATH+"views/df-child-table.html",link:function(scope,elem,attrs){scope.options={},scope.childRecordsBy="",scope.service=scope.childOptions.service,scope.closeChildTable=function(){scope._closeChildTable()},scope._parseSystemTableName=function(tableNameStr){return"df_sys_"===tableNameStr.substr(0,"df_sys_".length)?tableNameStr.substr("df_sys_".length):tableNameStr},scope._setSystemService=function(tableNameStr){return"df_sys_"===tableNameStr.substr(0,"df_sys_".length)?"system":scope.service},scope._closeChildTable=function(){scope.$emit(dfTableEventService.closeChildTable),angular.element(elem).remove()};var watchChildRecordsBy=scope.$watch("childRecordsBy",function(newValue,oldValue){if(!newValue)return!1;var options={service:scope._setSystemService(newValue.ref_table),table:newValue.ref_table,url:INSTANCE_URL.url+"/"+scope._setSystemService(newValue.ref_table)+"/_table/"+scope._parseSystemTableName(newValue.ref_table),params:{filter:newValue.ref_field+" = "+scope.childTableParentRecord[newValue.field]}};scope.options=dfObjectService.deepMergeObjects(options,scope.childOptions)});scope.$on("$destroy",function(e){watchChildRecordsBy()})}}}]).service("dfTableEventService",[function(){return{alertSuccess:"alert:success",refreshTable:"refresh:table",closeChildTable:"close:childtable"}}]).service("dfTableCallbacksService",[function(){var callbacks={onCreate:{pre:[],post:[]},onDelete:{pre:[],post:[]},onUpdate:{pre:[],post:[]}};return{add:function(actionStr,processStr,method){callbacks[actionStr][processStr].push(method)},run:function(actionStr,processStr,inputRecord){if(0==callbacks[actionStr][processStr].length)return!1;angular.forEach(callbacks[actionStr][processStr],function(value,index){value.call(void 0,inputRecord)})},reset:function(){callbacks={onCreate:{pre:[],post:[]},onDelete:{pre:[],post:[]},onUpdate:{pre:[],post:[]}}}}}]),angular.module("dfHome",["ngRoute","dfUtility","dfApplication","dfHelp"]).constant("MOD_HOME_ROUTER_PATH","/home").constant("MOD_HOME_ASSET_PATH","admin_components/adf-home/").config(["$routeProvider","MOD_HOME_ROUTER_PATH","MOD_HOME_ASSET_PATH",function($routeProvider,MOD_HOME_ROUTER_PATH,MOD_HOME_ASSET_PATH){$routeProvider.when(MOD_HOME_ROUTER_PATH,{templateUrl:MOD_HOME_ASSET_PATH+"views/main.html",controller:"HomeCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("HomeCtrl",["$q","$scope","$sce","dfApplicationData","SystemConfigDataService",function($q,$scope,$sce,dfApplicationData,SystemConfigDataService){$scope.trustUrl=function(url){return $sce.trustAsResourceUrl(url)},$scope.$parent.title="Home",$scope.$parent.titleIcon="home";var links=[{name:"welcome-home",label:"Welcome",template:"admin_components/adf-home/views/welcome.html",attributes:[]},{name:"quickstart-home",label:"Quickstart",template:"admin_components/adf-home/views/quickstart.html",attributes:[]},{name:"resource-home",label:"Resources",template:"admin_components/adf-home/views/resources.html",attributes:[]},{name:"download-home",label:"Download",template:"admin_components/adf-home/views/download.html",attributes:[]}],systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.hasOwnProperty("home_links")&&(links=angular.copy(systemConfig.home_links)),$scope.links=links,angular.forEach($scope.links,function(link){link.label||(link.label=link.name)})}]),angular.module("dfLimit",["ngRoute","dfUtility"]).constant("MOD_LIMIT_ROUTER_PATH","/limits").constant("MOD_LIMIT_ASSET_PATH","admin_components/adf-limit/").config(["$routeProvider","MOD_LIMIT_ROUTER_PATH","MOD_LIMIT_ASSET_PATH",function($routeProvider,MOD_LIMIT_ROUTER_PATH,MOD_LIMIT_ASSET_PATH){$routeProvider.when(MOD_LIMIT_ROUTER_PATH,{templateUrl:MOD_LIMIT_ASSET_PATH+"views/main.html",controller:"LimitCtl",resolve:{checkAdmin:["checkAdminService",function(checkAdminService){return checkAdminService.checkAdmin()}],checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).factory("editLimitService",[function(){return{record:{},recordCopy:{}}}]).controller("LimitCtl",["$rootScope","$scope","$http","dfApplicationData","dfNotify","dfObjectService","$location",function($rootScope,$scope,$http,dfApplicationData,dfNotify,dfObjectService,$location){$scope.$parent.title="Limits",$scope.$parent.titleIcon="minus-circle",$scope.links=[{name:"manage-limits",label:"Manage",path:"manage-limits"},{name:"create-limit",label:"Create",path:"create-limit"}],$scope.instanceTypes=[{value:"instance",name:"Instance"},{value:"instance.user",name:"User"},{value:"instance.each_user",name:"Each User"},{value:"instance.service",name:"Service"},{value:"instance.role",name:"Role"},{value:"instance.user.service",name:"Service by User"},{value:"instance.each_user.service",name:"Service by Each User"},{value:"instance.service.endpoint",name:"Endpoint"},{value:"instance.user.service.endpoint",name:"Endpoint by User"},{value:"instance.each_user.service.endpoint",name:"Endpoint by Each User"}],$scope.limitPeriods=[{value:"minute",name:"Minute"},{value:"hour",name:"Hour"},{value:"day",name:"Day"},{value:"7-day",name:"Week"},{value:"30-day",name:"30 Days"}],$scope.emptySectionOptions={title:"You have no Limits!",text:"Click the button below to get started adding limits. You can always create new limits by clicking the tab located in the section menu to the left.",buttonText:"Create A Limit!",viewLink:$scope.links[1],active:!1},$scope.hidden={users:!0,roles:!0,services:!0,endpoint:!0},$scope.selectType=function(recordType){if(angular.isObject(recordType))switch(recordType.value){case"instance":$scope.hidden={users:!0,roles:!0,services:!0,endpoint:!0};break;case"instance.user":$scope.hidden={users:!1,roles:!0,services:!0,endpoint:!0};break;case"instance.each_user":$scope.hidden={users:!0,roles:!0,services:!0,endpoint:!0};break;case"instance.service":$scope.hidden={users:!0,roles:!0,services:!1,endpoint:!0};break;case"instance.role":$scope.hidden={users:!0,roles:!1,services:!0,endpoint:!0};break;case"instance.user.service":$scope.hidden={users:!1,roles:!0,services:!1,endpoint:!0};break;case"instance.each_user.service":$scope.hidden={users:!0,roles:!0,services:!1,endpoint:!0};break;case"instance.service.endpoint":$scope.hidden={users:!0,roles:!0,services:!1,endpoint:!1};break;case"instance.user.service.endpoint":$scope.hidden={users:!1,roles:!0,services:!1,endpoint:!1};break;case"instance.each_user.service.endpoint":$scope.hidden={users:!0,roles:!0,services:!1,endpoint:!1}}},$scope.$on("$destroy",function(e){$scope.$broadcast("toolbar:paginate:limit:destroy")}),$scope.limitEnabled=!1,$scope.subscription_required=!1,$scope.apiData=null,$scope.loadTabData=function(init){$scope.dataLoading=!0;var apis,newApiData,errorFunc=function(error){var messageOptions={module:"Limits",provider:"dreamfactory",type:"error",message:"There was an error loading data for the Limits tab. Please try refreshing your browser and logging in again."};$location.url("/home"),dfNotify.error(messageOptions)};dfApplicationData.getApiData(["system"]).then(function(response){angular.forEach(response[0].resource,function(value){"limit"===value.name&&($scope.limitEnabled=!0)}),$scope.limitEnabled?(apis=["limit","role","service","user"],dfApplicationData.getApiData(apis).then(function(response){newApiData={},apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData,init&&$scope.$broadcast("toolbar:paginate:limit:load")},errorFunc)):($scope.subscription_required=!0,$scope.links[1].path=$scope.links[0].path)},errorFunc).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(!0)}]).directive("dfManageLimits",["$rootScope","MOD_LIMIT_ASSET_PATH","dfApplicationData","dfNotify","$timeout","editLimitService","$http","INSTANCE_URL",function($rootScope,MOD_LIMIT_ASSET_PATH,dfApplicationData,dfNotify,$timeout,editLimitService,$http,INSTANCE_URL){return{restrict:"E",scope:!1,templateUrl:MOD_LIMIT_ASSET_PATH+"views/df-manage-limits.html",link:function(scope,elem,attrs){var ManagedLimit=function(limitData){return{__dfUI:{selected:!1},record:limitData,recordCopy:limitData}};scope.limits=null,scope.currentEditLimit=editLimitService,scope.fields=[{name:"id",label:"ID",active:!0},{name:"name",label:"Limit Name",active:!0},{name:"type",label:"Limit Type",active:!0},{name:"rate",label:"Limit Rate",active:!0},{name:"percent",label:"Limit Counter",active:!0},{name:"user_id",label:"User",active:!0},{name:"service_id",label:"Service",active:!0},{name:"role_id",label:"Role",active:!0},{name:"active",label:"Active",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedLimits=[],scope.editLimit=function(limit){scope._editLimit(limit)},scope.deleteLimit=function(limit){dfNotify.confirm("Delete "+limit.record.name+"?")&&(scope._deleteLimit(limit),scope.selectAll(!1))},scope.resetCounter=function(limit){dfNotify.confirm("Clear counter for "+limit.record.name+"?")&&scope._deleteLimitCache(limit)},scope.deleteSelectedLimits=function(){dfNotify.confirm("Delete selected limits?")&&scope._deleteSelectedLimits()},scope.resetSelectedLimits=function(){dfNotify.confirm("Reset selected limits?")&&scope._resetSelectedLimits()},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setSelected=function(limit){scope._setSelected(limit)},scope.selectAll=function(checkStatus){scope.selectedLimits.length&&!1===checkStatus&&(scope.selectedLimits=[]),angular.forEach(scope.limits,function(limit){!1===checkStatus?(limit.__dfUI.selected=!1,scope.selectedLimits.splice(limit.record.id,1)):(limit.__dfUI.selected=!0,scope.selectedLimits.push(limit.record.id))})},scope._deleteCacheFromServer=function(requestDataObj){return $http({method:"DELETE",url:INSTANCE_URL.url+"/system/limit_cache",params:requestDataObj.params})},scope._editLimit=function(limit){angular.copy(limit,scope.currentEditLimit);var limitType=limit.record.type,limitPeriod=limit.record.period,userId=limit.record.user_id;scope.currentEditLimit.record.typeObj=scope.instanceTypes.filter(function(obj){return obj.value==limitType})[0],scope.currentEditLimit.recordCopy.typeObj=scope.currentEditLimit.record.typeObj,scope.currentEditLimit.record.periodObj=scope.limitPeriods.filter(function(obj){return obj.value==limitPeriod})[0],scope.currentEditLimit.recordCopy.periodObj=scope.currentEditLimit.record.periodObj,angular.isObject(scope.users)&&(scope.currentEditLimit.record.user_id=scope.users.filter(function(obj){return obj.id==userId})[0],scope.currentEditLimit.recordCopy.user_id=scope.currentEditLimit.record.user_id),scope.selectType(scope.currentEditLimit.record.typeObj)},scope._deleteLimitCache=function(limit){var requestDataObj={params:{ids:limit.record.id}};scope._deleteCacheFromServer(requestDataObj).then(function(result){var messageOptions={module:"Limits",type:"success",provider:"dreamfactory",message:"Limit counter successfully reset."};angular.forEach(limit.record.limit_cache_by_limit_id,function(cache){cache.attempts=0,cache.percent=0}),dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._deleteLimit=function(limit){var requestDataObj={params:{id:limit.record.id}};dfApplicationData.deleteApiData("limit",requestDataObj).$promise.then(function(result){var messageOptions={module:"Limits",type:"success",provider:"dreamfactory",message:"Limit successfully deleted."};dfNotify.success(messageOptions),limit.__dfUI.selected&&scope.setSelected(limit),scope.$broadcast("toolbar:paginate:limit:delete")},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope._setSelected=function(limit){for(var i=0;i"}}]).directive("dfLimitDetails",["MOD_LIMIT_ASSET_PATH","dfApplicationData","dfNotify","dfObjectService","$http","$cookies","UserDataService","$rootScope","editLimitService",function(MOD_LIMIT_ASSET_PATH,dfApplicationData,dfNotify,dfObjectService,$http,$cookies,UserDataService,$rootScope,editLimitService){return{restrict:"E",scope:{limitData:"=?",newLimit:"=newLimit",selectType:"=?",activeView:"=?",apiData:"=?"},templateUrl:MOD_LIMIT_ASSET_PATH+"views/df-limit-details.html",link:function(scope,elem,attrs){var Limit=function(limitData){var _limit={is_active:!0,key_text:null,description:null,name:null,period:null,rate:null,role_id:null,service_id:null,type:null,endpoint:null,user_id:null,cacheData:{}};return limitData=limitData||_limit,{__dfUI:{selected:!1},record:angular.copy(limitData),recordCopy:angular.copy(limitData)}};scope.limit=null,scope.saveData={},scope.currentEditLimit=editLimitService,scope.newLimit&&(scope.currentEditLimit=new Limit),scope.verbs=["GET","POST","PATCH","PUT","DELETE"],scope.dfSimpleHelp={verb:{title:"Limit by Verb ",text:"By default, all verbs will be limited unless a specific verb is selected for the limit type."},endpoint:{title:"Endpoint Limits ",text:'Endpoint limits are combined with a service and follow the same conventions in the API Docs for endpoints. The endpoint created must follow a simple form, such as with db service, "_schema/{table_name}". Anything more detailed will still filter at the table level.'}},scope.saveLimit=function(){scope._validateData()&&(scope.newLimit?scope._saveLimit():scope._updateLimit())},scope.cancelEditor=function(){(dfObjectService.compareObjectsAsJson(scope.currentEditLimit.record,scope.currentEditLimit.recordCopy)||dfNotify.confirmNoSave())&&scope.closeEditor()},scope.closeEditor=function(){scope.currentEditLimit.record={},scope.limit=new Limit,scope.$emit("sidebar-nav:view:reset")},scope._validateData=function(){var checkData=scope.currentEditLimit.record;if(null==checkData.typeObj){options={module:"Limit Create Error",message:"Please select a limit type.",type:"error"};return dfNotify.error(options),!1}if(null===checkData.name||""==checkData.name){options={module:"Limit Create Error",message:"The limit name cannot be blank.",type:"error"};return dfNotify.error(options),!1}if(!angular.isDefined(checkData.typeObj)){options={module:"Limit Create Error",message:"A Limit type must be selected.",type:"error"};return dfNotify.error(options),!1}if(null===checkData.rate||""==checkData.rate){options={module:"Limit Create Error",message:"The limit rate cannot be blank.",type:"error"};return dfNotify.error(options),!1}if(!/^\d+$/.test(checkData.rate)){var options={module:"Limit Create Error",message:"The limit rate must be an integer.",type:"error"};return dfNotify.error(options),!1}return!0},scope._saveLimit=function(){if(scope.saveData=scope._prepareLimitData(),!scope.saveData)return!1;var requestDataObj={params:{fields:"*",related:"service_by_service_id,role_by_role_id,user_by_user_id,limit_cache_by_limit_id"},data:scope.saveData};dfApplicationData.saveApiData("limit",requestDataObj).$promise.then(function(result){var messageOptions={module:"Limits",provider:"dreamfactory",type:"success",message:"Limit saved successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._updateLimit=function(){scope.saveData=scope._prepareLimitData();var requestDataObj={params:{fields:"*",related:"service_by_service_id,role_by_role_id,user_by_user_id,limit_cache_by_limit_id"},data:scope.saveData};dfApplicationData.updateApiData("limit",requestDataObj).$promise.then(function(result){var messageOptions={module:"Limit",provider:"dreamfactory",type:"success",message:"Limit updated successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._prepareLimitData=function(){var saveData=angular.copy(scope.currentEditLimit.record);angular.isObject(saveData.periodObj)&&(saveData.period=saveData.periodObj.value),angular.isObject(saveData.typeObj)&&(saveData.type=saveData.typeObj.value),angular.isObject(saveData.user_by_user_id)&&(saveData.user_id=saveData.user_by_user_id.id),angular.isObject(saveData.role_by_role_id)&&(saveData.role_id=saveData.role_by_role_id.id),angular.isObject(saveData.service_by_service_id)&&(saveData.service_id=saveData.service_by_service_id.id);var endpointTypes=["instance.service.endpoint","instance.user.service.endpoint","instance.each_user.service.endpoint"];return saveData.endpoint&&-1!==endpointTypes.indexOf(saveData.type)||(saveData.endpoint=null),delete saveData.key_text,delete saveData.periodObj,delete saveData.typeObj,delete saveData.user_by_user_id,delete saveData.role_by_role_id,delete saveData.service_by_service_id,delete saveData.limit_cache_by_limit_id,saveData};var watchLimitData=scope.$watch("limitData",function(newValue,oldValue){if(!newValue)return!1;scope.limit=new Limit(newValue)});scope.$on("$destroy",function(e){scope.currentEditLimit.record={},scope.limit=new Limit,watchLimitData()}),scope.dfHelp={}}}}]),angular.module("dfLicenseExpiredBanner",["dfApplication"]).directive("dfLicenseExpiredBanner",["SystemConfigDataService","LicenseDataService",function(SystemConfigDataService,LicenseDataService){return{restrict:"E",templateUrl:"admin_components/adf-license-expired/license-expiry-banner/license-expiry-banner.html",link:function(scope){function updateSubscriptionData(platform){platform&&platform.hasOwnProperty("license")&&LicenseDataService.isLicenseRequiredSubscription(platform.license)?LicenseDataService.getSubscriptionData().then(function(data){scope.subscriptionData=data}):scope.subscriptionData={}}scope.subscriptionData={},scope.hasLicenseExpired=function(){return 401==scope.subscriptionData.status_code},scope.$watch(function(){return SystemConfigDataService.getSystemConfig().platform},function(platform){updateSubscriptionData(platform)})}}}]),angular.module("dfLicenseExpired",["ngRoute"]).config(["$routeProvider",setLicenseExpiredRoute]),angular.module("dfReports",["ngRoute","dfUtility","dfApplication","dfHelp"]).constant("MOD_REPORT_ROUTER_PATH","/reports").constant("MOD_REPORT_ASSET_PATH","admin_components/adf-reports/").config(["$routeProvider","MOD_REPORT_ROUTER_PATH","MOD_REPORT_ASSET_PATH",function($routeProvider,MOD_REPORT_ROUTER_PATH,MOD_REPORT_ASSET_PATH){$routeProvider.when(MOD_REPORT_ROUTER_PATH,{templateUrl:MOD_REPORT_ASSET_PATH+"views/main.html",controller:"ReportsCtrl",resolve:{checkAdmin:["checkAdminService",function(checkAdminService){return checkAdminService.checkAdmin()}],checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("ReportsCtrl",["$rootScope","$scope","dfApplicationData","dfNotify","$location",function($rootScope,$scope,dfApplicationData,dfNotify,$location){$scope.$parent.title="Reports",$scope.links=[{name:"manage-service-reports",label:"Manage service reports",path:"manage-service-reports"}],$scope.emptySearchResult={title:"You have no Reports that match your search criteria!",text:""},$scope.dfLargeHelp={manageReports:{title:"Manage Service Reports",text:"Service reports tell you when each service was created, modified, and deleted."}},$scope.apiData=null,$scope.loadTabData=function(init){$scope.dataLoading=!0;var errorFunc=function(error){var messageOptions={module:"Reports",provider:"dreamfactory",type:"error",message:"To use the Reports tab you must be Root Admin and have GOLD license."};$location.url("/home"),dfNotify.warn(messageOptions)};dfApplicationData.getApiData(["system"]).then(function(response){if(angular.forEach(response[0].resource,function(value){"service_report"===value.name&&($scope.reportsEnabled=!0)}),$scope.reportsEnabled){var apis=["service_report"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData,init&&$scope.$broadcast("toolbar:paginate:service_report:load")},errorFunc)}else $scope.subscription_required=!0},function(error){var messageOptions={module:"Reports",provider:"dreamfactory",type:"error",message:"There was an error loading data for the Reports tab. Please try refreshing your browser and logging in again."};$location.url("/home"),dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(!0)}]).directive("dfManageServiceReports",["$rootScope","MOD_REPORT_ASSET_PATH","dfApplicationData","dfNotify","$location",function($rootScope,MOD_REPORT_ASSET_PATH,dfApplicationData,dfNotify,$location){return{restrict:"E",scope:!1,templateUrl:MOD_REPORT_ASSET_PATH+"views/df-manage-service-reports.html",link:function(scope,elem,attrs){var ManagedServiceReport=function(serviceReportData){return{__dfUI:{selected:!1},record:serviceReportData}};scope.serviceReports=null,scope.fields=[{name:"id",label:"ID",active:!0},{name:"time",label:"Time",active:!0},{name:"service_id",label:"Service Id",active:!0},{name:"service_name",label:"Service Name",active:!0},{name:"user_email",label:"User Email",active:!0},{name:"action",label:"Action",active:!0},{name:"request_method",label:"Request",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedReports=[],scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)};var watchApiData=scope.$watchCollection(function(){return dfApplicationData.getApiDataFromCache("service_report")},function(newValue,oldValue){var _serviceReports=[];newValue&&angular.forEach(newValue,function(serviceReport){_serviceReports.push(new ManagedServiceReport(serviceReport))}),scope.serviceReports=_serviceReports});scope.$on("$destroy",function(e){watchApiData(),scope.$broadcast("toolbar:paginate:service_report:reset")})}}}]).directive("dfReportsLoading",[function(){return{restrict:"E",template:"
"}}]),angular.module("dfScheduler",["ngRoute","dfUtility"]).constant("MOD_SCHEDULER_ROUTER_PATH","/scheduler").constant("MOD_SCHEDULER_ASSET_PATH","admin_components/adf-scheduler/").config(["$routeProvider","MOD_SCHEDULER_ROUTER_PATH","MOD_SCHEDULER_ASSET_PATH",function($routeProvider,MOD_SCHEDULER_ROUTER_PATH,MOD_SCHEDULER_ASSET_PATH){$routeProvider.when(MOD_SCHEDULER_ROUTER_PATH,{templateUrl:MOD_SCHEDULER_ASSET_PATH+"views/main.html",controller:"SchedulerCtrl",resolve:{checkAdmin:["checkAdminService",function(checkAdminService){return checkAdminService.checkAdmin()}],checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("SchedulerCtrl",["$rootScope","$scope","dfApplicationData","dfNotify","$location",function($rootScope,$scope,dfApplicationData,dfNotify,$location){$scope.$parent.title="Scheduler",$scope.$parent.titleIcon="clock-o",$scope.links=[{name:"manage-tasks",label:"Manage",path:"manage-tasks"},{name:"create-task",label:"Create",path:"create-task"}],$scope.emptySectionOptions={title:"You have no Scheduler Tasks!",text:'Click the button below to get started building your first Scheduler Task. You can always create new tasks by clicking the "Create" tab located in the section menu to the left.',buttonText:"Create A Scheduler Task!",viewLink:$scope.links[1]},$scope.$on("$destroy",function(e){$scope.$broadcast("toolbar:paginate:scheduler:destroy")}),$scope.schedulerEnabled=!1,$scope.subscription_required=!1,$scope.apiData=null,$scope.loadTabData=function(init){$scope.dataLoading=!0;var errorFunc=function(error){var msg="There was an error loading data for the Scheduler tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Scheduler tab your role must allow GET access to system/scheduler. To create, update, or delete scheduled tasks you need POST, PUT, DELETE access to /system/scheduler and/or /system/scheduler/*.",$location.url("/home"));var messageOptions={module:"Scheduler",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions)};dfApplicationData.getApiData(["system"]).then(function(response){if(angular.forEach(response[0].resource,function(value){"scheduler"===value.name&&($scope.schedulerEnabled=!0)}),$scope.schedulerEnabled){var apis=["scheduler","service_list"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData,$scope.services=newApiData.service_list,init&&$scope.$broadcast("toolbar:paginate:scheduler:load")},errorFunc)}else $scope.subscription_required=!0,$scope.links[1].path=$scope.links[0].path},errorFunc).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(!0)}]).directive("dfManageTasks",["$rootScope","MOD_SCHEDULER_ASSET_PATH","dfApplicationData","dfNotify",function($rootScope,MOD_SCHEDULER_ASSET_PATH,dfApplicationData,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_SCHEDULER_ASSET_PATH+"views/df-manage-tasks.html",link:function(scope,elem,attrs){$rootScope.schedulerEnabled&&angular.forEach(scope.apiData.service_list,function(svc){svc.components||(svc.components=["","*"])});var ManagedTask=function(taskData){return taskData.service_name=scope._getService(taskData.service_id).name,taskData.service=scope._getService(taskData.service_id),taskData.frequency=parseInt(taskData.frequency),taskData.hasOwnProperty("task_log_by_task_id")&&taskData.task_log_by_task_id?taskData.has_log=!0:taskData.has_log=!1,{__dfUI:{selected:!1},record:taskData}};scope.tasks=null,scope.currentEditTask=null,scope.fields=[{name:"id",label:"Id",active:!0},{name:"name",label:"Name",active:!0},{name:"description",label:"Description",active:!0},{name:"is_active",label:"Active",active:!0},{name:"service_name",label:"Service",active:!0},{name:"component",label:"Component",active:!0},{name:"verb",label:"Method",active:!0},{name:"frequency",label:"Frequency",active:!0},{name:"has_log",label:"Log",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedTasks=[],scope.editTask=function(task){scope._editTask(task)},scope.deleteTask=function(task){dfNotify.confirm("Delete "+task.record.name+"?")&&scope._deleteTask(task)},scope.deleteSelectedTasks=function(){dfNotify.confirm("Delete selected tasks?")&&scope._deleteSelectedTasks()},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setSelected=function(task){scope._setSelected(task)},scope._editTask=function(task){scope.currentEditTask=task},scope._getService=function(serviceId){for(var i=0;i"}}]).directive("dfTaskDetails",["MOD_SCHEDULER_ASSET_PATH","dfApplicationData","dfNotify","dfObjectService","$timeout",function(MOD_SCHEDULER_ASSET_PATH,dfApplicationData,dfNotify,dfObjectService,$timeout){return{restrict:"E",scope:{taskData:"=?",newTask:"=?",apiData:"=?"},templateUrl:MOD_SCHEDULER_ASSET_PATH+"views/df-task-details.html",link:function(scope,elem,attrs){var Task=function(taskData){var newTask={name:null,description:null,is_active:!0,service_id:null,component:null,id:null,verb_mask:1,verb:"GET",frequency:1};return taskData=taskData||newTask,{__dfUI:{selected:!1},record:angular.copy(taskData),recordCopy:angular.copy(taskData)}};scope.basicInfoError=!1,scope.task=null,scope.isBasicTab=!0,scope.taskErrorEditorObj={editor:null},scope.newTask&&(scope.task=new Task),scope.saveTask=function(){scope.newTask?scope._saveTask():scope._updateTask()},scope.deleteTask=function(){scope._deleteTask()},scope.cancelEditor=function(){scope._prepareTaskData(),(dfObjectService.compareObjectsAsJson(scope.task.record,scope.task.recordCopy)||dfNotify.confirmNoSave())&&scope.closeEditor()},scope._prepareTaskData=function(){if(scope.task.record.name)if(scope.basicInfoError=!1,scope.task.record.service_id&&scope.task.record.service)scope.prepareTaskPayload();else{scope.noServiceIdError=!0;var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:"Service is required."};dfNotify.error(messageOptions)}else scope.basicInfoError=!0},scope.prepareTaskPayload=function(){"GET"!==scope.task.record.verb?scope.task.record.payload=scope.taskPayloadEditorObj.editor.getValue():scope.task.record.payload=null},scope.refreshTaskEditor=function($event){scope.isBasicTab="basic-tab"===$event.target.id},scope.refreshTaskConfigEditor=function(){$timeout(function(){angular.element("#config-tab").trigger("click")})},scope.closeEditor=function(){scope.taskData=null,scope.task=new Task,$timeout(function(){angular.element("#basic-tab").trigger("click")}),scope.basicInfoError=!1,scope.$emit("sidebar-nav:view:reset")},scope._saveTask=function(){scope._prepareTaskData();var requestDataObj={params:{fields:"*"},data:scope.task.record};dfApplicationData.saveApiData("scheduler",requestDataObj).$promise.then(function(result){var messageOptions={module:"Scheduler",type:"success",provider:"dreamfactory",message:"Scheduler task saved successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var msg=reject.data.message,messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._updateTask=function(){scope._prepareTaskData();var requestDataObj={params:{fields:"*"},data:scope.task.record};dfApplicationData.updateApiData("scheduler",requestDataObj).$promise.then(function(result){scope.task=new Task(result);var messageOptions={module:"Scheduler",type:"success",provider:"dreamfactory",message:"Scheduler task updated successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var msg=reject.data.message,messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._deleteTask=function(){var requestDataObj={params:{},data:scope.task.record};dfApplicationData.deleteApiData("scheduler",requestDataObj).$promise.then(function(result){var messageOptions={module:"Scheduler",type:"success",provider:"dreamfactory",message:"Scheduler task successfully deleted."};dfNotify.success(messageOptions),scope.task=null},function(reject){var msg=reject.data.message,messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})};var watchTaskData=scope.$watch("taskData",function(newValue,oldValue){newValue&&!scope.newTask&&(scope.task=new Task(newValue))}),watchServiceData=scope.$watchCollection("apiData.service_list",function(newValue,oldValue){newValue&&(scope.services=angular.copy(newValue),angular.forEach(scope.services,function(svc){svc.components||(svc.components=["","*"])}))});scope.$on("$destroy",function(e){watchTaskData(),watchServiceData()}),scope.dfSimpleHelp={taskConfig:{title:"Scheduler Task Config",text:"Create or update Scheduler tasks configs for DreamFactory."}},scope.dfLargeHelp={basic:{title:"Scheduler Task Overview",text:"Scheduler task provide a way to schedule requests to the platform."},config:{title:"Scheduler Task Config",text:"Use this interface to configure scheduled calls for an API endpoint."},log:{title:"Scheduler Task Log",text:"This interface displays the scheduler task error log."}}}}}]).directive("schedulerTaskConfig",["MOD_SCHEDULER_ASSET_PATH","INSTANCE_URL","$http","dfNotify",function(MOD_SCHEDULER_ASSET_PATH,INSTANCE_URL,$http,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_SCHEDULER_ASSET_PATH+"views/df-task-config.html",link:function(scope,elem,attrs){scope.verbs={GET:{name:"GET",active:!1,description:" (read)",mask:1},POST:{name:"POST",active:!1,description:" (create)",mask:2},PUT:{name:"PUT",active:!1,description:" (replace)",mask:4},PATCH:{name:"PATCH",active:!1,description:" (update)",mask:8},DELETE:{name:"DELETE",active:!1,description:" (remove)",mask:16}},scope.taskPayloadEditorObj={editor:null},scope.taskPayloadUpdateCounter=0,scope._toggleVerbState=function(nameStr,event){void 0!==event&&event.stopPropagation(),scope.task.record.verb_mask=scope.verbs[nameStr].mask,scope.task.record.verb=nameStr,scope.task.record.payload=scope.taskPayloadEditorObj.editor.getValue(),document.getElementById("task_verb_picker").click()},scope._getComponents=function(){var name=scope.task.record.service.name;return $http.get(INSTANCE_URL.url+"/"+name+"/?as_access_list=true")};var watchTaskService=scope.$watch("task.record.service",function(newValue,oldValue){if(!newValue&&!scope.task)return!1;if(!newValue)return scope.task.record.service_id=null,void(scope.task.record.service_name=null);scope.task.record.service_id=newValue.id,scope.task.record.service_name=newValue.name;var components=["","*"];scope._getComponents().then(function(result){components=result.data.resource,scope.task.__dfUI.hasError=!1},function(reject){scope.task.__dfUI.hasError=!0,scope.task.record.component=null;var messageOptions={module:"Scheduler",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.task.record.service.components=components})}),watchServiceData=scope.$watchCollection("apiData.service_list",function(newValue,oldValue){newValue&&(scope.services=angular.copy(newValue),angular.forEach(scope.services,function(svc){svc.components||(svc.components=["","*"])}))});scope.$on("$destroy",function(newValue,oldValue){watchTaskService(),watchServiceData()})}}}]),angular.module("dreamfactoryApp",["ngAnimate","ngCookies","ngResource","ngRoute","ngSanitize","ngTouch","dfUtility","dfHome","dfSystemConfig","dfAdmins","dfUsers","dfApps","dfData","dfServices","dfRoles","dfSchema","dfUserManagement","dfScripts","dfProfile","dfApplication","dfHelp","dfLaunchPad","dfApiDocs","dfFileManager","dfPackageManager","dfLimit","dfLicenseExpired","dfLicenseExpiredBanner","dfLimit","dfReports","dfScheduler"]).factory("checkUserService",function($location,$q,SystemConfigDataService){return{checkUser:function(){var deferred=$q.defer(),systemConfig=SystemConfigDataService.getSystemConfig(),result=!1;return systemConfig&&(result=systemConfig.apps&&systemConfig.apps.filter(function(item){return"admin"===item.name}).length>0),result?deferred.resolve():($location.url("/launchpad"),deferred.reject()),deferred.promise}}}).factory("checkAdminService",function($q,UserDataService,$location){return{checkAdmin:function(){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();return currentUser&¤tUser.is_sys_admin?deferred.resolve():($location.url("/launchpad"),deferred.reject()),deferred.promise}}}).factory("allowAdminAccess",function(SystemConfigDataService){return{get:function(){var result=!1,systemConfig=SystemConfigDataService.getSystemConfig();return systemConfig&&(result=systemConfig.apps&&systemConfig.apps.filter(function(item){return"admin"===item.name}).length>0),result}}}).constant("APP_VERSION","4.12.0").constant("INSTANCE_BASE_URL","").constant("INSTANCE_API_PREFIX","/api/v2").service("INSTANCE_URL",["INSTANCE_BASE_URL","INSTANCE_API_PREFIX",function(INSTANCE_BASE_URL,INSTANCE_API_PREFIX){this.url=INSTANCE_BASE_URL+INSTANCE_API_PREFIX}]).constant("APP_API_KEY","6498a8ad1beb9d84d63035c5d1120c007fad6de706734db9689f8996707e0f7d").config(["$httpProvider","APP_API_KEY",function($httpProvider,APP_API_KEY){$httpProvider.defaults.headers.common["X-Dreamfactory-API-Key"]=APP_API_KEY,$httpProvider.defaults.headers.delete={"Content-Type":"application/json;charset=utf-8"}}]).config(["$routeProvider","$locationProvider","$httpProvider","$qProvider",function($routeProvider,$locationProvider,$httpProvider,$qProvider){$locationProvider.hashPrefix(""),$routeProvider.when("/login",{controller:"LoginCtrl",templateUrl:"views/login.html",resolve:{checkOtherRoute:["$q","UserDataService","$location","SystemConfigDataService",function($q,UserDataService,$location,SystemConfigDataService){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();if(currentUser&¤tUser.session_token){if(currentUser.is_sys_admin){var systemConfig=SystemConfigDataService.getSystemConfig();"user@example.com"===currentUser.email&&systemConfig&&systemConfig.platform&&systemConfig.platform.hasOwnProperty("bitnami_demo")&&!systemConfig.platform.bitnami_demo?$location.url("/profile"):$location.url("/home")}else $location.url("/launchpad");deferred.reject()}else deferred.resolve();return deferred.promise}]}}).when("/logout",{templateUrl:"views/logout.html",controller:"LogoutCtrl"}).when("/register",{templateUrl:"views/register.html",controller:"RegisterCtrl",resolve:{checkRegisterRoute:["$q","UserDataService","$location","SystemConfigDataService",function($q,UserDataService,$location,SystemConfigDataService){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();if(currentUser)currentUser.is_sys_admin?$location.url("/home"):$location.url("/launchpad"),deferred.reject();else{var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("allow_open_registration")&&systemConfig.authentication.allow_open_registration?deferred.resolve():($location.url("/login"),deferred.reject())}return deferred.promise}]}}).when("/register-complete",{templateUrl:"views/register-complete.html",controller:"RegisterCompleteCtrl",resolve:{checkRegisterCompleteRoute:["$q","UserDataService","$location","SystemConfigDataService",function($q,UserDataService,$location,SystemConfigDataService){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();if(currentUser)currentUser.is_sys_admin?$location.url("/home"):$location.url("/launchpad"),deferred.reject();else{var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("allow_open_registration")&&systemConfig.authentication.allow_open_registration?deferred.resolve():($location.url("/login"),deferred.reject())}return deferred.promise}]}}).when("/register-confirm",{templateUrl:"views/register-confirm.html",controller:"RegisterConfirmCtrl",resolve:{checkRegisterConfirmRoute:["$q","UserDataService","$location","SystemConfigDataService",function($q,UserDataService,$location,SystemConfigDataService){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();if(currentUser)currentUser.is_sys_admin?$location.url("/home"):$location.url("/launchpad"),deferred.reject();else{var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("allow_open_registration")&&systemConfig.authentication.allow_open_registration?deferred.resolve():($location.url("/login"),deferred.reject())}return deferred.promise}]}}).when("/reset-password",{templateUrl:"views/reset-password-email.html",controller:"ResetPasswordEmailCtrl",resolve:{checkResetPasswordRoute:["$q","UserDataService","$location",function($q,UserDataService,$location){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();return currentUser?(currentUser.is_sys_admin?$location.url("/home"):$location.url("/launchpad"),deferred.reject()):deferred.resolve(),deferred.promise}]}}).when("/user-invite",{templateUrl:"views/user-invite.html",controller:"UserInviteCtrl",resolve:{checkUserInviteRoute:["$q","UserDataService","$location",function($q,UserDataService,$location){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();return currentUser?(currentUser.is_sys_admin?$location.url("/home"):$location.url("/launchpad"),deferred.reject()):deferred.resolve(),deferred.promise}]}}).otherwise({controller:"LoginCtrl",templateUrl:"views/login.html",resolve:{checkOtherRoute:["$q","UserDataService","$location","SystemConfigDataService",function($q,UserDataService,$location,SystemConfigDataService){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();if(currentUser&¤tUser.session_token)if(currentUser.is_sys_admin){var systemConfig=SystemConfigDataService.getSystemConfig();"user@example.com"===currentUser.email&&systemConfig&&systemConfig.platform.hasOwnProperty("bitnami_demo")&&!systemConfig.platform.bitnami_demo?$location.url("/profile"):$location.url("/home")}else $location.url("/launchpad");else $location.url("/login");return deferred.reject(),deferred.promise}]}}),$httpProvider.interceptors.push("httpValidSession")}]).config(["$provide",function($provide){$provide.decorator("$exceptionHandler",["$delegate","$injector",function($delegate,$injector){return function(exception,foo){if("string"==typeof exception){var prefix="Possibly unhandled rejection: ";0===exception.indexOf(prefix)&&(exception=angular.fromJson(exception.slice(prefix.length)))}if(!exception.provider||"dreamfactory"!==exception.provider)return $delegate(exception);$injector.invoke(["dfNotify",function(dfNotify){var messageOptions={module:exception.module,type:exception.type,provider:exception.provider,message:exception.exception};dfNotify.error(messageOptions)}])}}])}]),angular.module("dreamfactoryApp").controller("MainCtrl",["$scope","UserDataService","SystemConfigDataService","$location","dfApplicationData","dfNotify","dfIconService","allowAdminAccess","$animate","$http","INSTANCE_URL",function($scope,UserDataService,SystemConfigDataService,$location,dfApplicationData,dfNotify,dfIconService,allowAdminAccess,$animate,$http,INSTANCE_URL){function isCurrentUserRootAdmin(){return $scope.currentUser.hasOwnProperty("is_root_admin")&&$scope.currentUser.is_sys_admin&&$scope.currentUser.is_root_admin}function splitSchemaDataTab(accessibleTabs,schemaDataIndex){var schemaDataArr=accessibleTabs[schemaDataIndex].split("/");return accessibleTabs.splice(schemaDataIndex,1,schemaDataArr[0],schemaDataArr[1]),accessibleTabs}function getConfigTabInsertIndex(accessibleLinks,tabsLinks){var scriptsTabIndex=accessibleLinks.indexOf(tabsLinks.scripts),packagesTabIndex=accessibleLinks.indexOf(tabsLinks.packages);return-1!==scriptsTabIndex||-1!==packagesTabIndex?-1!==scriptsTabIndex?scriptsTabIndex+1:packagesTabIndex:accessibleLinks.length}function addDefaultTab(accessibleLinks,tabsLinks,tabName){switch(tabName){case"home":accessibleLinks.unshift(tabsLinks[tabName]);break;case"config":-1===accessibleLinks.indexOf(tabsLinks[tabName])&&accessibleLinks.splice(getConfigTabInsertIndex(accessibleLinks,tabsLinks),0,tabsLinks[tabName])}return accessibleLinks}function getAccessibleLinks(tabsLinks,accessibleTabs){var accessibleLinks=addDefaultTab([],tabsLinks,"home");return accessibleTabs.forEach(function(tab){accessibleLinks.push(tabsLinks[tab])}),accessibleLinks=addDefaultTab(accessibleLinks,tabsLinks,"config")}$animate.enabled(!1),$scope.title="",$scope.currentUser=UserDataService.getCurrentUser(),$scope.topLevelLinks=[{path:"https://www.dreamfactory.com/products/",target:"_blank",label:"Subscribe",name:"upgrade",icon:dfIconService().upgrade,show:!0},{path:"#/launchpad",target:null,label:"LaunchPad",name:"launchpad",icon:dfIconService().launchpad,show:!1},{path:"#/home",target:null,label:"Admin",name:"admin",icon:dfIconService().admin,show:!1},{path:"#/login",target:null,label:"Login",name:"login",icon:dfIconService().login,show:!1},{path:"#/register",target:null,label:"Register",name:"register",icon:dfIconService().register,show:!1},{path:null,target:null,label:UserDataService.getCurrentUser().name,name:"user",icon:dfIconService().user,show:!1,subLinks:[{path:"#/profile",target:null,label:"Profile",name:"profile",icon:null,show:!1},{path:"#/logout",target:null,label:"Logout",name:"logout",icon:null,show:!1}]}],$scope.topLevelNavOptions={links:$scope.topLevelLinks},$scope.showAdminComponentNav=!1,$scope.showHeader=!0,$scope.showLicenseExpiredBanner=!0;var navLinks={home:{name:"home",label:"Home",path:"/home"},services:{name:"services",label:"Services",path:"/services"},apps:{name:"apps",label:"Apps",path:"/apps"},admins:{name:"admins",label:"Admins",path:"/admins"},users:{name:"users",label:"Users",path:"/users"},roles:{name:"roles",label:"Roles",path:"/roles"},apidocs:{name:"apidocs",label:"API Docs",path:"/apidocs"},schema:{name:"schema",label:"Schema",path:"/schema"},data:{name:"data",label:"Data",path:"/data"},files:{name:"file-manager",label:"Files",path:"/file-manager"},scripts:{name:"scripts",label:"Scripts",path:"/scripts"},config:{name:"config",label:"Config",path:"/config"},packages:{name:"package-manager",label:"Packages",path:"/package-manager"},limits:{name:"limits",label:"Limits",path:"/limits"},scheduler:{name:"scheduler",label:"Scheduler",path:"/scheduler"}};$scope._setComponentLinks=function(isAdmin){var links=angular.copy(navLinks);isAdmin?$scope.currentUser.role_id?$scope._setAccessibleLinks(links):!dfApplicationData.isGoldLicense()||isCurrentUserRootAdmin()?(links.reports={name:"reports",label:"Reports",path:"/reports"},$scope.componentNavOptions={links:Object.values(links)}):dfApplicationData.isGoldLicense()&&(delete links.admins,$scope.doesRootAdminExist(),$scope.componentNavOptions={links:Object.values(links)}):(delete links.admins,delete links.roles,delete links.limits,delete links.scheduler,$scope.componentNavOptions={links:Object.values(links)})},$scope._setAccessibleLinks=function(tabsLinks){delete tabsLinks.roles,$http.get(INSTANCE_URL.url+"/system/role/"+$scope.currentUser.role_id+"?related=role_service_access_by_role_id&accessible_tabs=true").then(function(result){if(result&&result.data.hasOwnProperty("accessible_tabs")){var accessibleTabs=result.data.accessible_tabs,schemaDataIndex=accessibleTabs.indexOf("schema/data");-1!==schemaDataIndex&&(accessibleTabs=splitSchemaDataTab(accessibleTabs,schemaDataIndex)),$scope.componentNavOptions={links:getAccessibleLinks(tabsLinks,accessibleTabs)}}else $scope.componentNavOptions={links:Object.values(tabsLinks)}},function(result){UserDataService.unsetCurrentUser(),$location.url("/login"),console.error(result)})},$scope.doesRootAdminExist=function(){var systemConfig=SystemConfigDataService.getSystemConfig();if(!(systemConfig.hasOwnProperty("platform")&&systemConfig.platform.hasOwnProperty("root_admin_exists")&&systemConfig.platform.root_admin_exists)){var messageOptions={module:"Admins",provider:"dreamfactory",type:"error",message:"There is no root administrator selected. Some functionality might not work. Use df:root_admin command to choose one."};dfNotify.error(messageOptions)}},$scope._setActiveLinks=function(linksArr,activeLinksArr){var found,i;angular.forEach(linksArr,function(link){for(found=!1,i=0;i0&&links.push("launchpad"),systemConfig.hasOwnProperty("platform")&&links.push("upgrade")),newValue?($scope.setTopLevelLinkValue("user","label",newValue.name),links.push("user")):(links.push("login"),systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("allow_open_registration")&&systemConfig.authentication.allow_open_registration&&links.push("register")),allowAdminAccess.get()&&links.push("admin"),$scope._setActiveLinks($scope.topLevelLinks,links),$scope._setComponentLinks(newValue&&newValue.is_sys_admin)}),$scope.$watch(function(){return UserDataService.getCurrentUser().name},function(n,o){n&&$scope.setTopLevelLinkValue("user","label",n)}),$scope.$on("$routeChangeSuccess",function(e){switch($scope.showHeader=!0,$scope.showLicenseExpiredBanner=!0,$location.path()){case"/home":case"/apps":case"/admins":case"/users":case"/roles":case"/services":case"/apidocs":case"/schema":case"/data":case"/file-manager":case"/scripts":case"/config":case"/package-manager":case"/limits":case"/reports":case"/scheduler":$scope.showAdminComponentNav=!0;break;case"/license-expired":$scope.showHeader=!1,$scope.showLicenseExpiredBanner=!1,$scope.showAdminComponentNav=!1;break;default:$scope.showAdminComponentNav=!1}})}]).controller("LoginCtrl",["$scope","$window","$location","$timeout","UserDataService","UserEventsService","dfApplicationData","SystemConfigDataService","dfNotify",function($scope,$window,$location,$timeout,UserDataService,UserEventsService,dfApplicationData,SystemConfigDataService,dfNotify){$scope.loginOptions={showTemplate:!0},$scope.$on(UserEventsService.password.passwordSetSuccess,function(e,userCredsObj){var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"Password reset successful."};dfNotify.success(messageOptions),$scope.$broadcast(UserEventsService.login.loginRequest,userCredsObj)}),$scope.$on(UserEventsService.login.loginError,function(e){e.stopPropagation()}),$scope.$on(UserEventsService.login.loginSuccess,function(e,userDataObj){angular.equals($scope.$parent.currentUser,userDataObj)||dfApplicationData.resetApplicationObj(),$scope.$parent.currentUser=userDataObj;var queryString=location.search.substring(1);if($scope.loginOptions.showTemplate=!1,userDataObj.is_sys_admin)if(queryString){uri=$location.absUrl().split("?");$window.location.href=uri[0]+"#/home"}else if(userDataObj.is_sys_admin&&"user@example.com"===userDataObj.email){var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.platform&&systemConfig.platform.hasOwnProperty("bitnami_demo")&&!systemConfig.platform.bitnami_demo?$location.url("/profile"):$location.url("/home")}else $location.url("/home");else if(queryString){var uri=$location.absUrl().split("?");$window.location.href=uri[0]+"#/launchpad"}else $location.url("/launchpad")})}]).controller("LogoutCtrl",["$scope","$location","UserEventsService","dfApplicationData",function($scope,$location,UserEventsService,dfApplicationData){$scope.$on(UserEventsService.logout.logoutSuccess,function(e,userDataObj){$scope.$parent.currentUser=userDataObj,$location.url("/login")})}]).controller("RegisterCtrl",["$scope","$location","UserEventsService","SystemConfigDataService",function($scope,$location,UserEventsService,SystemConfigDataService){var confirmationRequired=!0,systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("open_reg_email_service_id")&&(confirmationRequired=!!systemConfig.authentication.open_reg_email_service_id),$scope.options={confirmationRequired:confirmationRequired},$scope.$on(UserEventsService.register.registerSuccess,function(e,userCredsObj){$scope.$broadcast(UserEventsService.login.loginRequest,userCredsObj)}),$scope.$on(UserEventsService.register.registerConfirmation,function(e){$location.url("/register-complete")}),$scope.$on(UserEventsService.login.loginSuccess,function(e,userDataObj){$scope.$parent.currentUser=userDataObj,$location.url("/launchpad")}),$scope.$on(UserEventsService.login.loginError,function(e){e.stopPropagation()})}]).controller("RegisterCompleteCtrl",["$scope",function($scope){}]).controller("RegisterConfirmCtrl",["$scope","$location","dfApplicationData","UserEventsService","SystemConfigDataService","dfNotify",function($scope,$location,dfApplicationData,UserEventsService,SystemConfigDataService,dfNotify){$scope.confirmOptions={showTemplate:!0,title:"Registration Confirmation"},$scope.loginOptions={showTemplate:!1},$scope.registerLoginErrorMsg="",$scope.inviteType="user",$scope.$on(UserEventsService.confirm.confirmationSuccess,function(e,userCredsObj){$scope.$broadcast(UserEventsService.login.loginRequest,userCredsObj)}),$scope.$on(UserEventsService.login.loginSuccess,function(e,userDataObj){var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"Registration Confirmation successful."};dfNotify.success(messageOptions),$scope.$parent.currentUser=userDataObj,$location.url("/launchpad")}),$scope.$on(UserEventsService.login.loginError,function(e,errMsg){e.stopPropagation(),$scope.registerLoginErrorMsg=errMsg.data.error.message})}]).controller("ResetPasswordEmailCtrl",["$scope","$location","dfApplicationData","UserEventsService","SystemConfigDataService","dfNotify","$timeout",function($scope,$location,dfApplicationData,UserEventsService,SystemConfigDataService,dfNotify,$timeout){$scope.loginOptions={showTemplate:!1},$scope.resetPasswordLoginErrorMsg="",$scope.$on(UserEventsService.password.passwordSetSuccess,function(e,userCredsObj){e.stopPropagation(),$scope.$broadcast(UserEventsService.login.loginRequest,userCredsObj)}),$scope.$on(UserEventsService.login.loginSuccess,function(e,userDataObj){var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"Password reset successful."};if(dfNotify.success(messageOptions),$scope.$parent.currentUser=userDataObj,$scope.loginOptions.showTemplate=!1,userDataObj.is_sys_admin&&"user@example.com"===userDataObj.email){var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.platform&&systemConfig.platform.hasOwnProperty("bitnami_demo")&&!systemConfig.platform.bitnami_demo?$location.url("/profile"):$location.url("/home")}else $location.url("/home")}),$scope.$on(UserEventsService.login.loginError,function(e,errMsg){e.stopPropagation(),$scope.resetPasswordLoginErrorMsg=errMsg.data.error.message})}]).controller("UserInviteCtrl",["$scope","$location","dfApplicationData","UserEventsService","SystemConfigDataService","dfNotify",function($scope,$location,dfApplicationData,UserEventsService,SystemConfigDataService,dfNotify){$scope.confirmOptions={showTemplate:!0,title:"Invitation Confirmation"},$scope.inviteType=1==$location.search().admin?"admin":"user",$scope.loginOptions={showTemplate:!1},$scope.confirmLoginErrorMsg="",$scope.$on(UserEventsService.confirm.confirmationSuccess,function(e,userCredsObj){$scope.$broadcast(UserEventsService.login.loginRequest,userCredsObj)}),$scope.$on(UserEventsService.login.loginSuccess,function(e,userDataObj){var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"User Confirmation successful."};dfNotify.success(messageOptions),$scope.$parent.currentUser=userDataObj,$location.url("/launchpad")}),$scope.$on(UserEventsService.login.loginError,function(e,errMsg){e.stopPropagation(),$scope.confirmLoginErrorMsg=errMsg.data.error.message})}]).controller("PaywallCtrl",["$scope","$http","UserDataService","SystemConfigDataService",function($scope,$http,UserDataService,SystemConfigDataService){$scope.$on("hitPaywall",function(e,data){$scope.sendRequest(data)}),$scope.sendRequest=function(serviceName){var data={email:UserDataService.getCurrentUser().email,ip_address:SystemConfigDataService.getSystemConfig().client.ip_address,service_name:serviceName},req={method:"POST",url:"https://updates.dreamfactory.com/api/paywall",data:JSON.stringify(data)};$http(req).then()}}]),Array.of||(Array.of=function(){return Array.prototype.slice.call(arguments)}),Array.prototype.copyWithin||(Array.prototype.copyWithin=function(target,start){if(null==this)throw new TypeError("this is null or not defined");var O=Object(this),len=O.length>>>0,relativeTarget=target>>0,to=relativeTarget<0?Math.max(len+relativeTarget,0):Math.min(relativeTarget,len),relativeStart=start>>0,from=relativeStart<0?Math.max(len+relativeStart,0):Math.min(relativeStart,len),end=arguments[2],relativeEnd=void 0===end?len:end>>0,final=relativeEnd<0?Math.max(len+relativeEnd,0):Math.min(relativeEnd,len),count=Math.min(final-from,len-to),direction=1;for(from0;)from in O?O[to]=O[from]:delete O[to],from+=direction,to+=direction,count--;return O}),Array.prototype.every||(Array.prototype.every=function(callbackfn,thisArg){var T,k;if(null==this)throw new TypeError("this is null or not defined");var O=Object(this),len=O.length>>>0;if("function"!=typeof callbackfn)throw new TypeError;for(arguments.length>1&&(T=thisArg),k=0;k>>0,relativeStart=arguments[1]>>0,k=relativeStart<0?Math.max(len+relativeStart,0):Math.min(relativeStart,len),end=arguments[2],relativeEnd=void 0===end?len:end>>0,final=relativeEnd<0?Math.max(len+relativeEnd,0):Math.min(relativeEnd,len);k>>0;if("function"!=typeof fun)throw new TypeError;for(var res=[],thisArg=arguments.length>=2?arguments[1]:void 0,i=0;i>>0;if("function"!=typeof predicate)throw new TypeError("predicate must be a function");for(var thisArg=arguments[1],k=0;k>>0;if("function"!=typeof predicate)throw new TypeError("predicate must be a function");for(var thisArg=arguments[1],k=0;k>>0;if("function"!=typeof callback)throw new TypeError(callback+" is not a function");for(arguments.length>1&&(T=arguments[1]),k=0;k>>0;if(0===len)return!1;for(var n=0|fromIndex,k=Math.max(n>=0?n:len-Math.abs(n),0);k>>0;if(0===len)return-1;var n=0|fromIndex;if(n>=len)return-1;for(k=Math.max(n>=0?n:len-Math.abs(n),0);k>>0;if(0===len)return-1;for(n=len-1,arguments.length>1&&((n=Number(arguments[1]))!=n?n=0:0!=n&&n!=1/0&&n!=-1/0&&(n=(n>0||-1)*Math.floor(Math.abs(n)))),k=n>=0?Math.min(n,len-1):len-Math.abs(n);k>=0;k--)if(k in t&&t[k]===searchElement)return k;return-1}),Array.prototype.map||(Array.prototype.map=function(callback){var T,A,k;if(null==this)throw new TypeError("this is null or not defined");var O=Object(this),len=O.length>>>0;if("function"!=typeof callback)throw new TypeError(callback+" is not a function");for(arguments.length>1&&(T=arguments[1]),A=new Array(len),k=0;k>>0,k=0;if(2==arguments.length)value=arguments[1];else{for(;k=len)throw new TypeError("Reduce of empty array with no initial value");value=o[k++]}for(;k>>0)-1;if(arguments.length>=2)value=arguments[1];else{for(;k>=0&&!(k in t);)k--;if(k<0)throw new TypeError("Reduce of empty array with no initial value");value=t[k--]}for(;k>=0;k--)k in t&&(value=callback(value,t[k],k,t));return value}),Array.prototype.some||(Array.prototype.some=function(fun){if(null==this)throw new TypeError("Array.prototype.some called on null or undefined");if("function"!=typeof fun)throw new TypeError;for(var t=Object(this),len=t.length>>>0,thisArg=arguments.length>=2?arguments[1]:void 0,i=0;i>>0;if(0===len)return"";for(var firstElement=a[0],r=null==firstElement?"":firstElement.toLocaleString(locales,options),k=1;k0,scope.selectedService=null,scope.rememberMe=!1,"username"===scope.loginAttribute?scope.userField={icon:"fa-user",text:"Enter Username",type:"text"}:scope.userField={icon:"fa-envelope",text:"Enter Email",type:"email"},scope.rememberLogin=function(checked){scope.rememberMe=checked},scope.useAdLdapService=function(service){scope.selectedService=service,service?(scope.userField={icon:"fa-user",text:"Enter Username",type:"text"},scope.creds={username:"",password:"",service:service}):"username"===scope.loginAttribute?(scope.userField={icon:"fa-user",text:"Enter Username",type:"text"},scope.creds={username:"",password:""}):(scope.userField={icon:"fa-envelope",text:"Enter Email",type:"email"},scope.creds={email:"",password:""})},scope.getQueryParameter=function(key){key=key.replace(/[*+?^$.\[\]{}()|\\\/]/g,"\\$&");var match=window.location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)")),result=match&&decodeURIComponent(match[1].replace(/\+/g," "));return result||""};var token=scope.getQueryParameter("session_token"),oauth_code=scope.getQueryParameter("code"),oauth_state=scope.getQueryParameter("state"),oauth_token=scope.getQueryParameter("oauth_token"),baseUrl=$location.absUrl().split("?")[0];""!==token?(scope.loginWaiting=!0,scope.showOAuth=!1,scope.loginDirect=!0,$http.get(INSTANCE_URL.url+"/user/session?session_token="+token).then(function(result){UserDataService.setCurrentUser(result.data),scope.$emit(scope.es.loginSuccess,result.data),scope.loginDirect=!1},function(result){window.location.href=baseUrl+"#/login",scope.loginDirect=!1})):(oauth_code&&oauth_state||oauth_token)&&(scope.loginWaiting=!0,scope.showOAuth=!1,$http.post(INSTANCE_URL.url+"/user/session?oauth_callback=true&"+location.search.substring(1)).then(function(result){UserDataService.setCurrentUser(result.data),scope.$emit(scope.es.loginSuccess,result.data)})),scope.login=function(credsDataObj){scope.selectedService?(credsDataObj.username=$("#df-login-email").val(),credsDataObj.password=$("#df-login-password").val(),credsDataObj.service=scope.selectedService):"username"===scope.loginAttribute?(credsDataObj.username=$("#df-login-email").val(),credsDataObj.password=$("#df-login-password").val()):""!==credsDataObj.email&&""!==credsDataObj.password||(credsDataObj.email=$("#df-login-email").val(),credsDataObj.password=$("#df-login-password").val()),credsDataObj.remember_me=scope.rememberMe,scope._login(credsDataObj)},scope.forgotPassword=function(){scope._forgotPassword()},scope.skipLogin=function(){scope._skipLogin()},scope.showLoginForm=function(){scope._toggleForms()},scope.dismissError=function(){scope.errorMsg=""},scope.dismissSuccess=function(){scope.successMsg=""},scope._loginRequest=function(credsDataObj,admin){return admin?$http.post(INSTANCE_URL.url+"/system/admin/session",credsDataObj):$http.post(INSTANCE_URL.url+"/user/session",credsDataObj)},scope._toggleFormsState=function(){scope.loginActive=!scope.loginActive,scope.resetPasswordActive=!scope.resetPasswordActive},scope._login=function(credsDataObj){scope.loginWaiting=!0,scope._loginRequest(credsDataObj,!1).then(function(result){UserDataService.setCurrentUser(result.data),scope.$emit(scope.es.loginSuccess,result.data),scope.$root.$emit(scope.es.loginSuccess,result.data)},function(reject){"401"!=reject.status&&"404"!=reject.status||scope.selectedService?(scope.errorMsg=reject.data.error.message,scope.$emit(scope.es.loginError,reject)):(scope.loginWaiting=!0,scope._loginRequest(credsDataObj,!0).then(function(result){UserDataService.setCurrentUser(result.data),scope.$emit(scope.es.loginSuccess,result.data),scope.$root.$emit(scope.es.loginSuccess,result.data)},function(reject){scope.errorMsg=reject.data.error.message,scope.$emit(scope.es.loginError,reject)}).finally(function(){scope.loginWaiting=!1}))}).finally(function(){scope.loginWaiting=!1})},scope._toggleForms=function(){scope._toggleFormsState()},scope._forgotPassword=function(){scope.$broadcast(UserEventsService.password.passwordResetRequest,{email:scope.creds.email})},scope._skipLogin=function(){$location.url("/services")};scope.$watch("options",function(newValue,oldValue){newValue&&newValue.hasOwnProperty("showTemplate")&&(scope.showTemplate=newValue.showTemplate)},!0);scope.$on(scope.es.loginRequest,function(e,userDataObj){scope._login(userDataObj)})}}}]).directive("dreamfactoryForgotPwordEmail",["MODUSRMNGR_ASSET_PATH","INSTANCE_URL","$http","UserEventsService","SystemConfigDataService",function(MODUSRMNGR_ASSET_PATH,INSTANCE_URL,$http,UserEventsService,SystemConfigDataService){return{restrict:"E",replace:!0,scope:!1,templateUrl:MODUSRMNGR_ASSET_PATH+"views/fp-email-conf.html",link:function(scope,elem,attrs){scope.es=UserEventsService.password,scope.emailForm=!0,scope.emailError=!1,scope.securityQuestionForm=!1,scope.hidePasswordField=!1,scope.allowForeverSessions=!1,scope.loginAttribute="email",scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&(scope.systemConfig.authentication.hasOwnProperty("allow_forever_sessions")&&(scope.allowForeverSessions=scope.systemConfig.authentication.allow_forever_sessions),scope.systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=scope.systemConfig.authentication.login_attribute)),scope.resetByEmail=!0,scope.resetByUsername=!1,"username"===scope.loginAttribute&&(scope.resetByEmail=!1,scope.resetByUsername=!0),scope.sq={email:null,username:null,security_question:null,security_answer:null,new_password:null,verify_password:null},scope.identical=!0,scope.requestWaiting=!1,scope.questionWaiting=!1,scope.requestPasswordReset=function(emailDataObj){scope._requestPasswordReset(emailDataObj)},scope.securityQuestionSubmit=function(reset){scope.identical?scope._verifyPasswordLength(reset)?scope._securityQuestionSubmit(reset):scope.errorMsg="Password must be at least 5 characters.":scope.errorMsg="Passwords do not match."},scope.verifyPassword=function(user){scope._verifyPassword(user)},scope._resetPasswordRequest=function(requestDataObj,admin){return admin?$http.post(INSTANCE_URL.url+"/system/admin/password?reset=true",requestDataObj):$http.post(INSTANCE_URL.url+"/user/password?reset=true",requestDataObj)},scope._resetPasswordSQ=function(requestDataObj,admin){return admin?$http.post(INSTANCE_URL.url+"/system/admin/password?login=false",requestDataObj):$http.post(INSTANCE_URL.url+"/user/password?login=false",requestDataObj)},scope._verifyPassword=function(userDataObj){scope.identical=userDataObj.new_password===userDataObj.verify_password},scope._verifyPasswordLength=function(credsDataObj){return credsDataObj.new_password.length>=5},scope._requestPasswordReset=function(requestDataObj){requestDataObj.reset=!0,scope.requestWaiting=!0,scope._resetPasswordRequest(requestDataObj,!1).then(function(result){result.data.hasOwnProperty("security_question")?(scope.emailForm=!1,scope.securityQuestionForm=!0,scope.sq.email=requestDataObj.email,scope.sq.username=requestDataObj.username?requestDataObj.username:null,scope.sq.security_question=result.data.security_question):(scope.successMsg="A password reset email has been sent to the user's email address.",scope.$emit(scope.es.passwordResetRequestSuccess,requestDataObj.email))},function(reject){"401"==reject.status||"404"==reject.status?scope._resetPasswordRequest(requestDataObj,!0).then(function(result){result.data.hasOwnProperty("security_question")?(scope.emailForm=!1,scope.securityQuestionForm=!0,scope.sq.email=requestDataObj.email,scope.sq.security_question=result.data.security_question):(scope.successMsg="A password reset email has been sent to the user's email address.",scope.$emit(scope.es.passwordResetRequestSuccess,requestDataObj.email))},function(reject){scope.errorMsg=reject.data.error.message}).finally(function(){scope.requestWaiting=!1}):scope.errorMsg=reject.data.error.message}).finally(function(){scope.requestWaiting=!1})},scope._securityQuestionSubmit=function(reset){scope.questionWaiting=!0,scope._resetPasswordSQ(reset,!1).then(function(result){var userCredsObj={email:reset.email,username:reset.username?reset.username:null,password:reset.new_password};scope.$emit(UserEventsService.password.passwordSetSuccess,userCredsObj)},function(reject){"401"==reject.status||"404"==reject.status?scope._resetPasswordSQ(reset,!0).then(function(result){var userCredsObj={email:reset.email,password:reset.new_password};scope.$emit(UserEventsService.password.passwordSetSuccess,userCredsObj)},function(reject){scope.questionWaiting=!1,scope.errorMsg=reject.data.error.message,scope.$emit(UserEventsService.password.passwordSetError)}).finally(function(){}):(scope.questionWaiting=!1,scope.errorMsg=reject.data.error.message,scope.$emit(UserEventsService.password.passwordSetError))}).finally(function(){})},scope.$on(UserEventsService.password.passwordResetRequest,function(e,resetDataObj){scope._toggleForms()})}}}]).directive("dreamfactoryForgotPwordQuestion",["MODUSRMNGR_ASSET_PATH",function(MODUSRMNGR_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MODUSRMNGR_ASSET_PATH+"views/fp-security-question.html",link:function(scope,elem,attrs){}}}]).directive("dreamfactoryPasswordReset",["MODUSRMNGR_ASSET_PATH","INSTANCE_URL","$http","UserEventsService","_dfObjectService","dfNotify","$location","SystemConfigDataService",function(MODUSRMNGR_ASSET_PATH,INSTANCE_URL,$http,UserEventsService,_dfObjectService,dfNotify,$location,SystemConfigDataService){return{restrict:"E",scope:{options:"=?",inErrorMsg:"=?"},templateUrl:MODUSRMNGR_ASSET_PATH+"views/password-reset.html",link:function(scope,elem,attrs){scope.es=UserEventsService.password;var defaults={showTemplate:!0,login:!1};scope.options=_dfObjectService.mergeObjects(scope.options,defaults),scope.showTemplate=scope.options.showTemplate,scope.identical=!0,scope.successMsg="",scope.errorMsg="",scope.loginAttribute="email",scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&scope.systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=scope.systemConfig.authentication.login_attribute),scope.resetByEmail=!0,scope.resetByUsername=!1,"username"===scope.loginAttribute&&(scope.resetByEmail=!1,scope.resetByUsername=!0),scope.resetWaiting=!1,scope.user={};var UrlParams=$location.search();Object.keys(UrlParams).forEach(function(key,index){scope.user[key]=UrlParams[key]});var isAdmin="1"==scope.user.admin;scope.dismissError=function(){scope.errorMsg=""},scope.dismissSuccess=function(){scope.successMsg=""},scope.resetPassword=function(credsDataObj){scope.identical?scope._verifyPasswordLength(credsDataObj)?scope._resetPassword(credsDataObj):scope.errorMsg="Password must be at least 5 characters.":scope.errorMsg="Passwords do not match."},scope.verifyPassword=function(user){scope._verifyPassword(user)},scope._setPasswordRequest=function(requestDataObj,admin){var url=INSTANCE_URL.url+"/system/admin/password";return admin||(url=INSTANCE_URL.url+"/user/password"),$http({url:url,method:"POST",params:{login:scope.options.login},data:requestDataObj})},scope._verifyPassword=function(userDataObj){scope.identical=userDataObj.new_password===userDataObj.verify_password},scope._verifyPasswordLength=function(credsDataObj){return credsDataObj.new_password.length>=5},scope._resetPassword=function(credsDataObj){scope.resetWaiting=!0;var requestDataObj={email:credsDataObj.email,username:credsDataObj.username?credsDataObj.username:null,code:credsDataObj.code,new_password:credsDataObj.new_password};scope._setPasswordRequest(requestDataObj,isAdmin).then(function(result){var userCredsObj={email:credsDataObj.email,username:credsDataObj.username?credsDataObj.username:null,password:credsDataObj.new_password};scope.$emit(scope.es.passwordSetSuccess,userCredsObj),scope.showTemplate=!1},function(reject){"401"==reject.status||"404"==reject.status?scope._setPasswordRequest(requestDataObj,!0).then(function(result){var userCredsObj={email:credsDataObj.email,password:credsDataObj.new_password};scope.$emit(scope.es.passwordSetSuccess,userCredsObj),scope.showTemplate=!1},function(reject){scope.errorMsg=reject.data.error.message,scope.$emit(scope.es.passwordSetError),scope.resetWaiting=!1}).finally(function(){scope.resetWaiting=!1}):(scope.errorMsg=reject.data.error.message,scope.$emit(scope.es.passwordSetError),scope.resetWaiting=!1)}).finally(function(){scope.resetWaiting=!1})};var watchInErrorMsg=scope.$watch("inErrorMsg",function(n,o){scope.confirmWaiting=!1,scope.errorMsg=n});scope.$on(scope.es.passwordSetRequest,function(e,credsDataObj){scope._resetPassword(credsDataObj)}),scope.$on("$destroy",function(e){watchInErrorMsg()})}}}]).directive("dreamfactoryUserLogout",["INSTANCE_URL","$http","UserEventsService","UserDataService",function(INSTANCE_URL,$http,UserEventsService,UserDataService){return{restrict:"E",scope:{},link:function(scope,elem,attrs){scope.es=UserEventsService.logout,scope._logoutRequest=function(admin){var url=UserDataService.getCurrentUser().is_sys_admin?"/system/admin/session":"/user/session";return $http.delete(INSTANCE_URL.url+url)},scope._logout=function(){scope._logoutRequest(!1).then(function(){UserDataService.unsetCurrentUser(),scope.$emit(scope.es.logoutSuccess,!1)},function(reject){if("401"!=reject.status&&"401"!=reject.data.error.code)throw{module:"DreamFactory User Management",type:"error",provider:"dreamfactory",exception:reject};UserDataService.unsetCurrentUser(),scope.$emit(scope.es.logoutSuccess,!1)})},scope.$on(scope.es.logoutRequest,function(e){scope._logout()}),scope._logout()}}}]).directive("dreamfactoryRegisterUser",["MODUSRMNGR_ASSET_PATH","INSTANCE_URL","$http","$rootScope","$location","UserEventsService","_dfObjectService","dfXHRHelper","SystemConfigDataService",function(MODUSRMNGR_ASSET_PATH,INSTANCE_URL,$http,$rootScope,$location,UserEventsService,_dfObjectService,dfXHRHelper,SystemConfigDataService){return{restrict:"E",templateUrl:MODUSRMNGR_ASSET_PATH+"views/register.html",scope:{options:"=?"},link:function(scope,elem,attrs){scope.es=UserEventsService.register;var defaults={showTemplate:!0,login:!1};scope.options=_dfObjectService.mergeObjects(scope.options,defaults),scope.showTemplate=scope.options.showTemplate,scope.identical=!0,scope.errorMsg="",scope.loginAttribute="email",scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&scope.systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=scope.systemConfig.authentication.login_attribute),scope.user={};var UrlParams=$location.search();Object.keys(UrlParams).forEach(function(key,index){scope.user[key]=UrlParams[key]}),scope.dismissError=function(){scope.errorMsg=""},scope.register=function(registerDataObj){scope._register(registerDataObj)},scope.verifyPassword=function(user){scope._verifyPassword(user)},scope._registerRequest=function(registerDataObj){return $http({url:INSTANCE_URL.url+"/user/register",method:"POST",params:{login:scope.options.login},data:registerDataObj})},scope._getSystemConfig=function(){return $http.get(INSTANCE_URL.url+"/system/environment")},scope._register=function(registerDataObj){1==scope.identical?(scope._runRegister=function(registerDataObj){scope._registerRequest(registerDataObj).then(function(result){if(null==scope.options.confirmationRequired){var userCredsObj={email:registerDataObj.email,password:registerDataObj.new_password};scope.$emit(scope.es.registerSuccess,userCredsObj)}else scope.$emit(scope.es.registerConfirmation,result.data)},function(reject){var msg="Validation failed. ",context=reject.data.error.context;null==context?reject.data&&reject.data.error&&reject.data.error.message&&(msg+=reject.data.error.message):angular.forEach(context,function(value,key){msg=msg+key+": "+value+" "},msg),scope.errorMsg=msg})},null==scope.options.confirmationRequired?scope._getSystemConfig().then(function(result){var systemConfigDataObj=result.data;scope.options.confirmationRequired=systemConfigDataObj.authentication.open_reg_email_service_id,scope._runRegister(registerDataObj)},function(reject){throw{module:"DreamFactory User Management",type:"error",provider:"dreamfactory",exception:reject}}):scope._runRegister(registerDataObj)):scope.errorMsg="Password and confirm password do not match."},scope._verifyPassword=function(userDataObj){scope.identical=userDataObj.new_password===userDataObj.verify_password},scope.$watchCollection("options",function(newValue,oldValue){if(!newValue.hasOwnProperty("confirmationRequired")){var config=dfXHRHelper.get({url:"system/environment"});scope.options.confirmationRequired=!(!config.authentication.allow_open_registration||!config.authentication.open_reg_email_service_id)||null}}),scope.$on(scope.es.registerRequest,function(e,registerDataObj){scope._register(registerDataObj)})}}}]).directive("dreamfactoryUserProfile",["MODUSRMNGR_ASSET_PATH","_dfObjectService","UserDataService","UserEventsService",function(MODUSRMNGR_ASSET_PATH,_dfObjectService,UserDataService,UserEventsService){return{restrict:"E",replace:!0,templateUrl:MODUSRMNGR_ASSET_PATH+"views/edit-profile.html",scope:{options:"=?"},link:function(scope,elem,attrs){scope.es=UserEventsService.profile;var defaults={showTemplate:!0};scope.options=_dfObjectService.mergeObjects(scope.options,defaults)}}}]).directive("dreamfactoryRemoteAuthProviders",["MODUSRMNGR_ASSET_PATH","SystemConfigDataService","INSTANCE_URL",function(MODUSRMNGR_ASSET_PATH,SystemConfigDataService,INSTANCE_URL){return{restrict:"E",replace:!0,templateUrl:MODUSRMNGR_ASSET_PATH+"views/remote-auth-providers.html",scope:!1,link:function(scope,elem,attrs){scope.url=INSTANCE_URL.url,scope.oauths=[],scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&scope.systemConfig.authentication.hasOwnProperty("oauth")&&(scope.oauths=scope.systemConfig.authentication.oauth),scope.remoteAuthLogin=function(providerData){window.top.location.href=scope.url+"/"+providerData}}}}]).directive("dreamfactorySamlAuthProviders",["MODUSRMNGR_ASSET_PATH","SystemConfigDataService","INSTANCE_URL",function(MODUSRMNGR_ASSET_PATH,SystemConfigDataService,INSTANCE_URL){return{restrict:"E",replace:!0,templateUrl:MODUSRMNGR_ASSET_PATH+"views/saml-auth-providers.html",scope:!1,link:function(scope,elem,attrs){scope.url=INSTANCE_URL.url,scope.samls=[],scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&scope.systemConfig.authentication.hasOwnProperty("saml")&&(scope.samls=scope.systemConfig.authentication.saml),scope.samlAuthLogin=function(providerData){window.top.location.href=scope.url+"/"+providerData}}}}]).directive("dreamfactoryConfirmUser",["MODUSRMNGR_ASSET_PATH","INSTANCE_URL","$location","$http","_dfObjectService","UserDataService","UserEventsService","SystemConfigDataService",function(MODUSRMNGR_ASSET_PATH,INSTANCE_URL,$location,$http,_dfObjectService,UserDataService,UserEventsService,SystemConfigDataService){return{restrict:"E",replace:!0,templateUrl:MODUSRMNGR_ASSET_PATH+"views/confirmation-code.html",scope:{options:"=?",inErrorMsg:"=?",inviteType:"=?"},link:function(scope,elem,attrs){var defaults={showTemplate:!0,title:"User Confirmation"};scope.options=_dfObjectService.mergeObjects(scope.options,defaults),scope.showTemplate=scope.options.showTemplate,scope.identical=!0,scope.errorMsg="",scope.successMsg="",scope.confirmWaiting=!1,scope.submitLabel="Confirm "+scope.inviteType.charAt(0).toUpperCase()+scope.inviteType.slice(1),scope.loginAttribute="email",scope.systemConfig=SystemConfigDataService.getSystemConfig(),scope.systemConfig&&scope.systemConfig.authentication&&scope.systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=scope.systemConfig.authentication.login_attribute),scope.useEmail=!0,scope.useUsername=!1,"username"===scope.loginAttribute&&(scope.useEmail=!1,scope.useUsername=!0),scope.user={};var UrlParams=$location.search();Object.keys(UrlParams).forEach(function(key,index){scope.user[key]=UrlParams[key]}),scope.dismissError=function(){scope.errorMsg=""},scope.dismissSuccess=function(){scope.successMsg=""},scope.confirm=function(userConfirmObj){scope.identical?scope._verifyPasswordLength(userConfirmObj)?scope._confirm(userConfirmObj):scope.errorMsg="Password must be at least 5 characters.":scope.errorMsg="Passwords do not match."},scope.verifyPassword=function(user){scope._verifyPassword(user)},scope._verifyPassword=function(userDataObj){scope.identical=userDataObj.new_password===userDataObj.verify_password},scope._verifyPasswordLength=function(user){return user.new_password.length>=5},scope._confirmUserToServer=function(requestDataObj){var api="user"===scope.inviteType?"user/password":"system/admin/password";return $http({url:INSTANCE_URL.url+"/"+api,method:"POST",params:{login:!1},data:requestDataObj})},scope._confirm=function(userConfirmObj){scope.confirmWaiting=!0;var requestDataObj=userConfirmObj;scope._confirmUserToServer(requestDataObj).then(function(result){var userCreds={email:requestDataObj.email,username:requestDataObj.username?requestDataObj.username:null,password:requestDataObj.new_password};scope.$emit(UserEventsService.confirm.confirmationSuccess,userCreds)},function(reject){scope.errorMsg=reject.data.error.message,scope.$emit(UserEventsService.confirm.confirmationError),scope.confirmWaiting=!1}).finally(function(){})};var watchInErrorMsg=scope.$watch("inErrorMsg",function(n,o){scope.confirmWaiting=!1,scope.errorMsg=n});scope.$on("$destroy",function(e){watchInErrorMsg()}),scope.$on(UserEventsService.confirm.confirmationRequest,function(e,confirmationObj){scope._confirm(confirmationObj)})}}}]).directive("dreamfactoryWaiting",["MODUSRMNGR_ASSET_PATH",function(MODUSRMNGR_ASSET_PATH){return{restrict:"E",scope:{show:"=?"},replace:!1,templateUrl:MODUSRMNGR_ASSET_PATH+"views/dreamfactory-waiting.html",link:function(scope,elem,attrs){function size(){h=el.parent(".panel-body").outerHeight(),w=el.parent(".panel-body").outerWidth(),t=el.parent(".panel-body").position().top,l=el.parent(".panel-body").position().left,container.css({height:h+"px",width:w+"px",position:"absolute",left:l,top:t}),container.children(".df-spinner").css({position:"absolute",top:(h-110)/2,left:(w-70)/2})}var el=$(elem),container=el.children(),h=el.parent(".panel-body").outerHeight(),w=el.parent(".panel-body").outerWidth(),t=el.position().top+parseInt(el.parent().css("padding-top"))+"px",l=el.position().left+parseInt(el.parent().css("padding-left"))+"px";scope._showWaiting=function(){size(),container.fadeIn("fast")},scope._hideWaiting=function(){container.hide()},scope.$watch("show",function(n,o){n?scope._showWaiting():scope._hideWaiting()}),$(window).on("resize load",function(){size()})}}}]).service("UserEventsService",[function(){return{login:{loginRequest:"user:login:request",loginSuccess:"user:login:success",loginError:"user:login:error"},logout:{logoutRequest:"user:logout:request",logoutSuccess:"user:logout:success",logoutError:"user:logout:error"},register:{registerRequest:"user:register:request",registerSuccess:"user:register:success",registerError:"user:register:error",registerConfirmation:"user:register:confirmation"},password:{passwordResetRequest:"user:passwordreset:request",passwordResetRequestSuccess:"user:passwordreset:requestsuccess",passwordSetRequest:"user:passwordset:request",passwordSetSuccess:"user:passwordset:success",passwordSetError:"user:passwordset:error"},profile:{},confirm:{confirmationSuccess:"user:confirmation:success",confirmationError:"user:confirmation:error",confirmationRequest:"user:confirmation:request"}}}]).service("UserDataService",["$cookies","$http",function($cookies,$http){function _getCurrentUser(){return currentUser}function _setCurrentUser(userDataObj){delete userDataObj.session_id,$cookies.putObject("CurrentUserObj",userDataObj),$http.defaults.headers.common["X-DreamFactory-Session-Token"]=userDataObj.session_token,currentUser=userDataObj}function _unsetCurrentUser(){$cookies.remove("CurrentUserObj"),delete $http.defaults.headers.common["X-DreamFactory-Session-Token"],currentUser=!1}var currentUser=!1;return{getCurrentUser:function(){return _getCurrentUser()},setCurrentUser:function(userDataObj){_setCurrentUser(userDataObj)},unsetCurrentUser:function(){_unsetCurrentUser()}}}]).service("_dfObjectService",[function(){return{self:this,mergeObjects:function(obj1,obj2){for(var key in obj1)obj2[key]=obj1[key];return obj2},deepMergeObjects:function(obj1,obj2){var self=this;for(var _key in obj1)obj2.hasOwnProperty(_key)&&("object"==typeof obj2[_key]?obj2[_key]=self.deepMergeObjects(obj1[_key],obj2[_key]):obj2[_key]=obj1[_key]);return obj2}}}]).service("dfXHRHelper",["INSTANCE_URL","APP_API_KEY","UserDataService",function(INSTANCE_URL,APP_API_KEY,UserDataService){function _isEmpty(obj){if(null==obj)return!0;if(obj.length>0)return!1;if(0===obj.length)return!0;for(var key in obj)if(hasOwnProperty.call(obj,key))return!1;return!0}function _setHeaders(_xhrObj,_headersDataObj){_xhrObj.setRequestHeader("X-DreamFactory-API-Key",APP_API_KEY);var currentUser=UserDataService.getCurrentUser();currentUser&¤tUser.session_tpken&&xhrObj.setRequestHeader("X-DreamFactory-Session-Token",currentUser.session_token);for(var _key in _headersDataObj)_xhrObj.setRequestHeader(_key,_headersDataObj[_key])}function _setParams(_paramsDataObj){var params="";if(!_isEmpty(_paramsDataObj)){params="?";for(var _key in _paramsDataObj)params+=_key+"="+_paramsDataObj[_key]+"&"}return""!==params&&(params=params.substring(0,params.length-1),encodeURI(params)),params}function _makeRequest(_method,_url,_async,_params,_headers,_mimeType){var xhr;xhr=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP");var params=_setParams(_params);return xhr.open(_method,INSTANCE_URL.url+"/"+_url+params,_async),_setHeaders(xhr,_headers),xhr.overrideMimeType(_mimeType),xhr.send(),4==xhr.readyState&&200==xhr.status?angular.fromJson(xhr.responseText):xhr.status}function _get(optionsDataObj){if(!optionsDataObj.url||""===optionsDataObj.url)throw{module:"DreamFactory System Config Module",type:"error",provider:"dreamfactory",exception:"XHRHelper Request Failure: No URL provided"};var defaults={method:"GET",url:"",async:!1,params:{},headers:{},mimeType:"application/json"};for(var _key in defaults)optionsDataObj.hasOwnProperty(_key)&&(defaults[_key]=optionsDataObj[_key]);return _makeRequest(defaults.method,defaults.url,defaults.async,defaults.params,defaults.headers,defaults.mimeType)}return{get:function(requestOptions){return _get(requestOptions)}}}]),angular.module("dfUtility",["dfApplication"]).constant("MOD_UTILITY_ASSET_PATH","admin_components/adf-utility/").directive("dfGithubModal",["MOD_UTILITY_ASSET_PATH","$http","dfApplicationData","$rootScope",function(MOD_UTILITY_ASSET_PATH,$http,dfApplicationData,$rootScope){return{restrict:"E",scope:{editorObj:"=?",accept:"=?",target:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-github-modal.html",link:function(scope,elem,attrs){scope.modalError={},scope.githubModal={},scope.githubUpload=function(){var url=angular.copy(scope.githubModal.url);if(url){var url_array=url.substr(url.indexOf(".com/")+5).split("/"),owner="",repo="",branch="",path="";url.indexOf("raw.github")>-1?(owner=url_array[0],repo=url_array[1],branch=url_array[2],path=url_array.splice(3,url_array.length-3).join("/")):(owner=url_array[0],repo=url_array[1],branch=url_array[3],path=url_array.splice(4,url_array.length-4).join("/"));var github_api_url="https://api.github.com/repos/"+owner+"/"+repo+"/contents/"+path+"?ref="+branch,username=angular.copy(scope.githubModal.username),password=angular.copy(scope.githubModal.password),authdata=btoa(username+":"+password);username&&($http.defaults.headers.common.Authorization="Basic "+authdata),$http.get(github_api_url,{headers:{"X-DreamFactory-API-Key":void 0,"X-DreamFactory-Session-Token":void 0},ignore401:!0}).then(function(response){switch(path.substr(path.lastIndexOf(".")+1,path.length-path.lastIndexOf("."))){case"js":"javascript";break;case"php":"php";break;case"py":"python";break;case"json":"json";break;default:"javascript"}if(scope.editorObj&&scope.editorObj.editor){var decodedString=atob(response.data.content);scope.editorObj.editor.session.setValue(decodedString),scope.editorObj.editor.focus()}var element=angular.element("#"+scope.target);element.on("hidden.bs.modal",function(){void 0!==$(this).find("form")[0]&&$(this).find("form")[0].reset()}),scope.githubModal={private:!1},scope.modalError={},element.appendTo("body").modal("hide")},function(response){401===response.status&&(scope.modalError={visible:!0,message:"Error: Authentication failed."}),404===response.status&&(scope.modalError={visible:!0,message:"Error: The file could not be found."})})}},scope.githubModalCancel=function(){scope.githubModal={private:!1},scope.modalError={};var element=angular.element("#"+scope.target);element.on("hidden.bs.modal",function(){void 0!==$(this).find("form")[0]&&$(this).find("form")[0].reset()}),element.appendTo("body").modal("hide")};scope.$watch("githubModal.username",function(newValue,oldValue){if(!newValue)return!1;scope.modalError={visible:!1,message:""}}),scope.$watch("githubModal.password",function(newValue,oldValue){if(!newValue)return!1;scope.modalError={visible:!1,message:""}}),scope.$watch("githubModal.url",function(newValue,oldValue){if(!newValue)return!1;scope.modalError={visible:!1,message:""};var file_ext=newValue.substring(newValue.lastIndexOf(".")+1,newValue.length);if(scope.accept.indexOf(file_ext)>-1){var url=angular.copy(scope.githubModal.url),url_array=url.substr(url.indexOf(".com/")+5).split("/"),github_api_url="https://api.github.com/repos/"+url_array[0]+"/"+url_array[1];$http.get(github_api_url,{headers:{"X-DreamFactory-API-Key":void 0,"X-DreamFactory-Session-Token":void 0}}).then(function(response){scope.githubModal.private=response.data.private},function(response){scope.githubModal.private=!0})}else{var formats=scope.accept.join(", ");scope.modalError={visible:!0,message:"Error: Invalid file format. Only "+formats+" file format(s) allowed"}}});scope.$on("githubShowModal",function(event,data){if(void 0!==data){var element=angular.element("#"+data);element.on("hidden.bs.modal",function(){void 0!==$(this).find("form")[0]&&$(this).find("form")[0].reset()}),element.appendTo("body").modal("show")}})}}}]).directive("dfComponentTitle",["MOD_UTILITY_ASSET_PATH","$location",function(MOD_UTILITY_ASSET_PATH,$location){return{restrict:"E",replace:!0,scope:!1,template:''}}]).directive("dfTopLevelNavStd",["MOD_UTILITY_ASSET_PATH","$location","UserDataService",function(MOD_UTILITY_ASSET_PATH,$location,UserDataService){return{restrict:"E",scope:{options:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-top-level-nav-std.html",link:function(scope,elem,attrs){scope.links=scope.options.links,scope.activeLink=null,scope.$watch(function(){return $location.path()},function(newValue,oldValue){switch(newValue){case"/home":case"/apps":case"/admins":case"/users":case"/roles":case"/services":case"/schema":case"/data":case"/file-manager":case"/scripts":case"/config":case"/package-manager":case"/apidocs":case"/downloads":case"/limits":case"/reports":case"/scheduler":scope.activeLink="admin";break;case"/launchpad":scope.activeLink="launchpad";break;case"/profile":scope.activeLink="user";break;case"/login":scope.activeLink="login";break;case"/register":case"/register-complete":case"/register-confirm":scope.activeLink="register"}})}}}]).directive("dfNavNotification",["MOD_UTILITY_ASSET_PATH","$http",function(MOD_UTILITY_ASSET_PATH,$http){return{replace:!0,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-nav-notification.html",link:function(scope,elem,attrs){$http.get("https://dreamfactory.com/in_product_v2/notifications.php").then(function(result){scope.notifications=result.data.notifications})}}}]).directive("dfComponentNav",["MOD_UTILITY_ASSET_PATH","$location","$route","$rootScope",function(MOD_UTILITY_ASSET_PATH,$location,$route,$rootScope){return{restrict:"E",scope:{options:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-component-nav.html",link:function(scope,elem,attrs){scope.activeLink=null,scope.toggleMenu=!1,scope.openMenu=function(){scope._openMenu()},scope.closeMenu=function(){scope._closeMenu()},scope.reloadRoute=function(path){scope._activeTabClicked(path)&&$route.reload()},scope._activeTabClicked=function(path){return $location.path()===path},scope._openMenu=function(){scope.toggleMenu=!0},scope._closeMenu=function(){scope.toggleMenu=!1},scope.$watch("toggleMenu",function(n,o){return 1==n?($("#component-nav-flyout-mask").fadeIn(250),$("#top-bar-mask").fadeIn(250),$("#dreamfactoryApp").css({position:"fixed",right:"0",left:"0"}).animate({right:"+=300",left:"-=300"},250,function(){}),void $("#component-nav-flyout-menu").animate({right:"+=300"},250,function(){})):!1===n&&o?($("#dreamfactoryApp").animate({right:"-=300",left:"+=300"},250,function(){}),$("#component-nav-flyout-menu").animate({right:"-=300"},250,function(){}),$("#dreamfactoryApp").css("position","relative"),$("#component-nav-flyout-mask").fadeOut(250),void $("#top-bar-mask").fadeOut(250)):void 0}),scope.$watch(function(){return $location.path()},function(newValue,oldValue){scope.activeLink=newValue?newValue.substr(1,newValue.length):null}),$rootScope.$on("$routeChangeSuccess",function(e){scope.$broadcast("component-nav:view:change"),scope._closeMenu()})}}}]).directive("dfSidebarNav",["MOD_UTILITY_ASSET_PATH","$rootScope","$location",function(MOD_UTILITY_ASSET_PATH,$rootScope,$location){return{restrict:"E",scope:!1,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-sidebar-nav.html",link:function(scope,elem,attrs){function setMargin(location){switch(location){case"/schema":case"/data":case"/file-manager":case"/scripts":case"/apidocs":case"/package-manager":case"/downloads":$(".df-component-nav-title").css({marginLeft:0});break;case"/home":case"/apps":case"/admins":case"/users":case"/roles":case"/services":case"/config":case"/reports":case"/scheduler":var _elem=$(document).find("#sidebar-open");_elem&&_elem.is(":visible")?$(".df-component-nav-title").css({marginLeft:"45px"}):$(".df-component-nav-title").css({marginLeft:0})}}scope.activeView=scope.links[0],scope.toggleMenu=!1,scope.setActiveView=function(linkObj){scope._setActiveView(linkObj)},scope.openMenu=function(){scope._openMenu()},scope.closeMenu=function(){scope._closeMenu()},scope._setActiveView=function(linkObj){scope.activeView=linkObj,scope._closeMenu(),scope.$broadcast("sidebar-nav:view:change")},scope._openMenu=function(){scope.toggleMenu=!0},scope._closeMenu=function(){scope.toggleMenu=!1},scope.$on("sidebar-nav:view:reset",function(event){angular.forEach(scope.links,function(link,id){0===id?scope.links[0].active=!0:scope.links[id].active=!1}),scope.setActiveView(scope.links[0])}),scope.$watch("toggleMenu",function(n,o){return 1==n?($("#sidebar-nav-flyout-mask").css("z-index",10).fadeIn(250),$("#top-bar-mask").fadeIn(250),$("#dreamfactoryApp").css({position:"fixed",right:"0",left:"0"}).animate({right:"-=300",left:"+=300"},250,function(){}),void $("#sidebar-nav-flyout-menu").animate({left:"+=300"},250,function(){})):!1===n&&o?($("#dreamfactoryApp").animate({right:"+=300",left:"-=300"},250,function(){}),$("#sidebar-nav-flyout-menu").animate({left:"-=300"},250,function(){}),$("#dreamfactoryApp").css("position","relative"),$("#sidebar-nav-flyout-mask").fadeOut(250),void $("#top-bar-mask").fadeOut(250)):void 0}),scope.$watch("activeView",function(newValue,oldValue){if(!newValue)return!1;oldValue.active=!1,newValue.active=!0}),$(window).resize(function(){setMargin($location.path())}),scope.$watch(function(){return $location.path()},function(newValue,oldValue){setMargin(newValue)}),"#/roles#create"===location.hash&&scope.setActiveView(scope.links[1])}}}]).directive("dreamfactoryAutoHeight",["$window","$route",function($window){return{restrict:"A",link:function(scope,elem,attrs){scope._getWindow=function(){return $(window)},scope._getDocument=function(){return $(document)},scope._getParent=function(parentStr){switch(parentStr){case"window":return scope._getWindow();case"document":return scope._getDocument();default:return $(parentStr)}},scope._setElementHeight=function(){angular.element(elem).css({height:scope._getParent(attrs.autoHeightParent).height()-200-attrs.autoHeightPadding})},scope._setElementHeight(),angular.element($window).on("resize",function(){scope._setElementHeight()})}}}]).directive("resize",[function($window){return function(scope,element){var w=angular.element($window);scope.getWindowDimensions=function(){return{h:w.height(),w:w.width()}},scope.$watch(scope.getWindowDimensions,function(newValue,oldValue){scope.windowHeight=newValue.h,scope.windowWidth=newValue.w,angular.element(element).css({width:newValue.w-angular.element("sidebar").css("width")+"px"})},!0)}}]).directive("dfFsHeight",["$window","$rootScope",function($window,$rootScope){var dfFsHeight={rules:[{comment:"If this is the swagger iframe",order:10,test:function(element,data){return element.is("#apidocs")},setSize:function(element,data){element.css({minHeight:data.windowInnerHeight-data.menuBottomPosition-26})}},{comment:"If this is the file manager iframe",order:20,test:function(element,data){return element.is("#file-manager")},setSize:function(element,data){element.css({minHeight:data.windowInnerHeight-data.menuBottomPosition-26}),$rootScope.$emit("filemanager:sized")}},{comment:"If this is the scripting sidebar list",order:30,test:function(element,data){return element.is("#scripting-sidebar-list")},setSize:function(element,data){element.css({height:data.windowInnerHeight-element.offset().top-26})}},{comment:"If this is the scripting IDE",order:40,test:function(element,data){return"ide"===element.attr("id")},setSize:function(element,data){element.css({height:data.winHeight-element.offset().top-26})}},{comment:"If any element on desktop screen",order:50,test:function(element,data){return data.winWidth>=992},setSize:function(element,data){element.css({minHeight:data.windowInnerHeight-data.menuBottomPosition})}}],default:{setSize:function(element,data){element.css({height:"auto"})}},rulesOrderComparator:function(a,b){return a.order-b.order}},setSize=function(elem){setTimeout(function(){var _elem=$(elem),dfMenu=$(".df-menu")[0],data={menuBottomPosition:dfMenu?dfMenu.getBoundingClientRect().bottom:0,windowInnerHeight:window.innerHeight,winWidth:$(document).width(),winHeight:$(document).height()},rule=dfFsHeight.rules.sort(dfFsHeight.rulesOrderComparator).find(function(value){return value.test(_elem,data)});rule?rule.setSize(_elem,data):dfFsHeight.default.setSize(_elem,data)},10)};return function(scope,elem,attrs){var eventHandler=function(e){setSize(elem)};scope.$on("apidocs:loaded",eventHandler),scope.$on("filemanager:loaded",eventHandler),scope.$on("script:loaded:success",eventHandler),scope.$on("sidebar-nav:view:change",eventHandler),scope.$on("sidebar-nav:view:change",eventHandler),$rootScope.$on("$routeChangeSuccess",eventHandler),$(document).ready(eventHandler),$(window).on("resize",eventHandler)}}]).directive("dfGroupedPicklist",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{selected:"=?",options:"=?"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-grouped-picklist.html",link:function(scope,elem,attrs){scope.selectedLabel=!1,scope.selectItem=function(item){scope.selected=item.name},scope.$watch("selected",function(n,o){if(null==n&&void 0==n)return!1;angular.forEach(scope.options,function(option){option.items&&angular.forEach(option.items,function(item){n===item.name&&(scope.selectedLabel=item.label)})})}),elem.css({display:"inline-block",position:"relative"})}}}]).directive("dfEventPicker",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{selected:"=?",options:"=?"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-event-picker.html",link:function(scope,elem,attrs){scope.selectItem=function(item){scope.selected=item.name},scope.events=[],scope.$watch("options",function(newValue,oldValue){var events=[];newValue&&(angular.forEach(newValue,function(e){e.items&&(events.length>0&&events.push({class:"divider"}),angular.forEach(e.items,function(item){item.class="",events.push(item)}))}),scope.events=events)})}}}]).directive("dfFileCertificate",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{selected:"=?"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-file-certificate.html",link:function(scope,elem,attrs){elem.find("input").bind("change",function(event){var file=event.target.files[0],reader=new FileReader;reader.onload=function(readerEvt){var string=readerEvt.target.result;scope.selected=string,scope.$apply()},reader.readAsBinaryString(file)}),elem.css({display:"inline-block",position:"relative"})}}}]).directive("dfMultiPicklist",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{options:"=?",selectedOptions:"=?",cols:"=?",legend:"=?"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-multi-picklist.html",link:function(scope,elem,attrs){angular.forEach(scope.options,function(option){option.active=!1}),scope.allSelected=!1,scope.cols||(scope.cols=3),scope.width=100/(1*scope.cols)-3,scope.toggleSelectAll=function(){var selected=[];scope.allSelected&&angular.forEach(scope.options,function(option){selected.push(option.name)}),scope.selectedOptions=selected},scope.setSelectedOptions=function(){var selected=[];angular.forEach(scope.options,function(option){option.active&&selected.push(option.name)}),scope.selectedOptions=selected},scope.$watch("selectedOptions",function(newValue,oldValue){newValue&&angular.forEach(scope.options,function(option){option.active=newValue.indexOf(option.name)>=0})}),elem.css({display:"inline-block",position:"relative"})}}}]).directive("dfVerbPicker",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{allowedVerbs:"=?",allowedVerbMask:"=?",description:"=?",size:"@"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-verb-picker.html",link:function(scope,elem,attrs){scope.verbs={GET:{name:"GET",active:!1,description:" (read)",mask:1},POST:{name:"POST",active:!1,description:" (create)",mask:2},PUT:{name:"PUT",active:!1,description:" (replace)",mask:4},PATCH:{name:"PATCH",active:!1,description:" (update)",mask:8},DELETE:{name:"DELETE",active:!1,description:" (remove)",mask:16}},scope.btnText="None Selected",scope.description=!0,scope.checkAll={checked:!1},scope._toggleSelectAll=function(event){void 0!==event&&event.stopPropagation();var verbsSet=[];Object.keys(scope.verbs).forEach(function(key,index){!0===scope.verbs[key].active&&verbsSet.push(key)}),verbsSet.length>0?angular.forEach(verbsSet,function(verb){scope._toggleVerbState(verb,event)}):Object.keys(scope.verbs).forEach(function(key,index){scope._toggleVerbState(key,event)})},scope._setVerbState=function(nameStr,stateBool){var verb=scope.verbs[nameStr];scope.verbs.hasOwnProperty(verb.name)&&(scope.verbs[verb.name].active=stateBool)},scope._toggleVerbState=function(nameStr,event){void 0!==event&&event.stopPropagation(),scope.verbs.hasOwnProperty(scope.verbs[nameStr].name)&&(scope.verbs[nameStr].active=!scope.verbs[nameStr].active,scope.allowedVerbMask=scope.allowedVerbMask^scope.verbs[nameStr].mask),scope.allowedVerbs=[],angular.forEach(scope.verbs,function(_obj){_obj.active&&scope.allowedVerbs.push(_obj.name)})},scope._isVerbActive=function(verbStr){return scope.verbs[verbStr].active},scope._setButtonText=function(){var verbs=[];angular.forEach(scope.verbs,function(verbObj){verbObj.active&&verbs.push(verbObj.name)}),scope.btnText="";0==verbs.length?scope.btnText="None Selected":verbs.length>0&&verbs.length<=1?angular.forEach(verbs,function(_value,_index){scope._isVerbActive(_value)&&(_index!=verbs.length-1?scope.btnText+=_value+", ":scope.btnText+=_value)}):verbs.length>1&&(scope.btnText=verbs.length+" Selected")},scope.$watch("allowedVerbs",function(newValue,oldValue){if(!newValue)return!1;Object.keys(scope.verbs).forEach(function(key){scope._setVerbState(key,!1)}),angular.forEach(scope.allowedVerbs,function(_value,_index){scope._setVerbState(_value,!0)}),scope._setButtonText()}),scope.$watch("allowedVerbMask",function(n,o){if(null==n&&void 0==n)return!1;angular.forEach(scope.verbs,function(verbObj){n&verbObj.mask&&(verbObj.active=!0)}),scope._setButtonText()}),elem.css({display:"inline-block",position:"relative"})}}}]).directive("dfRequestorPicker",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{allowedRequestors:"=?",allowedRequestorMask:"=?",size:"@"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-requestor-picker.html",link:function(scope,elem,attrs){scope.requestors={API:{name:"API",active:!1,mask:1},SCRIPT:{name:"SCRIPT",active:!1,mask:2}},scope.btnText="None Selected",scope._setRequestorState=function(nameStr,stateBool){var requestor=scope.requestors[nameStr];scope.requestors.hasOwnProperty(requestor.name)&&(scope.requestors[requestor.name].active=stateBool)},scope._toggleRequestorState=function(nameStr,event){event.stopPropagation(),scope.requestors.hasOwnProperty(scope.requestors[nameStr].name)&&(scope.requestors[nameStr].active=!scope.requestors[nameStr].active,scope.allowedRequestorMask=scope.allowedRequestorMask^scope.requestors[nameStr].mask),scope.allowedRequestors=[],angular.forEach(scope.requestors,function(_obj){_obj.active&&scope.allowedRequestors.push(_obj.name)})},scope._isRequestorActive=function(requestorStr){return scope.requestors[requestorStr].active},scope._setButtonText=function(){var requestors=[];angular.forEach(scope.requestors,function(rObj){rObj.active&&requestors.push(rObj.name)}),scope.btnText="",0==requestors.length?scope.btnText="None Selected":angular.forEach(requestors,function(_value,_index){scope._isRequestorActive(_value)&&(_index!=requestors.length-1?scope.btnText+=_value+", ":scope.btnText+=_value)})},scope.$watch("allowedRequestors",function(newValue,oldValue){if(!newValue)return!1;angular.forEach(scope.allowedRequestors,function(_value,_index){scope._setRequestorState(_value,!0)}),scope._setButtonText()}),scope.$watch("allowedRequestorMask",function(n,o){if(null==n&&void 0==n)return!1;angular.forEach(scope.requestors,function(requestorObj){n&requestorObj.mask&&(requestorObj.active=!0)}),scope._setButtonText()}),elem.css({display:"inline-block",position:"absolute"})}}}]).directive("dfDbFunctionUsePicker",["MOD_UTILITY_ASSET_PATH",function(DF_UTILITY_ASSET_PATH){return{restrict:"E",scope:{allowedUses:"=?",description:"=?",size:"@"},templateUrl:DF_UTILITY_ASSET_PATH+"views/df-db-function-use-picker.html",link:function(scope,elem,attrs){scope.uses={SELECT:{name:"SELECT",active:!1,description:" (get)"},FILTER:{name:"FILTER",active:!1,description:" (get)"},INSERT:{name:"INSERT",active:!1,description:" (post)"},UPDATE:{name:"UPDATE",active:!1,description:" (patch)"}},scope.btnText="None Selected",scope.description=!0,scope._setDbFunctionUseState=function(nameStr,stateBool){scope.uses.hasOwnProperty(scope.uses[nameStr].name)&&(scope.uses[nameStr].active=stateBool)},scope._toggleDbFunctionUseState=function(nameStr,event){event.stopPropagation(),scope.uses.hasOwnProperty(scope.uses[nameStr].name)&&(scope.uses[nameStr].active=!scope.uses[nameStr].active),scope.allowedUses=[],angular.forEach(scope.uses,function(_obj){_obj.active&&scope.allowedUses.push(_obj.name)})},scope._isDbFunctionUseActive=function(nameStr){return scope.uses[nameStr].active},scope._setButtonText=function(){var uses=[];angular.forEach(scope.uses,function(useObj){useObj.active&&uses.push(useObj.name)}),scope.btnText="";0==uses.length?scope.btnText="None Selected":uses.length>0&&uses.length<=1?angular.forEach(uses,function(_value,_index){scope._isDbFunctionUseActive(_value)&&(_index!=uses.length-1?scope.btnText+=_value+", ":scope.btnText+=_value)}):uses.length>1&&(scope.btnText=uses.length+" Selected")},scope.$watch("allowedUses",function(newValue,oldValue){if(!newValue)return!1;Object.keys(scope.uses).forEach(function(key){scope._setDbFunctionUseState(key,!1)}),angular.forEach(scope.allowedUses,function(_value,_index){scope._setDbFunctionUseState(_value,!0)}),scope._setButtonText()}),elem.css({display:"inline-block",position:"relative"})}}}]).directive("dfServicePicker",["MOD_UTILITY_ASSET_PATH","INSTANCE_URL","$http",function(MOD_UTILITY_ASSET_PATH,INSTANCE_URL,$http){return{restrict:"E",scope:{services:"=?",selected:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-service-picker.html",link:function(scope,elem,attrs){scope.resources=[],scope.activeResource=null,scope.activeService=null,scope.setServiceAndResource=function(){scope._checkForActive()&&scope._setServiceAndResource()},scope._getResources=function(){return $http({method:"GET",url:INSTANCE_URL.url+"/"+scope.activeService})},scope._setServiceAndResource=function(){scope.selected={service:scope.activeService,resource:scope.activeResource}},scope._checkForActive=function(){return!!scope.activeResource&&scope.activeService},scope.$watch("activeService",function(newValue,oldValue){if(!newValue)return scope.resources=[],scope.activeResource=null,!1;scope.resources=[],scope._getResources().then(function(result){scope.resources=result.data.resource},function(reject){throw{module:"DreamFactory Utility Module",type:"error",provider:"dreamfactory",exception:reject}})})}}}]).directive("dfDbTablePicker",["MOD_UTILITY_ASSET_PATH","INSTANCE_URL","$http","dfApplicationData",function(MOD_UTILITY_ASSET_PATH,INSTANCE_URL,$http,dfApplicationData){return{restrict:"E",scope:{services:"=?",selected:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-db-table-picker.html",link:function(scope,elem,attrs){scope.resources=[],scope.activeResource=null,scope.activeService=null,scope.setServiceAndResource=function(){scope._checkForActive()&&scope._setServiceAndResource()},scope._getResources=function(){return dfApplicationData.getServiceComponents(scope.activeService,INSTANCE_URL.url+"/"+scope.activeService+"/_table/",{params:{fields:"name,label"}})},scope._setServiceAndResource=function(){scope.selected={service:scope.activeService,resource:scope.activeResource}},scope._checkForActive=function(){return!!scope.activeResource&&scope.activeService},scope.$watch("activeService",function(newValue,oldValue){if(!newValue)return scope.resources=[],scope.activeResource=null,!1;scope.resources=[],scope._getResources().then(function(result){scope.resources=result},function(reject){throw{module:"DreamFactory Utility Module",type:"error",provider:"dreamfactory",exception:reject}})})}}}]).directive("dfDbSchemaPicker",["MOD_UTILITY_ASSET_PATH","INSTANCE_URL","$http",function(MOD_UTILITY_ASSET_PATH,INSTANCE_URL,$http){return{restrict:"E",scope:{services:"=?",selected:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-db-schema-picker.html",link:function(scope,elem,attrs){scope.resources=[],scope.activeResource=null,scope.activeService=null,scope.setServiceAndResource=function(){scope._checkForActive()&&scope._setServiceAndResource()},scope._getResources=function(){return $http({method:"GET",url:INSTANCE_URL.url+"/"+scope.activeService+"/_schema/"})},scope._setServiceAndResource=function(){scope.selected={service:scope.activeService,resource:scope.activeResource}},scope._checkForActive=function(){return!!scope.activeResource&&scope.activeService},scope.$watch("activeService",function(newValue,oldValue){if(!newValue)return scope.resources=[],scope.activeResource=null,!1;scope.resources=[],scope._getResources().then(function(result){scope.resources=result.data.resource},function(reject){throw{module:"DreamFactory Utility Module",type:"error",provider:"dreamfactory",exception:reject}})})}}}]).directive("dfAceEditor",["MOD_UTILITY_ASSET_PATH","$compile",function(MOD_UTILITY_ASSET_PATH,$compile){return{restrict:"E",scope:{inputType:"=?",inputContent:"=?",inputUpdate:"=?",inputFormat:"=?",isEditable:"=?",editorObj:"=?",targetDiv:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-ace-editor.html",link:function(scope,elem,attrs){window.define=window.define||ace.define,$(elem).children(".ide-attach").append($compile('
')(scope)),scope.editor=null,scope.currentContent="",scope.verbose=!1,scope._setEditorInactive=function(inactive){scope.verbose&&console.log(scope.targetDiv,"_setEditorInactive",inactive),inactive?(scope.editor.setOptions({readOnly:!0,highlightActiveLine:!1,highlightGutterLine:!1}),scope.editor.container.style.opacity=.75,scope.editor.renderer.$cursorLayer.element.style.opacity=0):(scope.editor.setOptions({readOnly:!1,highlightActiveLine:!0,highlightGutterLine:!0}),scope.editor.container.style.opacity=1,scope.editor.renderer.$cursorLayer.element.style.opacity=100)},scope._setEditorMode=function(mode){scope.verbose&&console.log(scope.targetDiv,"_setEditorMode",mode),scope.editor.session.setMode({path:"ace/mode/"+mode,inline:!0,v:Date.now()})},scope._loadEditor=function(newValue){if(scope.verbose&&console.log(scope.targetDiv,"_loadEditor",newValue),null!==newValue&&void 0!==newValue){var content=newValue;"object"===scope.inputType&&(content=angular.toJson(content,!0)),scope.currentContent=content,scope.editor=ace.edit("ide_"+scope.targetDiv),scope.editorObj.editor=scope.editor,scope.editor.renderer.setShowGutter(!0),scope.editor.session.setValue(content)}},scope.$watch("inputContent",scope._loadEditor),scope.$watch("inputUpdate",function(newValue){scope.verbose&&console.log(scope.targetDiv,"inputUpdate",newValue),scope._loadEditor(scope.currentContent)}),scope.$watch("inputFormat",function(newValue){scope.verbose&&console.log(scope.targetDiv,"inputFormat",newValue),newValue&&("nodejs"===newValue?newValue="javascript":"python3"===newValue&&(newValue="python"),scope._setEditorMode(newValue))}),scope.$watch("isEditable",function(newValue){scope.verbose&&console.log(scope.targetDiv,"isEditable",newValue),scope._setEditorInactive(!newValue)}),scope.$on("$destroy",function(e){scope.verbose&&console.log(scope.targetDiv,"$destroy"),scope.editor.destroy()})}}}]).directive("fileModel",["$parse",function($parse){return{restrict:"A",scope:!1,link:function(scope,element,attrs){var modelSetter=$parse(attrs.fileModel).assign;element.on("change",function(){scope.$apply(function(){modelSetter(scope,element[0].files[0])})})}}}]).directive("fileModel2",["$parse",function($parse){return{restrict:"A",scope:!1,link:function(scope,element,attrs){var modelSetter=$parse(attrs.fileModel).assign;element.on("change",function(){scope.$apply(function(){modelSetter(scope,element[0].files[0])})})}}}]).directive("showtab",[function(){return{restrict:"A",link:function(scope,element,attrs){element.click(function(e){e.preventDefault(),$(element).tab("show")}),scope.activeTab=$(element).attr("id")}}}]).directive("dfSectionToolbar",["MOD_UTILITY_ASSET_PATH","$compile","dfApplicationData","$location","$timeout","$route",function(MOD_UTILITY_ASSET_PATH,$compile,dfApplicationData,$location,$timeout,$route){return{restrict:"E",scope:!1,transclude:!0,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-toolbar.html",link:function(scope,elem,attrs){scope.changeFilter=function(searchStr){$timeout(function(){if(searchStr===scope.filterText||!scope.filterText)return scope.filterText=scope.filterText||null,void $location.search("filter",scope.filterText)},1e3)},scope.filterText=$location.search()&&$location.search().filter?$location.search().filter:"",elem.find("input")[0]&&elem.find("input")[0].focus()}}}]).directive("dfToolbarHelp",["MOD_UTILITY_ASSET_PATH",function(MOD_UTILITY_ASSET_PATH){return{restrict:"E",scope:!1,replace:!0,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-toolbar-help.html",link:function(scope,elem,attrs){scope=scope.$parent}}}]).directive("dfToolbarPaginate",["MOD_UTILITY_ASSET_PATH","dfApplicationData","dfNotify","$location",function(MOD_UTILITY_ASSET_PATH,dfApplicationData,dfNotify,$location){return{restrict:"E",scope:{api:"=",type:"=?"},replace:!0,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-toolbar-paginate.html",link:function(scope,elem,attrs){scope.totalCount=dfApplicationData.getApiRecordCount(scope.api),scope.pagesArr=[],scope.currentPage={},scope.isInProgress=!1,scope.getPrevious=function(){if(scope._isFirstPage()||scope.isInProgress)return!1;scope._getPrevious()},scope.getNext=function(){if(scope._isLastPage()||scope.isInProgress)return!1;scope._getNext()},scope.getPage=function(pageObj){scope._getPage(pageObj)},scope._getDataFromServer=function(offset,filter){var params={offset:offset,include_count:!0};return filter&&(params.filter=filter),dfApplicationData.getDataSetFromServer(scope.api,{params:params}).$promise},scope._calcTotalPages=function(totalCount,numPerPage){return Math.ceil(totalCount/numPerPage)},scope._createPageObj=function(_pageNum){return{number:_pageNum+1,value:_pageNum,offset:_pageNum*dfApplicationData.getApiPrefs().data[scope.api].limit,stopPropagation:!1}},scope._createPagesArr=function(_totalCount){scope.pagesArr=[];for(var i=0;i<_totalCount;i++)scope.pagesArr.push(scope._createPageObj(i))},scope._setCurrentPage=function(pageDataObj){scope.currentPage=pageDataObj},scope._getCurrentPage=function(){return!scope.currentPage&&scope.pagesArr.length>0?scope.currentPage=scope.pagesArr[0]:scope.currentPage||scope.pagesArr.length||(scope.pagesArr.push(scope._createPageObj(0)),scope.currentPage=scope.pagesArr[0]),scope.currentPage},scope._isFirstPage=function(){return 0===scope._getCurrentPage().value},scope._isLastPage=function(){return scope.currentPage.value===scope.pagesArr.length-1},scope._previousPage=function(){scope.currentPage=scope.pagesArr[scope.currentPage.value-1]},scope._nextPage=function(){scope.currentPage=scope.pagesArr[scope.currentPage.value+1]},scope._calcPagination=function(api){if(scope.pagesArr=[],0==scope.totalCount)return scope.pagesArr.push(scope._createPageObj(0)),!1;scope._createPagesArr(scope._calcTotalPages(scope.totalCount,dfApplicationData.getApiPrefs().data[api].limit))};var detectFilter=function(){var filterText=$location.search()&&$location.search().filter?$location.search().filter:"";if(!filterText)return"";var arr=["first_name","last_name","name","email"];return $location.path().includes("apps")&&(arr=["name","description"]),$location.path().includes("roles")&&(arr=["name","description"]),$location.path().includes("services")&&(arr=["name","label","description","type"]),$location.path().includes("reports")?(arr=["id","service_id","service_name","user_email","action","request_verb"]).map(function(item){return item.includes("id")?Number.isNaN(parseInt(filterText))?"":"("+item+" like "+parseInt(filterText)+")":"("+item+' like "%'+filterText+'%")'}).filter(function(filter){return"string"==typeof filter&&filter.length>0}).join(" or "):arr.map(function(item){return"("+item+' like "%'+filterText+'%")'}).join(" or ")};scope._getPrevious=function(){if(scope.isInProgress)return!1;scope.isInProgress=!0;var offset=scope.pagesArr[scope.currentPage.value-1].offset;scope._getDataFromServer(offset,detectFilter()).then(function(result){scope._previousPage(),scope.$emit("toolbar:paginate:"+scope.api+":update")},function(reject){var messageOptions={module:"DreamFactory Paginate Table",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.isInProgress=!1})},scope._getNext=function(){if(scope.isInProgress)return!1;scope.isInProgress=!0;var offset=scope.pagesArr[scope.currentPage.value+1].offset;scope._getDataFromServer(offset,detectFilter()).then(function(result){scope._nextPage(),scope.$emit("toolbar:paginate:"+scope.api+":update")},function(reject){var messageOptions={module:"DreamFactory Paginate Table",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.isInProgress=!1})},scope._getPage=function(pageObj){if(scope.isInProgress)return!1;scope.isInProgress=!0,scope._getDataFromServer(pageObj.offset,detectFilter()).then(function(result){scope._setCurrentPage(pageObj),scope.$emit("toolbar:paginate:"+scope.api+":update")},function(reject){var messageOptions={module:"DreamFactory Paginate Table",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.isInProgress=!1})};scope.$watch("api",function(newValue,oldValue){if(!newValue)return!1;scope.totalCount=dfApplicationData.getApiRecordCount(newValue),scope._calcPagination(newValue),scope._setCurrentPage(scope.pagesArr[0])});scope.$on("toolbar:paginate:"+scope.api+":load",function(e){scope.totalCount=dfApplicationData.getApiRecordCount(scope.api),scope._calcPagination(scope.api),scope._setCurrentPage(scope.pagesArr[0])}),scope.$on("toolbar:paginate:"+scope.api+":destroy",function(e){1!==scope.currentPage.number&&(dfApplicationData.deleteApiDataFromCache(scope.api),scope.totalCount=0,scope._calcPagination(scope.api),scope._setCurrentPage(scope.pagesArr[0]))}),scope.$on("toolbar:paginate:"+scope.api+":reset",function(e){if("/logout"!==$location.path()&&void 0!==dfApplicationData.getApiDataFromCache(scope.api)){if(scope.isInProgress)return!1;scope.isInProgress=!0,scope._getDataFromServer(0,detectFilter()).then(function(result){scope.totalCount=dfApplicationData.getApiRecordCount(scope.api),scope._calcPagination(scope.api),scope._setCurrentPage(scope.pagesArr[0]),scope.$emit("toolbar:paginate:"+scope.api+":update")},function(reject){var messageOptions={module:"DreamFactory Paginate Table",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.isInProgress=!1})}}),scope.$on("toolbar:paginate:"+scope.api+":delete",function(e){if(!scope.isInProgress){var curOffset=scope.currentPage.offset,recalcPagination=!1;scope._isLastPage()&&!dfApplicationData.getApiDataFromCache(scope.api).length&&(recalcPagination=!0,1!==scope.currentPage.number&&(curOffset=scope.currentPage.offset-dfApplicationData.getApiPrefs().data[scope.api].limit)),scope.isInProgress=!0,scope._getDataFromServer(curOffset,detectFilter()).then(function(result){scope.totalCount=dfApplicationData.getApiRecordCount(scope.api),recalcPagination&&(scope._calcPagination(scope.api),scope._setCurrentPage(scope.pagesArr[scope.pagesArr.length-1])),scope.$emit("toolbar:paginate:"+scope.api+":update")},function(reject){var messageOptions={module:"DreamFactory Paginate Table",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.isInProgress=!1})}})}}}]).directive("dfDetailsHeader",["MOD_UTILITY_ASSET_PATH",function(MOD_UTILITY_ASSET_PATH){return{restrict:"E",scope:{new:"=",name:"=?",apiName:"=?"},template:'

Create {{apiName}}

Edit {{name}}

',link:function(scope,elem,attrs){}}}]).directive("dfSectionHeader",[function(){return{restrict:"E",scope:{title:"=?"},template:'

{{title}}

',link:function(scope,elem,attrs){}}}]).directive("dfSetUserPassword",["MOD_UTILITY_ASSET_PATH","$compile",function(MOD_USER_ASSET_PATH,$compile){return{restrict:"E",scope:!1,templateUrl:MOD_USER_ASSET_PATH+"views/df-input-manual-password.html",link:function(scope,elem,attrs){scope.requireOldPassword=!1,scope.password=null,scope.setPassword=!1,scope.identical=!0,scope._verifyPassword=function(){scope.identical=scope.password.new_password===scope.password.verify_password},scope._resetUserPasswordForm=function(){scope.password=null,scope.setPassword=!1,scope.identical=!0},scope.$watch("setPassword",function(newValue){if(newValue){var html="";html+='
';var el=$compile(html+='
')(scope);angular.element("#set-password").append(el)}}),scope.$on("reset:user:form",function(e){scope._resetUserPasswordForm()})}}}]).directive("dfSetSecurityQuestion",["MOD_UTILITY_ASSET_PATH","$compile",function(MOD_UTILITY_ASSET_PATH,$compile){return{restrict:"E",scope:!1,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-set-security-question.html",link:function(scope,elem,attrs){scope.setQuestion=!1,scope.$watch("setQuestion",function(newValue){if(newValue){var html="";html+='
',angular.element("#set-question").append($compile(html)(scope))}})}}}]).directive("dfDownloadSdk",["MOD_UTILITY_ASSET_PATH",function(MOD_UTILITY_ASSET_PATH){return{restrict:"E",scope:{btnSize:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-download-sdk.html",link:function(scope,elem,attrs){scope.sampleAppLinks=[{label:"Android",href:"https://github.com/dreamfactorysoftware/android-sdk",icon:""},{label:"iOS Objective-C",href:"https://github.com/dreamfactorysoftware/ios-sdk",icon:""},{label:"iOS Swift",href:"https://github.com/dreamfactorysoftware/ios-swift-sdk",icon:""},{label:"JavaScript",href:"https://github.com/dreamfactorysoftware/javascript-sdk",icon:""},{label:"AngularJS",href:"https://github.com/dreamfactorysoftware/angular-sdk",icon:""},{label:"Angular 2",href:"https://github.com/dreamfactorysoftware/angular2-sdk",icon:""},{label:"Ionic",href:"https://github.com/dreamfactorysoftware/ionic-sdk",icon:""},{label:"Titanium",href:"https://github.com/dreamfactorysoftware/titanium-sdk",icon:""},{label:"ReactJS",href:"https://github.com/dreamfactorysoftware/reactjs-sdk",icon:""},{label:".NET",href:"https://github.com/dreamfactorysoftware/.net-sdk",icon:""}]}}}]).directive("dfEmptySection",["MOD_UTILITY_ASSET_PATH",function(MOD_UTILITY_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-empty-section.html"}}]).directive("dfEmptySearchResult",["MOD_UTILITY_ASSET_PATH","$location",function(MOD_UTILITY_ASSET_PATH,$location){return{restrict:"E",scope:!1,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-empty-search-result.html",link:function(scope,elem,attrs){$location.search()&&$location.search().filter&&(scope.$parent.filterText=$location.search()&&$location.search().filter?$location.search().filter:null)}}}]).directive("dfPopupLogin",["MOD_UTILITY_ASSET_PATH","$compile","$location","UserEventsService",function(MOD_UTILITY_ASSET_PATH,$compile,$location,UserEventsService){return{restrict:"A",scope:!1,link:function(scope,elem,attrs){scope.popupLoginOptions={showTemplate:!0},scope.openLoginWindow=function(errormsg){scope._openLoginWindow(errormsg)},scope._openLoginWindow=function(errormsg){$("#popup-login-container").html($compile('
')(scope))},scope.$on(UserEventsService.login.loginSuccess,function(e,userDataObj){e.stopPropagation(),$("#df-login-frame").remove()}),scope.$on(UserEventsService.login.loginError,function(e,userDataObj){$("#df-login-frame").remove(),$location.url("/logout")})}}}]).directive("dfCopyrightFooter",["MOD_UTILITY_ASSET_PATH","APP_VERSION",function(MOD_UTILITY_ASSET_PATH,APP_VERSION){return{restrict:"E",scope:!1,templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-copyright-footer.html",link:function(scope,elem,attrs){scope.version=APP_VERSION,scope.currentYear=(new Date).getFullYear()}}}]).directive("dfPaywall",["MOD_UTILITY_ASSET_PATH",function(MOD_UTILITY_ASSET_PATH){return{restrict:"E",scope:{serviceName:"=?",licenseType:"=?"},templateUrl:MOD_UTILITY_ASSET_PATH+"views/df-paywall.html",link:function(scope,elem,attrs){scope.$watch("serviceName",function(newValue,oldValue){scope.serviceName&&scope.$emit("hitPaywall",newValue)}),Calendly.initInlineWidget({url:"https://calendly.com/dreamfactory-platform/unlock-all-features",parentElement:document.querySelector(".calendly-inline-widget"),autoLoad:!1})}}}]).service("dfObjectService",[function(){return{mergeDiff:function(obj1,obj2){for(var key in obj1)obj2.hasOwnProperty(key)||"$"===key.substr(0,1)||(obj2[key]=obj1[key]);return obj2},mergeObjects:function(obj1,obj2){for(var key in obj1)obj2[key]=obj1[key];return obj2},deepMergeObjects:function(obj1,obj2){var self=this;for(var _key in obj1)if(obj2.hasOwnProperty(_key))switch(Object.prototype.toString.call(obj2[_key])){case"[object Object]":obj2[_key]=self.deepMergeObjects(obj1[_key],obj2[_key]);break;case"[object Array]":obj2[_key]=obj1[_key];break;default:obj2[_key]=obj1[_key]}return obj2},compareObjectsAsJson:function(o,p){return angular.toJson(o)===angular.toJson(p)}}}]).service("XHRHelper",["INSTANCE_URL","APP_API_KEY","$cookies",function(INSTANCE_URL,APP_API_KEY,$cookies){function _isEmpty(obj){if(null==obj)return!0;if(obj.length>0)return!1;if(0===obj.length)return!0;for(var key in obj)if(hasOwnProperty.call(obj,key))return!1;return!0}function _setHeaders(_xhrObj,_headersDataObj){_xhrObj.setRequestHeader("X-DreamFactory-API-Key",APP_API_KEY);var currentUser=UserDataService.getCurrentUser();currentUser&¤tUser.session_tpken&&xhrObj.setRequestHeader("X-DreamFactory-Session-Token",currentUser.session_token);for(var _key in _headersDataObj)_xhrObj.setRequestHeader(_key,_headersDataObj[_key])}function _setParams(_paramsDataObj){var params="";if(!_isEmpty(_paramsDataObj)){params="?";for(var _key in _paramsDataObj)params+=_key+"="+_paramsDataObj[_key]+"&"}return""!==params&&(params=params.substring(0,params.length-1),encodeURI(params)),params}function _makeRequest(_method,_url,_async,_params,_headers,_mimeType){var xhr;xhr=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP");var params=_setParams(_params);if(xhr.open(_method,INSTANCE_URL.url+"/"+_url+params,_async),_setHeaders(xhr,_headers),xhr.overrideMimeType(_mimeType),xhr.send(),4===xhr.readyState)return xhr}function _ajax(optionsDataObj){if(!optionsDataObj.url||""===optionsDataObj.url)throw{module:"DreamFactory Utility Module",type:"error",provider:"dreamfactory",exception:"XHRHelper Request Failure: No URL provided"};var defaults={method:"GET",url:"",async:!1,params:{},headers:{},mimeType:"application/json"};for(var _key in defaults)optionsDataObj.hasOwnProperty(_key)&&(defaults[_key]=optionsDataObj[_key]);return _makeRequest(defaults.method,defaults.url,defaults.async,defaults.params,defaults.headers,defaults.mimeType)}return{ajax:function(requestOptions){return _ajax(requestOptions)}}}]).service("dfNotify",["dfApplicationData",function(dfApplicationData){function pnotify(messageOptions){function notificationExists(notification){return notification.options.tag===messageOptions.tag}var notificationCardStyle="",notificationIcon="";switch(messageOptions.type){case"success":notificationCardStyle="notification-card-success",notificationIcon="fa fa-check fa-lg fa-green";break;case"error":notificationCardStyle="notification-card-error",notificationIcon="fa fa-exclamation-triangle fa-lg fa-red";break;case"warn":notificationCardStyle="notification-card-warn",notificationIcon="fa fa-exclamation fa-lg fa-yellow";break;case"testing":notificationCardStyle="notification-card-success",notificationIcon="fa fa-refresh fa-spin fa-lg"}var notificationOptions={title:messageOptions.module,type:messageOptions.type,text:messageOptions.message,addclass:"stack-bottomleft "+notificationCardStyle,animate:{animate:!0,in_class:"animate__slideInLeft",out_class:"animate__slideOutLeft"},animate_speed:"normal",buttons:{closer:!0,sticker:!0,classes:{closer:"fa fa-times-circle",pin_up:"fa fa-pause",pin_down:"fa fa-play"}},icon:notificationIcon,tag:messageOptions.tag,hide:"testing"!==messageOptions.type,delay:"testing"===messageOptions.type?null:5e3,stack:stack_bar_bottom,mouse_reset:!0};if(messageOptions.tag&¬ifications.findIndex(notificationExists)>=0)var indexOfExistingNotice=notifications.findIndex(notificationExists);if(void 0!==indexOfExistingNotice){var updatedNotice=notifications[indexOfExistingNotice].update(notificationOptions);"closed"===updatedNotice.state&&updatedNotice.open(),notifications.splice(indexOfExistingNotice,1)}else{var notice=new PNotify(notificationOptions);notice.options.tag&¬ifications.push(notice)}}function parseDreamfactoryError(errorDataObj){var result,error,resource,message;return"[object String]"===Object.prototype.toString.call(errorDataObj)?result=errorDataObj:(result="The server returned an unknown error.",(error=errorDataObj.data?errorDataObj.data.error:errorDataObj.error)&&((message=error.message)&&(result=message),1e3===error.code&&error.context&&(resource=error.context.resource,error=error.context.error,resource&&error&&(result="",angular.forEach(error,function(index){result&&(result+="\n"),result+=resource[index].message}))))),result}var notifications=[],stack_bar_bottom={dir1:"up",dir2:"right",spacing1:10};return{success:function(options){pnotify(options)},error:function(options){options.message=parseDreamfactoryError(options.message),pnotify(options)},warn:function(options){pnotify(options)},confirmNoSave:function(){return confirm("Continue without saving?")},confirm:function(msg){return confirm(msg)}}}]).service("dfIconService",[function(){return function(){return{upgrade:"fa fa-fw fa-level-up",support:"fa fa-fw fa-support",launchpad:"fa fa-fw fa-bars",admin:"fa fa-fw fa-cog",login:"fa fa-fw fa-sign-in",register:"fa fa-fw fa-group",user:"fa fa-fw fa-user"}}}]).service("dfServerInfoService",["$window",function($window){return{currentServer:function(){return $window.location.origin}}}]).service("serviceTypeToGroup",[function(){return function(type,serviceTypes){var i,length,result=null;if(type&&serviceTypes)for(length=serviceTypes.length,i=0;iupB?1:0});break;default:filtered.sort(function(a,b){a.hasOwnProperty("record")&&b.hasOwnProperty("record")?(a=a.record[field],b=b.record[field]):(a=a[field],b=b[field]);var upA=a=null===a||void 0===a?"":a,upB=b=null===b||void 0===b?"":b;return upAupB?1:0})}return reverse&&filtered.reverse(),filtered}}]).filter("dfFilterBy",[function(){return function(items,options){if(!options.on)return items;var filtered=[];return options&&options.field&&options.value?(options.regex||(options.regex=new RegExp(options.value,"i")),angular.forEach(items,function(item){options.regex.test(item[options.field])&&filtered.push(item)}),filtered):items}}]).filter("dfOrderExplicit",[function(){return function(items,order){var filtered=[],i=0;return angular.forEach(items,function(value,index){value.name===order[i]&&filtered.push(value),i++}),filtered}}]),angular.module("dfSystemConfig",["ngRoute","dfUtility","dfApplication"]).constant("MODSYSCONFIG_ROUTER_PATH","/config").constant("MODSYSCONFIG_ASSET_PATH","admin_components/adf-system-config/").config(["$routeProvider","MODSYSCONFIG_ROUTER_PATH","MODSYSCONFIG_ASSET_PATH",function($routeProvider,MODSYSCONFIG_ROUTER_PATH,MODSYSCONFIG_ASSET_PATH){$routeProvider.when(MODSYSCONFIG_ROUTER_PATH,{templateUrl:MODSYSCONFIG_ASSET_PATH+"views/main.html",controller:"SystemConfigurationCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("SystemConfigurationCtrl",["$scope","dfApplicationData","SystemConfigEventsService","SystemConfigDataService","dfObjectService","dfNotify","UserDataService",function($scope,dfApplicationData,SystemConfigEventsService,SystemConfigDataService,dfObjectService,dfNotify,UserDataService){var currentUser=UserDataService.getCurrentUser();$scope.isSysAdmin=currentUser&¤tUser.is_sys_admin,$scope.$parent.title="Config",$scope.$parent.titleIcon="gear",$scope.es=SystemConfigEventsService.systemConfigController,$scope.buildLinks=function(checkData){var links=[];return checkData&&!$scope.apiData.environment||links.push({name:"system-info",label:"System Info",path:"system-info",active:0===links.length}),checkData&&!$scope.apiData.cache||links.push({name:"cache",label:"Cache",path:"cache",active:0===links.length}),checkData&&!$scope.apiData.cors||links.push({name:"cors",label:"CORS",path:"cors",active:0===links.length}),checkData&&!$scope.apiData.email_template||links.push({name:"email-templates",label:"Email Templates",path:"email-templates",active:0===links.length}),checkData&&!$scope.apiData.lookup||links.push({name:"global-lookup-keys",label:"Global Lookup Keys",path:"global-lookup-keys",active:0===links.length}),links},$scope.links=$scope.buildLinks(!1),$scope.$emit("sidebar-nav:view:reset"),$scope.$on("$locationChangeStart",function(e){$scope.hasOwnProperty("systemConfig")&&(dfObjectService.compareObjectsAsJson($scope.systemConfig.record,$scope.systemConfig.recordCopy)||dfNotify.confirmNoSave()||e.preventDefault())}),$scope.dfLargeHelp={systemInfo:{title:"System Info Overview",text:"Displays current system information."},cacheConfig:{title:"Cache Overview",text:"Flush system-wide cache or per-service caches. Use the cache clearing buttons below to refresh any changes made to your system configuration values."},corsConfig:{title:"CORS Overview",text:"Enter allowed hosts and HTTP verbs. You can enter * for all hosts. Use the * option for development to enable application code running locally on your computer to communicate directly with your DreamFactory instance."},emailTemplates:{title:"Email Templates Overview",text:"Create and edit email templates for User Registration, User Invite, Password Reset, and your custom email services."},globalLookupKeys:{title:"Global Lookup Keys Overview",text:'An administrator can create any number of "key value" pairs attached to DreamFactory. The key values are automatically substituted on the server. For example, you can use Lookup Keys in Email Templates, as parameters in external REST Services, and in the username and password fields to connect to a SQL or NoSQL database. Mark any Lookup Key as private to securely encrypt the key value on the server and hide it in the user interface. Note that Lookup Keys for REST service configuration and credentials must be private.'}},$scope.apiData={},$scope.loadTabData=function(){var apis=["cache","environment","cors","lookup","email_template","custom"];angular.forEach(apis,function(api){dfApplicationData.getApiData([api]).then(function(response){$scope.apiData[api]=response[0].resource?response[0].resource:response[0]},function(error){}).finally(function(){$scope.links=$scope.buildLinks(!0),$scope.$emit("sidebar-nav:view:reset")})})},$scope.loadTabData()}]).directive("dreamfactorySystemInfo",["MODSYSCONFIG_ASSET_PATH","LicenseDataService","SystemConfigDataService",function(MODSYSCONFIG_ASSET_PATH,LicenseDataService,SystemConfigDataService){return{restrict:"E",scope:!1,templateUrl:MODSYSCONFIG_ASSET_PATH+"views/system-info.html",link:function(scope,elem,attrs){scope.paidLicense=!1,scope.upgrade=function(){window.top.location="http://wiki.dreamfactory.com/"};var platform=SystemConfigDataService.getSystemConfig().platform;platform&&platform.hasOwnProperty("license")&&LicenseDataService.isLicenseRequiredSubscription(platform.license)?(scope.paidLicense=!0,LicenseDataService.getSubscriptionData().then(function(data){scope.subscriptionData=data})):scope.subscriptionData={};var watchEnvironment=scope.$watchCollection("apiData.environment",function(newValue,oldValue){newValue&&(scope.systemEnv=newValue)});scope.$on("$destroy",function(e){watchEnvironment()})}}}]).directive("dreamfactoryCacheConfig",["MODSYSCONFIG_ASSET_PATH","INSTANCE_URL","$http","dfNotify",function(MODSYSCONFIG_ASSET_PATH,INSTANCE_URL,$http,dfNotify){return{restrict:"E",scope:!1,templateUrl:MODSYSCONFIG_ASSET_PATH+"views/cache-config.html",link:function(scope,elem,attrs){scope.apiData.cache&&scope.apiData.cache.length>0&&scope.apiData.cache.sort(function(a,b){return a.label>b.label?1:a.label0?scope.adminRoleId=result.data.user_to_app_to_role_by_user_id[0].role_id:(scope.adminRoleId=null,scope.widgetDescription="Restricted admin. An auto-generated role will be created for this admin.")},function(result){scope.adminRoleId=null,console.error(result)})}}),watchPassword=scope.$watch("setPassword",function(newValue){newValue?scope.password={new_password:"",verify_password:""}:(scope.password=null,scope.identical=!0)});scope.$on("$destroy",function(e){watchAdminData(),watchPassword()}),scope.dfHelp={adminConfirmation:{title:"Admin Confirmation Info",text:"Is the admin confirmed? You can send an invite to unconfirmed admins."},adminLookupKeys:{title:"Admin Lookup Keys Info",text:'The DreamFactory administrator can create any number of "key value" pairs attached to a admin. The key values are automatically substituted on the server. For example, key names can be used in the username and password fields required to hook up a SQL or NoSQL database. They can also be used in Email Templates or as parameters for external REST services. Any Lookup Key can be marked as private, and in this case the key value is securely encrypted on the server and is no longer accessible through the platform interface. Lookup keys for service configuration and credentials must be made private.'}}}}}]).directive("dfConfirmAdmin",["INSTANCE_URL","MOD_ADMIN_ASSET_PATH","$http","SystemConfigDataService","dfNotify",function(INSTANCE_URL,MOD_ADMIN_ASSET_PATH,$http,SystemConfigDataService,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_ADMIN_ASSET_PATH+"views/df-input-confirm-admin.html",link:function(scope,elem,attrs){scope.sendEmailOnCreate=!1,scope.invite=function(){$http({url:INSTANCE_URL.url+"/system/admin/"+scope.admin.record.id,method:"PATCH",params:{send_invite:!0}}).then(function(result){var messageOptions={module:"Admins",type:"success",provider:"dreamfactory",message:"Admin invite has been sent."};dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Admins",type:"error",provider:"dreamfactory",exception:reject.data};dfNotify.error(messageOptions)})}}}}]).directive("dfAccessByTabs",["INSTANCE_URL","MOD_ADMIN_ASSET_PATH","$http","SystemConfigDataService","UserDataService","dfApplicationData",function(INSTANCE_URL,MOD_ADMIN_ASSET_PATH,$http,SystemConfigDataService,UserDataService,dfApplicationData){return{restrict:"E",scope:!1,templateUrl:MOD_ADMIN_ASSET_PATH+"views/df-access-by-tabs.html",link:function(scope,elem,attrs){var currentUser=UserDataService.getCurrentUser();scope.accessByTabsLoaded=!1,scope.subscription_required=!dfApplicationData.isGoldLicense(),scope.isRootAdmin=currentUser.is_root_admin,scope.widgetDescription="Restricted admin. An auto-generated role will be created for this admin.",scope.accessByTabs=[{name:"apps",title:"Apps",checked:!0},{name:"users",title:"Users",checked:!0},{name:"services",title:"Services",checked:!0},{name:"apidocs",title:"API Docs",checked:!0},{name:"schema/data",title:"Schema/Data",checked:!0},{name:"files",title:"Files",checked:!0},{name:"scripts",title:"Scripts",checked:!0},{name:"config",title:"Config",checked:!0},{name:"packages",title:"Packages",checked:!0},{name:"limits",title:"Limits",checked:!0},{name:"scheduler",title:"Scheduler",checked:!0}],scope.areAllTabsSelected=!0,scope.selectTab=function(){scope.areAllTabsSelected=scope.accessByTabs.every(function(tab){return tab.checked})},scope.selectAllTabs=function(isSelected){scope.areAllTabsSelected=isSelected,scope.areAllTabsSelected?scope.accessByTabs.forEach(function(tab){tab.checked=!0}):scope.accessByTabs.forEach(function(tab){tab.checked=!1})};var watchAccessTabsData=scope.$watch("adminRoleId",function(newValue,oldValue){newValue&&(scope.widgetDescription="Restricted admin. Role id: "+newValue,$http.get(INSTANCE_URL.url+"/system/role/"+newValue+"/?accessible_tabs=true").then(function(result){scope.accessByTabs.forEach(function(tab){result.data.accessible_tabs&&-1===result.data.accessible_tabs.indexOf(tab.name)&&(tab.checked=!1)}),scope.areAllTabsSelected=scope.accessByTabs.every(function(tab){return!0===tab.checked})},function(result){console.error(result)}))});scope.$on("$destroy",function(e){watchAccessTabsData()})}}}]).directive("dfAdminLookupKeys",["MOD_ADMIN_ASSET_PATH",function(MOD_ADMIN_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_ADMIN_ASSET_PATH+"views/df-input-lookup-keys.html",link:function(scope,elem,attrs){var LookupKey=function(lookupKeyData){var _new={name:"",value:"",private:!1,allow_admin_update:!1};return{__dfUI:{unique:!0},record:angular.copy(lookupKeyData||_new),recordCopy:angular.copy(lookupKeyData||_new)}};scope.lookupKeys=[],scope.sameKeys=[],scope.newKey=function(){scope._newKey()},scope.removeKey=function(index){scope._removeKey(index)},scope._isUniqueKey=function(){scope.sameKeys=[],angular.forEach(scope.lookupKeys,function(value,index){angular.forEach(scope.lookupKeys,function(_value,_index){index!==_index&&value.record.name===_value.record.name&&scope.sameKeys.push(value)})})},scope._preparePasswordData=function(){scope.setPassword?scope.admin.record.password=scope.password.new_password:scope.admin.record.password&&delete scope.admin.record.password},scope._prepareAccessByTabsData=function(){var accessByTabs=[];scope.accessByTabs.forEach(function(tab){tab.checked&&accessByTabs.push(tab.name)}),scope.admin.record.access_by_tabs=accessByTabs,scope.admin.record.is_restricted_admin=!scope.areAllTabsSelected||!!scope.adminRoleId},scope._prepareLookupKeyData=function(){var tempArr=[];angular.forEach(scope.lookupKeys,function(lk){tempArr.push(lk.record)}),scope.admin.record.lookup_by_user_id=tempArr},scope._newKey=function(){scope.lookupKeys.push(new LookupKey)},scope._removeKey=function(index){void 0!==scope.lookupKeys[index].record.user_id?scope.lookupKeys[index].record.user_id=null:scope.lookupKeys.splice(index,1)};var watchAdmin=scope.$watch("admin",function(newValue,oldValue){newValue&&(newValue.record.hasOwnProperty("lookup_by_user_id")&&newValue.record.lookup_by_user_id.length>0?(scope.lookupKeys=[],angular.forEach(newValue.record.lookup_by_user_id,function(lookupKeyData){scope.lookupKeys.push(new LookupKey(lookupKeyData))})):scope.lookupKeys=[])}),watchSameKeys=scope.$watch("sameKeys",function(newValue,oldValue){0!==newValue.length?angular.forEach(scope.lookupKeys,function(lk){angular.forEach(newValue,function(_lk){lk.record.name===_lk.record.name?lk.__dfUI.unique=!1:lk.__dfUI.unique=!0})}):angular.forEach(scope.lookupKeys,function(lk){lk.__dfUI.unique=!0})});scope.$watchCollection("lookupKeys",function(newValue,oldValue){newValue&&scope._isUniqueKey()});scope.$on("$destroy",function(e){watchAdmin(),watchSameKeys()})}}}]).directive("dfManageAdmins",["$rootScope","MOD_ADMIN_ASSET_PATH","dfApplicationData","dfNotify","$location",function($rootScope,MOD_ADMIN_ASSET_PATH,dfApplicationData,dfNotify,$location){return{restrict:"E",scope:!1,templateUrl:MOD_ADMIN_ASSET_PATH+"views/df-manage-admins.html",link:function(scope,elem,attrs){var ManagedAdmin=function(adminData){return adminData&&(adminData.confirm_msg="N/A",!0===adminData.confirmed?adminData.confirm_msg="Confirmed":!1===adminData.confirmed&&(adminData.confirm_msg="Pending"),!0===adminData.expired&&(adminData.confirm_msg="Expired")),{__dfUI:{selected:!1},record:adminData}};scope.uploadFile=null,scope.admins=null,scope.currentEditAdmin=null,scope.fields=[{name:"id",label:"ID",active:!0},{name:"email",label:"Email",active:!0},{name:"name",label:"Display Name",active:!0},{name:"first_name",label:"First Name",active:!0},{name:"last_name",label:"Last Name",active:!0},{name:"is_active",label:"Active",active:!0},{name:"confirmed",label:"Registration",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedAdmins=[],scope.editAdmin=function(admin){scope._editAdmin(admin)},scope.deleteAdmin=function(admin){dfNotify.confirm("Delete "+admin.record.name+"?")&&scope._deleteAdmin(admin)},scope.deleteSelectedAdmins=function(){dfNotify.confirm("Delete selected admins?")&&scope._deleteSelectedAdmins()},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setSelected=function(admin){scope._setSelected(admin)},scope._editAdmin=function(admin){scope.currentEditAdmin=admin},scope._deleteAdmin=function(admin){var requestDataObj={params:{id:admin.record.id}};dfApplicationData.deleteApiData("admin",requestDataObj).$promise.then(function(result){var messageOptions={module:"Admins",type:"success",provider:"dreamfactory",message:"Admin successfully deleted."};dfNotify.success(messageOptions),admin.__dfUI.selected&&scope.setSelected(admin),scope.$broadcast("toolbar:paginate:admin:delete")},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope._setSelected=function(admin){for(var i=0;i"}}]).directive("dfImportAdmins",["MOD_ADMIN_ASSET_PATH","INSTANCE_URL","$http","dfTableEventService","dfNotify",function(MOD_ADMIN_ASSET_PATH,INSTANCE_URL,$http,dfTableEventService,dfNotify){return{restrict:"A",scope:!1,replace:!0,link:function(scope,elem,attrs){scope.importType=null,scope.field=angular.element("#upload"),scope.importAdmins=function(){scope._importAdmins()},scope._importAdmins=function(){scope.field.trigger("click")},scope._uploadFile=function(fileObj){return $http({method:"POST",url:INSTANCE_URL.url+"/system/admin",headers:{"Content-Type":"csv"===scope.importType?"text/csv":"application/"+scope.importType},params:{},data:fileObj})},scope._checkFileType=function(fileObj){var extension=fileObj.name.split("."),value=!1;switch(extension=extension[extension.length-1]){case"csv":case"json":case"xml":scope.importType=extension,value=!0;break;default:value=!1}return value},scope.$watch("uploadFile",function(newValue,oldValue){if(!newValue)return!1;if(newValue=scope.uploadFile,!scope._checkFileType(newValue)){scope.uploadFile=null;var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:"Acceptable file formats are csv, json, and xml."};return dfNotify.error(messageOptions),!1}scope._uploadFile(newValue).then(function(result){scope.importType=null,scope.uploadFile=null,$("#upload").val("");var messageOptions={module:"Admins",type:"success",provider:"dreamfactory",message:"Admins imported successfully."};dfNotify.success(messageOptions),scope.$broadcast("toolbar:paginate:admin:reset")},function(reject){scope.importType=null,scope.uploadFile=null,$("#upload").val("");var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions),scope.$broadcast("toolbar:paginate:admin:reset")})})}}}]).directive("dfExportAdmins",["MOD_ADMIN_ASSET_PATH","INSTANCE_URL","UserDataService","$http","$window","APP_API_KEY",function(MOD_ADMIN_ASSET_PATH,INSTANCE_URL,UserDataService,$http,$window,APP_API_KEY){return{restrict:"A",scope:!1,replace:!0,link:function(scope,elem,attrs){scope.fileFormatStr=null,scope.exportAdmins=function(fileFormatStr){scope._exportAdmins(fileFormatStr)},scope._getFile=function(urlStr){return $http({method:"GET",url:urlStr})},scope._exportAdmins=function(fileFormatStr){if("csv"===fileFormatStr||"json"===fileFormatStr||"xml"===fileFormatStr){scope.fileFormatStr=fileFormatStr;var params="file=admin."+scope.fileFormatStr+"&api_key="+APP_API_KEY,currentUser=UserDataService.getCurrentUser();currentUser&¤tUser.session_token&&(params+="&session_token="+currentUser.session_token),$window.location.href=INSTANCE_URL.url+"/system/admin?"+params}}}}}]),angular.module("dfUsers",["ngRoute","dfUtility","dfApplication","dfHelp"]).constant("MOD_USER_ROUTER_PATH","/users").constant("MOD_USER_ASSET_PATH","admin_components/adf-users/").config(["$routeProvider","MOD_USER_ROUTER_PATH","MOD_USER_ASSET_PATH",function($routeProvider,MOD_USER_ROUTER_PATH,MOD_USER_ASSET_PATH){$routeProvider.when(MOD_USER_ROUTER_PATH,{templateUrl:MOD_USER_ASSET_PATH+"views/main.html",controller:"UsersCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("UsersCtrl",["$rootScope","$scope","dfApplicationData","dfNotify","$location",function($rootScope,$scope,dfApplicationData,dfNotify,$location){$scope.$parent.title="Users",$scope.$parent.titleIcon="users",$scope.links=[{name:"manage-users",label:"Manage",path:"manage-users"},{name:"create-user",label:"Create",path:"create-user"}],$scope.emptySectionOptions={title:"You have no Users!",text:"Click the button below to get started adding users. You can always create new users by clicking the tab located in the section menu to the left.",buttonText:"Create A User!",viewLink:$scope.links[1],active:!1},$scope.emptySearchResult={title:"You have no Users that match your search criteria!",text:""},$scope.apiData=null,$scope.loadTabData=function(){$scope.dataLoading=!0;var apis=["user","role","app"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData},function(error){var msg="There was an error loading data for the Users tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Users tab your role must allow GET access to system/user, system/role, and system/app. To create, update, or delete users you need POST, PUT, DELETE access to /system/user and/or /system/user/*.",$location.url("/home"));var messageOptions={module:"Users",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData()}]).directive("dfUserDetails",["MOD_USER_ASSET_PATH","dfApplicationData","dfNotify","dfObjectService","INSTANCE_URL","$http","$cookies","UserDataService","$rootScope","SystemConfigDataService",function(MOD_USER_ASSET_PATH,dfApplicationData,dfNotify,dfObjectService,INSTANCE_URL,$http,$cookies,UserDataService,$rootScope,SystemConfigDataService){return{restrict:"E",scope:{userData:"=?",newUser:"=?",apiData:"=?"},templateUrl:MOD_USER_ASSET_PATH+"views/df-user-details.html",link:function(scope,elem,attrs){var User=function(userData){var _user={name:null,first_name:null,last_name:null,email:null,phone:null,confirmed:!1,is_active:!0,default_app_id:null,user_source:0,user_data:[],password:null,lookup_by_user_id:[],user_to_app_to_role_by_user_id:[]};return userData=userData||_user,{__dfUI:{selected:!1},record:angular.copy(userData),recordCopy:angular.copy(userData)}};scope.loginAttribute="email";var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=systemConfig.authentication.login_attribute),scope.user=null,scope.newUser&&(scope.user=new User),scope.sendEmailOnCreate=!1,scope._validateData=function(){if(scope.newUser){if(!scope.setPassword&&!scope.sendEmailOnCreate)return dfNotify.error({module:"Users",type:"error",message:"Please select email invite or set password."}),!1;if(scope.setPassword&&scope.sendEmailOnCreate)return dfNotify.error({module:"Users",type:"error",message:"Please select email invite or set password, but not both."}),!1}return!scope.setPassword||scope.password.new_password===scope.password.verify_password||(dfNotify.error({module:"Users",type:"error",message:"Passwords do not match."}),!1)},scope.saveUser=function(){scope._validateData()&&(scope.newUser?scope._saveUser():scope._updateUser())},scope.cancelEditor=function(){scope._prepareUserData(),(dfObjectService.compareObjectsAsJson(scope.user.record,scope.user.recordCopy)||dfNotify.confirmNoSave())&&scope.closeEditor()},scope.closeEditor=function(){scope.userData=null,scope.user=new User,scope.roleToAppMap={},scope.lookupKeys=[],scope._resetUserPasswordForm(),scope.$emit("sidebar-nav:view:reset")},scope._prepareUserData=function(){scope._preparePasswordData(),scope._prepareLookupKeyData()},scope._saveUser=function(){scope._prepareUserData();var requestDataObj={params:{fields:"*",related:"user_to_app_to_role_by_user_id,lookup_by_user_id",send_invite:scope.sendEmailOnCreate},data:scope.user.record};dfApplicationData.saveApiData("user",requestDataObj).$promise.then(function(result){var messageOptions={module:"Users",provider:"dreamfactory",type:"success",message:"User saved successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._updateUser=function(){scope._prepareUserData();var requestDataObj={params:{fields:"*",related:"user_to_app_to_role_by_user_id,lookup_by_user_id"},data:scope.user.record};dfApplicationData.updateApiData("user",requestDataObj).$promise.then(function(result){if(result.session_token){var existingUser=UserDataService.getCurrentUser();existingUser.session_token=result.session_token,UserDataService.setCurrentUser(existingUser)}var messageOptions={module:"Users",provider:"dreamfactory",type:"success",message:"User updated successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})};var watchUserData=scope.$watch("userData",function(newValue,oldValue){newValue&&(scope.user=new User(newValue))}),watchPassword=scope.$watch("setPassword",function(newValue){newValue?scope.password={new_password:"",verify_password:""}:(scope.password=null,scope.identical=!0)});scope.$on("$destroy",function(e){watchUserData(),watchPassword()}),scope.dfHelp={userRole:{title:"User Role Info",text:"Roles provide a way to grant or deny access to specific applications and services on a per-user basis. Each user who is not a system admin must be assigned a role. Go to the Roles tab to create and manage roles."},userConfirmation:{title:"User Confirmation Info",text:"Is the user confirmed? You can send an invite to unconfirmed users."},userLookupKeys:{title:"User Lookup Keys Info",text:'The DreamFactory administrator can create any number of "key value" pairs attached to a user. The key values are automatically substituted on the server. For example, key names can be used in the username and password fields required to hook up a SQL or NoSQL database. They can also be used in Email Templates or as parameters for external REST services. Any Lookup Key can be marked as private, and in this case the key value is securely encrypted on the server and is no longer accessible through the platform interface. Lookup keys for service configuration and credentials must be made private.'}}}}}]).directive("dfConfirmUser",["INSTANCE_URL","MOD_USER_ASSET_PATH","$http","dfNotify",function(INSTANCE_URL,MOD_USER_ASSET_PATH,$http,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_USER_ASSET_PATH+"views/df-input-confirm-user.html",link:function(scope,elem,attrs){scope.sendEmailOnCreate=!1,scope.invite=function(){$http({url:INSTANCE_URL.url+"/system/user/"+scope.user.record.id,method:"PATCH",params:{send_invite:!0}}).then(function(result){var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"User invite has been sent."};dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Users",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)})}}}}]).directive("dfUserRoles",["MOD_USER_ASSET_PATH",function(MOD_USER_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_USER_ASSET_PATH+"views/df-user-roles.html",link:function(scope,elem,attrs){scope.roleToAppMap={},scope.$watch("user",function(){scope.user&&scope.user.record.user_to_app_to_role_by_user_id.forEach(function(item){scope.roleToAppMap[item.app_id]=item.role_id})}),scope.selectRole=function(){Object.keys(scope.roleToAppMap).forEach(function(item){scope.roleToAppMap[item]?scope._updateRoleApp(item,scope.roleToAppMap[item]):scope._removeRoleApp(item,scope.roleToAppMap[item])})},scope._removeRoleApp=function(appId){var existing=scope.user.record.user_to_app_to_role_by_user_id.filter(function(item){return item.app_id==appId})[0];existing&&(existing.user_id=null)},scope._updateRoleApp=function(appId,roleId){var existing=scope.user.record.user_to_app_to_role_by_user_id.filter(function(item){return item.app_id==appId})[0];existing?(existing.app_id=appId,existing.role_id=roleId):scope.user.record.user_to_app_to_role_by_user_id.push({app_id:appId,role_id:roleId,user_id:scope.user.record.id})}}}}]).directive("dfUserLookupKeys",["MOD_USER_ASSET_PATH",function(MOD_USER_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_USER_ASSET_PATH+"views/df-input-lookup-keys.html",link:function(scope,elem,attrs){var LookupKey=function(lookupKeyData){var _new={name:"",value:"",private:!1,allow_user_update:!1};return{__dfUI:{unique:!0},record:angular.copy(lookupKeyData||_new),recordCopy:angular.copy(lookupKeyData||_new)}};scope.lookupKeys=[],scope.sameKeys=[],scope.newKey=function(){scope._newKey()},scope.removeKey=function(index){scope._removeKey(index)},scope._isUniqueKey=function(){scope.sameKeys=[],angular.forEach(scope.lookupKeys,function(value,index){angular.forEach(scope.lookupKeys,function(_value,_index){index!==_index&&value.record.name===_value.record.name&&scope.sameKeys.push(value)})})},scope._preparePasswordData=function(){scope.setPassword?scope.user.record.password=scope.password.new_password:scope.user.record.password&&delete scope.user.record.password},scope._prepareLookupKeyData=function(){var tempArr=[];angular.forEach(scope.lookupKeys,function(lk){tempArr.push(lk.record)}),scope.user.record.lookup_by_user_id=tempArr},scope._newKey=function(){scope.lookupKeys.push(new LookupKey)},scope._removeKey=function(index){void 0!==scope.lookupKeys[index].record.user_id?scope.lookupKeys[index].record.user_id=null:scope.lookupKeys.splice(index,1)};var watchUser=scope.$watch("user",function(newValue,oldValue){newValue&&(newValue.record.hasOwnProperty("lookup_by_user_id")&&newValue.record.lookup_by_user_id.length>0?(scope.lookupKeys=[],angular.forEach(newValue.record.lookup_by_user_id,function(lookupKeyData){scope.lookupKeys.push(new LookupKey(lookupKeyData))})):scope.lookupKeys=[])}),watchSameKeys=scope.$watch("sameKeys",function(newValue,oldValue){0!==newValue.length?angular.forEach(scope.lookupKeys,function(lk){angular.forEach(newValue,function(_lk){lk.record.name===_lk.record.name?lk.__dfUI.unique=!1:lk.__dfUI.unique=!0})}):angular.forEach(scope.lookupKeys,function(lk){lk.__dfUI.unique=!0})}),watchLookupKeys=scope.$watchCollection("lookupKeys",function(newValue,oldValue){newValue&&scope._isUniqueKey()});scope.$on("$destroy",function(e){watchUser(),watchSameKeys(),watchLookupKeys()})}}}]).directive("dfManageUsers",["$rootScope","MOD_USER_ASSET_PATH","dfApplicationData","dfNotify",function($rootScope,MOD_USER_ASSET_PATH,dfApplicationData,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_USER_ASSET_PATH+"views/df-manage-users.html",link:function(scope,elem,attrs){var ManagedUser=function(userData){return userData&&(userData.confirm_msg="N/A",!0===userData.confirmed?userData.confirm_msg="Confirmed":!1===userData.confirmed&&(userData.confirm_msg="Pending"),!0===userData.expired&&(userData.confirm_msg="Expired")),{__dfUI:{selected:!1},record:userData}};scope.uploadFile={path:""},scope.users=null,scope.currentEditUser=null,scope.fields=[{name:"id",label:"ID",active:!0},{name:"email",label:"Email",active:!0},{name:"name",label:"Display Name",active:!0},{name:"first_name",label:"First Name",active:!0},{name:"last_name",label:"Last Name",active:!0},{name:"is_active",label:"Active",active:!0},{name:"confirmed",label:"Registration",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedUsers=[],scope.editUser=function(user){scope._editUser(user)},scope.deleteUser=function(user){dfNotify.confirm("Delete "+user.record.name+"?")&&scope._deleteUser(user)},scope.deleteSelectedUsers=function(){dfNotify.confirm("Delete selected users?")&&scope._deleteSelectedUsers()},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setSelected=function(user){scope._setSelected(user)},scope._editUser=function(user){scope.currentEditUser=user},scope._deleteUser=function(user){var requestDataObj={params:{id:user.record.id}};dfApplicationData.deleteApiData("user",requestDataObj).$promise.then(function(result){var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"User successfully deleted."};dfNotify.success(messageOptions),user.__dfUI.selected&&scope.setSelected(user),scope.$broadcast("toolbar:paginate:user:delete")},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope._setSelected=function(user){for(var i=0;i"}}]).directive("dfImportUsers",["MOD_USER_ASSET_PATH","INSTANCE_URL","$http","dfTableEventService","dfNotify",function(MOD_USER_ASSET_PATH,INSTANCE_URL,$http,dfTableEventService,dfNotify){return{restrict:"A",scope:!1,replace:!0,link:function(scope,elem,attrs){scope.importType=null,scope.field=angular.element("#upload"),scope.importUsers=function(){scope._importUsers()},scope._importUsers=function(){scope.field.trigger("click")},scope._uploadFile=function(fileObj){return $http({method:"POST",url:INSTANCE_URL.url+"/system/user",headers:{"Content-Type":"csv"===scope.importType?"text/csv":"application/"+scope.importType},params:{},data:fileObj})},scope._checkFileType=function(fileObj){var extension=fileObj.name.split("."),value=!1;switch(extension=extension[extension.length-1]){case"csv":case"json":case"xml":scope.importType=extension,value=!0;break;default:value=!1}return value},scope.$watch("uploadFile.path",function(newValue,oldValue){if(!newValue)return!1;if(newValue=scope.uploadFile.path,!scope._checkFileType(newValue)){scope.uploadFile.path="";var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:"Acceptable file formats are csv, json, and xml."};return dfNotify.error(messageOptions),!1}scope._uploadFile(newValue).then(function(result){scope.importType=null,scope.uploadFile.path="",$("#upload").val("");var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"Users imported successfully."};dfNotify.success(messageOptions),scope.$broadcast("toolbar:paginate:user:reset")},function(reject){scope.importType=null,scope.uploadFile.path="",$("#upload").val("");var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions),scope.$broadcast("toolbar:paginate:user:reset")})})}}}]).directive("dfExportUsers",["MOD_USER_ASSET_PATH","INSTANCE_URL","UserDataService","$http","$window","APP_API_KEY",function(MOD_USER_ASSET_PATH,INSTANCE_URL,UserDataService,$http,$window,APP_API_KEY){return{restrict:"A",scope:!1,replace:!0,link:function(scope,elem,attrs){scope.fileFormatStr=null,scope.exportUsers=function(fileFormatStr){scope._exportUsers(fileFormatStr)},scope._getFile=function(urlStr){return $http({method:"GET",url:urlStr})},scope._exportUsers=function(fileFormatStr){if("csv"===fileFormatStr||"json"===fileFormatStr||"xml"===fileFormatStr){scope.fileFormatStr=fileFormatStr;var params="file=user."+scope.fileFormatStr+"&api_key="+APP_API_KEY,currentUser=UserDataService.getCurrentUser();currentUser&¤tUser.session_token&&(params+="&session_token="+currentUser.session_token),$window.location.href=INSTANCE_URL.url+"/system/user?"+params}}}}}]),angular.module("dfApps",["ngRoute","dfUtility","dfApplication","dfHelp","dfTable"]).constant("MOD_APPS_ROUTER_PATH","/apps").constant("MOD_APPS_ASSET_PATH","admin_components/adf-apps/").config(["$routeProvider","MOD_APPS_ROUTER_PATH","MOD_APPS_ASSET_PATH",function($routeProvider,MOD_APPS_ROUTER_PATH,MOD_APPS_ASSET_PATH){$routeProvider.when(MOD_APPS_ROUTER_PATH,{templateUrl:MOD_APPS_ASSET_PATH+"views/main.html",controller:"AppsCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("AppsCtrl",["$rootScope","$scope","dfApplicationData","dfNotify","$location",function($rootScope,$scope,dfApplicationData,dfNotify,$location){$scope.$parent.title="Apps",$scope.$parent.titleIcon="desktop",$scope.links=[{name:"manage-apps",label:"Manage",path:"manage-apps"},{name:"create-app",label:"Create",path:"create-app"},{name:"import-app",label:"Import",path:"import-app"}],$scope.emptySectionOptions={title:"You have no Apps!",text:"Click the button below to get started building your first application. You can always create new applications by clicking the tab located in the section menu to the left.",buttonText:"Create An App!",viewLink:$scope.links[1],active:!1},$scope.emptySearchResult={title:"You have no Apps that match your search criteria!",text:""},$scope.$on("$destroy",function(e){$scope.$broadcast("toolbar:paginate:app:destroy")}),$scope.apiData=null,$scope.loadTabData=function(init){$scope.dataLoading=!0;var apis=["app","role","service"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index],"service"===value&&(newApiData[value]=newApiData[value].filter(function(obj){return["local_file","aws_s3","azure_blob","rackspace_cloud_files","openstack_object_storage","ftp_file","sftp_file","gridfs"].indexOf(obj.type)>=0}))}),$scope.apiData=newApiData,init&&$scope.$broadcast("toolbar:paginate:app:load")},function(error){var msg="There was an error loading data for the Apps tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Apps tab your role must allow GET access to system/app, system/role, and system/service. To create, update, or delete apps you need POST, PUT, DELETE access to /system/app and/or /system/app/*.",$location.url("/home"));var messageOptions={module:"Apps",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(!0)}]).directive("dfAppDetails",["MOD_APPS_ASSET_PATH","dfServerInfoService","dfApplicationData","dfNotify","dfObjectService",function(MOD_APPS_ASSET_PATH,dfServerInfoService,dfApplicationData,dfNotify,dfObjectService){return{restrict:"E",scope:{appData:"=?",newApp:"=?",apiData:"=?"},templateUrl:MOD_APPS_ASSET_PATH+"views/df-app-details.html",link:function(scope,elem,attrs){var getLocalFileStorageServiceId=function(){var localFileSvc=scope.apiData.service.filter(function(obj){return"local_file"===obj.type});return localFileSvc&&localFileSvc.length>0?localFileSvc[0].id:null},App=function(appData){var _app={name:"",description:"",type:0,storage_service_id:getLocalFileStorageServiceId(),storage_container:"applications",path:"",url:"",role_id:null};return appData=appData||_app,{__dfUI:{selected:!1},record:angular.copy(appData),recordCopy:angular.copy(appData)}};scope.currentServer=dfServerInfoService.currentServer(),scope.app=null,scope.locations=[{label:"No Storage Required - remote device, client, or desktop.",value:"0"},{label:"On a provisioned file storage service.",value:"1"},{label:"On this web server.",value:"3"},{label:"On a remote URL.",value:"2"}],scope.newApp&&(scope.app=new App),scope.saveApp=function(){scope.newApp?scope._saveApp():scope._updateApp()},scope.cancelEditor=function(){(dfObjectService.compareObjectsAsJson(scope.app.record,scope.app.recordCopy)||dfNotify.confirmNoSave())&&scope.closeEditor()},scope._prepareAppData=function(record){var _app=angular.copy(record);switch(parseInt(_app.record.type)){case 0:delete _app.record.storage_service_id,delete _app.record.storage_container,delete _app.record.path,delete _app.record.url;break;case 1:delete _app.record.url;break;case 2:delete _app.record.storage_service_id,delete _app.record.storage_container,delete _app.record.path;break;case 3:delete _app.record.storage_service_id,delete _app.record.storage_container,delete _app.record.url}return _app.record},scope.closeEditor=function(){scope.appData=null,scope.app=new App,scope.$emit("sidebar-nav:view:reset")},scope._saveApp=function(){var requestDataObj={params:{fields:"*",related:"role_by_role_id"},data:scope._prepareAppData(scope.app)};dfApplicationData.saveApiData("app",requestDataObj).$promise.then(function(result){var messageOptions={module:"Apps",type:"success",provider:"dreamfactory",message:scope.app.record.name+" saved successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._updateApp=function(){var requestDataObj={params:{fields:"*",related:"role_by_role_id"},data:scope._prepareAppData(scope.app)};dfApplicationData.updateApiData("app",requestDataObj).$promise.then(function(result){var messageOptions={module:"Apps",type:"success",provider:"dreamfactory",message:scope.app.record.name+" updated successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})};var watchAppStorageService=scope.$watch("app.record.storage_service_id",function(newValue,oldValue){scope.app&&scope.app.record&&scope.apiData.service&&(scope.selectedStorageService=scope.apiData.service.filter(function(item){return item.id==scope.app.record.storage_service_id})[0])}),watchAppData=scope.$watch("appData",function(newValue,oldValue){newValue&&(scope.app=new App(newValue))});scope.$on("$destroy",function(e){watchAppStorageService(),watchAppData()}),scope.dfHelp={applicationName:{title:"Application API Key",text:"This API KEY is unique per application and must be included with each API request as a query param (api_key=yourapikey) or a header (X-DreamFactory-API-Key: yourapikey)."},name:{title:"Display Name",text:"The display name or label for your app, seen by users of the app in the LaunchPad UI."},description:{title:"Description",text:"The app description, seen by users of the app in the LaunchPad UI."},appLocation:{title:"App Location",text:"Select File Storage if you want to store your app code on your DreamFactory instance or some other remote file storage. Select Native for native apps or running the app from code on your local machine (CORS required). Select URL to specify a URL for your app."},storageService:{title:"Storage Service",text:"Where to store the files for your app."},storageContainer:{title:"Storage Folder",text:"The folder on the selected storage service."},defaultPath:{title:"Default Path",text:"The is the file to load when your app is run. Default is index.html."},remoteUrl:{title:"Remote Url",text:"Applications can consist of only a URL. This could be an app on some other server or a web site URL."},assignRole:{title:"Assign a Default Role",text:"Unauthenticated or guest users of the app will have this role."}}}}}]).directive("dfManageApps",["$rootScope","MOD_APPS_ASSET_PATH","dfApplicationData","dfNotify","$window",function($rootScope,MOD_APPS_ASSET_PATH,dfApplicationData,dfNotify,$window){return{restrict:"E",scope:!1,templateUrl:MOD_APPS_ASSET_PATH+"views/df-manage-apps.html",link:function(scope,elem,attrs){var ManagedApp=function(appData){return{__dfUI:{selected:!1},record:appData}};scope.apps=null,scope.currentEditApp=null,scope.fields=[{name:"id",label:"ID",active:!0},{name:"name",label:"Name",active:!0},{name:"role_by_role_id",label:"Role",active:!0},{name:"api_key",label:"API Key",active:!0},{name:"description",label:"Description",active:!0},{name:"is_active",label:"Active",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedApps=[],scope.removeFilesOnDelete=!1,scope.launchApp=function(app){scope._launchApp(app)},scope.editApp=function(app){scope._editApp(app)},scope.deleteApp=function(app){dfNotify.confirm("Delete "+app.record.name+"?")&&(app.record.native||null==app.record.storage_service_id||(scope.removeFilesOnDelete=dfNotify.confirm("Delete application files? Pressing cancel will retain the files in storage.")),scope._deleteApp(app))},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setSelected=function(app){scope._setSelected(app)},scope.deleteSelectedApps=function(){dfNotify.confirm("Delete selected apps?")&&(scope.removeFilesOnDelete=dfNotify.confirm("Delete application files?"),scope._deleteSelectedApps())},scope._launchApp=function(app){$window.open(app.record.launch_url)},scope._editApp=function(app){scope.currentEditApp=app},scope._deleteApp=function(app){var requestDataObj={params:{delete_storage:scope.removeFilesOnDelete,related:"role_by_role_id",fields:"*"},data:app.record};dfApplicationData.deleteApiData("app",requestDataObj).$promise.then(function(result){var messageOptions={module:"Apps",type:"success",provider:"dreamfactory",message:"App successfully deleted."};dfNotify.success(messageOptions),scope.$broadcast("toolbar:paginate:app:delete")},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope._setSelected=function(app){for(var i=0;i"}}]).directive("dfImportApp",["MOD_APPS_ASSET_PATH","$http","dfApplicationData","dfNotify",function(MOD_APPS_ASSET_PATH,$http,dfApplicationData,dfNotify){return{restrict:"E",scope:{apiData:"=?"},templateUrl:MOD_APPS_ASSET_PATH+"views/df-import-app.html",link:function(scope,elem,attrs){scope.containers=[],scope.appPath=null,scope.storageService="",scope.storageContainer="",scope.field=angular.element("#upload"),scope.uploadFile=null,scope.sampleAppsFirstColumn=[{name:"Address Book for Android",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/android-sdk/master/package/add_android.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/android-sdk"},{name:"Address Book for iOS Objective-C",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/ios-sdk/master/example-ios/package/add_ios.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/ios-sdk"},{name:"Address Book for iOS Swift",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/ios-swift-sdk/master/SampleAppSwift/package/add_ios_swift.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/ios-swift-sdk"},{name:"Address Book for JavaScript",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/javascript-sdk/master/add_javascript.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/javascript-sdk"},{name:"Address Book for AngularJS",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/angular-sdk/master/add_angular.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/angular-sdk"}],scope.sampleAppsSecondColumn=[{name:"Address Book for Angular 2",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/angular2-sdk/master/add_angular2.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/angular2-sdk"},{name:"Address Book for Ionic",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/ionic-sdk/master/package/add_ionic.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/ionic-sdk"},{name:"Address Book for Titanium",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/titanium-sdk/master/add_titanium.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/titanium-sdk"},{name:"Address Book for ReactJS",description:"",package_url:"https://github.com/dreamfactorysoftware/df-react-example-application/raw/master/df-react-example-application.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/df-react-example-application"},{name:"Address Book for .NET",description:"",package_url:"https://raw.github.com/dreamfactorysoftware/.net-sdk/master/DreamFactory.AddressBook/App_Package/add_dotnet.dfpkg",repo_url:"https://github.com/dreamfactorysoftware/.net-sdk"}],scope.submitApp=function(){if(!scope.appPath)return!1;scope._submitApp()},scope.browseFileSystem=function(){scope._resetImportApp(),scope.field.trigger("click")},scope.loadSampleApp=function(appObj){scope._loadSampleApp(appObj)},scope._isAppPathUrl=function(appPathStr){return"http://"===appPathStr.substr(0,7)||"https://"===appPathStr.substr(0,8)},scope._importAppToServer=function(requestDataObj){var _options={params:{},data:requestDataObj,dontWrapData:!0};return scope._isAppPathUrl(scope.appPath)?_options.headers={"Content-Type":"application/json"}:(_options.headers={"Content-Type":void 0},$http.defaults.transformRequest=angular.identity),dfApplicationData.saveApiData("app",_options).$promise},scope._isDFPackage=function(appPathStr){return".dfpkg"===appPathStr.substr(appPathStr.lastIndexOf("."))},scope._resetImportApp=function(){scope.appPath=null,scope.storageService="",scope.storageContainer="",scope.uploadFile=null,scope.field.val("")},scope._loadSampleApp=function(appObj){scope.appPath=appObj.package_url},scope._submitApp=function(){var requestDataObj={};if(scope._isAppPathUrl(scope.appPath))requestDataObj={import_url:scope.appPath,storage_service_id:scope.storageService.id,storage_container:scope.storageContainer};else{var fd=new FormData,storageId=scope.storageService&&void 0!==scope.storageService.id?scope.storageService.id:0,storageContainer=scope.storageContainer;fd.append("file",scope.uploadFile),fd.append("storage_service_id",storageId),fd.append("storage_container",storageContainer),requestDataObj=fd}scope._importAppToServer(requestDataObj).then(function(result){var messageOptions={module:"Apps",type:"success",provider:"dreamfactory",message:"App successfully imported."};dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(success){scope._resetImportApp(),$http.defaults.transformRequest=function(d,headers){if(angular.isObject(d))return angular.toJson(d)}})};var watchUploadFile=scope.$watch("uploadFile",function(n,o){n&&(scope.appPath=n.name)});scope.$on("$destroy",function(e){watchUploadFile()}),scope.dfHelp={applicationName:{title:"Application Name",text:"This is some help text that will be displayed in the help window"}}}}}]),angular.module("dfData",["ngRoute","dfUtility","dfTable"]).constant("MOD_DATA_ROUTER_PATH","/data").constant("MOD_DATA_ASSET_PATH","admin_components/adf-data/").config(["$routeProvider","MOD_DATA_ROUTER_PATH","MOD_DATA_ASSET_PATH",function($routeProvider,MOD_DATA_ROUTER_PATH,MOD_DATA_ASSET_PATH){$routeProvider.when(MOD_DATA_ROUTER_PATH,{templateUrl:MOD_DATA_ASSET_PATH+"views/main.html",controller:"DataCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("DataCtrl",["$scope","INSTANCE_URL","dfApplicationData","dfNotify","$location",function($scope,INSTANCE_URL,dfApplicationData,dfNotify,$location){$scope.$parent.title="Data",$scope.$parent.titleIcon="database",$scope.links=[{name:"manage-data",label:"Manage",path:"manage-data"}],$scope.services=null,$scope.selected={service:null,resource:null},$scope.options={service:$scope.selected.service,table:$scope.selected.resource,url:INSTANCE_URL.url+"/"+$scope.selected.service+"/_table/"+$scope.selected.resource,allowChildTable:!0,childTableAttachPoint:"#child-table-attach"},$scope.$watchCollection("selected",function(newValue,oldValue){var options={service:newValue.service,table:newValue.resource,url:INSTANCE_URL.url+"/"+newValue.service+"/_table/"+newValue.resource,allowChildTable:!0,childTableAttachPoint:"#child-table-attach"};$scope.options=options}),$scope.$watchCollection("apiData.service_list",function(newValue,oldValue){newValue&&($scope.services=newValue.filter(function(obj){return["mysql","pgsql","sqlite","sqlsrv","memsql","sqlanywhere","oracle","ibmdb2","informix","firebird","aws_redshift_db","apache_hive","snowflake"].indexOf(obj.type)>=0}))}),$scope.apiData=null,$scope.loadTabData=function(){var apis=["service_list"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData},function(error){var messageOptions={module:"Data",provider:"dreamfactory",type:"error",message:"There was an error loading the Data tab. Please try refreshing your browser and logging in again."};dfNotify.error(messageOptions)})},$scope.loadTabData()}]),angular.module("dfServices",["ngRoute","dfUtility","dfApplication"]).constant("MOD_SERVICES_ROUTER_PATH","/services").constant("MOD_SERVICES_ASSET_PATH","admin_components/adf-services/").config(["$routeProvider","MOD_SERVICES_ROUTER_PATH","MOD_SERVICES_ASSET_PATH",function($routeProvider,MOD_SERVICES_ROUTER_PATH,MOD_SERVICES_ASSET_PATH){$routeProvider.when(MOD_SERVICES_ROUTER_PATH,{templateUrl:MOD_SERVICES_ASSET_PATH+"views/main.html",controller:"ServicesCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).factory("dfSelectedService",function(){return{currentServiceName:null,relatedRole:null,cleanCurrentService:function(){this.currentServiceName=null}}}).controller("ServicesCtrl",["$rootScope","$scope","dfApplicationData","dfNotify","$location",function($rootScope,$scope,dfApplicationData,dfNotify,$location){$scope.$parent.title="Services",$scope.$parent.titleIcon="cubes",$scope.relatedRoles=[],$scope.links=[{name:"manage-services",label:"Manage",path:"manage-services"},{name:"create-service",label:"Create",path:"create-service"}],$scope.emptySearchResult={title:"You have no Services that match your search criteria!",text:""},$scope.emptySectionOptions={title:"You have no Services!",text:'Click the button below to get started building your first Service. You can always create new services by clicking the "Create" tab located in the section menu to the left.',buttonText:"Create A Service!",viewLink:$scope.links[1]},$scope.$on("$destroy",function(e){$scope.$broadcast("toolbar:paginate:service:destroy")}),$scope.apiData=null,$scope.loadTabData=function(init){$scope.dataLoading=!0;var apis=["service","service_link","storage_service_link","service_type","role","environment"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData,init&&$scope.$broadcast("toolbar:paginate:service:load")},function(error){var msg="There was an error loading data for the Services tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Services tab your role must allow GET access to system/service and system/service_type. To create, update, or delete services you need POST, PUT, DELETE access to /system/service and/or /system/service/*.",$location.url("/home"));var messageOptions={module:"Services",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(!0)}]).directive("dfServiceLoading",[function(){return{restrict:"E",template:"
"}}]).directive("dfManageServices",["$rootScope","MOD_SERVICES_ASSET_PATH","dfApplicationData","dfNotify","$http","INSTANCE_URL","dfSelectedService",function($rootScope,MOD_SERVICES_ASSET_PATH,dfApplicationData,dfNotify,$http,INSTANCE_URL,dfSelectedService){return{restrict:"E",scope:!1,templateUrl:MOD_SERVICES_ASSET_PATH+"views/df-manage-services.html",link:function(scope,elem,attrs){var ManagedService=function(serviceData){return{__dfUI:{selected:!1},record:serviceData}};scope.services=[],scope.currentEditService=null,scope.selectedServices=[];var getRelatedRoles=function(){var currentServiceId=scope.currentEditService.id;return scope.apiData.role.filter(function(role){return role.role_service_access_by_role_id.some(function(service){return currentServiceId===service.service_id})})};scope.editService=function(service){scope.currentEditService=service,scope.$root.relatedRoles=getRelatedRoles()},scope.deleteService=function(service){if(dfNotify.confirm("Delete "+service.record.label+"?")){var requestDataObj={params:{id:service.record.id}};dfApplicationData.deleteApiData("service",requestDataObj).$promise.then(function(result){var messageOptions={module:"Services",type:"success",provider:"dreamfactory",message:"Service successfully deleted."};dfNotify.success(messageOptions),service.__dfUI.selected&&scope.setSelected(service),scope.$broadcast("toolbar:paginate:service:delete")},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})}},scope.deleteSelectedServices=function(){if(dfNotify.confirm("Delete selected services?")){var requestDataObj={params:{ids:scope.selectedServices.join(","),rollback:!0}};dfApplicationData.deleteApiData("service",requestDataObj).$promise.then(function(result){var messageOptions={module:"Services",type:"success",provider:"dreamfactory",message:"Services deleted successfully."};dfNotify.success(messageOptions),scope.selectedServices=[],scope.$broadcast("toolbar:paginate:service:reset")},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})}},scope.fields=[{name:"id",label:"ID",active:!0},{name:"name",label:"Name",active:!0},{name:"label",label:"Label",active:!0},{name:"description",label:"Description",active:!0},{name:"type",label:"Type",active:!0},{name:"is_active",label:"Active",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope.setSelected=function(service){for(var i=0;i-1&&data.config[item.name]&&data.config[item.name].length&&convert(item)}),data};scope.testServiceSchema=function(){var url=INSTANCE_URL.url+"/"+scope.serviceInfo.name+"/_schema",serviceName=scope.serviceInfo.name;return $http.get(url).then(function(response){return{type:"success",message:"Test connection succeeded.",serviceName:serviceName}},function(reject){if(!0===scope.apiData.environment.platform.app_debug)errorMessage="Test connection failed
Message: "+reject.data.error.message;else var errorMessage="Test connection failed, could just be a typo. Please check config credentials for Service Name: "+serviceName;return{type:"error",message:errorMessage,serviceName:serviceName}})},scope.isServiceTypeDatabase=function(){return"Database"===scope.selectedSchema.group},scope.notifyTestResults=function(testResult){var messageOptions={module:"Test Result for "+testResult.serviceName,type:testResult.type,message:testResult.message,tag:testResult.serviceName};"success"===messageOptions.type?dfNotify.success(messageOptions):dfNotify.error(messageOptions)},scope.saveService=function(){scope.prepareServiceData();var requestDataObj={params:{fields:"*",related:"service_doc_by_service_id"},data:normalizeKeyValuePairs()};dfApplicationData.saveApiData("service",requestDataObj).$promise.then(function(result){dfApplicationData.getApiData(["service_list"],!0);var messageOptions={module:"Services: "+scope.serviceInfo.name,type:scope.isServiceTypeDatabase()?"testing":"success",provider:"dreamfactory",message:scope.isServiceTypeDatabase()?"Service saved successfully. Now running connection test in the background.":"Service saved successfully.",tag:scope.isServiceTypeDatabase()?scope.serviceInfo.name:null};dfNotify.success(messageOptions),scope.closeEditor(),scope.isServiceTypeDatabase()&&scope.testServiceSchema().then(function(result){scope.notifyTestResults(result)})},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope.updateService=function(){scope.prepareServiceData();var requestDataObj={params:{fields:"*",related:"service_doc_by_service_id"},data:normalizeKeyValuePairs()};dfApplicationData.updateApiData("service",requestDataObj).$promise.then(function(result){var messageOptions={module:"Services: "+scope.serviceInfo.name,type:scope.isServiceTypeDatabase()?"testing":"success",provider:"dreamfactory",message:scope.isServiceTypeDatabase()?"Service updated successfully. Now running connection test in the background.":"Service updated successfully.",tag:scope.isServiceTypeDatabase()?scope.serviceInfo.name:null};scope.selections.saveAndClearCache&&(scope.clearCache(),messageOptions.message=scope.isServiceTypeDatabase()?"Service updated successfully and cache cleared. Now running connection test in the background.":"Service updated and cache successfully."),dfNotify.success(messageOptions),scope.selections.saveAndClose?scope.closeEditor():scope.serviceDetails=new ServiceDetails(result),scope.isServiceTypeDatabase()&&scope.testServiceSchema().then(function(result){scope.notifyTestResults(result)})},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope.refreshServiceConfigEditor=function(){$("#config-tab").tab("show"),scope.isInfoTab=!1;var editor=scope.serviceConfigEditorObj.editor;editor&&(editor.renderer.updateText(),editor.resize(!0),editor.focus())},scope.refreshServiceInfoEditor=function(){scope.isInfoTab=!0},scope.refreshServiceDefEditor=function(){scope.isInfoTab=!1;var editor=scope.serviceDefEditorObj.editor;editor&&(editor.renderer.updateText(),editor.resize(!0),editor.focus())},scope.serviceTypeToSchema=function(type){var schema=(scope.newService?scope.creatableServiceTypes:scope.editableServiceTypes).filter(function(item){return item.name===type});return schema.length>0?schema[0]:null};var watchServiceData=scope.$watch("serviceData",function(newValue,oldValue){scope.serviceDetails=new ServiceDetails(newValue),scope.updateHelpText(newValue)});scope.$on("$destroy",function(e){watchServiceData()}),scope.dfHelp={createService:{title:"Create Service Information",text:"Create Service information help text"}},scope.updateHelpText=function(record){var details,configText,serviceDefText,serviceDefReadOnlyText;details=" this service ",record&&record.label&&(details=" "+record.label+" "),configText="Specify any service-specific configuration for"+details+"below.",details="remote and script services",record&&record.label&&(details=" "+record.label+""),serviceDefText="For "+details+', you can specify a definition of the service below. Refer to the OpenAPI docs for details, or build and export your own from here.',details=" this service ",record&&record.label&&(details=" "+record.label+" "),serviceDefReadOnlyText="The service definition for "+details+"is pre-defined and can not be edited.",scope.dfLargeHelp={basic:{title:"Services Overview",text:"Services are where you set up REST API connections to databases, file storage, email, remote web services, and more."},config:{title:"Config Overview",text:configText},serviceDef:{title:"Service Definition Overview",text:serviceDefText},serviceDefReadOnly:{title:"Service Definition Overview",text:serviceDefReadOnlyText}}}}}}]).directive("dfServiceInfo",["MOD_SERVICES_ASSET_PATH","SystemConfigDataService","dfNotify","$location","dfSelectedService",function(MOD_SERVICES_ASSET_PATH,SystemConfigDataService,dfNotify,$location,dfSelectedService){return{restrict:"E",scope:!1,templateUrl:MOD_SERVICES_ASSET_PATH+"views/df-service-info.html",link:function(scope,elem,attrs){scope.serviceTypes=[],scope.serviceInfoError=!1,scope.serviceInfo={},scope.prepareServiceInfo=function(){return scope.serviceInfo},scope.sortArray=function(groupsArray,orderArray){var result=[];if(orderArray.forEach(function(group){-1!==groupsArray.indexOf(group)&&result.push(group)}),groupsArray.length>orderArray.length){var unsortedGroups=groupsArray.filter(function(i){return result.indexOf(i)<0});result.push.apply(result,unsortedGroups)}return result},scope.updateAffectedFields=function(fieldValue,field){if("driver"===field.name&&field.values){var foundValue=field.values.filter(function(item){return item.name===fieldValue})[0]||{};scope.serviceConfig.dsn=foundValue.dsn}},scope.validateServiceName=function(){var isNameValid=scope.serviceInfo.name.match(/^[a-z0-9_-]+$/);if(!isNameValid||0===isNameValid.length){var messageOptions={module:"Services",provider:"dreamfactory",type:"warn",message:"Be sure that service name is in lowercase and alphanumeric. It should only contain letters, numbers, underscores and dashes."};dfNotify.warn(messageOptions)}},scope.addMissingPaidServices=function(types){var silverServices=[{name:"adldap",label:"Active Directory",description:"A service for supporting Active Directory integration",group:"LDAP"},{name:"ldap",label:"Standard LDAP",description:"A service for supporting Open LDAP integration",group:"LDAP"},{name:"oidc",label:"OpenID Connect",description:"OpenID Connect service supporting SSO.",group:"OAuth"},{name:"oauth_azure_ad",label:"Azure Active Directory OAuth",description:"OAuth service for supporting Azure Active Directory authentication and API access.",group:"OAuth"},{name:"saml",label:"SAML 2.0",description:"SAML 2.0 service supporting SSO.",group:"SSO"},{name:"okta_saml",label:"Okta SAML",description:"Okta service supporting SSO.",group:"SSO"},{name:"auth0_sso",label:"Auth0 SSO",description:"Auth0 service supporting SSO.",group:"SSO"},{name:"ibmdb2",label:"IBM DB2",description:"Database service supporting IBM DB2 SQL connections.",group:"Database"},{name:"informix",label:"IBM Informix",description:"Database service supporting IBM Informix SQL connections.",group:"Database"},{name:"oracle",label:"Oracle",description:"Database service supporting SQL connections.",group:"Database"},{name:"salesforce_db",label:"Salesforce",description:"Database service with SOAP and/or OAuth authentication support for Salesforce connections.",group:"Database"},{name:"soap",label:"SOAP Service",description:"A service to handle SOAP Services",group:"Remote Service"},{name:"sqlanywhere",label:"SAP SQL Anywhere",description:"Database service supporting SAP SQL Anywhere connections.",group:"Database"},{name:"sqlsrv",label:"SQL Server",description:"Database service supporting SQL Server connections.",group:"Database"},{name:"memsql",label:"MemSQL",description:"Database service supporting MemSQL connections.",group:"Database"},{name:"apns",label:"Apple Push Notification",description:"Apple Push Notification Service Provider.",group:"Notification"},{name:"gcm",label:"GCM Push Notification",description:"GCM Push Notification Service Provider.",group:"Notification"},{name:"mqtt",label:"MQTT Client",description:"MQTT Client based on Mosquitto.",group:"IoT"},{name:"mysql",label:"MySQL",description:"Database service supporting MySLQ connections.",group:"Database"},{name:"mariadb",label:"MariaDB",description:"Database service supporting MariaDB connections.",group:"Database"},{name:"nodejs",label:"Node.js",description:"Service that allows client-callable scripts utilizing the system scripting.",group:"Script"},{name:"php",label:"PHP",description:"Service that allows client-callable scripts utilizing the system scripting.",group:"Script"},{name:"python",label:"Python",description:"Service that allows client-callable scripts utilizing the system scripting.",group:"Script"},{name:"python3",label:"Python3",description:"Service that allows client-callable scripts utilizing the system scripting.",group:"Script"},{name:"mongodb",label:"MongoDB",description:"Database service for MongoDB connections.",group:"Database"},{name:"gridfs",label:"GridFS",description:"GridFS File Storage services.",group:"File"}],goldServices=[{name:"logstash",label:"Logstash",description:"Logstash service.",group:"Log"},{name:"snowflake",label:"Snowflake",description:"Database service supporting Snowflake connections.",group:"Big Data"},{name:"apache_hive",label:"Apache Hive",description:"The Apache Hive data warehouse software facilitates reading, writing, and managing large datasets residing in distributed storage using SQL",group:"Big Data"},{name:"hadoop_hdfs",label:"Hadoop HDFS",description:"Hadoop Distributed File System",group:"File"}],add=[];return angular.forEach(silverServices,function(svc){0===types.filter(function(type){return svc.name===type.name}).length&&(svc.singleton=!1,svc.available=!1,svc.config_schema=null,svc.subscription_required="SILVER",add.push(svc))}),angular.forEach(goldServices,function(svc){0===types.filter(function(type){return svc.name===type.name}).length&&(svc.singleton=!1,svc.available=!1,svc.config_schema=null,svc.subscription_required="GOLD",add.push(svc))}),types=types.concat(add),angular.forEach(types,function(svc){svc.hasOwnProperty("available")||(svc.available=!0)}),types},scope.changeServiceType=function(type){scope.serviceInfo.type=type,scope.serviceConfig={},scope.selectedSchema=scope.serviceTypeToSchema(type),scope.selectedSchema&&scope.decorateSchema(),scope.resetServiceDef()};var watchServiceDetails=scope.$watch("serviceDetails",function(newValue,oldValue){if(!newValue)return!1;scope.serviceInfo=angular.copy(newValue.record)}),watchServiceTypes=scope.$watchCollection("apiData.service_type",function(newValue,oldValue){if(newValue){scope.editableServiceTypes=scope.addMissingPaidServices(newValue),scope.creatableServiceTypes=scope.editableServiceTypes.filter(function(el){return!el.singleton});var typeObj={},groups=scope.creatableServiceTypes.map(function(obj){return typeObj.hasOwnProperty(obj.group)||(typeObj[obj.group]=[]),typeObj[obj.group].push({name:obj.name,label:obj.label}),obj.group});groups=groups.filter(function(v,i){return groups.indexOf(v)===i});var sortingArray=["Database","Big Data","File","Email","Notification","Remote Service","Script","OAuth","LDAP"];groups=scope.sortArray(groups,sortingArray),scope.serviceTypesSingleColLimit=5;var newTypeObj={};angular.forEach(typeObj,function(types,group){var i,j,newTypes=angular.copy(types),limit=scope.serviceTypesSingleColLimit;if(types.length>limit){for(i=0,j=0;i=0&&(service=service.substr(0,index)),temp[service]||(temp[service]=[]),temp[service].push({label:event,name:event})}),angular.forEach(temp,function(items,service){items.unshift({label:"All "+service+" events",name:service+".*"}),serviceEvents.push({label:service,name:service,items:items})}),scope.eventList=serviceEvents)}),watchConfig=scope.$watchCollection("serviceConfig",function(newValue,oldValue){scope.disableServiceLinkRefresh=!scope.getRefreshEnable()}),watchSelections=scope.$watchCollection("selections",function(newValue,oldValue){scope.disableServiceLinkRefresh=!scope.getRefreshEnable(),newValue&&(scope.isServiceConfigEditable=null===newValue.service,null!==newValue.service&&(scope.serviceConfig.content="",scope.serviceConfigUpdateCounter++))}),watchUploadSpreadsheet=scope.$watch("uploadSpreadsheet",function(n,o){n&&(scope.spreadsheetUploadPath=n.name)});scope.$on("$destroy",function(e){watchServiceDetails(),watchSelectedSchema(),watchEventList(),watchConfig(),watchSelections(),watchUploadSpreadsheet()}),scope.prepareServiceConfig=function(){var config=scope.serviceConfig,type=scope.serviceInfo.type;return"nodejs"!==type&&"php"!==type&&"python"!==type&&"python3"!==type||(scope.selections.service?(config.content="",scope.serviceConfigUpdateCounter++):config.content=scope.serviceConfigEditorObj.editor.getValue(),config.storage_service_id=scope.selections.service?scope.selections.service.id:null,!scope.selections.service||"github"!==scope.selections.service.type&&"gitlab"!==scope.selections.service.type&&"bitbucket"!==scope.selections.service.type?config.scm_repository=null:config.scm_repository=config.scm_repository?config.scm_repository:null,!scope.selections.service||"github"!==scope.selections.service.type&&"gitlab"!==scope.selections.service.type&&"bitbucket"!==scope.selections.service.type?config.scm_reference=null:config.scm_reference=config.scm_reference?config.scm_reference:null,scope.selections.service?config.storage_path=config.storage_path?config.storage_path:null:config.storage_path=null),"excel"===type&&(config.storage_service_id=scope.selections.service?scope.selections.service.id:null,scope.selections.service?config.storage_container=config.storage_container?config.storage_container:null:config.storage_container=null),config},scope.isFieldsSeparated=function(schemaName){return"mysql"===schemaName||"sqlsrv"===schemaName||"oracle"===schemaName||"pgsql"===schemaName},scope.isBasic=function(fieldName){var basicFieldsNames=new Set(["host","port","database","username","password","schema"]);return("mysql"!==scope.selectedSchema.name||"schema"!==fieldName)&&basicFieldsNames.has(fieldName)},scope.isCaching=function(fieldName){return fieldName.includes("cache")||fieldName.includes("caching")},scope.showAdvancedSettings=!0,scope.showAdvancedFields=function(){var moreButton,lessButton,advancedFieldWrapper,advancedFieldContent,totalHeight;return totalHeight=0,moreButton=$(".advanced-fields .more-fields .button").parent(),lessButton=$(".advanced-fields .less-fields .button").parent(),advancedFieldWrapper=moreButton.parent(),advancedFieldContent=advancedFieldWrapper.find("#advanced-fields-wrapper:not('.more-fields')"),moreButton.fadeOut(),lessButton.fadeIn(),scope.showAdvancedSettings=!scope.showAdvancedSettings,totalHeight+=advancedFieldContent.outerHeight(),advancedFieldWrapper.css({height:advancedFieldWrapper.height(),"max-height":9999}).animate({height:totalHeight}),!1},scope.hideAdvancedFields=function(){var moreButton,lessButton,advancedFieldWrapper;return moreButton=$(".advanced-fields .more-fields .button").parent(),lessButton=$(".advanced-fields .less-fields .button").parent(),advancedFieldWrapper=moreButton.parent(),moreButton.fadeIn(),lessButton.fadeOut(),advancedFieldWrapper.animate({height:255}),!1}}}}]).directive("dfServiceDefinition",["MOD_SERVICES_ASSET_PATH","$timeout","$rootScope",function(MOD_SERVICES_ASSET_PATH,$timeout,$rootScope){return{restrict:"E",scope:!1,templateUrl:MOD_SERVICES_ASSET_PATH+"views/df-service-definition.html",link:function(scope,elem,attrs){scope.serviceDefEditorObj={editor:null},scope.allowedDefinitionFormats=["json","yml","yaml"],scope.serviceDefGitHubTarget="definition",scope.serviceDefUpdateCounter=0,scope.serviceDefinition={content:"",format:"json"},scope.isServiceDefEditable=!1,scope.resetServiceDef=function(){switch(scope.serviceDefinition={content:"",format:"json"},scope.serviceInfo.type){case"rws":case"nodejs":case"php":case"python":case"python3":scope.isServiceDefEditable=!0;break;default:scope.isServiceDefEditable=!1}},scope.prepareServiceDefinition=function(){var format,doc=null;switch(scope.serviceInfo.type){case"rws":case"nodejs":case"php":case"python":case"python3":var content=scope.serviceDefEditorObj.editor.getValue();""!==content&&((doc=scope.serviceDetails.record.service_doc_by_service_id||{}).content=content,format=scope.serviceDefinition.format,doc.format="yaml"===format?1:0)}return doc},scope.handleDefinitionFiles=function(files){if(files&&files[0]){var reader=new FileReader;reader.readAsText(files[0],"UTF-8"),reader.onload=function(evt){var format;scope.serviceDefinition.content=evt.target.result,scope.serviceDefUpdateCounter++,format=-1!==files[0].name.indexOf("yml")||-1!==files[0].name.indexOf("yaml")?"yaml":"json",scope.serviceDefinition.format=format,scope.$apply()},reader.onerror=function(evt){}}},scope.$watch("serviceDetails",function(newValue,oldValue){if(newValue){var content="",format="json",editable=!1;switch(newValue.record.type){case"rws":case"nodejs":case"php":case"python":case"python3":var doc=newValue.record.service_doc_by_service_id;doc&&(doc.hasOwnProperty("content")&&doc.content&&(content=doc.content),doc.hasOwnProperty("format")&&(format=1===doc.format?"yaml":"json")),editable=!0}scope.serviceDefinition={content:content,format:format},scope.isServiceDefEditable=editable}}),scope.githubModalShowDef=function(){$rootScope.$broadcast("githubShowModal",scope.serviceDefGitHubTarget)},$(window).on("resize",function(){var h=$(window).height();$('div[id^="ide_"]').css({height:h-400+"px"})})}}}]),angular.module("dfRoles",["ngRoute","dfUtility","dfApplication","dfTable"]).constant("MOD_ROLES_ROUTER_PATH","/roles").constant("MOD_ROLES_ASSET_PATH","admin_components/adf-roles/").config(["$routeProvider","MOD_ROLES_ROUTER_PATH","MOD_ROLES_ASSET_PATH",function($routeProvider,MOD_ROLES_ROUTER_PATH,MOD_ROLES_ASSET_PATH){$routeProvider.when(MOD_ROLES_ROUTER_PATH,{templateUrl:MOD_ROLES_ASSET_PATH+"views/main.html",controller:"RolesCtrl",resolve:{checkAdmin:["checkAdminService",function(checkAdminService){return checkAdminService.checkAdmin()}],checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("RolesCtrl",["$rootScope","$scope","$q","dfApplicationData","SystemConfigDataService","dfNotify","$location",function($rootScope,$scope,$q,dfApplicationData,SystemConfigDataService,dfNotify,$location){$scope.$parent.title="Roles",$scope.$parent.titleIcon="exclamation-circle",$scope.links=[{name:"manage-roles",label:"Manage",path:"manage-roles"},{name:"create-role",label:"Create",path:"create-role"}],$scope.emptySearchResult={title:"You have no Roles that match your search criteria!",text:""},$scope.adldap=0;var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("adldap")&&($scope.adldap=systemConfig.authentication.adldap.length),$scope.emptySectionOptions={title:"You have no Roles!",text:"Click the button below to get started creating your first role. You can always create new roles by clicking the tab located in the section menu to the left.",buttonText:"Create A Role!",viewLink:$scope.links[1],active:!1},$scope.$on("$destroy",function(e){$scope.$broadcast("toolbar:paginate:role:destroy")}),$scope.apiData=null,$scope.loadTabData=function(init){$scope.dataLoading=!0;var apis=["role","service_list","service_type_list"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData,init&&$scope.$broadcast("toolbar:paginate:role:load")},function(error){error&&error.error&&(401===error.error.code||403===error.error.code)&&$location.url("/home");var messageOptions={module:"Roles",provider:"dreamfactory",type:"error",message:"To use the Roles tab your role must allow GET access to service 'system' and system/role/*. To create, update, or delete roles you need POST, PUT, DELETE access to /system/role/*."};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(!0)}]).directive("dfRoleDetails",["MOD_ROLES_ASSET_PATH","dfApplicationData","dfNotify","dfObjectService","$q","SystemConfigDataService","dfSystemData","$timeout",function(MOD_ROLES_ASSET_PATH,dfApplicationData,dfNotify,dfObjectService,$q,SystemConfigDataService,dfSystemData,$timeout){return{restrict:"E",scope:{roleData:"=?",newRole:"=?",apiData:"=?"},templateUrl:MOD_ROLES_ASSET_PATH+"views/df-role-details.html",link:function(scope,elem,attrs){scope.adldap=0;var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("adldap")&&(scope.adldap=systemConfig.authentication.adldap.length);var Role=function(roleData){var newRole={name:null,description:null,is_active:!1,default_app_id:null,role_service_access_by_role_id:[],id:null,lookup_by_role_id:[]};return roleData=roleData||newRole,{__dfUI:{selected:!1},record:angular.copy(roleData),recordCopy:angular.copy(roleData)}};scope.basicInfoError=!1,scope.role=null,scope.isBasicTab=!0,scope.newRole&&(scope.role=new Role),scope.saveRole=function(){scope.newRole?scope._saveRole():scope._updateRole()},scope.deleteRole=function(){scope._deleteRole()},scope.cancelEditor=function(){scope._prepareRoleData(),(dfObjectService.compareObjectsAsJson(scope.role.record,scope.role.recordCopy)||dfNotify.confirmNoSave())&&scope.closeEditor()},scope._prepareRoleData=function(){scope.role.record.name?(scope.basicInfoError=!1,scope.adldap&&scope.role.record.dn&&(scope.role.record.role_adldap_by_role_id=scope.role.record.id?{role_id:scope.role.record.id,dn:scope.role.record.dn}:{dn:scope.role.record.dn},delete scope.role.record.dn),scope._prepareServiceAccessData(),scope._prepareRoleLookUpKeysData()):scope.basicInfoError=!0},scope.refreshRoleEditor=function($event){scope.isBasicTab="basic-tab"===$event.target.id},scope.refreshRoleAccessEditor=function(){$timeout(function(){angular.element("#access-tab").trigger("click")})},scope.closeEditor=function(){scope.roleData=null,scope.role=new Role,$timeout(function(){angular.element("#basic-tab").trigger("click")}),scope.lookupKeysError=!1,scope.basicInfoError=!1,scope.$emit("sidebar-nav:view:reset")},scope._prepareServiceAccessData=function(){var preppedArr=[];angular.forEach(scope.roleServiceAccesses,function(obj){var _obj=angular.copy(obj.record);delete _obj.service,preppedArr.push(_obj)}),scope.role.record.role_service_access_by_role_id=preppedArr},scope._saveRole=function(){scope._prepareRoleData();var requestDataObj={params:{fields:"*",related:"role_service_access_by_role_id,lookup_by_role_id"},data:scope.role.record};dfApplicationData.saveApiData("role",requestDataObj).$promise.then(function(result){var messageOptions={module:"Roles",type:"success",provider:"dreamfactory",message:"Role saved successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var msg=reject.data.message,messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._updateRole=function(){scope._prepareRoleData();var requestDataObj={params:{fields:"*",related:"role_service_access_by_role_id,lookup_by_role_id"},data:scope.role.record};dfApplicationData.updateApiData("role",requestDataObj).$promise.then(function(result){scope.adldap?dfSystemData.resource({params:{fields:"*",related:"role_adldap_by_role_id"}}).get({api:"role",id:result.id,related:"role_adldap_by_role_id"}).$promise.then(function(adResult){adResult.role_adldap_by_role_id&&(adResult.role_adldap_by_role_id.length>0||adResult.role_adldap_by_role_id.hasOwnProperty("dn"))&&(adResult.role_adldap_by_role_id.length>0?result.dn=adResult.role_adldap_by_role_id[0].dn:result.dn=adResult.role_adldap_by_role_id.dn),scope.role=new Role(result)},function(reject){scope.role=new Role(result)}):scope.role=new Role(result);var messageOptions={module:"Roles",type:"success",provider:"dreamfactory",message:"Role updated successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var msg=reject.data.message;scope.role.record.role_adldap_by_role_id&&(scope.role.record.role_adldap_by_role_id.length>0||scope.role.record.role_adldap_by_role_id.hasOwnProperty("dn"))&&(scope.role.record.role_adldap_by_role_id.length>0?scope.role.record.dn=scope.role.record.role_adldap_by_role_id[0].dn:scope.role.record.dn=scope.role.record.role_adldap_by_role_id.dn);var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._deleteRole=function(){var requestDataObj={params:{},data:scope.role.record};dfApplicationData.deleteApiData("role",requestDataObj).$promise.then(function(result){var messageOptions={module:"Roles",type:"success",provider:"dreamfactory",message:"Role successfully deleted."};dfNotify.success(messageOptions),scope.role=null},function(reject){var msg=reject.data.message,messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})};var watchRoleData=scope.$watch("roleData",function(newValue,oldValue){newValue&&!scope.newRole&&(scope.role=new Role(newValue))}),watchServiceData=scope.$watchCollection("apiData.service_list",function(newValue,oldValue){newValue&&(scope.services=angular.copy(newValue),scope.services.sort(function(a,b){return a.nameb.name?1:0}),"All"!==scope.services[0].name&&scope.services.unshift({id:null,name:"All"}),angular.forEach(scope.services,function(svc){svc.components||(svc.components=["","*"])}))});scope.$on("$destroy",function(e){watchRoleData(),watchServiceData()}),scope.dfSimpleHelp={serviceAccess:{title:"Role Service Access Information",text:"Access rules for DreamFactory services. Use caution when allowing system access."}},scope.dfLargeHelp={basic:{title:"Roles Overview",text:"Roles provide a way to grant or deny API access to specific services or apps."},access:{title:"Access Overview",text:"This section allows you set up rules for a role restricting what services and components users assigned to the role will have access to. Advanced Filters are for implementing additional server side filter logic on database transactions."},lookupkeys:{title:"Lookup Keys Overview",text:'The DreamFactory administrator can create any number of "key value" pairs attached to a role. The key values are automatically substituted on the server. For example, key names can be used in the username and password fields required to hook up a SQL or NoSQL database. They can also be used in Email Templates or as parameters for external REST services. Any Lookup Key can be marked as private, and in this case the key value is securely encrypted on the server and is no longer accessible through the platform interface. Lookup keys for service configuration and credentials must be made private.'}}}}}]).directive("assignServiceAccess",["MOD_ROLES_ASSET_PATH","dfNotify",function(MOD_ROLES_ASSET_PATH,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_ROLES_ASSET_PATH+"views/df-assign-service-access.html",link:function(scope,elem,attrs){var ServiceAccess=function(){return{__dfUI:{allowFilters:!1,showFilters:!1,hasError:!1},record:{verb_mask:0,requestor_mask:1,component:"*",service:scope.services[0]||null,service_id:scope.services[0].id||null,filters:[],filter_op:"AND"}}};scope.roleServiceAccesses=[],scope.addServiceAccess=function(){scope._addServiceAccess()},scope.removeServiceAccess=function(serviceAccessObjIndex){scope._removeServiceAccess(serviceAccessObjIndex)},scope._addServiceAccess=function(){scope.roleServiceAccesses.push(new ServiceAccess)},scope._removeServiceAccess=function(serviceAccessObjIndex){scope.roleServiceAccesses[serviceAccessObjIndex].record.id?scope.roleServiceAccesses[serviceAccessObjIndex].record.role_id=null:scope.roleServiceAccesses.splice(serviceAccessObjIndex,1)},scope._getService=function(serviceId){for(var i=0;i","<",">=","<=","in","not in","starts with","ends with","contains","is null","is not null"],scope.toggleServiceAccessFilters=function(){scope._toggleServiceAccessFilters()},scope.addServiceAccessFilter=function(){scope._addServiceAccessFilter()},scope.removeServiceAccessFilter=function(serviceAccessFilterIndex){scope._removeServiceAccessFilter(serviceAccessFilterIndex)},scope.toggleServiceFilterOp=function(){scope._toggleServiceFilterOp()},scope.allowFilters=function(){var type=scope.serviceAccess.record.service.type,group=serviceTypeToGroup(type,scope.apiData.service_type_list);scope.serviceAccess.__dfUI.allowFilters="Database"===group&&"couchdb"!==type},scope._toggleServiceAccessFilters=function(){scope.serviceAccess.__dfUI.show_filters=!scope.serviceAccess.__dfUI.show_filters},scope._addServiceAccessFilter=function(){scope.serviceAccess.record.filters.push(new ServiceAccessFilter)},scope._removeServiceAccessFilter=function(serviceAccessFilterIndex){scope.serviceAccess.record.filters.splice(serviceAccessFilterIndex,1)},scope._toggleServiceFilterOp=function(){scope.serviceAccess.record.filter_op="AND"===scope.serviceAccess.record.filter_op?"OR":"AND"},scope._getComponents=function(){var name=scope.serviceAccess.record.service.name;return $http.get(INSTANCE_URL.url+"/"+name+"/?as_access_list=true")};var watchServiceAccessRecordService=scope.$watch("serviceAccess.record.service",function(newValue,oldValue){if(!newValue)return!1;scope.serviceAccess.__dfUI.hasError=!1,scope.allowFilters(),scope.serviceAccess.record.service_id=newValue.id;var name=scope.serviceAccess.record.service.name,group=serviceTypeToGroup(scope.serviceAccess.record.service.type,scope.apiData.service_type_list);if("All"!==name&&null!==group&&"Email"!==group){var components=["","*"];scope._getComponents().then(function(result){components=result.data.resource},function(reject){scope.serviceAccess.__dfUI.hasError=!0,scope.serviceAccess.record.component=null;var messageOptions={module:"Roles",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.serviceAccess.record.service.components=components})}});scope.$on("$destroy",function(e){watchServiceAccessRecordService()})}}}]).directive("dfManageRoles",["$rootScope","MOD_ROLES_ASSET_PATH","dfApplicationData","dfNotify","dfSystemData","SystemConfigDataService","dfSelectedService",function($rootScope,MOD_ROLES_ASSET_PATH,dfApplicationData,dfNotify,dfSystemData,SystemConfigDataService,dfSelectedService){return{restrict:"E",scope:!1,templateUrl:MOD_ROLES_ASSET_PATH+"views/df-manage-roles.html",link:function(scope,elem,attrs){var ManagedRole=function(roleData){return{__dfUI:{selected:!1},record:roleData}};scope.adldap=0;var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("adldap")&&(scope.adldap=systemConfig.authentication.adldap.length),scope.roles=null,scope.currentEditRole=null,scope.fields=[{name:"id",label:"label",active:!0},{name:"name",label:"Name",active:!0},{name:"description",label:"Description",active:!0},{name:"is_active",label:"Active",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedRoles=[],scope.editRole=function(role){scope.adldap?dfSystemData.resource({params:{fields:"*",related:"role_adldap_by_role_id"}}).get({api:"role",id:role.id,related:"role_adldap_by_role_id"}).$promise.then(function(result){result.role_adldap_by_role_id&&(result.role_adldap_by_role_id.length>0||result.role_adldap_by_role_id.hasOwnProperty("dn"))&&(result.role_adldap_by_role_id.length>0?role.dn=result.role_adldap_by_role_id[0].dn:role.dn=result.role_adldap_by_role_id.dn),scope._editRole(role)},function(reject){scope._editRole(role)}):scope._editRole(role)},scope.deleteRole=function(role){dfNotify.confirm("Delete "+role.record.name+"?")&&scope._deleteRole(role)},scope.deleteSelectedRoles=function(){dfNotify.confirm("Delete selected roles?")&&scope._deleteSelectedRoles()},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setSelected=function(role){scope._setSelected(role)},scope._editRole=function(role){scope.currentEditRole=role},scope._deleteRole=function(role){var requestDataObj={params:{},data:role.record};dfApplicationData.deleteApiData("role",requestDataObj).$promise.then(function(result){var messageOptions={module:"Roles",type:"success",provider:"dreamfactory",message:"Role successfully deleted."};dfNotify.success(messageOptions),role.__dfUI.selected&&scope.setSelected(role),scope.$broadcast("toolbar:paginate:role:delete")},function(reject){var msg=reject.data.message,messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope._setSelected=function(role){for(var i=0;i"}}]).directive("dfAssignLookUpKeys",["MOD_ROLES_ASSET_PATH",function(MOD_ROLES_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_ROLES_ASSET_PATH+"views/df-assign-lookup-keys.html",link:function(scope,elem,attrs){var LookUpKey=function(lookupKeyData){var _new={name:"",value:"",private:!1,allow_user_update:!1};return{__dfUI:{unique:!0},record:angular.copy(lookupKeyData||_new),recordCopy:angular.copy(lookupKeyData||_new)}};scope.roleLookUpKeys=[],scope.sameKeys=[],scope.lookupKeysError=!1,scope.addLookUpKey=function(){scope._addLookUpKey()},scope.deleteLookUpKey=function(keyObjIndex){scope._deleteLookUpKey(keyObjIndex)},scope._prepareRoleLookUpKeysData=function(){var tempArr=[];angular.forEach(scope.roleLookUpKeys,function(lk){tempArr.push(lk.record)}),scope.role.record.lookup_by_role_id=tempArr},scope._isUniqueKey=function(){scope.sameKeys=[],angular.forEach(scope.roleLookUpKeys,function(value,index){angular.forEach(scope.roleLookUpKeys,function(_value,_index){index!==_index&&value.record.name===_value.record.name&&scope.sameKeys.push(value)})})},scope._addLookUpKey=function(){scope.roleLookUpKeys.push(new LookUpKey)},scope._deleteLookUpKey=function(keyObjIndex){void 0!==scope.roleLookUpKeys[keyObjIndex].record.role_id?scope.roleLookUpKeys[keyObjIndex].record.role_id=null:scope.roleLookUpKeys.splice(keyObjIndex,1)};var watchRole=scope.$watch("role",function(newValue,oldValue){if(!newValue)return!1;scope.roleLookUpKeys=null,scope.newRole?scope.roleLookUpKeys=[]:(scope.roleLookUpKeys=[],angular.forEach(newValue.record.lookup_by_role_id,function(lkObj){scope.roleLookUpKeys.push(new LookUpKey(lkObj))}))}),watchSameKeys=scope.$watch("sameKeys",function(newValue,oldValue){0!==newValue.length||0!==scope.roleLookUpKeys.length?0===newValue.length&&scope.roleLookUpKeys.length>0?angular.forEach(scope.roleLookUpKeys,function(lk){lk.__dfUI.unique=!0,scope.lookupKeysError=!1}):(angular.forEach(scope.roleLookUpKeys,function(lk){angular.forEach(newValue,function(_lk){lk.record.name===_lk.record.name?lk.__dfUI.unique=!1:lk.__dfUI.unique=!0})}),scope.lookupKeysError=!0):scope.lookupKeysError=!1}),watchLookupKeys=scope.$watchCollection("roleLookUpKeys",function(newValue,oldValue){newValue&&scope._isUniqueKey()});scope.$on("$destroy",function(e){watchRole(),watchSameKeys(),watchLookupKeys()})}}}]),angular.module("dfSchema",["ngRoute","dfUtility"]).constant("MOD_SCHEMA_ROUTER_PATH","/schema").constant("MOD_SCHEMA_ASSET_PATH","admin_components/adf-schema/").config(["$routeProvider","MOD_SCHEMA_ROUTER_PATH","MOD_SCHEMA_ASSET_PATH",function($routeProvider,MOD_SCHEMA_ROUTER_PATH,MOD_SCHEMA_ASSET_PATH){$routeProvider.when(MOD_SCHEMA_ROUTER_PATH,{templateUrl:MOD_SCHEMA_ASSET_PATH+"views/main.html",controller:"SchemaCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).factory("TableListService",["INSTANCE_URL","$q","$timeout","dfApplicationData","StateService","dfNotify",function(INSTANCE_URL,$q,$timeout,dfApplicationData,StateService,dfNotify){return{getTableList:function(forceRefresh){var deferred=$q.defer(),currentService=StateService.get("dfservice");if(currentService)return dfApplicationData.getServiceComponents(currentService.name,INSTANCE_URL.url+"/"+currentService.name+"/_schema",{params:{refresh:!0,fields:"name,label"}},forceRefresh).then(function(result){currentService.updateComponents(result),StateService.set("dfservice",currentService);var messageOptions={module:"Schema",type:"success",provider:"dreamfactory",message:currentService.label+" is refreshed."};forceRefresh&&dfNotify.success(messageOptions),deferred.resolve(currentService)},function(reject){var messageOptions={module:"Schema",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions),deferred.reject()}),deferred.promise}}}]).factory("Table",["$q","$http","INSTANCE_URL","dfNotify",function($q,$http,INSTANCE_URL,dfNotify){function Table(tableData){tableData&&this.setData(tableData)}return Table.prototype={setData:function(tableData){angular.extend(this,tableData)},delete:function(params){return $http.delete(INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table)},update:function(params){return $http({method:"PATCH",url:INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table,data:this})},_saveField:function(params,fieldData){var data={resource:[fieldData.record]},verb=fieldData.__dfUI.newField?"POST":"PATCH";return $http({method:verb,url:INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table+"/_field",data:data})},_updateRelations:function(params){}},Table}]).factory("tableManager",["INSTANCE_URL","$http","$q","Table","StateService","dfNotify","TableObj",function(INSTANCE_URL,$http,$q,Table,StateService,dfNotify,TableObj){return{_pool:{},_retrieveInstance:function(tableName,tableData){if(!tableName)return!1;var instance=this._pool[tableName];return instance?instance.setData(tableData):(instance=new Table(tableData),this._pool[tableName]=instance),instance},_search:function(tableName){return this._pool[tableName]},_load:function(params,deferred){var scope=this,url=INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table+"?refresh=true";$http.get(url).then(function(response){var tableData=response.data,table=scope._retrieveInstance(tableData.name,tableData);deferred.resolve(table)},function(reject){deferred.reject()})},_delete:function(params){return $http.delete(INSTANCE_URL.url+"/"+params.service.name+"/_schema/"+params.table)},_deleteField:function(params){return $http.delete(INSTANCE_URL.url+"/"+params.service.name+"/_schema/"+params.table+"/_field/"+params.field)},_clearPool:function(){this._pool={}},getTable:function(params){var deferred=$q.defer(),table=this._search(params.table);return table?deferred.resolve(table):this._load(params,deferred),deferred.promise},loadAllTables:function(params){var deferred=$q.defer(),scope=this,url=INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table;return $http.get(url).then(function(response){var tables,tablesArray=response.data;Array.isArray(tablesArray)?tablesArray.forEach(function(tableData){var table=scope._retrieveInstance(tableData.name,tableData);tables.push(table)}):tables=tablesArray,deferred.resolve(tables)},function(reject){deferred.reject()}),deferred.promise},setTable:function(tableData,saveToServer){var tableName="";tableName=tableData.hasOwnProperty("record")?tableData.__dfUI.newTable?"__new":tableData.record.name:tableData.name;var scope=this,table=this._search(tableName);if(!table&&saveToServer){var param={resource:[tableData]};return $http.post(INSTANCE_URL.url+"/"+StateService.get("dfservice").name+"/_schema?fields=*",param)}if(table){if(table.setData(tableData),saveToServer)return table.update({service:StateService.get("dfservice").name,table:tableName})}else table=scope._retrieveInstance(tableName,tableData.record);return table},setDat:function(tableData){scope._retrieveInstance(tableData)},setField:function(tableName,fieldData,saveToServer){var table=this._search(tableName);if(void 0!==table){var index=table.field.findIndex(function(obj){return obj.name==fieldData.record.name});if(index<0?table.field.push(fieldData.record):table.field[index]=fieldData.record,table.field[index]=fieldData.record,table.setData(table),saveToServer){var params={service:StateService.get("dfservice").name,table:tableName};return table._saveField(params,fieldData)}}},getField:function(fieldName,tableName){var table=this._search(tableName);if(table.hasOwnProperty("field")){var index=table.field.findIndex(function(obj){return obj.name==fieldName});return index>-1?table.field[index]:void 0}return null},deleteField:function(params){return this._deleteField(params)},deleteTable:function(params){return this._delete(params)},_saveRelation:function(params,relationData){var data={resource:[relationData.record]};return relationData.__dfUI.newRelation?$http.post(INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table+"/_related",data):$http({method:"PATCH",url:INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table+"/_related",data:data})},saveRelation:function(params,relationData){return this._saveRelation(params,relationData)},_deleteRelation:function(params){return $http.delete(INSTANCE_URL.url+"/"+params.service+"/_schema/"+params.table+"/_related/"+params.relation)},deleteRelation:function(params){return this._deleteRelation(params)},updateRelations:function(params){var table=this._search(params.table),url=INSTANCE_URL.url+"/"+params.service.name+"/_schema/"+params.table+"/_related";return $http.get(url).then(function(response){var relationData=response.data;table.related=relationData.resource,table.setData(table)},function(reject){})},clearPool:function(){this._clearPool()}}}]).service("StateService",function(){var selectedService={};return{get:function(state){if(selectedService.hasOwnProperty(state))return selectedService[state]},set:function(state,value){selectedService[state]=value}}}).service("ServiceModel",function(){function getSchemaComponents(array){var service=[];return angular.forEach(array,function(component){var componentObj={__dfUI:{newTable:!1},name:component.name,label:component.label};service.push(componentObj)}),service}return function(schemaData){return{__dfUI:{unfolded:!1},name:schemaData.name,label:schemaData.label,components:getSchemaComponents(schemaData.components),updateComponents:function(array){this.components=getSchemaComponents(array)}}}}).service("TableObj",function(){return function(tableObj,currentService){var _new={alias:null,description:null,name:null,label:null,plural:null,primary_key:null,name_field:null,is_view:!1,related:[],field:[]},newTable=!tableObj;return tableObj=tableObj||_new,{__dfUI:{newTable:newTable},record:tableObj,recordCopy:angular.copy(tableObj)}}}).service("FieldObj",function(){return function(fieldData1){var _new={allow_null:!1,auto_increment:!1,db_function:null,db_type:null,default:null,fixed_length:!1,is_aggregate:!1,is_foreign_key:!1,is_primary_key:!1,is_unique:!1,is_virtual:!1,label:null,length:null,name:null,picklist:null,precision:null,ref_field:"",ref_table:"",required:!1,scale:0,supports_multibyte:!1,type:null,validation:null,value:[]},_newField=!fieldData1;return fieldData1=fieldData1||_new,{__dfUI:{newField:_newField},record:fieldData1,recordCopy:angular.copy(fieldData1)}}}).service("RelationObj",function(){return function(RelationObj){var _new={alias:null,always_fetch:!1,description:null,field:null,is_virtual:!0,junction_field:null,junction_ref_field:null,junction_service_id:null,junction_table:null,label:null,name:null,ref_field:null,ref_service_id:null,ref_table:null,type:null},_newRelation=!RelationObj;return RelationObj=RelationObj||_new,{__dfUI:{newRelation:_newRelation},record:RelationObj,recordCopy:angular.copy(RelationObj)}}}).service("TableDataModel",function(){this.model=null,this.setTableModel=function(data){this.model=data},this.setTableModel=function(data){this.model=data},this.updateTableModel=function(data){this.model=data},this.deleteTableModel=function(){this.model=null}}).service("NavigationService",function(){return this.currentStep=null,{getStep:function(){return this.currentStep},setStep:function(step){this.currentStep=step},nextStep:function(){},previousStep:function(){}}}).service("FieldOptions",function(){this.typeOptions=[{name:"I will manually enter a type",value:""},{name:"id",value:"id"},{name:"string",value:"string"},{name:"integer",value:"integer"},{name:"text",value:"text"},{name:"boolean",value:"boolean"},{name:"binary",value:"binary"},{name:"float",value:"float"},{name:"double",value:"double"},{name:"decimal",value:"decimal"},{name:"datetime",value:"datetime"},{name:"date",value:"date"},{name:"time",value:"time"},{name:"reference",value:"reference"},{name:"user_id",value:"user_id"},{name:"user_id_on_create",value:"user_id_on_create"},{name:"user_id_on_update",value:"user_id_on_update"},{name:"timestamp",value:"timestamp"},{name:"timestamp_on_create",value:"timestamp_on_create"},{name:"timestamp_on_update",value:"timestamp_on_update"}],this.returnTypeOptions=[{name:"string",value:"string"},{name:"integer",value:"integer"},{name:"boolean",value:"boolean"},{name:"binary",value:"binary"},{name:"float",value:"float"},{name:"double",value:"double"},{name:"decimal",value:"decimal"}],this.helpText={name:{title:"Name",text:"The field name used by the API."},alias:{title:"Alias",text:"If set, the alias is used in table access instead of the name."},label:{title:"Label",text:"A displayable name used by clients."},type:{title:"Type",text:"This is a simplified DreamFactory type."},database_type:{title:"Database Type",text:"If necessary, enter a type acceptable to the underlying database."},db_function:{title:"DB Function",text:'Enter valid syntax for a database function supported by this database vendor, like upper(fieldname), max(fieldname) or concat(field1, \'.\', field2), to apply to this field for various operations. See here for more info.'},validation:{title:"Validation",text:'A JSON object detailing required validations, if any. See here for more info.'},aggregate_db_unction:{title:"Aggregate DB Function",text:'Supported DB functions to apply to this field. See here for more info.'}}}).service("SchemaJSONData",function(){this.schemaJSON={resource:[{name:"todo",label:"Todo",plural:"Todos",alias:null,field:[{name:"id",label:"Id",type:"id"},{name:"name",label:"Name",type:"string",size:80,allow_null:!1},{name:"complete",label:"Complete",type:"boolean",default:!1}]}]}}).controller("SchemaCtrl",["$scope","dfApplicationData","ServiceModel","dfNotify","$location",function($scope,dfApplicationData,ServiceModel,dfNotify,$location){$scope.$parent.title="Schema",$scope.$parent.titleIcon="table",$scope.links=[{name:"manage-schema",label:"Manage",path:"manage-schema"}],$scope.currentService=null,$scope.currentTable=null,$scope.lastTable="";var watchServices=$scope.$watchCollection("apiData.service_list",function(newValue,oldValue){if(newValue){var tempObj={};angular.forEach(newValue,function(service){tempObj[service.name]=new ServiceModel(service)}),$scope.schemaManagerData=tempObj}});$scope.$on("$destroy",function(e){watchServices()}),$scope.$on("refresh:table",function(e,resource){}),$scope.$on("update:components",function(e,resource){$scope.currentService.components.push({__dfUI:{newTable:!1},name:resource.name,label:resource.label}),$scope.currentTable=$scope.currentService.components[$scope.currentService.components.length-1].name}),$scope.dfLargeHelp={manageSchema:{title:"Schema Manager Overview",text:"Choose a database service from the list to view or edit the schema. You can create a new database service in the Services section of this Admin Console."}},$scope.apiData=null,$scope.loadTabData=function(){$scope.dataLoading=!0;var apis=["service_list"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index],"service_list"===value&&(newApiData[value]=newApiData[value].filter(function(obj){return["mysql","pgsql","sqlite","sqlsrv","memsql","sqlanywhere","oracle","ibmdb2","informix","firebird","aws_redshift_db","mongodb","apache_hive","snowflake"].indexOf(obj.type)>=0}))}),$scope.apiData=newApiData},function(error){var messageOptions={module:"Schema",provider:"dreamfactory",type:"error",message:"There was an error loading the Schema tab. Please try refreshing your browser and logging in again."};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData()}]).directive("dfSchemaLoading",[function(){return{restrict:"E",template:"
"}}]).directive("dfTableTemplate",["MOD_SCHEMA_ASSET_PATH","$q","$timeout","NavigationService","Table","TableDataModel","FieldObj","RelationObj","StateService","tableManager",function(MOD_SCHEMA_ASSET_PATH,$q,$timeout,NavigationService,Table,TableDataModel,FieldObj,RelationObj,StateService,tableManager){return{restrict:"E",scope:{tableData:"=",apiData:"="},templateUrl:MOD_SCHEMA_ASSET_PATH+"views/df-table-template.html",transclude:!0,controllerAs:"ctrl",controller:["$scope",function($scope){$scope.selView="empty",this.selectedView="empty";var ctrl=this;ctrl.childCtrl=[],ctrl.register=function(child,childCtrl){ctrl.childCtrl[child]=childCtrl},ctrl.$onDestroy=function(){ctrl.childCtrl.length=0}}],link:function(scope,elem,attrs,ctrl){scope.$on("reload",function(event,args){scope.selView="empty"}),scope.$on("table",function(event,args){switch(args.notify){case"delete":ctrl.childCtrl.table_edit.deleteTable(args).then(function(){scope.selView="empty"},function(){});break;case"create:form":scope.selView="create",ctrl.childCtrl.table_create.getEmpty(args);break;case"create:upload":scope.selView="upload",ctrl.childCtrl.table_upload.setDefault();break;case"edit":null!==args.table?(scope.selView="edit",ctrl.childCtrl.table_edit.getTable(args)):scope.selView="empty";break;case"close":scope.selView="empty"}}),scope.$on("field",function(event,args){switch(args.notify){case"new:create":args.value.newTable=!0,scope.newTable=!0,scope.selView="field",scope.fieldEditData=new FieldObj,scope.tableStatus=args.newTable;break;case"edit:create":args.value.newTable=!1,scope.newTable=!1,scope.selView="field",scope.fieldEditData=new FieldObj,scope.tableStatus=args.newTable;break;case"new:close":scope.selView="create";break;case"edit:close":scope.selView="edit",ctrl.childCtrl.table_create.getEmpty(),ctrl.childCtrl.table_edit.syncRecord();break;case"edit":scope.selView="field",scope.fieldEditData=args.value.field,scope.tableStatus=args.value.newTable}}),scope.$on("relation",function(event,args){switch(args.notify){case"create":scope.selView="relation",scope.relationEditData=new RelationObj;break;case"edit":NavigationService.setStep("relation"),scope.selView="relation",scope.relationEditData=args.value.relation;break;case"close":scope.selView="edit",ctrl.childCtrl.table_edit.updateRelations(args.selected)}}),scope.$on("table:navigation:close",function(event,args){scope.selView="empty"})}}}]).directive("dfTableCreateView",["MOD_SCHEMA_ASSET_PATH","NavigationService","Table","TableDataModel","$http","dfNotify","dfObjectService","StateService","dfApplicationData","TableObj","tableManager",function(MOD_SCHEMA_ASSET_PATH,NavigationService,Table,TableDataModel,$http,dfNotify,dfObjectService,StateService,dfApplicationData,TableObj,tableManager){return{restrict:"E",scope:{tableData:"=",selectedView:"="},require:["dfTableCreateView","^^dfTableTemplate"],templateUrl:MOD_SCHEMA_ASSET_PATH+"views/df-table-create-view.html",controller:function($scope){$scope.viewMode="table",$scope.table={};var ctrl=this;ctrl.getEmpty=function(){$scope.table=new TableObj,tableManager.setTable($scope.table,!1)},ctrl.getCached=function(service){var requestDataObj={service:service.service,table:service.table};tableManager.getTable(requestDataObj).then(function(tables){$scope.table={__dfUI:{newTable:!0},record:tables,recordCopy:angular.copy(tables),currentService:service.service}})}},link:function(scope,elem,attrs,ctrls){var childCtrl=ctrls[0];ctrls[1].register("table_create",childCtrl),scope.saveTable=function(){if(-1===StateService.get("dfservice").components.findIndex(function(element,index,array){return element.name===scope.table.record.name}))scope._saveTable();else{var messageOptions={module:"Validation Error",type:"error",provider:"dreamfactory",message:"The name already exists"};dfNotify.error(messageOptions)}},scope.cancelTable=function(){scope._cancelTable()},scope._saveTable=function(){tableManager.clearPool(),scope.currentService=StateService.get("dfservice"),scope.table.currentService={name:scope.currentService.name},tableManager.setTable(scope.table.record,!0).then(function(result){var messageOptions={module:"Schema",type:"success",provider:"dreamfactory",message:"Table saved successfully."},newTable=result.data.resource[0],component={__dfUI:{newTable:!1},name:scope.table.record.name,label:scope.table.record.label||result.data.resource[0].label};scope.currentService.components.push(component),dfApplicationData.updateServiceComponentsLocal(scope.currentService),scope.table.__dfUI.newTable=!1,scope.table.recordCopy=angular.copy(scope.table.record),StateService.set("dftable",scope.table.record.name),dfNotify.success(messageOptions);var naviObj={service:scope.currentService.name,table:scope.table.record.name,type:"form",data:newTable};scope.$emit("table:navigation:select",naviObj)},function(errMsg){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:errMsg.error.message};dfNotify.error(messageOptions)})},scope._cancelTable=function(){if(!dfObjectService.compareObjectsAsJson(scope.table.record,scope.table.recordCopy)&&!dfNotify.confirmNoSave())return!1;scope.table=null,scope.$emit("table",{notify:"close"})}}}}]).directive("dfTableEditView",["MOD_SCHEMA_ASSET_PATH","$q","NavigationService","Table","TableDataModel","$http","dfNotify","tableManager","TableObj","dfObjectService","dfApplicationData","StateService",function(MOD_SCHEMA_ASSET_PATH,$q,NavigationService,Table,TableDataModel,$http,dfNotify,tableManager,TableObj,dfObjectService,dfApplicationData,StateService){return{restrict:"E",scope:{tableData:"=",selectedView:"="},require:["dfTableEditView","^dfTableTemplate"],templateUrl:MOD_SCHEMA_ASSET_PATH+"views/df-table-edit-view.html",controller:function($scope){var ctrl=this;$scope.table=null,$scope.viewMode="table",$scope.schemaJsonEditorObj={editor:null},$scope.reset=function(){$scope.table=null,$scope.viewMode="table",$scope.table=null,$scope.currentTable=null},$scope.thisService=null,ctrl.syncRecord=function(){$scope.table.recordCopy=angular.copy($scope.table.record)},ctrl.getTable=function(service){var requestDataObj={service:service.service,table:service.table};tableManager.getTable(requestDataObj).then(function(tables){$scope.table={__dfUI:{newTable:!1},record:tables,recordCopy:angular.copy(tables),currentService:service.service}})},ctrl.updateRelations=function(obj){tableManager.updateRelations(obj).then(function(tables){})},ctrl.deleteTable=function(obj){if(dfNotify.confirm("Are you sure you want to drop table "+obj.table+"?"))return $scope._deleteTable(obj)},$scope._deleteTable=function(obj){var deferred=$q.defer(),requestDataObj={table:obj.table,service:obj.service};return tableManager.deleteTable(requestDataObj).then(function(result){for(var messageOptions={module:"Schema",type:"success",provider:"dreamfactory",message:"Table deleted successfully."},currentService=requestDataObj.service,i=0;ihere for more info.'}}}}}]).directive("dfSchemaNavigator",["MOD_SCHEMA_ASSET_PATH","dfApplicationData","StateService","TableListService","NavigationService","tableManager","dfNotify",function(MOD_SCHEMA_ASSET_PATH,dfApplicationData,StateService,TableListService,NavigationService,tableManager,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_SCHEMA_ASSET_PATH+"views/df-schema-navigator.html",link:function(scope,elem,attrs){scope.serviceSelect=function(){tableManager.clearPool(),scope.$broadcast("table",{notify:"close"}),scope.currentTable=null,StateService.set("dfservice",scope.currentService),TableListService.getTableList()},scope.navigationSelect=function(selected){var naviObj={type:selected,notify:"create:"+selected,value:{service:scope.currentService.name}};scope.currentTable=null,scope.$broadcast("table",naviObj)},scope.deleteTable=function(){var params={table:scope.currentTable,service:scope.currentService,notify:"delete"};scope.$broadcast("table",params)},scope.tableSelect=function(obj){var params={table:scope.currentTable,service:scope.currentService.name,notify:"edit"};StateService.set("dftable",scope.currentTable),scope.$broadcast("table",params)},scope.reload=function(){tableManager.clearPool(),TableListService.getTableList(!0).then(function(result){-1===result.components.findIndex(function(element,index,array){return element.name===scope.currentTable})?(scope.currentTable=null,StateService.set("dftable",scope.currentTable),scope.$broadcast("table",{notify:"close"})):scope.tableSelect()})},scope.$on("table:navigation:select",function(event,args){if(args.hasOwnProperty("service")&&args.hasOwnProperty("table")&&args.hasOwnProperty("type")){scope.currentTable=args.table;var params={table:args.table,service:args.service,notify:"edit"};scope.$broadcast("table",params)}}),scope.$on("table:navigation:close",function(event,args){scope.currentService=args.service,scope.currentTable=null})}}}]).directive("dfSchemaEditor",["MOD_SCHEMA_ASSET_PATH",function(MOD_SCHEMA_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_SCHEMA_ASSET_PATH+"views/df-schema-editor.html",link:function(scope,elem,attrs){}}}]).directive("dfSchemaResizable",[function(){return{restrict:"A",scope:{},link:function(scope,elem,attrs){$(function(){$("#schema-navigator-resizable").resizable({alsoResize:"#schema-navigator-resizable-also"}),$("#schema-navigator-resizable-also").resizable()})}}}]).directive("dfUploadSchema",["INSTANCE_URL","MOD_SCHEMA_ASSET_PATH","$http","dfNotify","$timeout","SchemaJSONData","StateService","dfApplicationData",function(INSTANCE_URL,MOD_SCHEMA_ASSET_PATH,$http,dfNotify,$timeout,SchemaJSONData,StateService,dfApplicationData){return{restrict:"E",scope:!1,require:["dfUploadSchema","^dfTableTemplate"],templateUrl:MOD_SCHEMA_ASSET_PATH+"views/df-upload-schema.html",controller:function($scope){this.setDefault=function(){$scope.uploadSchemaData=SchemaJSONData.schemaJSON}},link:function(scope,elem,attrs,ctrls){var childCtrl=ctrls[0];ctrls[1].register("table_upload",childCtrl),scope.uploadObj={record:null,recordCopy:null},scope.schemaUploadEditorObj={editor:null},scope.uploadSchema=function(){var messageOptions;try{var editorData=angular.fromJson(scope.schemaUploadEditorObj.editor.getValue())}catch(e){return messageOptions={module:"Validation Error",type:"error",provider:"dreamfactory",message:"The schema JSON is not valid."},void dfNotify.error(messageOptions)}if(-1!==StateService.get("dfservice").components.findIndex(function(element,index,array){return element.name===editorData.resource[0].name}))return messageOptions={module:"Validation Error",type:"error",provider:"dreamfactory",message:"The table name already exists."},void dfNotify.error(messageOptions);scope._uploadSchema()},scope.closeUploadSchema=function(){scope._closeUploadSchema()},scope._uploadSchema=function(){var requestDataObj={params:{include_schema:!0},data:angular.fromJson(scope.schemaUploadEditorObj.editor.getValue())};scope._saveSchemaToServer(requestDataObj).then(function(result){var messageOptions={module:"Schema",type:"success",provider:"dreamfactory",message:"Tables created successfully."};angular.forEach(result.data.table,function(dataObj){scope.currentService.components.push({__dfUI:{newTable:!1},name:dataObj.name,path:"_schema/"+dataObj.name})});var curService=StateService.get("dfservice"),component={__dfUI:{newTable:!1},name:requestDataObj.data.resource[0].name,label:requestDataObj.data.resource[0].label};curService.components.push(component),dfApplicationData.updateServiceComponentsLocal(curService),scope.uploadSchemaData=null;var naviObj={service:curService.name,table:requestDataObj.data.resource[0].name,type:"upload"};scope.$emit("table:navigation:select",naviObj),dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)})},scope._saveSchemaToServer=function(requestDataObj){return $http({method:"POST",url:INSTANCE_URL.url+"/"+StateService.get("dfservice").name+"/_schema",data:requestDataObj.data})},scope._closeUploadSchema=function(){scope.$emit("table",{notify:"close"})}}}}]).directive("jsonEdit",function(){return{restrict:"A",require:"ngModel",template:'',replace:!0,scope:{model:"=jsonEdit"},link:function(scope,element,attrs,ngModelCtrl){function setEditing(value){scope.jsonEditing=angular.copy(JSON2String(value))}function updateModel(value){scope.model=string2JSON(value)}function setValid(){ngModelCtrl.$setValidity("json",!0)}function setInvalid(){ngModelCtrl.$setValidity("json",!1)}function string2JSON(text){try{return angular.fromJson(text)}catch(err){return setInvalid(),text}}function JSON2String(object){return angular.toJson(object,!0)}function isValidJson(model){var flag=!0;try{angular.fromJson(model)}catch(err){flag=!1}return flag}setEditing(scope.model),scope.$watch("jsonEditing",function(newval,oldval){newval!=oldval&&(isValidJson(newval)?(setValid(),updateModel(newval)):setInvalid())},!0),scope.$watch("model",function(newval,oldval){newval!=oldval&&setEditing(newval)},!0)}}}),angular.module("dfScripts",["ngRoute","dfUtility"]).constant("MODSCRIPTING_ROUTER_PATH","/scripts").constant("MODSCRIPTING_ASSET_PATH","admin_components/adf-scripts/").constant("MODSCRIPTING_EXAMPLES_PATH","admin_components/adf-scripts/examples/").config(["$routeProvider","MODSCRIPTING_ROUTER_PATH","MODSCRIPTING_ASSET_PATH",function($routeProvider,MODSCRIPTING_ROUTER_PATH,MODSCRIPTING_ASSET_PATH){$routeProvider.when(MODSCRIPTING_ROUTER_PATH,{templateUrl:MODSCRIPTING_ASSET_PATH+"views/main.html",controller:"ScriptsCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("ScriptsCtrl",["INSTANCE_URL","SystemConfigDataService","$scope","$rootScope","$http","dfApplicationData","dfNotify","$location","dfSelectedService",function(INSTANCE_URL,SystemConfigDataService,$scope,$rootScope,$http,dfApplicationData,dfNotify,$location,dfSelectedService){$scope.$parent.title="Scripts",$scope.$parent.titleIcon="code",$scope.scriptGitHubTarget="scripts",$scope.newScript=!0,$scope.isEventScriptEditable=!0,$scope.eventScriptUpdateCounter=0,$scope.disableServiceLinkRefresh=!0,$scope.selections={service:null};var ScriptObj=function(name){return{name:name,type:"nodejs",content:"",is_active:!1,allow_event_modification:!1,storage_service_id:null,scm_repository:null,scm_reference:null,storage_path:null}};$scope.handleFiles=function(element){var file=element.files&&element.files[0];if(file){var reader=new FileReader;reader.readAsText(file,"UTF-8"),reader.onload=function(evt){$scope.$apply(function(){$scope.currentScriptObj.content=evt.target.result,$scope.eventScriptUpdateCounter++})},reader.onerror=function(evt){}}},$scope.githubModalShow=function(){$rootScope.$broadcast("githubShowModal",$scope.scriptGitHubTarget)},$scope.isHostedSystem=!1,$scope.apiData=null,$scope.subscription_required=!1,$scope.loadTabData=function(){$scope.dataLoading=!0;dfApplicationData.getApiData(["system"]).then(function(response){if(angular.forEach(response[0].resource,function(value){"script_type"!==value.name&&"event_script"!==value.name||($scope.scriptsEnabled=!0)}),$scope.scriptsEnabled){var primaryApis=["event_script"],secondaryApis=["service_list","script_type","service_link","environment"];dfApplicationData.getApiData(primaryApis,!0).then(function(response){var newApiData={};primaryApis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),dfApplicationData.getApiData(secondaryApis,null===$scope.apiData).then(function(response){secondaryApis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData,dfSelectedService.currentServiceName&&$scope.selectService(dfSelectedService.currentServiceName)},function(error){var msg="There was an error loading data for the Scripts tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Scripts tab your role must allow GET access to system/event_script, system/event, and system/script_type. To create, update, or delete scripts you need POST and DELETE access to /system/event_script.",$location.url("/home"));var messageOptions={module:"Scripts",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},function(error){var msg="There was an error loading data for the Scripts tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Scripts tab your role must allow GET access to system/event_script, system/event, and system/script_type. To create, update, or delete scripts you need POST and DELETE access to /system/event_script.",$location.url("/home"));var messageOptions={module:"Scripts",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions),$scope.dataLoading=!1})}else $scope.subscription_required=!0},function(error){var messageOptions={module:"Limits",provider:"dreamfactory",type:"error",message:"There was an error loading data for the Limits tab. Please try refreshing your browser and logging in again."};dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.getRefreshEnable=function(){var type,enable=!1;return $scope.currentScriptObj&&$scope.selections.service&&("github"===(type=$scope.selections.service.type)||"gitlab"===type||"bitbucket"===type?$scope.currentScriptObj.scm_repository&&$scope.currentScriptObj.scm_reference&&$scope.currentScriptObj.storage_path&&(enable=!0):$scope.currentScriptObj.storage_path&&(enable=!0)),enable},$scope.resetServiceLink=function(){$scope.currentScriptObj.scm_repository=null,$scope.currentScriptObj.scm_reference=null,$scope.currentScriptObj.storage_path=null},$scope.pullLatestScript=function(){var serviceName=$scope.selections.service.name,serviceRepo=$scope.currentScriptObj.scm_repository,serviceRef=$scope.currentScriptObj.scm_reference,servicePath=$scope.currentScriptObj.storage_path,url=INSTANCE_URL.url+"/"+serviceName;if(!$scope.selections.service||"github"!==$scope.selections.service.type&&"gitlab"!==$scope.selections.service.type&&"bitbucket"!==$scope.selections.service.type)url=url+"/"+servicePath;else{var params={path:servicePath,branch:serviceRef,content:1};url=url+"/_repo/"+serviceRepo}$http({method:"GET",url:url,params:params}).then(function(result){$scope.currentScriptObj.content=result.data,$scope.eventScriptUpdateCounter++;var messageOptions={module:"Scripts",provider:"dreamfactory",type:"success",message:"Successfully pulled the latest script from source."};dfNotify.error(messageOptions)},function(error){var messageOptions={module:"Scripts",provider:"dreamfactory",type:"error",message:"There was an error pulling the latest script from source. Please make sure your service, path and permissions are correct and try again."};dfNotify.error(messageOptions)}).finally(function(){})},$scope.deleteScriptFromCache=function(){$http({method:"DELETE",url:INSTANCE_URL.url+"/system/cache/_event/"+$scope.currentScriptObj.name}).then(function(result){var messageOptions={module:"Scripts",provider:"dreamfactory",type:"success",message:"Successfully cleared script from cache."};dfNotify.error(messageOptions)},function(error){var messageOptions={module:"Scripts",provider:"dreamfactory",type:"error",message:"Failed to cleared script from cache."};dfNotify.error(messageOptions)}).finally(function(){})},$scope.loadTabData(),$scope.allowedScriptFormats=["js","php","py","txt"],$scope.currentServiceObj=null,$scope.currentResourceObj=null,$scope.currentEndpointObj=null,$scope.currentScriptObj=null,$scope.menuPathArr=[],$scope.eventLookup={},$scope.eventsLoading=!1,$scope.eventScriptEditorObj={editor:null},$scope.explodeEndpoint=function(endpointName,parameter){var endpoints=[endpointName];return null!==parameter&&endpointName.indexOf("{")>=0&&endpointName.indexOf("}")>=0&&angular.forEach(parameter,function(paramArray,paramName){angular.forEach(paramArray,function(itemName){endpoints.push(endpointName.replace("{"+paramName+"}",itemName))})}),endpoints},$scope.buildEventLookup=function(eventData){var lookupObj,newData=angular.copy(eventData),lookupData={};return angular.forEach(newData,function(resources,serviceName){angular.forEach(resources,function(resourceData,resourceName){angular.forEach(resourceData.endpoints,function(endpointName){lookupObj={service:serviceName,resource:resourceName,endpoint:endpointName},lookupData[endpointName]=lookupObj,null!==resourceData.parameter&&endpointName.indexOf("{")>=0&&endpointName.indexOf("}")>=0&&angular.forEach(resourceData.parameter,function(paramArray,paramName){angular.forEach(paramArray,function(itemName){lookupData[endpointName.replace("{"+paramName+"}",itemName)]=lookupObj})})})})}),lookupData},$scope.highlightService=function(serviceName){return $scope.apiData.event_script.some(function(scriptName){return 0===scriptName.indexOf(serviceName+".")})},$scope.highlightResource=function(resourceName){return $scope.apiData.event_script.some(function(scriptName){var event=$scope.eventLookup[scriptName];return!!event&&event.resource===resourceName})},$scope.highlightEndpoint=function(endpointName){return $scope.apiData.event_script.some(function(scriptName){var event=$scope.eventLookup[scriptName];return!!event&&event.endpoint===endpointName})},$scope.highlightExplodedEndpoint=function(endpointName){return $scope.apiData.event_script.some(function(scriptName){return scriptName===endpointName})},$scope.selectService=function(service){if(!$scope.eventsLoading){$scope.eventsLoading=!0;var serviceName=service.name;$http({method:"GET",url:INSTANCE_URL.url+"/system/event",params:{service:serviceName,scriptable:!0}}).then(function(result){$scope.menuPathArr.push(serviceName);var resources=result.data[serviceName];$scope.currentServiceObj={name:serviceName,resources:resources},$scope.eventLookup=$scope.buildEventLookup(result.data)},function(reject){var messageOptions={module:"Scripts",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){$scope.eventsLoading=!1})}},$scope.selectResource=function(resourceName,resource){$scope.menuPathArr.push(resourceName),$scope.currentResourceObj={name:resourceName,endpoints:resource.endpoints,parameter:resource.parameter}},$scope.selectEndpoint=function(endpointName){var endpoints;$scope.menuPathArr.push(endpointName),endpoints=$scope.explodeEndpoint(endpointName,$scope.currentResourceObj.parameter),$scope.currentEndpointObj={name:endpointName,endpoints:endpoints}},$scope.getServiceById=function(id){var matches=$scope.apiData.service_link.filter(function(service){return service.id===id});return 0===matches.length?null:matches[0]},$scope.getScript=function(scriptName){$scope.menuPathArr.push(scriptName);var requestDataObj={name:scriptName,params:{}};$http({method:"GET",url:INSTANCE_URL.url+"/system/event_script/"+requestDataObj.name,params:requestDataObj.params}).then(function(result){var obj=result.data;$scope.selections.service=$scope.getServiceById(obj.storage_service_id),$scope.selections.service&&(obj.content=""),$scope.currentScriptObj=obj,$scope.newScript=!1},function(reject){if(reject.data&&reject.data.error&&404===reject.data.error.code)$scope.currentScriptObj=new ScriptObj(scriptName),$scope.newScript=!0,$scope.selections.service=null;else{var messageOptions={module:"Scripts",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions),$scope.menuBack()}}).finally(function(){})},$scope.saveScript=function(){if($scope.currentScriptObj.name){$scope.currentScriptObj.storage_service_id=$scope.selections.service?$scope.selections.service.id:null,!$scope.selections.service||"github"!==$scope.selections.service.type&&"gitlab"!==$scope.selections.service.type&&"bitbucket"!==$scope.selections.service.type?$scope.currentScriptObj.scm_repository=null:$scope.currentScriptObj.scm_repository=$scope.currentScriptObj.scm_repository?$scope.currentScriptObj.scm_repository:null,!$scope.selections.service||"github"!==$scope.selections.service.type&&"gitlab"!==$scope.selections.service.type&&"bitbucket"!==$scope.selections.service.type?$scope.currentScriptObj.scm_reference=null:$scope.currentScriptObj.scm_reference=$scope.currentScriptObj.scm_reference?$scope.currentScriptObj.scm_reference:null,$scope.selections.service?$scope.currentScriptObj.storage_path=$scope.currentScriptObj.storage_path?$scope.currentScriptObj.storage_path:null:$scope.currentScriptObj.storage_path=null,$scope.selections.service?($scope.currentScriptObj.content="",$scope.eventScriptUpdateCounter++):$scope.currentScriptObj.content=$scope.eventScriptEditorObj.editor.getValue();var requestDataObj={name:$scope.currentScriptObj.name,params:{},data:$scope.currentScriptObj};$http({method:"POST",url:INSTANCE_URL.url+"/system/event_script/"+requestDataObj.name,params:requestDataObj.params,data:requestDataObj.data}).then(function(result){$scope.newScript=!1;var messageOptions={module:"Scripts",type:"success",provider:"dreamfactory",message:'Script "'+$scope.currentScriptObj.name+'" saved successfully.'};dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Scripts",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){$scope.loadTabData()})}},$scope.deleteScript=function(){if(dfNotify.confirm("Delete "+$scope.currentScriptObj.name+"?")){var requestDataObj={name:$scope.currentScriptObj.name,params:{}};$http({method:"DELETE",url:INSTANCE_URL.url+"/system/event_script/"+requestDataObj.name,params:requestDataObj.params}).then(function(result){var messageOptions={module:"Scripts",type:"success",provider:"dreamfactory",message:"Script deleted successfully."};dfNotify.success(messageOptions),$scope.menuPathArr.pop(),$scope.currentScriptObj=null},function(reject){var messageOptions={module:"Scripts",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){$scope.loadTabData()})}},$scope.menuOpen=!0,$scope.toggleMenu=function(){$scope.menuOpen=!$scope.menuOpen},$scope.menuBack=function(){$scope.menuPathArr.length>0&&($scope.menuPathArr.pop(),$scope.currentScriptObj=null,$scope.eventScriptEditorObj.editor.setValue(""))},$scope.jumpTo=function(index){for(;$scope.menuPathArr.length-1!==index;)$scope.menuBack()},$scope.$broadcast("script:loaded:success");var watchGithubCredUser=$scope.$watch("githubModal.username",function(newValue,oldValue){if(!newValue)return!1;$scope.modalError={visible:!1,message:""}}),watchGithubCredPass=$scope.$watch("githubModal.password",function(newValue,oldValue){if(!newValue)return!1;$scope.modalError={visible:!1,message:""}}),watchGithubURL=$scope.$watch("githubModal.url",function(newValue,oldValue){if(!newValue)return!1;if($scope.modalError={visible:!1,message:""},newValue.indexOf(".js")>0||newValue.indexOf(".py")>0||newValue.indexOf(".php")>0||newValue.indexOf(".txt")>0){var url=angular.copy($scope.githubModal.url),url_array=url.substr(url.indexOf(".com/")+5).split("/"),github_api_url="https://api.github.com/repos/"+url_array[0]+"/"+url_array[1];$http.get(github_api_url,{headers:{"X-DreamFactory-API-Key":void 0,"X-DreamFactory-Session-Token":void 0}}).then(function(response){$scope.githubModal.private=response.data.private,$scope.modalError={visible:!1,message:""}},function(response){404===response.status&&($scope.modalError={visible:!0,message:"Error: The repository could not be found."})})}}),watchCurrentScriptObj=$scope.$watchCollection("currentScriptObj",function(newValue,oldValue){newValue&&($scope.disableServiceLinkRefresh=!$scope.getRefreshEnable())}),watchSelections=$scope.$watchCollection("selections",function(newValue,oldValue){$scope.disableServiceLinkRefresh=!$scope.getRefreshEnable(),newValue&&($scope.isEventScriptEditable=null===newValue.service,null!==newValue.service&&($scope.currentScriptObj.content="",$scope.eventScriptUpdateCounter++))}),watchApiData=$scope.$watchCollection("apiData",function(newValue,oldValue){newValue&&newValue.environment&&newValue.environment.platform&&newValue.environment.platform.is_hosted&&($scope.isHostedSystem=!0)});$scope.$on("$destroy",function(e){watchGithubURL(),watchGithubCredUser(),watchGithubCredPass(),watchCurrentScriptObj(),watchSelections(),watchApiData(),dfSelectedService.cleanCurrentService()})}]).directive("scriptSidebarMenu",["MODSCRIPTING_ASSET_PATH",function(MODSCRIPTING_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MODSCRIPTING_ASSET_PATH+"views/script-sidebar-menu.html",link:function(scope,elem,attrs){}}}]).directive("dfAceSamplesSelect",["MODSCRIPTING_ASSET_PATH","MODSCRIPTING_EXAMPLES_PATH","$http",function(MODSCRIPTING_ASSET_PATH,MODSCRIPTING_EXAMPLES_PATH,$http){return{restrict:"E",scope:!1,templateUrl:MODSCRIPTING_ASSET_PATH+"views/df-ace-samples.html",link:function(scope,elem,attrs){scope.eventScriptSamplesEditorObj={editor:null},scope.eventScriptSamplesType="nodejs",scope.eventScriptSamplesContent="",scope.scriptSamplesSelect=function(type){var fileExt;switch(type){case"nodejs":fileExt="node.js";break;case"php":fileExt="php";break;case"python":fileExt="py";break;case"python3":fileExt="python3.py";break;default:return}scope.eventScriptSamplesType=type,$http.get(MODSCRIPTING_EXAMPLES_PATH+"example.scripts."+fileExt).then(function(result){scope.eventScriptSamplesContent=result.data},function(reject){})},scope.scriptSamplesSelect("nodejs")}}}]).directive("dfScriptingLoading",[function(){return{restrict:"E",template:"
"}}]),angular.module("dfProfile",["ngRoute","dfUtility","dfUserManagement","dfApplication"]).constant("MOD_PROFILE_ROUTER_PATH","/profile").constant("MOD_PROFILE_ASSET_PATH","admin_components/adf-profile/").config(["$routeProvider","MOD_PROFILE_ROUTER_PATH","MOD_PROFILE_ASSET_PATH",function($routeProvider,MOD_PROFILE_ROUTER_PATH,MOD_PROFILE_ASSET_PATH){$routeProvider.when(MOD_PROFILE_ROUTER_PATH,{templateUrl:MOD_PROFILE_ASSET_PATH+"views/main.html",controller:"ProfileCtrl",resolve:{checkProfileRoute:["UserDataService","$location",function(UserDataService,$location){UserDataService.getCurrentUser()||$location.url("/login")}]}})}]).run([function(){}]).controller("ProfileCtrl",["$scope","UserDataService","dfApplicationData","dfNotify","$http","INSTANCE_URL",function($scope,UserDataService,dfApplicationData,dfNotify,$http,INSTANCE_URL){$scope.user=null,$scope.isAdminUser=UserDataService.getCurrentUser().is_sys_admin,$scope.resource=$scope.isAdminUser?"system/admin":"user",$http({method:"GET",url:INSTANCE_URL.url+"/"+$scope.resource+"/profile"}).then(function(result){$scope.user=result.data,($scope.user.adldap||$scope.user.oauth_provider)&&(angular.element("#set-password-section").hide(),angular.element("#set-security-question-section").hide())},function(error){var messageOptions={module:"Profile",provider:"dreamfactory",type:"error",message:"There was an error loading User Profile data. Please try refreshing your browser and logging in again."};dfNotify.error(messageOptions)}),$scope.$parent.title="",$scope.links=[{name:"edit-profile",label:"Profile",path:"edit-profile"}]}]).directive("dfEditProfile",["MOD_PROFILE_ASSET_PATH","INSTANCE_URL","dfNotify","dfApplicationData","UserDataService","dfObjectService","$http","$cookies","SystemConfigDataService",function(MOD_APPS_ASSET_PATH,INSTANCE_URL,dfNotify,dfApplicationData,UserDataService,dfObjectService,$http,$cookies,SystemConfigDataService){return{restrict:"E",scope:!1,templateUrl:MOD_APPS_ASSET_PATH+"views/df-edit-profile.html",link:function(scope,elem,attrs){var messageOptions,requestDataObj,session_token,existingUser;scope.loginAttribute="email",scope.bitnami_demo=!1;var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("login_attribute")&&(scope.loginAttribute=systemConfig.authentication.login_attribute),systemConfig&&systemConfig.platform&&systemConfig.platform.hasOwnProperty("bitnami_demo")&&(scope.bitnami_demo=systemConfig.platform.bitnami_demo),scope.requireCurrentPassword=!1,scope.emailChange=function(){scope.requireCurrentPassword=!0},scope.updateUser=function(){scope.setPassword?scope.updatePassword():scope.updateProfile(!1)},scope.updatePassword=function(){if(scope.password.old_password&&scope.password.new_password&&scope.password.verify_password){if(scope.password.new_password!==scope.password.verify_password)return messageOptions={module:"Profile",type:"error",provider:"dreamfactory",message:"Passwords do not match."},void dfNotify.error(messageOptions);requestDataObj={params:{reset:!1,login:!0},data:{old_password:scope.password.old_password,new_password:scope.password.new_password}},scope.updateUserPasswordToServer(requestDataObj).then(function(result){(session_token=result.data.session_token)&&((existingUser=UserDataService.getCurrentUser()).session_token=session_token,UserDataService.setCurrentUser(existingUser)),scope.requireCurrentPassword&&(scope.user.current_password=scope.password.new_password),scope.updateProfile(!0)},function(reject){var messageOptions={module:"Profile",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)})}},scope.updateProfile=function(passwordUpdated){requestDataObj={params:{fields:"*"},data:scope.user,url:INSTANCE_URL.url+"/"+scope.resource+"/profile"},scope.updateUserToServer(requestDataObj).then(function(result){(session_token=result.data.session_token)&&((existingUser=UserDataService.getCurrentUser()).session_token=session_token,UserDataService.setCurrentUser(existingUser)),scope.user.hasOwnProperty("security_question")&&delete scope.user.security_question,scope.user.hasOwnProperty("security_answer")&&delete scope.user.security_answer,UserDataService.setCurrentUser(dfObjectService.mergeObjects(scope.user,UserDataService.getCurrentUser())),scope.isAdminUser&&dfApplicationData.deleteApiDataFromCache("admin"),scope.setPassword=!1,scope.setQuestion=!1,messageOptions={module:"Profile",type:"success",provider:"dreamfactory",message:(passwordUpdated?"Profile and password":"Profile")+" updated successfully."},scope.requireCurrentPassword=!1,dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Profile",type:"error",provider:"dreamfactory",message:passwordUpdated?"Password updated successfully but Profile could not be saved.":reject};dfNotify.error(messageOptions)}).finally(function(){scope.user.current_password=""})},scope.updateUserToServer=function(requestDataObj){return $http({method:"PUT",url:INSTANCE_URL.url+"/"+scope.resource+"/profile",data:requestDataObj.data})},scope.updateUserPasswordToServer=function(requestDataObj){return $http({method:"POST",url:INSTANCE_URL.url+"/"+scope.resource+"/password",params:requestDataObj.params,data:requestDataObj.data})},scope.$watch("setPassword",function(newValue){newValue?(scope.user.current_password="",scope.requireOldPassword=!0,scope.password={old_password:"",new_password:"",verify_password:""}):(scope.password=null,scope.identical=!0)})}}}]),angular.module("dfApplication",["dfUtility","dfUserManagement","ngResource"]).run([function(){}]).service("dfApplicationData",["$q","$http","INSTANCE_URL","dfObjectService","UserDataService","dfSystemData","dfDataWrapper","$rootScope","$location",function($q,$http,INSTANCE_URL,dfObjectService,UserDataService,dfSystemData,dfDataWrapper,$rootScope,$location){function _checkParams(options){options.params?angular.forEach(options.params,function(value,key){null==value&&delete options.params[key]}):options.params={}}function _getApiData(apis,forceRefresh){var deferred=$q.defer(),promises=apis.map(function(api){return _loadOne(api,forceRefresh)});return $q.all(promises).then(function(response){deferred.resolve(response)},function(response){deferred.reject(response)}),deferred.promise}function _loadOne(api,forceRefresh){var params,options,deferred=$q.defer();if(!0===forceRefresh&&delete dfApplicationObj.apis[api],dfApplicationObj.apis.hasOwnProperty(api))deferred.resolve(dfApplicationObj.apis[api]);else{switch((params=_getApiPrefs().data[api])||(params={}),options=null,api){case"system":params.api="";break;case"event_list":params.api="event";break;case"service_link":case"storage_service_link":case"service_list":case"service_type_list":options={url:INSTANCE_URL.url};break;default:params.api=api}dfSystemData.resource(options).get(params).$promise.then(function(response){dfApplicationObj.apis[api]="service_link"===api||"service_list"===api||"storage_service_link"===api?{resource:response.services}:"service_type_list"===api?{resource:response.service_types}:response,deferred.resolve(dfApplicationObj.apis[api])},function(error){deferred.reject(error.data)})}return deferred.promise}function _getApiDataSync(api,forceRefresh){if(!0===forceRefresh&&delete dfApplicationObj.apis[api],dfApplicationObj.apis.hasOwnProperty(api));else{var xhr,currentUser=UserDataService.getCurrentUser();xhr=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP");var url=INSTANCE_URL.url+"/system/"+("system"===api?"":api);xhr.open("GET",url,!1),xhr.setRequestHeader("X-DreamFactory-API-Key","6498a8ad1beb9d84d63035c5d1120c007fad6de706734db9689f8996707e0f7d"),currentUser&¤tUser.session_token&&xhr.setRequestHeader("X-DreamFactory-Session-Token",currentUser.session_token),xhr.setRequestHeader("Content-Type","application/json"),xhr.send(),4==xhr.readyState&&200==xhr.status&&(Array.isArray(angular.fromJson(xhr.responseText))?dfApplicationObj.apis[api]=dfDataWrapper.wrapArrayResponse(xhr.responseText):dfApplicationObj.apis[api]=angular.fromJson(xhr.responseText))}return dfApplicationObj.apis[api]}function _isGoldLicense(){var systemList=_getApiDataSync("system"),limitsEnabled=!1,serviceReportsEnabled=!1;return angular.forEach(systemList.resource,function(value){"limit"===value.name?limitsEnabled=!0:"service_report"===value.name&&(serviceReportsEnabled=!0)}),limitsEnabled&&serviceReportsEnabled}function _resetApplicationObj(){dfApplicationObj={apis:{}}}function _saveApiData(api,options){_checkParams(options);var params=options.params;return params.api=api,options.dontWrapData||(options.data={resource:[options.data]}),dfSystemData.resource(options).post(params,options.data,function(result){result&&result.resource&&"[object Array]"===Object.prototype.toString.call(result.resource)&&result.resource.length>0&&(result=result.resource[0]),__insertApiData(api,result)})}function _updateApiData(api,options){_checkParams(options);var params=options.params;return params.api=api,dfSystemData.resource({url:options.url})[options.method||"put"](params,options.data,function(result){__updateApiData(api,result)})}function _deleteApiData(api,options){_checkParams(options);var params=options.params;return params.api=api,params.rollback=_getApiPrefs().data[api].rollback,dfSystemData.resource().delete(params,options.data,function(result){__deleteApiData(api,result)})}function _getDataSetFromServer(api,options){options=options||{params:{}};var defaults=_getApiPrefs().data[api];options.params=dfObjectService.mergeObjects(defaults,options.params);var params=options.params;return params.api=api,dfSystemData.resource(options).get(params,function(result){__replaceApiData(api,result)})}function _getApiPrefs(){return{data:{app:{include_count:!0,limit:100,related:"role_by_role_id"},role:{include_count:!0,related:"role_service_access_by_role_id,lookup_by_role_id",limit:1e4},admin:{include_count:!0,limit:100,related:"lookup_by_user_id"},user:{include_count:!0,limit:100,related:"lookup_by_user_id,user_to_app_to_role_by_user_id"},service:{include_count:!0,limit:100,related:"service_doc_by_service_id"},service_link:{group:"source control,file"},storage_service_link:{group:"file"},service_list:{},service_type_list:{},cache:{fields:"*"},email_template:{include_count:!0},lookup:{include_count:!0},cors:{include_count:!0},event_list:{as_list:!0},event_script:{as_list:!0},limit:{include_count:!0,limit:100,related:"service_by_service_id,role_by_role_id,user_by_user_id,limit_cache_by_limit_id"},service_report:{include_count:!0,limit:100},scheduler:{include_count:!0,limit:100,related:"task_log_by_task_id"}}}}function __insertApiData(api,dataObj){dfApplicationObj.apis.hasOwnProperty(api)&&"[object Array]"===Object.prototype.toString.call(dfApplicationObj.apis[api].resource)&&dfApplicationObj.apis[api].resource.push(dataObj),dfApplicationObj.apis.hasOwnProperty(api)&&dfApplicationObj.apis[api].hasOwnProperty("meta")&&"[object Object]"===Object.prototype.toString.call(dfApplicationObj.apis[api].meta)&&(dfApplicationObj.apis[api].meta.hasOwnProperty("count")?dfApplicationObj.apis[api].meta.count++:dfApplicationObj.apis[api].meta.count=1)}function __updateApiData(api,dataObj){if(dataObj.resource&&(dataObj=dataObj.resource),dfApplicationObj.apis.hasOwnProperty(api)&&"[object Array]"===Object.prototype.toString.call(dfApplicationObj.apis[api].resource))for(var found=!1,i=0;!found&&i<=dfApplicationObj.apis[api].resource.length-1;)dataObj.id===dfApplicationObj.apis[api].resource[i].id&&(found=!0,dfApplicationObj.apis[api].resource.splice(i,1,dataObj)),i++}function __deleteApiData(api,result){function removeRecord(record){for(var found=!1,i=0;!found&&i=0)&&reject.data.error)return reject.data.error.message.indexOf("Token has expired")>=0||-1!==reject.config.url.indexOf("/profile")?refreshSession(reject):newSession(reject)}return $q.reject(reject)}}}]),angular.module("dfHelp",[]).constant("MOD_HELP_ASSET_PATH","admin_components/adf-help/").directive("dfSimpleHelp",["MOD_HELP_ASSET_PATH",function(MOD_HELP_ASSET_PATH){return{restrict:"E",replace:!0,scope:{options:"=?"},templateUrl:MOD_HELP_ASSET_PATH+"views/simple-help.html",link:function(scope,elem,attrs){var helpDiv=$(elem).children(".help-box");scope.showHelp=function(){scope._showHelp()},scope.closeHelp=function(){scope._closeHelp()},scope._setVisible=function(){helpDiv.is(":hidden")&&helpDiv.show()},scope._setHidden=function(){helpDiv.is(":visible")&&helpDiv.hide()},scope._setWidth=function(){helpDiv.css({width:$(window).outerWidth()/6})},scope._showHelp=function(){if(helpDiv.is(":visible"))return scope.closeHelp(),!1;helpDiv.addClass("dfp-right-bottom"),scope._setWidth(),scope._setVisible()},scope._closeHelp=function(){if(helpDiv.is(":hidden"))return!1;helpDiv.removeClass("dfp-right-bottom"),scope._setHidden()}}}}]).directive("dfLargeHelp",["MOD_HELP_ASSET_PATH","$compile",function(MOD_HELP_ASSET_PATH,$compile){return{restrict:"E",replace:!0,scope:{options:"="},templateUrl:MOD_HELP_ASSET_PATH+"views/df-large-help.html",link:function(scope,elem,attrs){scope.$watch("options",function(newValue,oldValue){newValue&&(newValue.hasOwnProperty("title")&&$(elem).children(".df-large-help-title").html(newValue.title),newValue.hasOwnProperty("text")&&$(elem).children(".df-large-help-text").html(newValue.text))})}}}]),angular.module("dfLaunchPad",["ngRoute","dfUtility","dfTable"]).constant("MOD_LAUNCHPAD_ROUTER_PATH","/launchpad").constant("MOD_LAUNCHPAD_ASSET_PATH","admin_components/adf-launchpad/").config(["$routeProvider","MOD_LAUNCHPAD_ROUTER_PATH","MOD_LAUNCHPAD_ASSET_PATH",function($routeProvider,MOD_LAUNCHPAD_ROUTER_PATH,MOD_LAUNCHPAD_ASSET_PATH){$routeProvider.when(MOD_LAUNCHPAD_ROUTER_PATH,{templateUrl:MOD_LAUNCHPAD_ASSET_PATH+"views/main.html",controller:"LaunchpadCtrl",resolve:{loadApps:["SystemConfigDataService","UserDataService","$location","$q",function(SystemConfigDataService,UserDataService,$location,$q){var defer=$q.defer(),systemConfig=SystemConfigDataService.getSystemConfig();return location.search.substring(1)?($location.url("/login"),defer.reject()):systemConfig&&systemConfig.apps&&0!==systemConfig.apps.length||UserDataService.getCurrentUser()?defer.resolve(systemConfig):($location.url("/login"),defer.reject()),defer.promise}]}})}]).run([function(){}]).controller("LaunchpadCtrl",["$scope","UserDataService","SystemConfigDataService","loadApps",function($scope,UserDataService,SystemConfigDataService,loadApps){$scope.apps=[],$scope.error=!1,$scope.$watch(function(){return loadApps},function(newValue,oldValue){var apps=[],error=!0;newValue&&newValue.hasOwnProperty("apps")&&(error=!1,angular.forEach(newValue.apps,function(app){app.url&&apps.push(app)})),$scope.apps=apps,$scope.error=error},!0)}]).directive("dfApp",["MOD_LAUNCHPAD_ASSET_PATH","$window",function(MOD_LAUNCHPAD_ASSET_PATH,$window){return{restrict:"E",scope:{app:"="},replace:!0,templateUrl:MOD_LAUNCHPAD_ASSET_PATH+"views/df-app.html",link:function(scope,elem,attrs){scope.launchApp=function(app){scope._launchApp(app)},scope._launchApp=function(app){"admin"===app.name&&(app.url+="#/home"),$window.open(app.url)}}}}]),angular.module("dfApiDocs",["ngRoute","dfUtility"]).constant("MOD_APIDOCS_ROUTER_PATH","/apidocs").constant("MOD_APIDOCS_ASSET_PATH","admin_components/adf-apidocs/").config(["$routeProvider","MOD_APIDOCS_ROUTER_PATH","MOD_APIDOCS_ASSET_PATH",function($routeProvider,MOD_APIDOCS_ROUTER_PATH,MOD_APIDOCS_ASSET_PATH){$routeProvider.when(MOD_APIDOCS_ROUTER_PATH,{templateUrl:MOD_APIDOCS_ASSET_PATH+"views/main.html",controller:"ApiDocsCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("ApiDocsCtrl",["$scope",function($scope){$scope.$parent.title="API Docs",$scope.$parent.titleIcon="book",$scope.links=[{name:"apidocs",label:"View",path:"apidocs"}]}]).directive("apiDocs",["MOD_APIDOCS_ASSET_PATH","INSTANCE_BASE_URL",function(MOD_APIDOCS_ASSET_PATH,INSTANCE_BASE_URL){return{restrict:"E",scope:{},templateUrl:MOD_APIDOCS_ASSET_PATH+"views/apidocs.html",link:function(scope,elem,attrs){scope.server=INSTANCE_BASE_URL+"/df-api-docs-ui/dist/index.html?admin_app=1",scope.$broadcast("apidocs:loaded")}}}]),angular.module("dfFileManager",["ngRoute","dfUtility"]).constant("MOD_FILE_MANAGER_ROUTER_PATH","/file-manager").constant("MOD_FILE_MANAGER_ASSET_PATH","admin_components/adf-file-manager/").config(["$routeProvider","MOD_FILE_MANAGER_ROUTER_PATH","MOD_FILE_MANAGER_ASSET_PATH",function($routeProvider,MOD_FILE_MANAGER_ROUTER_PATH,MOD_FILE_MANAGER_ASSET_PATH){$routeProvider.when(MOD_FILE_MANAGER_ROUTER_PATH,{templateUrl:MOD_FILE_MANAGER_ASSET_PATH+"views/main.html",controller:"FileCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("FileCtrl",["$scope",function($scope){$scope.$parent.title="Files",$scope.$parent.titleIcon="file-o",$scope.links=[{name:"manage-files",label:"Manage",path:"manage-files"}]}]).directive("dfFileManager",["MOD_FILE_MANAGER_ASSET_PATH","INSTANCE_BASE_URL",function(MOD_FILE_MANAGER_ASSET_PATH,INSTANCE_BASE_URL){return{restrict:"E",scope:!1,templateUrl:MOD_FILE_MANAGER_ASSET_PATH+"views/df-file-manager.html",link:function(scope,elem,attrs){$("#root-file-manager iframe").attr("src",INSTANCE_BASE_URL+"/filemanager/index.html?path=/&allowroot=true").show(),scope.$broadcast("filemanager:loaded")}}}]),angular.module("dfPackageManager",["ngRoute","dfUtility","ngclipboard"]).constant("MOD_PACKAGE_MANAGER_ROUTER_PATH","/package-manager").constant("MOD_PACKAGE_MANAGER_ASSET_PATH","admin_components/adf-package-manager/").config(["$routeProvider","MOD_PACKAGE_MANAGER_ROUTER_PATH","MOD_PACKAGE_MANAGER_ASSET_PATH",function($routeProvider,MOD_PACKAGE_MANAGER_ROUTER_PATH,MOD_PACKAGE_MANAGER_ASSET_PATH){$routeProvider.when(MOD_PACKAGE_MANAGER_ROUTER_PATH,{templateUrl:MOD_PACKAGE_MANAGER_ASSET_PATH+"views/main.html",controller:"PackageCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).directive("tabs",function(){return{restrict:"E",transclude:!0,scope:{},controller:["$scope",function($scope){var panes=$scope.panes=[];$scope.select=function(pane){angular.forEach(panes,function(pane){pane.selected=!1}),pane.selected=!0},this.addPane=function(pane){0==panes.length&&$scope.select(pane),panes.push(pane)}}],template:'',replace:!0}}).directive("pane",function(){return{require:"^tabs",restrict:"E",transclude:!0,scope:{title:"@"},link:function(scope,element,attrs,tabsCtrl){tabsCtrl.addPane(scope)},template:'
',replace:!0}}).controller("PackageCtrl",["$scope","$rootScope","dfApplicationData","dfNotify","$location",function($scope,$rootScope,dfApplicationData,dfNotify,$location){$scope.$parent.title="Packages",$scope.$parent.titleIcon="plus-square",$scope.apiData=null,$scope.loadTabData=function(){$scope.dataLoading=!0;var primaryApis=["service_list","service_type_list","environment","package"],secondaryApis=["app"],errorFunc=function(error){var msg="There was an error loading data for the Packages tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Packages tab your role must allow GET and POST access to system/package.",$location.url("/home"));var messageOptions={module:"Packages",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions),$scope.dataLoading=!1};dfApplicationData.getApiData(["system"]).then(function(response){angular.forEach(response[0].resource,function(value){"event_script"===value.name&&($scope.eventScriptEnabled=!0)}),dfApplicationData.getApiData(primaryApis,!0).then(function(response){var newApiData={};primaryApis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),dfApplicationData.getApiData(secondaryApis,!0).then(function(response){secondaryApis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]})},function(error){newApiData.app=[]}).finally(function(){$scope.apiData=newApiData,$scope.dataLoading=!1})},errorFunc)},errorFunc).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(),$scope.dfLargeHelp={packageManager:{title:"Packages Overview",text:"Import and export users, apps, files, database schemas and more."},packageExport:{title:"",text:"To create a DreamFactory package export file, follow these instructions.
  • Use the UI below to build a list of items to export.
  • You should enter a password if you'd like exported user passwords and service credentials to be encrypted. This password will be required if you decide to import this package file later.
  • Select a file service to store the exported zip file. Folder name is optional.
  • Click the Export button to save the zip file to the file storage location you selected.
"}}}]).directive("file",function(){return{scope:{file:"="},link:function(scope,el,attrs){el.bind("change",function(event){var file=event.target.files[0];scope.file=file||void 0,scope.$apply()})}}}).directive("dfImportPackage",["MOD_PACKAGE_MANAGER_ASSET_PATH","INSTANCE_URL","UserDataService","dfApplicationData","dfNotify","$timeout","$http",function(MOD_PACKAGE_MANAGER_ASSET_PATH,INSTANCE_URL,UserDataService,dfApplicationData,dfNotify,$timeout,$http){return{restrict:"E",scope:!1,templateUrl:MOD_PACKAGE_MANAGER_ASSET_PATH+"views/df-import-package.html",link:function(scope,elem,attrs){scope.packageImportPassword="",scope.overwrite=!1,scope.fileSelector=angular.element("#fileSelect"),scope.fileImportPath=null,scope.uploadFile=null,scope.browseFileSystem=function(){scope.fileSelector.trigger("click")},scope.importPackageFile=function(){var file=scope.file;if(void 0===file&&(file=scope.fileImportPath),file){var currentUser=UserDataService.getCurrentUser();$http({method:"POST",url:INSTANCE_URL.url+"/system/package?password="+scope.packageImportPassword+"&overwrite="+scope.overwrite,headers:{"X-DreamFactory-Session-Token":currentUser.session_token,"Content-Type":void 0},data:{files:file,import_url:file},transformRequest:function(data){var formData=new FormData;return angular.forEach(data,function(value,key){formData.append(key,value)}),formData}}).then(function(result){if(result&&result.data)if(!0===result.data.success){var messageOptions={module:"Packages",provider:"dreamfactory",type:"success",message:"Package was imported successfully."};dfNotify.success(messageOptions),scope.importClear(),scope.loadTabData()}else{var notice="";angular.forEach(result.data.log.notice,function(value,key){notice+="* "+value+"\n"});var msg="Package import failed.\n\nReason:\n"+notice;$timeout(function(){alert(msg)})}},function(reject){var messageOptions={module:"Packages",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}),scope.packageImportPassword=""}else{var messageOptions={module:"Packages",provider:"dreamfactory",type:"error",message:"No package file selected."};dfNotify.error(messageOptions)}},scope.importClear=function(){scope.file&&delete scope.file,angular.element("input[type='file']").val(null),scope.packageImportPassword="",scope.fileImportPath=null};var watchUploadFile=scope.$watch("uploadFile",function(n,o){n&&(scope.fileImportPath=n.name)});scope.$on("$destroy",function(e){watchUploadFile()})}}}]).directive("dfViewContent",["MOD_PACKAGE_MANAGER_ASSET_PATH",function(MOD_PACKAGE_MANAGER_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_PACKAGE_MANAGER_ASSET_PATH+"views/df-view-content.html",link:function(scope,elem,attrs){}}}]).directive("dfSelectContent",["$http","$timeout","MOD_PACKAGE_MANAGER_ASSET_PATH","dfApplicationData","dfNotify",function($http,$timeout,MOD_PACKAGE_MANAGER_ASSET_PATH,dfApplicationData,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_PACKAGE_MANAGER_ASSET_PATH+"views/df-select-content.html",link:function(scope,elem,attrs){scope.initVars=function(){scope.types=[],scope.selectedType=null,scope.names=[],scope.selectedName=null,scope.selectedNameData=[],scope.tableData=[],scope.search={}},scope.resetVars=function(){scope.selectedType=null,scope.selectedName=null,scope.selectedNameData=[],scope.tableData=[],scope.search={}},scope.initVars();var filterTextTimeout,tempFilterText=null,TableData=function(tableData){return{__dfUI:{selected:!1},record:tableData}};scope.init=function(){scope.initVars();var env=scope.apiData.environment;scope.enablePassword=env.platform.secured_package_export;var _serviceTypes=scope.apiData.service_type_list,_services=scope.apiData.service_list;angular.forEach(scope.apiData.package.service,function(manifestValue,manifestKey){var _service=_services.filter(function(obj){return obj.name===manifestKey}),type=_serviceTypes.filter(function(obj){return obj.name==_service[0].type}),_typeObj={name:type[0].name,label:type[0].label,group:type[0].group};"Database"===_typeObj.group&&(_typeObj.label+=" Schema"),0===scope.types.filter(function(obj){return obj.name==_typeObj.name}).length&&scope.types.push(_typeObj)})},scope.anySelected=function(){return scope.selectedNameData.map(function(d){return d.__dfUI.selected}).indexOf(!0)>=0},scope.getAllNames=function(){return scope.selectedNameData.map(function(d){return d.record.display_label})},scope.getSelectedNames=function(){var selected;return selected=[],angular.forEach(scope.selectedNameData,function(value){!0===value.__dfUI.selected&&selected.push(value.record.display_label)}),selected},scope.removeRow=function(row){scope.tableData.splice(row,1)},scope.addToPackage=function(selectAll){var selectAllExists=!1;if(angular.forEach(scope.tableData,function(value){value.type.name===scope.selectedType.name&&value.name===scope.selectedName&&!0===value.selectAll&&(selectAllExists=!0)}),!selectAllExists||scope.addAppFiles(scope.getAllNames())){if(!0===selectAll){var tableRemoveArray=[];angular.forEach(scope.tableData,function(value,index){value.name===scope.selectedName&&value.type.name===scope.selectedType.name&&tableRemoveArray.push(index)}),tableRemoveArray.reverse(),angular.forEach(tableRemoveArray,function(value){scope.removeRow(value)});var allNames=scope.getAllNames();scope.tableData.push({type:scope.selectedType,name:scope.selectedName,selectAll:!0,selected:allNames,descr:"All"}),"system"===scope.selectedType.name&&"app"===scope.selectedName&&scope.addAppFiles(allNames)}else{var newSelected=scope.getSelectedNames();angular.forEach(newSelected,function(sel){0===scope.tableData.filter(function(obj){return obj.type.name===scope.selectedType.name&&obj.name===scope.selectedName&&obj.selected[0]===sel}).length&&scope.tableData.push({type:scope.selectedType,name:scope.selectedName,selectAll:!1,selected:[sel],descr:sel}),"system"===scope.selectedType.name&&"app"===scope.selectedName&&scope.addAppFiles([sel])})}angular.forEach(scope.selectedNameData,function(value){value.__dfUI.selected=!1}),console.log("tableData",scope.tableData)}else{var messageOptions={module:"Packages",provider:"dreamfactory",type:"error",message:"You have already selected all items for "+scope.selectedType.label+" / "+scope.selectedName+"."};dfNotify.error(messageOptions)}},scope.addAppFiles=function(appNames){var services,serviceId,serviceName,container,retVal=!1,apps=scope.apiData.app;return angular.forEach(appNames,function(value){if(1===(matches=apps.filter(function(obj){return obj.name===value})).length&&(serviceId=matches[0].storage_service_id,container=matches[0].storage_container+"/",services=scope.apiData.service_list,1===(matches=services.filter(function(obj){return obj.id===serviceId})).length)){var type={group:"File",label:matches[0].label,name:matches[0].type};serviceName=matches[0].name;var matches=scope.tableData.filter(function(obj){return obj.type.name===type.name&&obj.name===serviceName&&obj.selected.indexOf(container)>=0});0===matches.length&&(retVal=!0,scope.tableData.push({type:type,name:serviceName,selectAll:!1,selected:[container],descr:container}))}}),retVal},scope.loadTable=function(newValue,filter){var record,nameData=[],values=[];switch(newValue&&-1!==newValue.indexOf("[unavailable]")&&(alert("You have selected a service that is currently unavailable/unreachable. Please check DreamFactory log or client console for error details."),newValue=newValue.replace(" [unavailable]","")),scope.selectedType.group){case"System":values=scope.apiData.package.service.system[newValue];break;case"Database":values=scope.apiData.package.service[newValue]._schema;break;case"File":values=scope.apiData.package.service[newValue].filter(function(obj){return obj.indexOf("/")>0})}angular.forEach(values,function(value){record="System"!==scope.selectedType.group||"admin"!==scope.selectedName&&"user"!==scope.selectedName?{display_label:value}:{display_label:value.email,first_name:value.first_name,last_name:value.last_name},(!filter||value.indexOf(filter)>=0)&&nameData.push(new TableData(record))}),scope.selectedNameData=nameData},scope.$watch("search.text",function(newValue,oldValue){null!==newValue&&void 0!==newValue&&(filterTextTimeout&&$timeout.cancel(filterTextTimeout),tempFilterText=newValue,filterTextTimeout=$timeout(function(){scope.loadTable(scope.selectedName,tempFilterText)},500))},!0),scope.$watch("selectedType",function(newValue){var _type,_name,_services,_service,_names=[];scope.names=[],scope.selectedName=null,scope.selectedNameData=[],newValue&&newValue.name&&("system"===(_type=newValue.name)?angular.forEach(scope.apiData.package.service.system,function(manifestValue,manifestKey){_names.push(manifestKey)}):(_services=scope.apiData.service_list,angular.forEach(scope.apiData.package.service,function(manifestValue,manifestKey){(_service=_services.filter(function(obj){return obj.name===manifestKey}))[0].type===_type&&(_name=_service[0].name,!1===manifestValue.reachable&&(_name+=" [unavailable]"),_names.push(_name))})),scope.names=_names)}),scope.$watch("selectedName",function(newValue){newValue&&scope.loadTable(newValue,null)}),scope.$watchCollection("apiData",function(newValue){newValue&&scope.init()})}}}]).directive("dfSelectFolder",["MOD_PACKAGE_MANAGER_ASSET_PATH",function(MOD_PACKAGE_MANAGER_ASSET_PATH){return{restrict:"E",scope:!1,templateUrl:MOD_PACKAGE_MANAGER_ASSET_PATH+"views/df-select-folder.html",link:function(scope,elem,attrs){}}}]).directive("dfExportPackage",["INSTANCE_URL","INSTANCE_API_PREFIX","APP_API_KEY","dfNotify","$http","$window","$timeout","UserDataService",function(INSTANCE_URL,INSTANCE_API_PREFIX,APP_API_KEY,dfNotify,$http,$window,$timeout,UserDataService){return{restrict:"A",scope:!1,replace:!0,link:function(scope,elem,attrs){scope.availableFileServices=null,scope.selectedFileService=null,scope.folderName="",scope.fileName="",scope.packagePassword="",scope.showFilePath=!1,scope.publicFilePath="N/A",scope.publicPathNote="";var exportPath="",payload={};scope.folderInit=function(){var _services=scope.apiData.service_list,_searchTypes=scope.apiData.service_type_list.filter(function(obj){return"File"===obj.group}).map(function(type){return type.name}),_fileServices=[];angular.forEach(_services,function(value){_searchTypes.indexOf(value.type)>-1&&_fileServices.push(value)}),scope.selectedFileService=null,scope.availableFileServices=_fileServices},scope.exportPackage=function(){var name,type,group,selected;if(0===scope.tableData.length){messageOptions={module:"Packages",provider:"dreamfactory",type:"error",message:"No package content is selected."};dfNotify.error(messageOptions)}else if(scope.selectedFileService){payload={secured:scope.packagePassword.length>0,password:scope.packagePassword,storage:{name:scope.selectedFileService.name,folder:scope.folderName,filename:scope.fileName},service:{}};var tableData=scope.tableData;angular.forEach(tableData,function(value){switch(selected=value.selected,type=value.type.name,name=value.name,group=value.type.group){case"System":void 0===payload.service[type]&&(payload.service[type]={}),void 0===payload.service[type][name]&&(payload.service[type][name]=[]),payload.service[type][name]=payload.service[type][name].concat(selected);break;case"Database":void 0===payload.service[name]&&(payload.service[name]={}),void 0===payload.service[name]._schema&&(payload.service[name]._schema=[]),payload.service[name]._schema=payload.service[name]._schema.concat(selected);break;case"File":void 0===payload.service[name]&&(payload.service[name]=[]),payload.service[name]=payload.service[name].concat(selected)}}),console.log("manifest",payload),$http({method:"POST",url:INSTANCE_URL.url+"/system/package",data:payload}).then(function(response){exportPath=response.data.path;var path=response.data.path;path=path.replace(INSTANCE_API_PREFIX,""),scope.publicFilePath=path,scope.showFilePath=!0;var msg="The package has been exported. Click the Download button to download the file.\n\nThe path to the exported package is: \n"+path+"\n";if(!1===response.data.is_public){var subFolder=""===scope.folderName?"__EXPORTS":scope.folderName,pathNote='\nTo make your exported file publicly accessible/downloadable, edit your "'+scope.selectedFileService.label+'" service configuration to add "'+subFolder+'" under "Public Path".';msg+=pathNote,scope.publicPathNote=pathNote}$timeout(function(){alert(msg)})},function(response){var msg="An error occurred!\n\nReason:\n"+response.data.error.message+"\n";$timeout(function(){alert(msg)})})}else{var messageOptions={module:"Packages",provider:"dreamfactory",type:"error",message:"No file service is selected."};dfNotify.error(messageOptions)}},scope.exportDownload=function(){if(""!==exportPath){var params="?api_key="+APP_API_KEY,currentUser=UserDataService.getCurrentUser();currentUser&¤tUser.session_token&&(params+="&session_token="+currentUser.session_token),window.location.href=exportPath+params}},scope.exportClear=function(){scope.resetVars(),exportPath="",scope.folderName="",scope.fileName="",scope.packagePassword="",scope.showFilePath=!1,scope.publicFilePath="N/A",scope.publicPathNote=""},scope.$watchCollection("apiData",function(newValue){newValue&&scope.folderInit()})}}}]).directive("dfPackageLoading",[function(){return{restrict:"E",template:"
"}}]),angular.module("dfTable",["dfUtility"]).constant("DF_TABLE_ASSET_PATH","admin_components/adf-table/").run(["$templateCache",function($templateCache){$templateCache.put("df-input-text.html",''),$templateCache.put("df-input-ref-text.html",''),$templateCache.put("df-input-number.html",''),$templateCache.put("df-input-int.html",''),$templateCache.put("df-input-textarea.html",''),$templateCache.put("df-input-binary.html","

BINARY DATA

"),$templateCache.put("df-input-datetime.html","

DATETIME

"),$templateCache.put("df-input-reference.html",'
'),$templateCache.put("df-input-checkbox.html",''),$templateCache.put("df-input-bool-picklist.html",'
'),$templateCache.put("df-input-select.html",''),$templateCache.put("df-input-values-picklist.html",'
\x3c!-- /btn-group --\x3e
\x3c!-- /input-group --\x3e
\x3c!-- /.col-lg-6 --\x3e
'),$templateCache.put("df-input-values-only-picklist.html",'
'),$templateCache.put("df-input-date-time-picker.html",'
\n
\n\n\n\n
\n
\n\n
\n
')}]).filter("typeFilter",[function(){return function(object){var array=[];return angular.forEach(object,function(option){"boolean"!=option.type&&"integer"!=option.type&&"string"!=option.type&&"text"!=option.type&&"float"!=option.type&&"double"!=option.type&&"decimal"!=option.type||array.push(option)}),array}}]).directive("dfTable",["DF_TABLE_ASSET_PATH","$http","$q","$filter","$compile","dfObjectService","dfTableEventService","dfTableCallbacksService",function(DF_TABLE_ASSET_PATH,$http,$q,$filter,$compile,dfObjectService,dfTableEventService,dfTableCallbacksService){return{restrict:"E",scope:{userOptions:"=options",parentRecord:"=?",exportField:"=?"},templateUrl:DF_TABLE_ASSET_PATH+"views/dreamfactory-table.html",link:function(scope,elem,attrs){scope.es=dfTableEventService,scope.defaults={service:"",table:"",url:"",normalizeData:!1,normalizeSchema:!0,autoClose:!0,params:{filter:null,limit:50,offset:0,fields:"*",include_schema:!0,include_count:!0},defaultFields:null,overrideFields:[],extendFieldTypes:[],extendData:[],extendSchema:[],relatedData:[],excludeFields:[],groupFields:[],exportValueOn:!1,allowChildTable:!1,childTableAttachPoint:null,isChildTable:!1},scope.options={},scope.disableTableBtns=!1,scope.record=null,scope.schema=null,scope.overrideFields={},scope.tableFields={onStartTotalActiveFields:0},scope.tableFieldsAll=!1,scope.tableFilterOn=!0,scope.defaultFieldsShown={},scope.numAutoSelectFields=8,scope.selectedAll=!1,scope.filterOn=!1,scope.filter={viewBy:"",prop:"",props:"",type:"",value:null},scope.operators={integer:["<",">","="],boolean:[],string:[],text:[],float:["<",">","="],double:["<",">","="],decimal:["<",">","="]},scope.filterType={operator:null},scope.order={orderBy:"",orderByReverse:!1},scope.filteredRecords=!1,scope.orderedRecords=!1,scope.activeTab=null,scope.activeView="table",scope.pagesArr=[],scope.currentPage={},scope.currentEditRecord=null,scope.extendFieldTypes={},scope.inProgress=!1,scope.count=0,scope._exportValue=null,scope.newRecord=null,scope.relatedExpand=!1,scope.extendedData={},scope.extendedSchema={},scope.excludedFields={},scope.filteredSchema=[],scope.groupedSchema=[],scope.childTableActive=!1,scope.childTableOptions={},scope.childTableParentRecord=null,scope.setTab=function(tabStr){scope._setTab(tabStr)},scope.toggleSelected=function(dataObj){if(scope.childTableActive)return!1;scope._toggleSelected(dataObj)},scope.getPrevious=function(){if(scope._isFirstPage()||scope._isInProgress())return!1;scope._checkForUnsavedRecords(scope.record)?scope._confirmAction("You have Unsaved records. Continue without saving?",scope._getPrevious):scope._getPrevious()},scope.getNext=function(){if(scope._isLastPage()||scope._isInProgress())return!1;scope._checkForUnsavedRecords(scope.record)?scope._confirmAction("You have Unsaved records. Continue without saving?",scope._getNext):scope._getNext()},scope.editRecord=function(dataObj){scope._editRecord(dataObj)},scope.createRecord=function(){scope._createRecord()},scope.saveRecords=function(){scope._saveRecords()},scope.revertRecords=function(){scope._revertRecords()},scope.deleteRecords=function(){scope._confirmAction("You are about to delete records. Continue?",scope._deleteRecords)},scope.applyFilter=function(){scope._applyFilter()},scope.removeFilter=function(){scope._removeFilter()},scope.refreshResults=function(){scope._refreshResults()},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setExportValue=function(dataObj){scope._setExportValue(dataObj)},scope.toggleExpandEditor=function(){scope._toggleExpandEditor()},scope.editExportRecord=function(dataObj){scope._editExportRecord(dataObj)},scope.filterRecords=function(){scope._filterRecords()},scope.toggleAllFields=function(){scope._toggleAllFields()},scope.resetAllFields=function(){scope._resetAllFields()},scope.toggleAllRecords=function(){scope._toggleAllRecords()},scope.showChildTable=function(parentRecordObj){scope._showChildTable(parentRecordObj)},scope._addSelectedProp=function(dataObj){dataObj.__dfUI.hasOwnProperty("selected")||(dataObj.__dfUI.selected=!1)},scope._addUnsavedProp=function(dataObj){dataObj.__dfUI.hasOwnProperty("unsaved")||(dataObj.__dfUI.unsaved=!1)},scope._addExportProp=function(dataObj){dataObj.__dfUI.hasOwnProperty("export")||(dataObj.__dfUI.export=!1)},scope._addHideProp=function(dataObj){dataObj.__dfUI.hasOwnProperty("hide")||(dataObj.__dfUI.hide=!1)},scope._addStateProps=function(dataObj){dataObj.hasOwnProperty.__dfUI||(dataObj.__dfUI={}),scope._addSelectedProp(dataObj),scope._addUnsavedProp(dataObj),scope._addExportProp(dataObj),scope._addHideProp(dataObj)},scope._removeStateProps=function(dataObj){dataObj.hasOwnProperty.__dfUI&&delete dataObj.__dfUI},scope._toggleSelectedState=function(dataObj){dataObj.__dfUI.selected=!dataObj.__dfUI.selected},scope._toggleUnsavedState=function(dataObj){dataObj.__dfUI.unsaved=!dataObj.__dfUI.unsaved},scope._setSelectedState=function(dataObj,stateBool){dataObj.__dfUI.selected=stateBool},scope._setUnsavedState=function(dataObj,stateBool){dataObj.__dfUI.unsaved=stateBool},scope._setExportState=function(dataObj,stateBool){dataObj&&(dataObj.__dfUI.export=stateBool)},scope._setHideState=function(dataObj,stateBool){dataObj&&(dataObj.__dfUI.hide=stateBool)},scope._isUnsaved=function(dataObj){return dataObj.__dfUI.unsaved},scope._isSelected=function(dataObj){return dataObj.__dfUI.selected},scope._isExport=function(dataObj){return dataObj.__dfUI.export},scope._checkForUnsavedRecords=function(data){if(!data)return!1;var unsavedRecords=!1,i=0;do{if(i>=data.length)break;data[i].__dfUI.unsaved&&(unsavedRecords=!0),i++}while(0==unsavedRecords);return unsavedRecords},scope._checkForParams=function(){return scope.options.hasOwnProperty("params")?scope.options.params:scope.defaults.params},scope._getRecordsFromServer=function(requestDataObj){var params=scope._checkForParams();return(requestDataObj=requestDataObj||null)&&(params=dfObjectService.mergeObjects(requestDataObj.params,params)),scope.options.relatedData.length>0&&(params.related=scope.options.relatedData.join(",")),$http({method:"GET",url:scope.options.url,params:params})},scope._getRecordsFromData=function(dataObj){var limit=scope._checkForParams().limit,records=[];return dataObj.hasOwnProperty("resource")?records=dataObj.resource:dataObj.hasOwnProperty("data")&&(records=dataObj.data.hasOwnProperty("resource")?dataObj.data.resource:dataObj.data.data.resource),records.length>limit?records.slice(0,limit):records},scope._getMetaFromData=function(dataObj){var meta={};return dataObj.hasOwnProperty("meta")?meta=dataObj.meta:dataObj.hasOwnProperty("data")&&(meta=dataObj.data.hasOwnProperty("meta")?dataObj.data.meta:dataObj.data.data.meta),meta},scope._getSchemaFromData=function(dataObj){return scope._getMetaFromData(dataObj).schema},scope._getCountFromMeta=function(dataObj){var count=scope._getMetaFromData(dataObj).count;return scope._setCount(count),count},scope._setCount=function(countInt){scope.count=countInt},scope._getOptionFromParams=function(keyStr){return scope._checkForParams()[keyStr]},scope._setOptionFromParams=function(keyStr,valueStr){},scope._buildField=function(fieldNameStr){console.log(fieldNameStr)},scope._createRevertCopy=function(dataObj){dataObj.__dfData={},dataObj.__dfData.revert=angular.copy(dataObj),dataObj.__dfData.revert.hasOwnProperty("_exportValue")||(dataObj.__dfData.revert._exportValue={})},scope._getRevertCopy=function(dataObj){return dataObj.__dfData.revert},scope._hasRevertCopy=function(dataObj){return!!dataObj.hasOwnProperty("__dfData")&&!!dataObj.__dfData.hasOwnProperty("revert")},scope._removeRevertCopy=function(dataObj){dataObj.__dfData.revert&&delete dataObj.__dfData.revert},scope._removeAllDFData=function(dataObj){dataObj.__dfData&&delete dataObj.__dfData},scope._removeAllUIData=function(dataObj){delete dataObj.__dfUI},scope._compareObjects=function(dataObj1,dataObj2){for(var key in dataObj1)if("dfUISelected"!==key&&"dfUIUnsaved"!==key&&"__dfUI"!==key&&"__dfData"!=key&&"created_date"!=key&&"last_modified_date"!=key&&"$$hashKey"!==key&&dataObj1[key]!==dataObj2[key])return(null!=dataObj1[key]&&""!=dataObj1[key]||null!=dataObj2[key]&&""!=dataObj2[key])&&!(dataObj1[key]instanceof Array&&dataObj2[key]instanceof Array&&dataObj1[key].length==dataObj2[key].length);return!1},scope._getRecordsWithState=function(recordsDataArr,stateStr,removeDFDataBool,removeUIDataBool){var records=[];return removeDFDataBool=void 0!==removeDFDataBool&&removeDFDataBool,removeUIDataBool=void 0!==removeUIDataBool&&removeUIDataBool,angular.forEach(recordsDataArr,function(_obj){_obj.__dfUI[stateStr]&&(removeDFDataBool&&scope._removeAllDFData(_obj),removeUIDataBool&&scope._removeAllUIData(_obj),records.push(_obj))}),records},scope._saveRecordsToServer=function(recordsDataArr){if(0==recordsDataArr.length){var defer=$q.defer();return defer.reject("No records selected for save."),defer.promise}return $http({method:"PATCH",url:scope.options.url,data:{resource:recordsDataArr}})},scope._deleteRecordsFromServer=function(recordsDataArr){if(0==recordsDataArr.length){var defer=$q.defer();return defer.reject("No records selected for delete."),defer.promise}return $http({method:"DELETE",url:scope.options.url,data:{resource:recordsDataArr}})},scope._isInProgress=function(){return scope.inProgress},scope._setInProgress=function(stateBool){scope.inProgress=stateBool},scope._createNewRecordObj=function(){var newRecord={};return angular.forEach(scope.schema.field,function(_obj){scope.excludedFields.hasOwnProperty(_obj.name)&&scope.excludedFields[_obj.name].fields.create||(newRecord[_obj.name]=_obj.default)}),scope._addStateProps(newRecord),newRecord},scope._setCurrentEditRecord=function(dataObj){scope.currentEditRecord=dataObj},scope._setNewRecordObj=function(){scope.newRecord=scope._createNewRecordObj()},scope._confirmAction=function(_message,_action){confirm(_message)&&_action.call()},scope._filterFormSchema=function(formNameStr){if(0==scope.excludedFields.length)return!1;angular.forEach(scope.schema.field,function(_obj){scope.excludedFields.hasOwnProperty(_obj.name)&&scope.excludedFields[_obj.name].fields[formNameStr]||scope.filteredSchema.push(_obj)})},scope._buildSchemaGroups=function(){if(0==scope.options.groupFields.length)return!1;var _schema=scope.filteredSchema.length>0?scope.filteredSchema:scope.schema.field;angular.forEach(scope.options.groupFields,function(fobj){var group={};group.name=fobj.name,group.fields=[],group.dividers=fobj.dividers,angular.forEach(_schema,function(item){angular.forEach(fobj.fields,function(field,index){item.name===field&&(group.fields[index]=item)})}),scope.groupedSchema.push(group)})},scope._checkForGroupedSchema=function(groupNameStr){0==scope.groupedSchema.length&&scope.groupedSchema.push({name:groupNameStr,fields:scope.schema.field})},scope._clearFilteredSchema=function(){scope.filteredSchema=[]},scope._clearGroupedSchema=function(){scope.groupedSchema=[]},scope._getDefaultFields=function(dataObj){return dataObj.hasOwnProperty("defaultFields")?dataObj.defaultFields:null},scope._removePrivateFields=function(dataObj){dataObj&&angular.forEach(scope.record,function(_obj){for(var _key in _obj)dataObj[_key]&&"private"==dataObj[_key]&&delete _obj[_key]})},scope._setElementActive=function(tabStr){scope.activeTab=tabStr},scope._setDisableTableBtnsState=function(stateBool){scope.disableTableBtns=stateBool},scope._createFieldsObj=function(schemaDataObj){if(scope.tableFields={onStartTotalActiveFields:0},!scope.defaultFieldsShown){var allKeys=Object.keys(schemaDataObj);return allKeys.length0&&(scope.schema=scope._normalizeSchema(scope.schema,scope.record)),angular.forEach(scope.extendedSchema,function(_obj){scope.schema.field.push(_obj)})},scope._prepareExtendedSchema=function(data){if(null==data.extendSchema)return!1;angular.forEach(data.extendSchema,function(_obj){scope.extendedSchema[_obj.name]={},scope.extendedSchema[_obj.name].name=_obj.name,scope.extendedSchema[_obj.name].type=_obj.type,scope.extendedSchema[_obj.name].label=_obj.label})},scope._prepareOverrideFields=function(data){if(null==data.overrideFields)return!1;angular.forEach(data.overrideFields,function(_obj){scope.overrideFields[_obj.field]={},_obj.hasOwnProperty("record")&&(scope.overrideFields[_obj.field].records=scope._getRecordsFromData(_obj.record)),scope.overrideFields[_obj.field].display=_obj.display})},scope._prepareExtendedFieldTypes=function(data){if(null==data.extendFieldTypes)return!1;angular.forEach(data.extendFieldTypes,function(_obj){scope.extendFieldTypes[_obj.db_type]={};for(var _key in _obj)scope.extendFieldTypes[_obj.db_type][_key]=_obj[_key]})},scope._prepareExtendedData=function(data){if(null==data.extendData)return!1;angular.forEach(data.extendData,function(_obj){scope.extendedData[_obj.name]={},scope.extendedData[_obj.name].name=_obj.name,scope.extendedData[_obj.name].value=_obj.value||null})},scope._addExtendedData=function(dataObj){angular.forEach(scope.extendedData,function(_obj){dataObj[_obj.name]=_obj.value})},scope._setActiveView=function(viewStr){scope.activeView=viewStr},scope._setExportValueToParent=function(dataObj){scope._exportValue=dataObj||null},scope._prepareExcludedFields=function(data){if(null==data.extendSchema)return!1;angular.forEach(data.excludeFields,function(_obj){scope.excludedFields[_obj.name]={},scope.excludedFields[_obj.name].fields=_obj.fields})},scope._calcTotalPages=function(totalCount,numPerPage){return Math.ceil(totalCount/numPerPage)},scope._createPageObj=function(_pageNum){return{number:_pageNum+1,value:_pageNum,offset:_pageNum*scope._getOptionFromParams("limit"),stopPropagation:!1}},scope._createPagesArr=function(_totalCount){scope.pagesArr=[];for(var i=0;i<_totalCount;i++)scope.pagesArr.push(scope._createPageObj(i))},scope._setCurrentPage=function(pageDataObj){scope.currentPage=pageDataObj},scope._getCurrentPage=function(){return!scope.currentPage&&scope.pagesArr.length>0?scope.currentPage=scope.pagesArr[0]:scope.currentPage||scope.pagesArr.length||(scope.pagesArr.push(scope._createPageObj(0)),scope.currentPage=scope.pagesArr[0]),scope.currentPage},scope._isFirstPage=function(){return 0===scope._getCurrentPage().value},scope._isLastPage=function(){return scope.currentPage.value===scope.pagesArr.length-1},scope._previousPage=function(){scope.currentPage=scope.pagesArr[scope.currentPage.value-1]},scope._nextPage=function(){scope.currentPage=scope.pagesArr[scope.currentPage.value+1]},scope._calcPagination=function(newValue){scope.pagesArr=[];var count=scope._getCountFromMeta(newValue);if(0==count)return scope.pagesArr.push(scope._createPageObj(0)),!1;scope._createPagesArr(scope._calcTotalPages(count,scope._getOptionFromParams("limit")))},scope._resetFilter=function(schemaDataObj){if(!schemaDataObj)return!1;scope.filter={viewBy:schemaDataObj.field[0].name||"",prop:schemaDataObj.field[0].name||"",type:schemaDataObj.field[0].type||"",props:schemaDataObj.field[0],value:null}},scope._isFiltered=function(){return scope.filteredRecords},scope._createFilterParams=function(){var param="";switch(scope.filter.prop.type){case"boolean":param=scope.filter.prop.name+" = "+scope.filter.value;break;case"text":case"string":param=scope.filter.prop.name+' like "%'+scope.filter.value+'%"';break;case"integer":case"float":case"double":case"decimal":param=scope.filter.prop.name+" "+scope.filterType.operator+" "+scope.filter.value}return param},scope._unsetFilterInOptions=function(){scope.options.params.hasOwnProperty("filter")&&delete scope.options.params.filter},scope._setFilterInOptions=function(){return!!scope._checkForFilterValue()&&(scope.options.params.hasOwnProperty("filter"),scope.options.params.filter=scope._createFilterParams(),!0)},scope._checkForFilterValue=function(){return!!scope.filter.value},scope._resetOrder=function(schemaDataObj){if(!schemaDataObj)return!1;scope.order={orderBy:schemaDataObj.field[0].name||"",orderByReverse:!1}},scope._isOrdered=function(){return scope.orderedRecords},scope._createOrderParams=function(){var orderStr=scope.order.orderBy+" ";return orderStr+=scope.order.orderByReverse?"DESC":"ASC"},scope._unsetOrderInOptions=function(){scope.options.params.hasOwnProperty("order")&&delete scope.options.params.order},scope._setOrderInOptions=function(){scope.options.params.hasOwnProperty("order"),scope.options.params.order=scope._createOrderParams()},scope._setChildTableActive=function(stateBool){scope.childTableActive=stateBool},scope._setChildTableParentRecord=function(recordObj){scope.childTableParentRecord=recordObj},scope._buildChildTableOptions=function(){scope.childTableOptions={isChildTable:!0,allowChildTable:!1},scope.childTableOptions=dfObjectService.deepMergeObjects(scope.childTableOptions,angular.copy(scope.defaults))},scope._addChildTable=function(){angular.element(scope.options.childTableAttachPoint).append($compile('')(scope))},scope._setTab=function(tabStr){scope._setElementActive(tabStr)},scope._toggleSelected=function(dataObj){scope._toggleSelectedState(dataObj)},scope._normalizeData=function(dataObj){return angular.forEach(dataObj,function(_obj){for(var _key in _obj)null==_obj[_key]&&(_obj[_key]="NULL")}),dataObj},scope._normalizeSchema=function(schemaDataObj,recordsDataArr){var normalizedSchema=[];for(var _key in schemaDataObj.field)recordsDataArr[0].hasOwnProperty(schemaDataObj.field[_key].name)&&normalizedSchema.push(schemaDataObj.field[_key]);return delete schemaDataObj.field,schemaDataObj.field=normalizedSchema,schemaDataObj},scope._getPrevious=function(){scope._previousPage()},scope._getNext=function(){scope._nextPage()},scope._editRecord=function(dataObj){scope._setCurrentEditRecord(dataObj)},scope._saveRecords=function(){scope._setInProgress(!0);var recordsToSave=scope._getRecordsWithState(scope.record,"unsaved",!0);scope._saveRecordsToServer(recordsToSave).then(function(result){angular.forEach(scope.record,function(_obj){scope._isUnsaved(_obj)&&scope._toggleUnsavedState(_obj),scope._isSelected(_obj)&&scope._toggleSelectedState(_obj),scope._hasRevertCopy(_obj)&&scope._removeRevertCopy(_obj)}),scope.$emit(scope.es.alertSuccess,{message:"Records saved."})},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._revertRecords=function(){angular.forEach(scope.record,function(_obj,_index){scope._isUnsaved(_obj)&&scope._hasRevertCopy(scope.record[_index])&&(scope.record[_index]=scope._getRevertCopy(_obj))}),scope.$emit(scope.es.alertSuccess,{message:"Records reverted."})},scope._deleteRecords=function(){var recordsToDelete=scope._getRecordsWithState(scope.record,"selected");scope._deleteRecordsFromServer(recordsToDelete).then(function(result){var requestDataObj={},curPage=scope._getCurrentPage().value,curOffset=scope._getCurrentPage().offset;scope._isLastPage()&&scope.record.length===scope._getRecordsFromData(result).length&&(curOffset-=scope._getOptionFromParams("limit")),requestDataObj.params=dfObjectService.mergeObjects({offset:curOffset},scope.options.params),scope._getRecordsFromServer(requestDataObj).then(function(_result){scope.$emit(scope.es.alertSuccess,{message:"Records deleted."}),scope._prepareRecords(_result),scope._createPagesArr(scope._calcTotalPages(scope._getCountFromMeta(_result),scope._getOptionFromParams("limit"))),curPage>scope.pagesArr.length-1&&0!==curPage&&(curPage-=1,scope.pagesArr[curPage].stopPropagation=!0),scope._setCurrentPage(scope.pagesArr[curPage])},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}})},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._getRecordsWithFilter=function(){var requestDataObj={};requestDataObj.params=dfObjectService.mergeObjects({filter:scope._createFilterParams()},scope.options.params),scope._setInProgress(!0),scope._getRecordsFromServer(requestDataObj).then(function(result){scope._init(dfObjectService.mergeObjects({data:result},scope.options))},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._refreshResults=function(checkUnsavedBool){if((checkUnsavedBool=checkUnsavedBool||!0)&&scope._checkForUnsavedRecords(scope.record)&&!confirm("You have Unsaved records. Continue without saving?"))return!1;var requestDataObj={};requestDataObj.params={offset:0},scope._setInProgress(!0),scope._getRecordsFromServer(requestDataObj).then(function(result){scope._prepareRecords(result),scope._calcPagination(result),scope._setCurrentPage(scope.pagesArr[0])},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._applyFilter=function(){if(scope._checkForUnsavedRecords(scope.record)&&!confirm("You have Unsaved records. Continue without saving?"))return!1;scope._setFilterInOptions()&&(scope.filteredRecords=!0),scope._setOrderInOptions(),scope.orderedRecords=!0;var requestDataObj={};requestDataObj.params={offset:0},scope._setInProgress(!0),scope._getRecordsFromServer(requestDataObj).then(function(result){scope._prepareRecords(result),scope._calcPagination(result),scope._setCurrentPage(scope.pagesArr[0])},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._removeFilter=function(){if(scope._checkForUnsavedRecords(scope.record)&&!confirm("You have Unsaved records. Continue without saving?"))return!1;scope._unsetFilterInOptions(),scope._unsetOrderInOptions(),scope._resetFilter(scope.schema),scope._resetOrder(scope.schema),scope.filteredRecords=!1,scope.orderedRecords=!1;var requestDataObj={};requestDataObj.params={offset:0},scope._setInProgress(!0),scope._getRecordsFromServer(requestDataObj).then(function(result){scope._prepareRecords(result),scope._calcPagination(result),scope._setCurrentPage(scope.pagesArr[0]),scope.filter.prop=scope.schema.field[0]},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope._createRecord=function(){scope._setNewRecordObj()},scope._setExportValue=function(dataObj){scope._setExportValueToParent(dataObj)},scope._toggleExpandEditor=function(){scope.relatedExpand=!scope.relatedExpand},scope._editExportRecord=function(dataObj){scope.options.exportValueOn&&scope.parentRecord&&(scope.relatedExpand?scope.relatedExpand&&!scope.currentEditRecord&&scope._setCurrentEditRecord(dataObj):(scope._setCurrentEditRecord(dataObj),scope._toggleExpandEditor()))},scope._filterRecords=function(){scope.filterOn=!scope.filterOn},scope._toggleAllFields=function(){scope.tableFieldsAll=!scope.tableFieldsAll,angular.forEach(scope.tableFields,function(_obj){"[object Object]"===Object.prototype.toString.call(_obj)&&_obj.hasOwnProperty("active")&&(_obj.active=scope.tableFieldsAll)})},scope._resetAllFields=function(){scope._createFieldsObj(scope.schema.field)},scope._toggleAllRecords=function(){scope.selectedAll=!scope.selectedAll,angular.forEach(scope.record,function(_obj){scope._setSelectedState(_obj,scope.selectedAll)})},scope._showChildTable=function(parentRecordObj){if(scope.childTableActive)return!1;scope._setChildTableActive(!0),scope._setChildTableParentRecord(parentRecordObj),scope._buildChildTableOptions(),scope._addChildTable(),scope._setDisableTableBtnsState(!0)};var watchUserOptions=scope.$watchCollection("userOptions",function(newValue,oldValue){if(!newValue)return!1;scope.options=dfObjectService.deepMergeObjects(newValue,scope.defaults),scope._setActiveView("table"),dfTableCallbacksService.reset()}),watchOptions=scope.$watchCollection("options",function(newValue,oldValue){if(!newValue)return!1;if(!newValue.service)return!1;if(scope.options.exportValueOn&&!scope._exportValue&&scope.parentRecord[scope.exportField.name]){var requestDataObj={};requestDataObj.params={filter:scope.exportField.ref_field+" = "+scope.parentRecord[scope.exportField.name]},scope._getRecordsFromServer(requestDataObj).then(function(result){var record=scope._getRecordsFromData(result)[0];scope._addStateProps(record),scope._exportValue=record,scope.options.params.filter&&delete scope.options.params.filter,newValue.data?(scope._init(newValue),scope._resetFilter(scope.schema),scope._resetOrder(scope.schema)):scope._getRecordsFromServer().then(function(_result){scope._init(_result),scope._resetFilter(scope.schema),scope._resetOrder(scope.schema)},function(_reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:_reject}})},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}})}else newValue.data?(scope._init(newValue),scope._resetFilter(scope.schema),scope._resetOrder(scope.schema)):(scope.options.params.offset=newValue.table!==oldValue.table?0:scope.options.params.offset,scope._getRecordsFromServer().then(function(_result){scope._init(_result),scope._resetFilter(scope.schema),scope._resetOrder(scope.schema)},function(_reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:_reject}}))}),watchCurrentPage=scope.$watch("currentPage",function(newValue,oldValue){if(newValue.value==oldValue.value)return!1;if(newValue.stopPropagation)return newValue.stopPropagation=!1,!1;if(scope._checkForUnsavedRecords(scope.record)&&!confirm("You have Unsaved records. Continue without saving?"))return oldValue.stopPropagation=!0,scope._setCurrentPage(oldValue),!1;var requestDataObj={};requestDataObj.params={offset:newValue.offset},scope._setInProgress(!0),scope._getRecordsFromServer(requestDataObj).then(function(result){scope._prepareRecords(result)},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})}),watchCurrentEditRecord=scope.$watch("currentEditRecord",function(newValue,oldValue){newValue?(scope._hasRevertCopy(newValue)||scope._createRevertCopy(newValue),scope._filterFormSchema("edit"),scope._buildSchemaGroups(),scope._checkForGroupedSchema("Edit "+scope.schema.name.charAt(0).toUpperCase()+scope.schema.name.slice(1)),scope._setActiveView("edit")):(scope._setActiveView("table"),scope._clearGroupedSchema(),scope._clearFilteredSchema())}),watchCurrentEditRecordState=scope.$watchCollection("currentEditRecord",function(newValue,oldValue){oldValue&&null==newValue&&scope._hasRevertCopy(oldValue)&&(scope._compareObjects(oldValue,oldValue.__dfData.revert)?scope._setUnsavedState(oldValue,!0):scope._setUnsavedState(oldValue,!1))}),watchParentRecord=scope.$watchCollection("parentRecord",function(newValue,oldValue){if(!newValue)return!1;if(!newValue&&!scope._exportValue)return!1;if(null==(!scope._exportValue&&newValue[scope.exportField.name]))return!1;if(!newValue[scope.exportField.name])return scope._exportValue=null,!1;if(!scope._exportValue&&newValue[scope.exportField.name]||scope._exportValue[scope.exportField.ref_field]!==newValue[scope.exportField.name]){var requestDataObj={};return requestDataObj.params={filter:scope.exportField.ref_field+" = "+newValue[scope.exportField.name],offset:0},scope._getRecordsFromServer(requestDataObj).then(function(result){var record=scope._getRecordsFromData(result);if(!record)throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:"Revert related data record not found."};scope._addStateProps(record[0]),scope._exportValue=record[0],scope.options.params.filter&&delete scope.options.params.filter},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}),!1}}),watchExportValue=scope.$watch("_exportValue",function(newValue,oldValue){if(!newValue&&!oldValue)return!1;if(!newValue&&oldValue){scope._setExportState(oldValue,!1);var found=!1,i=0;if(scope.record)for(;!found&&iscope.pagesArr.length-1&&0!==curPage&&(curPage-=1,scope.pagesArr[curPage].stopPropagation=!0),scope._setCurrentPage(scope.pagesArr[curPage]),scope._setCurrentEditRecord(null)},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}})},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})},scope._saveRecord=function(){scope._setInProgress(!0),dfTableCallbacksService.run("onUpdate","pre",scope.currentEditRecord),scope._saveRecordToServer(scope.currentEditRecord).then(function(result){scope._removeRevertCopy(scope.currentEditRecord),scope._setUnsavedState(scope.currentEditRecord,!1),dfTableCallbacksService.run("onUpdate","pre",result),scope.$emit(scope.es.alertSuccess,{message:"Record saved."}),scope.options.autoClose?scope._closeEdit():scope._createRevertCopy(scope.currentEditRecord)},function(reject){throw{module:"DreamFactory Table Module",type:"error",provider:"dreamfactory",exception:reject}}).finally(function(){scope._setInProgress(!1)},function(){scope._setInProgress(!1)})}}}}]).directive("createRecord",["DF_TABLE_ASSET_PATH","$http","dfTableEventService","dfTableCallbacksService",function(DF_TABLE_ASSET_PATH,$http,dfTableEventService,dfTableCallbacksService){return{restrict:"E",scope:!1,templateUrl:DF_TABLE_ASSET_PATH+"views/create-record.html",link:function(scope,elem,attrs){scope.es=dfTableEventService,scope.closeCreateRecord=function(){scope._closeCreateRecord()},scope.saveNewRecord=function(){scope._saveNewRecord()},scope._setCreateNewRecordNull=function(){scope.newRecord=null},scope._saveNewRecordToServer=function(){return $http({method:"POST",url:scope.options.url,data:{resource:[scope.newRecord]},params:{fields:"*"}})},scope._closeCreateRecord=function(){scope._setCreateNewRecordNull()},scope._saveNewRecord=function(){var dataField,schemaField;for(dataField in scope.newRecord)if(scope.newRecord.hasOwnProperty(dataField)&&null===scope.newRecord[dataField])for(schemaField in scope.tableFields)scope.tableFields.hasOwnProperty(schemaField)&&dataField===schemaField&&scope.tableFields[schemaField].hasOwnProperty("allow_null")&&!scope.tableFields[schemaField].allow_null&&scope.tableFields[schemaField].hasOwnProperty("auto_increment")&&scope.tableFields[schemaField].auto_increment&&delete scope.newRecord[dataField];scope._setInProgress(!0),dfTableCallbacksService.run("onCreate","pre",scope.newRecord),scope._saveNewRecordToServer().then(function(result){dfTableCallbacksService.run("onCreate","post",result),0===scope.record.length?scope._refreshResults():scope.record.length0&&(scope.field.hasOwnProperty("validation")&&null!==scope.field.validation&&scope.field.validation.hasOwnProperty("picklist")?scope.templateData.template="df-input-values-only-picklist.html":scope.templateData.template="df-input-values-picklist.html",scope.data=scope.field.picklist,scope.assignValue=function(itemStr){scope.currentEditRecord[scope.field.name]=itemStr});break;case"boolean":scope.templateData.template="df-input-bool-picklist.html",scope.__dfBools=[{value:!0,name:"TRUE"},{value:!1,name:"FALSE"}],scope.field.allow_null&&scope.__dfBools.unshift({value:"",name:"NULL"});break;case"reference":scope._parseSystemTableName=function(tableNameStr){return"df_sys_"===tableNameStr.substr(0,"df_sys_".length)?tableNameStr.substr("df_sys_".length):tableNameStr},scope._buildURL=function(serviceNameStr,tableNameStr){return INSTANCE_URL.url+"/"+serviceNameStr+"/_table/"+tableNameStr},scope.relatedOptions={service:scope.service,table:scope._parseSystemTableName(scope.field.ref_table),url:scope._buildURL(scope.service,scope._parseSystemTableName(scope.field.ref_table)),params:{filter:null,limit:10,offset:0,fields:"*",include_schema:!0,include_count:!0},defaultFields:{},exportValueOn:!0},scope.relatedOptions.defaultFields[scope.field.ref_field]=!0}elem.append($compile($templateCache.get(scope.templateData.template))(scope))}}}]).directive("dfChildTable",["DF_TABLE_ASSET_PATH","INSTANCE_URL","dfObjectService","dfTableEventService",function(DF_TABLE_ASSET_PATH,INSTANCE_URL,dfObjectService,dfTableEventService){return{restrict:"E",scope:{childOptions:"=",parentSchema:"=",childTableParentRecord:"="},templateUrl:DF_TABLE_ASSET_PATH+"views/df-child-table.html",link:function(scope,elem,attrs){scope.options={},scope.childRecordsBy="",scope.service=scope.childOptions.service,scope.closeChildTable=function(){scope._closeChildTable()},scope._parseSystemTableName=function(tableNameStr){return"df_sys_"===tableNameStr.substr(0,"df_sys_".length)?tableNameStr.substr("df_sys_".length):tableNameStr},scope._setSystemService=function(tableNameStr){return"df_sys_"===tableNameStr.substr(0,"df_sys_".length)?"system":scope.service},scope._closeChildTable=function(){scope.$emit(dfTableEventService.closeChildTable),angular.element(elem).remove()};var watchChildRecordsBy=scope.$watch("childRecordsBy",function(newValue,oldValue){if(!newValue)return!1;var options={service:scope._setSystemService(newValue.ref_table),table:newValue.ref_table,url:INSTANCE_URL.url+"/"+scope._setSystemService(newValue.ref_table)+"/_table/"+scope._parseSystemTableName(newValue.ref_table),params:{filter:newValue.ref_field+" = "+scope.childTableParentRecord[newValue.field]}};scope.options=dfObjectService.deepMergeObjects(options,scope.childOptions)});scope.$on("$destroy",function(e){watchChildRecordsBy()})}}}]).service("dfTableEventService",[function(){return{alertSuccess:"alert:success",refreshTable:"refresh:table",closeChildTable:"close:childtable"}}]).service("dfTableCallbacksService",[function(){var callbacks={onCreate:{pre:[],post:[]},onDelete:{pre:[],post:[]},onUpdate:{pre:[],post:[]}};return{add:function(actionStr,processStr,method){callbacks[actionStr][processStr].push(method)},run:function(actionStr,processStr,inputRecord){if(0==callbacks[actionStr][processStr].length)return!1;angular.forEach(callbacks[actionStr][processStr],function(value,index){value.call(void 0,inputRecord)})},reset:function(){callbacks={onCreate:{pre:[],post:[]},onDelete:{pre:[],post:[]},onUpdate:{pre:[],post:[]}}}}}]),angular.module("dfHome",["ngRoute","dfUtility","dfApplication","dfHelp"]).constant("MOD_HOME_ROUTER_PATH","/home").constant("MOD_HOME_ASSET_PATH","admin_components/adf-home/").config(["$routeProvider","MOD_HOME_ROUTER_PATH","MOD_HOME_ASSET_PATH",function($routeProvider,MOD_HOME_ROUTER_PATH,MOD_HOME_ASSET_PATH){$routeProvider.when(MOD_HOME_ROUTER_PATH,{templateUrl:MOD_HOME_ASSET_PATH+"views/main.html",controller:"HomeCtrl",resolve:{checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("HomeCtrl",["$q","$scope","$sce","dfApplicationData","SystemConfigDataService",function($q,$scope,$sce,dfApplicationData,SystemConfigDataService){$scope.trustUrl=function(url){return $sce.trustAsResourceUrl(url)},$scope.$parent.title="Home",$scope.$parent.titleIcon="home";var links=[{name:"welcome-home",label:"Welcome",template:"admin_components/adf-home/views/welcome.html",attributes:[]},{name:"quickstart-home",label:"Quickstart",template:"admin_components/adf-home/views/quickstart.html",attributes:[]},{name:"resource-home",label:"Resources",template:"admin_components/adf-home/views/resources.html",attributes:[]},{name:"download-home",label:"Download",template:"admin_components/adf-home/views/download.html",attributes:[]}],systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.hasOwnProperty("home_links")&&(links=angular.copy(systemConfig.home_links)),$scope.links=links,angular.forEach($scope.links,function(link){link.label||(link.label=link.name)})}]),angular.module("dfLimit",["ngRoute","dfUtility"]).constant("MOD_LIMIT_ROUTER_PATH","/limits").constant("MOD_LIMIT_ASSET_PATH","admin_components/adf-limit/").config(["$routeProvider","MOD_LIMIT_ROUTER_PATH","MOD_LIMIT_ASSET_PATH",function($routeProvider,MOD_LIMIT_ROUTER_PATH,MOD_LIMIT_ASSET_PATH){$routeProvider.when(MOD_LIMIT_ROUTER_PATH,{templateUrl:MOD_LIMIT_ASSET_PATH+"views/main.html",controller:"LimitCtl",resolve:{checkAdmin:["checkAdminService",function(checkAdminService){return checkAdminService.checkAdmin()}],checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).factory("editLimitService",[function(){return{record:{},recordCopy:{}}}]).controller("LimitCtl",["$rootScope","$scope","$http","dfApplicationData","dfNotify","dfObjectService","$location",function($rootScope,$scope,$http,dfApplicationData,dfNotify,dfObjectService,$location){$scope.$parent.title="Limits",$scope.$parent.titleIcon="minus-circle",$scope.links=[{name:"manage-limits",label:"Manage",path:"manage-limits"},{name:"create-limit",label:"Create",path:"create-limit"}],$scope.instanceTypes=[{value:"instance",name:"Instance"},{value:"instance.user",name:"User"},{value:"instance.each_user",name:"Each User"},{value:"instance.service",name:"Service"},{value:"instance.role",name:"Role"},{value:"instance.user.service",name:"Service by User"},{value:"instance.each_user.service",name:"Service by Each User"},{value:"instance.service.endpoint",name:"Endpoint"},{value:"instance.user.service.endpoint",name:"Endpoint by User"},{value:"instance.each_user.service.endpoint",name:"Endpoint by Each User"}],$scope.limitPeriods=[{value:"minute",name:"Minute"},{value:"hour",name:"Hour"},{value:"day",name:"Day"},{value:"7-day",name:"Week"},{value:"30-day",name:"30 Days"}],$scope.emptySectionOptions={title:"You have no Limits!",text:"Click the button below to get started adding limits. You can always create new limits by clicking the tab located in the section menu to the left.",buttonText:"Create A Limit!",viewLink:$scope.links[1],active:!1},$scope.hidden={users:!0,roles:!0,services:!0,endpoint:!0},$scope.selectType=function(recordType){if(angular.isObject(recordType))switch(recordType.value){case"instance":$scope.hidden={users:!0,roles:!0,services:!0,endpoint:!0};break;case"instance.user":$scope.hidden={users:!1,roles:!0,services:!0,endpoint:!0};break;case"instance.each_user":$scope.hidden={users:!0,roles:!0,services:!0,endpoint:!0};break;case"instance.service":$scope.hidden={users:!0,roles:!0,services:!1,endpoint:!0};break;case"instance.role":$scope.hidden={users:!0,roles:!1,services:!0,endpoint:!0};break;case"instance.user.service":$scope.hidden={users:!1,roles:!0,services:!1,endpoint:!0};break;case"instance.each_user.service":$scope.hidden={users:!0,roles:!0,services:!1,endpoint:!0};break;case"instance.service.endpoint":$scope.hidden={users:!0,roles:!0,services:!1,endpoint:!1};break;case"instance.user.service.endpoint":$scope.hidden={users:!1,roles:!0,services:!1,endpoint:!1};break;case"instance.each_user.service.endpoint":$scope.hidden={users:!0,roles:!0,services:!1,endpoint:!1}}},$scope.$on("$destroy",function(e){$scope.$broadcast("toolbar:paginate:limit:destroy")}),$scope.limitEnabled=!1,$scope.subscription_required=!1,$scope.apiData=null,$scope.loadTabData=function(init){$scope.dataLoading=!0;var apis,newApiData,errorFunc=function(error){var messageOptions={module:"Limits",provider:"dreamfactory",type:"error",message:"There was an error loading data for the Limits tab. Please try refreshing your browser and logging in again."};$location.url("/home"),dfNotify.error(messageOptions)};dfApplicationData.getApiData(["system"]).then(function(response){angular.forEach(response[0].resource,function(value){"limit"===value.name&&($scope.limitEnabled=!0)}),$scope.limitEnabled?(apis=["limit","role","service","user"],dfApplicationData.getApiData(apis).then(function(response){newApiData={},apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData,init&&$scope.$broadcast("toolbar:paginate:limit:load")},errorFunc)):($scope.subscription_required=!0,$scope.links[1].path=$scope.links[0].path)},errorFunc).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(!0)}]).directive("dfManageLimits",["$rootScope","MOD_LIMIT_ASSET_PATH","dfApplicationData","dfNotify","$timeout","editLimitService","$http","INSTANCE_URL",function($rootScope,MOD_LIMIT_ASSET_PATH,dfApplicationData,dfNotify,$timeout,editLimitService,$http,INSTANCE_URL){return{restrict:"E",scope:!1,templateUrl:MOD_LIMIT_ASSET_PATH+"views/df-manage-limits.html",link:function(scope,elem,attrs){var ManagedLimit=function(limitData){return{__dfUI:{selected:!1},record:limitData,recordCopy:limitData}};scope.limits=null,scope.currentEditLimit=editLimitService,scope.fields=[{name:"id",label:"ID",active:!0},{name:"name",label:"Limit Name",active:!0},{name:"type",label:"Limit Type",active:!0},{name:"rate",label:"Limit Rate",active:!0},{name:"percent",label:"Limit Counter",active:!0},{name:"user_id",label:"User",active:!0},{name:"service_id",label:"Service",active:!0},{name:"role_id",label:"Role",active:!0},{name:"active",label:"Active",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedLimits=[],scope.editLimit=function(limit){scope._editLimit(limit)},scope.deleteLimit=function(limit){dfNotify.confirm("Delete "+limit.record.name+"?")&&(scope._deleteLimit(limit),scope.selectAll(!1))},scope.resetCounter=function(limit){dfNotify.confirm("Clear counter for "+limit.record.name+"?")&&scope._deleteLimitCache(limit)},scope.deleteSelectedLimits=function(){dfNotify.confirm("Delete selected limits?")&&scope._deleteSelectedLimits()},scope.resetSelectedLimits=function(){dfNotify.confirm("Reset selected limits?")&&scope._resetSelectedLimits()},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setSelected=function(limit){scope._setSelected(limit)},scope.selectAll=function(checkStatus){scope.selectedLimits.length&&!1===checkStatus&&(scope.selectedLimits=[]),angular.forEach(scope.limits,function(limit){!1===checkStatus?(limit.__dfUI.selected=!1,scope.selectedLimits.splice(limit.record.id,1)):(limit.__dfUI.selected=!0,scope.selectedLimits.push(limit.record.id))})},scope._deleteCacheFromServer=function(requestDataObj){return $http({method:"DELETE",url:INSTANCE_URL.url+"/system/limit_cache",params:requestDataObj.params})},scope._editLimit=function(limit){angular.copy(limit,scope.currentEditLimit);var limitType=limit.record.type,limitPeriod=limit.record.period,userId=limit.record.user_id;scope.currentEditLimit.record.typeObj=scope.instanceTypes.filter(function(obj){return obj.value==limitType})[0],scope.currentEditLimit.recordCopy.typeObj=scope.currentEditLimit.record.typeObj,scope.currentEditLimit.record.periodObj=scope.limitPeriods.filter(function(obj){return obj.value==limitPeriod})[0],scope.currentEditLimit.recordCopy.periodObj=scope.currentEditLimit.record.periodObj,angular.isObject(scope.users)&&(scope.currentEditLimit.record.user_id=scope.users.filter(function(obj){return obj.id==userId})[0],scope.currentEditLimit.recordCopy.user_id=scope.currentEditLimit.record.user_id),scope.selectType(scope.currentEditLimit.record.typeObj)},scope._deleteLimitCache=function(limit){var requestDataObj={params:{ids:limit.record.id}};scope._deleteCacheFromServer(requestDataObj).then(function(result){var messageOptions={module:"Limits",type:"success",provider:"dreamfactory",message:"Limit counter successfully reset."};angular.forEach(limit.record.limit_cache_by_limit_id,function(cache){cache.attempts=0,cache.percent=0}),dfNotify.success(messageOptions)},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._deleteLimit=function(limit){var requestDataObj={params:{id:limit.record.id}};dfApplicationData.deleteApiData("limit",requestDataObj).$promise.then(function(result){var messageOptions={module:"Limits",type:"success",provider:"dreamfactory",message:"Limit successfully deleted."};dfNotify.success(messageOptions),limit.__dfUI.selected&&scope.setSelected(limit),scope.$broadcast("toolbar:paginate:limit:delete")},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)},scope._setSelected=function(limit){for(var i=0;i"}}]).directive("dfLimitDetails",["MOD_LIMIT_ASSET_PATH","dfApplicationData","dfNotify","dfObjectService","$http","$cookies","UserDataService","$rootScope","editLimitService",function(MOD_LIMIT_ASSET_PATH,dfApplicationData,dfNotify,dfObjectService,$http,$cookies,UserDataService,$rootScope,editLimitService){return{restrict:"E",scope:{limitData:"=?",newLimit:"=newLimit",selectType:"=?",activeView:"=?",apiData:"=?"},templateUrl:MOD_LIMIT_ASSET_PATH+"views/df-limit-details.html",link:function(scope,elem,attrs){var Limit=function(limitData){var _limit={is_active:!0,key_text:null,description:null,name:null,period:null,rate:null,role_id:null,service_id:null,type:null,endpoint:null,user_id:null,cacheData:{}};return limitData=limitData||_limit,{__dfUI:{selected:!1},record:angular.copy(limitData),recordCopy:angular.copy(limitData)}};scope.limit=null,scope.saveData={},scope.currentEditLimit=editLimitService,scope.newLimit&&(scope.currentEditLimit=new Limit),scope.verbs=["GET","POST","PATCH","PUT","DELETE"],scope.dfSimpleHelp={verb:{title:"Limit by Verb ",text:"By default, all verbs will be limited unless a specific verb is selected for the limit type."},endpoint:{title:"Endpoint Limits ",text:'Endpoint limits are combined with a service and follow the same conventions in the API Docs for endpoints. The endpoint created must follow a simple form, such as with db service, "_schema/{table_name}". Anything more detailed will still filter at the table level.'}},scope.saveLimit=function(){scope._validateData()&&(scope.newLimit?scope._saveLimit():scope._updateLimit())},scope.cancelEditor=function(){(dfObjectService.compareObjectsAsJson(scope.currentEditLimit.record,scope.currentEditLimit.recordCopy)||dfNotify.confirmNoSave())&&scope.closeEditor()},scope.closeEditor=function(){scope.currentEditLimit.record={},scope.limit=new Limit,scope.$emit("sidebar-nav:view:reset")},scope._validateData=function(){var checkData=scope.currentEditLimit.record;if(null==checkData.typeObj){options={module:"Limit Create Error",message:"Please select a limit type.",type:"error"};return dfNotify.error(options),!1}if(null===checkData.name||""==checkData.name){options={module:"Limit Create Error",message:"The limit name cannot be blank.",type:"error"};return dfNotify.error(options),!1}if(!angular.isDefined(checkData.typeObj)){options={module:"Limit Create Error",message:"A Limit type must be selected.",type:"error"};return dfNotify.error(options),!1}if(null===checkData.rate||""==checkData.rate){options={module:"Limit Create Error",message:"The limit rate cannot be blank.",type:"error"};return dfNotify.error(options),!1}if(!/^\d+$/.test(checkData.rate)){var options={module:"Limit Create Error",message:"The limit rate must be an integer.",type:"error"};return dfNotify.error(options),!1}return!0},scope._saveLimit=function(){if(scope.saveData=scope._prepareLimitData(),!scope.saveData)return!1;var requestDataObj={params:{fields:"*",related:"service_by_service_id,role_by_role_id,user_by_user_id,limit_cache_by_limit_id"},data:scope.saveData};dfApplicationData.saveApiData("limit",requestDataObj).$promise.then(function(result){var messageOptions={module:"Limits",provider:"dreamfactory",type:"success",message:"Limit saved successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._updateLimit=function(){scope.saveData=scope._prepareLimitData();var requestDataObj={params:{fields:"*",related:"service_by_service_id,role_by_role_id,user_by_user_id,limit_cache_by_limit_id"},data:scope.saveData};dfApplicationData.updateApiData("limit",requestDataObj).$promise.then(function(result){var messageOptions={module:"Limit",provider:"dreamfactory",type:"success",message:"Limit updated successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var messageOptions={module:"Api Error",provider:"dreamfactory",type:"error",message:reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._prepareLimitData=function(){var saveData=angular.copy(scope.currentEditLimit.record);angular.isObject(saveData.periodObj)&&(saveData.period=saveData.periodObj.value),angular.isObject(saveData.typeObj)&&(saveData.type=saveData.typeObj.value),angular.isObject(saveData.user_by_user_id)&&(saveData.user_id=saveData.user_by_user_id.id),angular.isObject(saveData.role_by_role_id)&&(saveData.role_id=saveData.role_by_role_id.id),angular.isObject(saveData.service_by_service_id)&&(saveData.service_id=saveData.service_by_service_id.id);var endpointTypes=["instance.service.endpoint","instance.user.service.endpoint","instance.each_user.service.endpoint"];return saveData.endpoint&&-1!==endpointTypes.indexOf(saveData.type)||(saveData.endpoint=null),delete saveData.key_text,delete saveData.periodObj,delete saveData.typeObj,delete saveData.user_by_user_id,delete saveData.role_by_role_id,delete saveData.service_by_service_id,delete saveData.limit_cache_by_limit_id,saveData};var watchLimitData=scope.$watch("limitData",function(newValue,oldValue){if(!newValue)return!1;scope.limit=new Limit(newValue)});scope.$on("$destroy",function(e){scope.currentEditLimit.record={},scope.limit=new Limit,watchLimitData()}),scope.dfHelp={}}}}]),angular.module("dfLicenseExpiredBanner",["dfApplication"]).directive("dfLicenseExpiredBanner",["SystemConfigDataService","LicenseDataService",function(SystemConfigDataService,LicenseDataService){return{restrict:"E",templateUrl:"admin_components/adf-license-expired/license-expiry-banner/license-expiry-banner.html",link:function(scope){function updateSubscriptionData(platform){platform&&platform.hasOwnProperty("license")&&LicenseDataService.isLicenseRequiredSubscription(platform.license)?LicenseDataService.getSubscriptionData().then(function(data){scope.subscriptionData=data}):scope.subscriptionData={}}scope.subscriptionData={},scope.hasLicenseExpired=function(){return 401==scope.subscriptionData.status_code},scope.$watch(function(){return SystemConfigDataService.getSystemConfig().platform},function(platform){updateSubscriptionData(platform)})}}}]),angular.module("dfLicenseExpired",["ngRoute"]).config(["$routeProvider",setLicenseExpiredRoute]),angular.module("dfReports",["ngRoute","dfUtility","dfApplication","dfHelp"]).constant("MOD_REPORT_ROUTER_PATH","/reports").constant("MOD_REPORT_ASSET_PATH","admin_components/adf-reports/").config(["$routeProvider","MOD_REPORT_ROUTER_PATH","MOD_REPORT_ASSET_PATH",function($routeProvider,MOD_REPORT_ROUTER_PATH,MOD_REPORT_ASSET_PATH){$routeProvider.when(MOD_REPORT_ROUTER_PATH,{templateUrl:MOD_REPORT_ASSET_PATH+"views/main.html",controller:"ReportsCtrl",resolve:{checkAdmin:["checkAdminService",function(checkAdminService){return checkAdminService.checkAdmin()}],checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("ReportsCtrl",["$rootScope","$scope","dfApplicationData","dfNotify","$location",function($rootScope,$scope,dfApplicationData,dfNotify,$location){$scope.$parent.title="Reports",$scope.links=[{name:"manage-service-reports",label:"Manage service reports",path:"manage-service-reports"}],$scope.emptySearchResult={title:"You have no Reports that match your search criteria!",text:""},$scope.dfLargeHelp={manageReports:{title:"Manage Service Reports",text:"Service reports tell you when each service was created, modified, and deleted."}},$scope.apiData=null,$scope.loadTabData=function(init){$scope.dataLoading=!0;var errorFunc=function(error){var messageOptions={module:"Reports",provider:"dreamfactory",type:"error",message:"To use the Reports tab you must be Root Admin and have GOLD license."};$location.url("/home"),dfNotify.warn(messageOptions)};dfApplicationData.getApiData(["system"]).then(function(response){if(angular.forEach(response[0].resource,function(value){"service_report"===value.name&&($scope.reportsEnabled=!0)}),$scope.reportsEnabled){var apis=["service_report"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData,init&&$scope.$broadcast("toolbar:paginate:service_report:load")},errorFunc)}else $scope.subscription_required=!0},function(error){var messageOptions={module:"Reports",provider:"dreamfactory",type:"error",message:"There was an error loading data for the Reports tab. Please try refreshing your browser and logging in again."};$location.url("/home"),dfNotify.error(messageOptions)}).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(!0)}]).directive("dfManageServiceReports",["$rootScope","MOD_REPORT_ASSET_PATH","dfApplicationData","dfNotify","$location",function($rootScope,MOD_REPORT_ASSET_PATH,dfApplicationData,dfNotify,$location){return{restrict:"E",scope:!1,templateUrl:MOD_REPORT_ASSET_PATH+"views/df-manage-service-reports.html",link:function(scope,elem,attrs){var ManagedServiceReport=function(serviceReportData){return{__dfUI:{selected:!1},record:serviceReportData}};scope.serviceReports=null,scope.fields=[{name:"id",label:"ID",active:!0},{name:"time",label:"Time",active:!0},{name:"service_id",label:"Service Id",active:!0},{name:"service_name",label:"Service Name",active:!0},{name:"user_email",label:"User Email",active:!0},{name:"action",label:"Action",active:!0},{name:"request_method",label:"Request",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedReports=[],scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope._orderOnSelect=function(fieldObj){scope.order.orderBy===fieldObj.name?scope.order.orderByReverse=!scope.order.orderByReverse:(scope.order.orderBy=fieldObj.name,scope.order.orderByReverse=!1)};var watchApiData=scope.$watchCollection(function(){return dfApplicationData.getApiDataFromCache("service_report")},function(newValue,oldValue){var _serviceReports=[];newValue&&angular.forEach(newValue,function(serviceReport){_serviceReports.push(new ManagedServiceReport(serviceReport))}),scope.serviceReports=_serviceReports});scope.$on("$destroy",function(e){watchApiData(),scope.$broadcast("toolbar:paginate:service_report:reset")})}}}]).directive("dfReportsLoading",[function(){return{restrict:"E",template:"
"}}]),angular.module("dfScheduler",["ngRoute","dfUtility"]).constant("MOD_SCHEDULER_ROUTER_PATH","/scheduler").constant("MOD_SCHEDULER_ASSET_PATH","admin_components/adf-scheduler/").config(["$routeProvider","MOD_SCHEDULER_ROUTER_PATH","MOD_SCHEDULER_ASSET_PATH",function($routeProvider,MOD_SCHEDULER_ROUTER_PATH,MOD_SCHEDULER_ASSET_PATH){$routeProvider.when(MOD_SCHEDULER_ROUTER_PATH,{templateUrl:MOD_SCHEDULER_ASSET_PATH+"views/main.html",controller:"SchedulerCtrl",resolve:{checkAdmin:["checkAdminService",function(checkAdminService){return checkAdminService.checkAdmin()}],checkUser:["checkUserService",function(checkUserService){return checkUserService.checkUser()}]}})}]).run([function(){}]).controller("SchedulerCtrl",["$rootScope","$scope","dfApplicationData","dfNotify","$location",function($rootScope,$scope,dfApplicationData,dfNotify,$location){$scope.$parent.title="Scheduler",$scope.$parent.titleIcon="clock-o",$scope.links=[{name:"manage-tasks",label:"Manage",path:"manage-tasks"},{name:"create-task",label:"Create",path:"create-task"}],$scope.emptySectionOptions={title:"You have no Scheduler Tasks!",text:'Click the button below to get started building your first Scheduler Task. You can always create new tasks by clicking the "Create" tab located in the section menu to the left.',buttonText:"Create A Scheduler Task!",viewLink:$scope.links[1]},$scope.$on("$destroy",function(e){$scope.$broadcast("toolbar:paginate:scheduler:destroy")}),$scope.schedulerEnabled=!1,$scope.subscription_required=!1,$scope.apiData=null,$scope.loadTabData=function(init){$scope.dataLoading=!0;var errorFunc=function(error){var msg="There was an error loading data for the Scheduler tab. Please try refreshing your browser and logging in again.";error&&error.error&&(401===error.error.code||403===error.error.code)&&(msg="To use the Scheduler tab your role must allow GET access to system/scheduler. To create, update, or delete scheduled tasks you need POST, PUT, DELETE access to /system/scheduler and/or /system/scheduler/*.",$location.url("/home"));var messageOptions={module:"Scheduler",provider:"dreamfactory",type:"error",message:msg};dfNotify.error(messageOptions)};dfApplicationData.getApiData(["system"]).then(function(response){if(angular.forEach(response[0].resource,function(value){"scheduler"===value.name&&($scope.schedulerEnabled=!0)}),$scope.schedulerEnabled){var apis=["scheduler","service_list"];dfApplicationData.getApiData(apis).then(function(response){var newApiData={};apis.forEach(function(value,index){newApiData[value]=response[index].resource?response[index].resource:response[index]}),$scope.apiData=newApiData,$scope.services=newApiData.service_list,init&&$scope.$broadcast("toolbar:paginate:scheduler:load")},errorFunc)}else $scope.subscription_required=!0,$scope.links[1].path=$scope.links[0].path},errorFunc).finally(function(){$scope.dataLoading=!1})},$scope.loadTabData(!0)}]).directive("dfManageTasks",["$rootScope","MOD_SCHEDULER_ASSET_PATH","dfApplicationData","dfNotify",function($rootScope,MOD_SCHEDULER_ASSET_PATH,dfApplicationData,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_SCHEDULER_ASSET_PATH+"views/df-manage-tasks.html",link:function(scope,elem,attrs){$rootScope.schedulerEnabled&&angular.forEach(scope.apiData.service_list,function(svc){svc.components||(svc.components=["","*"])});var ManagedTask=function(taskData){return taskData.service_name=scope._getService(taskData.service_id).name,taskData.service=scope._getService(taskData.service_id),taskData.frequency=parseInt(taskData.frequency),taskData.hasOwnProperty("task_log_by_task_id")&&taskData.task_log_by_task_id?taskData.has_log=!0:taskData.has_log=!1,{__dfUI:{selected:!1},record:taskData}};scope.tasks=null,scope.currentEditTask=null,scope.fields=[{name:"id",label:"Id",active:!0},{name:"name",label:"Name",active:!0},{name:"description",label:"Description",active:!0},{name:"is_active",label:"Active",active:!0},{name:"service_name",label:"Service",active:!0},{name:"component",label:"Component",active:!0},{name:"verb",label:"Method",active:!0},{name:"frequency",label:"Frequency",active:!0},{name:"has_log",label:"Log",active:!0}],scope.order={orderBy:"id",orderByReverse:!1},scope.selectedTasks=[],scope.editTask=function(task){scope._editTask(task)},scope.deleteTask=function(task){dfNotify.confirm("Delete "+task.record.name+"?")&&scope._deleteTask(task)},scope.deleteSelectedTasks=function(){dfNotify.confirm("Delete selected tasks?")&&scope._deleteSelectedTasks()},scope.orderOnSelect=function(fieldObj){scope._orderOnSelect(fieldObj)},scope.setSelected=function(task){scope._setSelected(task)},scope._editTask=function(task){scope.currentEditTask=task},scope._getService=function(serviceId){for(var i=0;i"}}]).directive("dfTaskDetails",["MOD_SCHEDULER_ASSET_PATH","dfApplicationData","dfNotify","dfObjectService","$timeout",function(MOD_SCHEDULER_ASSET_PATH,dfApplicationData,dfNotify,dfObjectService,$timeout){return{restrict:"E",scope:{taskData:"=?",newTask:"=?",apiData:"=?"},templateUrl:MOD_SCHEDULER_ASSET_PATH+"views/df-task-details.html",link:function(scope,elem,attrs){var Task=function(taskData){var newTask={name:null,description:null,is_active:!0,service_id:null,component:null,id:null,verb_mask:1,verb:"GET",frequency:1};return taskData=taskData||newTask,{__dfUI:{selected:!1},record:angular.copy(taskData),recordCopy:angular.copy(taskData)}};scope.basicInfoError=!1,scope.task=null,scope.isBasicTab=!0,scope.taskErrorEditorObj={editor:null},scope.newTask&&(scope.task=new Task),scope.saveTask=function(){scope.newTask?scope._saveTask():scope._updateTask()},scope.deleteTask=function(){scope._deleteTask()},scope.cancelEditor=function(){scope._prepareTaskData(),(dfObjectService.compareObjectsAsJson(scope.task.record,scope.task.recordCopy)||dfNotify.confirmNoSave())&&scope.closeEditor()},scope._prepareTaskData=function(){if(scope.task.record.name)if(scope.basicInfoError=!1,scope.task.record.service_id&&scope.task.record.service)scope.prepareTaskPayload();else{scope.noServiceIdError=!0;var messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:"Service is required."};dfNotify.error(messageOptions)}else scope.basicInfoError=!0},scope.prepareTaskPayload=function(){"GET"!==scope.task.record.verb?scope.task.record.payload=scope.taskPayloadEditorObj.editor.getValue():scope.task.record.payload=null},scope.refreshTaskEditor=function($event){scope.isBasicTab="basic-tab"===$event.target.id},scope.refreshTaskConfigEditor=function(){$timeout(function(){angular.element("#config-tab").trigger("click")})},scope.closeEditor=function(){scope.taskData=null,scope.task=new Task,$timeout(function(){angular.element("#basic-tab").trigger("click")}),scope.basicInfoError=!1,scope.$emit("sidebar-nav:view:reset")},scope._saveTask=function(){scope._prepareTaskData();var requestDataObj={params:{fields:"*"},data:scope.task.record};dfApplicationData.saveApiData("scheduler",requestDataObj).$promise.then(function(result){var messageOptions={module:"Scheduler",type:"success",provider:"dreamfactory",message:"Scheduler task saved successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var msg=reject.data.message,messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._updateTask=function(){scope._prepareTaskData();var requestDataObj={params:{fields:"*"},data:scope.task.record};dfApplicationData.updateApiData("scheduler",requestDataObj).$promise.then(function(result){scope.task=new Task(result);var messageOptions={module:"Scheduler",type:"success",provider:"dreamfactory",message:"Scheduler task updated successfully."};dfNotify.success(messageOptions),scope.closeEditor()},function(reject){var msg=reject.data.message,messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})},scope._deleteTask=function(){var requestDataObj={params:{},data:scope.task.record};dfApplicationData.deleteApiData("scheduler",requestDataObj).$promise.then(function(result){var messageOptions={module:"Scheduler",type:"success",provider:"dreamfactory",message:"Scheduler task successfully deleted."};dfNotify.success(messageOptions),scope.task=null},function(reject){var msg=reject.data.message,messageOptions={module:"Api Error",type:"error",provider:"dreamfactory",message:msg||reject};dfNotify.error(messageOptions)}).finally(function(){})};var watchTaskData=scope.$watch("taskData",function(newValue,oldValue){newValue&&!scope.newTask&&(scope.task=new Task(newValue))}),watchServiceData=scope.$watchCollection("apiData.service_list",function(newValue,oldValue){newValue&&(scope.services=angular.copy(newValue),angular.forEach(scope.services,function(svc){svc.components||(svc.components=["","*"])}))});scope.$on("$destroy",function(e){watchTaskData(),watchServiceData()}),scope.dfSimpleHelp={taskConfig:{title:"Scheduler Task Config",text:"Create or update Scheduler tasks configs for DreamFactory."}},scope.dfLargeHelp={basic:{title:"Scheduler Task Overview",text:"Scheduler task provide a way to schedule requests to the platform."},config:{title:"Scheduler Task Config",text:"Use this interface to configure scheduled calls for an API endpoint."},log:{title:"Scheduler Task Log",text:"This interface displays the scheduler task error log."}}}}}]).directive("schedulerTaskConfig",["MOD_SCHEDULER_ASSET_PATH","INSTANCE_URL","$http","dfNotify",function(MOD_SCHEDULER_ASSET_PATH,INSTANCE_URL,$http,dfNotify){return{restrict:"E",scope:!1,templateUrl:MOD_SCHEDULER_ASSET_PATH+"views/df-task-config.html",link:function(scope,elem,attrs){scope.verbs={GET:{name:"GET",active:!1,description:" (read)",mask:1},POST:{name:"POST",active:!1,description:" (create)",mask:2},PUT:{name:"PUT",active:!1,description:" (replace)",mask:4},PATCH:{name:"PATCH",active:!1,description:" (update)",mask:8},DELETE:{name:"DELETE",active:!1,description:" (remove)",mask:16}},scope.taskPayloadEditorObj={editor:null},scope.taskPayloadUpdateCounter=0,scope._toggleVerbState=function(nameStr,event){void 0!==event&&event.stopPropagation(),scope.task.record.verb_mask=scope.verbs[nameStr].mask,scope.task.record.verb=nameStr,scope.task.record.payload=scope.taskPayloadEditorObj.editor.getValue(),document.getElementById("task_verb_picker").click()},scope._getComponents=function(){var name=scope.task.record.service.name;return $http.get(INSTANCE_URL.url+"/"+name+"/?as_access_list=true")};var watchTaskService=scope.$watch("task.record.service",function(newValue,oldValue){if(!newValue&&!scope.task)return!1;if(!newValue)return scope.task.record.service_id=null,void(scope.task.record.service_name=null);scope.task.record.service_id=newValue.id,scope.task.record.service_name=newValue.name;var components=["","*"];scope._getComponents().then(function(result){components=result.data.resource,scope.task.__dfUI.hasError=!1},function(reject){scope.task.__dfUI.hasError=!0,scope.task.record.component=null;var messageOptions={module:"Scheduler",type:"error",provider:"dreamfactory",message:reject};dfNotify.error(messageOptions)}).finally(function(){scope.task.record.service.components=components})}),watchServiceData=scope.$watchCollection("apiData.service_list",function(newValue,oldValue){newValue&&(scope.services=angular.copy(newValue),angular.forEach(scope.services,function(svc){svc.components||(svc.components=["","*"])}))});scope.$on("$destroy",function(newValue,oldValue){watchTaskService(),watchServiceData()})}}}]),angular.module("dreamfactoryApp",["ngAnimate","ngCookies","ngResource","ngRoute","ngSanitize","ngTouch","dfUtility","dfHome","dfSystemConfig","dfAdmins","dfUsers","dfApps","dfData","dfServices","dfRoles","dfSchema","dfUserManagement","dfScripts","dfProfile","dfApplication","dfHelp","dfLaunchPad","dfApiDocs","dfFileManager","dfPackageManager","dfLimit","dfLicenseExpired","dfLicenseExpiredBanner","dfLimit","dfReports","dfScheduler"]).factory("checkUserService",function($location,$q,SystemConfigDataService){return{checkUser:function(){var deferred=$q.defer(),systemConfig=SystemConfigDataService.getSystemConfig(),result=!1;return systemConfig&&(result=systemConfig.apps&&systemConfig.apps.filter(function(item){return"admin"===item.name}).length>0),result?deferred.resolve():($location.url("/launchpad"),deferred.reject()),deferred.promise}}}).factory("checkAdminService",function($q,UserDataService,$location){return{checkAdmin:function(){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();return currentUser&¤tUser.is_sys_admin?deferred.resolve():($location.url("/launchpad"),deferred.reject()),deferred.promise}}}).factory("allowAdminAccess",function(SystemConfigDataService){return{get:function(){var result=!1,systemConfig=SystemConfigDataService.getSystemConfig();return systemConfig&&(result=systemConfig.apps&&systemConfig.apps.filter(function(item){return"admin"===item.name}).length>0),result}}}).constant("APP_VERSION","5.0.0").constant("INSTANCE_BASE_URL","").constant("INSTANCE_API_PREFIX","/api/v2").service("INSTANCE_URL",["INSTANCE_BASE_URL","INSTANCE_API_PREFIX",function(INSTANCE_BASE_URL,INSTANCE_API_PREFIX){this.url=INSTANCE_BASE_URL+INSTANCE_API_PREFIX}]).constant("APP_API_KEY","6498a8ad1beb9d84d63035c5d1120c007fad6de706734db9689f8996707e0f7d").config(["$httpProvider","APP_API_KEY",function($httpProvider,APP_API_KEY){$httpProvider.defaults.headers.common["X-Dreamfactory-API-Key"]=APP_API_KEY,$httpProvider.defaults.headers.delete={"Content-Type":"application/json;charset=utf-8"}}]).config(["$routeProvider","$locationProvider","$httpProvider","$qProvider",function($routeProvider,$locationProvider,$httpProvider,$qProvider){$locationProvider.hashPrefix(""),$routeProvider.when("/login",{controller:"LoginCtrl",templateUrl:"views/login.html",resolve:{checkOtherRoute:["$q","UserDataService","$location","SystemConfigDataService",function($q,UserDataService,$location,SystemConfigDataService){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();if(currentUser&¤tUser.session_token){if(currentUser.is_sys_admin){var systemConfig=SystemConfigDataService.getSystemConfig();"user@example.com"===currentUser.email&&systemConfig&&systemConfig.platform&&systemConfig.platform.hasOwnProperty("bitnami_demo")&&!systemConfig.platform.bitnami_demo?$location.url("/profile"):$location.url("/home")}else $location.url("/launchpad");deferred.reject()}else deferred.resolve();return deferred.promise}]}}).when("/logout",{templateUrl:"views/logout.html",controller:"LogoutCtrl"}).when("/register",{templateUrl:"views/register.html",controller:"RegisterCtrl",resolve:{checkRegisterRoute:["$q","UserDataService","$location","SystemConfigDataService",function($q,UserDataService,$location,SystemConfigDataService){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();if(currentUser)currentUser.is_sys_admin?$location.url("/home"):$location.url("/launchpad"),deferred.reject();else{var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("allow_open_registration")&&systemConfig.authentication.allow_open_registration?deferred.resolve():($location.url("/login"),deferred.reject())}return deferred.promise}]}}).when("/register-complete",{templateUrl:"views/register-complete.html",controller:"RegisterCompleteCtrl",resolve:{checkRegisterCompleteRoute:["$q","UserDataService","$location","SystemConfigDataService",function($q,UserDataService,$location,SystemConfigDataService){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();if(currentUser)currentUser.is_sys_admin?$location.url("/home"):$location.url("/launchpad"),deferred.reject();else{var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("allow_open_registration")&&systemConfig.authentication.allow_open_registration?deferred.resolve():($location.url("/login"),deferred.reject())}return deferred.promise}]}}).when("/register-confirm",{templateUrl:"views/register-confirm.html",controller:"RegisterConfirmCtrl",resolve:{checkRegisterConfirmRoute:["$q","UserDataService","$location","SystemConfigDataService",function($q,UserDataService,$location,SystemConfigDataService){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();if(currentUser)currentUser.is_sys_admin?$location.url("/home"):$location.url("/launchpad"),deferred.reject();else{var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("allow_open_registration")&&systemConfig.authentication.allow_open_registration?deferred.resolve():($location.url("/login"),deferred.reject())}return deferred.promise}]}}).when("/reset-password",{templateUrl:"views/reset-password-email.html",controller:"ResetPasswordEmailCtrl",resolve:{checkResetPasswordRoute:["$q","UserDataService","$location",function($q,UserDataService,$location){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();return currentUser?(currentUser.is_sys_admin?$location.url("/home"):$location.url("/launchpad"),deferred.reject()):deferred.resolve(),deferred.promise}]}}).when("/user-invite",{templateUrl:"views/user-invite.html",controller:"UserInviteCtrl",resolve:{checkUserInviteRoute:["$q","UserDataService","$location",function($q,UserDataService,$location){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();return currentUser?(currentUser.is_sys_admin?$location.url("/home"):$location.url("/launchpad"),deferred.reject()):deferred.resolve(),deferred.promise}]}}).otherwise({controller:"LoginCtrl",templateUrl:"views/login.html",resolve:{checkOtherRoute:["$q","UserDataService","$location","SystemConfigDataService",function($q,UserDataService,$location,SystemConfigDataService){var deferred=$q.defer(),currentUser=UserDataService.getCurrentUser();if(currentUser&¤tUser.session_token)if(currentUser.is_sys_admin){var systemConfig=SystemConfigDataService.getSystemConfig();"user@example.com"===currentUser.email&&systemConfig&&systemConfig.platform.hasOwnProperty("bitnami_demo")&&!systemConfig.platform.bitnami_demo?$location.url("/profile"):$location.url("/home")}else $location.url("/launchpad");else $location.url("/login");return deferred.reject(),deferred.promise}]}}),$httpProvider.interceptors.push("httpValidSession")}]).config(["$provide",function($provide){$provide.decorator("$exceptionHandler",["$delegate","$injector",function($delegate,$injector){return function(exception,foo){if("string"==typeof exception){var prefix="Possibly unhandled rejection: ";0===exception.indexOf(prefix)&&(exception=angular.fromJson(exception.slice(prefix.length)))}if(!exception.provider||"dreamfactory"!==exception.provider)return $delegate(exception);$injector.invoke(["dfNotify",function(dfNotify){var messageOptions={module:exception.module,type:exception.type,provider:exception.provider,message:exception.exception};dfNotify.error(messageOptions)}])}}])}]),angular.module("dreamfactoryApp").controller("MainCtrl",["$scope","UserDataService","SystemConfigDataService","$location","dfApplicationData","dfNotify","dfIconService","allowAdminAccess","$animate","$http","INSTANCE_URL",function($scope,UserDataService,SystemConfigDataService,$location,dfApplicationData,dfNotify,dfIconService,allowAdminAccess,$animate,$http,INSTANCE_URL){function isCurrentUserRootAdmin(){return $scope.currentUser.hasOwnProperty("is_root_admin")&&$scope.currentUser.is_sys_admin&&$scope.currentUser.is_root_admin}function splitSchemaDataTab(accessibleTabs,schemaDataIndex){var schemaDataArr=accessibleTabs[schemaDataIndex].split("/");return accessibleTabs.splice(schemaDataIndex,1,schemaDataArr[0],schemaDataArr[1]),accessibleTabs}function getConfigTabInsertIndex(accessibleLinks,tabsLinks){var scriptsTabIndex=accessibleLinks.indexOf(tabsLinks.scripts),packagesTabIndex=accessibleLinks.indexOf(tabsLinks.packages);return-1!==scriptsTabIndex||-1!==packagesTabIndex?-1!==scriptsTabIndex?scriptsTabIndex+1:packagesTabIndex:accessibleLinks.length}function addDefaultTab(accessibleLinks,tabsLinks,tabName){switch(tabName){case"home":accessibleLinks.unshift(tabsLinks[tabName]);break;case"config":-1===accessibleLinks.indexOf(tabsLinks[tabName])&&accessibleLinks.splice(getConfigTabInsertIndex(accessibleLinks,tabsLinks),0,tabsLinks[tabName])}return accessibleLinks}function getAccessibleLinks(tabsLinks,accessibleTabs){var accessibleLinks=addDefaultTab([],tabsLinks,"home");return accessibleTabs.forEach(function(tab){accessibleLinks.push(tabsLinks[tab])}),accessibleLinks=addDefaultTab(accessibleLinks,tabsLinks,"config")}$animate.enabled(!1),$scope.title="",$scope.currentUser=UserDataService.getCurrentUser(),$scope.topLevelLinks=[{path:"https://www.dreamfactory.com/products/",target:"_blank",label:"Subscribe",name:"upgrade",icon:dfIconService().upgrade,show:!0},{path:"#/launchpad",target:null,label:"LaunchPad",name:"launchpad",icon:dfIconService().launchpad,show:!1},{path:"#/home",target:null,label:"Admin",name:"admin",icon:dfIconService().admin,show:!1},{path:"#/login",target:null,label:"Login",name:"login",icon:dfIconService().login,show:!1},{path:"#/register",target:null,label:"Register",name:"register",icon:dfIconService().register,show:!1},{path:null,target:null,label:UserDataService.getCurrentUser().name,name:"user",icon:dfIconService().user,show:!1,subLinks:[{path:"#/profile",target:null,label:"Profile",name:"profile",icon:null,show:!1},{path:"#/logout",target:null,label:"Logout",name:"logout",icon:null,show:!1}]}],$scope.topLevelNavOptions={links:$scope.topLevelLinks},$scope.showAdminComponentNav=!1,$scope.showHeader=!0,$scope.showLicenseExpiredBanner=!0;var navLinks={home:{name:"home",label:"Home",path:"/home"},services:{name:"services",label:"Services",path:"/services"},apps:{name:"apps",label:"Apps",path:"/apps"},admins:{name:"admins",label:"Admins",path:"/admins"},users:{name:"users",label:"Users",path:"/users"},roles:{name:"roles",label:"Roles",path:"/roles"},apidocs:{name:"apidocs",label:"API Docs",path:"/apidocs"},schema:{name:"schema",label:"Schema",path:"/schema"},data:{name:"data",label:"Data",path:"/data"},files:{name:"file-manager",label:"Files",path:"/file-manager"},scripts:{name:"scripts",label:"Scripts",path:"/scripts"},config:{name:"config",label:"Config",path:"/config"},packages:{name:"package-manager",label:"Packages",path:"/package-manager"},limits:{name:"limits",label:"Limits",path:"/limits"},scheduler:{name:"scheduler",label:"Scheduler",path:"/scheduler"}};$scope._setComponentLinks=function(isAdmin){var links=angular.copy(navLinks);isAdmin?$scope.currentUser.role_id?$scope._setAccessibleLinks(links):!dfApplicationData.isGoldLicense()||isCurrentUserRootAdmin()?(links.reports={name:"reports",label:"Reports",path:"/reports"},$scope.componentNavOptions={links:Object.values(links)}):dfApplicationData.isGoldLicense()&&(delete links.admins,$scope.doesRootAdminExist(),$scope.componentNavOptions={links:Object.values(links)}):(delete links.admins,delete links.roles,delete links.limits,delete links.scheduler,$scope.componentNavOptions={links:Object.values(links)})},$scope._setAccessibleLinks=function(tabsLinks){delete tabsLinks.roles,$http.get(INSTANCE_URL.url+"/system/role/"+$scope.currentUser.role_id+"?related=role_service_access_by_role_id&accessible_tabs=true").then(function(result){if(result&&result.data.hasOwnProperty("accessible_tabs")){var accessibleTabs=result.data.accessible_tabs,schemaDataIndex=accessibleTabs.indexOf("schema/data");-1!==schemaDataIndex&&(accessibleTabs=splitSchemaDataTab(accessibleTabs,schemaDataIndex)),$scope.componentNavOptions={links:getAccessibleLinks(tabsLinks,accessibleTabs)}}else $scope.componentNavOptions={links:Object.values(tabsLinks)}},function(result){UserDataService.unsetCurrentUser(),$location.url("/login"),console.error(result)})},$scope.doesRootAdminExist=function(){var systemConfig=SystemConfigDataService.getSystemConfig();if(!(systemConfig.hasOwnProperty("platform")&&systemConfig.platform.hasOwnProperty("root_admin_exists")&&systemConfig.platform.root_admin_exists)){var messageOptions={module:"Admins",provider:"dreamfactory",type:"error",message:"There is no root administrator selected. Some functionality might not work. Use df:root_admin command to choose one."};dfNotify.error(messageOptions)}},$scope._setActiveLinks=function(linksArr,activeLinksArr){var found,i;angular.forEach(linksArr,function(link){for(found=!1,i=0;i0&&links.push("launchpad"),systemConfig.hasOwnProperty("platform")&&links.push("upgrade")),newValue?($scope.setTopLevelLinkValue("user","label",newValue.name),links.push("user")):(links.push("login"),systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("allow_open_registration")&&systemConfig.authentication.allow_open_registration&&links.push("register")),allowAdminAccess.get()&&links.push("admin"),$scope._setActiveLinks($scope.topLevelLinks,links),$scope._setComponentLinks(newValue&&newValue.is_sys_admin)}),$scope.$watch(function(){return UserDataService.getCurrentUser().name},function(n,o){n&&$scope.setTopLevelLinkValue("user","label",n)}),$scope.$on("$routeChangeSuccess",function(e){switch($scope.showHeader=!0,$scope.showLicenseExpiredBanner=!0,$location.path()){case"/home":case"/apps":case"/admins":case"/users":case"/roles":case"/services":case"/apidocs":case"/schema":case"/data":case"/file-manager":case"/scripts":case"/config":case"/package-manager":case"/limits":case"/reports":case"/scheduler":$scope.showAdminComponentNav=!0;break;case"/license-expired":$scope.showHeader=!1,$scope.showLicenseExpiredBanner=!1,$scope.showAdminComponentNav=!1;break;default:$scope.showAdminComponentNav=!1}})}]).controller("LoginCtrl",["$scope","$window","$location","$timeout","UserDataService","UserEventsService","dfApplicationData","SystemConfigDataService","dfNotify",function($scope,$window,$location,$timeout,UserDataService,UserEventsService,dfApplicationData,SystemConfigDataService,dfNotify){$scope.loginOptions={showTemplate:!0},$scope.$on(UserEventsService.password.passwordSetSuccess,function(e,userCredsObj){var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"Password reset successful."};dfNotify.success(messageOptions),$scope.$broadcast(UserEventsService.login.loginRequest,userCredsObj)}),$scope.$on(UserEventsService.login.loginError,function(e){e.stopPropagation()}),$scope.$on(UserEventsService.login.loginSuccess,function(e,userDataObj){angular.equals($scope.$parent.currentUser,userDataObj)||dfApplicationData.resetApplicationObj(),$scope.$parent.currentUser=userDataObj;var queryString=location.search.substring(1);if($scope.loginOptions.showTemplate=!1,userDataObj.is_sys_admin)if(queryString){uri=$location.absUrl().split("?");$window.location.href=uri[0]+"#/home"}else if(userDataObj.is_sys_admin&&"user@example.com"===userDataObj.email){var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.platform&&systemConfig.platform.hasOwnProperty("bitnami_demo")&&!systemConfig.platform.bitnami_demo?$location.url("/profile"):$location.url("/home")}else $location.url("/home");else if(queryString){var uri=$location.absUrl().split("?");$window.location.href=uri[0]+"#/launchpad"}else $location.url("/launchpad")})}]).controller("LogoutCtrl",["$scope","$location","UserEventsService","dfApplicationData",function($scope,$location,UserEventsService,dfApplicationData){$scope.$on(UserEventsService.logout.logoutSuccess,function(e,userDataObj){$scope.$parent.currentUser=userDataObj,$location.url("/login")})}]).controller("RegisterCtrl",["$scope","$location","UserEventsService","SystemConfigDataService",function($scope,$location,UserEventsService,SystemConfigDataService){var confirmationRequired=!0,systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.authentication&&systemConfig.authentication.hasOwnProperty("open_reg_email_service_id")&&(confirmationRequired=!!systemConfig.authentication.open_reg_email_service_id),$scope.options={confirmationRequired:confirmationRequired},$scope.$on(UserEventsService.register.registerSuccess,function(e,userCredsObj){$scope.$broadcast(UserEventsService.login.loginRequest,userCredsObj)}),$scope.$on(UserEventsService.register.registerConfirmation,function(e){$location.url("/register-complete")}),$scope.$on(UserEventsService.login.loginSuccess,function(e,userDataObj){$scope.$parent.currentUser=userDataObj,$location.url("/launchpad")}),$scope.$on(UserEventsService.login.loginError,function(e){e.stopPropagation()})}]).controller("RegisterCompleteCtrl",["$scope",function($scope){}]).controller("RegisterConfirmCtrl",["$scope","$location","dfApplicationData","UserEventsService","SystemConfigDataService","dfNotify",function($scope,$location,dfApplicationData,UserEventsService,SystemConfigDataService,dfNotify){$scope.confirmOptions={showTemplate:!0,title:"Registration Confirmation"},$scope.loginOptions={showTemplate:!1},$scope.registerLoginErrorMsg="",$scope.inviteType="user",$scope.$on(UserEventsService.confirm.confirmationSuccess,function(e,userCredsObj){$scope.$broadcast(UserEventsService.login.loginRequest,userCredsObj)}),$scope.$on(UserEventsService.login.loginSuccess,function(e,userDataObj){var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"Registration Confirmation successful."};dfNotify.success(messageOptions),$scope.$parent.currentUser=userDataObj,$location.url("/launchpad")}),$scope.$on(UserEventsService.login.loginError,function(e,errMsg){e.stopPropagation(),$scope.registerLoginErrorMsg=errMsg.data.error.message})}]).controller("ResetPasswordEmailCtrl",["$scope","$location","dfApplicationData","UserEventsService","SystemConfigDataService","dfNotify","$timeout",function($scope,$location,dfApplicationData,UserEventsService,SystemConfigDataService,dfNotify,$timeout){$scope.loginOptions={showTemplate:!1},$scope.resetPasswordLoginErrorMsg="",$scope.$on(UserEventsService.password.passwordSetSuccess,function(e,userCredsObj){e.stopPropagation(),$scope.$broadcast(UserEventsService.login.loginRequest,userCredsObj)}),$scope.$on(UserEventsService.login.loginSuccess,function(e,userDataObj){var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"Password reset successful."};if(dfNotify.success(messageOptions),$scope.$parent.currentUser=userDataObj,$scope.loginOptions.showTemplate=!1,userDataObj.is_sys_admin&&"user@example.com"===userDataObj.email){var systemConfig=SystemConfigDataService.getSystemConfig();systemConfig&&systemConfig.platform&&systemConfig.platform.hasOwnProperty("bitnami_demo")&&!systemConfig.platform.bitnami_demo?$location.url("/profile"):$location.url("/home")}else $location.url("/home")}),$scope.$on(UserEventsService.login.loginError,function(e,errMsg){e.stopPropagation(),$scope.resetPasswordLoginErrorMsg=errMsg.data.error.message})}]).controller("UserInviteCtrl",["$scope","$location","dfApplicationData","UserEventsService","SystemConfigDataService","dfNotify",function($scope,$location,dfApplicationData,UserEventsService,SystemConfigDataService,dfNotify){$scope.confirmOptions={showTemplate:!0,title:"Invitation Confirmation"},$scope.inviteType=1==$location.search().admin?"admin":"user",$scope.loginOptions={showTemplate:!1},$scope.confirmLoginErrorMsg="",$scope.$on(UserEventsService.confirm.confirmationSuccess,function(e,userCredsObj){$scope.$broadcast(UserEventsService.login.loginRequest,userCredsObj)}),$scope.$on(UserEventsService.login.loginSuccess,function(e,userDataObj){var messageOptions={module:"Users",type:"success",provider:"dreamfactory",message:"User Confirmation successful."};dfNotify.success(messageOptions),$scope.$parent.currentUser=userDataObj,$location.url("/launchpad")}),$scope.$on(UserEventsService.login.loginError,function(e,errMsg){e.stopPropagation(),$scope.confirmLoginErrorMsg=errMsg.data.error.message})}]).controller("PaywallCtrl",["$scope","$http","UserDataService","SystemConfigDataService",function($scope,$http,UserDataService,SystemConfigDataService){$scope.$on("hitPaywall",function(e,data){$scope.sendRequest(data)}),$scope.sendRequest=function(serviceName){var data={email:UserDataService.getCurrentUser().email,ip_address:SystemConfigDataService.getSystemConfig().client.ip_address,service_name:serviceName},req={method:"POST",url:"https://updates.dreamfactory.com/api/paywall",data:JSON.stringify(data)};$http(req).then()}}]),Array.of||(Array.of=function(){return Array.prototype.slice.call(arguments)}),Array.prototype.copyWithin||(Array.prototype.copyWithin=function(target,start){if(null==this)throw new TypeError("this is null or not defined");var O=Object(this),len=O.length>>>0,relativeTarget=target>>0,to=relativeTarget<0?Math.max(len+relativeTarget,0):Math.min(relativeTarget,len),relativeStart=start>>0,from=relativeStart<0?Math.max(len+relativeStart,0):Math.min(relativeStart,len),end=arguments[2],relativeEnd=void 0===end?len:end>>0,final=relativeEnd<0?Math.max(len+relativeEnd,0):Math.min(relativeEnd,len),count=Math.min(final-from,len-to),direction=1;for(from0;)from in O?O[to]=O[from]:delete O[to],from+=direction,to+=direction,count--;return O}),Array.prototype.every||(Array.prototype.every=function(callbackfn,thisArg){var T,k;if(null==this)throw new TypeError("this is null or not defined");var O=Object(this),len=O.length>>>0;if("function"!=typeof callbackfn)throw new TypeError;for(arguments.length>1&&(T=thisArg),k=0;k>>0,relativeStart=arguments[1]>>0,k=relativeStart<0?Math.max(len+relativeStart,0):Math.min(relativeStart,len),end=arguments[2],relativeEnd=void 0===end?len:end>>0,final=relativeEnd<0?Math.max(len+relativeEnd,0):Math.min(relativeEnd,len);k>>0;if("function"!=typeof fun)throw new TypeError;for(var res=[],thisArg=arguments.length>=2?arguments[1]:void 0,i=0;i>>0;if("function"!=typeof predicate)throw new TypeError("predicate must be a function");for(var thisArg=arguments[1],k=0;k>>0;if("function"!=typeof predicate)throw new TypeError("predicate must be a function");for(var thisArg=arguments[1],k=0;k>>0;if("function"!=typeof callback)throw new TypeError(callback+" is not a function");for(arguments.length>1&&(T=arguments[1]),k=0;k>>0;if(0===len)return!1;for(var n=0|fromIndex,k=Math.max(n>=0?n:len-Math.abs(n),0);k>>0;if(0===len)return-1;var n=0|fromIndex;if(n>=len)return-1;for(k=Math.max(n>=0?n:len-Math.abs(n),0);k>>0;if(0===len)return-1;for(n=len-1,arguments.length>1&&((n=Number(arguments[1]))!=n?n=0:0!=n&&n!=1/0&&n!=-1/0&&(n=(n>0||-1)*Math.floor(Math.abs(n)))),k=n>=0?Math.min(n,len-1):len-Math.abs(n);k>=0;k--)if(k in t&&t[k]===searchElement)return k;return-1}),Array.prototype.map||(Array.prototype.map=function(callback){var T,A,k;if(null==this)throw new TypeError("this is null or not defined");var O=Object(this),len=O.length>>>0;if("function"!=typeof callback)throw new TypeError(callback+" is not a function");for(arguments.length>1&&(T=arguments[1]),A=new Array(len),k=0;k>>0,k=0;if(2==arguments.length)value=arguments[1];else{for(;k=len)throw new TypeError("Reduce of empty array with no initial value");value=o[k++]}for(;k>>0)-1;if(arguments.length>=2)value=arguments[1];else{for(;k>=0&&!(k in t);)k--;if(k<0)throw new TypeError("Reduce of empty array with no initial value");value=t[k--]}for(;k>=0;k--)k in t&&(value=callback(value,t[k],k,t));return value}),Array.prototype.some||(Array.prototype.some=function(fun){if(null==this)throw new TypeError("Array.prototype.some called on null or undefined");if("function"!=typeof fun)throw new TypeError;for(var t=Object(this),len=t.length>>>0,thisArg=arguments.length>=2?arguments[1]:void 0,i=0;i>>0;if(0===len)return"";for(var firstElement=a[0],r=null==firstElement?"":firstElement.toLocaleString(locales,options),k=1;k