From 1e0a78db3002e267b2bb7c74a3144af01e9fc800 Mon Sep 17 00:00:00 2001 From: Jordan Wright Date: Tue, 26 Mar 2019 22:17:20 -0500 Subject: [PATCH 01/27] Refactoring API into separate package for easier management. (#1411) --- controllers/api.go | 772 ---------------------------------- controllers/api/api_test.go | 122 ++++++ controllers/api/campaign.go | 137 ++++++ controllers/api/group.go | 118 ++++++ controllers/api/import.go | 157 +++++++ controllers/api/page.go | 91 ++++ controllers/api/reset.go | 24 ++ controllers/api/response.go | 22 + controllers/api/server.go | 76 ++++ controllers/api/smtp.go | 96 +++++ controllers/api/template.go | 97 +++++ controllers/api/util.go | 122 ++++++ controllers/api_test.go | 50 --- controllers/phish.go | 3 +- controllers/route.go | 34 +- middleware/middleware_test.go | 35 ++ 16 files changed, 1105 insertions(+), 851 deletions(-) delete mode 100644 controllers/api.go create mode 100644 controllers/api/api_test.go create mode 100644 controllers/api/campaign.go create mode 100644 controllers/api/group.go create mode 100644 controllers/api/import.go create mode 100644 controllers/api/page.go create mode 100644 controllers/api/reset.go create mode 100644 controllers/api/response.go create mode 100644 controllers/api/server.go create mode 100644 controllers/api/smtp.go create mode 100644 controllers/api/template.go create mode 100644 controllers/api/util.go diff --git a/controllers/api.go b/controllers/api.go deleted file mode 100644 index a4341355..00000000 --- a/controllers/api.go +++ /dev/null @@ -1,772 +0,0 @@ -package controllers - -import ( - "bytes" - "crypto/tls" - "encoding/json" - "errors" - "fmt" - "net/http" - "strconv" - "strings" - "time" - - "github.com/PuerkitoBio/goquery" - "github.com/gophish/gophish/auth" - ctx "github.com/gophish/gophish/context" - log "github.com/gophish/gophish/logger" - "github.com/gophish/gophish/models" - "github.com/gophish/gophish/util" - "github.com/gorilla/mux" - "github.com/jinzhu/gorm" - "github.com/jordan-wright/email" - "github.com/sirupsen/logrus" -) - -// APIReset (/api/reset) resets the currently authenticated user's API key -func (as *AdminServer) APIReset(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "POST": - u := ctx.Get(r, "user").(models.User) - u.ApiKey = auth.GenerateSecureKey() - err := models.PutUser(&u) - if err != nil { - http.Error(w, "Error setting API Key", http.StatusInternalServerError) - } else { - JSONResponse(w, models.Response{Success: true, Message: "API Key successfully reset!", Data: u.ApiKey}, http.StatusOK) - } - } -} - -// APICampaigns returns a list of campaigns if requested via GET. -// If requested via POST, APICampaigns creates a new campaign and returns a reference to it. -func (as *AdminServer) APICampaigns(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "GET": - cs, err := models.GetCampaigns(ctx.Get(r, "user_id").(int64)) - if err != nil { - log.Error(err) - } - JSONResponse(w, cs, http.StatusOK) - //POST: Create a new campaign and return it as JSON - case r.Method == "POST": - c := models.Campaign{} - // Put the request into a campaign - err := json.NewDecoder(r.Body).Decode(&c) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Invalid JSON structure"}, http.StatusBadRequest) - return - } - err = models.PostCampaign(&c, ctx.Get(r, "user_id").(int64)) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - // If the campaign is scheduled to launch immediately, send it to the worker. - // Otherwise, the worker will pick it up at the scheduled time - if c.Status == models.CampaignInProgress { - go as.worker.LaunchCampaign(c) - } - JSONResponse(w, c, http.StatusCreated) - } -} - -// APICampaignsSummary returns the summary for the current user's campaigns -func (as *AdminServer) APICampaignsSummary(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "GET": - cs, err := models.GetCampaignSummaries(ctx.Get(r, "user_id").(int64)) - if err != nil { - log.Error(err) - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) - return - } - JSONResponse(w, cs, http.StatusOK) - } -} - -// APICampaign returns details about the requested campaign. If the campaign is not -// valid, APICampaign returns null. -func (as *AdminServer) APICampaign(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - id, _ := strconv.ParseInt(vars["id"], 0, 64) - c, err := models.GetCampaign(id, ctx.Get(r, "user_id").(int64)) - if err != nil { - log.Error(err) - JSONResponse(w, models.Response{Success: false, Message: "Campaign not found"}, http.StatusNotFound) - return - } - switch { - case r.Method == "GET": - JSONResponse(w, c, http.StatusOK) - case r.Method == "DELETE": - err = models.DeleteCampaign(id) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error deleting campaign"}, http.StatusInternalServerError) - return - } - JSONResponse(w, models.Response{Success: true, Message: "Campaign deleted successfully!"}, http.StatusOK) - } -} - -// APICampaignResults returns just the results for a given campaign to -// significantly reduce the information returned. -func (as *AdminServer) APICampaignResults(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - id, _ := strconv.ParseInt(vars["id"], 0, 64) - cr, err := models.GetCampaignResults(id, ctx.Get(r, "user_id").(int64)) - if err != nil { - log.Error(err) - JSONResponse(w, models.Response{Success: false, Message: "Campaign not found"}, http.StatusNotFound) - return - } - if r.Method == "GET" { - JSONResponse(w, cr, http.StatusOK) - return - } -} - -// APICampaignSummary returns the summary for a given campaign. -func (as *AdminServer) APICampaignSummary(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - id, _ := strconv.ParseInt(vars["id"], 0, 64) - switch { - case r.Method == "GET": - cs, err := models.GetCampaignSummary(id, ctx.Get(r, "user_id").(int64)) - if err != nil { - if err == gorm.ErrRecordNotFound { - JSONResponse(w, models.Response{Success: false, Message: "Campaign not found"}, http.StatusNotFound) - } else { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) - } - log.Error(err) - return - } - JSONResponse(w, cs, http.StatusOK) - } -} - -// APICampaignComplete effectively "ends" a campaign. -// Future phishing emails clicked will return a simple "404" page. -func (as *AdminServer) APICampaignComplete(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - id, _ := strconv.ParseInt(vars["id"], 0, 64) - switch { - case r.Method == "GET": - err := models.CompleteCampaign(id, ctx.Get(r, "user_id").(int64)) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error completing campaign"}, http.StatusInternalServerError) - return - } - JSONResponse(w, models.Response{Success: true, Message: "Campaign completed successfully!"}, http.StatusOK) - } -} - -// APIGroups returns a list of groups if requested via GET. -// If requested via POST, APIGroups creates a new group and returns a reference to it. -func (as *AdminServer) APIGroups(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "GET": - gs, err := models.GetGroups(ctx.Get(r, "user_id").(int64)) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "No groups found"}, http.StatusNotFound) - return - } - JSONResponse(w, gs, http.StatusOK) - //POST: Create a new group and return it as JSON - case r.Method == "POST": - g := models.Group{} - // Put the request into a group - err := json.NewDecoder(r.Body).Decode(&g) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Invalid JSON structure"}, http.StatusBadRequest) - return - } - _, err = models.GetGroupByName(g.Name, ctx.Get(r, "user_id").(int64)) - if err != gorm.ErrRecordNotFound { - JSONResponse(w, models.Response{Success: false, Message: "Group name already in use"}, http.StatusConflict) - return - } - g.ModifiedDate = time.Now().UTC() - g.UserId = ctx.Get(r, "user_id").(int64) - err = models.PostGroup(&g) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - JSONResponse(w, g, http.StatusCreated) - } -} - -// APIGroupsSummary returns a summary of the groups owned by the current user. -func (as *AdminServer) APIGroupsSummary(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "GET": - gs, err := models.GetGroupSummaries(ctx.Get(r, "user_id").(int64)) - if err != nil { - log.Error(err) - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) - return - } - JSONResponse(w, gs, http.StatusOK) - } -} - -// APIGroup returns details about the requested group. -// If the group is not valid, APIGroup returns null. -func (as *AdminServer) APIGroup(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - id, _ := strconv.ParseInt(vars["id"], 0, 64) - g, err := models.GetGroup(id, ctx.Get(r, "user_id").(int64)) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Group not found"}, http.StatusNotFound) - return - } - switch { - case r.Method == "GET": - JSONResponse(w, g, http.StatusOK) - case r.Method == "DELETE": - err = models.DeleteGroup(&g) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error deleting group"}, http.StatusInternalServerError) - return - } - JSONResponse(w, models.Response{Success: true, Message: "Group deleted successfully!"}, http.StatusOK) - case r.Method == "PUT": - // Change this to get from URL and uid (don't bother with id in r.Body) - g = models.Group{} - err = json.NewDecoder(r.Body).Decode(&g) - if g.Id != id { - JSONResponse(w, models.Response{Success: false, Message: "Error: /:id and group_id mismatch"}, http.StatusInternalServerError) - return - } - g.ModifiedDate = time.Now().UTC() - g.UserId = ctx.Get(r, "user_id").(int64) - err = models.PutGroup(&g) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - JSONResponse(w, g, http.StatusOK) - } -} - -// APIGroupSummary returns a summary of the groups owned by the current user. -func (as *AdminServer) APIGroupSummary(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "GET": - vars := mux.Vars(r) - id, _ := strconv.ParseInt(vars["id"], 0, 64) - g, err := models.GetGroupSummary(id, ctx.Get(r, "user_id").(int64)) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Group not found"}, http.StatusNotFound) - return - } - JSONResponse(w, g, http.StatusOK) - } -} - -// APITemplates handles the functionality for the /api/templates endpoint -func (as *AdminServer) APITemplates(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "GET": - ts, err := models.GetTemplates(ctx.Get(r, "user_id").(int64)) - if err != nil { - log.Error(err) - } - JSONResponse(w, ts, http.StatusOK) - //POST: Create a new template and return it as JSON - case r.Method == "POST": - t := models.Template{} - // Put the request into a template - err := json.NewDecoder(r.Body).Decode(&t) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Invalid JSON structure"}, http.StatusBadRequest) - return - } - _, err = models.GetTemplateByName(t.Name, ctx.Get(r, "user_id").(int64)) - if err != gorm.ErrRecordNotFound { - JSONResponse(w, models.Response{Success: false, Message: "Template name already in use"}, http.StatusConflict) - return - } - t.ModifiedDate = time.Now().UTC() - t.UserId = ctx.Get(r, "user_id").(int64) - err = models.PostTemplate(&t) - if err == models.ErrTemplateNameNotSpecified { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - if err == models.ErrTemplateMissingParameter { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error inserting template into database"}, http.StatusInternalServerError) - log.Error(err) - return - } - JSONResponse(w, t, http.StatusCreated) - } -} - -// APITemplate handles the functions for the /api/templates/:id endpoint -func (as *AdminServer) APITemplate(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - id, _ := strconv.ParseInt(vars["id"], 0, 64) - t, err := models.GetTemplate(id, ctx.Get(r, "user_id").(int64)) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Template not found"}, http.StatusNotFound) - return - } - switch { - case r.Method == "GET": - JSONResponse(w, t, http.StatusOK) - case r.Method == "DELETE": - err = models.DeleteTemplate(id, ctx.Get(r, "user_id").(int64)) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error deleting template"}, http.StatusInternalServerError) - return - } - JSONResponse(w, models.Response{Success: true, Message: "Template deleted successfully!"}, http.StatusOK) - case r.Method == "PUT": - t = models.Template{} - err = json.NewDecoder(r.Body).Decode(&t) - if err != nil { - log.Error(err) - } - if t.Id != id { - JSONResponse(w, models.Response{Success: false, Message: "Error: /:id and template_id mismatch"}, http.StatusBadRequest) - return - } - t.ModifiedDate = time.Now().UTC() - t.UserId = ctx.Get(r, "user_id").(int64) - err = models.PutTemplate(&t) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - JSONResponse(w, t, http.StatusOK) - } -} - -// APIPages handles requests for the /api/pages/ endpoint -func (as *AdminServer) APIPages(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "GET": - ps, err := models.GetPages(ctx.Get(r, "user_id").(int64)) - if err != nil { - log.Error(err) - } - JSONResponse(w, ps, http.StatusOK) - //POST: Create a new page and return it as JSON - case r.Method == "POST": - p := models.Page{} - // Put the request into a page - err := json.NewDecoder(r.Body).Decode(&p) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Invalid request"}, http.StatusBadRequest) - return - } - // Check to make sure the name is unique - _, err = models.GetPageByName(p.Name, ctx.Get(r, "user_id").(int64)) - if err != gorm.ErrRecordNotFound { - JSONResponse(w, models.Response{Success: false, Message: "Page name already in use"}, http.StatusConflict) - log.Error(err) - return - } - p.ModifiedDate = time.Now().UTC() - p.UserId = ctx.Get(r, "user_id").(int64) - err = models.PostPage(&p) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) - return - } - JSONResponse(w, p, http.StatusCreated) - } -} - -// APIPage contains functions to handle the GET'ing, DELETE'ing, and PUT'ing -// of a Page object -func (as *AdminServer) APIPage(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - id, _ := strconv.ParseInt(vars["id"], 0, 64) - p, err := models.GetPage(id, ctx.Get(r, "user_id").(int64)) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Page not found"}, http.StatusNotFound) - return - } - switch { - case r.Method == "GET": - JSONResponse(w, p, http.StatusOK) - case r.Method == "DELETE": - err = models.DeletePage(id, ctx.Get(r, "user_id").(int64)) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error deleting page"}, http.StatusInternalServerError) - return - } - JSONResponse(w, models.Response{Success: true, Message: "Page Deleted Successfully"}, http.StatusOK) - case r.Method == "PUT": - p = models.Page{} - err = json.NewDecoder(r.Body).Decode(&p) - if err != nil { - log.Error(err) - } - if p.Id != id { - JSONResponse(w, models.Response{Success: false, Message: "/:id and /:page_id mismatch"}, http.StatusBadRequest) - return - } - p.ModifiedDate = time.Now().UTC() - p.UserId = ctx.Get(r, "user_id").(int64) - err = models.PutPage(&p) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error updating page: " + err.Error()}, http.StatusInternalServerError) - return - } - JSONResponse(w, p, http.StatusOK) - } -} - -// APISendingProfiles handles requests for the /api/smtp/ endpoint -func (as *AdminServer) APISendingProfiles(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == "GET": - ss, err := models.GetSMTPs(ctx.Get(r, "user_id").(int64)) - if err != nil { - log.Error(err) - } - JSONResponse(w, ss, http.StatusOK) - //POST: Create a new SMTP and return it as JSON - case r.Method == "POST": - s := models.SMTP{} - // Put the request into a page - err := json.NewDecoder(r.Body).Decode(&s) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Invalid request"}, http.StatusBadRequest) - return - } - // Check to make sure the name is unique - _, err = models.GetSMTPByName(s.Name, ctx.Get(r, "user_id").(int64)) - if err != gorm.ErrRecordNotFound { - JSONResponse(w, models.Response{Success: false, Message: "SMTP name already in use"}, http.StatusConflict) - log.Error(err) - return - } - s.ModifiedDate = time.Now().UTC() - s.UserId = ctx.Get(r, "user_id").(int64) - err = models.PostSMTP(&s) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) - return - } - JSONResponse(w, s, http.StatusCreated) - } -} - -// APISendingProfile contains functions to handle the GET'ing, DELETE'ing, and PUT'ing -// of a SMTP object -func (as *AdminServer) APISendingProfile(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - id, _ := strconv.ParseInt(vars["id"], 0, 64) - s, err := models.GetSMTP(id, ctx.Get(r, "user_id").(int64)) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "SMTP not found"}, http.StatusNotFound) - return - } - switch { - case r.Method == "GET": - JSONResponse(w, s, http.StatusOK) - case r.Method == "DELETE": - err = models.DeleteSMTP(id, ctx.Get(r, "user_id").(int64)) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error deleting SMTP"}, http.StatusInternalServerError) - return - } - JSONResponse(w, models.Response{Success: true, Message: "SMTP Deleted Successfully"}, http.StatusOK) - case r.Method == "PUT": - s = models.SMTP{} - err = json.NewDecoder(r.Body).Decode(&s) - if err != nil { - log.Error(err) - } - if s.Id != id { - JSONResponse(w, models.Response{Success: false, Message: "/:id and /:smtp_id mismatch"}, http.StatusBadRequest) - return - } - err = s.Validate() - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - s.ModifiedDate = time.Now().UTC() - s.UserId = ctx.Get(r, "user_id").(int64) - err = models.PutSMTP(&s) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error updating page"}, http.StatusInternalServerError) - return - } - JSONResponse(w, s, http.StatusOK) - } -} - -// APIImportGroup imports a CSV of group members -func (as *AdminServer) APIImportGroup(w http.ResponseWriter, r *http.Request) { - ts, err := util.ParseCSV(r) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error parsing CSV"}, http.StatusInternalServerError) - return - } - JSONResponse(w, ts, http.StatusOK) - return -} - -// APIImportEmail allows for the importing of email. -// Returns a Message object -func (as *AdminServer) APIImportEmail(w http.ResponseWriter, r *http.Request) { - if r.Method != "POST" { - JSONResponse(w, models.Response{Success: false, Message: "Method not allowed"}, http.StatusBadRequest) - return - } - ir := struct { - Content string `json:"content"` - ConvertLinks bool `json:"convert_links"` - }{} - err := json.NewDecoder(r.Body).Decode(&ir) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error decoding JSON Request"}, http.StatusBadRequest) - return - } - e, err := email.NewEmailFromReader(strings.NewReader(ir.Content)) - if err != nil { - log.Error(err) - } - // If the user wants to convert links to point to - // the landing page, let's make it happen by changing up - // e.HTML - if ir.ConvertLinks { - d, err := goquery.NewDocumentFromReader(bytes.NewReader(e.HTML)) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - d.Find("a").Each(func(i int, a *goquery.Selection) { - a.SetAttr("href", "{{.URL}}") - }) - h, err := d.Html() - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) - return - } - e.HTML = []byte(h) - } - er := emailResponse{ - Subject: e.Subject, - Text: string(e.Text), - HTML: string(e.HTML), - } - JSONResponse(w, er, http.StatusOK) - return -} - -// APIImportSite allows for the importing of HTML from a website -// Without "include_resources" set, it will merely place a "base" tag -// so that all resources can be loaded relative to the given URL. -func (as *AdminServer) APIImportSite(w http.ResponseWriter, r *http.Request) { - cr := cloneRequest{} - if r.Method != "POST" { - JSONResponse(w, models.Response{Success: false, Message: "Method not allowed"}, http.StatusBadRequest) - return - } - err := json.NewDecoder(r.Body).Decode(&cr) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error decoding JSON Request"}, http.StatusBadRequest) - return - } - if err = cr.validate(); err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - tr := &http.Transport{ - TLSClientConfig: &tls.Config{ - InsecureSkipVerify: true, - }, - } - client := &http.Client{Transport: tr} - resp, err := client.Get(cr.URL) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - // Insert the base href tag to better handle relative resources - d, err := goquery.NewDocumentFromResponse(resp) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - // Assuming we don't want to include resources, we'll need a base href - if d.Find("head base").Length() == 0 { - d.Find("head").PrependHtml(fmt.Sprintf("", cr.URL)) - } - forms := d.Find("form") - forms.Each(func(i int, f *goquery.Selection) { - // We'll want to store where we got the form from - // (the current URL) - url := f.AttrOr("action", cr.URL) - if !strings.HasPrefix(url, "http") { - url = fmt.Sprintf("%s%s", cr.URL, url) - } - f.PrependHtml(fmt.Sprintf("", url)) - }) - h, err := d.Html() - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) - return - } - cs := cloneResponse{HTML: h} - JSONResponse(w, cs, http.StatusOK) - return -} - -// APISendTestEmail sends a test email using the template name -// and Target given. -func (as *AdminServer) APISendTestEmail(w http.ResponseWriter, r *http.Request) { - s := &models.EmailRequest{ - ErrorChan: make(chan error), - UserId: ctx.Get(r, "user_id").(int64), - } - if r.Method != "POST" { - JSONResponse(w, models.Response{Success: false, Message: "Method not allowed"}, http.StatusBadRequest) - return - } - err := json.NewDecoder(r.Body).Decode(s) - if err != nil { - JSONResponse(w, models.Response{Success: false, Message: "Error decoding JSON Request"}, http.StatusBadRequest) - return - } - - storeRequest := false - - // If a Template is not specified use a default - if s.Template.Name == "" { - //default message body - text := "It works!\n\nThis is an email letting you know that your gophish\nconfiguration was successful.\n" + - "Here are the details:\n\nWho you sent from: {{.From}}\n\nWho you sent to: \n" + - "{{if .FirstName}} First Name: {{.FirstName}}\n{{end}}" + - "{{if .LastName}} Last Name: {{.LastName}}\n{{end}}" + - "{{if .Position}} Position: {{.Position}}\n{{end}}" + - "\nNow go send some phish!" - t := models.Template{ - Subject: "Default Email from Gophish", - Text: text, - } - s.Template = t - } else { - // Get the Template requested by name - s.Template, err = models.GetTemplateByName(s.Template.Name, s.UserId) - if err == gorm.ErrRecordNotFound { - log.WithFields(logrus.Fields{ - "template": s.Template.Name, - }).Error("Template does not exist") - JSONResponse(w, models.Response{Success: false, Message: models.ErrTemplateNotFound.Error()}, http.StatusBadRequest) - return - } else if err != nil { - log.Error(err) - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - s.TemplateId = s.Template.Id - // We'll only save the test request to the database if there is a - // user-specified template to use. - storeRequest = true - } - - if s.Page.Name != "" { - s.Page, err = models.GetPageByName(s.Page.Name, s.UserId) - if err == gorm.ErrRecordNotFound { - log.WithFields(logrus.Fields{ - "page": s.Page.Name, - }).Error("Page does not exist") - JSONResponse(w, models.Response{Success: false, Message: models.ErrPageNotFound.Error()}, http.StatusBadRequest) - return - } else if err != nil { - log.Error(err) - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - s.PageId = s.Page.Id - } - - // If a complete sending profile is provided use it - if err := s.SMTP.Validate(); err != nil { - // Otherwise get the SMTP requested by name - smtp, lookupErr := models.GetSMTPByName(s.SMTP.Name, s.UserId) - // If the Sending Profile doesn't exist, let's err on the side - // of caution and assume that the validation failure was more important. - if lookupErr != nil { - log.Error(err) - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - s.SMTP = smtp - } - s.FromAddress = s.SMTP.FromAddress - - // Validate the given request - if err = s.Validate(); err != nil { - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) - return - } - - // Store the request if this wasn't the default template - if storeRequest { - err = models.PostEmailRequest(s) - if err != nil { - log.Error(err) - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) - return - } - } - // Send the test email - err = as.worker.SendTestEmail(s) - if err != nil { - log.Error(err) - JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) - return - } - JSONResponse(w, models.Response{Success: true, Message: "Email Sent"}, http.StatusOK) - return -} - -// JSONResponse attempts to set the status code, c, and marshal the given interface, d, into a response that -// is written to the given ResponseWriter. -func JSONResponse(w http.ResponseWriter, d interface{}, c int) { - dj, err := json.MarshalIndent(d, "", " ") - if err != nil { - http.Error(w, "Error creating JSON response", http.StatusInternalServerError) - log.Error(err) - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(c) - fmt.Fprintf(w, "%s", dj) -} - -type cloneRequest struct { - URL string `json:"url"` - IncludeResources bool `json:"include_resources"` -} - -func (cr *cloneRequest) validate() error { - if cr.URL == "" { - return errors.New("No URL Specified") - } - return nil -} - -type cloneResponse struct { - HTML string `json:"html"` -} - -type emailResponse struct { - Text string `json:"text"` - HTML string `json:"html"` - Subject string `json:"subject"` -} diff --git a/controllers/api/api_test.go b/controllers/api/api_test.go new file mode 100644 index 00000000..c4a4a8b7 --- /dev/null +++ b/controllers/api/api_test.go @@ -0,0 +1,122 @@ +package api + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/gophish/gophish/config" + "github.com/gophish/gophish/models" + "github.com/stretchr/testify/suite" +) + +type APISuite struct { + suite.Suite + apiKey string + config *config.Config + apiServer *Server +} + +func (s *APISuite) SetupSuite() { + conf := &config.Config{ + DBName: "sqlite3", + DBPath: ":memory:", + MigrationsPath: "../../db/db_sqlite3/migrations/", + } + err := models.Setup(conf) + if err != nil { + s.T().Fatalf("Failed creating database: %v", err) + } + s.config = conf + s.Nil(err) + // Get the API key to use for these tests + u, err := models.GetUser(1) + s.Nil(err) + s.apiKey = u.ApiKey + // Move our cwd up to the project root for help with resolving + // static assets + err = os.Chdir("../") + s.Nil(err) + s.apiServer = NewServer() +} + +func (s *APISuite) TearDownTest() { + campaigns, _ := models.GetCampaigns(1) + for _, campaign := range campaigns { + models.DeleteCampaign(campaign.Id) + } +} + +func (s *APISuite) SetupTest() { + // Add a group + group := models.Group{Name: "Test Group"} + group.Targets = []models.Target{ + models.Target{BaseRecipient: models.BaseRecipient{Email: "test1@example.com", FirstName: "First", LastName: "Example"}}, + models.Target{BaseRecipient: models.BaseRecipient{Email: "test2@example.com", FirstName: "Second", LastName: "Example"}}, + } + group.UserId = 1 + models.PostGroup(&group) + + // Add a template + t := models.Template{Name: "Test Template"} + t.Subject = "Test subject" + t.Text = "Text text" + t.HTML = "Test" + t.UserId = 1 + models.PostTemplate(&t) + + // Add a landing page + p := models.Page{Name: "Test Page"} + p.HTML = "Test" + p.UserId = 1 + models.PostPage(&p) + + // Add a sending profile + smtp := models.SMTP{Name: "Test Page"} + smtp.UserId = 1 + smtp.Host = "example.com" + smtp.FromAddress = "test@test.com" + models.PostSMTP(&smtp) + + // Setup and "launch" our campaign + // Set the status such that no emails are attempted + c := models.Campaign{Name: "Test campaign"} + c.UserId = 1 + c.Template = t + c.Page = p + c.SMTP = smtp + c.Groups = []models.Group{group} + models.PostCampaign(&c, c.UserId) + c.UpdateStatus(models.CampaignEmailsSent) +} + +func (s *APISuite) TestSiteImportBaseHref() { + h := "" + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintln(w, h) + })) + hr := fmt.Sprintf("\n", ts.URL) + defer ts.Close() + req := httptest.NewRequest(http.MethodPost, "/api/import/site", + bytes.NewBuffer([]byte(fmt.Sprintf(` + { + "url" : "%s", + "include_resources" : false + } + `, ts.URL)))) + req.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + s.apiServer.ImportSite(response, req) + cs := cloneResponse{} + err := json.NewDecoder(response.Body).Decode(&cs) + s.Nil(err) + s.Equal(cs.HTML, hr) +} + +func TestAPISuite(t *testing.T) { + suite.Run(t, new(APISuite)) +} diff --git a/controllers/api/campaign.go b/controllers/api/campaign.go new file mode 100644 index 00000000..33c08fe7 --- /dev/null +++ b/controllers/api/campaign.go @@ -0,0 +1,137 @@ +package api + +import ( + "encoding/json" + "net/http" + "strconv" + + ctx "github.com/gophish/gophish/context" + log "github.com/gophish/gophish/logger" + "github.com/gophish/gophish/models" + "github.com/gorilla/mux" + "github.com/jinzhu/gorm" +) + +// Campaigns returns a list of campaigns if requested via GET. +// If requested via POST, APICampaigns creates a new campaign and returns a reference to it. +func (as *Server) Campaigns(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == "GET": + cs, err := models.GetCampaigns(ctx.Get(r, "user_id").(int64)) + if err != nil { + log.Error(err) + } + JSONResponse(w, cs, http.StatusOK) + //POST: Create a new campaign and return it as JSON + case r.Method == "POST": + c := models.Campaign{} + // Put the request into a campaign + err := json.NewDecoder(r.Body).Decode(&c) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Invalid JSON structure"}, http.StatusBadRequest) + return + } + err = models.PostCampaign(&c, ctx.Get(r, "user_id").(int64)) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + // If the campaign is scheduled to launch immediately, send it to the worker. + // Otherwise, the worker will pick it up at the scheduled time + if c.Status == models.CampaignInProgress { + go as.worker.LaunchCampaign(c) + } + JSONResponse(w, c, http.StatusCreated) + } +} + +// CampaignsSummary returns the summary for the current user's campaigns +func (as *Server) CampaignsSummary(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == "GET": + cs, err := models.GetCampaignSummaries(ctx.Get(r, "user_id").(int64)) + if err != nil { + log.Error(err) + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) + return + } + JSONResponse(w, cs, http.StatusOK) + } +} + +// Campaign returns details about the requested campaign. If the campaign is not +// valid, APICampaign returns null. +func (as *Server) Campaign(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + id, _ := strconv.ParseInt(vars["id"], 0, 64) + c, err := models.GetCampaign(id, ctx.Get(r, "user_id").(int64)) + if err != nil { + log.Error(err) + JSONResponse(w, models.Response{Success: false, Message: "Campaign not found"}, http.StatusNotFound) + return + } + switch { + case r.Method == "GET": + JSONResponse(w, c, http.StatusOK) + case r.Method == "DELETE": + err = models.DeleteCampaign(id) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error deleting campaign"}, http.StatusInternalServerError) + return + } + JSONResponse(w, models.Response{Success: true, Message: "Campaign deleted successfully!"}, http.StatusOK) + } +} + +// CampaignResults returns just the results for a given campaign to +// significantly reduce the information returned. +func (as *Server) CampaignResults(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + id, _ := strconv.ParseInt(vars["id"], 0, 64) + cr, err := models.GetCampaignResults(id, ctx.Get(r, "user_id").(int64)) + if err != nil { + log.Error(err) + JSONResponse(w, models.Response{Success: false, Message: "Campaign not found"}, http.StatusNotFound) + return + } + if r.Method == "GET" { + JSONResponse(w, cr, http.StatusOK) + return + } +} + +// CampaignSummary returns the summary for a given campaign. +func (as *Server) CampaignSummary(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + id, _ := strconv.ParseInt(vars["id"], 0, 64) + switch { + case r.Method == "GET": + cs, err := models.GetCampaignSummary(id, ctx.Get(r, "user_id").(int64)) + if err != nil { + if err == gorm.ErrRecordNotFound { + JSONResponse(w, models.Response{Success: false, Message: "Campaign not found"}, http.StatusNotFound) + } else { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) + } + log.Error(err) + return + } + JSONResponse(w, cs, http.StatusOK) + } +} + +// CampaignComplete effectively "ends" a campaign. +// Future phishing emails clicked will return a simple "404" page. +func (as *Server) CampaignComplete(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + id, _ := strconv.ParseInt(vars["id"], 0, 64) + switch { + case r.Method == "GET": + err := models.CompleteCampaign(id, ctx.Get(r, "user_id").(int64)) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error completing campaign"}, http.StatusInternalServerError) + return + } + JSONResponse(w, models.Response{Success: true, Message: "Campaign completed successfully!"}, http.StatusOK) + } +} diff --git a/controllers/api/group.go b/controllers/api/group.go new file mode 100644 index 00000000..26dcfb39 --- /dev/null +++ b/controllers/api/group.go @@ -0,0 +1,118 @@ +package api + +import ( + "encoding/json" + "net/http" + "strconv" + "time" + + ctx "github.com/gophish/gophish/context" + log "github.com/gophish/gophish/logger" + "github.com/gophish/gophish/models" + "github.com/gorilla/mux" + "github.com/jinzhu/gorm" +) + +// Groups returns a list of groups if requested via GET. +// If requested via POST, APIGroups creates a new group and returns a reference to it. +func (as *Server) Groups(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == "GET": + gs, err := models.GetGroups(ctx.Get(r, "user_id").(int64)) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "No groups found"}, http.StatusNotFound) + return + } + JSONResponse(w, gs, http.StatusOK) + //POST: Create a new group and return it as JSON + case r.Method == "POST": + g := models.Group{} + // Put the request into a group + err := json.NewDecoder(r.Body).Decode(&g) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Invalid JSON structure"}, http.StatusBadRequest) + return + } + _, err = models.GetGroupByName(g.Name, ctx.Get(r, "user_id").(int64)) + if err != gorm.ErrRecordNotFound { + JSONResponse(w, models.Response{Success: false, Message: "Group name already in use"}, http.StatusConflict) + return + } + g.ModifiedDate = time.Now().UTC() + g.UserId = ctx.Get(r, "user_id").(int64) + err = models.PostGroup(&g) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + JSONResponse(w, g, http.StatusCreated) + } +} + +// GroupsSummary returns a summary of the groups owned by the current user. +func (as *Server) GroupsSummary(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == "GET": + gs, err := models.GetGroupSummaries(ctx.Get(r, "user_id").(int64)) + if err != nil { + log.Error(err) + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) + return + } + JSONResponse(w, gs, http.StatusOK) + } +} + +// Group returns details about the requested group. +// If the group is not valid, Group returns null. +func (as *Server) Group(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + id, _ := strconv.ParseInt(vars["id"], 0, 64) + g, err := models.GetGroup(id, ctx.Get(r, "user_id").(int64)) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Group not found"}, http.StatusNotFound) + return + } + switch { + case r.Method == "GET": + JSONResponse(w, g, http.StatusOK) + case r.Method == "DELETE": + err = models.DeleteGroup(&g) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error deleting group"}, http.StatusInternalServerError) + return + } + JSONResponse(w, models.Response{Success: true, Message: "Group deleted successfully!"}, http.StatusOK) + case r.Method == "PUT": + // Change this to get from URL and uid (don't bother with id in r.Body) + g = models.Group{} + err = json.NewDecoder(r.Body).Decode(&g) + if g.Id != id { + JSONResponse(w, models.Response{Success: false, Message: "Error: /:id and group_id mismatch"}, http.StatusInternalServerError) + return + } + g.ModifiedDate = time.Now().UTC() + g.UserId = ctx.Get(r, "user_id").(int64) + err = models.PutGroup(&g) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + JSONResponse(w, g, http.StatusOK) + } +} + +// GroupSummary returns a summary of the groups owned by the current user. +func (as *Server) GroupSummary(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == "GET": + vars := mux.Vars(r) + id, _ := strconv.ParseInt(vars["id"], 0, 64) + g, err := models.GetGroupSummary(id, ctx.Get(r, "user_id").(int64)) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Group not found"}, http.StatusNotFound) + return + } + JSONResponse(w, g, http.StatusOK) + } +} diff --git a/controllers/api/import.go b/controllers/api/import.go new file mode 100644 index 00000000..f1b164d9 --- /dev/null +++ b/controllers/api/import.go @@ -0,0 +1,157 @@ +package api + +import ( + "bytes" + "crypto/tls" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + + "github.com/PuerkitoBio/goquery" + log "github.com/gophish/gophish/logger" + "github.com/gophish/gophish/models" + "github.com/gophish/gophish/util" + "github.com/jordan-wright/email" +) + +type cloneRequest struct { + URL string `json:"url"` + IncludeResources bool `json:"include_resources"` +} + +func (cr *cloneRequest) validate() error { + if cr.URL == "" { + return errors.New("No URL Specified") + } + return nil +} + +type cloneResponse struct { + HTML string `json:"html"` +} + +type emailResponse struct { + Text string `json:"text"` + HTML string `json:"html"` + Subject string `json:"subject"` +} + +// ImportGroup imports a CSV of group members +func (as *Server) ImportGroup(w http.ResponseWriter, r *http.Request) { + ts, err := util.ParseCSV(r) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error parsing CSV"}, http.StatusInternalServerError) + return + } + JSONResponse(w, ts, http.StatusOK) + return +} + +// ImportEmail allows for the importing of email. +// Returns a Message object +func (as *Server) ImportEmail(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + JSONResponse(w, models.Response{Success: false, Message: "Method not allowed"}, http.StatusBadRequest) + return + } + ir := struct { + Content string `json:"content"` + ConvertLinks bool `json:"convert_links"` + }{} + err := json.NewDecoder(r.Body).Decode(&ir) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error decoding JSON Request"}, http.StatusBadRequest) + return + } + e, err := email.NewEmailFromReader(strings.NewReader(ir.Content)) + if err != nil { + log.Error(err) + } + // If the user wants to convert links to point to + // the landing page, let's make it happen by changing up + // e.HTML + if ir.ConvertLinks { + d, err := goquery.NewDocumentFromReader(bytes.NewReader(e.HTML)) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + d.Find("a").Each(func(i int, a *goquery.Selection) { + a.SetAttr("href", "{{.URL}}") + }) + h, err := d.Html() + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) + return + } + e.HTML = []byte(h) + } + er := emailResponse{ + Subject: e.Subject, + Text: string(e.Text), + HTML: string(e.HTML), + } + JSONResponse(w, er, http.StatusOK) + return +} + +// ImportSite allows for the importing of HTML from a website +// Without "include_resources" set, it will merely place a "base" tag +// so that all resources can be loaded relative to the given URL. +func (as *Server) ImportSite(w http.ResponseWriter, r *http.Request) { + cr := cloneRequest{} + if r.Method != "POST" { + JSONResponse(w, models.Response{Success: false, Message: "Method not allowed"}, http.StatusBadRequest) + return + } + err := json.NewDecoder(r.Body).Decode(&cr) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error decoding JSON Request"}, http.StatusBadRequest) + return + } + if err = cr.validate(); err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + tr := &http.Transport{ + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: true, + }, + } + client := &http.Client{Transport: tr} + resp, err := client.Get(cr.URL) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + // Insert the base href tag to better handle relative resources + d, err := goquery.NewDocumentFromResponse(resp) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + // Assuming we don't want to include resources, we'll need a base href + if d.Find("head base").Length() == 0 { + d.Find("head").PrependHtml(fmt.Sprintf("", cr.URL)) + } + forms := d.Find("form") + forms.Each(func(i int, f *goquery.Selection) { + // We'll want to store where we got the form from + // (the current URL) + url := f.AttrOr("action", cr.URL) + if !strings.HasPrefix(url, "http") { + url = fmt.Sprintf("%s%s", cr.URL, url) + } + f.PrependHtml(fmt.Sprintf("", url)) + }) + h, err := d.Html() + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) + return + } + cs := cloneResponse{HTML: h} + JSONResponse(w, cs, http.StatusOK) + return +} diff --git a/controllers/api/page.go b/controllers/api/page.go new file mode 100644 index 00000000..bdebf5a7 --- /dev/null +++ b/controllers/api/page.go @@ -0,0 +1,91 @@ +package api + +import ( + "encoding/json" + "net/http" + "strconv" + "time" + + ctx "github.com/gophish/gophish/context" + log "github.com/gophish/gophish/logger" + "github.com/gophish/gophish/models" + "github.com/gorilla/mux" + "github.com/jinzhu/gorm" +) + +// Pages handles requests for the /api/pages/ endpoint +func (as *Server) Pages(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == "GET": + ps, err := models.GetPages(ctx.Get(r, "user_id").(int64)) + if err != nil { + log.Error(err) + } + JSONResponse(w, ps, http.StatusOK) + //POST: Create a new page and return it as JSON + case r.Method == "POST": + p := models.Page{} + // Put the request into a page + err := json.NewDecoder(r.Body).Decode(&p) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Invalid request"}, http.StatusBadRequest) + return + } + // Check to make sure the name is unique + _, err = models.GetPageByName(p.Name, ctx.Get(r, "user_id").(int64)) + if err != gorm.ErrRecordNotFound { + JSONResponse(w, models.Response{Success: false, Message: "Page name already in use"}, http.StatusConflict) + log.Error(err) + return + } + p.ModifiedDate = time.Now().UTC() + p.UserId = ctx.Get(r, "user_id").(int64) + err = models.PostPage(&p) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) + return + } + JSONResponse(w, p, http.StatusCreated) + } +} + +// Page contains functions to handle the GET'ing, DELETE'ing, and PUT'ing +// of a Page object +func (as *Server) Page(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + id, _ := strconv.ParseInt(vars["id"], 0, 64) + p, err := models.GetPage(id, ctx.Get(r, "user_id").(int64)) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Page not found"}, http.StatusNotFound) + return + } + switch { + case r.Method == "GET": + JSONResponse(w, p, http.StatusOK) + case r.Method == "DELETE": + err = models.DeletePage(id, ctx.Get(r, "user_id").(int64)) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error deleting page"}, http.StatusInternalServerError) + return + } + JSONResponse(w, models.Response{Success: true, Message: "Page Deleted Successfully"}, http.StatusOK) + case r.Method == "PUT": + p = models.Page{} + err = json.NewDecoder(r.Body).Decode(&p) + if err != nil { + log.Error(err) + } + if p.Id != id { + JSONResponse(w, models.Response{Success: false, Message: "/:id and /:page_id mismatch"}, http.StatusBadRequest) + return + } + p.ModifiedDate = time.Now().UTC() + p.UserId = ctx.Get(r, "user_id").(int64) + err = models.PutPage(&p) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error updating page: " + err.Error()}, http.StatusInternalServerError) + return + } + JSONResponse(w, p, http.StatusOK) + } +} diff --git a/controllers/api/reset.go b/controllers/api/reset.go new file mode 100644 index 00000000..1baf950d --- /dev/null +++ b/controllers/api/reset.go @@ -0,0 +1,24 @@ +package api + +import ( + "net/http" + + "github.com/gophish/gophish/auth" + ctx "github.com/gophish/gophish/context" + "github.com/gophish/gophish/models" +) + +// Reset (/api/reset) resets the currently authenticated user's API key +func (as *Server) Reset(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == "POST": + u := ctx.Get(r, "user").(models.User) + u.ApiKey = auth.GenerateSecureKey() + err := models.PutUser(&u) + if err != nil { + http.Error(w, "Error setting API Key", http.StatusInternalServerError) + } else { + JSONResponse(w, models.Response{Success: true, Message: "API Key successfully reset!", Data: u.ApiKey}, http.StatusOK) + } + } +} diff --git a/controllers/api/response.go b/controllers/api/response.go new file mode 100644 index 00000000..bf53014a --- /dev/null +++ b/controllers/api/response.go @@ -0,0 +1,22 @@ +package api + +import ( + "encoding/json" + "fmt" + "net/http" + + log "github.com/gophish/gophish/logger" +) + +// JSONResponse attempts to set the status code, c, and marshal the given interface, d, into a response that +// is written to the given ResponseWriter. +func JSONResponse(w http.ResponseWriter, d interface{}, c int) { + dj, err := json.MarshalIndent(d, "", " ") + if err != nil { + http.Error(w, "Error creating JSON response", http.StatusInternalServerError) + log.Error(err) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(c) + fmt.Fprintf(w, "%s", dj) +} diff --git a/controllers/api/server.go b/controllers/api/server.go new file mode 100644 index 00000000..ba605424 --- /dev/null +++ b/controllers/api/server.go @@ -0,0 +1,76 @@ +package api + +import ( + "net/http" + + mid "github.com/gophish/gophish/middleware" + "github.com/gophish/gophish/worker" + "github.com/gorilla/mux" +) + +// ServerOption is an option to apply to the API server. +type ServerOption func(*Server) + +// Server represents the routes and functionality of the Gophish API. +// It's not a server in the traditional sense, in that it isn't started and +// stopped. Rather, it's meant to be used as an http.Handler in the +// AdminServer. +type Server struct { + handler http.Handler + worker worker.Worker +} + +// NewServer returns a new instance of the API handler with the provided +// options applied. +func NewServer(options ...ServerOption) *Server { + defaultWorker, _ := worker.New() + as := &Server{ + worker: defaultWorker, + } + for _, opt := range options { + opt(as) + } + as.registerRoutes() + return as +} + +// WithWorker is an option that sets the background worker. +func WithWorker(w worker.Worker) ServerOption { + return func(as *Server) { + as.worker = w + } +} + +func (as *Server) registerRoutes() { + root := mux.NewRouter() + root = root.StrictSlash(true) + router := root.PathPrefix("/api/").Subrouter() + router.Use(mid.RequireAPIKey) + router.Use(mid.EnforceViewOnly) + router.HandleFunc("/reset", as.Reset) + router.HandleFunc("/campaigns/", as.Campaigns) + router.HandleFunc("/campaigns/summary", as.CampaignsSummary) + router.HandleFunc("/campaigns/{id:[0-9]+}", as.Campaign) + router.HandleFunc("/campaigns/{id:[0-9]+}/results", as.CampaignResults) + router.HandleFunc("/campaigns/{id:[0-9]+}/summary", as.CampaignSummary) + router.HandleFunc("/campaigns/{id:[0-9]+}/complete", as.CampaignComplete) + router.HandleFunc("/groups/", as.Groups) + router.HandleFunc("/groups/summary", as.GroupsSummary) + router.HandleFunc("/groups/{id:[0-9]+}", as.Group) + router.HandleFunc("/groups/{id:[0-9]+}/summary", as.GroupSummary) + router.HandleFunc("/templates/", as.Templates) + router.HandleFunc("/templates/{id:[0-9]+}", as.Template) + router.HandleFunc("/pages/", as.Pages) + router.HandleFunc("/pages/{id:[0-9]+}", as.Page) + router.HandleFunc("/smtp/", as.SendingProfiles) + router.HandleFunc("/smtp/{id:[0-9]+}", as.SendingProfile) + router.HandleFunc("/util/send_test_email", as.SendTestEmail) + router.HandleFunc("/import/group", as.ImportGroup) + router.HandleFunc("/import/email", as.ImportEmail) + router.HandleFunc("/import/site", as.ImportSite) + as.handler = router +} + +func (as *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + as.handler.ServeHTTP(w, r) +} diff --git a/controllers/api/smtp.go b/controllers/api/smtp.go new file mode 100644 index 00000000..2da33c93 --- /dev/null +++ b/controllers/api/smtp.go @@ -0,0 +1,96 @@ +package api + +import ( + "encoding/json" + "net/http" + "strconv" + "time" + + ctx "github.com/gophish/gophish/context" + log "github.com/gophish/gophish/logger" + "github.com/gophish/gophish/models" + "github.com/gorilla/mux" + "github.com/jinzhu/gorm" +) + +// SendingProfiles handles requests for the /api/smtp/ endpoint +func (as *Server) SendingProfiles(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == "GET": + ss, err := models.GetSMTPs(ctx.Get(r, "user_id").(int64)) + if err != nil { + log.Error(err) + } + JSONResponse(w, ss, http.StatusOK) + //POST: Create a new SMTP and return it as JSON + case r.Method == "POST": + s := models.SMTP{} + // Put the request into a page + err := json.NewDecoder(r.Body).Decode(&s) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Invalid request"}, http.StatusBadRequest) + return + } + // Check to make sure the name is unique + _, err = models.GetSMTPByName(s.Name, ctx.Get(r, "user_id").(int64)) + if err != gorm.ErrRecordNotFound { + JSONResponse(w, models.Response{Success: false, Message: "SMTP name already in use"}, http.StatusConflict) + log.Error(err) + return + } + s.ModifiedDate = time.Now().UTC() + s.UserId = ctx.Get(r, "user_id").(int64) + err = models.PostSMTP(&s) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) + return + } + JSONResponse(w, s, http.StatusCreated) + } +} + +// SendingProfile contains functions to handle the GET'ing, DELETE'ing, and PUT'ing +// of a SMTP object +func (as *Server) SendingProfile(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + id, _ := strconv.ParseInt(vars["id"], 0, 64) + s, err := models.GetSMTP(id, ctx.Get(r, "user_id").(int64)) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "SMTP not found"}, http.StatusNotFound) + return + } + switch { + case r.Method == "GET": + JSONResponse(w, s, http.StatusOK) + case r.Method == "DELETE": + err = models.DeleteSMTP(id, ctx.Get(r, "user_id").(int64)) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error deleting SMTP"}, http.StatusInternalServerError) + return + } + JSONResponse(w, models.Response{Success: true, Message: "SMTP Deleted Successfully"}, http.StatusOK) + case r.Method == "PUT": + s = models.SMTP{} + err = json.NewDecoder(r.Body).Decode(&s) + if err != nil { + log.Error(err) + } + if s.Id != id { + JSONResponse(w, models.Response{Success: false, Message: "/:id and /:smtp_id mismatch"}, http.StatusBadRequest) + return + } + err = s.Validate() + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + s.ModifiedDate = time.Now().UTC() + s.UserId = ctx.Get(r, "user_id").(int64) + err = models.PutSMTP(&s) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error updating page"}, http.StatusInternalServerError) + return + } + JSONResponse(w, s, http.StatusOK) + } +} diff --git a/controllers/api/template.go b/controllers/api/template.go new file mode 100644 index 00000000..da8cd90c --- /dev/null +++ b/controllers/api/template.go @@ -0,0 +1,97 @@ +package api + +import ( + "encoding/json" + "net/http" + "strconv" + "time" + + ctx "github.com/gophish/gophish/context" + log "github.com/gophish/gophish/logger" + "github.com/gophish/gophish/models" + "github.com/gorilla/mux" + "github.com/jinzhu/gorm" +) + +// Templates handles the functionality for the /api/templates endpoint +func (as *Server) Templates(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == "GET": + ts, err := models.GetTemplates(ctx.Get(r, "user_id").(int64)) + if err != nil { + log.Error(err) + } + JSONResponse(w, ts, http.StatusOK) + //POST: Create a new template and return it as JSON + case r.Method == "POST": + t := models.Template{} + // Put the request into a template + err := json.NewDecoder(r.Body).Decode(&t) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Invalid JSON structure"}, http.StatusBadRequest) + return + } + _, err = models.GetTemplateByName(t.Name, ctx.Get(r, "user_id").(int64)) + if err != gorm.ErrRecordNotFound { + JSONResponse(w, models.Response{Success: false, Message: "Template name already in use"}, http.StatusConflict) + return + } + t.ModifiedDate = time.Now().UTC() + t.UserId = ctx.Get(r, "user_id").(int64) + err = models.PostTemplate(&t) + if err == models.ErrTemplateNameNotSpecified { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + if err == models.ErrTemplateMissingParameter { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error inserting template into database"}, http.StatusInternalServerError) + log.Error(err) + return + } + JSONResponse(w, t, http.StatusCreated) + } +} + +// Template handles the functions for the /api/templates/:id endpoint +func (as *Server) Template(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + id, _ := strconv.ParseInt(vars["id"], 0, 64) + t, err := models.GetTemplate(id, ctx.Get(r, "user_id").(int64)) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Template not found"}, http.StatusNotFound) + return + } + switch { + case r.Method == "GET": + JSONResponse(w, t, http.StatusOK) + case r.Method == "DELETE": + err = models.DeleteTemplate(id, ctx.Get(r, "user_id").(int64)) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error deleting template"}, http.StatusInternalServerError) + return + } + JSONResponse(w, models.Response{Success: true, Message: "Template deleted successfully!"}, http.StatusOK) + case r.Method == "PUT": + t = models.Template{} + err = json.NewDecoder(r.Body).Decode(&t) + if err != nil { + log.Error(err) + } + if t.Id != id { + JSONResponse(w, models.Response{Success: false, Message: "Error: /:id and template_id mismatch"}, http.StatusBadRequest) + return + } + t.ModifiedDate = time.Now().UTC() + t.UserId = ctx.Get(r, "user_id").(int64) + err = models.PutTemplate(&t) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + JSONResponse(w, t, http.StatusOK) + } +} diff --git a/controllers/api/util.go b/controllers/api/util.go new file mode 100644 index 00000000..0f6c215c --- /dev/null +++ b/controllers/api/util.go @@ -0,0 +1,122 @@ +package api + +import ( + "encoding/json" + "net/http" + + ctx "github.com/gophish/gophish/context" + log "github.com/gophish/gophish/logger" + "github.com/gophish/gophish/models" + "github.com/jinzhu/gorm" + "github.com/sirupsen/logrus" +) + +// SendTestEmail sends a test email using the template name +// and Target given. +func (as *Server) SendTestEmail(w http.ResponseWriter, r *http.Request) { + s := &models.EmailRequest{ + ErrorChan: make(chan error), + UserId: ctx.Get(r, "user_id").(int64), + } + if r.Method != "POST" { + JSONResponse(w, models.Response{Success: false, Message: "Method not allowed"}, http.StatusBadRequest) + return + } + err := json.NewDecoder(r.Body).Decode(s) + if err != nil { + JSONResponse(w, models.Response{Success: false, Message: "Error decoding JSON Request"}, http.StatusBadRequest) + return + } + + storeRequest := false + + // If a Template is not specified use a default + if s.Template.Name == "" { + //default message body + text := "It works!\n\nThis is an email letting you know that your gophish\nconfiguration was successful.\n" + + "Here are the details:\n\nWho you sent from: {{.From}}\n\nWho you sent to: \n" + + "{{if .FirstName}} First Name: {{.FirstName}}\n{{end}}" + + "{{if .LastName}} Last Name: {{.LastName}}\n{{end}}" + + "{{if .Position}} Position: {{.Position}}\n{{end}}" + + "\nNow go send some phish!" + t := models.Template{ + Subject: "Default Email from Gophish", + Text: text, + } + s.Template = t + } else { + // Get the Template requested by name + s.Template, err = models.GetTemplateByName(s.Template.Name, s.UserId) + if err == gorm.ErrRecordNotFound { + log.WithFields(logrus.Fields{ + "template": s.Template.Name, + }).Error("Template does not exist") + JSONResponse(w, models.Response{Success: false, Message: models.ErrTemplateNotFound.Error()}, http.StatusBadRequest) + return + } else if err != nil { + log.Error(err) + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + s.TemplateId = s.Template.Id + // We'll only save the test request to the database if there is a + // user-specified template to use. + storeRequest = true + } + + if s.Page.Name != "" { + s.Page, err = models.GetPageByName(s.Page.Name, s.UserId) + if err == gorm.ErrRecordNotFound { + log.WithFields(logrus.Fields{ + "page": s.Page.Name, + }).Error("Page does not exist") + JSONResponse(w, models.Response{Success: false, Message: models.ErrPageNotFound.Error()}, http.StatusBadRequest) + return + } else if err != nil { + log.Error(err) + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + s.PageId = s.Page.Id + } + + // If a complete sending profile is provided use it + if err := s.SMTP.Validate(); err != nil { + // Otherwise get the SMTP requested by name + smtp, lookupErr := models.GetSMTPByName(s.SMTP.Name, s.UserId) + // If the Sending Profile doesn't exist, let's err on the side + // of caution and assume that the validation failure was more important. + if lookupErr != nil { + log.Error(err) + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + s.SMTP = smtp + } + s.FromAddress = s.SMTP.FromAddress + + // Validate the given request + if err = s.Validate(); err != nil { + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest) + return + } + + // Store the request if this wasn't the default template + if storeRequest { + err = models.PostEmailRequest(s) + if err != nil { + log.Error(err) + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) + return + } + } + // Send the test email + err = as.worker.SendTestEmail(s) + if err != nil { + log.Error(err) + JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError) + return + } + JSONResponse(w, models.Response{Success: true, Message: "Email Sent"}, http.StatusOK) + return +} diff --git a/controllers/api_test.go b/controllers/api_test.go index 9f9e26d9..de0a7366 100644 --- a/controllers/api_test.go +++ b/controllers/api_test.go @@ -1,10 +1,6 @@ package controllers import ( - "bytes" - "encoding/json" - "fmt" - "net/http" "net/http/httptest" "os" "testing" @@ -103,52 +99,6 @@ func (s *ControllersSuite) SetupTest() { c.UpdateStatus(models.CampaignEmailsSent) } -func (s *ControllersSuite) TestRequireAPIKey() { - resp, err := http.Post(fmt.Sprintf("%s/api/import/site", s.adminServer.URL), "application/json", nil) - s.Nil(err) - defer resp.Body.Close() - s.Equal(resp.StatusCode, http.StatusUnauthorized) -} - -func (s *ControllersSuite) TestInvalidAPIKey() { - resp, err := http.Get(fmt.Sprintf("%s/api/groups/?api_key=%s", s.adminServer.URL, "bogus-api-key")) - s.Nil(err) - defer resp.Body.Close() - s.Equal(resp.StatusCode, http.StatusUnauthorized) -} - -func (s *ControllersSuite) TestBearerToken() { - req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/groups/", s.adminServer.URL), nil) - s.Nil(err) - req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", s.apiKey)) - resp, err := http.DefaultClient.Do(req) - s.Nil(err) - defer resp.Body.Close() - s.Equal(resp.StatusCode, http.StatusOK) -} - -func (s *ControllersSuite) TestSiteImportBaseHref() { - h := "" - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintln(w, h) - })) - hr := fmt.Sprintf("\n", ts.URL) - defer ts.Close() - resp, err := http.Post(fmt.Sprintf("%s/api/import/site?api_key=%s", s.adminServer.URL, s.apiKey), "application/json", - bytes.NewBuffer([]byte(fmt.Sprintf(` - { - "url" : "%s", - "include_resources" : false - } - `, ts.URL)))) - s.Nil(err) - defer resp.Body.Close() - cs := cloneResponse{} - err = json.NewDecoder(resp.Body).Decode(&cs) - s.Nil(err) - s.Equal(cs.HTML, hr) -} - func (s *ControllersSuite) TearDownSuite() { // Tear down the admin and phishing servers s.adminServer.Close() diff --git a/controllers/phish.go b/controllers/phish.go index e2ff7870..a41708bc 100644 --- a/controllers/phish.go +++ b/controllers/phish.go @@ -13,6 +13,7 @@ import ( "github.com/NYTimes/gziphandler" "github.com/gophish/gophish/config" ctx "github.com/gophish/gophish/context" + "github.com/gophish/gophish/controllers/api" log "github.com/gophish/gophish/logger" "github.com/gophish/gophish/models" "github.com/gophish/gophish/util" @@ -299,7 +300,7 @@ func (ps *PhishingServer) TransparencyHandler(w http.ResponseWriter, r *http.Req SendDate: rs.SendDate, ContactAddress: ps.contactAddress, } - JSONResponse(w, tr, http.StatusOK) + api.JSONResponse(w, tr, http.StatusOK) } // setupContext handles some of the administrative work around receiving a new diff --git a/controllers/route.go b/controllers/route.go index 9adc3e4f..fd8beaa2 100644 --- a/controllers/route.go +++ b/controllers/route.go @@ -12,6 +12,7 @@ import ( "github.com/gophish/gophish/auth" "github.com/gophish/gophish/config" ctx "github.com/gophish/gophish/context" + "github.com/gophish/gophish/controllers/api" log "github.com/gophish/gophish/logger" mid "github.com/gophish/gophish/middleware" "github.com/gophish/gophish/models" @@ -106,31 +107,8 @@ func (as *AdminServer) registerRoutes() { router.HandleFunc("/settings", Use(as.Settings, mid.RequireLogin)) router.HandleFunc("/register", Use(as.Register, mid.RequireLogin, mid.RequirePermission(models.PermissionModifySystem))) // Create the API routes - api := router.PathPrefix("/api").Subrouter() - api = api.StrictSlash(true) - api.Use(mid.RequireAPIKey) - api.Use(mid.EnforceViewOnly) - api.HandleFunc("/reset", as.APIReset) - api.HandleFunc("/campaigns/", as.APICampaigns) - api.HandleFunc("/campaigns/summary", as.APICampaignsSummary) - api.HandleFunc("/campaigns/{id:[0-9]+}", as.APICampaign) - api.HandleFunc("/campaigns/{id:[0-9]+}/results", as.APICampaignResults) - api.HandleFunc("/campaigns/{id:[0-9]+}/summary", as.APICampaignSummary) - api.HandleFunc("/campaigns/{id:[0-9]+}/complete", as.APICampaignComplete) - api.HandleFunc("/groups/", as.APIGroups) - api.HandleFunc("/groups/summary", as.APIGroupsSummary) - api.HandleFunc("/groups/{id:[0-9]+}", as.APIGroup) - api.HandleFunc("/groups/{id:[0-9]+}/summary", as.APIGroupSummary) - api.HandleFunc("/templates/", as.APITemplates) - api.HandleFunc("/templates/{id:[0-9]+}", as.APITemplate) - api.HandleFunc("/pages/", as.APIPages) - api.HandleFunc("/pages/{id:[0-9]+}", as.APIPage) - api.HandleFunc("/smtp/", as.APISendingProfiles) - api.HandleFunc("/smtp/{id:[0-9]+}", as.APISendingProfile) - api.HandleFunc("/util/send_test_email", as.APISendTestEmail) - api.HandleFunc("/import/group", as.APIImportGroup) - api.HandleFunc("/import/email", as.APIImportEmail) - api.HandleFunc("/import/site", as.APIImportSite) + api := api.NewServer(api.WithWorker(as.worker)) + router.PathPrefix("/api/").Handler(api) // Setup static file serving router.PathPrefix("/").Handler(http.FileServer(unindexed.Dir("./static/"))) @@ -280,16 +258,16 @@ func (as *AdminServer) Settings(w http.ResponseWriter, r *http.Request) { if err == auth.ErrInvalidPassword { msg.Message = "Invalid Password" msg.Success = false - JSONResponse(w, msg, http.StatusBadRequest) + api.JSONResponse(w, msg, http.StatusBadRequest) return } if err != nil { msg.Message = err.Error() msg.Success = false - JSONResponse(w, msg, http.StatusBadRequest) + api.JSONResponse(w, msg, http.StatusBadRequest) return } - JSONResponse(w, msg, http.StatusOK) + api.JSONResponse(w, msg, http.StatusOK) } } diff --git a/middleware/middleware_test.go b/middleware/middleware_test.go index b17b6351..30752b01 100644 --- a/middleware/middleware_test.go +++ b/middleware/middleware_test.go @@ -1,6 +1,7 @@ package middleware import ( + "fmt" "net/http" "net/http/httptest" "testing" @@ -17,6 +18,7 @@ var successHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Reques type MiddlewareSuite struct { suite.Suite + apiKey string } func (s *MiddlewareSuite) SetupSuite() { @@ -29,6 +31,10 @@ func (s *MiddlewareSuite) SetupSuite() { if err != nil { s.T().Fatalf("Failed creating database: %v", err) } + // Get the API key to use for these tests + u, err := models.GetUser(1) + s.Nil(err) + s.apiKey = u.ApiKey } // MiddlewarePermissionTest maps an expected HTTP Method to an expected HTTP @@ -99,6 +105,35 @@ func (s *MiddlewareSuite) TestRequirePermission() { } } +func (s *MiddlewareSuite) TestRequireAPIKey() { + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + // Test that making a request without an API key is denied + RequireAPIKey(successHandler).ServeHTTP(response, req) + s.Equal(response.Code, http.StatusUnauthorized) +} + +func (s *MiddlewareSuite) TestInvalidAPIKey() { + req := httptest.NewRequest(http.MethodGet, "/", nil) + query := req.URL.Query() + query.Set("api_key", "bogus-api-key") + req.URL.RawQuery = query.Encode() + req.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + RequireAPIKey(successHandler).ServeHTTP(response, req) + s.Equal(response.Code, http.StatusUnauthorized) +} + +func (s *MiddlewareSuite) TestBearerToken() { + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", s.apiKey)) + req.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + RequireAPIKey(successHandler).ServeHTTP(response, req) + s.Equal(response.Code, http.StatusOK) +} + func TestMiddlewareSuite(t *testing.T) { suite.Run(t, new(MiddlewareSuite)) } From e634cbd6705a49feaabdec9d1d921ba5b9374713 Mon Sep 17 00:00:00 2001 From: Jordan Wright Date: Tue, 26 Mar 2019 22:19:18 -0500 Subject: [PATCH 02/27] Moving api_test.go to controllers_test.go --- controllers/controllers_test.go | 110 ++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 controllers/controllers_test.go diff --git a/controllers/controllers_test.go b/controllers/controllers_test.go new file mode 100644 index 00000000..de0a7366 --- /dev/null +++ b/controllers/controllers_test.go @@ -0,0 +1,110 @@ +package controllers + +import ( + "net/http/httptest" + "os" + "testing" + + "github.com/gophish/gophish/config" + "github.com/gophish/gophish/models" + "github.com/stretchr/testify/suite" +) + +// ControllersSuite is a suite of tests to cover API related functions +type ControllersSuite struct { + suite.Suite + apiKey string + config *config.Config + adminServer *httptest.Server + phishServer *httptest.Server +} + +func (s *ControllersSuite) SetupSuite() { + conf := &config.Config{ + DBName: "sqlite3", + DBPath: ":memory:", + MigrationsPath: "../db/db_sqlite3/migrations/", + } + err := models.Setup(conf) + if err != nil { + s.T().Fatalf("Failed creating database: %v", err) + } + s.config = conf + s.Nil(err) + // Setup the admin server for use in testing + s.adminServer = httptest.NewUnstartedServer(NewAdminServer(s.config.AdminConf).server.Handler) + s.adminServer.Config.Addr = s.config.AdminConf.ListenURL + s.adminServer.Start() + // Get the API key to use for these tests + u, err := models.GetUser(1) + s.Nil(err) + s.apiKey = u.ApiKey + // Start the phishing server + s.phishServer = httptest.NewUnstartedServer(NewPhishingServer(s.config.PhishConf).server.Handler) + s.phishServer.Config.Addr = s.config.PhishConf.ListenURL + s.phishServer.Start() + // Move our cwd up to the project root for help with resolving + // static assets + err = os.Chdir("../") + s.Nil(err) +} + +func (s *ControllersSuite) TearDownTest() { + campaigns, _ := models.GetCampaigns(1) + for _, campaign := range campaigns { + models.DeleteCampaign(campaign.Id) + } +} + +func (s *ControllersSuite) SetupTest() { + // Add a group + group := models.Group{Name: "Test Group"} + group.Targets = []models.Target{ + models.Target{BaseRecipient: models.BaseRecipient{Email: "test1@example.com", FirstName: "First", LastName: "Example"}}, + models.Target{BaseRecipient: models.BaseRecipient{Email: "test2@example.com", FirstName: "Second", LastName: "Example"}}, + } + group.UserId = 1 + models.PostGroup(&group) + + // Add a template + t := models.Template{Name: "Test Template"} + t.Subject = "Test subject" + t.Text = "Text text" + t.HTML = "Test" + t.UserId = 1 + models.PostTemplate(&t) + + // Add a landing page + p := models.Page{Name: "Test Page"} + p.HTML = "Test" + p.UserId = 1 + models.PostPage(&p) + + // Add a sending profile + smtp := models.SMTP{Name: "Test Page"} + smtp.UserId = 1 + smtp.Host = "example.com" + smtp.FromAddress = "test@test.com" + models.PostSMTP(&smtp) + + // Setup and "launch" our campaign + // Set the status such that no emails are attempted + c := models.Campaign{Name: "Test campaign"} + c.UserId = 1 + c.Template = t + c.Page = p + c.SMTP = smtp + c.Groups = []models.Group{group} + models.PostCampaign(&c, c.UserId) + c.UpdateStatus(models.CampaignEmailsSent) +} + +func (s *ControllersSuite) TearDownSuite() { + // Tear down the admin and phishing servers + s.adminServer.Close() + s.phishServer.Close() +} + +func TestControllerSuite(t *testing.T) { + suite.Run(t, new(ControllersSuite)) +} From 5c753465d1d3e836539663331c03b0136ee3682e Mon Sep 17 00:00:00 2001 From: Jordan Wright Date: Tue, 26 Mar 2019 22:20:35 -0500 Subject: [PATCH 03/27] Quick fix: Forgot to remove api_test.go --- controllers/api_test.go | 110 ---------------------------------------- 1 file changed, 110 deletions(-) delete mode 100644 controllers/api_test.go diff --git a/controllers/api_test.go b/controllers/api_test.go deleted file mode 100644 index de0a7366..00000000 --- a/controllers/api_test.go +++ /dev/null @@ -1,110 +0,0 @@ -package controllers - -import ( - "net/http/httptest" - "os" - "testing" - - "github.com/gophish/gophish/config" - "github.com/gophish/gophish/models" - "github.com/stretchr/testify/suite" -) - -// ControllersSuite is a suite of tests to cover API related functions -type ControllersSuite struct { - suite.Suite - apiKey string - config *config.Config - adminServer *httptest.Server - phishServer *httptest.Server -} - -func (s *ControllersSuite) SetupSuite() { - conf := &config.Config{ - DBName: "sqlite3", - DBPath: ":memory:", - MigrationsPath: "../db/db_sqlite3/migrations/", - } - err := models.Setup(conf) - if err != nil { - s.T().Fatalf("Failed creating database: %v", err) - } - s.config = conf - s.Nil(err) - // Setup the admin server for use in testing - s.adminServer = httptest.NewUnstartedServer(NewAdminServer(s.config.AdminConf).server.Handler) - s.adminServer.Config.Addr = s.config.AdminConf.ListenURL - s.adminServer.Start() - // Get the API key to use for these tests - u, err := models.GetUser(1) - s.Nil(err) - s.apiKey = u.ApiKey - // Start the phishing server - s.phishServer = httptest.NewUnstartedServer(NewPhishingServer(s.config.PhishConf).server.Handler) - s.phishServer.Config.Addr = s.config.PhishConf.ListenURL - s.phishServer.Start() - // Move our cwd up to the project root for help with resolving - // static assets - err = os.Chdir("../") - s.Nil(err) -} - -func (s *ControllersSuite) TearDownTest() { - campaigns, _ := models.GetCampaigns(1) - for _, campaign := range campaigns { - models.DeleteCampaign(campaign.Id) - } -} - -func (s *ControllersSuite) SetupTest() { - // Add a group - group := models.Group{Name: "Test Group"} - group.Targets = []models.Target{ - models.Target{BaseRecipient: models.BaseRecipient{Email: "test1@example.com", FirstName: "First", LastName: "Example"}}, - models.Target{BaseRecipient: models.BaseRecipient{Email: "test2@example.com", FirstName: "Second", LastName: "Example"}}, - } - group.UserId = 1 - models.PostGroup(&group) - - // Add a template - t := models.Template{Name: "Test Template"} - t.Subject = "Test subject" - t.Text = "Text text" - t.HTML = "Test" - t.UserId = 1 - models.PostTemplate(&t) - - // Add a landing page - p := models.Page{Name: "Test Page"} - p.HTML = "Test" - p.UserId = 1 - models.PostPage(&p) - - // Add a sending profile - smtp := models.SMTP{Name: "Test Page"} - smtp.UserId = 1 - smtp.Host = "example.com" - smtp.FromAddress = "test@test.com" - models.PostSMTP(&smtp) - - // Setup and "launch" our campaign - // Set the status such that no emails are attempted - c := models.Campaign{Name: "Test campaign"} - c.UserId = 1 - c.Template = t - c.Page = p - c.SMTP = smtp - c.Groups = []models.Group{group} - models.PostCampaign(&c, c.UserId) - c.UpdateStatus(models.CampaignEmailsSent) -} - -func (s *ControllersSuite) TearDownSuite() { - // Tear down the admin and phishing servers - s.adminServer.Close() - s.phishServer.Close() -} - -func TestControllerSuite(t *testing.T) { - suite.Run(t, new(ControllersSuite)) -} From af4c8f61da6c94e9ac2f1d1438bd7c7ac134d304 Mon Sep 17 00:00:00 2001 From: gfrancqu Date: Thu, 28 Mar 2019 04:48:31 +0100 Subject: [PATCH 04/27] Wait for db (#1402) Added a loop that attempts to connect to the configured database. --- models/models.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/models/models.go b/models/models.go index 3b1c82f9..1ef38a47 100644 --- a/models/models.go +++ b/models/models.go @@ -4,6 +4,7 @@ import ( "crypto/rand" "fmt" "io" + "time" "bitbucket.org/liamstask/goose/lib/goose" @@ -17,6 +18,8 @@ import ( var db *gorm.DB var conf *config.Config +const MaxDatabaseConnectionAttempts int = 10 + const ( CampaignInProgress string = "In progress" CampaignQueued string = "Queued" @@ -94,7 +97,20 @@ func Setup(c *config.Config) error { return err } // Open our database connection - db, err = gorm.Open(conf.DBName, conf.DBPath) + i := 0 + for { + db, err = gorm.Open(conf.DBName, conf.DBPath) + if err == nil { + break + } + if err != nil && i >= MaxDatabaseConnectionAttempts { + log.Error(err) + return err + } + i += 1 + log.Warn("waiting for database to be up...") + time.Sleep(5 * time.Second) + } db.LogMode(false) db.SetLogger(log.Logger) db.DB().SetMaxOpenConns(1) From 2eb4f4d348aa4554a23bf5e7e5578e7b34a026f5 Mon Sep 17 00:00:00 2001 From: Jordan Wright Date: Sun, 21 Apr 2019 15:21:36 -0500 Subject: [PATCH 05/27] Move API key to Bearer Token (#1439) * Moved api_key from URL to authorization header in requests (#1434) * Fixing some minor formatting and rebuilding minified JS --- static/js/dist/app/gophish.min.js | 2 +- static/js/dist/app/users.min.js | 2 +- static/js/src/app/gophish.js | 7 +++++-- static/js/src/app/users.js | 5 ++++- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/static/js/dist/app/gophish.min.js b/static/js/dist/app/gophish.min.js index d8b9cb99..526ae20d 100644 --- a/static/js/dist/app/gophish.min.js +++ b/static/js/dist/app/gophish.min.js @@ -1 +1 @@ -function errorFlash(e){$("#flashes").empty(),$("#flashes").append('
'+e+"
")}function successFlash(e){$("#flashes").empty(),$("#flashes").append('
'+e+"
")}function modalError(e){$("#modal\\.flashes").empty().append('
'+e+"
")}function query(e,t,n,r){return $.ajax({url:"/api"+e+"?api_key="+user.api_key,async:r,method:t,data:JSON.stringify(n),dataType:"json",contentType:"application/json"})}function escapeHtml(e){return $("
").text(e).html()}function unescapeHtml(e){return $("
").html(e).text()}var capitalize=function(e){return e.charAt(0).toUpperCase()+e.slice(1)},api={campaigns:{get:function(){return query("/campaigns/","GET",{},!1)},post:function(e){return query("/campaigns/","POST",e,!1)},summary:function(){return query("/campaigns/summary","GET",{},!1)}},campaignId:{get:function(e){return query("/campaigns/"+e,"GET",{},!0)},delete:function(e){return query("/campaigns/"+e,"DELETE",{},!1)},results:function(e){return query("/campaigns/"+e+"/results","GET",{},!0)},complete:function(e){return query("/campaigns/"+e+"/complete","GET",{},!0)},summary:function(e){return query("/campaigns/"+e+"/summary","GET",{},!0)}},groups:{get:function(){return query("/groups/","GET",{},!1)},post:function(e){return query("/groups/","POST",e,!1)},summary:function(){return query("/groups/summary","GET",{},!0)}},groupId:{get:function(e){return query("/groups/"+e,"GET",{},!1)},put:function(e){return query("/groups/"+e.id,"PUT",e,!1)},delete:function(e){return query("/groups/"+e,"DELETE",{},!1)}},templates:{get:function(){return query("/templates/","GET",{},!1)},post:function(e){return query("/templates/","POST",e,!1)}},templateId:{get:function(e){return query("/templates/"+e,"GET",{},!1)},put:function(e){return query("/templates/"+e.id,"PUT",e,!1)},delete:function(e){return query("/templates/"+e,"DELETE",{},!1)}},pages:{get:function(){return query("/pages/","GET",{},!1)},post:function(e){return query("/pages/","POST",e,!1)}},pageId:{get:function(e){return query("/pages/"+e,"GET",{},!1)},put:function(e){return query("/pages/"+e.id,"PUT",e,!1)},delete:function(e){return query("/pages/"+e,"DELETE",{},!1)}},SMTP:{get:function(){return query("/smtp/","GET",{},!1)},post:function(e){return query("/smtp/","POST",e,!1)}},SMTPId:{get:function(e){return query("/smtp/"+e,"GET",{},!1)},put:function(e){return query("/smtp/"+e.id,"PUT",e,!1)},delete:function(e){return query("/smtp/"+e,"DELETE",{},!1)}},import_email:function(e){return query("/import/email","POST",e,!1)},clone_site:function(e){return query("/import/site","POST",e,!1)},send_test_email:function(e){return query("/util/send_test_email","POST",e,!0)},reset:function(){return query("/reset","POST",{},!0)}};$(document).ready(function(){var e=location.pathname;$(".nav-sidebar li").each(function(){var t=$(this);t.find("a").attr("href")===e&&t.addClass("active")}),$.fn.dataTable.moment("MMMM Do YYYY, h:mm:ss a"),$('[data-toggle="tooltip"]').tooltip()}); \ No newline at end of file +function errorFlash(e){$("#flashes").empty(),$("#flashes").append('
'+e+"
")}function successFlash(e){$("#flashes").empty(),$("#flashes").append('
'+e+"
")}function modalError(e){$("#modal\\.flashes").empty().append('
'+e+"
")}function query(e,t,n,r){return $.ajax({url:"/api"+e,async:r,method:t,data:JSON.stringify(n),dataType:"json",contentType:"application/json",beforeSend:function(e){e.setRequestHeader("Authorization","Bearer "+user.api_key)}})}function escapeHtml(e){return $("
").text(e).html()}function unescapeHtml(e){return $("
").html(e).text()}var capitalize=function(e){return e.charAt(0).toUpperCase()+e.slice(1)},api={campaigns:{get:function(){return query("/campaigns/","GET",{},!1)},post:function(e){return query("/campaigns/","POST",e,!1)},summary:function(){return query("/campaigns/summary","GET",{},!1)}},campaignId:{get:function(e){return query("/campaigns/"+e,"GET",{},!0)},delete:function(e){return query("/campaigns/"+e,"DELETE",{},!1)},results:function(e){return query("/campaigns/"+e+"/results","GET",{},!0)},complete:function(e){return query("/campaigns/"+e+"/complete","GET",{},!0)},summary:function(e){return query("/campaigns/"+e+"/summary","GET",{},!0)}},groups:{get:function(){return query("/groups/","GET",{},!1)},post:function(e){return query("/groups/","POST",e,!1)},summary:function(){return query("/groups/summary","GET",{},!0)}},groupId:{get:function(e){return query("/groups/"+e,"GET",{},!1)},put:function(e){return query("/groups/"+e.id,"PUT",e,!1)},delete:function(e){return query("/groups/"+e,"DELETE",{},!1)}},templates:{get:function(){return query("/templates/","GET",{},!1)},post:function(e){return query("/templates/","POST",e,!1)}},templateId:{get:function(e){return query("/templates/"+e,"GET",{},!1)},put:function(e){return query("/templates/"+e.id,"PUT",e,!1)},delete:function(e){return query("/templates/"+e,"DELETE",{},!1)}},pages:{get:function(){return query("/pages/","GET",{},!1)},post:function(e){return query("/pages/","POST",e,!1)}},pageId:{get:function(e){return query("/pages/"+e,"GET",{},!1)},put:function(e){return query("/pages/"+e.id,"PUT",e,!1)},delete:function(e){return query("/pages/"+e,"DELETE",{},!1)}},SMTP:{get:function(){return query("/smtp/","GET",{},!1)},post:function(e){return query("/smtp/","POST",e,!1)}},SMTPId:{get:function(e){return query("/smtp/"+e,"GET",{},!1)},put:function(e){return query("/smtp/"+e.id,"PUT",e,!1)},delete:function(e){return query("/smtp/"+e,"DELETE",{},!1)}},import_email:function(e){return query("/import/email","POST",e,!1)},clone_site:function(e){return query("/import/site","POST",e,!1)},send_test_email:function(e){return query("/util/send_test_email","POST",e,!0)},reset:function(){return query("/reset","POST",{},!0)}};$(document).ready(function(){var e=location.pathname;$(".nav-sidebar li").each(function(){var t=$(this);t.find("a").attr("href")===e&&t.addClass("active")}),$.fn.dataTable.moment("MMMM Do YYYY, h:mm:ss a"),$('[data-toggle="tooltip"]').tooltip()}); \ No newline at end of file diff --git a/static/js/dist/app/users.min.js b/static/js/dist/app/users.min.js index 300f6acd..dc7d028f 100644 --- a/static/js/dist/app/users.min.js +++ b/static/js/dist/app/users.min.js @@ -1 +1 @@ -function save(e){var a=[];$.each($("#targetsTable").DataTable().rows().data(),function(e,t){a.push({first_name:unescapeHtml(t[0]),last_name:unescapeHtml(t[1]),email:unescapeHtml(t[2]),position:unescapeHtml(t[3])})});var t={name:$("#name").val(),targets:a};-1!=e?(t.id=e,api.groupId.put(t).success(function(e){successFlash("Group updated successfully!"),load(),dismiss(),$("#modal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)})):api.groups.post(t).success(function(e){successFlash("Group added successfully!"),load(),dismiss(),$("#modal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)})}function dismiss(){$("#targetsTable").dataTable().DataTable().clear().draw(),$("#name").val(""),$("#modal\\.flashes").empty()}function edit(e){if(targets=$("#targetsTable").dataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]}),$("#modalSubmit").unbind("click").click(function(){save(e)}),-1==e);else api.groupId.get(e).success(function(e){$("#name").val(e.name),$.each(e.targets,function(e,a){targets.DataTable().row.add([escapeHtml(a.first_name),escapeHtml(a.last_name),escapeHtml(a.email),escapeHtml(a.position),'']).draw()})}).error(function(){errorFlash("Error fetching group")});$("#csvupload").fileupload({url:"/api/import/group?api_key="+user.api_key,dataType:"json",add:function(e,a){$("#modal\\.flashes").empty();var t=/(csv|txt)$/i,s=a.originalFiles[0].name;if(s&&!t.test(s.split(".").pop()))return modalError("Unsupported file extension (use .csv or .txt)"),!1;a.submit()},done:function(e,a){$.each(a.result,function(e,a){addTarget(a.first_name,a.last_name,a.email,a.position)}),targets.DataTable().draw()}})}function addTarget(e,a,t,s){var o=escapeHtml(t).toLowerCase(),r=[escapeHtml(e),escapeHtml(a),o,escapeHtml(s),''],n=targets.DataTable(),i=n.column(2,{order:"index"}).data().indexOf(o);i>=0?n.row(i,{order:"index"}).data(r):n.row.add(r)}function load(){$("#groupTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.groups.summary().success(function(e){if($("#loading").hide(),e.total>0){groups=e.groups,$("#emptyMessage").hide(),$("#groupTable").show();var a=$("#groupTable").DataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]});a.clear(),$.each(groups,function(e,t){a.row.add([escapeHtml(t.name),escapeHtml(t.num_targets),moment(t.modified_date).format("MMMM Do YYYY, h:mm:ss a"),"
"]).draw()})}else $("#emptyMessage").show()}).error(function(){errorFlash("Error fetching groups")})}var groups=[],downloadCSVTemplate=function(){var e=[{"First Name":"Example","Last Name":"User",Email:"foobar@example.com",Position:"Systems Administrator"}],a=Papa.unparse(e,{}),t=new Blob([a],{type:"text/csv;charset=utf-8;"});if(navigator.msSaveBlob)navigator.msSaveBlob(t,"group_template.csv");else{var s=window.URL.createObjectURL(t),o=document.createElement("a");o.href=s,o.setAttribute("download","group_template.csv"),document.body.appendChild(o),o.click(),document.body.removeChild(o)}},deleteGroup=function(e){var a=groups.find(function(a){return a.id===e});a&&swal({title:"Are you sure?",text:"This will delete the group. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(a.name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.groupId.delete(e).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Group Deleted!","This group has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};$(document).ready(function(){load(),$("#targetForm").submit(function(){return addTarget($("#firstName").val(),$("#lastName").val(),$("#email").val(),$("#position").val()),targets.DataTable().draw(),$("#targetForm>div>input").val(""),$("#firstName").focus(),!1}),$("#targetsTable").on("click","span>i.fa-trash-o",function(){targets.DataTable().row($(this).parents("tr")).remove().draw()}),$("#modal").on("hide.bs.modal",function(){dismiss()}),$("#csv-template").click(downloadCSVTemplate)}); \ No newline at end of file +function save(e){var a=[];$.each($("#targetsTable").DataTable().rows().data(),function(e,t){a.push({first_name:unescapeHtml(t[0]),last_name:unescapeHtml(t[1]),email:unescapeHtml(t[2]),position:unescapeHtml(t[3])})});var t={name:$("#name").val(),targets:a};-1!=e?(t.id=e,api.groupId.put(t).success(function(e){successFlash("Group updated successfully!"),load(),dismiss(),$("#modal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)})):api.groups.post(t).success(function(e){successFlash("Group added successfully!"),load(),dismiss(),$("#modal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)})}function dismiss(){$("#targetsTable").dataTable().DataTable().clear().draw(),$("#name").val(""),$("#modal\\.flashes").empty()}function edit(e){if(targets=$("#targetsTable").dataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]}),$("#modalSubmit").unbind("click").click(function(){save(e)}),-1==e);else api.groupId.get(e).success(function(e){$("#name").val(e.name),$.each(e.targets,function(e,a){targets.DataTable().row.add([escapeHtml(a.first_name),escapeHtml(a.last_name),escapeHtml(a.email),escapeHtml(a.position),'']).draw()})}).error(function(){errorFlash("Error fetching group")});$("#csvupload").fileupload({url:"/api/import/group",dataType:"json",beforeSend:function(e){e.setRequestHeader("Authorization","Bearer "+user.api_key)},add:function(e,a){$("#modal\\.flashes").empty();var t=/(csv|txt)$/i,s=a.originalFiles[0].name;if(s&&!t.test(s.split(".").pop()))return modalError("Unsupported file extension (use .csv or .txt)"),!1;a.submit()},done:function(e,a){$.each(a.result,function(e,a){addTarget(a.first_name,a.last_name,a.email,a.position)}),targets.DataTable().draw()}})}function addTarget(e,a,t,s){var o=escapeHtml(t).toLowerCase(),r=[escapeHtml(e),escapeHtml(a),o,escapeHtml(s),''],n=targets.DataTable(),i=n.column(2,{order:"index"}).data().indexOf(o);i>=0?n.row(i,{order:"index"}).data(r):n.row.add(r)}function load(){$("#groupTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.groups.summary().success(function(e){if($("#loading").hide(),e.total>0){groups=e.groups,$("#emptyMessage").hide(),$("#groupTable").show();var a=$("#groupTable").DataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]});a.clear(),$.each(groups,function(e,t){a.row.add([escapeHtml(t.name),escapeHtml(t.num_targets),moment(t.modified_date).format("MMMM Do YYYY, h:mm:ss a"),"
"]).draw()})}else $("#emptyMessage").show()}).error(function(){errorFlash("Error fetching groups")})}var groups=[],downloadCSVTemplate=function(){var e=[{"First Name":"Example","Last Name":"User",Email:"foobar@example.com",Position:"Systems Administrator"}],a=Papa.unparse(e,{}),t=new Blob([a],{type:"text/csv;charset=utf-8;"});if(navigator.msSaveBlob)navigator.msSaveBlob(t,"group_template.csv");else{var s=window.URL.createObjectURL(t),o=document.createElement("a");o.href=s,o.setAttribute("download","group_template.csv"),document.body.appendChild(o),o.click(),document.body.removeChild(o)}},deleteGroup=function(e){var a=groups.find(function(a){return a.id===e});a&&swal({title:"Are you sure?",text:"This will delete the group. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(a.name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.groupId.delete(e).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Group Deleted!","This group has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};$(document).ready(function(){load(),$("#targetForm").submit(function(){return addTarget($("#firstName").val(),$("#lastName").val(),$("#email").val(),$("#position").val()),targets.DataTable().draw(),$("#targetForm>div>input").val(""),$("#firstName").focus(),!1}),$("#targetsTable").on("click","span>i.fa-trash-o",function(){targets.DataTable().row($(this).parents("tr")).remove().draw()}),$("#modal").on("hide.bs.modal",function(){dismiss()}),$("#csv-template").click(downloadCSVTemplate)}); \ No newline at end of file diff --git a/static/js/src/app/gophish.js b/static/js/src/app/gophish.js index 31c90d92..0e69ff2b 100644 --- a/static/js/src/app/gophish.js +++ b/static/js/src/app/gophish.js @@ -17,12 +17,15 @@ function modalError(message) { function query(endpoint, method, data, async) { return $.ajax({ - url: "/api" + endpoint + "?api_key=" + user.api_key, + url: "/api" + endpoint, async: async, method: method, data: JSON.stringify(data), dataType: "json", - contentType: "application/json" + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader('Authorization', 'Bearer ' + user.api_key); + } }) } diff --git a/static/js/src/app/users.js b/static/js/src/app/users.js index c2918103..02a2b890 100644 --- a/static/js/src/app/users.js +++ b/static/js/src/app/users.js @@ -87,8 +87,11 @@ function edit(id) { } // Handle file uploads $("#csvupload").fileupload({ - url: "/api/import/group?api_key=" + user.api_key, + url: "/api/import/group", dataType: "json", + beforeSend: function (xhr) { + xhr.setRequestHeader('Authorization', 'Bearer ' + user.api_key); + }, add: function (e, data) { $("#modal\\.flashes").empty() var acceptFileTypes = /(csv|txt)$/i; From 6ca2b76cebd8c6f913c34f7441a8cee9c16adcd4 Mon Sep 17 00:00:00 2001 From: Jordan Wright Date: Sun, 21 Apr 2019 16:34:52 -0500 Subject: [PATCH 06/27] Update Javascript Dependencies (#1440) * updated devDependencies, migrated gulpfile.js to gulp 4.0 syntax (#1438) * Rebuilding JS dependencies with new gulp config. Updated yarn.lock. Co-authored-by: Christian Schwartz --- gulpfile.js | 23 +- package.json | 19 +- static/js/dist/app/autocomplete.min.js | 2 +- static/js/dist/app/campaign_results.min.js | 2 +- static/js/dist/app/campaigns.min.js | 2 +- static/js/dist/app/dashboard.min.js | 2 +- static/js/dist/app/gophish.min.js | 2 +- static/js/dist/app/landing_pages.min.js | 2 +- static/js/dist/app/sending_profiles.min.js | 2 +- static/js/dist/app/templates.min.js | 2 +- static/js/dist/app/users.min.js | 2 +- static/js/dist/vendor.min.js | 31 +- yarn.lock | 2968 ++++++++++++++++++++ 13 files changed, 2999 insertions(+), 60 deletions(-) create mode 100644 yarn.lock diff --git a/gulpfile.js b/gulpfile.js index ea8e31b5..f89ed36e 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -17,8 +17,7 @@ var gulp = require('gulp'), dest_js_directory = 'static/js/dist/', dest_css_directory = 'static/css/dist/'; -gulp.task('vendorjs', function () { - // Vendor minifying / concat +vendorjs = function () { return gulp.src([ vendor_directory + 'jquery.js', vendor_directory + 'bootstrap.min.js', @@ -46,11 +45,11 @@ gulp.task('vendorjs', function () { })) .pipe(uglify()) .pipe(gulp.dest(dest_js_directory)); -}) +} -gulp.task('scripts', function () { +scripts = function () { // Gophish app files - gulp.src(app_directory) + return gulp.src(app_directory) .pipe(rename({ suffix: '.min' })) @@ -58,9 +57,9 @@ gulp.task('scripts', function () { console.log(e); })) .pipe(gulp.dest(dest_js_directory + 'app/')); -}) +} -gulp.task('styles', function () { +styles = function () { return gulp.src([ css_directory + 'bootstrap.min.css', css_directory + 'main.css', @@ -80,8 +79,10 @@ gulp.task('styles', function () { })) .pipe(concat('gophish.css')) .pipe(gulp.dest(dest_css_directory)); -}) +} -gulp.task('build', ['vendorjs', 'scripts', 'styles']); - -gulp.task('default', ['build']); \ No newline at end of file +exports.vendorjs = vendorjs +exports.scripts = scripts +exports.styles = styles +exports.build = gulp.parallel(vendorjs, scripts, styles) +exports.default = exports.build \ No newline at end of file diff --git a/package.json b/package.json index 36d7e62c..1f17d851 100644 --- a/package.json +++ b/package.json @@ -12,17 +12,16 @@ }, "homepage": "https://getgophish.com", "devDependencies": { - "clean-css": "^3.4.23", - "gulp": "^3.9.1", - "gulp-clean-css": "^2.3.2", - "gulp-cli": "^1.4.0", + "clean-css": "^4.2.1", + "gulp": "^4.0.0", + "gulp-clean-css": "^4.0.0", + "gulp-cli": "^2.2.0", "gulp-concat": "^2.6.1", - "gulp-jshint": "^2.0.4", - "gulp-rename": "^1.2.2", - "gulp-uglify": "^2.0.0", - "gulp-util": "^3.0.8", - "gulp-wrap": "^0.13.0", - "jshint": "^2.9.4", + "gulp-jshint": "^2.1.0", + "gulp-rename": "^1.4.0", + "gulp-uglify": "^3.0.2", + "gulp-wrap": "^0.15.0", + "jshint": "^2.10.2", "jshint-stylish": "^2.2.1" } } diff --git a/static/js/dist/app/autocomplete.min.js b/static/js/dist/app/autocomplete.min.js index 09a85ec5..0f6c41b4 100644 --- a/static/js/dist/app/autocomplete.min.js +++ b/static/js/dist/app/autocomplete.min.js @@ -1 +1 @@ -var TEMPLATE_TAGS=[{id:1,name:"RId",description:"The unique ID for the recipient."},{id:2,name:"FirstName",description:"The recipient's first name."},{id:3,name:"LastName",description:"The recipient's last name."},{id:4,name:"Position",description:"The recipient's position."},{id:5,name:"From",description:"The address emails are sent from."},{id:6,name:"TrackingURL",description:"The URL to track emails being opened."},{id:7,name:"Tracker",description:"An HTML tag that adds a hidden tracking image (recommended instead of TrackingURL)."},{id:8,name:"URL",description:"The URL to your Gophish listener."},{id:9,name:"BaseURL",description:"The base URL with the path and rid parameter stripped. Useful for making links to static files."}],textTestCallback=function(e){return e.collapsed?CKEDITOR.plugins.textMatch.match(e,matchCallback):null},matchCallback=function(e,t){var i=/\{{2}\.?([A-z]|\})*$/,a=e.slice(0,t).match(i);return a?{start:a.index,end:t}:null},dataCallback=function(e,t){t(TEMPLATE_TAGS.filter(function(t){return 0==("{{."+t.name.toLowerCase()+"}}").indexOf(e.query.toLowerCase())}))},setupAutocomplete=function(e){e.on("instanceReady",function(e){new CKEDITOR.plugins.autocomplete(e.editor,{textTestCallback:textTestCallback,dataCallback:dataCallback,itemTemplate:'
  • {name}
    {description}
  • ',outputTemplate:"[[.{name}]]"}).getHtmlToInsert=function(e){var t=this.outputTemplate.output(e);return t=t.replace("[[","{{").replace("]]","}}")}})}; \ No newline at end of file +var TEMPLATE_TAGS=[{id:1,name:"RId",description:"The unique ID for the recipient."},{id:2,name:"FirstName",description:"The recipient's first name."},{id:3,name:"LastName",description:"The recipient's last name."},{id:4,name:"Position",description:"The recipient's position."},{id:5,name:"From",description:"The address emails are sent from."},{id:6,name:"TrackingURL",description:"The URL to track emails being opened."},{id:7,name:"Tracker",description:"An HTML tag that adds a hidden tracking image (recommended instead of TrackingURL)."},{id:8,name:"URL",description:"The URL to your Gophish listener."},{id:9,name:"BaseURL",description:"The base URL with the path and rid parameter stripped. Useful for making links to static files."}],textTestCallback=function(e){return e.collapsed?CKEDITOR.plugins.textMatch.match(e,matchCallback):null},matchCallback=function(e,t){var i=e.slice(0,t).match(/\{{2}\.?([A-z]|\})*$/);return i?{start:i.index,end:t}:null},dataCallback=function(t,e){e(TEMPLATE_TAGS.filter(function(e){return 0==("{{."+e.name.toLowerCase()+"}}").indexOf(t.query.toLowerCase())}))},setupAutocomplete=function(e){e.on("instanceReady",function(e){new CKEDITOR.plugins.autocomplete(e.editor,{textTestCallback:textTestCallback,dataCallback:dataCallback,itemTemplate:'
  • {name}
    {description}
  • ',outputTemplate:"[[.{name}]]"}).getHtmlToInsert=function(e){var t=this.outputTemplate.output(e);return t=t.replace("[[","{{").replace("]]","}}")}})}; \ No newline at end of file diff --git a/static/js/dist/app/campaign_results.min.js b/static/js/dist/app/campaign_results.min.js index 8c461d9a..d02e60e3 100644 --- a/static/js/dist/app/campaign_results.min.js +++ b/static/js/dist/app/campaign_results.min.js @@ -1 +1 @@ -function dismiss(){$("#modal\\.flashes").empty(),$("#modal").modal("hide"),$("#resultsTable").dataTable().DataTable().clear().draw()}function deleteCampaign(){swal({title:"Are you sure?",text:"This will delete the campaign. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete Campaign",confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,showLoaderOnConfirm:!0,preConfirm:function(){return new Promise(function(e,t){api.campaignId.delete(campaign.id).success(function(t){e()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Campaign Deleted!","This campaign has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.href="/campaigns"})})}function completeCampaign(){swal({title:"Are you sure?",text:"Gophish will stop processing events for this campaign",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Complete Campaign",confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,showLoaderOnConfirm:!0,preConfirm:function(){return new Promise(function(e,t){api.campaignId.complete(campaign.id).success(function(t){e()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Campaign Completed!","This campaign has been completed!","success"),$("#complete_button")[0].disabled=!0,$("#complete_button").text("Completed!"),doPoll=!1})}function exportAsCSV(e){exportHTML=$("#exportButton").html();var t=null,a=campaign.name+" - "+capitalize(e)+".csv";switch(e){case"results":t=campaign.results;break;case"events":t=campaign.timeline}if(t){$("#exportButton").html('');var s=Papa.unparse(t,{}),i=new Blob([s],{type:"text/csv;charset=utf-8;"});if(navigator.msSaveBlob)navigator.msSaveBlob(i,a);else{var l=window.URL.createObjectURL(i),n=document.createElement("a");n.href=l,n.setAttribute("download",a),document.body.appendChild(n),n.click(),document.body.removeChild(n)}$("#exportButton").html(exportHTML)}}function replay(e){function t(){form.attr({action:url}),form.appendTo("body").submit().remove()}request=campaign.timeline[e],details=JSON.parse(request.details),url=null,form=$("
    ").attr({method:"POST",target:"_blank"}),$.each(Object.keys(details.payload),function(e,t){return"rid"==t||("__original_url"==t?(url=details.payload[t],!0):void $("").attr({name:t}).val(details.payload[t]).appendTo(form))}),swal({title:"Where do you want the credentials submitted to?",input:"text",showCancelButton:!0,inputPlaceholder:"http://example.com/login",inputValue:url||"",inputValidator:function(e){return new Promise(function(t,a){e?t():a("Invalid URL.")})}}).then(function(e){url=e,t()})}function renderTimeline(e){return record={id:e[0],first_name:e[2],last_name:e[3],email:e[4],position:e[5],status:e[6],reported:e[7],send_date:e[8]},results='
    Timeline for '+escapeHtml(record.first_name)+" "+escapeHtml(record.last_name)+'
    Email: '+escapeHtml(record.email)+"
    Result ID: "+escapeHtml(record.id)+'
    ',$.each(campaign.timeline,function(e,t){t.email&&t.email!=record.email||(results+='
    ',results+='
    '+escapeHtml(t.message)+' '+moment.utc(t.time).local().format("MMMM Do YYYY h:mm:ss a")+"",t.details&&(details=JSON.parse(t.details),"Clicked Link"!=t.message&&"Submitted Data"!=t.message||(deviceView=renderDevice(details),deviceView&&(results+=deviceView)),"Submitted Data"==t.message&&(results+='
    ',results+='
    View Details
    '),details.payload&&(results+='
    ',results+=' ',results+=" ",$.each(Object.keys(details.payload),function(e,t){if("rid"==t)return!0;results+=" ",results+=" ",results+=" ",results+=" "}),results+="
    ParameterValue(s)
    "+escapeHtml(t)+""+escapeHtml(details.payload[t])+"
    ",results+="
    "),details.error&&(results+='
    View Details
    ',results+='
    ',results+='Error '+details.error,results+="
    ")),results+="
    ")}),"Scheduled"!=record.status&&"Retrying"!=record.status||(results+='
    ',results+='
    Scheduled to send at '+record.send_date+""),results+="
    ",results}function createStatusLabel(e,t){var a=statuses[e].label||"label-default",s=''+e+"";if("Scheduled"==e||"Retrying"==e){s=''+e+""}return s}function poll(){api.campaignId.results(campaign.id).success(function(e){campaign=e;var t=[];$.each(campaign.timeline,function(e,a){var s=moment.utc(a.time).local();t.push({email:a.email,x:s.valueOf(),y:1})});var t=[];$.each(campaign.timeline,function(e,a){var s=moment.utc(a.time).local();t.push({email:a.email,message:a.message,x:s.valueOf(),y:1,marker:{fillColor:statuses[a.message].color}})}),$("#timeline_chart").highcharts().series[0].update({data:t});var a={};Object.keys(statusMapping).forEach(function(e){a[e]=0}),$.each(campaign.results,function(e,t){a[t.status]++,t.reported&&a["Email Reported"]++;for(var s=progressListing.indexOf(t.status),e=0;e":"":e},targets:[7]}]}),resultsTable.clear();var a={},s=[];Object.keys(statusMapping).forEach(function(e){a[e]=0}),$.each(campaign.results,function(e,t){resultsTable.row.add([t.id,'',escapeHtml(t.first_name)||"",escapeHtml(t.last_name)||"",escapeHtml(t.email)||"",escapeHtml(t.position)||"",t.status,t.reported,moment(t.send_date).format("MMMM Do YYYY, h:mm:ss a")]),a[t.status]++,t.reported&&a["Email Reported"]++;for(var s=progressListing.indexOf(t.status),e=0;e',s="laptop";t.device.type&&("tablet"!=t.device.type&&"mobile"!=t.device.type||(s=t.device.type));var i="";t.device.vendor&&"microsoft"==(i=t.device.vendor.toLowerCase())&&(i="windows");var l="Unknown";t.os.name&&(l=t.os.name,"Mac OS"==l?i="apple":"Windows"==l&&(i="windows"),t.device.vendor&&t.device.model&&(l=t.device.vendor+" "+t.device.model)),t.os.version&&(l=l+" (OS Version: "+t.os.version+")"),deviceString='
    '+escapeHtml(l)+"
    ",a+=deviceString;var n="Unknown",r="info-circle",o="";return t.browser&&t.browser.name&&(n=t.browser.name,n=n.replace("Mobile ",""),n&&"ie"==(r=n.toLowerCase())&&(r="internet-explorer"),o="(Version: "+t.browser.version+")"),a+='
    '+n+" "+o+"
    ",a+="
    "},renderTimelineChart=function(e){return Highcharts.chart("timeline_chart",{chart:{zoomType:"x",type:"line",height:"200px"},title:{text:"Campaign Timeline"},xAxis:{type:"datetime",dateTimeLabelFormats:{second:"%l:%M:%S",minute:"%l:%M",hour:"%l:%M",day:"%b %d, %Y",week:"%b %d, %Y",month:"%b %Y"}},yAxis:{min:0,max:2,visible:!1,tickInterval:1,labels:{enabled:!1},title:{text:""}},tooltip:{formatter:function(){return Highcharts.dateFormat("%A, %b %d %l:%M:%S %P",new Date(this.x))+"
    Event: "+this.point.message+"
    Email: "+this.point.email+""}},legend:{enabled:!1},plotOptions:{series:{marker:{enabled:!0,symbol:"circle",radius:3},cursor:"pointer"},line:{states:{hover:{lineWidth:1}}}},credits:{enabled:!1},series:[{data:e.data,dashStyle:"shortdash",color:"#cccccc",lineWidth:1,turboThreshold:0}]})},renderPieChart=function(e){return Highcharts.chart(e.elemId,{chart:{type:"pie",events:{load:function(){var t=this,a=t.renderer,s=t.series[0],i=t.plotLeft+s.center[0],l=t.plotTop+s.center[1];this.innerText=a.text(e.data[0].count,i,l).attr({"text-anchor":"middle","font-size":"24px","font-weight":"bold",fill:e.colors[0],"font-family":"Helvetica,Arial,sans-serif"}).add()},render:function(){this.innerText.attr({text:e.data[0].count})}}},title:{text:e.title},plotOptions:{pie:{innerSize:"80%",dataLabels:{enabled:!1}}},credits:{enabled:!1},tooltip:{formatter:function(){return void 0!=this.key&&''+this.point.name+": "+this.y+"%
    "}},series:[{data:e.data,colors:e.colors}]})},updateMap=function(e){map&&(bubbles=[],$.each(campaign.results,function(e,t){if(0==t.latitude&&0==t.longitude)return!0;newIP=!0,$.each(bubbles,function(e,a){if(a.ip==t.ip)return bubbles[e].radius+=1,newIP=!1,!1}),newIP&&bubbles.push({latitude:t.latitude,longitude:t.longitude,name:t.ip,fillKey:"point",radius:2})}),map.bubbles(bubbles))},setRefresh;$(document).ready(function(){Highcharts.setOptions({global:{useUTC:!1}}),load(),setRefresh=setTimeout(refresh,6e4)}); \ No newline at end of file +var map=null,doPoll=!0,statuses={"Email Sent":{color:"#1abc9c",label:"label-success",icon:"fa-envelope",point:"ct-point-sent"},"Emails Sent":{color:"#1abc9c",label:"label-success",icon:"fa-envelope",point:"ct-point-sent"},"In progress":{label:"label-primary"},Queued:{label:"label-info"},Completed:{label:"label-success"},"Email Opened":{color:"#f9bf3b",label:"label-warning",icon:"fa-envelope-open",point:"ct-point-opened"},"Clicked Link":{color:"#F39C12",label:"label-clicked",icon:"fa-mouse-pointer",point:"ct-point-clicked"},Success:{color:"#f05b4f",label:"label-danger",icon:"fa-exclamation",point:"ct-point-clicked"},"Email Reported":{color:"#45d6ef",label:"label-info",icon:"fa-bullhorn",point:"ct-point-reported"},Error:{color:"#6c7a89",label:"label-default",icon:"fa-times",point:"ct-point-error"},"Error Sending Email":{color:"#6c7a89",label:"label-default",icon:"fa-times",point:"ct-point-error"},"Submitted Data":{color:"#f05b4f",label:"label-danger",icon:"fa-exclamation",point:"ct-point-clicked"},Unknown:{color:"#6c7a89",label:"label-default",icon:"fa-question",point:"ct-point-error"},Sending:{color:"#428bca",label:"label-primary",icon:"fa-spinner",point:"ct-point-sending"},Retrying:{color:"#6c7a89",label:"label-default",icon:"fa-clock-o",point:"ct-point-error"},Scheduled:{color:"#428bca",label:"label-primary",icon:"fa-clock-o",point:"ct-point-sending"},"Campaign Created":{label:"label-success",icon:"fa-rocket"}},statusMapping={"Email Sent":"sent","Email Opened":"opened","Clicked Link":"clicked","Submitted Data":"submitted_data","Email Reported":"reported"},progressListing=["Email Sent","Email Opened","Clicked Link","Submitted Data"],campaign={},bubbles=[];function dismiss(){$("#modal\\.flashes").empty(),$("#modal").modal("hide"),$("#resultsTable").dataTable().DataTable().clear().draw()}function deleteCampaign(){swal({title:"Are you sure?",text:"This will delete the campaign. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete Campaign",confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,showLoaderOnConfirm:!0,preConfirm:function(){return new Promise(function(t,a){api.campaignId.delete(campaign.id).success(function(e){t()}).error(function(e){a(e.responseJSON.message)})})}}).then(function(){swal("Campaign Deleted!","This campaign has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.href="/campaigns"})})}function completeCampaign(){swal({title:"Are you sure?",text:"Gophish will stop processing events for this campaign",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Complete Campaign",confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,showLoaderOnConfirm:!0,preConfirm:function(){return new Promise(function(t,a){api.campaignId.complete(campaign.id).success(function(e){t()}).error(function(e){a(e.responseJSON.message)})})}}).then(function(){swal("Campaign Completed!","This campaign has been completed!","success"),$("#complete_button")[0].disabled=!0,$("#complete_button").text("Completed!"),doPoll=!1})}function exportAsCSV(e){exportHTML=$("#exportButton").html();var t=null,a=campaign.name+" - "+capitalize(e)+".csv";switch(e){case"results":t=campaign.results;break;case"events":t=campaign.timeline}if(t){$("#exportButton").html('');var s=Papa.unparse(t,{}),i=new Blob([s],{type:"text/csv;charset=utf-8;"});if(navigator.msSaveBlob)navigator.msSaveBlob(i,a);else{var l=window.URL.createObjectURL(i),n=document.createElement("a");n.href=l,n.setAttribute("download",a),document.body.appendChild(n),n.click(),document.body.removeChild(n)}$("#exportButton").html(exportHTML)}}function replay(e){return request=campaign.timeline[e],details=JSON.parse(request.details),url=null,form=$("").attr({method:"POST",target:"_blank"}),$.each(Object.keys(details.payload),function(e,t){return"rid"==t||("__original_url"==t?(url=details.payload[t],!0):void $("").attr({name:t}).val(details.payload[t]).appendTo(form))}),void swal({title:"Where do you want the credentials submitted to?",input:"text",showCancelButton:!0,inputPlaceholder:"http://example.com/login",inputValue:url||"",inputValidator:function(a){return new Promise(function(e,t){a?e():t("Invalid URL.")})}}).then(function(e){url=e,t()});function t(){form.attr({action:url}),form.appendTo("body").submit().remove()}}var renderDevice=function(e){var t=UAParser(details.browser["user-agent"]),a='
    ',s="laptop";t.device.type&&("tablet"!=t.device.type&&"mobile"!=t.device.type||(s=t.device.type));var i="";t.device.vendor&&"microsoft"==(i=t.device.vendor.toLowerCase())&&(i="windows");var l="Unknown";t.os.name&&("Mac OS"==(l=t.os.name)?i="apple":"Windows"==l&&(i="windows"),t.device.vendor&&t.device.model&&(l=t.device.vendor+" "+t.device.model)),t.os.version&&(l=l+" (OS Version: "+t.os.version+")"),deviceString='
    '+escapeHtml(l)+"
    ",a+=deviceString;var n="Unknown",r="info-circle",o="";return t.browser&&t.browser.name&&((n=(n=t.browser.name).replace("Mobile ",""))&&"ie"==(r=n.toLowerCase())&&(r="internet-explorer"),o="(Version: "+t.browser.version+")"),a+='
    '+n+" "+o+"
    ",a+="
    "};function renderTimeline(e){return record={id:e[0],first_name:e[2],last_name:e[3],email:e[4],position:e[5],status:e[6],reported:e[7],send_date:e[8]},results='
    Timeline for '+escapeHtml(record.first_name)+" "+escapeHtml(record.last_name)+'
    Email: '+escapeHtml(record.email)+"
    Result ID: "+escapeHtml(record.id)+'
    ',$.each(campaign.timeline,function(e,t){t.email&&t.email!=record.email||(results+='
    ',results+='
    '+escapeHtml(t.message)+' '+moment.utc(t.time).local().format("MMMM Do YYYY h:mm:ss a")+"",t.details&&(details=JSON.parse(t.details),"Clicked Link"!=t.message&&"Submitted Data"!=t.message||(deviceView=renderDevice(details),deviceView&&(results+=deviceView)),"Submitted Data"==t.message&&(results+='
    ',results+='
    View Details
    '),details.payload&&(results+='
    ',results+=' ',results+=" ",$.each(Object.keys(details.payload),function(e,t){if("rid"==t)return!0;results+=" ",results+=" ",results+=" ",results+=" "}),results+="
    ParameterValue(s)
    "+escapeHtml(t)+""+escapeHtml(details.payload[t])+"
    ",results+="
    "),details.error&&(results+='
    View Details
    ',results+='
    ',results+='Error '+details.error,results+="
    ")),results+="
    ")}),"Scheduled"!=record.status&&"Retrying"!=record.status||(results+='
    ',results+='
    Scheduled to send at '+record.send_date+""),results+="
    ",results}var setRefresh,renderTimelineChart=function(e){return Highcharts.chart("timeline_chart",{chart:{zoomType:"x",type:"line",height:"200px"},title:{text:"Campaign Timeline"},xAxis:{type:"datetime",dateTimeLabelFormats:{second:"%l:%M:%S",minute:"%l:%M",hour:"%l:%M",day:"%b %d, %Y",week:"%b %d, %Y",month:"%b %Y"}},yAxis:{min:0,max:2,visible:!1,tickInterval:1,labels:{enabled:!1},title:{text:""}},tooltip:{formatter:function(){return Highcharts.dateFormat("%A, %b %d %l:%M:%S %P",new Date(this.x))+"
    Event: "+this.point.message+"
    Email: "+this.point.email+""}},legend:{enabled:!1},plotOptions:{series:{marker:{enabled:!0,symbol:"circle",radius:3},cursor:"pointer"},line:{states:{hover:{lineWidth:1}}}},credits:{enabled:!1},series:[{data:e.data,dashStyle:"shortdash",color:"#cccccc",lineWidth:1,turboThreshold:0}]})},renderPieChart=function(l){return Highcharts.chart(l.elemId,{chart:{type:"pie",events:{load:function(){var e=this,t=e.renderer,a=e.series[0],s=e.plotLeft+a.center[0],i=e.plotTop+a.center[1];this.innerText=t.text(l.data[0].count,s,i).attr({"text-anchor":"middle","font-size":"24px","font-weight":"bold",fill:l.colors[0],"font-family":"Helvetica,Arial,sans-serif"}).add()},render:function(){this.innerText.attr({text:l.data[0].count})}}},title:{text:l.title},plotOptions:{pie:{innerSize:"80%",dataLabels:{enabled:!1}}},credits:{enabled:!1},tooltip:{formatter:function(){return null!=this.key&&''+this.point.name+": "+this.y+"%
    "}},series:[{data:l.data,colors:l.colors}]})},updateMap=function(e){map&&(bubbles=[],$.each(campaign.results,function(e,a){if(0==a.latitude&&0==a.longitude)return!0;newIP=!0,$.each(bubbles,function(e,t){if(t.ip==a.ip)return bubbles[e].radius+=1,newIP=!1}),newIP&&bubbles.push({latitude:a.latitude,longitude:a.longitude,name:a.ip,fillKey:"point",radius:2})}),map.bubbles(bubbles))};function createStatusLabel(e,t){var a=statuses[e].label||"label-default",s=''+e+"";"Scheduled"!=e&&"Retrying"!=e||(s=''+e+"");return s}function poll(){api.campaignId.results(campaign.id).success(function(e){campaign=e;var s=[];$.each(campaign.timeline,function(e,t){var a=moment.utc(t.time).local();s.push({email:t.email,x:a.valueOf(),y:1})});s=[];$.each(campaign.timeline,function(e,t){var a=moment.utc(t.time).local();s.push({email:t.email,message:t.message,x:a.valueOf(),y:1,marker:{fillColor:statuses[t.message].color}})}),$("#timeline_chart").highcharts().series[0].update({data:s});var i={};Object.keys(statusMapping).forEach(function(e){i[e]=0}),$.each(campaign.results,function(e,t){i[t.status]++,t.reported&&i["Email Reported"]++;var a=progressListing.indexOf(t.status);for(e=0;e":"":e},targets:[7]}]}),resultsTable.clear();var s={},i=[];Object.keys(statusMapping).forEach(function(e){s[e]=0}),$.each(campaign.results,function(e,t){resultsTable.row.add([t.id,'',escapeHtml(t.first_name)||"",escapeHtml(t.last_name)||"",escapeHtml(t.email)||"",escapeHtml(t.position)||"",t.status,t.reported,moment(t.send_date).format("MMMM Do YYYY, h:mm:ss a")]),s[t.status]++,t.reported&&s["Email Reported"]++;var a=progressListing.indexOf(t.status);for(e=0;e '+e.responseJSON.message+"
    "),swal.close()})})}}).then(function(){swal("Campaign Scheduled!","This campaign has been scheduled for launch!","success"),$('button:contains("OK")').on("click",function(){window.location="/campaigns/"+campaign.id.toString()})})}function sendTestEmail(){var e={template:{name:$("#template").select2("data")[0].text},first_name:$("input[name=to_first_name]").val(),last_name:$("input[name=to_last_name]").val(),email:$("input[name=to_email]").val(),position:$("input[name=to_position]").val(),url:$("#url").val(),page:{name:$("#page").select2("data")[0].text},smtp:{name:$("#profile").select2("data")[0].text}};btnHtml=$("#sendTestModalSubmit").html(),$("#sendTestModalSubmit").html(' Sending'),api.send_test_email(e).success(function(e){$("#sendTestEmailModal\\.flashes").empty().append('
    Email Sent!
    '),$("#sendTestModalSubmit").html(btnHtml)}).error(function(e){$("#sendTestEmailModal\\.flashes").empty().append('
    '+e.responseJSON.message+"
    "),$("#sendTestModalSubmit").html(btnHtml)})}function dismiss(){$("#modal\\.flashes").empty(),$("#name").val(""),$("#template").val("").change(),$("#page").val("").change(),$("#url").val(""),$("#profile").val("").change(),$("#users").val("").change(),$("#modal").modal("hide")}function deleteCampaign(e){swal({title:"Are you sure?",text:"This will delete the campaign. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+campaigns[e].name,confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.campaignId.delete(campaigns[e].id).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Campaign Deleted!","This campaign has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})}function setupOptions(){api.groups.get().success(function(e){if(0==e.length)return modalError("No groups found!"),!1;var a=$.map(e,function(e){return e.text=e.name,e});$("#users.form-control").select2({placeholder:"Select Groups",data:a})}),api.templates.get().success(function(e){if(0==e.length)return modalError("No templates found!"),!1;var a=$.map(e,function(e){return e.text=e.name,e}),t=$("#template.form-control");t.select2({placeholder:"Select a Template",data:a}),1===e.length&&(t.val(a[0].id),t.trigger("change.select2"))}),api.pages.get().success(function(e){if(0==e.length)return modalError("No pages found!"),!1;var a=$.map(e,function(e){return e.text=e.name,e}),t=$("#page.form-control");t.select2({placeholder:"Select a Landing Page",data:a}),1===e.length&&(t.val(a[0].id),t.trigger("change.select2"))}),api.SMTP.get().success(function(e){if(0==e.length)return modalError("No profiles found!"),!1;var a=$.map(e,function(e){return e.text=e.name,e}),t=$("#profile.form-control");t.select2({placeholder:"Select a Sending Profile",data:a}).select2("val",a[0]),1===e.length&&(t.val(a[0].id),t.trigger("change.select2"))})}function edit(e){setupOptions()}function copy(e){setupOptions(),api.campaignId.get(campaigns[e].id).success(function(e){$("#name").val("Copy of "+e.name),e.template.id?($("#template").val(e.template.id.toString()),$("#template").trigger("change.select2")):$("#template").select2({placeholder:e.template.name}),e.page.id?($("#page").val(e.page.id.toString()),$("#page").trigger("change.select2")):$("#page").select2({placeholder:e.page.name}),e.smtp.id?($("#profile").val(e.smtp.id.toString()),$("#profile").trigger("change.select2")):$("#profile").select2({placeholder:e.smtp.name}),$("#url").val(e.url)}).error(function(e){$("#modal\\.flashes").empty().append('
    '+e.responseJSON.message+"
    ")})}var labels={"In progress":"label-primary",Queued:"label-info",Completed:"label-success","Emails Sent":"label-success",Error:"label-danger"},campaigns=[],campaign={};$(document).ready(function(){$("#launch_date").datetimepicker({widgetPositioning:{vertical:"bottom"},showTodayButton:!0,defaultDate:moment(),format:"MMMM Do YYYY, h:mm a"}),$("#send_by_date").datetimepicker({widgetPositioning:{vertical:"bottom"},showTodayButton:!0,useCurrent:!1,format:"MMMM Do YYYY, h:mm a"}),$(".modal").on("hidden.bs.modal",function(e){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(e){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(e){dismiss()}),api.campaigns.summary().success(function(e){campaigns=e.campaigns,$("#loading").hide(),campaigns.length>0?($("#campaignTable").show(),$("#campaignTableArchive").show(),campaignTableOriginal=$("#campaignTable").DataTable({columnDefs:[{orderable:!1,targets:"no-sort"}],order:[[1,"desc"]]}),campaignTableArchive=$("#campaignTableArchive").DataTable({columnDefs:[{orderable:!1,targets:"no-sort"}],order:[[1,"desc"]]}),$.each(campaigns,function(e,a){campaignTable=campaignTableOriginal,"Completed"===a.status&&(campaignTable=campaignTableArchive),label=labels[a.status]||"label-default";var t;if(moment(a.launch_date).isAfter(moment())){t="Scheduled to start: "+moment(a.launch_date).format("MMMM Do YYYY, h:mm:ss a");var n=t+"

    Number of recipients: "+a.stats.total}else{t="Launch Date: "+moment(a.launch_date).format("MMMM Do YYYY, h:mm:ss a");var n=t+"

    Number of recipients: "+a.stats.total+"

    Emails opened: "+a.stats.opened+"

    Emails clicked: "+a.stats.clicked+"

    Submitted Credentials: "+a.stats.submitted_data+"

    Errors : "+a.stats.error+"Reported : "+a.stats.reported}campaignTable.row.add([escapeHtml(a.name),moment(a.created_date).format("MMMM Do YYYY, h:mm:ss a"),''+a.status+"",""]).draw(),$('[data-toggle="tooltip"]').tooltip()})):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching campaigns")}),$.fn.select2.defaults.set("width","100%"),$.fn.select2.defaults.set("dropdownParent",$("#modal_body")),$.fn.select2.defaults.set("theme","bootstrap"),$.fn.select2.defaults.set("sorter",function(e){return e.sort(function(e,a){return e.text.toLowerCase()>a.text.toLowerCase()?1:e.text.toLowerCase() '+e.responseJSON.message+"
    "),swal.close()})})}}).then(function(){swal("Campaign Scheduled!","This campaign has been scheduled for launch!","success"),$('button:contains("OK")').on("click",function(){window.location="/campaigns/"+campaign.id.toString()})})}function sendTestEmail(){var e={template:{name:$("#template").select2("data")[0].text},first_name:$("input[name=to_first_name]").val(),last_name:$("input[name=to_last_name]").val(),email:$("input[name=to_email]").val(),position:$("input[name=to_position]").val(),url:$("#url").val(),page:{name:$("#page").select2("data")[0].text},smtp:{name:$("#profile").select2("data")[0].text}};btnHtml=$("#sendTestModalSubmit").html(),$("#sendTestModalSubmit").html(' Sending'),api.send_test_email(e).success(function(e){$("#sendTestEmailModal\\.flashes").empty().append('
    Email Sent!
    '),$("#sendTestModalSubmit").html(btnHtml)}).error(function(e){$("#sendTestEmailModal\\.flashes").empty().append('
    '+e.responseJSON.message+"
    "),$("#sendTestModalSubmit").html(btnHtml)})}function dismiss(){$("#modal\\.flashes").empty(),$("#name").val(""),$("#template").val("").change(),$("#page").val("").change(),$("#url").val(""),$("#profile").val("").change(),$("#users").val("").change(),$("#modal").modal("hide")}function deleteCampaign(e){swal({title:"Are you sure?",text:"This will delete the campaign. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+campaigns[e].name,confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.campaignId.delete(campaigns[e].id).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Campaign Deleted!","This campaign has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})}function setupOptions(){api.groups.get().success(function(e){if(0==e.length)return modalError("No groups found!"),!1;var a=$.map(e,function(e){return e.text=e.name,e});$("#users.form-control").select2({placeholder:"Select Groups",data:a})}),api.templates.get().success(function(e){if(0==e.length)return modalError("No templates found!"),!1;var a=$.map(e,function(e){return e.text=e.name,e}),t=$("#template.form-control");t.select2({placeholder:"Select a Template",data:a}),1===e.length&&(t.val(a[0].id),t.trigger("change.select2"))}),api.pages.get().success(function(e){if(0==e.length)return modalError("No pages found!"),!1;var a=$.map(e,function(e){return e.text=e.name,e}),t=$("#page.form-control");t.select2({placeholder:"Select a Landing Page",data:a}),1===e.length&&(t.val(a[0].id),t.trigger("change.select2"))}),api.SMTP.get().success(function(e){if(0==e.length)return modalError("No profiles found!"),!1;var a=$.map(e,function(e){return e.text=e.name,e}),t=$("#profile.form-control");t.select2({placeholder:"Select a Sending Profile",data:a}).select2("val",a[0]),1===e.length&&(t.val(a[0].id),t.trigger("change.select2"))})}function edit(e){setupOptions()}function copy(e){setupOptions(),api.campaignId.get(campaigns[e].id).success(function(e){$("#name").val("Copy of "+e.name),e.template.id?($("#template").val(e.template.id.toString()),$("#template").trigger("change.select2")):$("#template").select2({placeholder:e.template.name}),e.page.id?($("#page").val(e.page.id.toString()),$("#page").trigger("change.select2")):$("#page").select2({placeholder:e.page.name}),e.smtp.id?($("#profile").val(e.smtp.id.toString()),$("#profile").trigger("change.select2")):$("#profile").select2({placeholder:e.smtp.name}),$("#url").val(e.url)}).error(function(e){$("#modal\\.flashes").empty().append('
    '+e.responseJSON.message+"
    ")})}$(document).ready(function(){$("#launch_date").datetimepicker({widgetPositioning:{vertical:"bottom"},showTodayButton:!0,defaultDate:moment(),format:"MMMM Do YYYY, h:mm a"}),$("#send_by_date").datetimepicker({widgetPositioning:{vertical:"bottom"},showTodayButton:!0,useCurrent:!1,format:"MMMM Do YYYY, h:mm a"}),$(".modal").on("hidden.bs.modal",function(e){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(e){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(e){dismiss()}),api.campaigns.summary().success(function(e){campaigns=e.campaigns,$("#loading").hide(),0
    Number of recipients: "+a.stats.total;else t="Launch Date: "+moment(a.launch_date).format("MMMM Do YYYY, h:mm:ss a")+"

    Number of recipients: "+a.stats.total+"

    Emails opened: "+a.stats.opened+"

    Emails clicked: "+a.stats.clicked+"

    Submitted Credentials: "+a.stats.submitted_data+"

    Errors : "+a.stats.error+"Reported : "+a.stats.reported;campaignTable.row.add([escapeHtml(a.name),moment(a.created_date).format("MMMM Do YYYY, h:mm:ss a"),''+a.status+"",""]).draw(),$('[data-toggle="tooltip"]').tooltip()})):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching campaigns")}),$.fn.select2.defaults.set("width","100%"),$.fn.select2.defaults.set("dropdownParent",$("#modal_body")),$.fn.select2.defaults.set("theme","bootstrap"),$.fn.select2.defaults.set("sorter",function(e){return e.sort(function(e,a){return e.text.toLowerCase()>a.text.toLowerCase()?1:e.text.toLowerCase()●'+this.point.name+": "+this.y+"%
    "}},series:[{data:e.data,colors:e.colors}]})}function generateStatsPieCharts(e){var t=[],a={},l=0;$.each(e,function(e,t){$.each(t.stats,function(e,t){if("total"==e)return l+=t,!0;a[e]?a[e]+=t:a[e]=t})}),$.each(a,function(e,a){if(!(e in statsMapping))return!0;status_label=statsMapping[e],t.push({name:status_label,y:Math.floor(a/l*100),count:a}),t.push({name:"",y:100-Math.floor(a/l*100)});renderPieChart({elemId:e+"_chart",title:status_label,name:e,data:t,colors:[statuses[status_label].color,"#dddddd"]});t=[]})}function generateTimelineChart(e){var t=[];$.each(e,function(e,a){var l=moment.utc(a.created_date).local();a.y=0,a.y+=a.stats.clicked,a.y=Math.floor(a.y/a.stats.total*100),t.push({campaign_id:a.id,name:a.name,x:l.valueOf(),y:a.y})}),Highcharts.chart("overview_chart",{chart:{zoomType:"x",type:"areaspline"},title:{text:"Phishing Success Overview"},xAxis:{type:"datetime",dateTimeLabelFormats:{second:"%l:%M:%S",minute:"%l:%M",hour:"%l:%M",day:"%b %d, %Y",week:"%b %d, %Y",month:"%b %Y"}},yAxis:{min:0,max:100,title:{text:"% of Success"}},tooltip:{formatter:function(){return Highcharts.dateFormat("%A, %b %d %l:%M:%S %P",new Date(this.x))+"
    "+this.point.name+"
    % Success: "+this.y+"%"}},legend:{enabled:!1},plotOptions:{series:{marker:{enabled:!0,symbol:"circle",radius:3},cursor:"pointer",point:{events:{click:function(e){window.location.href="/campaigns/"+this.campaign_id}}}}},credits:{enabled:!1},series:[{data:t,color:"#f05b4f",fillOpacity:.5}]})}var campaigns=[],statuses={"Email Sent":{color:"#1abc9c",label:"label-success",icon:"fa-envelope",point:"ct-point-sent"},"Emails Sent":{color:"#1abc9c",label:"label-success",icon:"fa-envelope",point:"ct-point-sent"},"In progress":{label:"label-primary"},Queued:{label:"label-info"},Completed:{label:"label-success"},"Email Opened":{color:"#f9bf3b",label:"label-warning",icon:"fa-envelope",point:"ct-point-opened"},"Email Reported":{color:"#45d6ef",label:"label-warning",icon:"fa-bullhorne",point:"ct-point-reported"},"Clicked Link":{color:"#F39C12",label:"label-clicked",icon:"fa-mouse-pointer",point:"ct-point-clicked"},Success:{color:"#f05b4f",label:"label-danger",icon:"fa-exclamation",point:"ct-point-clicked"},Error:{color:"#6c7a89",label:"label-default",icon:"fa-times",point:"ct-point-error"},"Error Sending Email":{color:"#6c7a89",label:"label-default",icon:"fa-times",point:"ct-point-error"},"Submitted Data":{color:"#f05b4f",label:"label-danger",icon:"fa-exclamation",point:"ct-point-clicked"},Unknown:{color:"#6c7a89",label:"label-default",icon:"fa-question",point:"ct-point-error"},Sending:{color:"#428bca",label:"label-primary",icon:"fa-spinner",point:"ct-point-sending"},"Campaign Created":{label:"label-success",icon:"fa-rocket"}},statsMapping={sent:"Email Sent",opened:"Email Opened",email_reported:"Email Reported",clicked:"Clicked Link",submitted_data:"Submitted Data"};$(document).ready(function(){Highcharts.setOptions({global:{useUTC:!1}}),api.campaigns.summary().success(function(e){$("#loading").hide(),campaigns=e.campaigns,campaigns.length>0?($("#dashboard").show(),campaignTable=$("#campaignTable").DataTable({columnDefs:[{orderable:!1,targets:"no-sort"},{className:"color-sent",targets:[2]},{className:"color-opened",targets:[3]},{className:"color-clicked",targets:[4]},{className:"color-success",targets:[5]},{className:"color-reported",targets:[6]}],order:[[1,"desc"]]}),$.each(campaigns,function(e,t){var a,l=moment(t.created_date).format("MMMM Do YYYY, h:mm:ss a"),i=statuses[t.status].label||"label-default";if(moment(t.launch_date).isAfter(moment())){a="Scheduled to start: "+moment(t.launch_date).format("MMMM Do YYYY, h:mm:ss a");var n=a+"

    Number of recipients: "+t.stats.total}else{a="Launch Date: "+moment(t.launch_date).format("MMMM Do YYYY, h:mm:ss a");var n=a+"

    Number of recipients: "+t.stats.total+"

    Emails opened: "+t.stats.opened+"

    Emails clicked: "+t.stats.clicked+"

    Submitted Credentials: "+t.stats.submitted_data+"

    Errors : "+t.stats.error+"

    Reported : "+t.stats.email_reported}campaignTable.row.add([escapeHtml(t.name),l,t.stats.sent,t.stats.opened,t.stats.clicked,t.stats.submitted_data,t.stats.email_reported,''+t.status+"",""]).draw(),$('[data-toggle="tooltip"]').tooltip()}),generateStatsPieCharts(campaigns),generateTimelineChart(campaigns)):$("#emptyMessage").show()}).error(function(){errorFlash("Error fetching campaigns")})}); \ No newline at end of file +var campaigns=[],statuses={"Email Sent":{color:"#1abc9c",label:"label-success",icon:"fa-envelope",point:"ct-point-sent"},"Emails Sent":{color:"#1abc9c",label:"label-success",icon:"fa-envelope",point:"ct-point-sent"},"In progress":{label:"label-primary"},Queued:{label:"label-info"},Completed:{label:"label-success"},"Email Opened":{color:"#f9bf3b",label:"label-warning",icon:"fa-envelope",point:"ct-point-opened"},"Email Reported":{color:"#45d6ef",label:"label-warning",icon:"fa-bullhorne",point:"ct-point-reported"},"Clicked Link":{color:"#F39C12",label:"label-clicked",icon:"fa-mouse-pointer",point:"ct-point-clicked"},Success:{color:"#f05b4f",label:"label-danger",icon:"fa-exclamation",point:"ct-point-clicked"},Error:{color:"#6c7a89",label:"label-default",icon:"fa-times",point:"ct-point-error"},"Error Sending Email":{color:"#6c7a89",label:"label-default",icon:"fa-times",point:"ct-point-error"},"Submitted Data":{color:"#f05b4f",label:"label-danger",icon:"fa-exclamation",point:"ct-point-clicked"},Unknown:{color:"#6c7a89",label:"label-default",icon:"fa-question",point:"ct-point-error"},Sending:{color:"#428bca",label:"label-primary",icon:"fa-spinner",point:"ct-point-sending"},"Campaign Created":{label:"label-success",icon:"fa-rocket"}},statsMapping={sent:"Email Sent",opened:"Email Opened",email_reported:"Email Reported",clicked:"Clicked Link",submitted_data:"Submitted Data"};function deleteCampaign(e){confirm("Delete "+campaigns[e].name+"?")&&api.campaignId.delete(campaigns[e].id).success(function(e){successFlash(e.message),location.reload()})}function renderPieChart(i){return Highcharts.chart(i.elemId,{chart:{type:"pie",events:{load:function(){var e=this,t=e.renderer,a=e.series[0],l=e.plotLeft+a.center[0],n=e.plotTop+a.center[1];this.innerText=t.text(i.data[0].count,l,n).attr({"text-anchor":"middle","font-size":"16px","font-weight":"bold",fill:i.colors[0],"font-family":"Helvetica,Arial,sans-serif"}).add()},render:function(){this.innerText.attr({text:i.data[0].count})}}},title:{text:i.title},plotOptions:{pie:{innerSize:"80%",dataLabels:{enabled:!1}}},credits:{enabled:!1},tooltip:{formatter:function(){return null!=this.key&&''+this.point.name+": "+this.y+"%
    "}},series:[{data:i.data,colors:i.colors}]})}function generateStatsPieCharts(e){var a=[],l={},n=0;$.each(e,function(e,t){$.each(t.stats,function(e,t){if("total"==e)return n+=t,!0;l[e]?l[e]+=t:l[e]=t})}),$.each(l,function(e,t){if(!(e in statsMapping))return!0;status_label=statsMapping[e],a.push({name:status_label,y:Math.floor(t/n*100),count:t}),a.push({name:"",y:100-Math.floor(t/n*100)});renderPieChart({elemId:e+"_chart",title:status_label,name:e,data:a,colors:[statuses[status_label].color,"#dddddd"]});a=[]})}function generateTimelineChart(e){var l=[];$.each(e,function(e,t){var a=moment.utc(t.created_date).local();t.y=0,t.y+=t.stats.clicked,t.y=Math.floor(t.y/t.stats.total*100),l.push({campaign_id:t.id,name:t.name,x:a.valueOf(),y:t.y})}),Highcharts.chart("overview_chart",{chart:{zoomType:"x",type:"areaspline"},title:{text:"Phishing Success Overview"},xAxis:{type:"datetime",dateTimeLabelFormats:{second:"%l:%M:%S",minute:"%l:%M",hour:"%l:%M",day:"%b %d, %Y",week:"%b %d, %Y",month:"%b %Y"}},yAxis:{min:0,max:100,title:{text:"% of Success"}},tooltip:{formatter:function(){return Highcharts.dateFormat("%A, %b %d %l:%M:%S %P",new Date(this.x))+"
    "+this.point.name+"
    % Success: "+this.y+"%"}},legend:{enabled:!1},plotOptions:{series:{marker:{enabled:!0,symbol:"circle",radius:3},cursor:"pointer",point:{events:{click:function(e){window.location.href="/campaigns/"+this.campaign_id}}}}},credits:{enabled:!1},series:[{data:l,color:"#f05b4f",fillOpacity:.5}]})}$(document).ready(function(){Highcharts.setOptions({global:{useUTC:!1}}),api.campaigns.summary().success(function(e){$("#loading").hide(),0<(campaigns=e.campaigns).length?($("#dashboard").show(),campaignTable=$("#campaignTable").DataTable({columnDefs:[{orderable:!1,targets:"no-sort"},{className:"color-sent",targets:[2]},{className:"color-opened",targets:[3]},{className:"color-clicked",targets:[4]},{className:"color-success",targets:[5]},{className:"color-reported",targets:[6]}],order:[[1,"desc"]]}),$.each(campaigns,function(e,t){var a=moment(t.created_date).format("MMMM Do YYYY, h:mm:ss a"),l=statuses[t.status].label||"label-default";if(moment(t.launch_date).isAfter(moment()))var n="Scheduled to start: "+moment(t.launch_date).format("MMMM Do YYYY, h:mm:ss a")+"

    Number of recipients: "+t.stats.total;else n="Launch Date: "+moment(t.launch_date).format("MMMM Do YYYY, h:mm:ss a")+"

    Number of recipients: "+t.stats.total+"

    Emails opened: "+t.stats.opened+"

    Emails clicked: "+t.stats.clicked+"

    Submitted Credentials: "+t.stats.submitted_data+"

    Errors : "+t.stats.error+"

    Reported : "+t.stats.email_reported;campaignTable.row.add([escapeHtml(t.name),a,t.stats.sent,t.stats.opened,t.stats.clicked,t.stats.submitted_data,t.stats.email_reported,''+t.status+"",""]).draw(),$('[data-toggle="tooltip"]').tooltip()}),generateStatsPieCharts(campaigns),generateTimelineChart(campaigns)):$("#emptyMessage").show()}).error(function(){errorFlash("Error fetching campaigns")})}); \ No newline at end of file diff --git a/static/js/dist/app/gophish.min.js b/static/js/dist/app/gophish.min.js index 526ae20d..2decaa38 100644 --- a/static/js/dist/app/gophish.min.js +++ b/static/js/dist/app/gophish.min.js @@ -1 +1 @@ -function errorFlash(e){$("#flashes").empty(),$("#flashes").append('
    '+e+"
    ")}function successFlash(e){$("#flashes").empty(),$("#flashes").append('
    '+e+"
    ")}function modalError(e){$("#modal\\.flashes").empty().append('
    '+e+"
    ")}function query(e,t,n,r){return $.ajax({url:"/api"+e,async:r,method:t,data:JSON.stringify(n),dataType:"json",contentType:"application/json",beforeSend:function(e){e.setRequestHeader("Authorization","Bearer "+user.api_key)}})}function escapeHtml(e){return $("
    ").text(e).html()}function unescapeHtml(e){return $("
    ").html(e).text()}var capitalize=function(e){return e.charAt(0).toUpperCase()+e.slice(1)},api={campaigns:{get:function(){return query("/campaigns/","GET",{},!1)},post:function(e){return query("/campaigns/","POST",e,!1)},summary:function(){return query("/campaigns/summary","GET",{},!1)}},campaignId:{get:function(e){return query("/campaigns/"+e,"GET",{},!0)},delete:function(e){return query("/campaigns/"+e,"DELETE",{},!1)},results:function(e){return query("/campaigns/"+e+"/results","GET",{},!0)},complete:function(e){return query("/campaigns/"+e+"/complete","GET",{},!0)},summary:function(e){return query("/campaigns/"+e+"/summary","GET",{},!0)}},groups:{get:function(){return query("/groups/","GET",{},!1)},post:function(e){return query("/groups/","POST",e,!1)},summary:function(){return query("/groups/summary","GET",{},!0)}},groupId:{get:function(e){return query("/groups/"+e,"GET",{},!1)},put:function(e){return query("/groups/"+e.id,"PUT",e,!1)},delete:function(e){return query("/groups/"+e,"DELETE",{},!1)}},templates:{get:function(){return query("/templates/","GET",{},!1)},post:function(e){return query("/templates/","POST",e,!1)}},templateId:{get:function(e){return query("/templates/"+e,"GET",{},!1)},put:function(e){return query("/templates/"+e.id,"PUT",e,!1)},delete:function(e){return query("/templates/"+e,"DELETE",{},!1)}},pages:{get:function(){return query("/pages/","GET",{},!1)},post:function(e){return query("/pages/","POST",e,!1)}},pageId:{get:function(e){return query("/pages/"+e,"GET",{},!1)},put:function(e){return query("/pages/"+e.id,"PUT",e,!1)},delete:function(e){return query("/pages/"+e,"DELETE",{},!1)}},SMTP:{get:function(){return query("/smtp/","GET",{},!1)},post:function(e){return query("/smtp/","POST",e,!1)}},SMTPId:{get:function(e){return query("/smtp/"+e,"GET",{},!1)},put:function(e){return query("/smtp/"+e.id,"PUT",e,!1)},delete:function(e){return query("/smtp/"+e,"DELETE",{},!1)}},import_email:function(e){return query("/import/email","POST",e,!1)},clone_site:function(e){return query("/import/site","POST",e,!1)},send_test_email:function(e){return query("/util/send_test_email","POST",e,!0)},reset:function(){return query("/reset","POST",{},!0)}};$(document).ready(function(){var e=location.pathname;$(".nav-sidebar li").each(function(){var t=$(this);t.find("a").attr("href")===e&&t.addClass("active")}),$.fn.dataTable.moment("MMMM Do YYYY, h:mm:ss a"),$('[data-toggle="tooltip"]').tooltip()}); \ No newline at end of file +function errorFlash(e){$("#flashes").empty(),$("#flashes").append('
    '+e+"
    ")}function successFlash(e){$("#flashes").empty(),$("#flashes").append('
    '+e+"
    ")}function modalError(e){$("#modal\\.flashes").empty().append('
    '+e+"
    ")}function query(e,t,n,r){return $.ajax({url:"/api"+e,async:r,method:t,data:JSON.stringify(n),dataType:"json",contentType:"application/json",beforeSend:function(e){e.setRequestHeader("Authorization","Bearer "+user.api_key)}})}function escapeHtml(e){return $("
    ").text(e).html()}function unescapeHtml(e){return $("
    ").html(e).text()}var capitalize=function(e){return e.charAt(0).toUpperCase()+e.slice(1)},api={campaigns:{get:function(){return query("/campaigns/","GET",{},!1)},post:function(e){return query("/campaigns/","POST",e,!1)},summary:function(){return query("/campaigns/summary","GET",{},!1)}},campaignId:{get:function(e){return query("/campaigns/"+e,"GET",{},!0)},delete:function(e){return query("/campaigns/"+e,"DELETE",{},!1)},results:function(e){return query("/campaigns/"+e+"/results","GET",{},!0)},complete:function(e){return query("/campaigns/"+e+"/complete","GET",{},!0)},summary:function(e){return query("/campaigns/"+e+"/summary","GET",{},!0)}},groups:{get:function(){return query("/groups/","GET",{},!1)},post:function(e){return query("/groups/","POST",e,!1)},summary:function(){return query("/groups/summary","GET",{},!0)}},groupId:{get:function(e){return query("/groups/"+e,"GET",{},!1)},put:function(e){return query("/groups/"+e.id,"PUT",e,!1)},delete:function(e){return query("/groups/"+e,"DELETE",{},!1)}},templates:{get:function(){return query("/templates/","GET",{},!1)},post:function(e){return query("/templates/","POST",e,!1)}},templateId:{get:function(e){return query("/templates/"+e,"GET",{},!1)},put:function(e){return query("/templates/"+e.id,"PUT",e,!1)},delete:function(e){return query("/templates/"+e,"DELETE",{},!1)}},pages:{get:function(){return query("/pages/","GET",{},!1)},post:function(e){return query("/pages/","POST",e,!1)}},pageId:{get:function(e){return query("/pages/"+e,"GET",{},!1)},put:function(e){return query("/pages/"+e.id,"PUT",e,!1)},delete:function(e){return query("/pages/"+e,"DELETE",{},!1)}},SMTP:{get:function(){return query("/smtp/","GET",{},!1)},post:function(e){return query("/smtp/","POST",e,!1)}},SMTPId:{get:function(e){return query("/smtp/"+e,"GET",{},!1)},put:function(e){return query("/smtp/"+e.id,"PUT",e,!1)},delete:function(e){return query("/smtp/"+e,"DELETE",{},!1)}},import_email:function(e){return query("/import/email","POST",e,!1)},clone_site:function(e){return query("/import/site","POST",e,!1)},send_test_email:function(e){return query("/util/send_test_email","POST",e,!0)},reset:function(){return query("/reset","POST",{},!0)}};$(document).ready(function(){var t=location.pathname;$(".nav-sidebar li").each(function(){var e=$(this);e.find("a").attr("href")===t&&e.addClass("active")}),$.fn.dataTable.moment("MMMM Do YYYY, h:mm:ss a"),$('[data-toggle="tooltip"]').tooltip()}); \ No newline at end of file diff --git a/static/js/dist/app/landing_pages.min.js b/static/js/dist/app/landing_pages.min.js index 477a8f6f..23226a32 100644 --- a/static/js/dist/app/landing_pages.min.js +++ b/static/js/dist/app/landing_pages.min.js @@ -1 +1 @@ -function save(e){var a={};a.name=$("#name").val(),editor=CKEDITOR.instances.html_editor,a.html=editor.getData(),a.capture_credentials=$("#capture_credentials_checkbox").prop("checked"),a.capture_passwords=$("#capture_passwords_checkbox").prop("checked"),a.redirect_url=$("#redirect_url_input").val(),-1!=e?(a.id=pages[e].id,api.pageId.put(a).success(function(e){successFlash("Page edited successfully!"),load(),dismiss()})):api.pages.post(a).success(function(e){successFlash("Page added successfully!"),load(),dismiss()}).error(function(e){modalError(e.responseJSON.message)})}function dismiss(){$("#modal\\.flashes").empty(),$("#name").val(""),$("#html_editor").val(""),$("#url").val(""),$("#redirect_url_input").val(""),$("#modal").find("input[type='checkbox']").prop("checked",!1),$("#capture_passwords").hide(),$("#redirect_url").hide(),$("#modal").modal("hide")}function importSite(){url=$("#url").val(),url?api.clone_site({url:url,include_resources:!1}).success(function(e){$("#html_editor").val(e.html),CKEDITOR.instances.html_editor.setMode("wysiwyg"),$("#importSiteModal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)}):modalError("No URL Specified!")}function edit(e){$("#modalSubmit").unbind("click").click(function(){save(e)}),$("#html_editor").ckeditor(),setupAutocomplete(CKEDITOR.instances.html_editor);var a={};-1!=e&&(a=pages[e],$("#name").val(a.name),$("#html_editor").val(a.html),$("#capture_credentials_checkbox").prop("checked",a.capture_credentials),$("#capture_passwords_checkbox").prop("checked",a.capture_passwords),$("#redirect_url_input").val(a.redirect_url),a.capture_credentials&&($("#capture_passwords").show(),$("#redirect_url").show()))}function copy(e){$("#modalSubmit").unbind("click").click(function(){save(-1)}),$("#html_editor").ckeditor();var a=pages[e];$("#name").val("Copy of "+a.name),$("#html_editor").val(a.html)}function load(){$("#pagesTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.pages.get().success(function(e){pages=e,$("#loading").hide(),pages.length>0?($("#pagesTable").show(),pagesTable=$("#pagesTable").DataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]}),pagesTable.clear(),$.each(pages,function(e,a){pagesTable.row.add([escapeHtml(a.name),moment(a.modified_date).format("MMMM Do YYYY, h:mm:ss a"),"
    \t\t
    "]).draw()}),$('[data-toggle="tooltip"]').tooltip()):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching pages")})}var pages=[],deletePage=function(e){swal({title:"Are you sure?",text:"This will delete the landing page. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(pages[e].name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.pageId.delete(pages[e].id).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Landing Page Deleted!","This landing page has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};$(document).ready(function(){$(".modal").on("hidden.bs.modal",function(e){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(e){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$.fn.modal.Constructor.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(e){this.$element[0]===e.target||this.$element.has(e.target).length||$(e.target).closest(".cke_dialog, .cke").length||this.$element.trigger("focus")},this))},$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(e){dismiss()}),$("#capture_credentials_checkbox").change(function(){$("#capture_passwords").toggle(),$("#redirect_url").toggle()}),CKEDITOR.on("dialogDefinition",function(e){var a=e.data.name,t=e.data.definition;if("link"==a){t.minWidth=500,t.minHeight=100;t.getContents("info").get("linkType").hidden=!0}}),load()}); \ No newline at end of file +var pages=[];function save(e){var a={};a.name=$("#name").val(),editor=CKEDITOR.instances.html_editor,a.html=editor.getData(),a.capture_credentials=$("#capture_credentials_checkbox").prop("checked"),a.capture_passwords=$("#capture_passwords_checkbox").prop("checked"),a.redirect_url=$("#redirect_url_input").val(),-1!=e?(a.id=pages[e].id,api.pageId.put(a).success(function(e){successFlash("Page edited successfully!"),load(),dismiss()})):api.pages.post(a).success(function(e){successFlash("Page added successfully!"),load(),dismiss()}).error(function(e){modalError(e.responseJSON.message)})}function dismiss(){$("#modal\\.flashes").empty(),$("#name").val(""),$("#html_editor").val(""),$("#url").val(""),$("#redirect_url_input").val(""),$("#modal").find("input[type='checkbox']").prop("checked",!1),$("#capture_passwords").hide(),$("#redirect_url").hide(),$("#modal").modal("hide")}var deletePage=function(e){swal({title:"Are you sure?",text:"This will delete the landing page. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(pages[e].name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.pageId.delete(pages[e].id).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Landing Page Deleted!","This landing page has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};function importSite(){url=$("#url").val(),url?api.clone_site({url:url,include_resources:!1}).success(function(e){$("#html_editor").val(e.html),CKEDITOR.instances.html_editor.setMode("wysiwyg"),$("#importSiteModal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)}):modalError("No URL Specified!")}function edit(e){$("#modalSubmit").unbind("click").click(function(){save(e)}),$("#html_editor").ckeditor(),setupAutocomplete(CKEDITOR.instances.html_editor);var a={};-1!=e&&(a=pages[e],$("#name").val(a.name),$("#html_editor").val(a.html),$("#capture_credentials_checkbox").prop("checked",a.capture_credentials),$("#capture_passwords_checkbox").prop("checked",a.capture_passwords),$("#redirect_url_input").val(a.redirect_url),a.capture_credentials&&($("#capture_passwords").show(),$("#redirect_url").show()))}function copy(e){$("#modalSubmit").unbind("click").click(function(){save(-1)}),$("#html_editor").ckeditor();var a=pages[e];$("#name").val("Copy of "+a.name),$("#html_editor").val(a.html)}function load(){$("#pagesTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.pages.get().success(function(e){pages=e,$("#loading").hide(),0\t\t
    "]).draw()}),$('[data-toggle="tooltip"]').tooltip()):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching pages")})}$(document).ready(function(){$(".modal").on("hidden.bs.modal",function(e){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(e){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$.fn.modal.Constructor.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(e){this.$element[0]===e.target||this.$element.has(e.target).length||$(e.target).closest(".cke_dialog, .cke").length||this.$element.trigger("focus")},this))},$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(e){dismiss()}),$("#capture_credentials_checkbox").change(function(){$("#capture_passwords").toggle(),$("#redirect_url").toggle()}),CKEDITOR.on("dialogDefinition",function(e){var a=e.data.name,t=e.data.definition;"link"==a&&(t.minWidth=500,t.minHeight=100,t.getContents("info").get("linkType").hidden=!0)}),load()}); \ No newline at end of file diff --git a/static/js/dist/app/sending_profiles.min.js b/static/js/dist/app/sending_profiles.min.js index da9e0936..85f9dd7b 100644 --- a/static/js/dist/app/sending_profiles.min.js +++ b/static/js/dist/app/sending_profiles.min.js @@ -1 +1 @@ -function sendTestEmail(){var e=[];$.each($("#headersTable").DataTable().rows().data(),function(a,t){e.push({key:unescapeHtml(t[0]),value:unescapeHtml(t[1])})});var a={template:{},first_name:$("input[name=to_first_name]").val(),last_name:$("input[name=to_last_name]").val(),email:$("input[name=to_email]").val(),position:$("input[name=to_position]").val(),url:"",smtp:{from_address:$("#from").val(),host:$("#host").val(),username:$("#username").val(),password:$("#password").val(),ignore_cert_errors:$("#ignore_cert_errors").prop("checked"),headers:e}};btnHtml=$("#sendTestModalSubmit").html(),$("#sendTestModalSubmit").html(' Sending'),api.send_test_email(a).success(function(e){$("#sendTestEmailModal\\.flashes").empty().append('
    \t Email Sent!
    '),$("#sendTestModalSubmit").html(btnHtml)}).error(function(e){$("#sendTestEmailModal\\.flashes").empty().append('
    \t '+e.responseJSON.message+"
    "),$("#sendTestModalSubmit").html(btnHtml)})}function save(e){var a={headers:[]};$.each($("#headersTable").DataTable().rows().data(),function(e,t){a.headers.push({key:unescapeHtml(t[0]),value:unescapeHtml(t[1])})}),a.name=$("#name").val(),a.interface_type=$("#interface_type").val(),a.from_address=$("#from").val(),a.host=$("#host").val(),a.username=$("#username").val(),a.password=$("#password").val(),a.ignore_cert_errors=$("#ignore_cert_errors").prop("checked"),-1!=e?(a.id=profiles[e].id,api.SMTPId.put(a).success(function(e){successFlash("Profile edited successfully!"),load(),dismiss()}).error(function(e){modalError(e.responseJSON.message)})):api.SMTP.post(a).success(function(e){successFlash("Profile added successfully!"),load(),dismiss()}).error(function(e){modalError(e.responseJSON.message)})}function dismiss(){$("#modal\\.flashes").empty(),$("#name").val(""),$("#interface_type").val("SMTP"),$("#from").val(""),$("#host").val(""),$("#username").val(""),$("#password").val(""),$("#ignore_cert_errors").prop("checked",!0),$("#headersTable").dataTable().DataTable().clear().draw(),$("#modal").modal("hide")}function edit(e){headers=$("#headersTable").dataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]}),$("#modalSubmit").unbind("click").click(function(){save(e)});var a={};-1!=e&&(a=profiles[e],$("#name").val(a.name),$("#interface_type").val(a.interface_type),$("#from").val(a.from_address),$("#host").val(a.host),$("#username").val(a.username),$("#password").val(a.password),$("#ignore_cert_errors").prop("checked",a.ignore_cert_errors),$.each(a.headers,function(e,a){addCustomHeader(a.key,a.value)}))}function copy(e){$("#modalSubmit").unbind("click").click(function(){save(-1)});var a={};a=profiles[e],$("#name").val("Copy of "+a.name),$("#interface_type").val(a.interface_type),$("#from").val(a.from_address),$("#host").val(a.host),$("#username").val(a.username),$("#password").val(a.password),$("#ignore_cert_errors").prop("checked",a.ignore_cert_errors)}function load(){$("#profileTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.SMTP.get().success(function(e){profiles=e,$("#loading").hide(),profiles.length>0?($("#profileTable").show(),profileTable=$("#profileTable").DataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]}),profileTable.clear(),$.each(profiles,function(e,a){profileTable.row.add([escapeHtml(a.name),a.interface_type,moment(a.modified_date).format("MMMM Do YYYY, h:mm:ss a"),"
    \t\t
    "]).draw()}),$('[data-toggle="tooltip"]').tooltip()):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching profiles")})}function addCustomHeader(e,a){var t=[escapeHtml(e),escapeHtml(a),''],s=headers.DataTable(),o=s.column(0).data().indexOf(escapeHtml(e));o>=0?s.row(o,{order:"index"}).data(t):s.row.add(t),s.draw()}var profiles=[],dismissSendTestEmailModal=function(){$("#sendTestEmailModal\\.flashes").empty(),$("#sendTestModalSubmit").html(" Send")},deleteProfile=function(e){swal({title:"Are you sure?",text:"This will delete the sending profile. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(profiles[e].name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.SMTPId.delete(profiles[e].id).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Sending Profile Deleted!","This sending profile has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};$(document).ready(function(){$(".modal").on("hidden.bs.modal",function(e){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(e){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$.fn.modal.Constructor.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(e){this.$element[0]===e.target||this.$element.has(e.target).length||$(e.target).closest(".cke_dialog, .cke").length||this.$element.trigger("focus")},this))},$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(e){dismiss()}),$("#sendTestEmailModal").on("hidden.bs.modal",function(e){dismissSendTestEmailModal()}),$("#headersForm").on("submit",function(){return headerKey=$("#headerKey").val(),headerValue=$("#headerValue").val(),""!=headerKey&&""!=headerValue&&(addCustomHeader(headerKey,headerValue),$("#headersForm>div>input").val(""),$("#headerKey").focus(),!1)}),$("#headersTable").on("click","span>i.fa-trash-o",function(){headers.DataTable().row($(this).parents("tr")).remove().draw()}),load()}); \ No newline at end of file +var profiles=[];function sendTestEmail(){var t=[];$.each($("#headersTable").DataTable().rows().data(),function(e,a){t.push({key:unescapeHtml(a[0]),value:unescapeHtml(a[1])})});var e={template:{},first_name:$("input[name=to_first_name]").val(),last_name:$("input[name=to_last_name]").val(),email:$("input[name=to_email]").val(),position:$("input[name=to_position]").val(),url:"",smtp:{from_address:$("#from").val(),host:$("#host").val(),username:$("#username").val(),password:$("#password").val(),ignore_cert_errors:$("#ignore_cert_errors").prop("checked"),headers:t}};btnHtml=$("#sendTestModalSubmit").html(),$("#sendTestModalSubmit").html(' Sending'),api.send_test_email(e).success(function(e){$("#sendTestEmailModal\\.flashes").empty().append('
    \t Email Sent!
    '),$("#sendTestModalSubmit").html(btnHtml)}).error(function(e){$("#sendTestEmailModal\\.flashes").empty().append('
    \t '+e.responseJSON.message+"
    "),$("#sendTestModalSubmit").html(btnHtml)})}function save(e){var t={headers:[]};$.each($("#headersTable").DataTable().rows().data(),function(e,a){t.headers.push({key:unescapeHtml(a[0]),value:unescapeHtml(a[1])})}),t.name=$("#name").val(),t.interface_type=$("#interface_type").val(),t.from_address=$("#from").val(),t.host=$("#host").val(),t.username=$("#username").val(),t.password=$("#password").val(),t.ignore_cert_errors=$("#ignore_cert_errors").prop("checked"),-1!=e?(t.id=profiles[e].id,api.SMTPId.put(t).success(function(e){successFlash("Profile edited successfully!"),load(),dismiss()}).error(function(e){modalError(e.responseJSON.message)})):api.SMTP.post(t).success(function(e){successFlash("Profile added successfully!"),load(),dismiss()}).error(function(e){modalError(e.responseJSON.message)})}function dismiss(){$("#modal\\.flashes").empty(),$("#name").val(""),$("#interface_type").val("SMTP"),$("#from").val(""),$("#host").val(""),$("#username").val(""),$("#password").val(""),$("#ignore_cert_errors").prop("checked",!0),$("#headersTable").dataTable().DataTable().clear().draw(),$("#modal").modal("hide")}var dismissSendTestEmailModal=function(){$("#sendTestEmailModal\\.flashes").empty(),$("#sendTestModalSubmit").html(" Send")},deleteProfile=function(e){swal({title:"Are you sure?",text:"This will delete the sending profile. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(profiles[e].name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.SMTPId.delete(profiles[e].id).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Sending Profile Deleted!","This sending profile has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};function edit(e){headers=$("#headersTable").dataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]}),$("#modalSubmit").unbind("click").click(function(){save(e)});var a={};-1!=e&&(a=profiles[e],$("#name").val(a.name),$("#interface_type").val(a.interface_type),$("#from").val(a.from_address),$("#host").val(a.host),$("#username").val(a.username),$("#password").val(a.password),$("#ignore_cert_errors").prop("checked",a.ignore_cert_errors),$.each(a.headers,function(e,a){addCustomHeader(a.key,a.value)}))}function copy(e){$("#modalSubmit").unbind("click").click(function(){save(-1)});var a;a=profiles[e],$("#name").val("Copy of "+a.name),$("#interface_type").val(a.interface_type),$("#from").val(a.from_address),$("#host").val(a.host),$("#username").val(a.username),$("#password").val(a.password),$("#ignore_cert_errors").prop("checked",a.ignore_cert_errors)}function load(){$("#profileTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.SMTP.get().success(function(e){profiles=e,$("#loading").hide(),0\t\t
    "]).draw()}),$('[data-toggle="tooltip"]').tooltip()):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching profiles")})}function addCustomHeader(e,a){var t=[escapeHtml(e),escapeHtml(a),''],s=headers.DataTable(),o=s.column(0).data().indexOf(escapeHtml(e));0<=o?s.row(o,{order:"index"}).data(t):s.row.add(t),s.draw()}$(document).ready(function(){$(".modal").on("hidden.bs.modal",function(e){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(e){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$.fn.modal.Constructor.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(e){this.$element[0]===e.target||this.$element.has(e.target).length||$(e.target).closest(".cke_dialog, .cke").length||this.$element.trigger("focus")},this))},$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(e){dismiss()}),$("#sendTestEmailModal").on("hidden.bs.modal",function(e){dismissSendTestEmailModal()}),$("#headersForm").on("submit",function(){return headerKey=$("#headerKey").val(),headerValue=$("#headerValue").val(),""==headerKey||""==headerValue||(addCustomHeader(headerKey,headerValue),$("#headersForm>div>input").val(""),$("#headerKey").focus()),!1}),$("#headersTable").on("click","span>i.fa-trash-o",function(){headers.DataTable().row($(this).parents("tr")).remove().draw()}),load()}); \ No newline at end of file diff --git a/static/js/dist/app/templates.min.js b/static/js/dist/app/templates.min.js index 643f36b6..36f58287 100644 --- a/static/js/dist/app/templates.min.js +++ b/static/js/dist/app/templates.min.js @@ -1 +1 @@ -function save(t){var e={attachments:[]};e.name=$("#name").val(),e.subject=$("#subject").val(),e.html=CKEDITOR.instances.html_editor.getData(),e.html=e.html.replace(/https?:\/\/{{\.URL}}/gi,"{{.URL}}"),$("#use_tracker_checkbox").prop("checked")?-1==e.html.indexOf("{{.Tracker}}")&&-1==e.html.indexOf("{{.TrackingUrl}}")&&(e.html=e.html.replace("","{{.Tracker}}")):e.html=e.html.replace("{{.Tracker}}",""),e.text=$("#text_editor").val(),$.each($("#attachmentsTable").DataTable().rows().data(),function(t,a){e.attachments.push({name:unescapeHtml(a[1]),content:a[3],type:a[4]})}),-1!=t?(e.id=templates[t].id,api.templateId.put(e).success(function(t){successFlash("Template edited successfully!"),load(),dismiss()}).error(function(t){modalError(t.responseJSON.message)})):api.templates.post(e).success(function(t){successFlash("Template added successfully!"),load(),dismiss()}).error(function(t){modalError(t.responseJSON.message)})}function dismiss(){$("#modal\\.flashes").empty(),$("#attachmentsTable").dataTable().DataTable().clear().draw(),$("#name").val(""),$("#subject").val(""),$("#text_editor").val(""),$("#html_editor").val(""),$("#modal").modal("hide")}function deleteTemplate(t){confirm("Delete "+templates[t].name+"?")&&api.templateId.delete(templates[t].id).success(function(t){successFlash(t.message),load()})}function attach(t){attachmentsTable=$("#attachmentsTable").DataTable({destroy:!0,order:[[1,"asc"]],columnDefs:[{orderable:!1,targets:"no-sort"},{sClass:"datatable_hidden",targets:[3,4]}]}),$.each(t,function(t,e){var a=new FileReader;a.onload=function(t){var o=icons[e.type]||"fa-file-o";attachmentsTable.row.add(['',escapeHtml(e.name),'',a.result.split(",")[1],e.type||"application/octet-stream"]).draw()},a.onerror=function(t){console.log(t)},a.readAsDataURL(e)})}function edit(t){$("#modalSubmit").unbind("click").click(function(){save(t)}),$("#attachmentUpload").unbind("click").click(function(){this.value=null}),$("#html_editor").ckeditor(),setupAutocomplete(CKEDITOR.instances.html_editor),$("#attachmentsTable").show(),attachmentsTable=$("#attachmentsTable").DataTable({destroy:!0,order:[[1,"asc"]],columnDefs:[{orderable:!1,targets:"no-sort"},{sClass:"datatable_hidden",targets:[3,4]}]});var e={attachments:[]};-1!=t&&(e=templates[t],$("#name").val(e.name),$("#subject").val(e.subject),$("#html_editor").val(e.html),$("#text_editor").val(e.text),$.each(e.attachments,function(t,e){var a=icons[e.type]||"fa-file-o";attachmentsTable.row.add(['',escapeHtml(e.name),'',e.content,e.type||"application/octet-stream"]).draw()}),-1!=e.html.indexOf("{{.Tracker}}")?$("#use_tracker_checkbox").prop("checked",!0):$("#use_tracker_checkbox").prop("checked",!1)),$("#attachmentsTable").unbind("click").on("click","span>i.fa-trash-o",function(){attachmentsTable.row($(this).parents("tr")).remove().draw()})}function copy(t){$("#modalSubmit").unbind("click").click(function(){save(-1)}),$("#attachmentUpload").unbind("click").click(function(){this.value=null}),$("#html_editor").ckeditor(),$("#attachmentsTable").show(),attachmentsTable=$("#attachmentsTable").DataTable({destroy:!0,order:[[1,"asc"]],columnDefs:[{orderable:!1,targets:"no-sort"},{sClass:"datatable_hidden",targets:[3,4]}]});var e={attachments:[]};e=templates[t],$("#name").val("Copy of "+e.name),$("#subject").val(e.subject),$("#html_editor").val(e.html),$("#text_editor").val(e.text),$.each(e.attachments,function(t,e){var a=icons[e.type]||"fa-file-o";attachmentsTable.row.add(['',escapeHtml(e.name),'',e.content,e.type||"application/octet-stream"]).draw()}),$("#attachmentsTable").unbind("click").on("click","span>i.fa-trash-o",function(){attachmentsTable.row($(this).parents("tr")).remove().draw()}),-1!=e.html.indexOf("{{.Tracker}}")?$("#use_tracker_checkbox").prop("checked",!0):$("#use_tracker_checkbox").prop("checked",!1)}function importEmail(){raw=$("#email_content").val(),convert_links=$("#convert_links_checkbox").prop("checked"),raw?api.import_email({content:raw,convert_links:convert_links}).success(function(t){$("#text_editor").val(t.text),$("#html_editor").val(t.html),$("#subject").val(t.subject),t.html&&(CKEDITOR.instances.html_editor.setMode("wysiwyg"),$('.nav-tabs a[href="#html"]').click()),$("#importEmailModal").modal("hide")}).error(function(t){modalError(t.responseJSON.message)}):modalError("No Content Specified!")}function load(){$("#templateTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.templates.get().success(function(t){templates=t,$("#loading").hide(),templates.length>0?($("#templateTable").show(),templateTable=$("#templateTable").DataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]}),templateTable.clear(),$.each(templates,function(t,e){templateTable.row.add([escapeHtml(e.name),moment(e.modified_date).format("MMMM Do YYYY, h:mm:ss a"),"
    \t\t
    "]).draw()}),$('[data-toggle="tooltip"]').tooltip()):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching templates")})}var templates=[],icons={"application/vnd.ms-excel":"fa-file-excel-o","text/plain":"fa-file-text-o","image/gif":"fa-file-image-o","image/png":"fa-file-image-o","application/pdf":"fa-file-pdf-o","application/x-zip-compressed":"fa-file-archive-o","application/x-gzip":"fa-file-archive-o","application/vnd.openxmlformats-officedocument.presentationml.presentation":"fa-file-powerpoint-o","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"fa-file-word-o","application/octet-stream":"fa-file-o","application/x-msdownload":"fa-file-o"},deleteTemplate=function(t){swal({title:"Are you sure?",text:"This will delete the template. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(templates[t].name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(e,a){api.templateId.delete(templates[t].id).success(function(t){e()}).error(function(t){a(t.responseJSON.message)})})}}).then(function(){swal("Template Deleted!","This template has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};$(document).ready(function(){$(".modal").on("hidden.bs.modal",function(t){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(t){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$.fn.modal.Constructor.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(t){this.$element[0]===t.target||this.$element.has(t.target).length||$(t.target).closest(".cke_dialog, .cke").length||this.$element.trigger("focus")},this))},$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(t){dismiss()}),$("#importEmailModal").on("hidden.bs.modal",function(t){$("#email_content").val("")}),CKEDITOR.on("dialogDefinition",function(t){var e=t.data.name,a=t.data.definition;if("link"==e){a.minWidth=500,a.minHeight=100;a.getContents("info").get("linkType").hidden=!0}}),load()}); \ No newline at end of file +var templates=[],icons={"application/vnd.ms-excel":"fa-file-excel-o","text/plain":"fa-file-text-o","image/gif":"fa-file-image-o","image/png":"fa-file-image-o","application/pdf":"fa-file-pdf-o","application/x-zip-compressed":"fa-file-archive-o","application/x-gzip":"fa-file-archive-o","application/vnd.openxmlformats-officedocument.presentationml.presentation":"fa-file-powerpoint-o","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"fa-file-word-o","application/octet-stream":"fa-file-o","application/x-msdownload":"fa-file-o"};function save(t){var a={attachments:[]};a.name=$("#name").val(),a.subject=$("#subject").val(),a.html=CKEDITOR.instances.html_editor.getData(),a.html=a.html.replace(/https?:\/\/{{\.URL}}/gi,"{{.URL}}"),$("#use_tracker_checkbox").prop("checked")?-1==a.html.indexOf("{{.Tracker}}")&&-1==a.html.indexOf("{{.TrackingUrl}}")&&(a.html=a.html.replace("","{{.Tracker}}")):a.html=a.html.replace("{{.Tracker}}",""),a.text=$("#text_editor").val(),$.each($("#attachmentsTable").DataTable().rows().data(),function(t,e){a.attachments.push({name:unescapeHtml(e[1]),content:e[3],type:e[4]})}),-1!=t?(a.id=templates[t].id,api.templateId.put(a).success(function(t){successFlash("Template edited successfully!"),load(),dismiss()}).error(function(t){modalError(t.responseJSON.message)})):api.templates.post(a).success(function(t){successFlash("Template added successfully!"),load(),dismiss()}).error(function(t){modalError(t.responseJSON.message)})}function dismiss(){$("#modal\\.flashes").empty(),$("#attachmentsTable").dataTable().DataTable().clear().draw(),$("#name").val(""),$("#subject").val(""),$("#text_editor").val(""),$("#html_editor").val(""),$("#modal").modal("hide")}var deleteTemplate=function(t){swal({title:"Are you sure?",text:"This will delete the template. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(templates[t].name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(e,a){api.templateId.delete(templates[t].id).success(function(t){e()}).error(function(t){a(t.responseJSON.message)})})}}).then(function(){swal("Template Deleted!","This template has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};function deleteTemplate(t){confirm("Delete "+templates[t].name+"?")&&api.templateId.delete(templates[t].id).success(function(t){successFlash(t.message),load()})}function attach(t){attachmentsTable=$("#attachmentsTable").DataTable({destroy:!0,order:[[1,"asc"]],columnDefs:[{orderable:!1,targets:"no-sort"},{sClass:"datatable_hidden",targets:[3,4]}]}),$.each(t,function(t,a){var o=new FileReader;o.onload=function(t){var e=icons[a.type]||"fa-file-o";attachmentsTable.row.add(['',escapeHtml(a.name),'',o.result.split(",")[1],a.type||"application/octet-stream"]).draw()},o.onerror=function(t){console.log(t)},o.readAsDataURL(a)})}function edit(t){$("#modalSubmit").unbind("click").click(function(){save(t)}),$("#attachmentUpload").unbind("click").click(function(){this.value=null}),$("#html_editor").ckeditor(),setupAutocomplete(CKEDITOR.instances.html_editor),$("#attachmentsTable").show(),attachmentsTable=$("#attachmentsTable").DataTable({destroy:!0,order:[[1,"asc"]],columnDefs:[{orderable:!1,targets:"no-sort"},{sClass:"datatable_hidden",targets:[3,4]}]});var e={attachments:[]};-1!=t&&(e=templates[t],$("#name").val(e.name),$("#subject").val(e.subject),$("#html_editor").val(e.html),$("#text_editor").val(e.text),$.each(e.attachments,function(t,e){var a=icons[e.type]||"fa-file-o";attachmentsTable.row.add(['',escapeHtml(e.name),'',e.content,e.type||"application/octet-stream"]).draw()}),-1!=e.html.indexOf("{{.Tracker}}")?$("#use_tracker_checkbox").prop("checked",!0):$("#use_tracker_checkbox").prop("checked",!1)),$("#attachmentsTable").unbind("click").on("click","span>i.fa-trash-o",function(){attachmentsTable.row($(this).parents("tr")).remove().draw()})}function copy(t){$("#modalSubmit").unbind("click").click(function(){save(-1)}),$("#attachmentUpload").unbind("click").click(function(){this.value=null}),$("#html_editor").ckeditor(),$("#attachmentsTable").show(),attachmentsTable=$("#attachmentsTable").DataTable({destroy:!0,order:[[1,"asc"]],columnDefs:[{orderable:!1,targets:"no-sort"},{sClass:"datatable_hidden",targets:[3,4]}]});var e={attachments:[]};e=templates[t],$("#name").val("Copy of "+e.name),$("#subject").val(e.subject),$("#html_editor").val(e.html),$("#text_editor").val(e.text),$.each(e.attachments,function(t,e){var a=icons[e.type]||"fa-file-o";attachmentsTable.row.add(['',escapeHtml(e.name),'',e.content,e.type||"application/octet-stream"]).draw()}),$("#attachmentsTable").unbind("click").on("click","span>i.fa-trash-o",function(){attachmentsTable.row($(this).parents("tr")).remove().draw()}),-1!=e.html.indexOf("{{.Tracker}}")?$("#use_tracker_checkbox").prop("checked",!0):$("#use_tracker_checkbox").prop("checked",!1)}function importEmail(){raw=$("#email_content").val(),convert_links=$("#convert_links_checkbox").prop("checked"),raw?api.import_email({content:raw,convert_links:convert_links}).success(function(t){$("#text_editor").val(t.text),$("#html_editor").val(t.html),$("#subject").val(t.subject),t.html&&(CKEDITOR.instances.html_editor.setMode("wysiwyg"),$('.nav-tabs a[href="#html"]').click()),$("#importEmailModal").modal("hide")}).error(function(t){modalError(t.responseJSON.message)}):modalError("No Content Specified!")}function load(){$("#templateTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.templates.get().success(function(t){templates=t,$("#loading").hide(),0\t\t
    "]).draw()}),$('[data-toggle="tooltip"]').tooltip()):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching templates")})}$(document).ready(function(){$(".modal").on("hidden.bs.modal",function(t){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(t){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$.fn.modal.Constructor.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(t){this.$element[0]===t.target||this.$element.has(t.target).length||$(t.target).closest(".cke_dialog, .cke").length||this.$element.trigger("focus")},this))},$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(t){dismiss()}),$("#importEmailModal").on("hidden.bs.modal",function(t){$("#email_content").val("")}),CKEDITOR.on("dialogDefinition",function(t){var e=t.data.name,a=t.data.definition;"link"==e&&(a.minWidth=500,a.minHeight=100,a.getContents("info").get("linkType").hidden=!0)}),load()}); \ No newline at end of file diff --git a/static/js/dist/app/users.min.js b/static/js/dist/app/users.min.js index dc7d028f..02d746e8 100644 --- a/static/js/dist/app/users.min.js +++ b/static/js/dist/app/users.min.js @@ -1 +1 @@ -function save(e){var a=[];$.each($("#targetsTable").DataTable().rows().data(),function(e,t){a.push({first_name:unescapeHtml(t[0]),last_name:unescapeHtml(t[1]),email:unescapeHtml(t[2]),position:unescapeHtml(t[3])})});var t={name:$("#name").val(),targets:a};-1!=e?(t.id=e,api.groupId.put(t).success(function(e){successFlash("Group updated successfully!"),load(),dismiss(),$("#modal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)})):api.groups.post(t).success(function(e){successFlash("Group added successfully!"),load(),dismiss(),$("#modal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)})}function dismiss(){$("#targetsTable").dataTable().DataTable().clear().draw(),$("#name").val(""),$("#modal\\.flashes").empty()}function edit(e){if(targets=$("#targetsTable").dataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]}),$("#modalSubmit").unbind("click").click(function(){save(e)}),-1==e);else api.groupId.get(e).success(function(e){$("#name").val(e.name),$.each(e.targets,function(e,a){targets.DataTable().row.add([escapeHtml(a.first_name),escapeHtml(a.last_name),escapeHtml(a.email),escapeHtml(a.position),'']).draw()})}).error(function(){errorFlash("Error fetching group")});$("#csvupload").fileupload({url:"/api/import/group",dataType:"json",beforeSend:function(e){e.setRequestHeader("Authorization","Bearer "+user.api_key)},add:function(e,a){$("#modal\\.flashes").empty();var t=/(csv|txt)$/i,s=a.originalFiles[0].name;if(s&&!t.test(s.split(".").pop()))return modalError("Unsupported file extension (use .csv or .txt)"),!1;a.submit()},done:function(e,a){$.each(a.result,function(e,a){addTarget(a.first_name,a.last_name,a.email,a.position)}),targets.DataTable().draw()}})}function addTarget(e,a,t,s){var o=escapeHtml(t).toLowerCase(),r=[escapeHtml(e),escapeHtml(a),o,escapeHtml(s),''],n=targets.DataTable(),i=n.column(2,{order:"index"}).data().indexOf(o);i>=0?n.row(i,{order:"index"}).data(r):n.row.add(r)}function load(){$("#groupTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.groups.summary().success(function(e){if($("#loading").hide(),e.total>0){groups=e.groups,$("#emptyMessage").hide(),$("#groupTable").show();var a=$("#groupTable").DataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]});a.clear(),$.each(groups,function(e,t){a.row.add([escapeHtml(t.name),escapeHtml(t.num_targets),moment(t.modified_date).format("MMMM Do YYYY, h:mm:ss a"),"
    "]).draw()})}else $("#emptyMessage").show()}).error(function(){errorFlash("Error fetching groups")})}var groups=[],downloadCSVTemplate=function(){var e=[{"First Name":"Example","Last Name":"User",Email:"foobar@example.com",Position:"Systems Administrator"}],a=Papa.unparse(e,{}),t=new Blob([a],{type:"text/csv;charset=utf-8;"});if(navigator.msSaveBlob)navigator.msSaveBlob(t,"group_template.csv");else{var s=window.URL.createObjectURL(t),o=document.createElement("a");o.href=s,o.setAttribute("download","group_template.csv"),document.body.appendChild(o),o.click(),document.body.removeChild(o)}},deleteGroup=function(e){var a=groups.find(function(a){return a.id===e});a&&swal({title:"Are you sure?",text:"This will delete the group. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(a.name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.groupId.delete(e).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Group Deleted!","This group has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};$(document).ready(function(){load(),$("#targetForm").submit(function(){return addTarget($("#firstName").val(),$("#lastName").val(),$("#email").val(),$("#position").val()),targets.DataTable().draw(),$("#targetForm>div>input").val(""),$("#firstName").focus(),!1}),$("#targetsTable").on("click","span>i.fa-trash-o",function(){targets.DataTable().row($(this).parents("tr")).remove().draw()}),$("#modal").on("hide.bs.modal",function(){dismiss()}),$("#csv-template").click(downloadCSVTemplate)}); \ No newline at end of file +var groups=[];function save(e){var t=[];$.each($("#targetsTable").DataTable().rows().data(),function(e,a){t.push({first_name:unescapeHtml(a[0]),last_name:unescapeHtml(a[1]),email:unescapeHtml(a[2]),position:unescapeHtml(a[3])})});var a={name:$("#name").val(),targets:t};-1!=e?(a.id=e,api.groupId.put(a).success(function(e){successFlash("Group updated successfully!"),load(),dismiss(),$("#modal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)})):api.groups.post(a).success(function(e){successFlash("Group added successfully!"),load(),dismiss(),$("#modal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)})}function dismiss(){$("#targetsTable").dataTable().DataTable().clear().draw(),$("#name").val(""),$("#modal\\.flashes").empty()}function edit(e){if(targets=$("#targetsTable").dataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]}),$("#modalSubmit").unbind("click").click(function(){save(e)}),-1==e);else api.groupId.get(e).success(function(e){$("#name").val(e.name),$.each(e.targets,function(e,a){targets.DataTable().row.add([escapeHtml(a.first_name),escapeHtml(a.last_name),escapeHtml(a.email),escapeHtml(a.position),'']).draw()})}).error(function(){errorFlash("Error fetching group")});$("#csvupload").fileupload({url:"/api/import/group",dataType:"json",beforeSend:function(e){e.setRequestHeader("Authorization","Bearer "+user.api_key)},add:function(e,a){$("#modal\\.flashes").empty();var t=a.originalFiles[0].name;if(t&&!/(csv|txt)$/i.test(t.split(".").pop()))return modalError("Unsupported file extension (use .csv or .txt)"),!1;a.submit()},done:function(e,a){$.each(a.result,function(e,a){addTarget(a.first_name,a.last_name,a.email,a.position)}),targets.DataTable().draw()}})}var downloadCSVTemplate=function(){var e="group_template.csv",a=Papa.unparse([{"First Name":"Example","Last Name":"User",Email:"foobar@example.com",Position:"Systems Administrator"}],{}),t=new Blob([a],{type:"text/csv;charset=utf-8;"});if(navigator.msSaveBlob)navigator.msSaveBlob(t,e);else{var s=window.URL.createObjectURL(t),o=document.createElement("a");o.href=s,o.setAttribute("download",e),document.body.appendChild(o),o.click(),document.body.removeChild(o)}},deleteGroup=function(s){var e=groups.find(function(e){return e.id===s});e&&swal({title:"Are you sure?",text:"This will delete the group. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(e.name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.groupId.delete(s).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Group Deleted!","This group has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};function addTarget(e,a,t,s){var o=escapeHtml(t).toLowerCase(),r=[escapeHtml(e),escapeHtml(a),o,escapeHtml(s),''],n=targets.DataTable(),i=n.column(2,{order:"index"}).data().indexOf(o);0<=i?n.row(i,{order:"index"}).data(r):n.row.add(r)}function load(){$("#groupTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.groups.summary().success(function(e){if($("#loading").hide(),0
    "]).draw()})}else $("#emptyMessage").show()}).error(function(){errorFlash("Error fetching groups")})}$(document).ready(function(){load(),$("#targetForm").submit(function(){return addTarget($("#firstName").val(),$("#lastName").val(),$("#email").val(),$("#position").val()),targets.DataTable().draw(),$("#targetForm>div>input").val(""),$("#firstName").focus(),!1}),$("#targetsTable").on("click","span>i.fa-trash-o",function(){targets.DataTable().row($(this).parents("tr")).remove().draw()}),$("#modal").on("hide.bs.modal",function(){dismiss()}),$("#csv-template").click(downloadCSVTemplate)}); \ No newline at end of file diff --git a/static/js/dist/vendor.min.js b/static/js/dist/vendor.min.js index 198a5889..2f348ef3 100755 --- a/static/js/dist/vendor.min.js +++ b/static/js/dist/vendor.min.js @@ -1,30 +1 @@ -if(function(t,e){function n(t){var e=t.length,n=ct.type(t);return!ct.isWindow(t)&&(!(1!==t.nodeType||!e)||("array"===n||"function"!==n&&(0===e||"number"==typeof e&&e>0&&e-1 in t)))}function i(t){var e=Ct[t]={};return ct.each(t.match(dt)||[],function(t,n){e[n]=!0}),e}function r(t,n,i,r){if(ct.acceptData(t)){var o,a,s=ct.expando,l=t.nodeType,u=l?ct.cache:t,c=l?t[s]:t[s]&&s;if(c&&u[c]&&(r||u[c].data)||i!==e||"string"!=typeof n)return c||(c=l?t[s]=et.pop()||ct.guid++:s),u[c]||(u[c]=l?{}:{toJSON:ct.noop}),("object"==typeof n||"function"==typeof n)&&(r?u[c]=ct.extend(u[c],n):u[c].data=ct.extend(u[c].data,n)),a=u[c],r||(a.data||(a.data={}),a=a.data),i!==e&&(a[ct.camelCase(n)]=i),"string"==typeof n?null==(o=a[n])&&(o=a[ct.camelCase(n)]):o=a,o}}function o(t,e,n){if(ct.acceptData(t)){var i,r,o=t.nodeType,a=o?ct.cache:t,l=o?t[ct.expando]:ct.expando;if(a[l]){if(e&&(i=n?a[l]:a[l].data)){ct.isArray(e)?e=e.concat(ct.map(e,ct.camelCase)):e in i?e=[e]:(e=ct.camelCase(e),e=e in i?[e]:e.split(" ")),r=e.length;for(;r--;)delete i[e[r]];if(n?!s(i):!ct.isEmptyObject(i))return}(n||(delete a[l].data,s(a[l])))&&(o?ct.cleanData([t],!0):ct.support.deleteExpando||a!=a.window?delete a[l]:a[l]=null)}}}function a(t,n,i){if(i===e&&1===t.nodeType){var r="data-"+n.replace(Tt,"-$1").toLowerCase();if("string"==typeof(i=t.getAttribute(r))){try{i="true"===i||"false"!==i&&("null"===i?null:+i+""===i?+i:Mt.test(i)?ct.parseJSON(i):i)}catch(t){}ct.data(t,n,i)}else i=e}return i}function s(t){var e;for(e in t)if(("data"!==e||!ct.isEmptyObject(t[e]))&&"toJSON"!==e)return!1;return!0}function l(){return!0}function u(){return!1}function c(){try{return Z.activeElement}catch(t){}}function h(t,e){do{t=t[e]}while(t&&1!==t.nodeType);return t}function d(t,e,n){if(ct.isFunction(e))return ct.grep(t,function(t,i){return!!e.call(t,i,t)!==n});if(e.nodeType)return ct.grep(t,function(t){return t===e!==n});if("string"==typeof e){if(Wt.test(e))return ct.filter(e,t,n);e=ct.filter(e,t)}return ct.grep(t,function(t){return ct.inArray(t,e)>=0!==n})}function f(t){var e=Yt.split("|"),n=t.createDocumentFragment();if(n.createElement)for(;e.length;)n.createElement(e.pop());return n}function p(t,e){return ct.nodeName(t,"table")&&ct.nodeName(1===e.nodeType?e:e.firstChild,"tr")?t.getElementsByTagName("tbody")[0]||t.appendChild(t.ownerDocument.createElement("tbody")):t}function g(t){return t.type=(null!==ct.find.attr(t,"type"))+"/"+t.type,t}function m(t){var e=re.exec(t.type);return e?t.type=e[1]:t.removeAttribute("type"),t}function v(t,e){for(var n,i=0;null!=(n=t[i]);i++)ct._data(n,"globalEval",!e||ct._data(e[i],"globalEval"))}function y(t,e){if(1===e.nodeType&&ct.hasData(t)){var n,i,r,o=ct._data(t),a=ct._data(e,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(i=0,r=s[n].length;r>i;i++)ct.event.add(e,n,s[n][i])}a.data&&(a.data=ct.extend({},a.data))}}function b(t,e){var n,i,r;if(1===e.nodeType){if(n=e.nodeName.toLowerCase(),!ct.support.noCloneEvent&&e[ct.expando]){r=ct._data(e);for(i in r.events)ct.removeEvent(e,i,r.handle);e.removeAttribute(ct.expando)}"script"===n&&e.text!==t.text?(g(e).text=t.text,m(e)):"object"===n?(e.parentNode&&(e.outerHTML=t.outerHTML),ct.support.html5Clone&&t.innerHTML&&!ct.trim(e.innerHTML)&&(e.innerHTML=t.innerHTML)):"input"===n&&ee.test(t.type)?(e.defaultChecked=e.checked=t.checked,e.value!==t.value&&(e.value=t.value)):"option"===n?e.defaultSelected=e.selected=t.defaultSelected:("input"===n||"textarea"===n)&&(e.defaultValue=t.defaultValue)}}function x(t,n){var i,r,o=0,a=typeof t.getElementsByTagName!==X?t.getElementsByTagName(n||"*"):typeof t.querySelectorAll!==X?t.querySelectorAll(n||"*"):e;if(!a)for(a=[],i=t.childNodes||t;null!=(r=i[o]);o++)!n||ct.nodeName(r,n)?a.push(r):ct.merge(a,x(r,n));return n===e||n&&ct.nodeName(t,n)?ct.merge([t],a):a}function w(t){ee.test(t.type)&&(t.defaultChecked=t.checked)}function S(t,e){if(e in t)return e;for(var n=e.charAt(0).toUpperCase()+e.slice(1),i=e,r=ke.length;r--;)if((e=ke[r]+n)in t)return e;return i}function _(t,e){return t=e||t,"none"===ct.css(t,"display")||!ct.contains(t.ownerDocument,t)}function k(t,e){for(var n,i,r,o=[],a=0,s=t.length;s>a;a++)i=t[a],i.style&&(o[a]=ct._data(i,"olddisplay"),n=i.style.display,e?(o[a]||"none"!==n||(i.style.display=""),""===i.style.display&&_(i)&&(o[a]=ct._data(i,"olddisplay",D(i.nodeName)))):o[a]||(r=_(i),(n&&"none"!==n||!r)&&ct._data(i,"olddisplay",r?n:ct.css(i,"display"))));for(a=0;s>a;a++)i=t[a],i.style&&(e&&"none"!==i.style.display&&""!==i.style.display||(i.style.display=e?o[a]||"":"none"));return t}function C(t,e,n){var i=ve.exec(e);return i?Math.max(0,i[1]-(n||0))+(i[2]||"px"):e}function M(t,e,n,i,r){for(var o=n===(i?"border":"content")?4:"width"===e?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=ct.css(t,n+_e[o],!0,r)),i?("content"===n&&(a-=ct.css(t,"padding"+_e[o],!0,r)),"margin"!==n&&(a-=ct.css(t,"border"+_e[o]+"Width",!0,r))):(a+=ct.css(t,"padding"+_e[o],!0,r),"padding"!==n&&(a+=ct.css(t,"border"+_e[o]+"Width",!0,r)));return a}function T(t,e,n){var i=!0,r="width"===e?t.offsetWidth:t.offsetHeight,o=ce(t),a=ct.support.boxSizing&&"border-box"===ct.css(t,"boxSizing",!1,o);if(0>=r||null==r){if(r=he(t,e,o),(0>r||null==r)&&(r=t.style[e]),ye.test(r))return r;i=a&&(ct.support.boxSizingReliable||r===t.style[e]),r=parseFloat(r)||0}return r+M(t,e,n||(a?"border":"content"),i,o)+"px"}function D(t){var e=Z,n=xe[t];return n||(n=A(t,e),"none"!==n&&n||(ue=(ue||ct("').bind("load",function(){var e,o=t.isArray(n.paramName)?n.paramName:[n.paramName];r.unbind("load").bind("load",function(){var e;try{if(e=r.contents(),!e.length||!e[0].firstChild)throw new Error}catch(t){e=void 0}l(200,"success",{iframe:e}),t('').appendTo(i),window.setTimeout(function(){i.remove()},0)}),i.prop("target",r.prop("name")).prop("action",n.url).prop("method",n.type),n.formData&&t.each(n.formData,function(e,n){t('').prop("name",n.name).val(n.value).appendTo(i)}),n.fileInput&&n.fileInput.length&&"POST"===n.type&&(e=n.fileInput.clone(),n.fileInput.after(function(t){return e[t]}),n.paramName&&n.fileInput.each(function(e){t(this).prop("name",o[e]||n.paramName)}),i.append(n.fileInput).prop("enctype","multipart/form-data").prop("encoding","multipart/form-data"),n.fileInput.removeAttr("form")),i.submit(),e&&e.length&&n.fileInput.each(function(n,i){var r=t(e[n]);t(i).prop("name",r.prop("name")).attr("form",r.attr("form")),r.replaceWith(i)})}),i.append(r).appendTo(document.body)},abort:function(){r&&r.unbind("load").prop("src",a),i&&i.remove()}}}}),t.ajaxSetup({converters:{"iframe text":function(e){return e&&t(e[0].body).text()},"iframe json":function(e){return e&&t.parseJSON(t(e[0].body).text())},"iframe html":function(e){return e&&t(e[0].body).html()},"iframe xml":function(e){var n=e&&e[0];return n&&t.isXMLDoc(n)?n:t.parseXML(n.XMLDocument&&n.XMLDocument.xml||t(n.body).html())},"iframe script":function(e){return e&&t.globalEval(t(e[0].body).text())}}})}),function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.Sweetalert2=e()}(this,function(){"use strict";function t(){if(void 0===arguments[0])return console.error("sweetAlert2 expects at least 1 attribute!"),!1;var t=l({},I);switch(typeof arguments[0]){case"string":t.title=arguments[0],t.text=arguments[1]||"",t.type=arguments[2]||"";break;case"object":l(t,arguments[0]),t.extraParams=arguments[0].extraParams,"email"===t.input&&null===t.inputValidator&&(t.inputValidator=function(t){return new Promise(function(e,n){/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/.test(t)?e():n("Invalid email address")})});break;default:return console.error('Unexpected type of argument! Expected "string" or "object", got '+typeof arguments[0]),!1}N(t);var i=f();return new Promise(function(o,a){function s(t,e){for(var n=0;n0;)I.removeAttribute(I.attributes[0].name);for(var H in t.inputAttributes)I.setAttribute(H,t.inputAttributes[H]);I.className=j,t.inputClass&&b(I,t.inputClass),k(I)}var z;switch(t.input){case"text":case"email":case"password":case"file":I=w(i,r.input),I.value=t.inputValue,I.placeholder=t.inputPlaceholder,I.type=t.input,S(I);break;case"select":var B=w(i,r.select);if(B.innerHTML="",t.inputPlaceholder){var W=document.createElement("option");W.innerHTML=t.inputPlaceholder,W.value="",W.disabled=!0,W.selected=!0,B.appendChild(W)}z=function(e){for(var n in e){var i=document.createElement("option");i.value=n,i.innerHTML=e[n],t.inputValue===n&&(i.selected=!0),B.appendChild(i)}S(B),B.focus()};break;case"radio":var $=w(i,r.radio);$.innerHTML="",z=function(e){for(var n in e){var i=1,o=document.createElement("input"),a=document.createElement("label"),s=document.createElement("span");o.type="radio",o.name=r.radio,o.value=n,o.id=r.radio+"-"+i++,t.inputValue===n&&(o.checked=!0),s.innerHTML=e[n],a.appendChild(o),a.appendChild(s),a.for=o.id,$.appendChild(a)}S($);var l=$.querySelectorAll("input");l.length&&l[0].focus()};break;case"checkbox":var q=w(i,r.checkbox),U=i.querySelector("#"+r.checkbox);U.value=1,U.checked=Boolean(t.inputValue);var Y=q.getElementsByTagName("span");Y.length&&q.removeChild(Y[0]),Y=document.createElement("span"),Y.innerHTML=t.inputPlaceholder,q.appendChild(Y),S(q);break;case"textarea":var G=w(i,r.textarea);G.value=t.inputValue,G.placeholder=t.inputPlaceholder,S(G);break;case null:break;default:console.error('Unexpected type of input! Expected "text" or "email" or "password", "select", "checkbox", "textarea" or "file", got '+typeof arguments[0])}"select"!==t.input&&"radio"!==t.input||(t.inputOptions instanceof Promise?(e.showLoading(),t.inputOptions.then(function(t){e.hideLoading(),z(t)})):"object"==typeof t.inputOptions?z(t.inputOptions):console.error("Unexpected type of inputOptions! Expected object or Promise, got "+t.inputOptions)),R(),F(t.animation,t.onOpen),s(-1,1)})}function e(){var n=arguments,i=f();return null===i&&(e.init(),i=f()),v(i,"visible")&&L(),t.apply(this,n)}var n="swal2-",i=function(t){var e={};for(var i in t)e[t[i]]=n+t[i];return e},r=i(["container","modal","overlay","close","content","spacer","confirm","cancel","icon","image","input","select","radio","checkbox","textarea","validationerror"]),o=i(["success","warning","info","question","error"]),a={title:"",text:"",html:"",type:null,animation:!0,allowOutsideClick:!0,allowEscapeKey:!0,showConfirmButton:!0,showCancelButton:!1,preConfirm:null,confirmButtonText:"OK",confirmButtonColor:"#3085d6",confirmButtonClass:null,cancelButtonText:"Cancel",cancelButtonColor:"#aaa",cancelButtonClass:null,buttonsStyling:!0,reverseButtons:!1,showCloseButton:!1,showLoaderOnConfirm:!1,imageUrl:null,imageWidth:null,imageHeight:null,imageClass:null,timer:null,width:500,padding:20,background:"#fff",input:null,inputPlaceholder:"",inputValue:"",inputOptions:{},inputAutoTrim:!0,inputClass:null,inputAttributes:{},inputValidator:null,onOpen:null,onClose:null},s='
    ',l=function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t},u=function(t,e){t=String(t).replace(/[^0-9a-f]/gi,""),t.length<6&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),e=e||0;for(var n="#",i=0;3>i;i++){var r=parseInt(t.substr(2*i,2),16);r=Math.round(Math.min(Math.max(0,r+r*e),255)).toString(16),n+=("00"+r).substr(r.length)}return n},c=n+"mediaquery",h={previousDocumentClick:null,previousWindowKeyDown:null,previousActiveElement:null},d=function(t){return document.querySelector("."+t)},f=function(){return d(r.modal)},p=function(){return d(r.overlay)},g=function(){return d(r.confirm)},m=function(){return d(r.cancel)},v=function(t,e){return new RegExp(" "+e+" ").test(" "+t.className+" ")},y=function(t){t.focus();var e=t.value;t.value="",t.value=e},b=function(t,e){e&&!v(t,e)&&(t.className+=" "+e)},x=function(t,e){var n=" "+t.className.replace(/[\t\r\n]/g," ")+" ";if(v(t,e)){for(;n.indexOf(" "+e+" ")>=0;)n=n.replace(" "+e+" "," ");t.className=n.replace(/^\s+|\s+$/g,"")}},w=function(t,e){for(var n=0;n1?1:r,n=+new Date,+t.style.opacity<1&&setTimeout(i,e)};i()}},A=function(t,e){if(+t.style.opacity>0){e=e||16;var n=t.style.opacity,i=+new Date,r=function(){var o=new Date-i,a=+t.style.opacity-o/(100*n);t.style.opacity=a,i=+new Date,+t.style.opacity>0?setTimeout(r,e):k(t)};r()}},P=function(t){if("function"==typeof MouseEvent){var e=new MouseEvent("click",{view:window,bubbles:!1,cancelable:!0});t.dispatchEvent(e)}else if(document.createEvent){var n=document.createEvent("MouseEvents");n.initEvent("click",!1,!1),t.dispatchEvent(n)}else document.createEventObject?t.fireEvent("onclick"):"function"==typeof t.onclick&&t.onclick()},E=function(t){"function"==typeof t.stopPropagation?(t.stopPropagation(),t.preventDefault()):window.event&&window.event.hasOwnProperty("cancelBubble")&&(window.event.cancelBubble=!0)},O=function(){var t=document.createElement("div"),e={WebkitAnimation:"webkitAnimationEnd",MozAnimation:"animationend",OAnimation:"oAnimationEnd oanimationend",msAnimation:"MSAnimationEnd",animation:"animationend"};for(var n in e)if(e.hasOwnProperty(n)&&void 0!==t.style[n])return e[n];return!1}(),L=function(){var t=f();window.onkeydown=h.previousWindowKeyDown,document.onclick=h.previousDocumentClick,h.previousActiveElement&&h.previousActiveElement.focus(),clearTimeout(t.timeout);var e=document.getElementsByTagName("head")[0],n=document.getElementById(c);n&&e.removeChild(n)},I=l({},a),N=function(t){var e,n=f();n.style.width=t.width+"px",n.style.padding=t.padding+"px",n.style.marginLeft=-t.width/2+"px",n.style.background=t.background;var i=document.getElementsByTagName("head")[0],a=document.createElement("style");a.type="text/css",a.id=c;var s=t.width+parseInt(.05*t.width*2,10);a.innerHTML="@media screen and (max-width: "+s+"px) {."+r.modal+" {width: auto !important;left: 5% !important;right: 5% !important;margin-left: 0 !important;}}",i.appendChild(a);var l=n.querySelector("h2"),u=n.querySelector("."+r.content),h=g(),d=m(),p=n.querySelector("."+r.spacer),v=n.querySelector("."+r.close);if(l.innerHTML=t.title.split("\n").join("
    "),t.text||t.html){if("object"==typeof t.html)if(u.innerHTML="",0 in t.html)for(e=0;e in t.html;e++)u.appendChild(t.html[e]);else u.appendChild(t.html);else u.innerHTML=t.html||t.text.split("\n").join("
    ");_(u)}else C(u);if(t.showCloseButton?_(v):C(v),n.className=r.modal,t.customClass&&b(n,t.customClass),C(n.querySelectorAll("."+r.icon)),t.type){var y=!1;for(var w in o)if(t.type===w){y=!0;break}if(!y)return console.error("Unknown alert type: "+t.type),!1;var S=n.querySelector("."+r.icon+"."+o[t.type]);switch(_(S),t.type){case"success":b(S,"animate"),b(S.querySelector(".tip"),"animate-success-tip"),b(S.querySelector(".long"),"animate-success-long");break;case"error":b(S,"animate-error-icon"),b(S.querySelector(".x-mark"),"animate-x-mark");break;case"warning":b(S,"pulse-warning")}}var k=n.querySelector("."+r.image);t.imageUrl?(k.setAttribute("src",t.imageUrl),_(k),t.imageWidth&&k.setAttribute("width",t.imageWidth),t.imageHeight&&k.setAttribute("height",t.imageHeight),t.imageClass&&b(k,t.imageClass)):C(k),t.showCancelButton?d.style.display="inline-block":C(d),t.showConfirmButton?M(h,"display"):C(h),t.showConfirmButton||t.showCancelButton?_(p):C(p),h.innerHTML=t.confirmButtonText,d.innerHTML=t.cancelButtonText,t.buttonsStyling&&(h.style.backgroundColor=t.confirmButtonColor,d.style.backgroundColor=t.cancelButtonColor),h.className=r.confirm,b(h,t.confirmButtonClass),d.className=r.cancel,b(d,t.cancelButtonClass),t.buttonsStyling?(b(h,"styled"),b(d,"styled")):(x(h,"styled"),x(d,"styled"),h.style.backgroundColor=h.style.borderLeftColor=h.style.borderRightColor="",d.style.backgroundColor=d.style.borderLeftColor=d.style.borderRightColor=""),!0===t.animation?x(n,"no-animation"):b(n,"no-animation")},F=function(t,e){var n=f();t?(D(p(),10),b(n,"show-swal2"),x(n,"hide-swal2")):_(p()),_(n),h.previousActiveElement=document.activeElement,b(n,"visible"),null!==e&&"function"==typeof e&&e.call(this,n)},R=function(){var t=f();t.style.marginTop=T(t)};return e.queue=function(t){return new Promise(function(n,i){!function r(o,a){ -o1)throw new TypeError("isEnabled expects a single character string parameter");switch(t){case"y":return-1!==l.indexOf("Y");case"M":return-1!==l.indexOf("M");case"d":return-1!==l.toLowerCase().indexOf("d");case"h":case"H":return-1!==l.toLowerCase().indexOf("h");case"m":return-1!==l.indexOf("m");case"s":return-1!==l.indexOf("s");default:return!1}},C=function(){return k("h")||k("m")||k("s")},M=function(){return k("y")||k("M")||k("d")},T=function(){var e=t("").append(t("").append(t("").addClass("prev").attr("data-action","previous").append(t("").addClass(i.icons.previous))).append(t("").addClass("picker-switch").attr("data-action","pickerSwitch").attr("colspan",i.calendarWeeks?"6":"5")).append(t("").addClass("next").attr("data-action","next").append(t("").addClass(i.icons.next)))),n=t("").append(t("").append(t("").attr("colspan",i.calendarWeeks?"8":"7")));return[t("
    ").addClass("datepicker-days").append(t("").addClass("table-condensed").append(e).append(t(""))),t("
    ").addClass("datepicker-months").append(t("
    ").addClass("table-condensed").append(e.clone()).append(n.clone())),t("
    ").addClass("datepicker-years").append(t("
    ").addClass("table-condensed").append(e.clone()).append(n.clone())),t("
    ").addClass("datepicker-decades").append(t("
    ").addClass("table-condensed").append(e.clone()).append(n.clone()))]},D=function(){var e=t(""),n=t(""),r=t("");return k("h")&&(e.append(t("
    ").append(t("").attr({href:"#",tabindex:"-1",title:i.tooltips.incrementHour}).addClass("btn").attr("data-action","incrementHours").append(t("").addClass(i.icons.up)))),n.append(t("").append(t("").addClass("timepicker-hour").attr({"data-time-component":"hours",title:i.tooltips.pickHour}).attr("data-action","showHours"))),r.append(t("").append(t("").attr({href:"#",tabindex:"-1",title:i.tooltips.decrementHour}).addClass("btn").attr("data-action","decrementHours").append(t("").addClass(i.icons.down))))),k("m")&&(k("h")&&(e.append(t("").addClass("separator")),n.append(t("").addClass("separator").html(":")),r.append(t("").addClass("separator"))),e.append(t("").append(t("").attr({href:"#",tabindex:"-1",title:i.tooltips.incrementMinute}).addClass("btn").attr("data-action","incrementMinutes").append(t("").addClass(i.icons.up)))),n.append(t("").append(t("").addClass("timepicker-minute").attr({"data-time-component":"minutes",title:i.tooltips.pickMinute}).attr("data-action","showMinutes"))),r.append(t("").append(t("").attr({href:"#",tabindex:"-1",title:i.tooltips.decrementMinute}).addClass("btn").attr("data-action","decrementMinutes").append(t("").addClass(i.icons.down))))),k("s")&&(k("m")&&(e.append(t("").addClass("separator")),n.append(t("").addClass("separator").html(":")),r.append(t("").addClass("separator"))),e.append(t("").append(t("").attr({href:"#",tabindex:"-1",title:i.tooltips.incrementSecond}).addClass("btn").attr("data-action","incrementSeconds").append(t("").addClass(i.icons.up)))),n.append(t("").append(t("").addClass("timepicker-second").attr({"data-time-component":"seconds",title:i.tooltips.pickSecond}).attr("data-action","showSeconds"))),r.append(t("").append(t("").attr({href:"#",tabindex:"-1",title:i.tooltips.decrementSecond}).addClass("btn").attr("data-action","decrementSeconds").append(t("").addClass(i.icons.down))))),s||(e.append(t("").addClass("separator")),n.append(t("").append(t("").addClass("separator"))),t("
    ").addClass("timepicker-picker").append(t("").addClass("table-condensed").append([e,n,r]))},A=function(){var e=t("
    ").addClass("timepicker-hours").append(t("
    ").addClass("table-condensed")),n=t("
    ").addClass("timepicker-minutes").append(t("
    ").addClass("table-condensed")),i=t("
    ").addClass("timepicker-seconds").append(t("
    ").addClass("table-condensed")),r=[D()];return k("h")&&r.push(e),k("m")&&r.push(n),k("s")&&r.push(i),r},P=function(){var e=[];return i.showTodayButton&&e.push(t("\s*$/g,Tt={option:[1,""],legend:[1,"
    ","
    "],area:[1,"",""],param:[1,"",""],thead:[1,"
    ").append(t("").attr({"data-action":"today",title:i.tooltips.today}).append(t("").addClass(i.icons.today)))),!i.sideBySide&&M()&&C()&&e.push(t("").append(t("").attr({"data-action":"togglePicker",title:i.tooltips.selectTime}).append(t("").addClass(i.icons.time)))),i.showClear&&e.push(t("").append(t("").attr({"data-action":"clear",title:i.tooltips.clear}).append(t("").addClass(i.icons.clear)))),i.showClose&&e.push(t("").append(t("").attr({"data-action":"close",title:i.tooltips.close}).append(t("").addClass(i.icons.close)))),t("").addClass("table-condensed").append(t("").append(t("").append(e)))},E=function(){var e=t("
    ").addClass("bootstrap-datetimepicker-widget dropdown-menu"),n=t("
    ").addClass("datepicker").append(T()),r=t("
    ").addClass("timepicker").append(A()),o=t("
      ").addClass("list-unstyled"),a=t("
    • ").addClass("picker-switch"+(i.collapse?" accordion-toggle":"")).append(P());return i.inline&&e.removeClass("dropdown-menu"),s&&e.addClass("usetwentyfour"),k("s")&&!s&&e.addClass("wider"),i.sideBySide&&M()&&C()?(e.addClass("timepicker-sbs"),"top"===i.toolbarPlacement&&e.append(a),e.append(t("
      ").addClass("row").append(n.addClass("col-md-6")).append(r.addClass("col-md-6"))),"bottom"===i.toolbarPlacement&&e.append(a),e):("top"===i.toolbarPlacement&&o.append(a),M()&&o.append(t("
    • ").addClass(i.collapse&&C()?"collapse in":"").append(n)),"default"===i.toolbarPlacement&&o.append(a),C()&&o.append(t("
    • ").addClass(i.collapse&&M()?"collapse":"").append(r)),"bottom"===i.toolbarPlacement&&o.append(a),e.append(o))},O=function(){var e,r=(f||n).position(),o=(f||n).offset(),a=i.widgetPositioning.vertical,s=i.widgetPositioning.horizontal;if(i.widgetParent)e=i.widgetParent.append(p);else if(n.is("input"))e=n.after(p).parent();else{if(i.inline)return void(e=n.append(p));e=n,n.children().first().after(p)}if("auto"===a&&(a=o.top+1.5*p.height()>=t(window).height()+t(window).scrollTop()&&p.height()+n.outerHeight()t(window).width()?"right":"left"),"top"===a?p.addClass("top").removeClass("bottom"):p.addClass("bottom").removeClass("top"),"right"===s?p.addClass("pull-right"):p.removeClass("pull-right"),"relative"!==e.css("position")&&(e=e.parents().filter(function(){return"relative"===t(this).css("position")}).first()),0===e.length)throw new Error("datetimepicker component should be placed within a relative positioned container");p.css({top:"top"===a?"auto":r.top+n.outerHeight(),bottom:"top"===a?r.top+n.outerHeight():"auto",left:"left"===s?e===n?0:r.left:"auto",right:"left"===s?"auto":e.outerWidth()-n.outerWidth()-(e===n?0:r.left)})},L=function(t){"dp.change"===t.type&&(t.date&&t.date.isSame(t.oldDate)||!t.date&&!t.oldDate)||n.trigger(t)},I=function(t){"y"===t&&(t="YYYY"),L({type:"dp.update",change:t,viewDate:o.clone()})},N=function(t){p&&(t&&(c=Math.max(g,Math.min(3,c+t))),p.find(".datepicker > div").hide().filter(".datepicker-"+m[c].clsName).show())},F=function(){var e=t("
    "),n=o.clone().startOf("w").startOf("d");for(!0===i.calendarWeeks&&e.append(t(""),i.calendarWeeks&&n.append('"),c.push(n)),a="",e.isBefore(o,"M")&&(a+=" old"),e.isAfter(o,"M")&&(a+=" new"),e.isSame(r,"d")&&!d&&(a+=" active"),B(e,"d")||(a+=" disabled"),e.isSame(_(),"d")&&(a+=" today"),0!==e.day()&&6!==e.day()||(a+=" weekend"),n.append('"),e.add(1,"d");l.find("tbody").empty().append(c),$(),q(),U()}},G=function(){var e=p.find(".timepicker-hours table"),n=o.clone().startOf("d"),i=[],r=t("");for(o.hour()>11&&!s&&n.hour(12);n.isSame(o,"d")&&(s||o.hour()<12&&n.hour()<12||o.hour()>11);)n.hour()%4==0&&(r=t(""),i.push(r)),r.append('"),n.add(1,"h");e.empty().append(i)},X=function(){for(var e=p.find(".timepicker-minutes table"),n=o.clone().startOf("h"),r=[],a=t(""),s=1===i.stepping?5:i.stepping;o.isSame(n,"h");)n.minute()%(4*s)==0&&(a=t(""),r.push(a)),a.append('"),n.add(s,"m");e.empty().append(r)},V=function(){for(var e=p.find(".timepicker-seconds table"),n=o.clone().startOf("m"),i=[],r=t("");o.isSame(n,"m");)n.second()%20==0&&(r=t(""),i.push(r)),r.append('"),n.add(5,"s");e.empty().append(i)},Z=function(){var t,e,n=p.find(".timepicker span[data-time-component]");s||(t=p.find(".timepicker [data-action=togglePeriod]"),e=r.clone().add(r.hours()>=12?-12:12,"h"),t.text(r.format("A")),B(e,"h")?t.removeClass("disabled"):t.addClass("disabled")),n.filter("[data-time-component=hours]").text(r.format(s?"HH":"hh")),n.filter("[data-time-component=minutes]").text(r.format("mm")),n.filter("[data-time-component=seconds]").text(r.format("ss")),G(),X(),V()},K=function(){p&&(Y(),Z())},J=function(t){var e=d?null:r;if(!t)return d=!0,a.val(""),n.data("date",""),L({type:"dp.change",date:!1,oldDate:e}),void K();t=t.clone().locale(i.locale),1!==i.stepping&&t.minutes(Math.round(t.minutes()/i.stepping)*i.stepping%60).seconds(0),B(t)?(r=t,o=r.clone(),a.val(r.format(l)),n.data("date",r.format(l)),d=!1,K(),L({type:"dp.change",date:r.clone(),oldDate:e})):(i.keepInvalid||a.val(d?"":r.format(l)),L({type:"dp.error",date:t}))},Q=function(){var e=!1;return p?(p.find(".collapse").each(function(){var n=t(this).data("collapse");return!n||!n.transitioning||(e=!0,!1)}),e?h:(f&&f.hasClass("btn")&&f.toggleClass("active"),p.hide(),t(window).off("resize",O),p.off("click","[data-action]"),p.off("mousedown",!1),p.remove(),p=!1,L({type:"dp.hide",date:r.clone()}),a.blur(),h)):h},tt=function(){J(null)},et={next:function(){var t=m[c].navFnc;o.add(m[c].navStep,t),Y(),I(t)},previous:function(){var t=m[c].navFnc;o.subtract(m[c].navStep,t),Y(),I(t)},pickerSwitch:function(){N(1)},selectMonth:function(e){var n=t(e.target).closest("tbody").find("span").index(t(e.target));o.month(n),c===g?(J(r.clone().year(o.year()).month(o.month())),i.inline||Q()):(N(-1),Y()),I("M")},selectYear:function(e){var n=parseInt(t(e.target).text(),10)||0;o.year(n),c===g?(J(r.clone().year(o.year())),i.inline||Q()):(N(-1),Y()),I("YYYY")},selectDecade:function(e){var n=parseInt(t(e.target).data("selection"),10)||0;o.year(n),c===g?(J(r.clone().year(o.year())),i.inline||Q()):(N(-1),Y()),I("YYYY")},selectDay:function(e){var n=o.clone();t(e.target).is(".old")&&n.subtract(1,"M"),t(e.target).is(".new")&&n.add(1,"M"),J(n.date(parseInt(t(e.target).text(),10))),C()||i.keepOpen||i.inline||Q()},incrementHours:function(){var t=r.clone().add(1,"h");B(t,"h")&&J(t)},incrementMinutes:function(){var t=r.clone().add(i.stepping,"m");B(t,"m")&&J(t)},incrementSeconds:function(){var t=r.clone().add(1,"s");B(t,"s")&&J(t)},decrementHours:function(){var t=r.clone().subtract(1,"h");B(t,"h")&&J(t)},decrementMinutes:function(){var t=r.clone().subtract(i.stepping,"m");B(t,"m")&&J(t)},decrementSeconds:function(){var t=r.clone().subtract(1,"s");B(t,"s")&&J(t)},togglePeriod:function(){J(r.clone().add(r.hours()>=12?-12:12,"h"))},togglePicker:function(e){var n,r=t(e.target),o=r.closest("ul"),a=o.find(".in"),s=o.find(".collapse:not(.in)");if(a&&a.length){if((n=a.data("collapse"))&&n.transitioning)return;a.collapse?(a.collapse("hide"),s.collapse("show")):(a.removeClass("in"),s.addClass("in")),r.is("span")?r.toggleClass(i.icons.time+" "+i.icons.date):r.find("span").toggleClass(i.icons.time+" "+i.icons.date)}},showPicker:function(){p.find(".timepicker > div:not(.timepicker-picker)").hide(),p.find(".timepicker .timepicker-picker").show()},showHours:function(){p.find(".timepicker .timepicker-picker").hide(),p.find(".timepicker .timepicker-hours").show()},showMinutes:function(){p.find(".timepicker .timepicker-picker").hide(),p.find(".timepicker .timepicker-minutes").show()},showSeconds:function(){p.find(".timepicker .timepicker-picker").hide(),p.find(".timepicker .timepicker-seconds").show()},selectHour:function(e){var n=parseInt(t(e.target).text(),10);s||(r.hours()>=12?12!==n&&(n+=12):12===n&&(n=0)),J(r.clone().hours(n)),et.showPicker.call(h)},selectMinute:function(e){J(r.clone().minutes(parseInt(t(e.target).text(),10))),et.showPicker.call(h)},selectSecond:function(e){J(r.clone().seconds(parseInt(t(e.target).text(),10))),et.showPicker.call(h)},clear:tt,today:function(){var t=_();B(t,"d")&&J(t)},close:Q},nt=function(e){return!t(e.currentTarget).is(".disabled")&&(et[t(e.currentTarget).data("action")].apply(h,arguments),!1)},it=function(){var e,n={year:function(t){return t.month(0).date(1).hours(0).seconds(0).minutes(0)},month:function(t){return t.date(1).hours(0).seconds(0).minutes(0)},day:function(t){return t.hours(0).seconds(0).minutes(0)},hour:function(t){return t.seconds(0).minutes(0)},minute:function(t){return t.seconds(0)}};return a.prop("disabled")||!i.ignoreReadonly&&a.prop("readonly")||p?h:(void 0!==a.val()&&0!==a.val().trim().length?J(ot(a.val().trim())):i.useCurrent&&d&&(a.is("input")&&0===a.val().trim().length||i.inline)&&(e=_(),"string"==typeof i.useCurrent&&(e=n[i.useCurrent](e)),J(e)),p=E(),F(),W(),p.find(".timepicker-hours").hide(),p.find(".timepicker-minutes").hide(),p.find(".timepicker-seconds").hide(),K(),N(),t(window).on("resize",O),p.on("click","[data-action]",nt),p.on("mousedown",!1),f&&f.hasClass("btn")&&f.toggleClass("active"),p.show(),O(),i.focusOnShow&&!a.is(":focus")&&a.focus(),L({type:"dp.show"}),h)},rt=function(){return p?Q():it()},ot=function(t){return t=void 0===i.parseInputDate?e.isMoment(t)||t instanceof Date?e(t):_(t):i.parseInputDate(t),t.locale(i.locale),t},at=function(t){var e,n,r,o,a=null,s=[],l={},u=t.which;S[u]="p";for(e in S)S.hasOwnProperty(e)&&"p"===S[e]&&(s.push(e),parseInt(e,10)!==u&&(l[e]=!0));for(e in i.keyBinds)if(i.keyBinds.hasOwnProperty(e)&&"function"==typeof i.keyBinds[e]&&(r=e.split(" "),r.length===s.length&&w[u]===r[r.length-1])){for(o=!0,n=r.length-2;n>=0;n--)if(!(w[r[n]]in l)){o=!1;break}if(o){a=i.keyBinds[e];break}}a&&(a.call(h,p),t.stopPropagation(),t.preventDefault())},st=function(t){S[t.which]="r",t.stopPropagation(),t.preventDefault()},lt=function(e){var n=t(e.target).val().trim(),i=n?ot(n):null;return J(i),e.stopImmediatePropagation(),!1},ut=function(){a.off({change:lt,blur:blur,keydown:at,keyup:st,focus:i.allowInputToggle?Q:""}),n.is("input")?a.off({focus:it}):f&&(f.off("click",rt),f.off("mousedown",!1))},ct=function(e){var n={};return t.each(e,function(){var t=ot(this);t.isValid()&&(n[t.format("YYYY-MM-DD")]=!0)}),!!Object.keys(n).length&&n},ht=function(e){var n={};return t.each(e,function(){n[this]=!0}),!!Object.keys(n).length&&n},dt=function(){var t=i.format||"L LT";l=t.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,function(t){return(r.localeData().longDateFormat(t)||t).replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,function(t){return r.localeData().longDateFormat(t)||t})}),u=i.extraFormats?i.extraFormats.slice():[],u.indexOf(t)<0&&u.indexOf(l)<0&&u.push(l),s=l.toLowerCase().indexOf("a")<1&&l.replace(/\[.*?\]/g,"").indexOf("h")<1,k("y")&&(g=2),k("M")&&(g=1),k("d")&&(g=0),c=Math.max(g,c),d||J(r)};if(h.destroy=function(){Q(),ut(),n.removeData("DateTimePicker"),n.removeData("date")},h.toggle=rt,h.show=it,h.hide=Q,h.disable=function(){return Q(),f&&f.hasClass("btn")&&f.addClass("disabled"),a.prop("disabled",!0),h},h.enable=function(){return f&&f.hasClass("btn")&&f.removeClass("disabled"),a.prop("disabled",!1),h},h.ignoreReadonly=function(t){if(0===arguments.length)return i.ignoreReadonly;if("boolean"!=typeof t)throw new TypeError("ignoreReadonly () expects a boolean parameter");return i.ignoreReadonly=t,h},h.options=function(e){if(0===arguments.length)return t.extend(!0,{},i);if(!(e instanceof Object))throw new TypeError("options() options parameter should be an object");return t.extend(!0,i,e),t.each(i,function(t,e){if(void 0===h[t])throw new TypeError("option "+t+" is not recognized!");h[t](e)}),h},h.date=function(t){if(0===arguments.length)return d?null:r.clone();if(!(null===t||"string"==typeof t||e.isMoment(t)||t instanceof Date))throw new TypeError("date() parameter must be one of [null, string, moment or Date]");return J(null===t?null:ot(t)),h},h.format=function(t){if(0===arguments.length)return i.format;if("string"!=typeof t&&("boolean"!=typeof t||!1!==t))throw new TypeError("format() expects a sting or boolean:false parameter "+t);return i.format=t,l&&dt(),h},h.timeZone=function(t){return 0===arguments.length?i.timeZone:(i.timeZone=t,h)},h.dayViewHeaderFormat=function(t){if(0===arguments.length)return i.dayViewHeaderFormat;if("string"!=typeof t)throw new TypeError("dayViewHeaderFormat() expects a string parameter");return i.dayViewHeaderFormat=t,h},h.extraFormats=function(t){if(0===arguments.length)return i.extraFormats;if(!1!==t&&!(t instanceof Array))throw new TypeError("extraFormats() expects an array or false parameter");return i.extraFormats=t,u&&dt(),h},h.disabledDates=function(e){if(0===arguments.length)return i.disabledDates?t.extend({},i.disabledDates):i.disabledDates;if(!e)return i.disabledDates=!1,K(),h;if(!(e instanceof Array))throw new TypeError("disabledDates() expects an array parameter");return i.disabledDates=ct(e),i.enabledDates=!1,K(),h},h.enabledDates=function(e){if(0===arguments.length)return i.enabledDates?t.extend({},i.enabledDates):i.enabledDates;if(!e)return i.enabledDates=!1,K(),h;if(!(e instanceof Array))throw new TypeError("enabledDates() expects an array parameter");return i.enabledDates=ct(e),i.disabledDates=!1,K(),h},h.daysOfWeekDisabled=function(t){if(0===arguments.length)return i.daysOfWeekDisabled.splice(0);if("boolean"==typeof t&&!t)return i.daysOfWeekDisabled=!1,K(),h;if(!(t instanceof Array))throw new TypeError("daysOfWeekDisabled() expects an array parameter");if(i.daysOfWeekDisabled=t.reduce(function(t,e){return(e=parseInt(e,10))>6||e<0||isNaN(e)?t:(-1===t.indexOf(e)&&t.push(e),t)},[]).sort(),i.useCurrent&&!i.keepInvalid){for(var e=0;!B(r,"d");){if(r.add(1,"d"),7===e)throw"Tried 7 times to find a valid date";e++}J(r)}return K(),h},h.maxDate=function(t){if(0===arguments.length)return i.maxDate?i.maxDate.clone():i.maxDate;if("boolean"==typeof t&&!1===t)return i.maxDate=!1,K(),h;"string"==typeof t&&("now"!==t&&"moment"!==t||(t=_()));var e=ot(t);if(!e.isValid())throw new TypeError("maxDate() Could not parse date parameter: "+t);if(i.minDate&&e.isBefore(i.minDate))throw new TypeError("maxDate() date parameter is before options.minDate: "+e.format(l));return i.maxDate=e,i.useCurrent&&!i.keepInvalid&&r.isAfter(t)&&J(i.maxDate),o.isAfter(e)&&(o=e.clone().subtract(i.stepping,"m")),K(),h},h.minDate=function(t){if(0===arguments.length)return i.minDate?i.minDate.clone():i.minDate;if("boolean"==typeof t&&!1===t)return i.minDate=!1,K(),h;"string"==typeof t&&("now"!==t&&"moment"!==t||(t=_()));var e=ot(t);if(!e.isValid())throw new TypeError("minDate() Could not parse date parameter: "+t);if(i.maxDate&&e.isAfter(i.maxDate))throw new TypeError("minDate() date parameter is after options.maxDate: "+e.format(l));return i.minDate=e,i.useCurrent&&!i.keepInvalid&&r.isBefore(t)&&J(i.minDate),o.isBefore(e)&&(o=e.clone().add(i.stepping,"m")),K(),h},h.defaultDate=function(t){if(0===arguments.length)return i.defaultDate?i.defaultDate.clone():i.defaultDate;if(!t)return i.defaultDate=!1,h;"string"==typeof t&&("now"!==t&&"moment"!==t||(t=_()));var e=ot(t);if(!e.isValid())throw new TypeError("defaultDate() Could not parse date parameter: "+t);if(!B(e))throw new TypeError("defaultDate() date passed is invalid according to component setup validations");return i.defaultDate=e,(i.defaultDate&&i.inline||""===a.val().trim())&&J(i.defaultDate),h},h.locale=function(t){if(0===arguments.length)return i.locale;if(!e.localeData(t))throw new TypeError("locale() locale "+t+" is not loaded from moment locales!");return i.locale=t,r.locale(i.locale),o.locale(i.locale),l&&dt(),p&&(Q(),it()),h},h.stepping=function(t){return 0===arguments.length?i.stepping:(t=parseInt(t,10),(isNaN(t)||t<1)&&(t=1),i.stepping=t,h)},h.useCurrent=function(t){var e=["year","month","day","hour","minute"];if(0===arguments.length)return i.useCurrent;if("boolean"!=typeof t&&"string"!=typeof t)throw new TypeError("useCurrent() expects a boolean or string parameter");if("string"==typeof t&&-1===e.indexOf(t.toLowerCase()))throw new TypeError("useCurrent() expects a string parameter of "+e.join(", "));return i.useCurrent=t,h},h.collapse=function(t){if(0===arguments.length)return i.collapse;if("boolean"!=typeof t)throw new TypeError("collapse() expects a boolean parameter");return i.collapse===t?h:(i.collapse=t,p&&(Q(),it()),h)},h.icons=function(e){if(0===arguments.length)return t.extend({},i.icons);if(!(e instanceof Object))throw new TypeError("icons() expects parameter to be an Object");return t.extend(i.icons,e),p&&(Q(),it()),h},h.tooltips=function(e){if(0===arguments.length)return t.extend({},i.tooltips);if(!(e instanceof Object))throw new TypeError("tooltips() expects parameter to be an Object");return t.extend(i.tooltips,e),p&&(Q(),it()),h},h.useStrict=function(t){if(0===arguments.length)return i.useStrict;if("boolean"!=typeof t)throw new TypeError("useStrict() expects a boolean parameter");return i.useStrict=t,h},h.sideBySide=function(t){if(0===arguments.length)return i.sideBySide;if("boolean"!=typeof t)throw new TypeError("sideBySide() expects a boolean parameter");return i.sideBySide=t,p&&(Q(),it()),h},h.viewMode=function(t){if(0===arguments.length)return i.viewMode;if("string"!=typeof t)throw new TypeError("viewMode() expects a string parameter");if(-1===v.indexOf(t))throw new TypeError("viewMode() parameter must be one of ("+v.join(", ")+") value");return i.viewMode=t,c=Math.max(v.indexOf(t),g),N(),h},h.toolbarPlacement=function(t){if(0===arguments.length)return i.toolbarPlacement;if("string"!=typeof t)throw new TypeError("toolbarPlacement() expects a string parameter");if(-1===x.indexOf(t))throw new TypeError("toolbarPlacement() parameter must be one of ("+x.join(", ")+") value");return i.toolbarPlacement=t,p&&(Q(),it()),h},h.widgetPositioning=function(e){if(0===arguments.length)return t.extend({},i.widgetPositioning);if("[object Object]"!=={}.toString.call(e))throw new TypeError("widgetPositioning() expects an object variable");if(e.horizontal){if("string"!=typeof e.horizontal)throw new TypeError("widgetPositioning() horizontal variable must be a string");if(e.horizontal=e.horizontal.toLowerCase(),-1===b.indexOf(e.horizontal))throw new TypeError("widgetPositioning() expects horizontal parameter to be one of ("+b.join(", ")+")");i.widgetPositioning.horizontal=e.horizontal}if(e.vertical){if("string"!=typeof e.vertical)throw new TypeError("widgetPositioning() vertical variable must be a string");if(e.vertical=e.vertical.toLowerCase(),-1===y.indexOf(e.vertical))throw new TypeError("widgetPositioning() expects vertical parameter to be one of ("+y.join(", ")+")");i.widgetPositioning.vertical=e.vertical}return K(),h},h.calendarWeeks=function(t){if(0===arguments.length)return i.calendarWeeks;if("boolean"!=typeof t)throw new TypeError("calendarWeeks() expects parameter to be a boolean value");return i.calendarWeeks=t,K(),h},h.showTodayButton=function(t){if(0===arguments.length)return i.showTodayButton;if("boolean"!=typeof t)throw new TypeError("showTodayButton() expects a boolean parameter");return i.showTodayButton=t,p&&(Q(),it()),h},h.showClear=function(t){if(0===arguments.length)return i.showClear;if("boolean"!=typeof t)throw new TypeError("showClear() expects a boolean parameter");return i.showClear=t,p&&(Q(),it()),h},h.widgetParent=function(e){if(0===arguments.length)return i.widgetParent;if("string"==typeof e&&(e=t(e)),null!==e&&"string"!=typeof e&&!(e instanceof t))throw new TypeError("widgetParent() expects a string or a jQuery object parameter");return i.widgetParent=e,p&&(Q(),it()),h},h.keepOpen=function(t){ -if(0===arguments.length)return i.keepOpen;if("boolean"!=typeof t)throw new TypeError("keepOpen() expects a boolean parameter");return i.keepOpen=t,h},h.focusOnShow=function(t){if(0===arguments.length)return i.focusOnShow;if("boolean"!=typeof t)throw new TypeError("focusOnShow() expects a boolean parameter");return i.focusOnShow=t,h},h.inline=function(t){if(0===arguments.length)return i.inline;if("boolean"!=typeof t)throw new TypeError("inline() expects a boolean parameter");return i.inline=t,h},h.clear=function(){return tt(),h},h.keyBinds=function(t){return i.keyBinds=t,h},h.getMoment=function(t){return _(t)},h.debug=function(t){if("boolean"!=typeof t)throw new TypeError("debug() expects a boolean parameter");return i.debug=t,h},h.allowInputToggle=function(t){if(0===arguments.length)return i.allowInputToggle;if("boolean"!=typeof t)throw new TypeError("allowInputToggle() expects a boolean parameter");return i.allowInputToggle=t,h},h.showClose=function(t){if(0===arguments.length)return i.showClose;if("boolean"!=typeof t)throw new TypeError("showClose() expects a boolean parameter");return i.showClose=t,h},h.keepInvalid=function(t){if(0===arguments.length)return i.keepInvalid;if("boolean"!=typeof t)throw new TypeError("keepInvalid() expects a boolean parameter");return i.keepInvalid=t,h},h.datepickerInput=function(t){if(0===arguments.length)return i.datepickerInput;if("string"!=typeof t)throw new TypeError("datepickerInput() expects a string parameter");return i.datepickerInput=t,h},h.parseInputDate=function(t){if(0===arguments.length)return i.parseInputDate;if("function"!=typeof t)throw new TypeError("parseInputDate() sholud be as function");return i.parseInputDate=t,h},h.disabledTimeIntervals=function(e){if(0===arguments.length)return i.disabledTimeIntervals?t.extend({},i.disabledTimeIntervals):i.disabledTimeIntervals;if(!e)return i.disabledTimeIntervals=!1,K(),h;if(!(e instanceof Array))throw new TypeError("disabledTimeIntervals() expects an array parameter");return i.disabledTimeIntervals=e,K(),h},h.disabledHours=function(e){if(0===arguments.length)return i.disabledHours?t.extend({},i.disabledHours):i.disabledHours;if(!e)return i.disabledHours=!1,K(),h;if(!(e instanceof Array))throw new TypeError("disabledHours() expects an array parameter");if(i.disabledHours=ht(e),i.enabledHours=!1,i.useCurrent&&!i.keepInvalid){for(var n=0;!B(r,"h");){if(r.add(1,"h"),24===n)throw"Tried 24 times to find a valid date";n++}J(r)}return K(),h},h.enabledHours=function(e){if(0===arguments.length)return i.enabledHours?t.extend({},i.enabledHours):i.enabledHours;if(!e)return i.enabledHours=!1,K(),h;if(!(e instanceof Array))throw new TypeError("enabledHours() expects an array parameter");if(i.enabledHours=ht(e),i.disabledHours=!1,i.useCurrent&&!i.keepInvalid){for(var n=0;!B(r,"h");){if(r.add(1,"h"),24===n)throw"Tried 24 times to find a valid date";n++}J(r)}return K(),h},h.viewDate=function(t){if(0===arguments.length)return o.clone();if(!t)return o=r.clone(),h;if(!("string"==typeof t||e.isMoment(t)||t instanceof Date))throw new TypeError("viewDate() parameter must be one of [string, moment or Date]");return o=ot(t),I(),h},n.is("input"))a=n;else if(a=n.find(i.datepickerInput),0===a.size())a=n.find("input");else if(!a.is("input"))throw new Error('CSS class "'+i.datepickerInput+'" cannot be applied to non input element');if(n.hasClass("input-group")&&(f=0===n.find(".datepickerbutton").size()?n.find(".input-group-addon"):n.find(".datepickerbutton")),!i.inline&&!a.is("input"))throw new Error("Could not initialize DateTimePicker without an input element");return r=_(),o=r.clone(),t.extend(!0,i,function(){var e,r={};return e=n.is("input")||i.inline?n.data():n.find("input").data(),e.dateOptions&&e.dateOptions instanceof Object&&(r=t.extend(!0,r,e.dateOptions)),t.each(i,function(t){var n="date"+t.charAt(0).toUpperCase()+t.slice(1);void 0!==e[n]&&(r[t]=e[n])}),r}()),h.options(i),dt(),function(){a.on({change:lt,blur:i.debug?"":Q,keydown:at,keyup:st,focus:i.allowInputToggle?it:""}),n.is("input")?a.on({focus:it}):f&&(f.on("click",rt),f.on("mousedown",!1))}(),a.prop("disabled")&&h.disable(),a.is("input")&&0!==a.val().trim().length?J(ot(a.val().trim())):i.defaultDate&&void 0===a.attr("placeholder")&&J(i.defaultDate),i.inline&&it(),h};t.fn.datetimepicker=function(e){return this.each(function(){var i=t(this);i.data("DateTimePicker")||(e=t.extend(!0,{},t.fn.datetimepicker.defaults,e),i.data("DateTimePicker",n(i,e)))})},t.fn.datetimepicker.defaults={timeZone:"Etc/UTC",format:!1,dayViewHeaderFormat:"MMMM YYYY",extraFormats:!1,stepping:1,minDate:!1,maxDate:!1,useCurrent:!0,collapse:!0,locale:e.locale(),defaultDate:!1,disabledDates:!1,enabledDates:!1,icons:{time:"glyphicon glyphicon-time",date:"glyphicon glyphicon-calendar",up:"glyphicon glyphicon-chevron-up",down:"glyphicon glyphicon-chevron-down",previous:"glyphicon glyphicon-chevron-left",next:"glyphicon glyphicon-chevron-right",today:"glyphicon glyphicon-screenshot",clear:"glyphicon glyphicon-trash",close:"glyphicon glyphicon-remove"},tooltips:{today:"Go to today",clear:"Clear selection",close:"Close the picker",selectMonth:"Select Month",prevMonth:"Previous Month",nextMonth:"Next Month",selectYear:"Select Year",prevYear:"Previous Year",nextYear:"Next Year",selectDecade:"Select Decade",prevDecade:"Previous Decade",nextDecade:"Next Decade",prevCentury:"Previous Century",nextCentury:"Next Century",pickHour:"Pick Hour",incrementHour:"Increment Hour",decrementHour:"Decrement Hour",pickMinute:"Pick Minute",incrementMinute:"Increment Minute",decrementMinute:"Decrement Minute",pickSecond:"Pick Second",incrementSecond:"Increment Second",decrementSecond:"Decrement Second",togglePeriod:"Toggle Period",selectTime:"Select Time"},useStrict:!1,sideBySide:!1,daysOfWeekDisabled:!1,calendarWeeks:!1,viewMode:"days",toolbarPlacement:"default",showTodayButton:!1,showClear:!1,showClose:!1,widgetPositioning:{horizontal:"auto",vertical:"auto"},widgetParent:null,ignoreReadonly:!1,keepOpen:!1,focusOnShow:!0,inline:!1,keepInvalid:!1,datepickerInput:".datepickerinput",keyBinds:{up:function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")?this.date(e.clone().subtract(7,"d")):this.date(e.clone().add(this.stepping(),"m"))}},down:function(t){if(!t)return void this.show();var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")?this.date(e.clone().add(7,"d")):this.date(e.clone().subtract(this.stepping(),"m"))},"control up":function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")?this.date(e.clone().subtract(1,"y")):this.date(e.clone().add(1,"h"))}},"control down":function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")?this.date(e.clone().add(1,"y")):this.date(e.clone().subtract(1,"h"))}},left:function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")&&this.date(e.clone().subtract(1,"d"))}},right:function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")&&this.date(e.clone().add(1,"d"))}},pageUp:function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")&&this.date(e.clone().subtract(1,"M"))}},pageDown:function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")&&this.date(e.clone().add(1,"M"))}},enter:function(){this.hide()},escape:function(){this.hide()},"control space":function(t){t.find(".timepicker").is(":visible")&&t.find('.btn[data-action="togglePeriod"]').click()},t:function(){this.date(this.getMoment())},delete:function(){this.clear()}},debug:!1,allowInputToggle:!1,disabledTimeIntervals:!1,disabledHours:!1,enabledHours:!1,viewDate:!1}}),function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t("object"==typeof exports?require("jquery"):jQuery)}(function(t){var e=function(){if(t&&t.fn&&t.fn.select2&&t.fn.select2.amd)var e=t.fn.select2.amd;var e;return function(){if(!e||!e.requirejs){e?n=e:e={};var t,n,i;!function(e){function r(t,e){return x.call(t,e)}function o(t,e){var n,i,r,o,a,s,l,u,c,h,d,f=e&&e.split("/"),p=y.map,g=p&&p["*"]||{};if(t&&"."===t.charAt(0))if(e){for(t=t.split("/"),a=t.length-1,y.nodeIdCompat&&S.test(t[a])&&(t[a]=t[a].replace(S,"")),t=f.slice(0,f.length-1).concat(t),c=0;c0&&(t.splice(c-1,2),c-=2)}t=t.join("/")}else 0===t.indexOf("./")&&(t=t.substring(2));if((f||g)&&p){for(n=t.split("/"),c=n.length;c>0;c-=1){if(i=n.slice(0,c).join("/"),f)for(h=f.length;h>0;h-=1)if((r=p[f.slice(0,h).join("/")])&&(r=r[i])){o=r,s=c;break}if(o)break;!l&&g&&g[i]&&(l=g[i],u=c)}!o&&l&&(o=l,s=u),o&&(n.splice(0,s,o),t=n.join("/"))}return t}function a(t,n){return function(){var i=w.call(arguments,0);return"string"!=typeof i[0]&&1===i.length&&i.push(null),f.apply(e,i.concat([t,n]))}}function s(t){return function(e){return o(e,t)}}function l(t){return function(e){m[t]=e}}function u(t){if(r(v,t)){var n=v[t];delete v[t],b[t]=!0,d.apply(e,n)}if(!r(m,t)&&!r(b,t))throw new Error("No "+t);return m[t]}function c(t){var e,n=t?t.indexOf("!"):-1;return n>-1&&(e=t.substring(0,n),t=t.substring(n+1,t.length)),[e,t]}function h(t){return function(){return y&&y.config&&y.config[t]||{}}}var d,f,p,g,m={},v={},y={},b={},x=Object.prototype.hasOwnProperty,w=[].slice,S=/\.js$/;p=function(t,e){var n,i=c(t),r=i[0];return t=i[1],r&&(r=o(r,e),n=u(r)),r?t=n&&n.normalize?n.normalize(t,s(e)):o(t,e):(t=o(t,e),i=c(t),r=i[0],t=i[1],r&&(n=u(r))),{f:r?r+"!"+t:t,n:t,pr:r,p:n}},g={require:function(t){return a(t)},exports:function(t){var e=m[t];return void 0!==e?e:m[t]={}},module:function(t){return{id:t,uri:"",exports:m[t],config:h(t)}}},d=function(t,n,i,o){var s,c,h,d,f,y,x=[],w=typeof i;if(o=o||t,"undefined"===w||"function"===w){for(n=!n.length&&i.length?["require","exports","module"]:n,f=0;f0&&(e.call(arguments,t.prototype.constructor),r=n.prototype.constructor),r.apply(this,arguments)}function r(){this.constructor=i}var o=e(n),a=e(t);n.displayName=t.displayName,i.prototype=new r;for(var s=0;sn;n++)t[n].apply(this,e)},n.Observable=i,n.generateChars=function(t){for(var e="",n=0;t>n;n++){e+=Math.floor(36*Math.random()).toString(36)}return e},n.bind=function(t,e){return function(){t.apply(e,arguments)}},n._convertData=function(t){for(var e in t){var n=e.split("-"),i=t;if(1!==n.length){for(var r=0;r":">",'"':""","'":"'","/":"/"};return"string"!=typeof t?t:String(t).replace(/[&<>"'\/\\]/g,function(t){return e[t]})},n.appendMany=function(e,n){if("1.7"===t.fn.jquery.substr(0,3)){var i=t();t.map(n,function(t){i=i.add(t)}),n=i}e.append(n)},n}),e.define("select2/results",["jquery","./utils"],function(t,e){function n(t,e,i){this.$element=t,this.data=i,this.options=e,n.__super__.constructor.call(this)}return e.Extend(n,e.Observable),n.prototype.render=function(){var e=t('
      ');return this.options.get("multiple")&&e.attr("aria-multiselectable","true"),this.$results=e,e},n.prototype.clear=function(){this.$results.empty()},n.prototype.displayMessage=function(e){var n=this.options.get("escapeMarkup");this.clear(),this.hideLoading();var i=t('
    • '),r=this.options.get("translations").get(e.message);i.append(n(r(e.args))),i[0].className+=" select2-results__message",this.$results.append(i)},n.prototype.hideMessages=function(){this.$results.find(".select2-results__message").remove()},n.prototype.append=function(t){this.hideLoading();var e=[];if(null==t.results||0===t.results.length)return void(0===this.$results.children().length&&this.trigger("results:message",{message:"noResults"}));t.results=this.sort(t.results);for(var n=0;n0?e.first().trigger("mouseenter"):t.first().trigger("mouseenter"),this.ensureHighlightVisible()},n.prototype.setClasses=function(){var e=this;this.data.current(function(n){var i=t.map(n,function(t){return t.id.toString()});e.$results.find(".select2-results__option[aria-selected]").each(function(){var e=t(this),n=t.data(this,"data"),r=""+n.id;null!=n.element&&n.element.selected||null==n.element&&t.inArray(r,i)>-1?e.attr("aria-selected","true"):e.attr("aria-selected","false")})})},n.prototype.showLoading=function(t){this.hideLoading();var e=this.options.get("translations").get("searching"),n={disabled:!0,loading:!0,text:e(t)},i=this.option(n);i.className+=" loading-results",this.$results.prepend(i)},n.prototype.hideLoading=function(){this.$results.find(".loading-results").remove()},n.prototype.option=function(e){var n=document.createElement("li");n.className="select2-results__option";var i={role:"treeitem","aria-selected":"false"};e.disabled&&(delete i["aria-selected"],i["aria-disabled"]="true"),null==e.id&&delete i["aria-selected"],null!=e._resultId&&(n.id=e._resultId),e.title&&(n.title=e.title),e.children&&(i.role="group",i["aria-label"]=e.text,delete i["aria-selected"]);for(var r in i){var o=i[r];n.setAttribute(r,o)}if(e.children){var a=t(n),s=document.createElement("strong");s.className="select2-results__group",t(s),this.template(e,s);for(var l=[],u=0;u",{class:"select2-results__options select2-results__options--nested"});d.append(l),a.append(s),a.append(d)}else this.template(e,n);return t.data(n,"data",e),n},n.prototype.bind=function(e,n){var i=this,r=e.id+"-results";this.$results.attr("id",r),e.on("results:all",function(t){i.clear(),i.append(t.data),e.isOpen()&&(i.setClasses(),i.highlightFirstItem())}),e.on("results:append",function(t){i.append(t.data),e.isOpen()&&i.setClasses()}),e.on("query",function(t){i.hideMessages(),i.showLoading(t)}),e.on("select",function(){e.isOpen()&&(i.setClasses(),i.highlightFirstItem())}),e.on("unselect",function(){e.isOpen()&&(i.setClasses(),i.highlightFirstItem())}),e.on("open",function(){i.$results.attr("aria-expanded","true"),i.$results.attr("aria-hidden","false"),i.setClasses(),i.ensureHighlightVisible()}),e.on("close",function(){i.$results.attr("aria-expanded","false"),i.$results.attr("aria-hidden","true"),i.$results.removeAttr("aria-activedescendant")}),e.on("results:toggle",function(){var t=i.getHighlightedResults();0!==t.length&&t.trigger("mouseup")}),e.on("results:select",function(){var t=i.getHighlightedResults();if(0!==t.length){var e=t.data("data");"true"==t.attr("aria-selected")?i.trigger("close",{}):i.trigger("select",{data:e})}}),e.on("results:previous",function(){var t=i.getHighlightedResults(),e=i.$results.find("[aria-selected]"),n=e.index(t);if(0!==n){var r=n-1;0===t.length&&(r=0);var o=e.eq(r);o.trigger("mouseenter");var a=i.$results.offset().top,s=o.offset().top,l=i.$results.scrollTop()+(s-a);0===r?i.$results.scrollTop(0):0>s-a&&i.$results.scrollTop(l)}}),e.on("results:next",function(){var t=i.getHighlightedResults(),e=i.$results.find("[aria-selected]"),n=e.index(t),r=n+1;if(!(r>=e.length)){var o=e.eq(r);o.trigger("mouseenter");var a=i.$results.offset().top+i.$results.outerHeight(!1),s=o.offset().top+o.outerHeight(!1),l=i.$results.scrollTop()+s-a;0===r?i.$results.scrollTop(0):s>a&&i.$results.scrollTop(l)}}),e.on("results:focus",function(t){t.element.addClass("select2-results__option--highlighted")}),e.on("results:message",function(t){i.displayMessage(t)}),t.fn.mousewheel&&this.$results.on("mousewheel",function(t){var e=i.$results.scrollTop(),n=i.$results.get(0).scrollHeight-e+t.deltaY,r=t.deltaY>0&&e-t.deltaY<=0,o=t.deltaY<0&&n<=i.$results.height();r?(i.$results.scrollTop(0),t.preventDefault(),t.stopPropagation()):o&&(i.$results.scrollTop(i.$results.get(0).scrollHeight-i.$results.height()),t.preventDefault(),t.stopPropagation())}),this.$results.on("mouseup",".select2-results__option[aria-selected]",function(e){var n=t(this),r=n.data("data");return"true"===n.attr("aria-selected")?void(i.options.get("multiple")?i.trigger("unselect",{originalEvent:e,data:r}):i.trigger("close",{})):void i.trigger("select",{originalEvent:e,data:r})}),this.$results.on("mouseenter",".select2-results__option[aria-selected]",function(e){var n=t(this).data("data");i.getHighlightedResults().removeClass("select2-results__option--highlighted"),i.trigger("results:focus",{data:n,element:t(this)})})},n.prototype.getHighlightedResults=function(){return this.$results.find(".select2-results__option--highlighted")},n.prototype.destroy=function(){this.$results.remove()},n.prototype.ensureHighlightVisible=function(){var t=this.getHighlightedResults();if(0!==t.length){var e=this.$results.find("[aria-selected]"),n=e.index(t),i=this.$results.offset().top,r=t.offset().top,o=this.$results.scrollTop()+(r-i),a=r-i;o-=2*t.outerHeight(!1),2>=n?this.$results.scrollTop(0):(a>this.$results.outerHeight()||0>a)&&this.$results.scrollTop(o)}},n.prototype.template=function(e,n){var i=this.options.get("templateResult"),r=this.options.get("escapeMarkup"),o=i(e,n);null==o?n.style.display="none":"string"==typeof o?n.innerHTML=r(o):t(n).append(o)},n}),e.define("select2/keys",[],function(){return{BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46}}),e.define("select2/selection/base",["jquery","../utils","../keys"],function(t,e,n){function i(t,e){this.$element=t,this.options=e,i.__super__.constructor.call(this)}return e.Extend(i,e.Observable),i.prototype.render=function(){var e=t('');return this._tabindex=0,null!=this.$element.data("old-tabindex")?this._tabindex=this.$element.data("old-tabindex"):null!=this.$element.attr("tabindex")&&(this._tabindex=this.$element.attr("tabindex")),e.attr("title",this.$element.attr("title")),e.attr("tabindex",this._tabindex),this.$selection=e,e},i.prototype.bind=function(t,e){var i=this,r=(t.id,t.id+"-results");this.container=t,this.$selection.on("focus",function(t){i.trigger("focus",t)}),this.$selection.on("blur",function(t){i._handleBlur(t)}),this.$selection.on("keydown",function(t){i.trigger("keypress",t),t.which===n.SPACE&&t.preventDefault()}),t.on("results:focus",function(t){i.$selection.attr("aria-activedescendant",t.data._resultId)}),t.on("selection:update",function(t){i.update(t.data)}),t.on("open",function(){i.$selection.attr("aria-expanded","true"),i.$selection.attr("aria-owns",r),i._attachCloseHandler(t)}),t.on("close",function(){i.$selection.attr("aria-expanded","false"),i.$selection.removeAttr("aria-activedescendant"),i.$selection.removeAttr("aria-owns"),i.$selection.focus(),i._detachCloseHandler(t)}),t.on("enable",function(){i.$selection.attr("tabindex",i._tabindex)}),t.on("disable",function(){i.$selection.attr("tabindex","-1")})},i.prototype._handleBlur=function(e){var n=this;window.setTimeout(function(){document.activeElement==n.$selection[0]||t.contains(n.$selection[0],document.activeElement)||n.trigger("blur",e)},1)},i.prototype._attachCloseHandler=function(e){t(document.body).on("mousedown.select2."+e.id,function(e){var n=t(e.target),i=n.closest(".select2");t(".select2.select2-container--open").each(function(){var e=t(this);this!=i[0]&&e.data("element").select2("close")})})},i.prototype._detachCloseHandler=function(e){t(document.body).off("mousedown.select2."+e.id)},i.prototype.position=function(t,e){e.find(".selection").append(t)},i.prototype.destroy=function(){this._detachCloseHandler(this.container)},i.prototype.update=function(t){throw new Error("The `update` method must be defined in child classes.")},i}),e.define("select2/selection/single",["jquery","./base","../utils","../keys"],function(t,e,n,i){function r(){r.__super__.constructor.apply(this,arguments)}return n.Extend(r,e),r.prototype.render=function(){var t=r.__super__.render.call(this);return t.addClass("select2-selection--single"),t.html(''),t},r.prototype.bind=function(t,e){var n=this;r.__super__.bind.apply(this,arguments);var i=t.id+"-container";this.$selection.find(".select2-selection__rendered").attr("id",i),this.$selection.attr("aria-labelledby",i),this.$selection.on("mousedown",function(t){1===t.which&&n.trigger("toggle",{originalEvent:t})}),this.$selection.on("focus",function(t){}),this.$selection.on("blur",function(t){}),t.on("focus",function(e){t.isOpen()||n.$selection.focus()}),t.on("selection:update",function(t){n.update(t.data)})},r.prototype.clear=function(){this.$selection.find(".select2-selection__rendered").empty()},r.prototype.display=function(t,e){var n=this.options.get("templateSelection");return this.options.get("escapeMarkup")(n(t,e))},r.prototype.selectionContainer=function(){return t("")},r.prototype.update=function(t){if(0===t.length)return void this.clear();var e=t[0],n=this.$selection.find(".select2-selection__rendered"),i=this.display(e,n);n.empty().append(i),n.prop("title",e.title||e.text)},r}),e.define("select2/selection/multiple",["jquery","./base","../utils"],function(t,e,n){function i(t,e){i.__super__.constructor.apply(this,arguments)}return n.Extend(i,e),i.prototype.render=function(){var t=i.__super__.render.call(this);return t.addClass("select2-selection--multiple"),t.html('
        '),t},i.prototype.bind=function(e,n){var r=this;i.__super__.bind.apply(this,arguments),this.$selection.on("click",function(t){r.trigger("toggle",{originalEvent:t})}),this.$selection.on("click",".select2-selection__choice__remove",function(e){if(!r.options.get("disabled")){var n=t(this),i=n.parent(),o=i.data("data");r.trigger("unselect",{originalEvent:e,data:o})}})},i.prototype.clear=function(){this.$selection.find(".select2-selection__rendered").empty()},i.prototype.display=function(t,e){var n=this.options.get("templateSelection");return this.options.get("escapeMarkup")(n(t,e))},i.prototype.selectionContainer=function(){return t('
      • ×
      • ')},i.prototype.update=function(t){if(this.clear(),0!==t.length){for(var e=[],i=0;i1||n)return t.call(this,e);this.clear();var i=this.createPlaceholder(this.placeholder);this.$selection.find(".select2-selection__rendered").append(i)},e}),e.define("select2/selection/allowClear",["jquery","../keys"],function(t,e){function n(){}return n.prototype.bind=function(t,e,n){var i=this;t.call(this,e,n),null==this.placeholder&&this.options.get("debug")&&window.console&&console.error&&console.error("Select2: The `allowClear` option should be used in combination with the `placeholder` option."),this.$selection.on("mousedown",".select2-selection__clear",function(t){i._handleClear(t)}),e.on("keypress",function(t){i._handleKeyboardClear(t,e)})},n.prototype._handleClear=function(t,e){if(!this.options.get("disabled")){var n=this.$selection.find(".select2-selection__clear");if(0!==n.length){e.stopPropagation();for(var i=n.data("data"),r=0;r0||0===n.length)){var i=t('×');i.data("data",n),this.$selection.find(".select2-selection__rendered").prepend(i)}},n}),e.define("select2/selection/search",["jquery","../utils","../keys"],function(t,e,n){function i(t,e,n){t.call(this,e,n)}return i.prototype.render=function(e){var n=t('');this.$searchContainer=n,this.$search=n.find("input");var i=e.call(this);return this._transferTabIndex(),i},i.prototype.bind=function(t,e,i){var r=this;t.call(this,e,i),e.on("open",function(){r.$search.trigger("focus")}),e.on("close",function(){r.$search.val(""),r.$search.removeAttr("aria-activedescendant"),r.$search.trigger("focus")}),e.on("enable",function(){r.$search.prop("disabled",!1),r._transferTabIndex()}),e.on("disable",function(){r.$search.prop("disabled",!0)}),e.on("focus",function(t){r.$search.trigger("focus")}),e.on("results:focus",function(t){r.$search.attr("aria-activedescendant",t.id)}),this.$selection.on("focusin",".select2-search--inline",function(t){r.trigger("focus",t)}),this.$selection.on("focusout",".select2-search--inline",function(t){r._handleBlur(t)}),this.$selection.on("keydown",".select2-search--inline",function(t){if(t.stopPropagation(),r.trigger("keypress",t),r._keyUpPrevented=t.isDefaultPrevented(),t.which===n.BACKSPACE&&""===r.$search.val()){var e=r.$searchContainer.prev(".select2-selection__choice");if(e.length>0){var i=e.data("data");r.searchRemoveChoice(i),t.preventDefault()}}});var o=document.documentMode,a=o&&11>=o;this.$selection.on("input.searchcheck",".select2-search--inline",function(t){return a?void r.$selection.off("input.search input.searchcheck"):void r.$selection.off("keyup.search")}),this.$selection.on("keyup.search input.search",".select2-search--inline",function(t){if(a&&"input"===t.type)return void r.$selection.off("input.search input.searchcheck");var e=t.which;e!=n.SHIFT&&e!=n.CTRL&&e!=n.ALT&&e!=n.TAB&&r.handleSearch(t)})},i.prototype._transferTabIndex=function(t){this.$search.attr("tabindex",this.$selection.attr("tabindex")),this.$selection.attr("tabindex","-1")},i.prototype.createPlaceholder=function(t,e){this.$search.attr("placeholder",e.text)},i.prototype.update=function(t,e){var n=this.$search[0]==document.activeElement;this.$search.attr("placeholder",""),t.call(this,e),this.$selection.find(".select2-selection__rendered").append(this.$searchContainer),this.resizeSearch(),n&&this.$search.focus()},i.prototype.handleSearch=function(){if(this.resizeSearch(),!this._keyUpPrevented){var t=this.$search.val();this.trigger("query",{term:t})}this._keyUpPrevented=!1},i.prototype.searchRemoveChoice=function(t,e){this.trigger("unselect",{data:e}),this.$search.val(e.text),this.handleSearch()},i.prototype.resizeSearch=function(){this.$search.css("width","25px");var t="";if(""!==this.$search.attr("placeholder"))t=this.$selection.find(".select2-selection__rendered").innerWidth();else{t=.75*(this.$search.val().length+1)+"em"}this.$search.css("width",t)},i}),e.define("select2/selection/eventRelay",["jquery"],function(t){function e(){}return e.prototype.bind=function(e,n,i){var r=this,o=["open","opening","close","closing","select","selecting","unselect","unselecting"],a=["opening","closing","selecting","unselecting"];e.call(this,n,i),n.on("*",function(e,n){if(-1!==t.inArray(e,o)){n=n||{};var i=t.Event("select2:"+e,{params:n});r.$element.trigger(i),-1!==t.inArray(e,a)&&(n.prevented=i.isDefaultPrevented())}})},e}),e.define("select2/translation",["jquery","require"],function(t,e){function n(t){this.dict=t||{}}return n.prototype.all=function(){return this.dict},n.prototype.get=function(t){return this.dict[t]},n.prototype.extend=function(e){this.dict=t.extend({},e.all(),this.dict)},n._cache={},n.loadPath=function(t){if(!(t in n._cache)){var i=e(t);n._cache[t]=i}return new n(n._cache[t])},n}),e.define("select2/diacritics",[],function(){return{"Ⓐ":"A","A":"A","À":"A","Á":"A","Â":"A","Ầ":"A","Ấ":"A","Ẫ":"A","Ẩ":"A","Ã":"A","Ā":"A","Ă":"A","Ằ":"A","Ắ":"A","Ẵ":"A","Ẳ":"A","Ȧ":"A","Ǡ":"A","Ä":"A","Ǟ":"A","Ả":"A","Å":"A","Ǻ":"A","Ǎ":"A","Ȁ":"A","Ȃ":"A","Ạ":"A","Ậ":"A","Ặ":"A","Ḁ":"A", -"Ą":"A","Ⱥ":"A","Ɐ":"A","Ꜳ":"AA","Æ":"AE","Ǽ":"AE","Ǣ":"AE","Ꜵ":"AO","Ꜷ":"AU","Ꜹ":"AV","Ꜻ":"AV","Ꜽ":"AY","Ⓑ":"B","B":"B","Ḃ":"B","Ḅ":"B","Ḇ":"B","Ƀ":"B","Ƃ":"B","Ɓ":"B","Ⓒ":"C","C":"C","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","Ç":"C","Ḉ":"C","Ƈ":"C","Ȼ":"C","Ꜿ":"C","Ⓓ":"D","D":"D","Ḋ":"D","Ď":"D","Ḍ":"D","Ḑ":"D","Ḓ":"D","Ḏ":"D","Đ":"D","Ƌ":"D","Ɗ":"D","Ɖ":"D","Ꝺ":"D","DZ":"DZ","DŽ":"DZ","Dz":"Dz","Dž":"Dz","Ⓔ":"E","E":"E","È":"E","É":"E","Ê":"E","Ề":"E","Ế":"E","Ễ":"E","Ể":"E","Ẽ":"E","Ē":"E","Ḕ":"E","Ḗ":"E","Ĕ":"E","Ė":"E","Ë":"E","Ẻ":"E","Ě":"E","Ȅ":"E","Ȇ":"E","Ẹ":"E","Ệ":"E","Ȩ":"E","Ḝ":"E","Ę":"E","Ḙ":"E","Ḛ":"E","Ɛ":"E","Ǝ":"E","Ⓕ":"F","F":"F","Ḟ":"F","Ƒ":"F","Ꝼ":"F","Ⓖ":"G","G":"G","Ǵ":"G","Ĝ":"G","Ḡ":"G","Ğ":"G","Ġ":"G","Ǧ":"G","Ģ":"G","Ǥ":"G","Ɠ":"G","Ꞡ":"G","Ᵹ":"G","Ꝿ":"G","Ⓗ":"H","H":"H","Ĥ":"H","Ḣ":"H","Ḧ":"H","Ȟ":"H","Ḥ":"H","Ḩ":"H","Ḫ":"H","Ħ":"H","Ⱨ":"H","Ⱶ":"H","Ɥ":"H","Ⓘ":"I","I":"I","Ì":"I","Í":"I","Î":"I","Ĩ":"I","Ī":"I","Ĭ":"I","İ":"I","Ï":"I","Ḯ":"I","Ỉ":"I","Ǐ":"I","Ȉ":"I","Ȋ":"I","Ị":"I","Į":"I","Ḭ":"I","Ɨ":"I","Ⓙ":"J","J":"J","Ĵ":"J","Ɉ":"J","Ⓚ":"K","K":"K","Ḱ":"K","Ǩ":"K","Ḳ":"K","Ķ":"K","Ḵ":"K","Ƙ":"K","Ⱪ":"K","Ꝁ":"K","Ꝃ":"K","Ꝅ":"K","Ꞣ":"K","Ⓛ":"L","L":"L","Ŀ":"L","Ĺ":"L","Ľ":"L","Ḷ":"L","Ḹ":"L","Ļ":"L","Ḽ":"L","Ḻ":"L","Ł":"L","Ƚ":"L","Ɫ":"L","Ⱡ":"L","Ꝉ":"L","Ꝇ":"L","Ꞁ":"L","LJ":"LJ","Lj":"Lj","Ⓜ":"M","M":"M","Ḿ":"M","Ṁ":"M","Ṃ":"M","Ɱ":"M","Ɯ":"M","Ⓝ":"N","N":"N","Ǹ":"N","Ń":"N","Ñ":"N","Ṅ":"N","Ň":"N","Ṇ":"N","Ņ":"N","Ṋ":"N","Ṉ":"N","Ƞ":"N","Ɲ":"N","Ꞑ":"N","Ꞥ":"N","NJ":"NJ","Nj":"Nj","Ⓞ":"O","O":"O","Ò":"O","Ó":"O","Ô":"O","Ồ":"O","Ố":"O","Ỗ":"O","Ổ":"O","Õ":"O","Ṍ":"O","Ȭ":"O","Ṏ":"O","Ō":"O","Ṑ":"O","Ṓ":"O","Ŏ":"O","Ȯ":"O","Ȱ":"O","Ö":"O","Ȫ":"O","Ỏ":"O","Ő":"O","Ǒ":"O","Ȍ":"O","Ȏ":"O","Ơ":"O","Ờ":"O","Ớ":"O","Ỡ":"O","Ở":"O","Ợ":"O","Ọ":"O","Ộ":"O","Ǫ":"O","Ǭ":"O","Ø":"O","Ǿ":"O","Ɔ":"O","Ɵ":"O","Ꝋ":"O","Ꝍ":"O","Ƣ":"OI","Ꝏ":"OO","Ȣ":"OU","Ⓟ":"P","P":"P","Ṕ":"P","Ṗ":"P","Ƥ":"P","Ᵽ":"P","Ꝑ":"P","Ꝓ":"P","Ꝕ":"P","Ⓠ":"Q","Q":"Q","Ꝗ":"Q","Ꝙ":"Q","Ɋ":"Q","Ⓡ":"R","R":"R","Ŕ":"R","Ṙ":"R","Ř":"R","Ȑ":"R","Ȓ":"R","Ṛ":"R","Ṝ":"R","Ŗ":"R","Ṟ":"R","Ɍ":"R","Ɽ":"R","Ꝛ":"R","Ꞧ":"R","Ꞃ":"R","Ⓢ":"S","S":"S","ẞ":"S","Ś":"S","Ṥ":"S","Ŝ":"S","Ṡ":"S","Š":"S","Ṧ":"S","Ṣ":"S","Ṩ":"S","Ș":"S","Ş":"S","Ȿ":"S","Ꞩ":"S","Ꞅ":"S","Ⓣ":"T","T":"T","Ṫ":"T","Ť":"T","Ṭ":"T","Ț":"T","Ţ":"T","Ṱ":"T","Ṯ":"T","Ŧ":"T","Ƭ":"T","Ʈ":"T","Ⱦ":"T","Ꞇ":"T","Ꜩ":"TZ","Ⓤ":"U","U":"U","Ù":"U","Ú":"U","Û":"U","Ũ":"U","Ṹ":"U","Ū":"U","Ṻ":"U","Ŭ":"U","Ü":"U","Ǜ":"U","Ǘ":"U","Ǖ":"U","Ǚ":"U","Ủ":"U","Ů":"U","Ű":"U","Ǔ":"U","Ȕ":"U","Ȗ":"U","Ư":"U","Ừ":"U","Ứ":"U","Ữ":"U","Ử":"U","Ự":"U","Ụ":"U","Ṳ":"U","Ų":"U","Ṷ":"U","Ṵ":"U","Ʉ":"U","Ⓥ":"V","V":"V","Ṽ":"V","Ṿ":"V","Ʋ":"V","Ꝟ":"V","Ʌ":"V","Ꝡ":"VY","Ⓦ":"W","W":"W","Ẁ":"W","Ẃ":"W","Ŵ":"W","Ẇ":"W","Ẅ":"W","Ẉ":"W","Ⱳ":"W","Ⓧ":"X","X":"X","Ẋ":"X","Ẍ":"X","Ⓨ":"Y","Y":"Y","Ỳ":"Y","Ý":"Y","Ŷ":"Y","Ỹ":"Y","Ȳ":"Y","Ẏ":"Y","Ÿ":"Y","Ỷ":"Y","Ỵ":"Y","Ƴ":"Y","Ɏ":"Y","Ỿ":"Y","Ⓩ":"Z","Z":"Z","Ź":"Z","Ẑ":"Z","Ż":"Z","Ž":"Z","Ẓ":"Z","Ẕ":"Z","Ƶ":"Z","Ȥ":"Z","Ɀ":"Z","Ⱬ":"Z","Ꝣ":"Z","ⓐ":"a","a":"a","ẚ":"a","à":"a","á":"a","â":"a","ầ":"a","ấ":"a","ẫ":"a","ẩ":"a","ã":"a","ā":"a","ă":"a","ằ":"a","ắ":"a","ẵ":"a","ẳ":"a","ȧ":"a","ǡ":"a","ä":"a","ǟ":"a","ả":"a","å":"a","ǻ":"a","ǎ":"a","ȁ":"a","ȃ":"a","ạ":"a","ậ":"a","ặ":"a","ḁ":"a","ą":"a","ⱥ":"a","ɐ":"a","ꜳ":"aa","æ":"ae","ǽ":"ae","ǣ":"ae","ꜵ":"ao","ꜷ":"au","ꜹ":"av","ꜻ":"av","ꜽ":"ay","ⓑ":"b","b":"b","ḃ":"b","ḅ":"b","ḇ":"b","ƀ":"b","ƃ":"b","ɓ":"b","ⓒ":"c","c":"c","ć":"c","ĉ":"c","ċ":"c","č":"c","ç":"c","ḉ":"c","ƈ":"c","ȼ":"c","ꜿ":"c","ↄ":"c","ⓓ":"d","d":"d","ḋ":"d","ď":"d","ḍ":"d","ḑ":"d","ḓ":"d","ḏ":"d","đ":"d","ƌ":"d","ɖ":"d","ɗ":"d","ꝺ":"d","dz":"dz","dž":"dz","ⓔ":"e","e":"e","è":"e","é":"e","ê":"e","ề":"e","ế":"e","ễ":"e","ể":"e","ẽ":"e","ē":"e","ḕ":"e","ḗ":"e","ĕ":"e","ė":"e","ë":"e","ẻ":"e","ě":"e","ȅ":"e","ȇ":"e","ẹ":"e","ệ":"e","ȩ":"e","ḝ":"e","ę":"e","ḙ":"e","ḛ":"e","ɇ":"e","ɛ":"e","ǝ":"e","ⓕ":"f","f":"f","ḟ":"f","ƒ":"f","ꝼ":"f","ⓖ":"g","g":"g","ǵ":"g","ĝ":"g","ḡ":"g","ğ":"g","ġ":"g","ǧ":"g","ģ":"g","ǥ":"g","ɠ":"g","ꞡ":"g","ᵹ":"g","ꝿ":"g","ⓗ":"h","h":"h","ĥ":"h","ḣ":"h","ḧ":"h","ȟ":"h","ḥ":"h","ḩ":"h","ḫ":"h","ẖ":"h","ħ":"h","ⱨ":"h","ⱶ":"h","ɥ":"h","ƕ":"hv","ⓘ":"i","i":"i","ì":"i","í":"i","î":"i","ĩ":"i","ī":"i","ĭ":"i","ï":"i","ḯ":"i","ỉ":"i","ǐ":"i","ȉ":"i","ȋ":"i","ị":"i","į":"i","ḭ":"i","ɨ":"i","ı":"i","ⓙ":"j","j":"j","ĵ":"j","ǰ":"j","ɉ":"j","ⓚ":"k","k":"k","ḱ":"k","ǩ":"k","ḳ":"k","ķ":"k","ḵ":"k","ƙ":"k","ⱪ":"k","ꝁ":"k","ꝃ":"k","ꝅ":"k","ꞣ":"k","ⓛ":"l","l":"l","ŀ":"l","ĺ":"l","ľ":"l","ḷ":"l","ḹ":"l","ļ":"l","ḽ":"l","ḻ":"l","ſ":"l","ł":"l","ƚ":"l","ɫ":"l","ⱡ":"l","ꝉ":"l","ꞁ":"l","ꝇ":"l","lj":"lj","ⓜ":"m","m":"m","ḿ":"m","ṁ":"m","ṃ":"m","ɱ":"m","ɯ":"m","ⓝ":"n","n":"n","ǹ":"n","ń":"n","ñ":"n","ṅ":"n","ň":"n","ṇ":"n","ņ":"n","ṋ":"n","ṉ":"n","ƞ":"n","ɲ":"n","ʼn":"n","ꞑ":"n","ꞥ":"n","nj":"nj","ⓞ":"o","o":"o","ò":"o","ó":"o","ô":"o","ồ":"o","ố":"o","ỗ":"o","ổ":"o","õ":"o","ṍ":"o","ȭ":"o","ṏ":"o","ō":"o","ṑ":"o","ṓ":"o","ŏ":"o","ȯ":"o","ȱ":"o","ö":"o","ȫ":"o","ỏ":"o","ő":"o","ǒ":"o","ȍ":"o","ȏ":"o","ơ":"o","ờ":"o","ớ":"o","ỡ":"o","ở":"o","ợ":"o","ọ":"o","ộ":"o","ǫ":"o","ǭ":"o","ø":"o","ǿ":"o","ɔ":"o","ꝋ":"o","ꝍ":"o","ɵ":"o","ƣ":"oi","ȣ":"ou","ꝏ":"oo","ⓟ":"p","p":"p","ṕ":"p","ṗ":"p","ƥ":"p","ᵽ":"p","ꝑ":"p","ꝓ":"p","ꝕ":"p","ⓠ":"q","q":"q","ɋ":"q","ꝗ":"q","ꝙ":"q","ⓡ":"r","r":"r","ŕ":"r","ṙ":"r","ř":"r","ȑ":"r","ȓ":"r","ṛ":"r","ṝ":"r","ŗ":"r","ṟ":"r","ɍ":"r","ɽ":"r","ꝛ":"r","ꞧ":"r","ꞃ":"r","ⓢ":"s","s":"s","ß":"s","ś":"s","ṥ":"s","ŝ":"s","ṡ":"s","š":"s","ṧ":"s","ṣ":"s","ṩ":"s","ș":"s","ş":"s","ȿ":"s","ꞩ":"s","ꞅ":"s","ẛ":"s","ⓣ":"t","t":"t","ṫ":"t","ẗ":"t","ť":"t","ṭ":"t","ț":"t","ţ":"t","ṱ":"t","ṯ":"t","ŧ":"t","ƭ":"t","ʈ":"t","ⱦ":"t","ꞇ":"t","ꜩ":"tz","ⓤ":"u","u":"u","ù":"u","ú":"u","û":"u","ũ":"u","ṹ":"u","ū":"u","ṻ":"u","ŭ":"u","ü":"u","ǜ":"u","ǘ":"u","ǖ":"u","ǚ":"u","ủ":"u","ů":"u","ű":"u","ǔ":"u","ȕ":"u","ȗ":"u","ư":"u","ừ":"u","ứ":"u","ữ":"u","ử":"u","ự":"u","ụ":"u","ṳ":"u","ų":"u","ṷ":"u","ṵ":"u","ʉ":"u","ⓥ":"v","v":"v","ṽ":"v","ṿ":"v","ʋ":"v","ꝟ":"v","ʌ":"v","ꝡ":"vy","ⓦ":"w","w":"w","ẁ":"w","ẃ":"w","ŵ":"w","ẇ":"w","ẅ":"w","ẘ":"w","ẉ":"w","ⱳ":"w","ⓧ":"x","x":"x","ẋ":"x","ẍ":"x","ⓨ":"y","y":"y","ỳ":"y","ý":"y","ŷ":"y","ỹ":"y","ȳ":"y","ẏ":"y","ÿ":"y","ỷ":"y","ẙ":"y","ỵ":"y","ƴ":"y","ɏ":"y","ỿ":"y","ⓩ":"z","z":"z","ź":"z","ẑ":"z","ż":"z","ž":"z","ẓ":"z","ẕ":"z","ƶ":"z","ȥ":"z","ɀ":"z","ⱬ":"z","ꝣ":"z","Ά":"Α","Έ":"Ε","Ή":"Η","Ί":"Ι","Ϊ":"Ι","Ό":"Ο","Ύ":"Υ","Ϋ":"Υ","Ώ":"Ω","ά":"α","έ":"ε","ή":"η","ί":"ι","ϊ":"ι","ΐ":"ι","ό":"ο","ύ":"υ","ϋ":"υ","ΰ":"υ","ω":"ω","ς":"σ"}}),e.define("select2/data/base",["../utils"],function(t){function e(t,n){e.__super__.constructor.call(this)}return t.Extend(e,t.Observable),e.prototype.current=function(t){throw new Error("The `current` method must be defined in child classes.")},e.prototype.query=function(t,e){throw new Error("The `query` method must be defined in child classes.")},e.prototype.bind=function(t,e){},e.prototype.destroy=function(){},e.prototype.generateResultId=function(e,n){var i=e.id+"-result-";return i+=t.generateChars(4),i+=null!=n.id?"-"+n.id.toString():"-"+t.generateChars(4)},e}),e.define("select2/data/select",["./base","../utils","jquery"],function(t,e,n){function i(t,e){this.$element=t,this.options=e,i.__super__.constructor.call(this)}return e.Extend(i,t),i.prototype.current=function(t){var e=[],i=this;this.$element.find(":selected").each(function(){var t=n(this),r=i.item(t);e.push(r)}),t(e)},i.prototype.select=function(t){var e=this;if(t.selected=!0,n(t.element).is("option"))return t.element.selected=!0,void this.$element.trigger("change");if(this.$element.prop("multiple"))this.current(function(i){var r=[];t=[t],t.push.apply(t,i);for(var o=0;o=0){var u=r.filter(function(t){return function(){return n(this).val()==t.id}}(l)),c=this.item(u),h=n.extend(!0,{},l,c),d=this.option(h);u.replaceWith(d)}else{var f=this.option(l);if(l.children){var p=this.convertToOptions(l.children);e.appendMany(f,p)}a.push(f)}}return a},i}),e.define("select2/data/ajax",["./array","../utils","jquery"],function(t,e,n){function i(t,e){this.ajaxOptions=this._applyDefaults(e.get("ajax")),null!=this.ajaxOptions.processResults&&(this.processResults=this.ajaxOptions.processResults),i.__super__.constructor.call(this,t,e)}return e.Extend(i,t),i.prototype._applyDefaults=function(t){var e={data:function(t){return n.extend({},t,{q:t.term})},transport:function(t,e,i){var r=n.ajax(t);return r.then(e),r.fail(i),r}};return n.extend({},e,t,!0)},i.prototype.processResults=function(t){return t},i.prototype.query=function(t,e){function i(){var i=o.transport(o,function(i){var o=r.processResults(i,t);r.options.get("debug")&&window.console&&console.error&&(o&&o.results&&n.isArray(o.results)||console.error("Select2: The AJAX results did not return an array in the `results` key of the response.")),e(o)},function(){i.status&&"0"===i.status||r.trigger("results:message",{message:"errorLoading"})});r._request=i}var r=this;null!=this._request&&(n.isFunction(this._request.abort)&&this._request.abort(),this._request=null);var o=n.extend({type:"GET"},this.ajaxOptions);"function"==typeof o.url&&(o.url=o.url.call(this.$element,t)),"function"==typeof o.data&&(o.data=o.data.call(this.$element,t)),this.ajaxOptions.delay&&null!=t.term?(this._queryTimeout&&window.clearTimeout(this._queryTimeout),this._queryTimeout=window.setTimeout(i,this.ajaxOptions.delay)):i()},i}),e.define("select2/data/tags",["jquery"],function(t){function e(e,n,i){var r=i.get("tags"),o=i.get("createTag");void 0!==o&&(this.createTag=o);var a=i.get("insertTag");if(void 0!==a&&(this.insertTag=a),e.call(this,n,i),t.isArray(r))for(var s=0;s0&&e.term.length>this.maximumInputLength?void this.trigger("results:message",{message:"inputTooLong",args:{maximum:this.maximumInputLength,input:e.term,params:e}}):void t.call(this,e,n)},t}),e.define("select2/data/maximumSelectionLength",[],function(){function t(t,e,n){this.maximumSelectionLength=n.get("maximumSelectionLength"),t.call(this,e,n)}return t.prototype.query=function(t,e,n){var i=this;this.current(function(r){var o=null!=r?r.length:0;return i.maximumSelectionLength>0&&o>=i.maximumSelectionLength?void i.trigger("results:message",{message:"maximumSelected",args:{maximum:i.maximumSelectionLength}}):void t.call(i,e,n)})},t}),e.define("select2/dropdown",["jquery","./utils"],function(t,e){function n(t,e){this.$element=t,this.options=e,n.__super__.constructor.call(this)}return e.Extend(n,e.Observable),n.prototype.render=function(){var e=t('');return e.attr("dir",this.options.get("dir")),this.$dropdown=e,e},n.prototype.bind=function(){},n.prototype.position=function(t,e){},n.prototype.destroy=function(){this.$dropdown.remove()},n}),e.define("select2/dropdown/search",["jquery","../utils"],function(t,e){function n(){}return n.prototype.render=function(e){var n=e.call(this),i=t('');return this.$searchContainer=i,this.$search=i.find("input"),n.prepend(i),n},n.prototype.bind=function(e,n,i){var r=this;e.call(this,n,i),this.$search.on("keydown",function(t){r.trigger("keypress",t),r._keyUpPrevented=t.isDefaultPrevented()}),this.$search.on("input",function(e){t(this).off("keyup")}),this.$search.on("keyup input",function(t){r.handleSearch(t)}),n.on("open",function(){r.$search.attr("tabindex",0),r.$search.focus(),window.setTimeout(function(){r.$search.focus()},0)}),n.on("close",function(){r.$search.attr("tabindex",-1),r.$search.val("")}),n.on("focus",function(){n.isOpen()&&r.$search.focus()}),n.on("results:all",function(t){if(null==t.query.term||""===t.query.term){r.showSearch(t)?r.$searchContainer.removeClass("select2-search--hide"):r.$searchContainer.addClass("select2-search--hide")}})},n.prototype.handleSearch=function(t){if(!this._keyUpPrevented){var e=this.$search.val();this.trigger("query",{term:e})}this._keyUpPrevented=!1},n.prototype.showSearch=function(t,e){return!0},n}),e.define("select2/dropdown/hidePlaceholder",[],function(){function t(t,e,n,i){this.placeholder=this.normalizePlaceholder(n.get("placeholder")),t.call(this,e,n,i)}return t.prototype.append=function(t,e){e.results=this.removePlaceholder(e.results),t.call(this,e)},t.prototype.normalizePlaceholder=function(t,e){return"string"==typeof e&&(e={id:"",text:e}),e},t.prototype.removePlaceholder=function(t,e){for(var n=e.slice(0),i=e.length-1;i>=0;i--){var r=e[i];this.placeholder.id===r.id&&n.splice(i,1)}return n},t}),e.define("select2/dropdown/infiniteScroll",["jquery"],function(t){function e(t,e,n,i){this.lastParams={},t.call(this,e,n,i),this.$loadingMore=this.createLoadingMore(),this.loading=!1}return e.prototype.append=function(t,e){this.$loadingMore.remove(),this.loading=!1,t.call(this,e),this.showLoadingMore(e)&&this.$results.append(this.$loadingMore)},e.prototype.bind=function(e,n,i){var r=this;e.call(this,n,i),n.on("query",function(t){r.lastParams=t,r.loading=!0}),n.on("query:append",function(t){r.lastParams=t,r.loading=!0}),this.$results.on("scroll",function(){var e=t.contains(document.documentElement,r.$loadingMore[0]);if(!r.loading&&e){r.$results.offset().top+r.$results.outerHeight(!1)+50>=r.$loadingMore.offset().top+r.$loadingMore.outerHeight(!1)&&r.loadMore()}})},e.prototype.loadMore=function(){this.loading=!0;var e=t.extend({},{page:1},this.lastParams);e.page++,this.trigger("query:append",e)},e.prototype.showLoadingMore=function(t,e){return e.pagination&&e.pagination.more},e.prototype.createLoadingMore=function(){var e=t('
      • '),n=this.options.get("translations").get("loadingMore");return e.html(n(this.lastParams)),e},e}),e.define("select2/dropdown/attachBody",["jquery","../utils"],function(t,e){function n(e,n,i){this.$dropdownParent=i.get("dropdownParent")||t(document.body),e.call(this,n,i)}return n.prototype.bind=function(t,e,n){var i=this,r=!1;t.call(this,e,n),e.on("open",function(){i._showDropdown(),i._attachPositioningHandler(e),r||(r=!0,e.on("results:all",function(){i._positionDropdown(),i._resizeDropdown()}),e.on("results:append",function(){i._positionDropdown(),i._resizeDropdown()}))}),e.on("close",function(){i._hideDropdown(),i._detachPositioningHandler(e)}),this.$dropdownContainer.on("mousedown",function(t){t.stopPropagation()})},n.prototype.destroy=function(t){t.call(this),this.$dropdownContainer.remove()},n.prototype.position=function(t,e,n){e.attr("class",n.attr("class")),e.removeClass("select2"),e.addClass("select2-container--open"),e.css({position:"absolute",top:-999999}),this.$container=n},n.prototype.render=function(e){var n=t(""),i=e.call(this);return n.append(i),this.$dropdownContainer=n,n},n.prototype._hideDropdown=function(t){this.$dropdownContainer.detach()},n.prototype._attachPositioningHandler=function(n,i){var r=this,o="scroll.select2."+i.id,a="resize.select2."+i.id,s="orientationchange.select2."+i.id,l=this.$container.parents().filter(e.hasScroll);l.each(function(){t(this).data("select2-scroll-position",{x:t(this).scrollLeft(),y:t(this).scrollTop()})}),l.on(o,function(e){var n=t(this).data("select2-scroll-position");t(this).scrollTop(n.y)}),t(window).on(o+" "+a+" "+s,function(t){r._positionDropdown(),r._resizeDropdown()})},n.prototype._detachPositioningHandler=function(n,i){var r="scroll.select2."+i.id,o="resize.select2."+i.id,a="orientationchange.select2."+i.id;this.$container.parents().filter(e.hasScroll).off(r),t(window).off(r+" "+o+" "+a)},n.prototype._positionDropdown=function(){var e=t(window),n=this.$dropdown.hasClass("select2-dropdown--above"),i=this.$dropdown.hasClass("select2-dropdown--below"),r=null,o=this.$container.offset();o.bottom=o.top+this.$container.outerHeight(!1);var a={height:this.$container.outerHeight(!1)};a.top=o.top,a.bottom=o.top+a.height;var s={height:this.$dropdown.outerHeight(!1)},l={top:e.scrollTop(),bottom:e.scrollTop()+e.height()},u=l.topo.bottom+s.height,h={left:o.left,top:a.bottom},d=this.$dropdownParent;"static"===d.css("position")&&(d=d.offsetParent());var f=d.offset();h.top-=f.top,h.left-=f.left,n||i||(r="below"),c||!u||n?!u&&c&&n&&(r="below"):r="above",("above"==r||n&&"below"!==r)&&(h.top=a.top-f.top-s.height),null!=r&&(this.$dropdown.removeClass("select2-dropdown--below select2-dropdown--above").addClass("select2-dropdown--"+r),this.$container.removeClass("select2-container--below select2-container--above").addClass("select2-container--"+r)),this.$dropdownContainer.css(h)},n.prototype._resizeDropdown=function(){var t={width:this.$container.outerWidth(!1)+"px"};this.options.get("dropdownAutoWidth")&&(t.minWidth=t.width,t.position="relative",t.width="auto"),this.$dropdown.css(t)},n.prototype._showDropdown=function(t){this.$dropdownContainer.appendTo(this.$dropdownParent),this._positionDropdown(),this._resizeDropdown()},n}),e.define("select2/dropdown/minimumResultsForSearch",[],function(){function t(e){for(var n=0,i=0;i0&&(h.dataAdapter=u.Decorate(h.dataAdapter,v)),h.maximumInputLength>0&&(h.dataAdapter=u.Decorate(h.dataAdapter,y)),h.maximumSelectionLength>0&&(h.dataAdapter=u.Decorate(h.dataAdapter,b)),h.tags&&(h.dataAdapter=u.Decorate(h.dataAdapter,g)),(null!=h.tokenSeparators||null!=h.tokenizer)&&(h.dataAdapter=u.Decorate(h.dataAdapter,m)),null!=h.query){var D=e(h.amdBase+"compat/query");h.dataAdapter=u.Decorate(h.dataAdapter,D)}if(null!=h.initSelection){var A=e(h.amdBase+"compat/initSelection");h.dataAdapter=u.Decorate(h.dataAdapter,A)}}if(null==h.resultsAdapter&&(h.resultsAdapter=n,null!=h.ajax&&(h.resultsAdapter=u.Decorate(h.resultsAdapter,_)),null!=h.placeholder&&(h.resultsAdapter=u.Decorate(h.resultsAdapter,S)),h.selectOnClose&&(h.resultsAdapter=u.Decorate(h.resultsAdapter,M))),null==h.dropdownAdapter){if(h.multiple)h.dropdownAdapter=x;else{var P=u.Decorate(x,w);h.dropdownAdapter=P}if(0!==h.minimumResultsForSearch&&(h.dropdownAdapter=u.Decorate(h.dropdownAdapter,C)),h.closeOnSelect&&(h.dropdownAdapter=u.Decorate(h.dropdownAdapter,T)),null!=h.dropdownCssClass||null!=h.dropdownCss||null!=h.adaptDropdownCssClass){var E=e(h.amdBase+"compat/dropdownCss");h.dropdownAdapter=u.Decorate(h.dropdownAdapter,E)}h.dropdownAdapter=u.Decorate(h.dropdownAdapter,k)}if(null==h.selectionAdapter){if(h.multiple?h.selectionAdapter=r:h.selectionAdapter=i,null!=h.placeholder&&(h.selectionAdapter=u.Decorate(h.selectionAdapter,o)),h.allowClear&&(h.selectionAdapter=u.Decorate(h.selectionAdapter,a)),h.multiple&&(h.selectionAdapter=u.Decorate(h.selectionAdapter,s)),null!=h.containerCssClass||null!=h.containerCss||null!=h.adaptContainerCssClass){var O=e(h.amdBase+"compat/containerCss");h.selectionAdapter=u.Decorate(h.selectionAdapter,O)}h.selectionAdapter=u.Decorate(h.selectionAdapter,l)}if("string"==typeof h.language)if(h.language.indexOf("-")>0){var L=h.language.split("-"),I=L[0];h.language=[h.language,I]}else h.language=[h.language];if(t.isArray(h.language)){var N=new c;h.language.push("en");for(var F=h.language,R=0;R0){for(var o=t.extend(!0,{},r),a=r.children.length-1;a>=0;a--){null==n(i,r.children[a])&&o.children.splice(a,1)}return o.children.length>0?o:n(i,o)}var s=e(r.text).toUpperCase(),l=e(i.term).toUpperCase();return s.indexOf(l)>-1?r:null}this.defaults={amdBase:"./",amdLanguageBase:"./i18n/",closeOnSelect:!0,debug:!1,dropdownAutoWidth:!1,escapeMarkup:u.escapeMarkup,language:D,matcher:n,minimumInputLength:0,maximumInputLength:0,maximumSelectionLength:0,minimumResultsForSearch:0,selectOnClose:!1,sorter:function(t){return t},templateResult:function(t){return t.text},templateSelection:function(t){return t.text},theme:"default",width:"resolve"}},A.prototype.set=function(e,n){var i=t.camelCase(e),r={};r[i]=n;var o=u._convertData(r);t.extend(this.defaults,o)},new A}),e.define("select2/options",["require","jquery","./defaults","./utils"],function(t,e,n,i){function r(e,r){if(this.options=e,null!=r&&this.fromElement(r),this.options=n.apply(this.options),r&&r.is("input")){var o=t(this.get("amdBase")+"compat/inputData");this.options.dataAdapter=i.Decorate(this.options.dataAdapter,o)}}return r.prototype.fromElement=function(t){var n=["select2"];null==this.options.multiple&&(this.options.multiple=t.prop("multiple")),null==this.options.disabled&&(this.options.disabled=t.prop("disabled")),null==this.options.language&&(t.prop("lang")?this.options.language=t.prop("lang").toLowerCase():t.closest("[lang]").prop("lang")&&(this.options.language=t.closest("[lang]").prop("lang"))),null==this.options.dir&&(t.prop("dir")?this.options.dir=t.prop("dir"):t.closest("[dir]").prop("dir")?this.options.dir=t.closest("[dir]").prop("dir"):this.options.dir="ltr"),t.prop("disabled",this.options.disabled),t.prop("multiple",this.options.multiple),t.data("select2Tags")&&(this.options.debug&&window.console&&console.warn&&console.warn('Select2: The `data-select2-tags` attribute has been changed to use the `data-data` and `data-tags="true"` attributes and will be removed in future versions of Select2.'),t.data("data",t.data("select2Tags")),t.data("tags",!0)),t.data("ajaxUrl")&&(this.options.debug&&window.console&&console.warn&&console.warn("Select2: The `data-ajax-url` attribute has been changed to `data-ajax--url` and support for the old attribute will be removed in future versions of Select2."),t.attr("ajax--url",t.data("ajaxUrl")),t.data("ajax--url",t.data("ajaxUrl")));var r={};r=e.fn.jquery&&"1."==e.fn.jquery.substr(0,2)&&t[0].dataset?e.extend(!0,{},t[0].dataset,t.data()):t.data();var o=e.extend(!0,{},r);o=i._convertData(o);for(var a in o)e.inArray(a,n)>-1||(e.isPlainObject(this.options[a])?e.extend(this.options[a],o[a]):this.options[a]=o[a]);return this},r.prototype.get=function(t){return this.options[t]},r.prototype.set=function(t,e){this.options[t]=e},r}),e.define("select2/core",["jquery","./options","./utils","./keys"],function(t,e,n,i){var r=function(t,n){null!=t.data("select2")&&t.data("select2").destroy(),this.$element=t,this.id=this._generateId(t),n=n||{},this.options=new e(n,t),r.__super__.constructor.call(this);var i=t.attr("tabindex")||0;t.data("old-tabindex",i),t.attr("tabindex","-1");var o=this.options.get("dataAdapter");this.dataAdapter=new o(t,this.options);var a=this.render();this._placeContainer(a);var s=this.options.get("selectionAdapter");this.selection=new s(t,this.options),this.$selection=this.selection.render(),this.selection.position(this.$selection,a);var l=this.options.get("dropdownAdapter");this.dropdown=new l(t,this.options),this.$dropdown=this.dropdown.render(),this.dropdown.position(this.$dropdown,a);var u=this.options.get("resultsAdapter");this.results=new u(t,this.options,this.dataAdapter),this.$results=this.results.render(),this.results.position(this.$results,this.$dropdown);var c=this;this._bindAdapters(),this._registerDomEvents(),this._registerDataEvents(),this._registerSelectionEvents(), -this._registerDropdownEvents(),this._registerResultsEvents(),this._registerEvents(),this.dataAdapter.current(function(t){c.trigger("selection:update",{data:t})}),t.addClass("select2-hidden-accessible"),t.attr("aria-hidden","true"),this._syncAttributes(),t.data("select2",this)};return n.Extend(r,n.Observable),r.prototype._generateId=function(t){var e="";return e=null!=t.attr("id")?t.attr("id"):null!=t.attr("name")?t.attr("name")+"-"+n.generateChars(2):n.generateChars(4),e=e.replace(/(:|\.|\[|\]|,)/g,""),e="select2-"+e},r.prototype._placeContainer=function(t){t.insertAfter(this.$element);var e=this._resolveWidth(this.$element,this.options.get("width"));null!=e&&t.css("width",e)},r.prototype._resolveWidth=function(t,e){var n=/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i;if("resolve"==e){var i=this._resolveWidth(t,"style");return null!=i?i:this._resolveWidth(t,"element")}if("element"==e){var r=t.outerWidth(!1);return 0>=r?"auto":r+"px"}if("style"==e){var o=t.attr("style");if("string"!=typeof o)return null;for(var a=o.split(";"),s=0,l=a.length;l>s;s+=1){var u=a[s].replace(/\s/g,""),c=u.match(n);if(null!==c&&c.length>=1)return c[1]}return null}return e},r.prototype._bindAdapters=function(){this.dataAdapter.bind(this,this.$container),this.selection.bind(this,this.$container),this.dropdown.bind(this,this.$container),this.results.bind(this,this.$container)},r.prototype._registerDomEvents=function(){var e=this;this.$element.on("change.select2",function(){e.dataAdapter.current(function(t){e.trigger("selection:update",{data:t})})}),this.$element.on("focus.select2",function(t){e.trigger("focus",t)}),this._syncA=n.bind(this._syncAttributes,this),this._syncS=n.bind(this._syncSubtree,this),this.$element[0].attachEvent&&this.$element[0].attachEvent("onpropertychange",this._syncA);var i=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver;null!=i?(this._observer=new i(function(n){t.each(n,e._syncA),t.each(n,e._syncS)}),this._observer.observe(this.$element[0],{attributes:!0,childList:!0,subtree:!1})):this.$element[0].addEventListener&&(this.$element[0].addEventListener("DOMAttrModified",e._syncA,!1),this.$element[0].addEventListener("DOMNodeInserted",e._syncS,!1),this.$element[0].addEventListener("DOMNodeRemoved",e._syncS,!1))},r.prototype._registerDataEvents=function(){var t=this;this.dataAdapter.on("*",function(e,n){t.trigger(e,n)})},r.prototype._registerSelectionEvents=function(){var e=this,n=["toggle","focus"];this.selection.on("toggle",function(){e.toggleDropdown()}),this.selection.on("focus",function(t){e.focus(t)}),this.selection.on("*",function(i,r){-1===t.inArray(i,n)&&e.trigger(i,r)})},r.prototype._registerDropdownEvents=function(){var t=this;this.dropdown.on("*",function(e,n){t.trigger(e,n)})},r.prototype._registerResultsEvents=function(){var t=this;this.results.on("*",function(e,n){t.trigger(e,n)})},r.prototype._registerEvents=function(){var t=this;this.on("open",function(){t.$container.addClass("select2-container--open")}),this.on("close",function(){t.$container.removeClass("select2-container--open")}),this.on("enable",function(){t.$container.removeClass("select2-container--disabled")}),this.on("disable",function(){t.$container.addClass("select2-container--disabled")}),this.on("blur",function(){t.$container.removeClass("select2-container--focus")}),this.on("query",function(e){t.isOpen()||t.trigger("open",{}),this.dataAdapter.query(e,function(n){t.trigger("results:all",{data:n,query:e})})}),this.on("query:append",function(e){this.dataAdapter.query(e,function(n){t.trigger("results:append",{data:n,query:e})})}),this.on("keypress",function(e){var n=e.which;t.isOpen()?n===i.ESC||n===i.TAB||n===i.UP&&e.altKey?(t.close(),e.preventDefault()):n===i.ENTER?(t.trigger("results:select",{}),e.preventDefault()):n===i.SPACE&&e.ctrlKey?(t.trigger("results:toggle",{}),e.preventDefault()):n===i.UP?(t.trigger("results:previous",{}),e.preventDefault()):n===i.DOWN&&(t.trigger("results:next",{}),e.preventDefault()):(n===i.ENTER||n===i.SPACE||n===i.DOWN&&e.altKey)&&(t.open(),e.preventDefault())})},r.prototype._syncAttributes=function(){this.options.set("disabled",this.$element.prop("disabled")),this.options.get("disabled")?(this.isOpen()&&this.close(),this.trigger("disable",{})):this.trigger("enable",{})},r.prototype._syncSubtree=function(t,e){var n=!1,i=this;if(!t||!t.target||"OPTION"===t.target.nodeName||"OPTGROUP"===t.target.nodeName){if(e)if(e.addedNodes&&e.addedNodes.length>0)for(var r=0;r0&&(n=!0);else n=!0;n&&this.dataAdapter.current(function(t){i.trigger("selection:update",{data:t})})}},r.prototype.trigger=function(t,e){var n=r.__super__.trigger,i={open:"opening",close:"closing",select:"selecting",unselect:"unselecting"};if(void 0===e&&(e={}),t in i){var o=i[t],a={prevented:!1,name:t,args:e};if(n.call(this,o,a),a.prevented)return void(e.prevented=!0)}n.call(this,t,e)},r.prototype.toggleDropdown=function(){this.options.get("disabled")||(this.isOpen()?this.close():this.open())},r.prototype.open=function(){this.isOpen()||this.trigger("query",{})},r.prototype.close=function(){this.isOpen()&&this.trigger("close",{})},r.prototype.isOpen=function(){return this.$container.hasClass("select2-container--open")},r.prototype.hasFocus=function(){return this.$container.hasClass("select2-container--focus")},r.prototype.focus=function(t){this.hasFocus()||(this.$container.addClass("select2-container--focus"),this.trigger("focus",{}))},r.prototype.enable=function(t){this.options.get("debug")&&window.console&&console.warn&&console.warn('Select2: The `select2("enable")` method has been deprecated and will be removed in later Select2 versions. Use $element.prop("disabled") instead.'),(null==t||0===t.length)&&(t=[!0]);var e=!t[0];this.$element.prop("disabled",e)},r.prototype.data=function(){this.options.get("debug")&&arguments.length>0&&window.console&&console.warn&&console.warn('Select2: Data can no longer be set using `select2("data")`. You should consider setting the value instead using `$element.val()`.');var t=[];return this.dataAdapter.current(function(e){t=e}),t},r.prototype.val=function(e){if(this.options.get("debug")&&window.console&&console.warn&&console.warn('Select2: The `select2("val")` method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead.'),null==e||0===e.length)return this.$element.val();var n=e[0];t.isArray(n)&&(n=t.map(n,function(t){return t.toString()})),this.$element.val(n).trigger("change")},r.prototype.destroy=function(){this.$container.remove(),this.$element[0].detachEvent&&this.$element[0].detachEvent("onpropertychange",this._syncA),null!=this._observer?(this._observer.disconnect(),this._observer=null):this.$element[0].removeEventListener&&(this.$element[0].removeEventListener("DOMAttrModified",this._syncA,!1),this.$element[0].removeEventListener("DOMNodeInserted",this._syncS,!1),this.$element[0].removeEventListener("DOMNodeRemoved",this._syncS,!1)),this._syncA=null,this._syncS=null,this.$element.off(".select2"),this.$element.attr("tabindex",this.$element.data("old-tabindex")),this.$element.removeClass("select2-hidden-accessible"),this.$element.attr("aria-hidden","false"),this.$element.removeData("select2"),this.dataAdapter.destroy(),this.selection.destroy(),this.dropdown.destroy(),this.results.destroy(),this.dataAdapter=null,this.selection=null,this.dropdown=null,this.results=null},r.prototype.render=function(){var e=t('');return e.attr("dir",this.options.get("dir")),this.$container=e,this.$container.addClass("select2-container--"+this.options.get("theme")),e.data("element",this.$element),e},r}),e.define("jquery-mousewheel",["jquery"],function(t){return t}),e.define("jquery.select2",["jquery","jquery-mousewheel","./select2/core","./select2/defaults"],function(t,e,n,i){if(null==t.fn.select2){var r=["open","close","destroy"];t.fn.select2=function(e){if("object"==typeof(e=e||{}))return this.each(function(){var i=t.extend(!0,{},e);new n(t(this),i)}),this;if("string"==typeof e){var i,o=Array.prototype.slice.call(arguments,1);return this.each(function(){var n=t(this).data("select2");null==n&&window.console&&console.error&&console.error("The select2('"+e+"') method was called on an element that is not using Select2."),i=n[e].apply(n,o)}),t.inArray(e,r)>-1?this:i}throw new Error("Invalid arguments for Select2: "+e)}}return null==t.fn.select2.defaults&&(t.fn.select2.defaults=i),n}),{define:e.define,require:e.require}}(),n=e.require("jquery.select2");return t.fn.select2.amd=e,n}),function(t,e,n){"use strict";!function(t){function e(i){if(n[i])return n[i].exports;var r=n[i]={exports:{},id:i,loaded:!1};return t[i].call(r.exports,r,r.exports,e),r.loaded=!0,r.exports}var n={};e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){n(1),n(50),n(51),n(52),n(54),n(55),n(58),n(59),n(60),n(61),n(62),n(63),n(64),n(65),n(66),n(68),n(70),n(72),n(74),n(77),n(78),n(79),n(83),n(86),n(87),n(88),n(89),n(91),n(92),n(93),n(94),n(95),n(97),n(99),n(100),n(101),n(103),n(104),n(105),n(107),n(108),n(109),n(111),n(112),n(113),n(114),n(115),n(116),n(117),n(118),n(119),n(120),n(121),n(122),n(123),n(124),n(126),n(130),n(131),n(132),n(133),n(137),n(139),n(140),n(141),n(142),n(143),n(144),n(145),n(146),n(147),n(148),n(149),n(150),n(151),n(152),n(158),n(159),n(161),n(162),n(163),n(167),n(168),n(169),n(170),n(171),n(173),n(174),n(175),n(176),n(179),n(181),n(182),n(183),n(185),n(187),n(189),n(190),n(191),n(193),n(194),n(195),n(196),n(203),n(206),n(207),n(209),n(210),n(211),n(212),n(213),n(214),n(215),n(216),n(217),n(218),n(219),n(220),n(222),n(223),n(224),n(225),n(226),n(227),n(228),n(229),n(231),n(234),n(235),n(237),n(238),n(239),n(240),n(241),n(242),n(243),n(244),n(245),n(246),n(247),n(249),n(250),n(251),n(252),n(253),n(254),n(255),n(256),n(258),n(259),n(261),n(262),n(263),n(264),n(267),n(268),n(269),n(270),n(271),n(272),n(273),n(274),n(276),n(277),n(278),n(279),n(280),n(281),n(282),n(283),n(284),n(285),n(286),n(287),n(288),n(291),n(156),n(293),n(292),n(294),n(295),n(296),n(297),n(298),n(300),n(301),n(302),n(304),t.exports=n(305)},function(t,e,i){var r=i(2),o=i(3),a=i(4),s=i(6),l=i(16),u=i(20).KEY,c=i(5),h=i(21),d=i(22),f=i(17),p=i(23),g=i(24),m=i(25),v=i(27),y=i(40),b=i(43),x=i(10),w=i(30),S=i(14),_=i(15),k=i(44),C=i(47),M=i(49),T=i(9),D=i(28),A=M.f,P=T.f,E=C.f,O=r.Symbol,L=r.JSON,I=L&&L.stringify,N="prototype",F=p("_hidden"),R=p("toPrimitive"),j={}.propertyIsEnumerable,H=h("symbol-registry"),z=h("symbols"),B=h("op-symbols"),W=Object[N],$="function"==typeof O,q=r.QObject,U=!q||!q[N]||!q[N].findChild,Y=a&&c(function(){return 7!=k(P({},"a",{get:function(){return P(this,"a",{value:7}).a}})).a})?function(t,e,n){var i=A(W,e);i&&delete W[e],P(t,e,n),i&&t!==W&&P(W,e,i)}:P,G=function(t){var e=z[t]=k(O[N]);return e._k=t,e},X=$&&"symbol"==typeof O.iterator?function(t){return"symbol"==typeof t}:function(t){return t instanceof O},V=function(t,e,n){return t===W&&V(B,e,n),x(t),e=S(e,!0),x(n),o(z,e)?(n.enumerable?(o(t,F)&&t[F][e]&&(t[F][e]=!1),n=k(n,{enumerable:_(0,!1)})):(o(t,F)||P(t,F,_(1,{})),t[F][e]=!0),Y(t,e,n)):P(t,e,n)},Z=function(t,e){x(t);for(var n,i=y(e=w(e)),r=0,o=i.length;o>r;)V(t,n=i[r++],e[n]);return t},K=function(t,e){return e===n?k(t):Z(k(t),e)},J=function(t){var e=j.call(this,t=S(t,!0));return!(this===W&&o(z,t)&&!o(B,t))&&(!(e||!o(this,t)||!o(z,t)||o(this,F)&&this[F][t])||e)},Q=function(t,e){if(t=w(t),e=S(e,!0),t!==W||!o(z,e)||o(B,e)){var n=A(t,e);return!n||!o(z,e)||o(t,F)&&t[F][e]||(n.enumerable=!0),n}},tt=function(t){for(var e,n=E(w(t)),i=[],r=0;n.length>r;)o(z,e=n[r++])||e==F||e==u||i.push(e);return i},et=function(t){for(var e,n=t===W,i=E(n?B:w(t)),r=[],a=0;i.length>a;)!o(z,e=i[a++])||n&&!o(W,e)||r.push(z[e]);return r};$||(O=function(){if(this instanceof O)throw TypeError("Symbol is not a constructor!");var t=f(arguments.length>0?arguments[0]:n),e=function(n){this===W&&e.call(B,n),o(this,F)&&o(this[F],t)&&(this[F][t]=!1),Y(this,t,_(1,n))};return a&&U&&Y(W,t,{configurable:!0,set:e}),G(t)},l(O[N],"toString",function(){return this._k}),M.f=Q,T.f=V,i(48).f=C.f=tt,i(42).f=J,i(41).f=et,a&&!i(26)&&l(W,"propertyIsEnumerable",J,!0),g.f=function(t){return G(p(t))}),s(s.G+s.W+s.F*!$,{Symbol:O});for(var nt="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),it=0;nt.length>it;)p(nt[it++]);for(var nt=D(p.store),it=0;nt.length>it;)m(nt[it++]);s(s.S+s.F*!$,"Symbol",{for:function(t){return o(H,t+="")?H[t]:H[t]=O(t)},keyFor:function(t){if(X(t))return v(H,t);throw TypeError(t+" is not a symbol!")},useSetter:function(){U=!0},useSimple:function(){U=!1}}),s(s.S+s.F*!$,"Object",{create:K,defineProperty:V,defineProperties:Z,getOwnPropertyDescriptor:Q,getOwnPropertyNames:tt,getOwnPropertySymbols:et}),L&&s(s.S+s.F*(!$||c(function(){var t=O();return"[null]"!=I([t])||"{}"!=I({a:t})||"{}"!=I(Object(t))})),"JSON",{stringify:function(t){if(t!==n&&!X(t)){for(var e,i,r=[t],o=1;arguments.length>o;)r.push(arguments[o++]);return e=r[1],"function"==typeof e&&(i=e),!i&&b(e)||(e=function(t,e){if(i&&(e=i.call(this,t,e)),!X(e))return e}),r[1]=e,I.apply(L,r)}}}),O[N][R]||i(8)(O[N],R,O[N].valueOf),d(O,"Symbol"),d(Math,"Math",!0),d(r.JSON,"JSON",!0)},function(t,n){var i=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof e&&(e=i)},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){t.exports=!n(5)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e,i){var r=i(2),o=i(7),a=i(8),s=i(16),l=i(18),u="prototype",c=function(t,e,i){var h,d,f,p,g=t&c.F,m=t&c.G,v=t&c.S,y=t&c.P,b=t&c.B,x=m?r:v?r[e]||(r[e]={}):(r[e]||{})[u],w=m?o:o[e]||(o[e]={}),S=w[u]||(w[u]={});m&&(i=e);for(h in i)d=!g&&x&&x[h]!==n,f=(d?x:i)[h],p=b&&d?l(f,r):y&&"function"==typeof f?l(Function.call,f):f,x&&s(x,h,f,t&c.U),w[h]!=f&&a(w,h,p),y&&S[h]!=f&&(S[h]=f)};r.core=o,c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,t.exports=c},function(e,n){var i=e.exports={version:"2.4.0"};"number"==typeof t&&(t=i)},function(t,e,n){var i=n(9),r=n(15);t.exports=n(4)?function(t,e,n){return i.f(t,e,r(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e,n){var i=n(10),r=n(12),o=n(14),a=Object.defineProperty;e.f=n(4)?Object.defineProperty:function(t,e,n){if(i(t),e=o(e,!0),i(n),r)try{return a(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e,n){var i=n(11);t.exports=function(t){if(!i(t))throw TypeError(t+" is not an object!");return t}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,n){t.exports=!n(4)&&!n(5)(function(){return 7!=Object.defineProperty(n(13)("div"),"a",{get:function(){return 7}}).a})},function(t,e,n){var i=n(11),r=n(2).document,o=i(r)&&i(r.createElement);t.exports=function(t){return o?r.createElement(t):{}}},function(t,e,n){var i=n(11);t.exports=function(t,e){if(!i(t))return t;var n,r;if(e&&"function"==typeof(n=t.toString)&&!i(r=n.call(t)))return r;if("function"==typeof(n=t.valueOf)&&!i(r=n.call(t)))return r;if(!e&&"function"==typeof(n=t.toString)&&!i(r=n.call(t)))return r;throw TypeError("Can't convert object to primitive value")}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,n){var i=n(2),r=n(8),o=n(3),a=n(17)("src"),s="toString",l=Function[s],u=(""+l).split(s);n(7).inspectSource=function(t){return l.call(t)},(t.exports=function(t,e,n,s){var l="function"==typeof n;l&&(o(n,"name")||r(n,"name",e)),t[e]!==n&&(l&&(o(n,a)||r(n,a,t[e]?""+t[e]:u.join(String(e)))),t===i?t[e]=n:s?t[e]?t[e]=n:r(t,e,n):(delete t[e],r(t,e,n)))})(Function.prototype,s,function(){return"function"==typeof this&&this[a]||l.call(this)})},function(t,e){var i=0,r=Math.random();t.exports=function(t){return"Symbol(".concat(t===n?"":t,")_",(++i+r).toString(36))}},function(t,e,i){var r=i(19);t.exports=function(t,e,i){if(r(t),e===n)return t;switch(i){case 1:return function(n){return t.call(e,n)};case 2:return function(n,i){return t.call(e,n,i)};case 3:return function(n,i,r){return t.call(e,n,i,r)}}return function(){return t.apply(e,arguments)}}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e,n){var i=n(17)("meta"),r=n(11),o=n(3),a=n(9).f,s=0,l=Object.isExtensible||function(){return!0},u=!n(5)(function(){return l(Object.preventExtensions({}))}),c=function(t){a(t,i,{value:{i:"O"+ ++s,w:{}}})},h=function(t,e){if(!r(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!o(t,i)){if(!l(t))return"F";if(!e)return"E";c(t)}return t[i].i},d=function(t,e){if(!o(t,i)){if(!l(t))return!0;if(!e)return!1;c(t)}return t[i].w},f=function(t){return u&&p.NEED&&l(t)&&!o(t,i)&&c(t),t},p=t.exports={KEY:i,NEED:!1,fastKey:h,getWeak:d,onFreeze:f}},function(t,e,n){var i=n(2),r="__core-js_shared__",o=i[r]||(i[r]={});t.exports=function(t){return o[t]||(o[t]={})}},function(t,e,n){var i=n(9).f,r=n(3),o=n(23)("toStringTag");t.exports=function(t,e,n){t&&!r(t=n?t:t.prototype,o)&&i(t,o,{configurable:!0,value:e})}},function(t,e,n){var i=n(21)("wks"),r=n(17),o=n(2).Symbol,a="function"==typeof o;(t.exports=function(t){return i[t]||(i[t]=a&&o[t]||(a?o:r)("Symbol."+t))}).store=i},function(t,e,n){e.f=n(23)},function(t,e,n){var i=n(2),r=n(7),o=n(26),a=n(24),s=n(9).f;t.exports=function(t){var e=r.Symbol||(r.Symbol=o?{}:i.Symbol||{});"_"==t.charAt(0)||t in e||s(e,t,{value:a.f(t)})}},function(t,e){t.exports=!1},function(t,e,n){var i=n(28),r=n(30);t.exports=function(t,e){for(var n,o=r(t),a=i(o),s=a.length,l=0;s>l;)if(o[n=a[l++]]===e)return n}},function(t,e,n){var i=n(29),r=n(39);t.exports=Object.keys||function(t){return i(t,r)}},function(t,e,n){var i=n(3),r=n(30),o=n(34)(!1),a=n(38)("IE_PROTO");t.exports=function(t,e){var n,s=r(t),l=0,u=[];for(n in s)n!=a&&i(s,n)&&u.push(n);for(;e.length>l;)i(s,n=e[l++])&&(~o(u,n)||u.push(n));return u}},function(t,e,n){var i=n(31),r=n(33);t.exports=function(t){return i(r(t))}},function(t,e,n){var i=n(32);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==i(t)?t.split(""):Object(t)}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e){t.exports=function(t){if(t==n)throw TypeError("Can't call method on "+t);return t}},function(t,e,n){var i=n(30),r=n(35),o=n(37);t.exports=function(t){return function(e,n,a){var s,l=i(e),u=r(l.length),c=o(a,u);if(t&&n!=n){for(;u>c;)if((s=l[c++])!=s)return!0}else for(;u>c;c++)if((t||c in l)&&l[c]===n)return t||c||0;return!t&&-1}}},function(t,e,n){var i=n(36),r=Math.min;t.exports=function(t){return t>0?r(i(t),9007199254740991):0}},function(t,e){var n=Math.ceil,i=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?i:n)(t)}},function(t,e,n){var i=n(36),r=Math.max,o=Math.min;t.exports=function(t,e){return t=i(t),t<0?r(t+e,0):o(t,e)}},function(t,e,n){var i=n(21)("keys"),r=n(17);t.exports=function(t){return i[t]||(i[t]=r(t))}},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e,n){var i=n(28),r=n(41),o=n(42);t.exports=function(t){var e=i(t),n=r.f;if(n)for(var a,s=n(t),l=o.f,u=0;s.length>u;)l.call(t,a=s[u++])&&e.push(a);return e}},function(t,e){e.f=Object.getOwnPropertySymbols},function(t,e){e.f={}.propertyIsEnumerable},function(t,e,n){var i=n(32);t.exports=Array.isArray||function(t){return"Array"==i(t)}},function(t,e,i){var r=i(10),o=i(45),a=i(39),s=i(38)("IE_PROTO"),l=function(){},u="prototype",c=function(){var t,e=i(13)("iframe"),n=a.length;for(e.style.display="none",i(46).appendChild(e),e.src="javascript:",t=e.contentWindow.document,t.open(),t.write(" +{{end}} \ No newline at end of file diff --git a/templates/nav.html b/templates/nav.html index 09af8982..728a8f7e 100644 --- a/templates/nav.html +++ b/templates/nav.html @@ -10,7 +10,7 @@ Campaigns
      • - Users & Groups + Users & Groups
      • Email Templates
      • @@ -21,8 +21,13 @@ Sending Profiles
      • - Settings Admin + Account Settings
      • + {{if .ModifySystem}} +
      • + User ManagementAdmin +
      • + {{end}}

      • diff --git a/templates/register.html b/templates/register.html deleted file mode 100644 index 518aec09..00000000 --- a/templates/register.html +++ /dev/null @@ -1,62 +0,0 @@ -{{ define "base" }} - - - - - - - - - - - - Gophish - {{ .Title }} - - - - - - - -
        - - - - {{template "flashes" .Flashes}} - - - - - - -
        - - - - - -{{ end }} \ No newline at end of file diff --git a/templates/settings.html b/templates/settings.html index b08842f4..eeac2c24 100644 --- a/templates/settings.html +++ b/templates/settings.html @@ -8,7 +8,8 @@
        @@ -22,19 +23,12 @@

        -
        - - -
        -
        {{end}}
        - +
        @@ -46,26 +40,30 @@
        - +

        - +

        - +

        - +
        diff --git a/templates/users.html b/templates/users.html index adbcad01..0f5736ef 100644 --- a/templates/users.html +++ b/templates/users.html @@ -2,31 +2,25 @@

        - Users & Groups + {{.Title}}

        - +
         
        -
        -
        ").addClass("cw").text("#"));n.isBefore(o.clone().endOf("w"));)e.append(t("").addClass("dow").text(n.format("dd"))),n.add(1,"d");p.find(".datepicker-days thead").append(e)},R=function(t){return!0===i.disabledDates[t.format("YYYY-MM-DD")]},j=function(t){return!0===i.enabledDates[t.format("YYYY-MM-DD")]},H=function(t){return!0===i.disabledHours[t.format("H")]},z=function(t){return!0===i.enabledHours[t.format("H")]},B=function(e,n){if(!e.isValid())return!1;if(i.disabledDates&&"d"===n&&R(e))return!1;if(i.enabledDates&&"d"===n&&!j(e))return!1;if(i.minDate&&e.isBefore(i.minDate,n))return!1;if(i.maxDate&&e.isAfter(i.maxDate,n))return!1;if(i.daysOfWeekDisabled&&"d"===n&&-1!==i.daysOfWeekDisabled.indexOf(e.day()))return!1;if(i.disabledHours&&("h"===n||"m"===n||"s"===n)&&H(e))return!1;if(i.enabledHours&&("h"===n||"m"===n||"s"===n)&&!z(e))return!1;if(i.disabledTimeIntervals&&("h"===n||"m"===n||"s"===n)){var r=!1;if(t.each(i.disabledTimeIntervals,function(){if(e.isBetween(this[0],this[1]))return r=!0,!1}),r)return!1}return!0},W=function(){for(var e=[],n=o.clone().startOf("y").startOf("d");n.isSame(o,"y");)e.push(t("").attr("data-action","selectMonth").addClass("month").text(n.format("MMM"))),n.add(1,"M");p.find(".datepicker-months td").empty().append(e)},$=function(){var e=p.find(".datepicker-months"),n=e.find("th"),a=e.find("tbody").find("span");n.eq(0).find("span").attr("title",i.tooltips.prevYear),n.eq(1).attr("title",i.tooltips.selectYear),n.eq(2).find("span").attr("title",i.tooltips.nextYear),e.find(".disabled").removeClass("disabled"),B(o.clone().subtract(1,"y"),"y")||n.eq(0).addClass("disabled"),n.eq(1).text(o.year()),B(o.clone().add(1,"y"),"y")||n.eq(2).addClass("disabled"),a.removeClass("active"),r.isSame(o,"y")&&!d&&a.eq(r.month()).addClass("active"),a.each(function(e){B(o.clone().month(e),"M")||t(this).addClass("disabled")})},q=function(){var t=p.find(".datepicker-years"),e=t.find("th"),n=o.clone().subtract(5,"y"),a=o.clone().add(6,"y"),s="";for(e.eq(0).find("span").attr("title",i.tooltips.prevDecade),e.eq(1).attr("title",i.tooltips.selectDecade),e.eq(2).find("span").attr("title",i.tooltips.nextDecade),t.find(".disabled").removeClass("disabled"),i.minDate&&i.minDate.isAfter(n,"y")&&e.eq(0).addClass("disabled"),e.eq(1).text(n.year()+"-"+a.year()),i.maxDate&&i.maxDate.isBefore(a,"y")&&e.eq(2).addClass("disabled");!n.isAfter(a,"y");)s+=''+n.year()+"",n.add(1,"y");t.find("td").html(s)},U=function(){var t=p.find(".datepicker-decades"),n=t.find("th"),a=e({y:o.year()-o.year()%100-1}),s=a.clone().add(100,"y"),l=a.clone(),u="";for(n.eq(0).find("span").attr("title",i.tooltips.prevCentury),n.eq(2).find("span").attr("title",i.tooltips.nextCentury),t.find(".disabled").removeClass("disabled"),(a.isSame(e({y:1900}))||i.minDate&&i.minDate.isAfter(a,"y"))&&n.eq(0).addClass("disabled"),n.eq(1).text(a.year()+"-"+s.year()),(a.isSame(e({y:2e3}))||i.maxDate&&i.maxDate.isBefore(s,"y"))&&n.eq(2).addClass("disabled");!a.isAfter(s,"y");)u+=''+(a.year()+1)+" - "+(a.year()+12)+"",a.add(12,"y");u+="",t.find("td").html(u),n.eq(1).text(l.year()+1+"-"+a.year())},Y=function(){var e,n,a,s,l=p.find(".datepicker-days"),u=l.find("th"),c=[];if(M()){for(u.eq(0).find("span").attr("title",i.tooltips.prevMonth),u.eq(1).attr("title",i.tooltips.selectMonth),u.eq(2).find("span").attr("title",i.tooltips.nextMonth),l.find(".disabled").removeClass("disabled"),u.eq(1).text(o.format(i.dayViewHeaderFormat)),B(o.clone().subtract(1,"M"),"M")||u.eq(0).addClass("disabled"),B(o.clone().add(1,"M"),"M")||u.eq(2).addClass("disabled"),e=o.clone().startOf("M").startOf("w").startOf("d"),s=0;s<42;s++)0===e.weekday()&&(n=t("
        '+e.week()+"'+e.date()+"
        '+n.format(s?"HH":"hh")+"
        '+n.format("mm")+"
        '+n.format("ss")+"
        + - - - + + @@ -43,56 +37,30 @@ - + - - - - - - - - - - -
        First NameLast NameEmailPosition
        "]).draw()})}else $("#emptyMessage").show()}).error(function(){errorFlash("Error fetching groups")})}$(document).ready(function(){load(),$("#targetForm").submit(function(){return addTarget($("#firstName").val(),$("#lastName").val(),$("#email").val(),$("#position").val()),targets.DataTable().draw(),$("#targetForm>div>input").val(""),$("#firstName").focus(),!1}),$("#targetsTable").on("click","span>i.fa-trash-o",function(){targets.DataTable().row($(this).parents("tr")).remove().draw()}),$("#modal").on("hide.bs.modal",function(){dismiss()}),$("#csv-template").click(downloadCSVTemplate)}); \ No newline at end of file +var groups=[];function save(e){var t=[];$.each($("#targetsTable").DataTable().rows().data(),function(e,a){t.push({first_name:unescapeHtml(a[0]),last_name:unescapeHtml(a[1]),email:unescapeHtml(a[2]),position:unescapeHtml(a[3])})});var a={name:$("#name").val(),targets:t};-1!=e?(a.id=e,api.groupId.put(a).success(function(e){successFlash("Group updated successfully!"),load(),dismiss(),$("#modal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)})):api.groups.post(a).success(function(e){successFlash("Group added successfully!"),load(),dismiss(),$("#modal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)})}function dismiss(){$("#targetsTable").dataTable().DataTable().clear().draw(),$("#name").val(""),$("#modal\\.flashes").empty()}function edit(e){if(targets=$("#targetsTable").dataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]}),$("#modalSubmit").unbind("click").click(function(){save(e)}),-1==e);else api.groupId.get(e).success(function(e){$("#name").val(e.name),$.each(e.targets,function(e,a){targets.DataTable().row.add([escapeHtml(a.first_name),escapeHtml(a.last_name),escapeHtml(a.email),escapeHtml(a.position),'']).draw()})}).error(function(){errorFlash("Error fetching group")});$("#csvupload").fileupload({url:"/api/import/group",dataType:"json",beforeSend:function(e){e.setRequestHeader("Authorization","Bearer "+user.api_key)},add:function(e,a){$("#modal\\.flashes").empty();var t=a.originalFiles[0].name;if(t&&!/(csv|txt)$/i.test(t.split(".").pop()))return modalError("Unsupported file extension (use .csv or .txt)"),!1;a.submit()},done:function(e,a){$.each(a.result,function(e,a){addTarget(a.first_name,a.last_name,a.email,a.position)}),targets.DataTable().draw()}})}var downloadCSVTemplate=function(){var e="group_template.csv",a=Papa.unparse([{"First Name":"Example","Last Name":"User",Email:"foobar@example.com",Position:"Systems Administrator"}],{}),t=new Blob([a],{type:"text/csv;charset=utf-8;"});if(navigator.msSaveBlob)navigator.msSaveBlob(t,e);else{var s=window.URL.createObjectURL(t),o=document.createElement("a");o.href=s,o.setAttribute("download",e),document.body.appendChild(o),o.click(),document.body.removeChild(o)}},deleteGroup=function(s){var e=groups.find(function(e){return e.id===s});e&&swal({title:"Are you sure?",text:"This will delete the group. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(e.name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.groupId.delete(s).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Group Deleted!","This group has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};function addTarget(e,a,t,s){var o=escapeHtml(t).toLowerCase(),r=[escapeHtml(e),escapeHtml(a),o,escapeHtml(s),''],n=targets.DataTable(),i=n.column(2,{order:"index"}).data().indexOf(o);0<=i?n.row(i,{order:"index"}).data(r):n.row.add(r)}function load(){$("#groupTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.groups.summary().success(function(e){if($("#loading").hide(),0 "]).draw()})}else $("#emptyMessage").show()}).error(function(){errorFlash("Error fetching groups")})}$(document).ready(function(){load(),$("#targetForm").submit(function(){var e=document.getElementById("targetForm");if(e.checkValidity())return addTarget($("#firstName").val(),$("#lastName").val(),$("#email").val(),$("#position").val()),targets.DataTable().draw(),$("#targetForm>div>input").val(""),$("#firstName").focus(),!1;e.reportValidity()}),$("#targetsTable").on("click","span>i.fa-trash-o",function(){targets.DataTable().row($(this).parents("tr")).remove().draw()}),$("#modal").on("hide.bs.modal",function(){dismiss()}),$("#csv-template").click(downloadCSVTemplate)}); \ No newline at end of file diff --git a/static/js/src/app/groups.js b/static/js/src/app/groups.js index 02a2b890..30181d81 100644 --- a/static/js/src/app/groups.js +++ b/static/js/src/app/groups.js @@ -258,6 +258,12 @@ $(document).ready(function () { // Setup the event listeners // Handle manual additions $("#targetForm").submit(function () { + // Validate the form data + var targetForm = document.getElementById("targetForm") + if (!targetForm.checkValidity()) { + targetForm.reportValidity() + return + } addTarget( $("#firstName").val(), $("#lastName").val(), From 26d99b5a653da4fc5c59d04b262d59aab35c32c9 Mon Sep 17 00:00:00 2001 From: Christian Schwartz Date: Tue, 4 Jun 2019 05:04:54 +0200 Subject: [PATCH 13/27] Add support for encrypted connections to mysql (#1460) --- config/config.go | 1 + models/models.go | 29 ++++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/config/config.go b/config/config.go index ba81e2f1..ccb6d639 100644 --- a/config/config.go +++ b/config/config.go @@ -32,6 +32,7 @@ type Config struct { PhishConf PhishServer `json:"phish_server"` DBName string `json:"db_name"` DBPath string `json:"db_path"` + DBSSLCaPath string `json:"db_sslca_path"` MigrationsPath string `json:"migrations_prefix"` TestFlag bool `json:"test_flag"` ContactAddress string `json:"contact_address"` diff --git a/models/models.go b/models/models.go index 1ef38a47..e929af02 100644 --- a/models/models.go +++ b/models/models.go @@ -5,10 +5,13 @@ import ( "fmt" "io" "time" + "crypto/tls" + "crypto/x509" + "io/ioutil" "bitbucket.org/liamstask/goose/lib/goose" - _ "github.com/go-sql-driver/mysql" // Blank import needed to import mysql + mysql "github.com/go-sql-driver/mysql" "github.com/gophish/gophish/config" log "github.com/gophish/gophish/logger" "github.com/jinzhu/gorm" @@ -96,6 +99,30 @@ func Setup(c *config.Config) error { log.Error(err) return err } + + // Register certificates for tls encrypted db connections + if conf.DBSSLCaPath != "" { + switch conf.DBName { + case "mysql": + rootCertPool := x509.NewCertPool() + pem, err := ioutil.ReadFile(conf.DBSSLCaPath) + if err != nil { + log.Error(err) + return err + } + if ok := rootCertPool.AppendCertsFromPEM(pem); !ok { + log.Error("Failed to append PEM.") + return err + } + mysql.RegisterTLSConfig("ssl_ca", &tls.Config{ + RootCAs: rootCertPool, + }) + // Default database is sqlite3, which supports no tls, as connection + // is file based + default: + } + } + // Open our database connection i := 0 for { From d30e9e2e2fdd1e3cc63d3b0589f5bf45b7e2fb6f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 18 Jul 2019 23:29:10 -0500 Subject: [PATCH 14/27] Bump lodash.merge from 4.6.1 to 4.6.2 (#1508) Bumps [lodash.merge](https://github.com/lodash/lodash) from 4.6.1 to 4.6.2. - [Release notes](https://github.com/lodash/lodash/releases) - [Commits](https://github.com/lodash/lodash/commits) Signed-off-by: dependabot[bot] --- yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/yarn.lock b/yarn.lock index ced1b618..1da22d7c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3107,9 +3107,9 @@ lodash.isobject@^3.0.2: integrity sha1-PI+41bW/S/kK4G4U8qUwpO2TXh0= lodash.merge@^4.6.0: - version "4.6.1" - resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.1.tgz#adc25d9cb99b9391c59624f379fbba60d7111d54" - integrity sha512-AOYza4+Hf5z1/0Hztxpm2/xiPZgi/cjMqdnKTUWTBSKchJlxXXuUSxCCl8rJlf4g6yww/j6mA8nC8Hw/EZWxKQ== + version "4.6.2" + resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.2.tgz#558aa53b43b661e1925a0afdfa36a9a1085fe57a" + integrity sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ== lodash@^4.12.0, lodash@^4.17.11, lodash@~4.17.11: version "4.17.11" From 1f16c7237d0d967b2acc40934e5a25741be234fd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 18 Jul 2019 23:29:45 -0500 Subject: [PATCH 15/27] Bump lodash from 4.17.11 to 4.17.14 (#1507) Bumps [lodash](https://github.com/lodash/lodash) from 4.17.11 to 4.17.14. - [Release notes](https://github.com/lodash/lodash/releases) - [Commits](https://github.com/lodash/lodash/compare/4.17.11...4.17.14) Signed-off-by: dependabot[bot] --- yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/yarn.lock b/yarn.lock index 1da22d7c..77516b79 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3112,9 +3112,9 @@ lodash.merge@^4.6.0: integrity sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ== lodash@^4.12.0, lodash@^4.17.11, lodash@~4.17.11: - version "4.17.11" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.11.tgz#b39ea6229ef607ecd89e2c8df12536891cac9b8d" - integrity sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg== + version "4.17.14" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.14.tgz#9ce487ae66c96254fe20b599f21b6816028078ba" + integrity sha512-mmKYbW3GLuJeX+iGP+Y7Gp1AiGHGbXHCOh/jZmrawMmsE7MS4znI3RL2FsjbqOyMayHInjOeykW7PEajUk1/xw== log-symbols@^1.0.0: version "1.0.2" From f95e9554c7cefd8bd0e772af8a19436090311e8c Mon Sep 17 00:00:00 2001 From: Jordan Wright Date: Sat, 3 Aug 2019 20:55:25 -0500 Subject: [PATCH 16/27] Add CORS support for Reporting Handler (#1529) * Added response headers for CORS and server identification (#1517) Co-Authored-By: Glenn Wilkinson --- controllers/phish.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/controllers/phish.go b/controllers/phish.go index a41708bc..bb084c15 100644 --- a/controllers/phish.go +++ b/controllers/phish.go @@ -161,6 +161,7 @@ func (ps *PhishingServer) TrackHandler(w http.ResponseWriter, r *http.Request) { // ReportHandler tracks emails as they are reported, updating the status for the given Result func (ps *PhishingServer) ReportHandler(w http.ResponseWriter, r *http.Request) { r, err := setupContext(r) + w.Header().Set("Access-Control-Allow-Origin", "*") // To allow Chrome extensions (or other pages) to report a campaign without violating CORS if err != nil { // Log the error if it wasn't something we can safely ignore if err != ErrInvalidRequest && err != ErrCampaignComplete { @@ -203,6 +204,7 @@ func (ps *PhishingServer) PhishHandler(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } + w.Header().Set("X-Server", config.ServerName) // Useful for checking if this is a GoPhish server (e.g. for campaign reporting plugins) var ptx models.PhishingTemplateContext // Check for a preview if preview, ok := ctx.Get(r, "result").(models.EmailRequest); ok { From 24fe998a3aa04e205900476a9601d481e94d8eea Mon Sep 17 00:00:00 2001 From: David Maciejak Date: Sat, 24 Aug 2019 10:07:15 +0800 Subject: [PATCH 17/27] Fix multiple XSS issues in User Management Page (#1547) If the user name is embedding some JS code, it will be executed on the client side. Note: gophish/static/js/dist/app/users.min.js will need to be regenerated too. --- static/js/src/app/users.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/static/js/src/app/users.js b/static/js/src/app/users.js index 81db6697..a53c9b89 100644 --- a/static/js/src/app/users.js +++ b/static/js/src/app/users.js @@ -19,7 +19,7 @@ const save = (id) => { user.id = id api.userId.put(user) .success(function (data) { - successFlash(`User ${user.username} updated successfully!`) + successFlash("User " + escapeHtml(user.username) + " updated successfully!") load() dismiss() $("#modal").modal('hide') @@ -32,7 +32,7 @@ const save = (id) => { // to /user api.users.post(user) .success(function (data) { - successFlash(`User ${user.username} registered successfully!`) + successFlash("User " + escapeHtml(user.username) + " registered successfully!") load() dismiss() $("#modal").modal('hide') @@ -79,7 +79,7 @@ const deleteUser = (id) => { } swal({ title: "Are you sure?", - text: `This will delete the account for ${user.username} as well as all of the objects they have created.\n\nThis can't be undone!`, + text: "This will delete the account for " + escapeHtml(user.username) + " as well as all of the objects they have created.\n\nThis can't be undone!", type: "warning", animation: false, showCancelButton: true, @@ -101,7 +101,7 @@ const deleteUser = (id) => { }).then(function () { swal( 'User Deleted!', - `The user account for ${user.username} and all associated objects have been deleted!`, + "The user account for " + escapeHtml(user.username) + " and all associated objects have been deleted!", 'success' ); $('button:contains("OK")').on('click', function () { @@ -175,4 +175,4 @@ $(document).ready(function () { $("#userTable").on('click', '.delete_button', function (e) { deleteUser($(this).attr('data-user-id')) }) -}); \ No newline at end of file +}); From 20295bd96a1a9231c5badc1cdbe290b03f4f0cb0 Mon Sep 17 00:00:00 2001 From: David Maciejak Date: Thu, 29 Aug 2019 20:36:04 +0800 Subject: [PATCH 18/27] Remove the Top Navigation Menu MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The top navigation menu is redundant to the sidebar. We’re opting to remove it so that we are free to update the sidebar to be more complex over time. --- templates/base.html | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/templates/base.html b/templates/base.html index 7956e6e5..176caaa3 100644 --- a/templates/base.html +++ b/templates/base.html @@ -43,20 +43,6 @@ "]).draw()}),$('[data-toggle="tooltip"]').tooltip()):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching pages")})}$(document).ready(function(){$(".modal").on("hidden.bs.modal",function(e){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(e){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$.fn.modal.Constructor.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(e){this.$element[0]===e.target||this.$element.has(e.target).length||$(e.target).closest(".cke_dialog, .cke").length||this.$element.trigger("focus")},this))},$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(e){dismiss()}),$("#capture_credentials_checkbox").change(function(){$("#capture_passwords").toggle(),$("#redirect_url").toggle()}),CKEDITOR.on("dialogDefinition",function(e){var a=e.data.name,t=e.data.definition;"link"==a&&(t.minWidth=500,t.minHeight=100,t.getContents("info").get("linkType").hidden=!0)}),load()}); \ No newline at end of file diff --git a/static/js/dist/app/sending_profiles.min.js b/static/js/dist/app/sending_profiles.min.js index 85f9dd7b..1bc4b7db 100644 --- a/static/js/dist/app/sending_profiles.min.js +++ b/static/js/dist/app/sending_profiles.min.js @@ -1 +1 @@ -var profiles=[];function sendTestEmail(){var t=[];$.each($("#headersTable").DataTable().rows().data(),function(e,a){t.push({key:unescapeHtml(a[0]),value:unescapeHtml(a[1])})});var e={template:{},first_name:$("input[name=to_first_name]").val(),last_name:$("input[name=to_last_name]").val(),email:$("input[name=to_email]").val(),position:$("input[name=to_position]").val(),url:"",smtp:{from_address:$("#from").val(),host:$("#host").val(),username:$("#username").val(),password:$("#password").val(),ignore_cert_errors:$("#ignore_cert_errors").prop("checked"),headers:t}};btnHtml=$("#sendTestModalSubmit").html(),$("#sendTestModalSubmit").html(' Sending'),api.send_test_email(e).success(function(e){$("#sendTestEmailModal\\.flashes").empty().append('
        \t Email Sent!
        '),$("#sendTestModalSubmit").html(btnHtml)}).error(function(e){$("#sendTestEmailModal\\.flashes").empty().append('
        \t '+e.responseJSON.message+"
        "),$("#sendTestModalSubmit").html(btnHtml)})}function save(e){var t={headers:[]};$.each($("#headersTable").DataTable().rows().data(),function(e,a){t.headers.push({key:unescapeHtml(a[0]),value:unescapeHtml(a[1])})}),t.name=$("#name").val(),t.interface_type=$("#interface_type").val(),t.from_address=$("#from").val(),t.host=$("#host").val(),t.username=$("#username").val(),t.password=$("#password").val(),t.ignore_cert_errors=$("#ignore_cert_errors").prop("checked"),-1!=e?(t.id=profiles[e].id,api.SMTPId.put(t).success(function(e){successFlash("Profile edited successfully!"),load(),dismiss()}).error(function(e){modalError(e.responseJSON.message)})):api.SMTP.post(t).success(function(e){successFlash("Profile added successfully!"),load(),dismiss()}).error(function(e){modalError(e.responseJSON.message)})}function dismiss(){$("#modal\\.flashes").empty(),$("#name").val(""),$("#interface_type").val("SMTP"),$("#from").val(""),$("#host").val(""),$("#username").val(""),$("#password").val(""),$("#ignore_cert_errors").prop("checked",!0),$("#headersTable").dataTable().DataTable().clear().draw(),$("#modal").modal("hide")}var dismissSendTestEmailModal=function(){$("#sendTestEmailModal\\.flashes").empty(),$("#sendTestModalSubmit").html(" Send")},deleteProfile=function(e){swal({title:"Are you sure?",text:"This will delete the sending profile. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(profiles[e].name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.SMTPId.delete(profiles[e].id).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(){swal("Sending Profile Deleted!","This sending profile has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};function edit(e){headers=$("#headersTable").dataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]}),$("#modalSubmit").unbind("click").click(function(){save(e)});var a={};-1!=e&&(a=profiles[e],$("#name").val(a.name),$("#interface_type").val(a.interface_type),$("#from").val(a.from_address),$("#host").val(a.host),$("#username").val(a.username),$("#password").val(a.password),$("#ignore_cert_errors").prop("checked",a.ignore_cert_errors),$.each(a.headers,function(e,a){addCustomHeader(a.key,a.value)}))}function copy(e){$("#modalSubmit").unbind("click").click(function(){save(-1)});var a;a=profiles[e],$("#name").val("Copy of "+a.name),$("#interface_type").val(a.interface_type),$("#from").val(a.from_address),$("#host").val(a.host),$("#username").val(a.username),$("#password").val(a.password),$("#ignore_cert_errors").prop("checked",a.ignore_cert_errors)}function load(){$("#profileTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.SMTP.get().success(function(e){profiles=e,$("#loading").hide(),0\t\t "]).draw()}),$('[data-toggle="tooltip"]').tooltip()):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching profiles")})}function addCustomHeader(e,a){var t=[escapeHtml(e),escapeHtml(a),''],s=headers.DataTable(),o=s.column(0).data().indexOf(escapeHtml(e));0<=o?s.row(o,{order:"index"}).data(t):s.row.add(t),s.draw()}$(document).ready(function(){$(".modal").on("hidden.bs.modal",function(e){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(e){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$.fn.modal.Constructor.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(e){this.$element[0]===e.target||this.$element.has(e.target).length||$(e.target).closest(".cke_dialog, .cke").length||this.$element.trigger("focus")},this))},$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(e){dismiss()}),$("#sendTestEmailModal").on("hidden.bs.modal",function(e){dismissSendTestEmailModal()}),$("#headersForm").on("submit",function(){return headerKey=$("#headerKey").val(),headerValue=$("#headerValue").val(),""==headerKey||""==headerValue||(addCustomHeader(headerKey,headerValue),$("#headersForm>div>input").val(""),$("#headerKey").focus()),!1}),$("#headersTable").on("click","span>i.fa-trash-o",function(){headers.DataTable().row($(this).parents("tr")).remove().draw()}),load()}); \ No newline at end of file +var profiles=[];function sendTestEmail(){var t=[];$.each($("#headersTable").DataTable().rows().data(),function(e,a){t.push({key:unescapeHtml(a[0]),value:unescapeHtml(a[1])})});var e={template:{},first_name:$("input[name=to_first_name]").val(),last_name:$("input[name=to_last_name]").val(),email:$("input[name=to_email]").val(),position:$("input[name=to_position]").val(),url:"",smtp:{from_address:$("#from").val(),host:$("#host").val(),username:$("#username").val(),password:$("#password").val(),ignore_cert_errors:$("#ignore_cert_errors").prop("checked"),headers:t}};btnHtml=$("#sendTestModalSubmit").html(),$("#sendTestModalSubmit").html(' Sending'),api.send_test_email(e).success(function(e){$("#sendTestEmailModal\\.flashes").empty().append('
        \t Email Sent!
        '),$("#sendTestModalSubmit").html(btnHtml)}).error(function(e){$("#sendTestEmailModal\\.flashes").empty().append('
        \t '+e.responseJSON.message+"
        "),$("#sendTestModalSubmit").html(btnHtml)})}function save(e){var t={headers:[]};$.each($("#headersTable").DataTable().rows().data(),function(e,a){t.headers.push({key:unescapeHtml(a[0]),value:unescapeHtml(a[1])})}),t.name=$("#name").val(),t.interface_type=$("#interface_type").val(),t.from_address=$("#from").val(),t.host=$("#host").val(),t.username=$("#username").val(),t.password=$("#password").val(),t.ignore_cert_errors=$("#ignore_cert_errors").prop("checked"),-1!=e?(t.id=profiles[e].id,api.SMTPId.put(t).success(function(e){successFlash("Profile edited successfully!"),load(),dismiss()}).error(function(e){modalError(e.responseJSON.message)})):api.SMTP.post(t).success(function(e){successFlash("Profile added successfully!"),load(),dismiss()}).error(function(e){modalError(e.responseJSON.message)})}function dismiss(){$("#modal\\.flashes").empty(),$("#name").val(""),$("#interface_type").val("SMTP"),$("#from").val(""),$("#host").val(""),$("#username").val(""),$("#password").val(""),$("#ignore_cert_errors").prop("checked",!0),$("#headersTable").dataTable().DataTable().clear().draw(),$("#modal").modal("hide")}var dismissSendTestEmailModal=function(){$("#sendTestEmailModal\\.flashes").empty(),$("#sendTestModalSubmit").html(" Send")},deleteProfile=function(e){Swal.fire({title:"Are you sure?",text:"This will delete the sending profile. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(profiles[e].name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(a,t){api.SMTPId.delete(profiles[e].id).success(function(e){a()}).error(function(e){t(e.responseJSON.message)})})}}).then(function(e){e.value&&Swal.fire("Sending Profile Deleted!","This sending profile has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};function edit(e){headers=$("#headersTable").dataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]}),$("#modalSubmit").unbind("click").click(function(){save(e)});var a={};-1!=e&&(a=profiles[e],$("#name").val(a.name),$("#interface_type").val(a.interface_type),$("#from").val(a.from_address),$("#host").val(a.host),$("#username").val(a.username),$("#password").val(a.password),$("#ignore_cert_errors").prop("checked",a.ignore_cert_errors),$.each(a.headers,function(e,a){addCustomHeader(a.key,a.value)}))}function copy(e){$("#modalSubmit").unbind("click").click(function(){save(-1)});var a;a=profiles[e],$("#name").val("Copy of "+a.name),$("#interface_type").val(a.interface_type),$("#from").val(a.from_address),$("#host").val(a.host),$("#username").val(a.username),$("#password").val(a.password),$("#ignore_cert_errors").prop("checked",a.ignore_cert_errors)}function load(){$("#profileTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.SMTP.get().success(function(e){profiles=e,$("#loading").hide(),0\t\t "]).draw()}),$('[data-toggle="tooltip"]').tooltip()):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching profiles")})}function addCustomHeader(e,a){var t=[escapeHtml(e),escapeHtml(a),''],s=headers.DataTable(),o=s.column(0).data().indexOf(escapeHtml(e));0<=o?s.row(o,{order:"index"}).data(t):s.row.add(t),s.draw()}$(document).ready(function(){$(".modal").on("hidden.bs.modal",function(e){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(e){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$.fn.modal.Constructor.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(e){this.$element[0]===e.target||this.$element.has(e.target).length||$(e.target).closest(".cke_dialog, .cke").length||this.$element.trigger("focus")},this))},$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(e){dismiss()}),$("#sendTestEmailModal").on("hidden.bs.modal",function(e){dismissSendTestEmailModal()}),$("#headersForm").on("submit",function(){return headerKey=$("#headerKey").val(),headerValue=$("#headerValue").val(),""==headerKey||""==headerValue||(addCustomHeader(headerKey,headerValue),$("#headersForm>div>input").val(""),$("#headerKey").focus()),!1}),$("#headersTable").on("click","span>i.fa-trash-o",function(){headers.DataTable().row($(this).parents("tr")).remove().draw()}),load()}); \ No newline at end of file diff --git a/static/js/dist/app/templates.min.js b/static/js/dist/app/templates.min.js index 36f58287..d3e1a5aa 100644 --- a/static/js/dist/app/templates.min.js +++ b/static/js/dist/app/templates.min.js @@ -1 +1 @@ -var templates=[],icons={"application/vnd.ms-excel":"fa-file-excel-o","text/plain":"fa-file-text-o","image/gif":"fa-file-image-o","image/png":"fa-file-image-o","application/pdf":"fa-file-pdf-o","application/x-zip-compressed":"fa-file-archive-o","application/x-gzip":"fa-file-archive-o","application/vnd.openxmlformats-officedocument.presentationml.presentation":"fa-file-powerpoint-o","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"fa-file-word-o","application/octet-stream":"fa-file-o","application/x-msdownload":"fa-file-o"};function save(t){var a={attachments:[]};a.name=$("#name").val(),a.subject=$("#subject").val(),a.html=CKEDITOR.instances.html_editor.getData(),a.html=a.html.replace(/https?:\/\/{{\.URL}}/gi,"{{.URL}}"),$("#use_tracker_checkbox").prop("checked")?-1==a.html.indexOf("{{.Tracker}}")&&-1==a.html.indexOf("{{.TrackingUrl}}")&&(a.html=a.html.replace("","{{.Tracker}}")):a.html=a.html.replace("{{.Tracker}}",""),a.text=$("#text_editor").val(),$.each($("#attachmentsTable").DataTable().rows().data(),function(t,e){a.attachments.push({name:unescapeHtml(e[1]),content:e[3],type:e[4]})}),-1!=t?(a.id=templates[t].id,api.templateId.put(a).success(function(t){successFlash("Template edited successfully!"),load(),dismiss()}).error(function(t){modalError(t.responseJSON.message)})):api.templates.post(a).success(function(t){successFlash("Template added successfully!"),load(),dismiss()}).error(function(t){modalError(t.responseJSON.message)})}function dismiss(){$("#modal\\.flashes").empty(),$("#attachmentsTable").dataTable().DataTable().clear().draw(),$("#name").val(""),$("#subject").val(""),$("#text_editor").val(""),$("#html_editor").val(""),$("#modal").modal("hide")}var deleteTemplate=function(t){swal({title:"Are you sure?",text:"This will delete the template. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(templates[t].name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(e,a){api.templateId.delete(templates[t].id).success(function(t){e()}).error(function(t){a(t.responseJSON.message)})})}}).then(function(){swal("Template Deleted!","This template has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};function deleteTemplate(t){confirm("Delete "+templates[t].name+"?")&&api.templateId.delete(templates[t].id).success(function(t){successFlash(t.message),load()})}function attach(t){attachmentsTable=$("#attachmentsTable").DataTable({destroy:!0,order:[[1,"asc"]],columnDefs:[{orderable:!1,targets:"no-sort"},{sClass:"datatable_hidden",targets:[3,4]}]}),$.each(t,function(t,a){var o=new FileReader;o.onload=function(t){var e=icons[a.type]||"fa-file-o";attachmentsTable.row.add(['',escapeHtml(a.name),'',o.result.split(",")[1],a.type||"application/octet-stream"]).draw()},o.onerror=function(t){console.log(t)},o.readAsDataURL(a)})}function edit(t){$("#modalSubmit").unbind("click").click(function(){save(t)}),$("#attachmentUpload").unbind("click").click(function(){this.value=null}),$("#html_editor").ckeditor(),setupAutocomplete(CKEDITOR.instances.html_editor),$("#attachmentsTable").show(),attachmentsTable=$("#attachmentsTable").DataTable({destroy:!0,order:[[1,"asc"]],columnDefs:[{orderable:!1,targets:"no-sort"},{sClass:"datatable_hidden",targets:[3,4]}]});var e={attachments:[]};-1!=t&&(e=templates[t],$("#name").val(e.name),$("#subject").val(e.subject),$("#html_editor").val(e.html),$("#text_editor").val(e.text),$.each(e.attachments,function(t,e){var a=icons[e.type]||"fa-file-o";attachmentsTable.row.add(['',escapeHtml(e.name),'',e.content,e.type||"application/octet-stream"]).draw()}),-1!=e.html.indexOf("{{.Tracker}}")?$("#use_tracker_checkbox").prop("checked",!0):$("#use_tracker_checkbox").prop("checked",!1)),$("#attachmentsTable").unbind("click").on("click","span>i.fa-trash-o",function(){attachmentsTable.row($(this).parents("tr")).remove().draw()})}function copy(t){$("#modalSubmit").unbind("click").click(function(){save(-1)}),$("#attachmentUpload").unbind("click").click(function(){this.value=null}),$("#html_editor").ckeditor(),$("#attachmentsTable").show(),attachmentsTable=$("#attachmentsTable").DataTable({destroy:!0,order:[[1,"asc"]],columnDefs:[{orderable:!1,targets:"no-sort"},{sClass:"datatable_hidden",targets:[3,4]}]});var e={attachments:[]};e=templates[t],$("#name").val("Copy of "+e.name),$("#subject").val(e.subject),$("#html_editor").val(e.html),$("#text_editor").val(e.text),$.each(e.attachments,function(t,e){var a=icons[e.type]||"fa-file-o";attachmentsTable.row.add(['',escapeHtml(e.name),'',e.content,e.type||"application/octet-stream"]).draw()}),$("#attachmentsTable").unbind("click").on("click","span>i.fa-trash-o",function(){attachmentsTable.row($(this).parents("tr")).remove().draw()}),-1!=e.html.indexOf("{{.Tracker}}")?$("#use_tracker_checkbox").prop("checked",!0):$("#use_tracker_checkbox").prop("checked",!1)}function importEmail(){raw=$("#email_content").val(),convert_links=$("#convert_links_checkbox").prop("checked"),raw?api.import_email({content:raw,convert_links:convert_links}).success(function(t){$("#text_editor").val(t.text),$("#html_editor").val(t.html),$("#subject").val(t.subject),t.html&&(CKEDITOR.instances.html_editor.setMode("wysiwyg"),$('.nav-tabs a[href="#html"]').click()),$("#importEmailModal").modal("hide")}).error(function(t){modalError(t.responseJSON.message)}):modalError("No Content Specified!")}function load(){$("#templateTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.templates.get().success(function(t){templates=t,$("#loading").hide(),0\t\t "]).draw()}),$('[data-toggle="tooltip"]').tooltip()):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching templates")})}$(document).ready(function(){$(".modal").on("hidden.bs.modal",function(t){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(t){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$.fn.modal.Constructor.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(t){this.$element[0]===t.target||this.$element.has(t.target).length||$(t.target).closest(".cke_dialog, .cke").length||this.$element.trigger("focus")},this))},$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(t){dismiss()}),$("#importEmailModal").on("hidden.bs.modal",function(t){$("#email_content").val("")}),CKEDITOR.on("dialogDefinition",function(t){var e=t.data.name,a=t.data.definition;"link"==e&&(a.minWidth=500,a.minHeight=100,a.getContents("info").get("linkType").hidden=!0)}),load()}); \ No newline at end of file +var templates=[],icons={"application/vnd.ms-excel":"fa-file-excel-o","text/plain":"fa-file-text-o","image/gif":"fa-file-image-o","image/png":"fa-file-image-o","application/pdf":"fa-file-pdf-o","application/x-zip-compressed":"fa-file-archive-o","application/x-gzip":"fa-file-archive-o","application/vnd.openxmlformats-officedocument.presentationml.presentation":"fa-file-powerpoint-o","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"fa-file-word-o","application/octet-stream":"fa-file-o","application/x-msdownload":"fa-file-o"};function save(e){var a={attachments:[]};a.name=$("#name").val(),a.subject=$("#subject").val(),a.html=CKEDITOR.instances.html_editor.getData(),a.html=a.html.replace(/https?:\/\/{{\.URL}}/gi,"{{.URL}}"),$("#use_tracker_checkbox").prop("checked")?-1==a.html.indexOf("{{.Tracker}}")&&-1==a.html.indexOf("{{.TrackingUrl}}")&&(a.html=a.html.replace("","{{.Tracker}}")):a.html=a.html.replace("{{.Tracker}}",""),a.text=$("#text_editor").val(),$.each($("#attachmentsTable").DataTable().rows().data(),function(e,t){a.attachments.push({name:unescapeHtml(t[1]),content:t[3],type:t[4]})}),-1!=e?(a.id=templates[e].id,api.templateId.put(a).success(function(e){successFlash("Template edited successfully!"),load(),dismiss()}).error(function(e){modalError(e.responseJSON.message)})):api.templates.post(a).success(function(e){successFlash("Template added successfully!"),load(),dismiss()}).error(function(e){modalError(e.responseJSON.message)})}function dismiss(){$("#modal\\.flashes").empty(),$("#attachmentsTable").dataTable().DataTable().clear().draw(),$("#name").val(""),$("#subject").val(""),$("#text_editor").val(""),$("#html_editor").val(""),$("#modal").modal("hide")}var deleteTemplate=function(e){Swal.fire({title:"Are you sure?",text:"This will delete the template. This can't be undone!",type:"warning",animation:!1,showCancelButton:!0,confirmButtonText:"Delete "+escapeHtml(templates[e].name),confirmButtonColor:"#428bca",reverseButtons:!0,allowOutsideClick:!1,preConfirm:function(){return new Promise(function(t,a){api.templateId.delete(templates[e].id).success(function(e){t()}).error(function(e){a(e.responseJSON.message)})})}}).then(function(e){e.value&&Swal.fire("Template Deleted!","This template has been deleted!","success"),$('button:contains("OK")').on("click",function(){location.reload()})})};function deleteTemplate(e){confirm("Delete "+templates[e].name+"?")&&api.templateId.delete(templates[e].id).success(function(e){successFlash(e.message),load()})}function attach(e){attachmentsTable=$("#attachmentsTable").DataTable({destroy:!0,order:[[1,"asc"]],columnDefs:[{orderable:!1,targets:"no-sort"},{sClass:"datatable_hidden",targets:[3,4]}]}),$.each(e,function(e,a){var o=new FileReader;o.onload=function(e){var t=icons[a.type]||"fa-file-o";attachmentsTable.row.add(['',escapeHtml(a.name),'',o.result.split(",")[1],a.type||"application/octet-stream"]).draw()},o.onerror=function(e){console.log(e)},o.readAsDataURL(a)})}function edit(e){$("#modalSubmit").unbind("click").click(function(){save(e)}),$("#attachmentUpload").unbind("click").click(function(){this.value=null}),$("#html_editor").ckeditor(),setupAutocomplete(CKEDITOR.instances.html_editor),$("#attachmentsTable").show(),attachmentsTable=$("#attachmentsTable").DataTable({destroy:!0,order:[[1,"asc"]],columnDefs:[{orderable:!1,targets:"no-sort"},{sClass:"datatable_hidden",targets:[3,4]}]});var t={attachments:[]};-1!=e&&(t=templates[e],$("#name").val(t.name),$("#subject").val(t.subject),$("#html_editor").val(t.html),$("#text_editor").val(t.text),$.each(t.attachments,function(e,t){var a=icons[t.type]||"fa-file-o";attachmentsTable.row.add(['',escapeHtml(t.name),'',t.content,t.type||"application/octet-stream"]).draw()}),-1!=t.html.indexOf("{{.Tracker}}")?$("#use_tracker_checkbox").prop("checked",!0):$("#use_tracker_checkbox").prop("checked",!1)),$("#attachmentsTable").unbind("click").on("click","span>i.fa-trash-o",function(){attachmentsTable.row($(this).parents("tr")).remove().draw()})}function copy(e){$("#modalSubmit").unbind("click").click(function(){save(-1)}),$("#attachmentUpload").unbind("click").click(function(){this.value=null}),$("#html_editor").ckeditor(),$("#attachmentsTable").show(),attachmentsTable=$("#attachmentsTable").DataTable({destroy:!0,order:[[1,"asc"]],columnDefs:[{orderable:!1,targets:"no-sort"},{sClass:"datatable_hidden",targets:[3,4]}]});var t={attachments:[]};t=templates[e],$("#name").val("Copy of "+t.name),$("#subject").val(t.subject),$("#html_editor").val(t.html),$("#text_editor").val(t.text),$.each(t.attachments,function(e,t){var a=icons[t.type]||"fa-file-o";attachmentsTable.row.add(['',escapeHtml(t.name),'',t.content,t.type||"application/octet-stream"]).draw()}),$("#attachmentsTable").unbind("click").on("click","span>i.fa-trash-o",function(){attachmentsTable.row($(this).parents("tr")).remove().draw()}),-1!=t.html.indexOf("{{.Tracker}}")?$("#use_tracker_checkbox").prop("checked",!0):$("#use_tracker_checkbox").prop("checked",!1)}function importEmail(){raw=$("#email_content").val(),convert_links=$("#convert_links_checkbox").prop("checked"),raw?api.import_email({content:raw,convert_links:convert_links}).success(function(e){$("#text_editor").val(e.text),$("#html_editor").val(e.html),$("#subject").val(e.subject),e.html&&(CKEDITOR.instances.html_editor.setMode("wysiwyg"),$('.nav-tabs a[href="#html"]').click()),$("#importEmailModal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)}):modalError("No Content Specified!")}function load(){$("#templateTable").hide(),$("#emptyMessage").hide(),$("#loading").show(),api.templates.get().success(function(e){templates=e,$("#loading").hide(),0\t\t "]).draw()}),$('[data-toggle="tooltip"]').tooltip()):$("#emptyMessage").show()}).error(function(){$("#loading").hide(),errorFlash("Error fetching templates")})}$(document).ready(function(){$(".modal").on("hidden.bs.modal",function(e){$(this).removeClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")-1)}),$(".modal").on("shown.bs.modal",function(e){void 0===$("body").data("fv_open_modals")&&$("body").data("fv_open_modals",0),$(this).hasClass("fv-modal-stack")||($(this).addClass("fv-modal-stack"),$("body").data("fv_open_modals",$("body").data("fv_open_modals")+1),$(this).css("z-index",1040+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not(".fv-modal-stack").css("z-index",1039+10*$("body").data("fv_open_modals")),$(".modal-backdrop").not("fv-modal-stack").addClass("fv-modal-stack"))}),$.fn.modal.Constructor.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(e){this.$element[0]===e.target||this.$element.has(e.target).length||$(e.target).closest(".cke_dialog, .cke").length||this.$element.trigger("focus")},this))},$(document).on("hidden.bs.modal",".modal",function(){$(".modal:visible").length&&$(document.body).addClass("modal-open")}),$("#modal").on("hidden.bs.modal",function(e){dismiss()}),$("#importEmailModal").on("hidden.bs.modal",function(e){$("#email_content").val("")}),CKEDITOR.on("dialogDefinition",function(e){var t=e.data.name,a=e.data.definition;"link"==t&&(a.minWidth=500,a.minHeight=100,a.getContents("info").get("linkType").hidden=!0)}),load()}); \ No newline at end of file diff --git a/static/js/dist/app/users.min.js b/static/js/dist/app/users.min.js index b2a3f080..f6aab604 100644 --- a/static/js/dist/app/users.min.js +++ b/static/js/dist/app/users.min.js @@ -1 +1 @@ -!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t){var r=[],n=function(){$("#username").val(""),$("#password").val(""),$("#confirm_password").val(""),$("#role").val(""),$("#modal\\.flashes").empty()},o=function(e){$("#modalSubmit").unbind("click").click(function(){!function(e){if($("#password").val()===$("#confirm_password").val()){var t={username:$("#username").val(),password:$("#password").val(),role:$("#role").val()};-1!=e?(t.id=e,api.userId.put(t).success(function(e){successFlash("User ".concat(t.username," updated successfully!")),s(),n(),$("#modal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)})):api.users.post(t).success(function(e){successFlash("User ".concat(t.username," registered successfully!")),s(),n(),$("#modal").modal("hide")}).error(function(e){modalError(e.responseJSON.message)})}else modalError("Passwords must match.")}(e)}),$("#role").select2(),-1==e?($("#role").val("user"),$("#role").trigger("change")):api.userId.get(e).success(function(e){$("#username").val(e.username),$("#role").val(e.role.slug),$("#role").trigger("change")}).error(function(){errorFlash("Error fetching user")})},s=function(){$("#userTable").hide(),$("#loading").show(),api.users.get().success(function(e){r=e,$("#loading").hide(),$("#userTable").show();var t=$("#userTable").DataTable({destroy:!0,columnDefs:[{orderable:!1,targets:"no-sort"}]});t.clear(),$.each(r,function(e,r){t.row.add([escapeHtml(r.username),escapeHtml(r.role.name),"
        "]).draw()})}).error(function(){errorFlash("Error fetching users")})};$(document).ready(function(){s(),$("#modal").on("hide.bs.modal",function(){n()}),$.fn.select2.defaults.set("width","100%"),$.fn.select2.defaults.set("dropdownParent",$("#role-select")),$.fn.select2.defaults.set("theme","bootstrap"),$.fn.select2.defaults.set("sorter",function(e){return e.sort(function(e,t){return e.text.toLowerCase()>t.text.toLowerCase()?1:e.text.toLowerCase() "]).draw()})}).error(function(){errorFlash("Error fetching users")})};$(document).ready(function(){s(),$("#modal").on("hide.bs.modal",function(){n()}),$.fn.select2.defaults.set("width","100%"),$.fn.select2.defaults.set("dropdownParent",$("#role-select")),$.fn.select2.defaults.set("theme","bootstrap"),$.fn.select2.defaults.set("sorter",function(e){return e.sort(function(e,t){return e.text.toLowerCase()>t.text.toLowerCase()?1:e.text.toLowerCase())[^>]*|#([\w-]*))$/,M=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,T=/^[\],:{}\s]*$/,D=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,P=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,E=/^-ms-/,O=/-([\da-z])/gi,L=function(){g.addEventListener?(g.removeEventListener("DOMContentLoaded",i,!1),p.removeEventListener("load",i,!1)):(g.detachEvent("onreadystatechange",i),p.detachEvent("onload",i))};function I(t){var e=t.length,n=xt.type(t);return!xt.isWindow(t)&&(!(1!==t.nodeType||!e)||("array"===n||"function"!==n&&(0===e||"number"==typeof e&&0"===t.charAt(t.length-1)&&3<=t.length?[null,t,null]:k.exec(t))||!i[1]&&e)return!e||e.jquery?(e||n).find(t):this.constructor(e).find(t);if(i[1]){if(e=e instanceof xt?e[0]:e,xt.merge(this,xt.parseHTML(i[1],e&&e.nodeType?e.ownerDocument||e:g,!0)),M.test(i[1])&&xt.isPlainObject(e))for(i in e)xt.isFunction(this[i])?this[i](e[i]):this.attr(i,e[i]);return this}if((r=g.getElementById(i[2]))&&r.parentNode){if(r.id!==i[2])return n.find(t);this.length=1,this[0]=r}return this.context=g,this.selector=t,this},selector:"",length:0,toArray:function(){return d.call(this)},get:function(t){return null==t?this.toArray():t<0?this[this.length+t]:this[t]},pushStack:function(t){var e=xt.merge(this.constructor(),t);return e.prevObject=this,e.context=this.context,e},each:function(t,e){return xt.each(this,t,e)},ready:function(t){return xt.ready.promise().done(t),this},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(t){var e=this.length,n=+t+(t<0?e:0);return this.pushStack(0<=n&&n+~]|"+R+")"+R+"*"),U=RegExp(R+"*[+~]"),Y=RegExp("="+R+"*([^\\]'\"]*)"+R+"*\\]","g"),G=RegExp(B),X=RegExp("^"+H+"$"),V={ID:RegExp("^#("+j+")"),CLASS:RegExp("^\\.("+j+")"),TAG:RegExp("^("+j.replace("w","w*")+")"),ATTR:RegExp("^"+z),PSEUDO:RegExp("^"+B),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+R+"*(even|odd|(([+-]|)(\\d*)n|)"+R+"*(?:([+-]|)"+R+"*(\\d+)|))"+R+"*\\)|)","i"),bool:RegExp("^(?:"+F+")$","i"),needsContext:RegExp("^"+R+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+R+"*((?:-\\d)?\\d*)"+R+"*\\)|)(?=[^-]|$)","i")},Z=/^[^{]+\{\s*\[native \w/,K=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,J=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,tt=/'|\\/g,et=RegExp("\\\\([\\da-f]{1,6}"+R+"?|("+R+")|.)","ig"),nt=function(t,e,n){var i="0x"+e-65536;return i!=i||n?e:i<0?String.fromCharCode(65536+i):String.fromCharCode(55296|i>>10,56320|1023&i)};try{L.apply(e=I.call(k.childNodes),k.childNodes),e[k.childNodes.length].nodeType}catch(t){L={apply:e.length?function(t,e){O.apply(t,I.call(e))}:function(t,e){for(var n=t.length,i=0;t[n++]=e[i++];);t.length=n-1}}}function it(t,e,n,i){var r,o,a,s,l,u,c,h,d,f;if((e?e.ownerDocument||e:k)!==C&&m(e),n=n||[],!t||"string"!=typeof t)return n;if(1!==(s=(e=e||C).nodeType)&&9!==s)return[];if(v&&!i){if(r=K.exec(t))if(a=r[1]){if(9===s){if(!(o=e.getElementById(a))||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(e.ownerDocument&&(o=e.ownerDocument.getElementById(a))&&b(e,o)&&o.id===a)return n.push(o),n}else{if(r[2])return L.apply(n,e.getElementsByTagName(t)),n;if((a=r[3])&&p.getElementsByClassName&&e.getElementsByClassName)return L.apply(n,e.getElementsByClassName(a)),n}if(p.qsa&&(!y||!y.test(t))){if(h=c=x,d=e,f=9===s&&t,1===s&&"object"!==e.nodeName.toLowerCase()){for(u=ft(t),(c=e.getAttribute("id"))?h=c.replace(tt,"\\$&"):e.setAttribute("id",h),h="[id='"+h+"'] ",l=u.length;l--;)u[l]=h+pt(u[l]);d=U.test(t)&&e.parentNode||e,f=u.join(",")}if(f)try{return L.apply(n,d.querySelectorAll(f)),n}catch(t){}finally{c||e.removeAttribute("id")}}}return function(t,e,n,i){var r,o,a,s,l,u=ft(t);if(!i&&1===u.length){if(2<(o=u[0]=u[0].slice(0)).length&&"ID"===(a=o[0]).type&&p.getById&&9===e.nodeType&&v&&S.relative[o[1].type]){if(!(e=(S.find.ID(a.matches[0].replace(et,nt),e)||[])[0]))return n;t=t.slice(o.shift().value.length)}for(r=V.needsContext.test(t)?0:o.length;r--&&(a=o[r],!S.relative[s=a.type]);)if((l=S.find[s])&&(i=l(a.matches[0].replace(et,nt),U.test(o[0].type)&&e.parentNode||e))){if(o.splice(r,1),!(t=i.length&&pt(o)))return L.apply(n,i),n;break}}return g(t,u)(i,e,!v,n,U.test(t)),n}(t.replace(W,"$1"),e,n,i)}function rt(){var i=[];return function t(e,n){return i.push(e+=" ")>S.cacheLength&&delete t[i.shift()],t[e]=n}}function ot(t){return t[x]=!0,t}function at(t){var e=C.createElement("div");try{return!!t(e)}catch(t){return!1}finally{e.parentNode&&e.parentNode.removeChild(e),e=null}}function st(t,e){for(var n=t.split("|"),i=t.length;i--;)S.attrHandle[n[i]]=e}function lt(t,e){var n=e&&t,i=n&&1===t.nodeType&&1===e.nodeType&&(~e.sourceIndex||1<<31)-(~t.sourceIndex||1<<31);if(i)return i;if(n)for(;n=n.nextSibling;)if(n===e)return-1;return t?1:-1}function ut(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function ct(n){return function(t){var e=t.nodeName.toLowerCase();return("input"===e||"button"===e)&&t.type===n}}function ht(a){return ot(function(o){return o=+o,ot(function(t,e){for(var n,i=a([],t.length,o),r=i.length;r--;)t[n=i[r]]&&(t[n]=!(e[n]=t[n]))})})}for(t in i=it.isXML=function(t){var e=t&&(t.ownerDocument||t).documentElement;return!!e&&"HTML"!==e.nodeName},p=it.support={},m=it.setDocument=function(t){var l=t?t.ownerDocument||t:k,e=l.defaultView;return l!==C&&9===l.nodeType&&l.documentElement?(a=(C=l).documentElement,v=!i(l),e&&e.attachEvent&&e!==e.top&&e.attachEvent("onbeforeunload",function(){m()}),p.attributes=at(function(t){return t.className="i",!t.getAttribute("className")}),p.getElementsByTagName=at(function(t){return t.appendChild(l.createComment("")),!t.getElementsByTagName("*").length}),p.getElementsByClassName=at(function(t){return t.innerHTML="
        ",t.firstChild.className="i",2===t.getElementsByClassName("i").length}),p.getById=at(function(t){return a.appendChild(t).id=x,!l.getElementsByName||!l.getElementsByName(x).length}),p.getById?(S.find.ID=function(t,e){if(typeof e.getElementById!=A&&v){var n=e.getElementById(t);return n&&n.parentNode?[n]:[]}},S.filter.ID=function(t){var e=t.replace(et,nt);return function(t){return t.getAttribute("id")===e}}):(delete S.find.ID,S.filter.ID=function(t){var n=t.replace(et,nt);return function(t){var e=typeof t.getAttributeNode!=A&&t.getAttributeNode("id");return e&&e.value===n}}),S.find.TAG=p.getElementsByTagName?function(t,e){return typeof e.getElementsByTagName!=A?e.getElementsByTagName(t):r}:function(t,e){var n,i=[],r=0,o=e.getElementsByTagName(t);if("*"!==t)return o;for(;n=o[r++];)1===n.nodeType&&i.push(n);return i},S.find.CLASS=p.getElementsByClassName&&function(t,e){return typeof e.getElementsByClassName!=A&&v?e.getElementsByClassName(t):r},s=[],y=[],(p.qsa=Z.test(l.querySelectorAll))&&(at(function(t){t.innerHTML="",t.querySelectorAll("[selected]").length||y.push("\\["+R+"*(?:value|"+F+")"),t.querySelectorAll(":checked").length||y.push(":checked")}),at(function(t){var e=l.createElement("input");e.setAttribute("type","hidden"),t.appendChild(e).setAttribute("t",""),t.querySelectorAll("[t^='']").length&&y.push("[*^$]="+R+"*(?:''|\"\")"),t.querySelectorAll(":enabled").length||y.push(":enabled",":disabled"),t.querySelectorAll("*,:x"),y.push(",.*:")})),(p.matchesSelector=Z.test(c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&at(function(t){p.disconnectedMatch=c.call(t,"div"),c.call(t,"[s!='']:x"),s.push("!=",B)}),y=y.length&&RegExp(y.join("|")),s=s.length&&RegExp(s.join("|")),b=Z.test(a.contains)||a.compareDocumentPosition?function(t,e){var n=9===t.nodeType?t.documentElement:t,i=e&&e.parentNode;return t===i||!(!i||1!==i.nodeType||!(n.contains?n.contains(i):t.compareDocumentPosition&&16&t.compareDocumentPosition(i)))}:function(t,e){if(e)for(;e=e.parentNode;)if(e===t)return!0;return!1},D=a.compareDocumentPosition?function(t,e){if(t===e)return T=!0,0;var n=e.compareDocumentPosition&&t.compareDocumentPosition&&t.compareDocumentPosition(e);return n?1&n||!p.sortDetached&&e.compareDocumentPosition(t)===n?t===l||b(k,t)?-1:e===l||b(k,e)?1:u?N.call(u,t)-N.call(u,e):0:4&n?-1:1:t.compareDocumentPosition?-1:1}:function(t,e){var n,i=0,r=t.parentNode,o=e.parentNode,a=[t],s=[e];if(t===e)return T=!0,0;if(!r||!o)return t===l?-1:e===l?1:r?-1:o?1:u?N.call(u,t)-N.call(u,e):0;if(r===o)return lt(t,e);for(n=t;n=n.parentNode;)a.unshift(n);for(n=e;n=n.parentNode;)s.unshift(n);for(;a[i]===s[i];)i++;return i?lt(a[i],s[i]):a[i]===k?-1:s[i]===k?1:0},l):C},it.matches=function(t,e){return it(t,null,null,e)},it.matchesSelector=function(t,e){if((t.ownerDocument||t)!==C&&m(t),e=e.replace(Y,"='$1']"),!(!p.matchesSelector||!v||s&&s.test(e)||y&&y.test(e)))try{var n=c.call(t,e);if(n||p.disconnectedMatch||t.document&&11!==t.document.nodeType)return n}catch(t){}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(t){return t[1]=t[1].replace(et,nt),t[3]=(t[4]||t[5]||"").replace(et,nt),"~="===t[2]&&(t[3]=" "+t[3]+" "),t.slice(0,4)},CHILD:function(t){return t[1]=t[1].toLowerCase(),"nth"===t[1].slice(0,3)?(t[3]||it.error(t[0]),t[4]=+(t[4]?t[5]+(t[6]||1):2*("even"===t[3]||"odd"===t[3])),t[5]=+(t[7]+t[8]||"odd"===t[3])):t[3]&&it.error(t[0]),t},PSEUDO:function(t){var e,n=!t[5]&&t[2];return V.CHILD.test(t[0])?null:(t[3]&&t[4]!==r?t[2]=t[4]:n&&G.test(n)&&(e=ft(n,!0))&&(e=n.indexOf(")",n.length-e)-n.length)&&(t[0]=t[0].slice(0,e),t[2]=n.slice(0,e)),t.slice(0,3))}},filter:{TAG:function(t){var e=t.replace(et,nt).toLowerCase();return"*"===t?function(){return!0}:function(t){return t.nodeName&&t.nodeName.toLowerCase()===e}},CLASS:function(t){var e=l[t+" "];return e||(e=RegExp("(^|"+R+")"+t+"("+R+"|$)"))&&l(t,function(t){return e.test("string"==typeof t.className&&t.className||typeof t.getAttribute!=A&&t.getAttribute("class")||"")})},ATTR:function(n,i,r){return function(t){var e=it.attr(t,n);return null==e?"!="===i:!i||(e+="","="===i?e===r:"!="===i?e!==r:"^="===i?r&&0===e.indexOf(r):"*="===i?r&&-1++i;)t.push(i);return t})}}).pseudos.nth=S.pseudos.eq,{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})S.pseudos[t]=ut(t);for(t in{submit:!0,reset:!0})S.pseudos[t]=ct(t);function dt(){}function ft(t,e){var n,i,r,o,a,s,l,u=d[t+" "];if(u)return e?0:u.slice(0);for(a=t,s=[],l=S.preFilter;a;){for(o in(!n||(i=$.exec(a)))&&(i&&(a=a.slice(i[0].length)||a),s.push(r=[])),n=!1,(i=q.exec(a))&&(n=i.shift(),r.push({value:n,type:i[0].replace(W," ")}),a=a.slice(n.length)),S.filter)!(i=V[o].exec(a))||l[o]&&!(i=l[o](i))||(n=i.shift(),r.push({value:n,type:o,matches:i}),a=a.slice(n.length));if(!n)break}return e?a.length:a?it.error(t):d(t,s).slice(0)}function pt(t){for(var e=0,n=t.length,i="";e
        a",t=c.getElementsByTagName("*")||[],!(e=c.getElementsByTagName("a")[0])||!e.style||!t.length)return o;a=(i=g.createElement("select")).appendChild(g.createElement("option")),n=c.getElementsByTagName("input")[0],e.style.cssText="top:1px;float:left;opacity:.5",o.getSetAttribute="t"!==c.className,o.leadingWhitespace=3===c.firstChild.nodeType,o.tbody=!c.getElementsByTagName("tbody").length,o.htmlSerialize=!!c.getElementsByTagName("link").length,o.style=/top/.test(e.getAttribute("style")),o.hrefNormalized="/a"===e.getAttribute("href"),o.opacity=/^0.5/.test(e.style.opacity),o.cssFloat=!!e.style.cssFloat,o.checkOn=!!n.value,o.optSelected=a.selected,o.enctype=!!g.createElement("form").enctype,o.html5Clone="<:nav>"!==g.createElement("nav").cloneNode(!0).outerHTML,o.inlineBlockNeedsLayout=!1,o.shrinkWrapBlocks=!1,o.pixelPosition=!1,o.deleteExpando=!0,o.noCloneEvent=!0,o.reliableMarginRight=!0,o.boxSizingReliable=!0,n.checked=!0,o.noCloneChecked=n.cloneNode(!0).checked,i.disabled=!0,o.optDisabled=!a.disabled;try{delete c.test}catch(t){o.deleteExpando=!1}for(u in(n=g.createElement("input")).setAttribute("value",""),o.input=""===n.getAttribute("value"),n.value="t",n.setAttribute("type","radio"),o.radioValue="t"===n.value,n.setAttribute("checked","t"),n.setAttribute("name","t"),(r=g.createDocumentFragment()).appendChild(n),o.appendChecked=n.checked,o.checkClone=r.cloneNode(!0).cloneNode(!0).lastChild.checked,c.attachEvent&&(c.attachEvent("onclick",function(){o.noCloneEvent=!1}),c.cloneNode(!0).click()),{submit:!0,change:!0,focusin:!0})c.setAttribute(s="on"+u,"t"),o[u+"Bubbles"]=s in p||!1===c.attributes[s].expando;for(u in c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",o.clearCloneStyle="content-box"===c.style.backgroundClip,xt(o))break;return o.ownLast="0"!==u,xt(function(){var t,e,n,i="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",r=g.getElementsByTagName("body")[0];r&&((t=g.createElement("div")).style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",r.appendChild(t).appendChild(c),c.innerHTML="
        t
        ",(n=c.getElementsByTagName("td"))[0].style.cssText="padding:0;margin:0;border:0;display:none",l=0===n[0].offsetHeight,n[0].style.display="",n[1].style.display="none",o.reliableHiddenOffsets=l&&0===n[0].offsetHeight,c.innerHTML="",c.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",xt.swap(r,null!=r.style.zoom?{zoom:1}:{},function(){o.boxSizing=4===c.offsetWidth}),p.getComputedStyle&&(o.pixelPosition="1%"!==(p.getComputedStyle(c,null)||{}).top,o.boxSizingReliable="4px"===(p.getComputedStyle(c,null)||{width:"4px"}).width,(e=c.appendChild(g.createElement("div"))).style.cssText=c.style.cssText=i,e.style.marginRight=e.style.width="0",c.style.width="1px",o.reliableMarginRight=!parseFloat((p.getComputedStyle(e,null)||{}).marginRight)),typeof c.style.zoom!==v&&(c.innerHTML="",c.style.cssText=i+"width:1px;padding:1px;display:inline;zoom:1",o.inlineBlockNeedsLayout=3===c.offsetWidth,c.style.display="block",c.innerHTML="
        ",c.firstChild.style.width="5px",o.shrinkWrapBlocks=3!==c.offsetWidth,o.inlineBlockNeedsLayout&&(r.style.zoom=1)),r.removeChild(t),t=c=n=e=null)}),t=i=r=a=e=n=null,o}({});var F=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,R=/([A-Z])/g;function j(t,e,n,i){if(xt.acceptData(t)){var r,o,a=xt.expando,s=t.nodeType,l=s?xt.cache:t,u=s?t[a]:t[a]&&a;if(u&&l[u]&&(i||l[u].data)||n!==_||"string"!=typeof e)return u||(u=s?t[a]=h.pop()||xt.guid++:a),l[u]||(l[u]=s?{}:{toJSON:xt.noop}),("object"==typeof e||"function"==typeof e)&&(i?l[u]=xt.extend(l[u],e):l[u].data=xt.extend(l[u].data,e)),o=l[u],i||(o.data||(o.data={}),o=o.data),n!==_&&(o[xt.camelCase(e)]=n),"string"==typeof e?null==(r=o[e])&&(r=o[xt.camelCase(e)]):r=o,r}}function H(t,e,n){if(xt.acceptData(t)){var i,r,o=t.nodeType,a=o?xt.cache:t,s=o?t[xt.expando]:xt.expando;if(a[s]){if(e&&(i=n?a[s]:a[s].data)){r=(e=xt.isArray(e)?e.concat(xt.map(e,xt.camelCase)):e in i?[e]:(e=xt.camelCase(e))in i?[e]:e.split(" ")).length;for(;r--;)delete i[e[r]];if(n?!B(i):!xt.isEmptyObject(i))return}(n||(delete a[s].data,B(a[s])))&&(o?xt.cleanData([t],!0):xt.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}function z(t,e,n){if(n===_&&1===t.nodeType){var i="data-"+e.replace(R,"-$1").toLowerCase();if("string"==typeof(n=t.getAttribute(i))){try{n="true"===n||"false"!==n&&("null"===n?null:+n+""===n?+n:F.test(n)?xt.parseJSON(n):n)}catch(t){}xt.data(t,e,n)}else n=_}return n}function B(t){var e;for(e in t)if(("data"!==e||!xt.isEmptyObject(t[e]))&&"toJSON"!==e)return!1;return!0}xt.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(t){return!!(t=t.nodeType?xt.cache[t[xt.expando]]:t[xt.expando])&&!B(t)},data:function(t,e,n){return j(t,e,n)},removeData:function(t,e){return H(t,e)},_data:function(t,e,n){return j(t,e,n,!0)},_removeData:function(t,e){return H(t,e,!0)},acceptData:function(t){if(t.nodeType&&1!==t.nodeType&&9!==t.nodeType)return!1;var e=t.nodeName&&xt.noData[t.nodeName.toLowerCase()];return!e||!0!==e&&t.getAttribute("classid")===e}}),xt.fn.extend({data:function(t,e){var n,i,r=null,o=0,a=this[0];if(t!==_)return"object"==typeof t?this.each(function(){xt.data(this,t)}):1o;o++)0===(i=n[o].name).indexOf("data-")&&z(a,i=xt.camelCase(i.slice(5)),r[i]);xt._data(a,"parsedAttrs",!0)}return r},removeData:function(t){return this.each(function(){xt.removeData(this,t)})}}),xt.extend({queue:function(t,e,n){var i;return t?(e=(e||"fx")+"queue",i=xt._data(t,e),n&&(!i||xt.isArray(n)?i=xt._data(t,e,xt.makeArray(n)):i.push(n)),i||[]):_},dequeue:function(t,e){e=e||"fx";var n=xt.queue(t,e),i=n.length,r=n.shift(),o=xt._queueHooks(t,e);"inprogress"===r&&(r=n.shift(),i--),r&&("fx"===e&&n.unshift("inprogress"),delete o.stop,r.call(t,function(){xt.dequeue(t,e)},o)),!i&&o&&o.empty.fire()},_queueHooks:function(t,e){var n=e+"queueHooks";return xt._data(t,n)||xt._data(t,n,{empty:xt.Callbacks("once memory").add(function(){xt._removeData(t,e+"queue"),xt._removeData(t,n)})})}}),xt.fn.extend({queue:function(e,n){var t=2;return"string"!=typeof e&&(n=e,e="fx",t--),t>arguments.length?xt.queue(this[0],e):n===_?this:this.each(function(){var t=xt.queue(this,e,n);xt._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&xt.dequeue(this,e)})},dequeue:function(t){return this.each(function(){xt.dequeue(this,t)})},delay:function(i,t){return i=xt.fx&&xt.fx.speeds[i]||i,t=t||"fx",this.queue(t,function(t,e){var n=setTimeout(t,i);e.stop=function(){clearTimeout(n)}})},clearQueue:function(t){return this.queue(t||"fx",[])},promise:function(t,e){function n(){--r||o.resolveWith(a,[a])}var i,r=1,o=xt.Deferred(),a=this,s=this.length;for("string"!=typeof t&&(e=t,t=_),t=t||"fx";s--;)(i=xt._data(a[s],t+"queueHooks"))&&i.empty&&(r++,i.empty.add(n));return n(),o.promise(e)}});var W,$,q=/[\t\r\n\f]/g,U=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,G=/^(?:a|area)$/i,X=/^(?:checked|selected)$/i,V=xt.support.getSetAttribute,Z=xt.support.input;xt.fn.extend({attr:function(t,e){return xt.access(this,xt.attr,t,e,1s&&a.push({elem:this,handlers:e.slice(s)}),a},fix:function(t){if(t[xt.expando])return t;var e,n,i,r=t.type,o=t,a=this.fixHooks[r];for(a||(this.fixHooks[r]=a=Q.test(r)?this.mouseHooks:J.test(r)?this.keyHooks:{}),i=a.props?this.props.concat(a.props):this.props,t=new xt.Event(o),e=i.length;e--;)t[n=i[e]]=o[n];return t.target||(t.target=o.srcElement||g),3===t.target.nodeType&&(t.target=t.target.parentNode),t.metaKey=!!t.metaKey,a.filter?a.filter(t,o):t},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(t,e){return null==t.which&&(t.which=null!=e.charCode?e.charCode:e.keyCode),t}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(t,e){var n,i,r,o=e.button,a=e.fromElement;return null==t.pageX&&null!=e.clientX&&(r=(i=t.target.ownerDocument||g).documentElement,n=i.body,t.pageX=e.clientX+(r&&r.scrollLeft||n&&n.scrollLeft||0)-(r&&r.clientLeft||n&&n.clientLeft||0),t.pageY=e.clientY+(r&&r.scrollTop||n&&n.scrollTop||0)-(r&&r.clientTop||n&&n.clientTop||0)),!t.relatedTarget&&a&&(t.relatedTarget=a===t.target?e.toElement:a),t.which||o===_||(t.which=1&o?1:2&o?3:4&o?2:0),t}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==rt()&&this.focus)try{return this.focus(),!1}catch(t){}},delegateType:"focusin"},blur:{trigger:function(){return this===rt()&&this.blur?(this.blur(),!1):_},delegateType:"focusout"},click:{trigger:function(){return xt.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):_},_default:function(t){return xt.nodeName(t.target,"a")}},beforeunload:{postDispatch:function(t){t.result!==_&&(t.originalEvent.returnValue=t.result)}}},simulate:function(t,e,n,i){var r=xt.extend(new xt.Event,n,{type:t,isSimulated:!0,originalEvent:{}});i?xt.event.trigger(r,null,e):xt.event.dispatch.call(e,r),r.isDefaultPrevented()&&n.preventDefault()}},xt.removeEvent=g.removeEventListener?function(t,e,n){t.removeEventListener&&t.removeEventListener(e,n,!1)}:function(t,e,n){var i="on"+e;t.detachEvent&&(typeof t[i]===v&&(t[i]=null),t.detachEvent(i,n))},xt.Event=function(t,e){return this instanceof xt.Event?(t&&t.type?(this.originalEvent=t,this.type=t.type,this.isDefaultPrevented=t.defaultPrevented||!1===t.returnValue||t.getPreventDefault&&t.getPreventDefault()?nt:it):this.type=t,e&&xt.extend(this,e),this.timeStamp=t&&t.timeStamp||xt.now(),this[xt.expando]=!0,_):new xt.Event(t,e)},xt.Event.prototype={isDefaultPrevented:it,isPropagationStopped:it,isImmediatePropagationStopped:it,preventDefault:function(){var t=this.originalEvent;this.isDefaultPrevented=nt,t&&(t.preventDefault?t.preventDefault():t.returnValue=!1)},stopPropagation:function(){var t=this.originalEvent;this.isPropagationStopped=nt,t&&(t.stopPropagation&&t.stopPropagation(),t.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=nt,this.stopPropagation()}},xt.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(t,r){xt.event.special[t]={delegateType:r,bindType:r,handle:function(t){var e,n=t.relatedTarget,i=t.handleObj;return(!n||n!==this&&!xt.contains(this,n))&&(t.type=i.origType,e=i.handler.apply(this,arguments),t.type=r),e}}}),xt.support.submitBubbles||(xt.event.special.submit={setup:function(){return!xt.nodeName(this,"form")&&(xt.event.add(this,"click._submit keypress._submit",function(t){var e=t.target,n=xt.nodeName(e,"input")||xt.nodeName(e,"button")?e.form:_;n&&!xt._data(n,"submitBubbles")&&(xt.event.add(n,"submit._submit",function(t){t._submit_bubble=!0}),xt._data(n,"submitBubbles",!0))}),_)},postDispatch:function(t){t._submit_bubble&&(delete t._submit_bubble,this.parentNode&&!t.isTrigger&&xt.event.simulate("submit",this.parentNode,t,!0))},teardown:function(){return!xt.nodeName(this,"form")&&(xt.event.remove(this,"._submit"),_)}}),xt.support.changeBubbles||(xt.event.special.change={setup:function(){return K.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(xt.event.add(this,"propertychange._change",function(t){"checked"===t.originalEvent.propertyName&&(this._just_changed=!0)}),xt.event.add(this,"click._change",function(t){this._just_changed&&!t.isTrigger&&(this._just_changed=!1),xt.event.simulate("change",this,t,!0)})),!1):(xt.event.add(this,"beforeactivate._change",function(t){var e=t.target;K.test(e.nodeName)&&!xt._data(e,"changeBubbles")&&(xt.event.add(e,"change._change",function(t){!this.parentNode||t.isSimulated||t.isTrigger||xt.event.simulate("change",this.parentNode,t,!0)}),xt._data(e,"changeBubbles",!0))}),_)},handle:function(t){var e=t.target;return this!==e||t.isSimulated||t.isTrigger||"radio"!==e.type&&"checkbox"!==e.type?t.handleObj.handler.apply(this,arguments):_},teardown:function(){return xt.event.remove(this,"._change"),!K.test(this.nodeName)}}),xt.support.focusinBubbles||xt.each({focus:"focusin",blur:"focusout"},function(t,e){function n(t){xt.event.simulate(e,t.target,xt.event.fix(t),!0)}var i=0;xt.event.special[e]={setup:function(){0==i++&&g.addEventListener(t,n,!0)},teardown:function(){0==--i&&g.removeEventListener(t,n,!0)}}}),xt.fn.extend({on:function(t,e,n,i,r){var o,a;if("object"==typeof t){for(o in"string"!=typeof e&&(n=n||e,e=_),t)this.on(o,e,n,t[o],r);return this}if(null==n&&null==i?(i=e,n=e=_):null==i&&("string"==typeof e?(i=n,n=_):(i=n,n=e,e=_)),!1===i)i=it;else if(!i)return this;return 1===r&&(a=i,(i=function(t){return xt().off(t),a.apply(this,arguments)}).guid=a.guid||(a.guid=xt.guid++)),this.each(function(){xt.event.add(this,t,i,n,e)})},one:function(t,e,n,i){return this.on(t,e,n,i,1)},off:function(t,e,n){var i,r;if(t&&t.preventDefault&&t.handleObj)return i=t.handleObj,xt(t.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"!=typeof t)return(!1===e||"function"==typeof e)&&(n=e,e=_),!1===n&&(n=it),this.each(function(){xt.event.remove(this,t,n,e)});for(r in t)this.off(r,e,t[r]);return this},trigger:function(t,e){return this.each(function(){xt.event.trigger(t,e,this)})},triggerHandler:function(t,e){var n=this[0];return n?xt.event.trigger(t,e,n,!0):_}});var ot=/^.[^:#\[\.,]*$/,at=/^(?:parents|prev(?:Until|All))/,st=xt.expr.match.needsContext,lt={children:!0,contents:!0,next:!0,prev:!0};function ut(t,e){for(;(t=t[e])&&1!==t.nodeType;);return t}function ct(t,n,i){if(xt.isFunction(n))return xt.grep(t,function(t,e){return!!n.call(t,e,t)!==i});if(n.nodeType)return xt.grep(t,function(t){return t===n!==i});if("string"==typeof n){if(ot.test(n))return xt.filter(n,t,i);n=xt.filter(n,t)}return xt.grep(t,function(t){return 0<=xt.inArray(t,n)!==i})}function ht(t){var e=dt.split("|"),n=t.createDocumentFragment();if(n.createElement)for(;e.length;)n.createElement(e.pop());return n}xt.fn.extend({find:function(t){var e,n=[],i=this,r=i.length;if("string"!=typeof t)return this.pushStack(xt(t).filter(function(){for(e=0;e]","i"),gt=/^\s+/,mt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,yt=/
        ","
        "],tr:[2,"","
        "],col:[2,"","
        "],td:[3,"","
        "],_default:xt.support.htmlSerialize?[0,"",""]:[1,"X
        ","
        "]},Dt=ht(g).appendChild(g.createElement("div"));function At(t,e){return xt.nodeName(t,"table")&&xt.nodeName(1===e.nodeType?e:e.firstChild,"tr")?t.getElementsByTagName("tbody")[0]||t.appendChild(t.ownerDocument.createElement("tbody")):t}function Pt(t){return t.type=(null!==xt.find.attr(t,"type"))+"/"+t.type,t}function Et(t){var e=kt.exec(t.type);return e?t.type=e[1]:t.removeAttribute("type"),t}function Ot(t,e){for(var n,i=0;null!=(n=t[i]);i++)xt._data(n,"globalEval",!e||xt._data(e[i],"globalEval"))}function Lt(t,e){if(1===e.nodeType&&xt.hasData(t)){var n,i,r,o=xt._data(t),a=xt._data(e,o),s=o.events;if(s)for(n in delete a.handle,a.events={},s)for(i=0,r=s[n].length;i");try{for(;n")?o=t.cloneNode(!0):(Dt.innerHTML=t.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(xt.support.noCloneEvent&&xt.support.noCloneChecked||1!==t.nodeType&&11!==t.nodeType||xt.isXMLDoc(t)))for(i=Nt(o),s=Nt(t),a=0;null!=(r=s[a]);++a)i[a]&&It(r,i[a]);if(e)if(n)for(s=s||Nt(t),i=i||Nt(o),a=0;null!=(r=s[a]);a++)Lt(r,i[a]);else Lt(t,o);return 0<(i=Nt(o,"script")).length&&Ot(i,!l&&Nt(t,"script")),i=s=r=null,o},buildFragment:function(t,e,n,i){for(var r,o,a,s,l,u,c,h=t.length,d=ht(e),f=[],p=0;p")+c[2],r=c[0];r--;)s=s.lastChild;if(!xt.support.leadingWhitespace&>.test(o)&&f.push(e.createTextNode(gt.exec(o)[0])),!xt.support.tbody)for(r=(o="table"!==l||yt.test(o)?""!==c[1]||yt.test(o)?0:s:s.firstChild)&&o.childNodes.length;r--;)xt.nodeName(u=o.childNodes[r],"tbody")&&!u.childNodes.length&&o.removeChild(u);for(xt.merge(f,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=d.lastChild}else f.push(e.createTextNode(o));for(s&&d.removeChild(s),xt.support.appendChecked||xt.grep(Nt(f,"input"),Ft),p=0;o=f[p++];)if((!i||-1===xt.inArray(o,i))&&(a=xt.contains(o.ownerDocument,o),s=Nt(d.appendChild(o),"script"),a&&Ot(s),n))for(r=0;o=s[r++];)Ct.test(o.type||"")&&n.push(o);return s=null,d},cleanData:function(t,e){for(var n,i,r,o,a=0,s=xt.expando,l=xt.cache,u=xt.support.deleteExpando,c=xt.event.special;null!=(n=t[a]);a++)if((e||xt.acceptData(n))&&(o=(r=n[s])&&l[r])){if(o.events)for(i in o.events)c[i]?xt.event.remove(n,i):xt.removeEvent(n,i,o.handle);l[r]&&(delete l[r],u?delete n[s]:typeof n.removeAttribute!==v?n.removeAttribute(s):n[s]=null,h.push(r))}},_evalUrl:function(t){return xt.ajax({url:t,type:"GET",dataType:"script",async:!1,global:!1,throws:!0})}}),xt.fn.extend({wrapAll:function(e){if(xt.isFunction(e))return this.each(function(t){xt(this).wrapAll(e.call(this,t))});if(this[0]){var t=xt(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var t=this;t.firstChild&&1===t.firstChild.nodeType;)t=t.firstChild;return t}).append(this)}return this},wrapInner:function(n){return xt.isFunction(n)?this.each(function(t){xt(this).wrapInner(n.call(this,t))}):this.each(function(){var t=xt(this),e=t.contents();e.length?e.wrapAll(n):t.append(n)})},wrap:function(e){var n=xt.isFunction(e);return this.each(function(t){xt(this).wrapAll(n?e.call(this,t):e)})},unwrap:function(){return this.parent().each(function(){xt.nodeName(this,"body")||xt(this).replaceWith(this.childNodes)}).end()}});var Rt,jt,Ht,zt=/alpha\([^)]*\)/i,Bt=/opacity\s*=\s*([^)]*)/,Wt=/^(top|right|bottom|left)$/,$t=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Ut=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Gt=RegExp("^([+-])=("+w+")","i"),Xt={BODY:"block"},Vt={position:"absolute",visibility:"hidden",display:"block"},Zt={letterSpacing:0,fontWeight:400},Kt=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"];function Qt(t,e){if(e in t)return e;for(var n=e.charAt(0).toUpperCase()+e.slice(1),i=e,r=Jt.length;r--;)if((e=Jt[r]+n)in t)return e;return i}function te(t,e){return t=e||t,"none"===xt.css(t,"display")||!xt.contains(t.ownerDocument,t)}function ee(t,e){for(var n,i,r,o=[],a=0,s=t.length;a").css("cssText","display:block !important")).appendTo(e.documentElement))[0].contentWindow||Rt[0].contentDocument).document).write(""),e.close(),n=ae(t,e),Rt.detach()),Xt[t]=n),n}function ae(t,e){var n=xt(e.createElement(t)).appendTo(e.body),i=xt.css(n[0],"display");return n.remove(),i}xt.fn.extend({css:function(t,e){return xt.access(this,function(t,e,n){var i,r,o={},a=0;if(xt.isArray(e)){for(r=jt(t),i=e.length;a").append(xt.parseHTML(t)).find(i):t)}).complete(n&&function(t,e){a.each(n,r||[t.responseText,e,t])}),this},xt.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(t,e){xt.fn[e]=function(t){return this.on(e,t)}}),xt.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:pe,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(fe[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Me,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":xt.parseJSON,"text xml":xt.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(t,e){return e?Ae(Ae(t,xt.ajaxSettings),e):Ae(xt.ajaxSettings,t)},ajaxPrefilter:Te(Ce),ajaxTransport:Te(ke),ajax:function(t,e){"object"==typeof t&&(e=t,t=_),e=e||{};var n,i,c,h,d,f,p,r,g=xt.ajaxSetup({},e),m=g.context||g,v=g.context&&(m.nodeType||m.jquery)?xt(m):xt.event,y=xt.Deferred(),b=xt.Callbacks("once memory"),x=g.statusCode||{},o={},a={},w=0,s="canceled",S={readyState:0,getResponseHeader:function(t){var e;if(2===w){if(!r)for(r={};e=be.exec(h);)r[e[1].toLowerCase()]=e[2];e=r[t.toLowerCase()]}return null==e?null:e},getAllResponseHeaders:function(){return 2===w?h:null},setRequestHeader:function(t,e){var n=t.toLowerCase();return w||(t=a[n]=a[n]||t,o[t]=e),this},overrideMimeType:function(t){return w||(g.mimeType=t),this},statusCode:function(t){var e;if(t)if(w<2)for(e in t)x[e]=[x[e],t[e]];else S.always(t[S.status]);return this},abort:function(t){var e=t||s;return p&&p.abort(e),l(0,e),this}};if(y.promise(S).complete=b.add,S.success=S.done,S.error=S.fail,g.url=((t||g.url||pe)+"").replace(ve,"").replace(we,fe[1]+"//"),g.type=e.method||e.type||g.method||g.type,g.dataTypes=xt.trim(g.dataType||"*").toLowerCase().match(C)||[""],null==g.crossDomain&&(n=Se.exec(g.url.toLowerCase()),g.crossDomain=!(!n||n[1]===fe[1]&&n[2]===fe[2]&&(n[3]||("http:"===n[1]?"80":"443"))===(fe[3]||("http:"===fe[1]?"80":"443")))),g.data&&g.processData&&"string"!=typeof g.data&&(g.data=xt.param(g.data,g.traditional)),De(Ce,g,e,S),2===w)return S;for(i in(f=g.global)&&0==xt.active++&&xt.event.trigger("ajaxStart"),g.type=g.type.toUpperCase(),g.hasContent=!xe.test(g.type),c=g.url,g.hasContent||(g.data&&(c=g.url+=(me.test(c)?"&":"?")+g.data,delete g.data),!1===g.cache&&(g.url=ye.test(c)?c.replace(ye,"$1_="+ge++):c+(me.test(c)?"&":"?")+"_="+ge++)),g.ifModified&&(xt.lastModified[c]&&S.setRequestHeader("If-Modified-Since",xt.lastModified[c]),xt.etag[c]&&S.setRequestHeader("If-None-Match",xt.etag[c])),(g.data&&g.hasContent&&!1!==g.contentType||e.contentType)&&S.setRequestHeader("Content-Type",g.contentType),S.setRequestHeader("Accept",g.dataTypes[0]&&g.accepts[g.dataTypes[0]]?g.accepts[g.dataTypes[0]]+("*"!==g.dataTypes[0]?", "+Me+"; q=0.01":""):g.accepts["*"]),g.headers)S.setRequestHeader(i,g.headers[i]);if(g.beforeSend&&(!1===g.beforeSend.call(m,S,g)||2===w))return S.abort();for(i in s="abort",{success:1,error:1,complete:1})S[i](g[i]);if(p=De(ke,g,e,S)){S.readyState=1,f&&v.trigger("ajaxSend",[S,g]),g.async&&0n;n++)(t=e[n])()||e[n]!==t||e.splice(n--,1);e.length||xt.fx.stop(),Re=_},xt.fx.timer=function(t){t()&&xt.timers.push(t)&&xt.fx.start()},xt.fx.interval=13,xt.fx.start=function(){je||(je=setInterval(xt.fx.tick,xt.fx.interval))},xt.fx.stop=function(){clearInterval(je),je=null},xt.fx.speeds={slow:600,fast:200,_default:400},xt.fx.step={},xt.expr&&xt.expr.filters&&(xt.expr.filters.animated=function(e){return xt.grep(xt.timers,function(t){return e===t.elem}).length}),xt.fn.offset=function(e){if(arguments.length)return e===_?this:this.each(function(t){xt.offset.setOffset(this,e,t)});var t,n,i={top:0,left:0},r=this[0],o=r&&r.ownerDocument;return o?(t=o.documentElement,xt.contains(t,r)?(typeof r.getBoundingClientRect!==v&&(i=r.getBoundingClientRect()),n=Ve(o),{top:i.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:i.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):i):void 0},xt.offset={setOffset:function(t,e,n){var i=xt.css(t,"position");"static"===i&&(t.style.position="relative");var r,o,a=xt(t),s=a.offset(),l=xt.css(t,"top"),u=xt.css(t,"left"),c={},h={};o=("absolute"===i||"fixed"===i)&&-1this.$items.length-1||t<0?void 0:this.sliding?this.$element.one("slid",function(){e.to(t)}):n==t?this.pause().cycle():this.slide(n .panel > .in");if(e&&e.length){var n=e.data("bs.collapse");if(n&&n.transitioning)return;e.collapse("hide"),n||e.data("bs.collapse",null)}var i=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[i](0),this.transitioning=1;var r=function(){this.$element.removeClass("collapsing").addClass("in")[i]("auto"),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!u.support.transition)return r.call(this);var o=u.camelCase(["scroll",i].join("-"));this.$element.one(u.support.transition.end,u.proxy(r,this)).emulateTransitionEnd(350)[i](this.$element[0][o])}}},r.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var t=u.Event("hide.bs.collapse");if(this.$element.trigger(t),!t.isDefaultPrevented()){var e=this.dimension();this.$element[e](this.$element[e]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var n=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return u.support.transition?void this.$element[e](0).one(u.support.transition.end,u.proxy(n,this)).emulateTransitionEnd(350):n.call(this)}}},r.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var t=u.fn.collapse;u.fn.collapse=function(i){return this.each(function(){var t=u(this),e=t.data("bs.collapse"),n=u.extend({},r.DEFAULTS,t.data(),"object"==typeof i&&i);e||t.data("bs.collapse",e=new r(this,n)),"string"==typeof i&&e[i]()})},u.fn.collapse.Constructor=r,u.fn.collapse.noConflict=function(){return u.fn.collapse=t,this},u(document).on("click.bs.collapse.data-api","[data-toggle=collapse]",function(t){var e,n=u(this),i=n.attr("data-target")||t.preventDefault()||(e=n.attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,""),r=u(i),o=r.data("bs.collapse"),a=o?"toggle":n.data(),s=n.attr("data-parent"),l=s&&u(s);o&&o.transitioning||(l&&l.find('[data-toggle=collapse][data-parent="'+s+'"]').not(n).addClass("collapsed"),n[r.hasClass("in")?"addClass":"removeClass"]("collapsed")),r.collapse(a)})}(jQuery),function(a){"use strict";function r(){a(".dropdown-backdrop").remove(),a(l).each(function(t){var e=s(a(this));e.hasClass("open")&&(e.trigger(t=a.Event("hide.bs.dropdown")),t.isDefaultPrevented()||e.removeClass("open").trigger("hidden.bs.dropdown"))})}function s(t){var e=t.attr("data-target");e||(e=(e=t.attr("href"))&&/#/.test(e)&&e.replace(/.*(?=#[^\s]*$)/,""));var n=e&&a(e);return n&&n.length?n:t.parent()}function i(t){a(t).on("click.bs.dropdown",this.toggle)}var l="[data-toggle=dropdown]";i.prototype.toggle=function(t){var e=a(this);if(!e.is(".disabled, :disabled")){var n=s(e),i=n.hasClass("open");if(r(),!i){if("ontouchstart"in document.documentElement&&!n.closest(".navbar-nav").length&&a(''}),((o.prototype=r.extend({},r.fn.tooltip.Constructor.prototype)).constructor=o).prototype.getDefaults=function(){return o.DEFAULTS},o.prototype.setContent=function(){var t=this.tip(),e=this.getTitle(),n=this.getContent();t.find(".popover-title")[this.options.html?"html":"text"](e),t.find(".popover-content")[this.options.html?"html":"text"](n),t.removeClass("fade top bottom left right in"),t.find(".popover-title").html()||t.find(".popover-title").hide()},o.prototype.hasContent=function(){return this.getTitle()||this.getContent()},o.prototype.getContent=function(){var t=this.$element,e=this.options;return t.attr("data-content")||("function"==typeof e.content?e.content.call(t[0]):e.content)},o.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},o.prototype.tip=function(){return this.$tip||(this.$tip=r(this.options.template)),this.$tip};var t=r.fn.popover;r.fn.popover=function(i){return this.each(function(){var t=r(this),e=t.data("bs.popover"),n="object"==typeof i&&i;e||t.data("bs.popover",e=new o(this,n)),"string"==typeof i&&e[i]()})},r.fn.popover.Constructor=o,r.fn.popover.noConflict=function(){return r.fn.popover=t,this}}(jQuery),function(o){"use strict";function r(t,e){var n,i=o.proxy(this.process,this);this.$element=o(t).is("body")?o(window):o(t),this.$body=o("body"),this.$scrollElement=this.$element.on("scroll.bs.scroll-spy.data-api",i),this.options=o.extend({},r.DEFAULTS,e),this.selector=(this.options.target||(n=o(t).attr("href"))&&n.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.offsets=o([]),this.targets=o([]),this.activeTarget=null,this.refresh(),this.process()}r.DEFAULTS={offset:10},r.prototype.refresh=function(){var i=this.$element[0]==window?"offset":"position";this.offsets=o([]),this.targets=o([]);var r=this;this.$body.find(this.selector).map(function(){var t=o(this),e=t.data("target")||t.attr("href"),n=/^#\w/.test(e)&&o(e);return n&&n.length&&[[n[i]().top+(!o.isWindow(r.$scrollElement.get(0))&&r.$scrollElement.scrollTop()),e]]||null}).sort(function(t,e){return t[0]-e[0]}).each(function(){r.offsets.push(this[0]),r.targets.push(this[1])})},r.prototype.process=function(){var t,e=this.$scrollElement.scrollTop()+this.options.offset,n=(this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight)-this.$scrollElement.height(),i=this.offsets,r=this.targets,o=this.activeTarget;if(n<=e)return o!=(t=r.last()[0])&&this.activate(t);for(t=i.length;t--;)o!=r[t]&&e>=i[t]&&(!i[t+1]||e<=i[t+1])&&this.activate(r[t])},r.prototype.activate=function(t){this.activeTarget=t,o(this.selector).parents(".active").removeClass("active");var e=this.selector+'[data-target="'+t+'"],'+this.selector+'[href="'+t+'"]',n=o(e).parents("li").addClass("active");n.parent(".dropdown-menu").length&&(n=n.closest("li.dropdown").addClass("active")),n.trigger("activate")};var t=o.fn.scrollspy;o.fn.scrollspy=function(i){return this.each(function(){var t=o(this),e=t.data("bs.scrollspy"),n="object"==typeof i&&i;e||t.data("bs.scrollspy",e=new r(this,n)),"string"==typeof i&&e[i]()})},o.fn.scrollspy.Constructor=r,o.fn.scrollspy.noConflict=function(){return o.fn.scrollspy=t,this},o(window).on("load",function(){o('[data-spy="scroll"]').each(function(){var t=o(this);t.scrollspy(t.data())})})}(jQuery),function(a){"use strict";function i(t){this.element=a(t)}i.prototype.show=function(){var t=this.element,e=t.closest("ul:not(.dropdown-menu)"),n=t.data("target");if(n||(n=(n=t.attr("href"))&&n.replace(/.*(?=#[^\s]*$)/,"")),!t.parent("li").hasClass("active")){var i=e.find(".active:last a")[0],r=a.Event("show.bs.tab",{relatedTarget:i});if(t.trigger(r),!r.isDefaultPrevented()){var o=a(n);this.activate(t.parent("li"),e),this.activate(o,o.parent(),function(){t.trigger({type:"shown.bs.tab",relatedTarget:i})})}}},i.prototype.activate=function(t,e,n){function i(){r.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),t.addClass("active"),o?(t[0].offsetWidth,t.addClass("in")):t.removeClass("fade"),t.parent(".dropdown-menu")&&t.closest("li.dropdown").addClass("active"),n&&n()}var r=e.find("> .active"),o=n&&a.support.transition&&r.hasClass("fade");o?r.one(a.support.transition.end,i).emulateTransitionEnd(150):i(),r.removeClass("in")};var t=a.fn.tab;a.fn.tab=function(n){return this.each(function(){var t=a(this),e=t.data("bs.tab");e||t.data("bs.tab",e=new i(this)),"string"==typeof n&&e[n]()})},a.fn.tab.Constructor=i,a.fn.tab.noConflict=function(){return a.fn.tab=t,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(t){t.preventDefault(),a(this).tab("show")})}(jQuery),function(s){"use strict";var l=function(t,e){this.options=s.extend({},l.DEFAULTS,e),this.$window=s(window).on("scroll.bs.affix.data-api",s.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",s.proxy(this.checkPositionWithEventLoop,this)),this.$element=s(t),this.affixed=this.unpin=null,this.checkPosition()};l.RESET="affix affix-top affix-bottom",l.DEFAULTS={offset:0},l.prototype.checkPositionWithEventLoop=function(){setTimeout(s.proxy(this.checkPosition,this),1)},l.prototype.checkPosition=function(){if(this.$element.is(":visible")){var t=s(document).height(),e=this.$window.scrollTop(),n=this.$element.offset(),i=this.options.offset,r=i.top,o=i.bottom;"object"!=typeof i&&(o=r=i),"function"==typeof r&&(r=i.top()),"function"==typeof o&&(o=i.bottom());var a=!(null!=this.unpin&&e+this.unpin<=n.top)&&(null!=o&&n.top+this.$element.height()>=t-o?"bottom":null!=r&&e<=r&&"top");this.affixed!==a&&(this.unpin&&this.$element.css("top",""),this.affixed=a,this.unpin="bottom"==a?n.top-e:null,this.$element.removeClass(l.RESET).addClass("affix"+(a?"-"+a:"")),"bottom"==a&&this.$element.offset({top:document.body.offsetHeight-o-this.$element.height()}))}};var t=s.fn.affix;s.fn.affix=function(i){return this.each(function(){var t=s(this),e=t.data("bs.affix"),n="object"==typeof i&&i;e||t.data("bs.affix",e=new l(this,n)),"string"==typeof i&&e[i]()})},s.fn.affix.Constructor=l,s.fn.affix.noConflict=function(){return s.fn.affix=t,this},s(window).on("load",function(){s('[data-spy="affix"]').each(function(){var t=s(this),e=t.data();e.offset=e.offset||{},e.offsetBottom&&(e.offset.bottom=e.offsetBottom),e.offsetTop&&(e.offset.top=e.offsetTop),t.affix(e)})})}(jQuery),function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.moment=e()}(this,function(){"use strict";function p(){return Dt.apply(null,arguments)}function r(t){return"[object Array]"===Object.prototype.toString.call(t)}function o(t){return t instanceof Date||"[object Date]"===Object.prototype.toString.call(t)}function g(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function a(t,e){for(var n in e)g(e,n)&&(t[n]=e[n]);return g(e,"toString")&&(t.toString=e.toString),g(e,"valueOf")&&(t.valueOf=e.valueOf),t}function s(t,e,n,i){return V(t,e,n,i,!0).utc()}function m(t){return null==t._pf&&(t._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}),t._pf}function l(t){if(null==t._isValid){var e=m(t);t._isValid=!isNaN(t._d.getTime())&&e.overflow<0&&!e.empty&&!e.invalidMonth&&!e.nullInput&&!e.invalidFormat&&!e.userInvalidated,t._strict&&(t._isValid=t._isValid&&0===e.charsLeftOver&&0===e.unusedTokens.length&&void 0===e.bigHour)}return t._isValid}function u(t){var e=s(NaN);return null!=t?a(m(e),t):m(e).userInvalidated=!0,e}function c(t,e){var n,i,r;if(void 0!==e._isAMomentObject&&(t._isAMomentObject=e._isAMomentObject),void 0!==e._i&&(t._i=e._i),void 0!==e._f&&(t._f=e._f),void 0!==e._l&&(t._l=e._l),void 0!==e._strict&&(t._strict=e._strict),void 0!==e._tzm&&(t._tzm=e._tzm),void 0!==e._isUTC&&(t._isUTC=e._isUTC),void 0!==e._offset&&(t._offset=e._offset),void 0!==e._pf&&(t._pf=m(e)),void 0!==e._locale&&(t._locale=e._locale),0=e&&v(r,n,!0)>=e-1)break;e--}o++}return null}(t)}function t(t,e){var n=t.toLowerCase();Lt[n]=Lt[n+"s"]=Lt[e]=t}function S(t){return"string"==typeof t?Lt[t]||Lt[t.toLowerCase()]:void 0}function _(t){var e,n,i={};for(n in t)g(t,n)&&((e=S(n))&&(i[e]=t[n]));return i}function e(e,n){return function(t){return null!=t?(k(this,e,t),p.updateOffset(this,n),this):C(this,e)}}function C(t,e){return t._d["get"+(t._isUTC?"UTC":"")+e]()}function k(t,e,n){return t._d["set"+(t._isUTC?"UTC":"")+e](n)}function M(t,e){var n;if("object"==typeof t)for(n in t)this.set(n,t[n]);else if("function"==typeof this[t=S(t)])return this[t](e);return this}function T(t,e,n){for(var i=""+Math.abs(t),r=0<=t;i.lengthI(n[Jt],n[Qt])?te:n[ee]<0||24W(r)&&(m(t)._overflowDayOfYear=!0),n=B(r,0,t._dayOfYear),t._a[Qt]=n.getUTCMonth(),t._a[te]=n.getUTCDate()),e=0;e<3&&null==t._a[e];++e)t._a[e]=o[e]=i[e];for(;e<7;e++)t._a[e]=o[e]=null==t._a[e]?2===e?1:0:t._a[e];24===t._a[ee]&&0===t._a[ne]&&0===t._a[ie]&&0===t._a[re]&&(t._nextDay=!0,t._a[ee]=0),t._d=(t._useUTC?B:function(t,e,n,i,r,o,a){var s=new Date(t,e,n,i,r,o,a);return t<1970&&s.setFullYear(t),s}).apply(null,o),null!=t._tzm&&t._d.setUTCMinutes(t._d.getUTCMinutes()-t._tzm),t._nextDay&&(t._a[ee]=24)}}function G(t){if(t._f!==p.ISO_8601){t._a=[],m(t).empty=!0;var e,n,i,r,o,a,s,l,u,c,h=""+t._i,d=h.length,f=0;for(i=P(t._f,t._locale).match(It)||[],e=0;ethis.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},Ae.isDSTShifted=function(){if(this._a){var t=this._isUTC?s(this._a):Z(this._a);return this.isValid()&&0=this._config.preview;if(y)v.postMessage({results:i,workerId:S.WORKER_ID,finished:o});else if(O(this._config.chunk)){if(this._config.chunk(i,this._handle),this._paused)return;i=void 0,this._completeResults=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(i.data),this._completeResults.errors=this._completeResults.errors.concat(i.errors),this._completeResults.meta=i.meta),!o||!O(this._config.complete)||i&&i.meta.aborted||this._config.complete(this._completeResults,this._input),o||i&&i.meta.paused||this._nextChunk(),i}},this._sendError=function(t){O(this._config.error)?this._config.error(t):y&&this._config.error&&v.postMessage({workerId:S.WORKER_ID,error:t,finished:!1})}}function o(t){var i;(t=t||{}).chunkSize||(t.chunkSize=S.RemoteChunkSize),a.call(this,t),this._nextChunk=r?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(t){this._input=t,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(i=new XMLHttpRequest,this._config.withCredentials&&(i.withCredentials=this._config.withCredentials),r||(i.onload=f(this._chunkLoaded,this),i.onerror=f(this._chunkError,this)),i.open("GET",this._input,!r),this._config.downloadRequestHeaders){var t=this._config.downloadRequestHeaders;for(var e in t)i.setRequestHeader(e,t[e])}if(this._config.chunkSize){var n=this._start+this._config.chunkSize-1;i.setRequestHeader("Range","bytes="+this._start+"-"+n),i.setRequestHeader("If-None-Match","webkit-no-cache")}try{i.send()}catch(t){this._chunkError(t.message)}r&&0===i.status?this._chunkError():this._start+=this._config.chunkSize}},this._chunkLoaded=function(){if(4==i.readyState){if(i.status<200||400<=i.status)return void this._chunkError();this._finished=!this._config.chunkSize||this._start>function(t){var e=t.getResponseHeader("Content-Range");return null===e?-1:parseInt(e.substr(e.lastIndexOf("/")+1))}(i),this.parseChunk(i.responseText)}},this._chunkError=function(t){var e=i.statusText||t;this._sendError(e)}}function s(t){(t=t||{}).chunkSize||(t.chunkSize=S.LocalChunkSize),a.call(this,t);var i,r,o="undefined"!=typeof FileReader;this.stream=function(t){this._input=t,r=t.slice||t.webkitSlice||t.mozSlice,o?((i=new FileReader).onload=f(this._chunkLoaded,this),i.onerror=f(this._chunkError,this)):i=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount=this._input.size,this.parseChunk(t.target.result)},this._chunkError=function(){this._sendError(i.error)}}function l(t){var n;a.call(this,t=t||{}),this.stream=function(t){return n=t,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var t=this._config.chunkSize,e=t?n.substr(0,t):n;return n=t?n.substr(t):"",this._finished=!n,this.parseChunk(e)}}}function u(t){a.call(this,t=t||{});var e=[],n=!0;this.stream=function(t){this._input=t,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._nextChunk=function(){e.length?this.parseChunk(e.shift()):n=!0},this._streamData=f(function(t){try{e.push("string"==typeof t?t:t.toString(this._config.encoding)),n&&(n=!1,this.parseChunk(e.shift()))}catch(t){this._streamError(t)}},this),this._streamError=f(function(t){this._streamCleanUp(),this._sendError(t.message)},this),this._streamEnd=f(function(){this._streamCleanUp(),this._finished=!0,this._streamData("")},this),this._streamCleanUp=f(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function n(g){function o(){if(f&&u&&(a("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+S.DefaultDelimiter+"'"),u=!1),g.skipEmptyLines)for(var t=0;t=d.length?"__parsed_extra":d[n]),o=r,r=function(t){return g.dynamicTypingFunction&&void 0===g.dynamicTyping[t]&&(g.dynamicTyping[t]=g.dynamicTypingFunction(t)),!0===(g.dynamicTyping[t]||g.dynamicTyping)}(i)?"true"===o||"TRUE"===o||"false"!==o&&"FALSE"!==o&&function(t){return c.test(t)?parseFloat(t):t}(o):o,"__parsed_extra"===i?(e[i]=e[i]||[],e[i].push(r)):e[i]=r}f.data[t]=e,g.header&&(n>d.length?a("FieldMismatch","TooManyFields","Too many fields: expected "+d.length+" fields but parsed "+n,t):ng.preview?l.abort():r(f,e)}}}this.parse=function(t,e,n){if(g.newline||(g.newline=function(t){var e=(t=t.substr(0,1048576)).split("\r"),n=t.split("\n"),i=1=e.length/2?"\r\n":"\r"}(t)),u=!1,g.delimiter)O(g.delimiter)&&(g.delimiter=g.delimiter(t),f.meta.delimiter=g.delimiter);else{var i=function(t,e,n){for(var i,r,o,a=[",","\t","|",";",S.RECORD_SEP,S.UNIT_SEP],s=0;s=T)return a(!0)}else{var S=P;for(P++;;){if(-1===(S=e.indexOf(A,S+1)))return i||p.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:f.length,index:P}),t();if(S===l-1)return t(e.substring(P,S).replace(w,A));if(e[S+1]!==A){if(e[S+1]===_){g.push(e.substring(P,S).replace(w,A)),P=S+1+u,b=e.indexOf(_,P),x=e.indexOf(C,P);break}if(e.substr(S+1,c)===C){if(g.push(e.substring(P,S).replace(w,A)),o(S+1+c),b=e.indexOf(_,P),d&&(s(),E))return a();if(T&&f.length>=T)return a(!0);break}p.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:f.length,index:P}),S++}else S++}}return t()},this.abort=function(){E=!0},this.getCharIndex=function(){return P}}function c(t){var e=t.data,n=x[e.workerId],i=!1;if(e.error)n.userError(e.error,e.file);else if(e.results&&e.results.data){var r={abort:function(){i=!0,h(e.workerId,{data:[],errors:[],meta:{aborted:!0}})},pause:d,resume:d};if(O(n.userStep)){for(var o=0;o>>1;o(t[r],e)<0?n=1+r:i=r}return n},right:function(t,e,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=t.length);n>>1;0>16,255&t>>8,255&t)}function ft(t){return dt(t)+""}function pt(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function gt(t,e,n){var i,r,o,a=0,s=0,l=0;if(i=/([a-z]+)\((.*)\)/i.exec(t))switch(r=i[2].split(","),i[1]){case"hsl":return n(parseFloat(r[0]),parseFloat(r[1])/100,parseFloat(r[2])/100);case"rgb":return e(bt(r[0]),bt(r[1]),bt(r[2]))}return(o=zo.get(t))?e(o.r,o.g,o.b):(null==t||"#"!==t.charAt(0)||isNaN(o=parseInt(t.slice(1),16))||(4===t.length?(a=(3840&o)>>4,a|=a>>4,s=240&o,s|=s>>4,l=15&o,l|=l<<4):7===t.length&&(a=(16711680&o)>>16,s=(65280&o)>>8,l=255&o)),e(a,s,l))}function mt(t,e,n){var i,r,o=Math.min(t/=255,e/=255,n/=255),a=Math.max(t,e,n),s=a-o,l=(a+o)/2;return s?(r=l<.5?s/(a+o):s/(2-a-o),i=t==a?(e-n)/s+(e=Uo.t&&(Uo.f=Uo.c(t-Uo.t)),Uo=Uo.n;return t}function Mt(){for(var t,e=Bo,n=1/0;e;)e=e.f?t?t.n=e.n:Bo=e.n:(e.ti&&0M}function p(t,e,n){var i=[1,0,0],r=oe(ie(t),ie(e)),o=re(r,r),a=r[0],s=o-a*a;if(!s)return!n&&t;var l=M*o/s,u=-M*a/s,c=oe(i,r),h=se(i,l);ae(h,se(r,u));var d=c,f=re(h,d),p=re(d,d),g=f*f-p*(re(h,h)-1);if(!(g<0)){var m=Math.sqrt(g),v=se(d,(-f-m)/p);if(ae(v,h),v=ue(v),!n)return v;var y,b=t[0],x=e[0],w=t[1],S=e[1];xxo;return we(f,function(s){var l,u,c,h,d;return{lineStart:function(){h=c=!1,d=1},point:function(t,e){var n,i=[t,e],r=f(t,e),o=m?r?0:g(t,e):r?g(t+(t<0?So:-So),e):0;if(!l&&(h=c=r)&&s.lineStart(),r!==c&&(n=p(l,i),(ce(l,n)||ce(i,n))&&(i[0]+=xo,i[1]+=xo,r=f(i[0],i[1]))),r!==c)d=0,r?(s.lineStart(),n=p(i,l),s.point(n[0],n[1])):(n=p(l,i),s.point(n[0],n[1]),s.lineEnd()),l=n;else if(v&&l&&m^r){var a;o&u||!(a=p(i,l,!0))||(d=0,m?(s.lineStart(),s.point(a[0][0],a[0][1]),s.point(a[1][0],a[1][1]),s.lineEnd()):(s.point(a[1][0],a[1][1]),s.lineEnd(),s.lineStart(),s.point(a[0][0],a[0][1])))}!r||l&&ce(l,i)||s.point(i[0],i[1]),l=i,c=r,u=o},lineEnd:function(){c&&s.lineEnd(),l=null},clean:function(){return d|(h&&c)<<1}}},Ve(r,6*Mo),m?[0,-r]:[-So,r-So])}((S=+t)*Mo),r()):S},e.clipExtent=function(t){return arguments.length?(w=(_=t)?Me(t[0][0],t[0][1],t[1][0],t[1][1]):wt,r()):_},e.scale=function(t){return arguments.length?(d=+t,i()):d},e.translate=function(t){return arguments.length?(f=+t[0],p=+t[1],i()):[f,p]},e.center=function(t){return arguments.length?(g=t[0]%360*Mo,m=t[1]%360*Mo,i()):[g*To,m*To]},e.rotate=function(t){return arguments.length?(v=t[0]%360*Mo,y=t[1]%360*Mo,b=2=u)return}else o={x:m,y:l};n={x:m,y:u}}else{if(o){if(o.y=u)return}else o={x:(l-r)/i,y:l};n={x:(u-r)/i,y:u}}else{if(o){if(o.y=s)return}else o={x:a,y:i*a+r};n={x:s,y:i*s+r}}else{if(o){if(o.xxo||eo(r-n)>xo)&&(s.splice(a,0,new En((v=o.site,y=c,b=eo(i-h)o&&(r=i.slice(o,r),s[a]?s[a]+=r:s[++a]=r),(e=e[0])===(n=n[0])?s[a]?s[a]+=n:s[++a]=n:(s[++a]=null,l.push({i:a,x:$n(e,n)})),o=Va.lastIndex;return or&&(i=n,r=e);return i}function Di(t){return t.reduce(Ai,0)}function Ai(t,e){return t+e[1]}function Pi(t,e){return Ei(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Ei(t,e){for(var n=-1,i=+t[0],r=(t[1]-i)/e,o=[];++n<=e;)o[n]=r*n+i;return o}function Oi(t){return[$r.min(t),$r.max(t)]}function Li(t,e){return t.value-e.value}function Ii(t,e){var n=t._pack_next;(t._pack_next=e)._pack_prev=t,(e._pack_next=n)._pack_prev=e}function Ni(t,e){(t._pack_next=e)._pack_prev=t}function Fi(t,e){var n=e.x-t.x,i=e.y-t.y,r=t.r+e.r;return n*n+i*i<.999*r*r}function Ri(t){function e(t){c=Math.min(t.x-t.r,c),h=Math.max(t.x+t.r,h),d=Math.min(t.y-t.r,d),f=Math.max(t.y+t.r,f)}if((n=t.children)&&(u=n.length)){var n,i,r,o,a,s,l,u,c=1/0,h=-1/0,d=1/0,f=-1/0;if(n.forEach(ji),(i=n[0]).x=-i.r,i.y=0,e(i),1d)return r();var e=f[f.active];e&&(--f.count,delete f[f.active],e.event&&e.event.interrupt.call(u,u.__data__,e.index)),f.active=d,p.event&&p.event.start.call(u,u.__data__,c),p.tween.forEach(function(t,e){(e=e.call(u,u.__data__,c))&&l.push(e)}),a=p.ease,o=p.duration,$r.timer(function(){return s.c=n(t||1)?ve:n,1},0,g)}function n(t){if(f.active!==d)return 1;for(var e=t/o,n=a(e),i=l.length;0e;)r.push(i/o);else for(;(i=t+n*++a)=g.length)return f?f.call(p,t):d?t.sort(d):t;for(var e,r,o,a,s=-1,l=t.length,u=g[i++],c=new y;++s=g.length)return t;var r=[],o=e[i++];return t.forEach(function(t,e){r.push({key:t,values:n(e,i)})}),o?r.sort(function(t,e){return o(t.key,e.key)}):r}(h($r.map,t,0),0)},p.key=function(t){return g.push(t),p},p.sortKeys=function(t){return e[g.length-1]=t,p},p.sortValues=function(t){return d=t,p},p.rollup=function(t){return f=t,p},p},$r.set=function(t){var e=new f;if(t)for(var n=0,i=t.length;n=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Vo=$r.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,e){return(t=$r.round(t,Tt(t,e))).toFixed(Math.max(0,Math.min(20,Tt(t*(1+1e-15),e))))}}),Zo=$r.time={},Ko=Date;At.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){Jo.setUTCDate.apply(this._,arguments)},setDay:function(){Jo.setUTCDay.apply(this._,arguments)},setFullYear:function(){Jo.setUTCFullYear.apply(this._,arguments)},setHours:function(){Jo.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Jo.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Jo.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Jo.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Jo.setUTCSeconds.apply(this._,arguments)},setTime:function(){Jo.setTime.apply(this._,arguments)}};var Jo=Date.prototype;Zo.year=Pt(function(t){return(t=Zo.day(t)).setMonth(0,1),t},function(t,e){t.setFullYear(t.getFullYear()+e)},function(t){return t.getFullYear()}),Zo.years=Zo.year.range,Zo.years.utc=Zo.year.utc.range,Zo.day=Pt(function(t){var e=new Ko(2e3,0);return e.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),e},function(t,e){t.setDate(t.getDate()+e)},function(t){return t.getDate()-1}),Zo.days=Zo.day.range,Zo.days.utc=Zo.day.utc.range,Zo.dayOfYear=function(t){var e=Zo.year(t);return Math.floor((t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(t,n){n=7-n;var e=Zo[t]=Pt(function(t){return(t=Zo.day(t)).setDate(t.getDate()-(t.getDay()+n)%7),t},function(t,e){t.setDate(t.getDate()+7*Math.floor(e))},function(t){var e=Zo.year(t).getDay();return Math.floor((Zo.dayOfYear(t)+(e+n)%7)/7)-(e!==n)});Zo[t+"s"]=e.range,Zo[t+"s"].utc=e.utc.range,Zo[t+"OfYear"]=function(t){var e=Zo.year(t).getDay();return Math.floor((Zo.dayOfYear(t)+(e+n)%7)/7)}}),Zo.week=Zo.sunday,Zo.weeks=Zo.sunday.range,Zo.weeks.utc=Zo.sunday.utc.range,Zo.weekOfYear=Zo.sundayOfYear;var Qo={"-":"",_:" ",0:"0"},ta=/^\s*\d+/,ea=/^%/;$r.locale=function(t){return{numberFormat:function(t){var C=t.decimal,s=t.thousands,l=t.grouping,i=t.currency,k=l&&s?function(t,e){for(var n=t.length,i=[],r=0,o=l[0],a=0;0e));)o=l[r=(r+1)%l.length];return i.reverse().join(s)}:wt;return function(t){var e=Xo.exec(t),c=e[1]||" ",h=e[2]||">",d=e[3]||"-",n=e[4]||"",f=e[5],p=+e[6],g=e[7],m=e[8],v=e[9],y=1,b="",x="",w=!1,S=!0;switch(m&&(m=+m.substring(1)),(f||"0"===c&&"="===h)&&(f=c="0",h="="),v){case"n":g=!0,v="g";break;case"%":y=100,x="%",v="f";break;case"p":y=100,x="%",v="r";break;case"b":case"o":case"x":case"X":"#"===n&&(b="0"+v.toLowerCase());case"c":S=!1;case"d":w=!0,m=0;break;case"s":y=-1,v="r"}"$"===n&&(b=i[0],x=i[1]),"r"!=v||m||(v="g"),null!=m&&("g"==v?m=Math.max(1,Math.min(21,m)):("e"==v||"f"==v)&&(m=Math.max(0,Math.min(20,m)))),v=Vo.get(v)||Dt;var _=f&&g;return function(t){var e=x;if(w&&t%1)return"";var n=t<0||0===t&&1/t<0?(t=-t,"-"):"-"===d?"":d;if(y<0){var i=$r.formatPrefix(t,m);t=i.scale(t),e=i.symbol+x}else t*=y;var r,o,a=(t=v(t,m)).lastIndexOf(".");if(a<0){var s=S?t.lastIndexOf("e"):-1;o=s<0?(r=t,""):(r=t.substring(0,s),t.substring(s))}else r=t.substring(0,a),o=C+t.substring(a+1);!f&&g&&(r=k(r,1/0));var l=b.length+r.length+o.length+(_?0:n.length),u=l"===h?u+n+t:"^"===h?u.substring(0,l>>=1)+n+t+u.substring(l):n+(_?t:u+t))+e}}}(t),timeFormat:function(t){function i(s){function t(t){for(var e,n,i,r=[],o=-1,a=0;++oh(d,p)&&(p=t):h(t,p)>h(d,p)&&(d=t):d<=p?(th(d,p)&&(p=t):h(t,p)>h(d,p)&&(d=t)}else c(t,e);v=n,m=t}function t(){w.point=i}function e(){x[0]=d,x[1]=p,w.point=c,v=null}function n(t,e){if(v){var n=t-m;y+=180xo&&(d=-(p=180)),x[0]=d,x[1]=p,v=null}function h(t,e){return(e-=t)<0?e+360:e}function l(t,e){return t[0]-e[0]}function u(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:th(s[0],s[1])&&(s[1]=r[1]),h(r[0],s[1])>h(s[0],s[1])&&(s[0]=r[0])):n.push(s=r);for(var i,r,o,a=-1/0,s=(e=0,n[o=n.length-1]);e<=o;s=r,++e)r=n[e],(i=h(s[1],r[0]))>a&&(a=i,d=r[0],p=s[1])}return b=x=null,1/0===d||1/0===f?[[NaN,NaN],[NaN,NaN]]:[[d,f],[p,g]]}}(),$r.geo.centroid=function(t){ua=ca=ha=da=fa=pa=ga=ma=va=ya=ba=0,$r.geo.stream(t,xa);var e=va,n=ya,i=ba,r=e*e+n*n+i*i;return rxo?Math.atan((Math.sin(e)*(o=Math.cos(i))*Math.sin(n)-Math.sin(i)*(r=Math.cos(e))*Math.sin(t))/(r*o*a)):(e+i)/2}(a,s,t,e),r.point(l,s),r.lineEnd(),r.lineStart(),r.point(n,s),o=0),r.point(a=t,s=e),l=n},lineEnd:function(){r.lineEnd(),a=s=NaN},clean:function(){return 2-o}}},function(t,e,n,i){var r;if(null==t)r=n*ko,i.point(-So,r),i.point(0,r),i.point(So,r),i.point(So,0),i.point(So,-r),i.point(0,-r),i.point(-So,-r),i.point(-So,0),i.point(-So,r);else if(eo(t[0]-e[0])>xo){var o=t[0]xo}).map(c)).concat($r.range(Math.ceil(s/g)*g,a,g).filter(function(t){return eo(t%v)>xo}).map(h))}var n,i,r,o,a,s,l,u,c,h,d,f,p=10,g=p,m=90,v=360,y=2.5;return e.lines=function(){return t().map(function(t){return{type:"LineString",coordinates:t}})},e.outline=function(){return{type:"Polygon",coordinates:[d(o).concat(f(l).slice(1),d(r).reverse().slice(1),f(u).reverse().slice(1))]}},e.extent=function(t){return arguments.length?e.majorExtent(t).minorExtent(t):e.minorExtent()},e.majorExtent=function(t){return arguments.length?(o=+t[0][0],r=+t[1][0],u=+t[0][1],l=+t[1][1],r=a&&i.x<=l&&i.y>=s&&i.y<=u?[[a,u],[l,u],[l,s],[a,s]]:[]).point=r[e]}),o}function n(t){return t.map(function(t,e){return{x:Math.round(o(t,e)/xo)*xo,y:Math.round(a(t,e)/xo)*xo,i:e}})}var i=ln,r=un,o=i,a=r,c=Ga;return t?e(t):(e.links=function(e){return Rn(n(e)).edges.filter(function(t){return t.l&&t.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})},e.triangles=function(d){var f=[];return Rn(n(d)).cells.forEach(function(t,e){for(var n,i=t.site,r=t.edges.sort(_n),o=-1,a=r.length,s=r[a-1].edge,l=s.l===i?s.r:s.l;++ol&&(l=e.x),e.y>u&&(u=e.y),n.push(e.x),i.push(e.y);else for(r=0;r=a[0]&&i<=a[1]&&((n=r[$r.bisect(s,i,1,u)-1]).y+=c,n.push(t[e]));return r}var h=!0,d=Number,f=Oi,p=Pi;return n.value=function(t){return arguments.length?(d=t,n):d},n.range=function(t){return arguments.length?(f=xt(t),n):f},n.bins=function(e){return arguments.length?(p="number"==typeof e?function(t){return Ei(t,e)}:xt(e),n):p},n.frequency=function(t){return arguments.length?(h=!!t,n):h},n},$r.layout.pack=function(){function e(t,e){var n=u.call(this,t,e),i=n[0],r=h[0],o=h[1],a=null==l?Math.sqrt:"function"==typeof l?l:function(){return l};if(i.x=i.y=0,vi(i,function(t){t.r=+a(t.value)}),vi(i,Ri),c){var s=c*(l?1:Math.max(2*i.r/r,2*i.r/o))/2;vi(i,function(t){t.r+=s}),vi(i,Ri),vi(i,function(t){t.r-=s})}return function t(e,n,i,r){var o=e.children;if(e.x=n+=r*e.x,e.y=i+=r*e.y,e.r*=r,o)for(var a=-1,s=o.length;++aa.x&&(a=t),t.depth>s.depth&&(s=t)});var l=b(o,a)/2-o.x,u=g[0]/(a.x+b(a,o)/2+l),c=g[1]/(s.depth||1);mi(i,function(t){t.x=(t.x+l)*u,t.y=t.depth*c})}return n}function h(t){var e=t.children,n=t.parent.children,i=t.i?n[t.i-1]:null;if(e.length){!function(t){for(var e,n=0,i=0,r=t.children,o=r.length;0<=--o;)(e=r[o]).z+=n,e.m+=n,n+=e.s+(i+=e.c)}(t);var r=(e[0].z+e[e.length-1].z)/2;i?(t.z=i.z+b(t._,i._),t.m=t.z-r):t.z=r}else i&&(t.z=i.z+b(t._,i._));t.parent.A=function(t,e,n){if(e){for(var i,r=t,o=t,a=e,s=r.parent.children[0],l=r.m,u=o.m,c=a.m,h=s.m;a=$i(a),r=Wi(r),a&&r;)s=Wi(s),(o=$i(o)).a=t,0<(i=a.z+c-r.z-l+b(a._,r._))&&(v=t,y=n,d=(m=a).a.parent===v.parent?m.a:y,void 0,g=(p=i)/((f=t).i-d.i),f.c-=g,f.s+=p,d.c+=g,f.z+=p,f.m+=p,l+=i,u+=i),c+=a.m,l+=r.m,h+=s.m,u+=o.m;a&&!$i(o)&&(o.t=a,o.m+=c-u),r&&!Wi(s)&&(s.t=r,s.m+=l-h,n=t)}var d,f,p,g;var m,v,y;return n}(t,i,t.parent.A||n[0])}function d(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function f(t){t.x*=g[0],t.y=t.depth*g[1]}var p=$r.layout.hierarchy().sort(null).value(null),b=Bi,g=[1,1],m=null;return e.separation=function(t){return arguments.length?(b=t,e):b},e.size=function(t){return arguments.length?(m=null==(g=t)?f:null,e):m?null:g},e.nodeSize=function(t){return arguments.length?(m=null==(g=t)?null:f,e):m?g:null},gi(e,p)},$r.layout.cluster=function(){function e(t,e){var n,i=c.call(this,t,e),r=i[0],o=0;vi(r,function(t){var e=t.children;e&&e.length?(t.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(e),t.y=function(t){return 1+$r.max(t,function(t){return t.y})}(e)):(t.x=n?o+=h(t,n):0,t.y=0,n=t)});var a=function t(e){var n=e.children;return n&&n.length?t(n[0]):e}(r),s=function t(e){var n,i=e.children;return i&&(n=i.length)?t(i[n-1]):e}(r),l=a.x-h(a,s)/2,u=s.x+h(s,a)/2;return vi(r,f?function(t){t.x=(t.x-r.x)*d[0],t.y=(r.y-t.y)*d[1]}:function(t){t.x=(t.x-l)/(u-l)*d[0],t.y=(1-(r.y?t.y/r.y:1))*d[1]}),i}var c=$r.layout.hierarchy().sort(null).value(null),h=Bi,d=[1,1],f=!1;return e.separation=function(t){return arguments.length?(h=t,e):h},e.size=function(t){return arguments.length?(f=null==(d=t),e):f?null:d},e.nodeSize=function(t){return arguments.length?(f=null!=(d=t),e):f?d:null},gi(e,c)},$r.layout.treemap=function(){function c(t,e){for(var n,i,r=-1,o=t.length;++rn.dy)&&(u=n.dy);++on.dx)&&(u=n.dx);++oi;o--);e=e.slice(r,o)}return e},o.tickFormat=function(t,e){if(!arguments.length)return ls;arguments.length<2?e=ls:"function"!=typeof e&&(e=$r.format(e));var n,i=Math.max(.1,t/o.ticks().length),r=u?(n=1e-12,Math.ceil):(n=-1e-12,Math.floor);return function(t){return t/d(r(h(t)+n))<=i?e(t):""}},o.copy=function(){return t(e.copy(),l,u,c)},Ki(o,e)}($r.scale.linear().domain([0,1]),10,!0,[1,10])};var ls=$r.format(".0e"),us={floor:function(t){return-Math.ceil(-t)},ceil:function(t){return-Math.floor(-t)}};$r.scale.pow=function(){return function t(e,n,i){function r(t){return e(o(t))}var o=ir(n),a=ir(1/n);return r.invert=function(t){return a(e.invert(t))},r.domain=function(t){return arguments.length?(e.domain((i=t.map(Number)).map(o)),r):i},r.ticks=function(t){return tr(i,t)},r.tickFormat=function(t,e){return er(i,t,e)},r.nice=function(t){return r.domain(Ji(i,t))},r.exponent=function(t){return arguments.length?(o=ir(n=t),a=ir(1/n),e.domain(i.map(o)),r):n},r.copy=function(){return t(e.copy(),n,i)},Ki(r,e)}($r.scale.linear(),1,[0,1])},$r.scale.sqrt=function(){return $r.scale.pow().exponent(.5)},$r.scale.ordinal=function(){return function t(s,l){function u(t){return h[((r.get(t)||("range"===l.t?r.set(t,s.push(t)):NaN))-1)%h.length]}function c(e,n){return $r.range(s.length).map(function(t){return e+n*t})}var r,h,d;return u.domain=function(t){if(!arguments.length)return s;s=[],r=new y;for(var e,n=-1,i=t.length;++nrect,.s>rect").attr("width",T[1]-T[0])}function w(t){t.select(".extent").attr("y",D[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",D[1]-D[0])}function a(){function t(){var t=$r.mouse(r),e=!1;i&&(t[0]+=i[0],t[1]+=i[1]),d||($r.event.altKey?(h||(h=[(T[0]+T[1])/2,(D[0]+D[1])/2]),p[0]=T[+(t[0]o;++o)if(r===s(e[o])){i=e[0],e[0]=e[o],e[o]=i;break}return e})}}function r(t,e){var n={type:"Feature",id:e.id,properties:e.properties||{},geometry:o(t,e)};return null==e.id&&delete n.id,n}function o(t,e){function r(t,e){e.length&&e.pop();for(var n,i=l[t<0?~t:t],r=0,o=i.length;r>>1;t[r]>1)-1,i=a[n];if(0<=h(t,i))break;a[i._=e]=i,a[t._=e=n]=t}}function r(t,e){for(;;){var n=e+1<<1,i=n-1,r=e,o=a[r];if(i"+n),this.options.fills){if("defaultFill"===r){if(!e.defaultFillName)continue;i=e.defaultFillName}else i=e.labels&&e.labels[r]?e.labels[r]:r+": ";n+="
        "+i+"
        ",n+='
         
        '}n+="",h.select(this.options.element).append("div").attr("class","datamaps-legend").html(n)}}function n(){var t=h.geo.graticule();this.svg.insert("path",".datamaps-subunits").datum(t).attr("class","datamaps-graticule").attr("d",this.path)}function i(t,e,a){var s=this;if(this.svg,!e||e&&!e.slice)throw"Datamaps Error - arcs must be an array";for(var n=0;n'+t.properties.name+""},popupOnHover:!0,highlightOnHover:!0,highlightFillColor:"#FC8D59",highlightBorderColor:"rgba(250, 15, 160, 0.2)",highlightBorderWidth:2},projectionConfig:{rotation:[97,0]},bubblesConfig:{borderWidth:2,borderColor:"#FFFFFF",popupOnHover:!0,radius:null,popupTemplate:function(t,e){return'
        '+e.name+"
        "},fillOpacity:.75,animate:!0,highlightOnHover:!0,highlightFillColor:"#FC8D59",highlightBorderColor:"rgba(250, 15, 160, 0.2)",highlightBorderWidth:2,highlightFillOpacity:.85,exitDelay:100},arcConfig:{strokeColor:"#DD1C77",strokeWidth:1,arcSharpness:1,animationSpeed:600}};l.prototype.resize=function(){var t=this.options;if(t.responsive){var e="-webkit-transform"in document.body.style?"-webkit-":"-moz-transform"in document.body.style?"-moz-":"-ms-transform"in document.body.style?"-ms-":"",n=t.element.clientWidth,i=h.select(t.element).select("svg").attr("data-width");h.select(t.element).select("svg").selectAll("g").style(e+"transform","scale("+n/i+")")}},l.prototype.draw=function(){function n(t){i.options.dataUrl&&h[i.options.dataType](i.options.dataUrl,function(t){if("csv"===i.options.dataType&&t&&t.slice){for(var e={},n=0;n").css({position:"fixed",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(O("
        ").css({position:"absolute",top:1,left:1,width:100,overflow:"scroll"}).append(O("
        ").css({width:"100%",height:10}))).appendTo("body"),i=n.children(),r=i.children();e.barWidth=i[0].offsetWidth-i[0].clientWidth,e.bScrollOversize=100===r[0].offsetWidth&&100!==i[0].clientWidth,e.bScrollbarLeft=1!==Math.round(r.offset().left),e.bBounding=!!n[0].getBoundingClientRect().width,n.remove()}O.extend(t.oBrowser,Jt.__browser),t.oScroll.iBarWidth=Jt.__browser.barWidth}function n(t,e,n,i,r,o){var a,s=!1;for(n!==L&&(a=n,s=!0);i!==r;)t.hasOwnProperty(i)&&(a=s?e(a,t[i],i,t):t[i],s=!0,i+=o);return a}function C(t,e){var n=Jt.defaults.column,i=t.aoColumns.length;n=O.extend({},Jt.models.oColumn,n,{nTh:e||y.createElement("th"),sTitle:n.sTitle?n.sTitle:e?e.innerHTML:"",aDataSort:n.aDataSort?n.aDataSort:[i],mData:n.mData?n.mData:i,idx:i});t.aoColumns.push(n),(n=t.aoPreSearchCols)[i]=O.extend({},Jt.models.oSearch,n[i]),k(t,i,O(e).data())}function k(t,e,n){e=t.aoColumns[e];var i=t.oClasses,r=O(e.nTh);if(!e.sWidthOrig){e.sWidthOrig=r.attr("width")||null;var o=(r.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);o&&(e.sWidthOrig=o[1])}n!==L&&null!==n&&(S(n),b(Jt.defaults.column,n),n.mDataProp!==L&&!n.mData&&(n.mData=n.mDataProp),n.sType&&(e._sManualType=n.sType),n.className&&!n.sClass&&(n.sClass=n.className),O.extend(e,n),It(e,n,"sWidth","sWidthOrig"),n.iDataSort!==L&&(e.aDataSort=[n.iDataSort]),It(e,n,"aDataSort"));var a=e.mData,s=F(a),l=e.mRender?F(e.mRender):null;n=function(t){return"string"==typeof t&&-1!==t.indexOf("@")};e._bAttrSrc=O.isPlainObject(a)&&(n(a.sort)||n(a.type)||n(a.filter)),e._setter=null,e.fnGetData=function(t,e,n){var i=s(t,e,L,n);return l&&e?l(i,e,t,n):i},e.fnSetData=function(t,e,n){return p(a)(t,e,n)},"number"!=typeof a&&(t._rowReadObject=!0),t.oFeatures.bSort||(e.bSortable=!1,r.addClass(i.sSortableNone)),t=-1!==O.inArray("asc",e.asSorting),n=-1!==O.inArray("desc",e.asSorting),e.bSortable&&(t||n)?t&&!n?(e.sSortingClass=i.sSortableAsc,e.sSortingClassJUI=i.sSortJUIAscAllowed):!t&&n?(e.sSortingClass=i.sSortableDesc,e.sSortingClassJUI=i.sSortJUIDescAllowed):(e.sSortingClass=i.sSortable,e.sSortingClassJUI=i.sSortJUI):(e.sSortingClass=i.sSortableNone,e.sSortingClassJUI="")}function I(t){if(!1!==t.oFeatures.bAutoWidth){var e=t.aoColumns;vt(t);for(var n=0,i=e.length;ne&&t[r]--;-1!=i&&n===L&&t.splice(i,1)}function r(n,i,t,e){var r,o=n.aoData[i],a=function(t,e){for(;t.childNodes.length;)t.removeChild(t.firstChild);t.innerHTML=E(n,i,e,"display")};if("dom"!==t&&(t&&"auto"!==t||"dom"!==o.src)){var s=o.anCells;if(s)if(e!==L)a(s[e],e);else for(t=0,r=s.length;t").appendTo(a)),e=0,n=c.length;etr").attr("role","row"),O(a).find(">tr>th, >tr>td").addClass(u.sHeaderTH),O(s).find(">tr>th, >tr>td").addClass(u.sFooterTH),null!==s)for(e=0,n=(t=t.aoFooter[0]).length;e=t.fnRecordsDisplay()?0:a,t.iInitDisplayStart=-1);a=t._iDisplayStart;var u=t.fnDisplayEnd();if(t.bDeferLoading)t.bDeferLoading=!1,t.iDraw++,ft(t,!1);else if(s){if(!t.bDestroying&&!q(t))return}else t.iDraw++;if(0!==l.length)for(o=s?t.aoData.length:u,s=s?0:a;s",{class:r?i[0]:""}).append(O("
        ").appendTo(this)),u.nTBody=t[0],0===(t=a.children("tfoot")).length&&0").appendTo(this)),0===t.length||0===t.children().length?a.addClass(i.sNoFooter):0t?new te(e[t],this[t]):null},filter:function(t){var e=[];if(be.filter)e=be.filter.call(this,t,this);else for(var n=0,i=this.length;n").addClass(e),O("td",n).addClass(e).html(t)[0].colSpan=M(r),o.push(n[0]))};a(t,e),n._details&&n._details.remove(),n._details=O(o),n._detailsShow&&n._details.insertAfter(n.nTr)}return this}),ee(["row().child.show()","row().child().show()"],function(){return Me(this,!0),this}),ee(["row().child.hide()","row().child().hide()"],function(){return Me(this,!1),this}),ee(["row().child.remove()","row().child().remove()"],function(){return ke(this),this}),ee("row().child.isShown()",function(){var t=this.context;return t.length&&this.length&&t[0].aoData[this[0]]._detailsShow||!1});function Te(t,e,n,i,r){n=[],i=0;for(var o=r.length;i").appendTo(t),v(o,a);else{switch(h=null,d="",a){case"ellipsis":t.append('');break;case"first":h=p.sFirst,d=a+(0",{class:f.sPageButton+" "+d,"aria-controls":s.sTableId,"aria-label":g[a],"data-dt-idx":m,tabindex:s.iTabIndex,id:0===l&&"string"==typeof a?s.sTableId+"_"+a:null}).html(h).appendTo(t),{action:a},n),m++)}};try{n=O(t).find(y.activeElement).data("dt-idx")}catch(t){}v(O(t).empty(),e),n&&O(t).find("[data-dt-idx="+n+"]").focus()}}}),O.extend(Jt.ext.type.detect,[function(t,e){var n=e.oLanguage.sDecimal;return Gt(t,n)?"num"+n:null},function(t){if(t&&!(t instanceof Date)&&(!ae.test(t)||!se.test(t)))return null;var e=Date.parse(t);return null!==e&&!isNaN(e)||qt(t)?"date":null},function(t,e){var n=e.oLanguage.sDecimal;return Gt(t,n,!0)?"num-fmt"+n:null},function(t,e){var n=e.oLanguage.sDecimal;return Xt(t,n)?"html-num"+n:null},function(t,e){var n=e.oLanguage.sDecimal;return Xt(t,n,!0)?"html-num-fmt"+n:null},function(t){return qt(t)||"string"==typeof t&&-1!==t.indexOf("<")?"html":null}]),O.extend(Jt.ext.type.search,{html:function(t){return qt(t)?t:"string"==typeof t?t.replace(re," ").replace(oe,""):""},string:function(t){return qt(t)?t:"string"==typeof t?t.replace(re," "):t}});var Le=function(t,e,n,i){return 0===t||t&&"-"!==t?(e&&(t=Yt(t,e)),t.replace&&(n&&(t=t.replace(n,"")),i&&(t=t.replace(i,""))),1*t):-1/0};O.extend(Qt.type.order,{"date-pre":function(t){return Date.parse(t)||0},"html-pre":function(t){return qt(t)?"":t.replace?t.replace(/<.*?>/g,"").toLowerCase():t+""},"string-pre":function(t){return qt(t)?"":"string"==typeof t?t.toLowerCase():t.toString?t.toString():""},"string-asc":function(t,e){return t").addClass(s.sSortJUIWrapper).append(o.contents()).append(O("").addClass(s.sSortIcon+" "+a.sSortingClassJUI)).appendTo(o),O(r.nTable).on("order.dt.DT",function(t,e,n,i){r===e&&(t=a.idx,o.removeClass(s.sSortAsc+" "+s.sSortDesc).addClass("asc"==i[t]?s.sSortAsc:"desc"==i[t]?s.sSortDesc:a.sSortingClass),o.find("span."+s.sSortIcon).removeClass(s.sSortJUIAsc+" "+s.sSortJUIDesc+" "+s.sSortJUI+" "+s.sSortJUIAscAllowed+" "+s.sSortJUIDescAllowed).addClass("asc"==i[t]?s.sSortJUIAsc:"desc"==i[t]?s.sSortJUIDesc:a.sSortingClassJUI))})}}});function Ie(t){return"string"==typeof t?t.replace(//g,">").replace(/"/g,"""):t}return Jt.render={number:function(i,r,o,a,s){return{display:function(t){if("number"!=typeof t&&"string"!=typeof t)return t;var e=t<0?"-":"",n=parseFloat(t);return isNaN(n)?Ie(t):(t=Math.abs(n),n=parseInt(t,10),t=o?r+(t-n).toFixed(o).substring(2):"",e+(a||"")+n.toString().replace(/\B(?=(\d{3})+(?!\d))/g,i)+t+(s||""))}}},text:function(){return{display:Ie}}},O.extend(Jt.ext.internal,{_fnExternApiFunc:e,_fnBuildAjax:$,_fnAjaxUpdate:q,_fnAjaxParameters:t,_fnAjaxUpdateDraw:U,_fnAjaxDataSrc:Y,_fnAddColumn:C,_fnColumnOptions:k,_fnAdjustColumnSizing:I,_fnVisibleToColumnIndex:N,_fnColumnIndexToVisible:u,_fnVisbleColumns:M,_fnGetColumns:T,_fnColumnTypes:a,_fnApplyColumnDefs:D,_fnHungarianMap:o,_fnCamelToHungarian:b,_fnLanguageCompat:x,_fnBrowserDetect:_,_fnAddData:A,_fnAddTr:P,_fnNodeToDataIndex:function(t,e){return e._DT_RowIndex!==L?e._DT_RowIndex:null},_fnNodeToColumnIndex:function(t,e,n){return O.inArray(n,t.aoData[e].anCells)},_fnGetCellData:E,_fnSetCellData:i,_fnSplitObjNotation:c,_fnGetObjectDataFn:F,_fnSetObjectDataFn:p,_fnGetDataMaster:f,_fnClearTable:s,_fnDeleteIndex:h,_fnInvalidate:r,_fnGetRowElements:l,_fnCreateTr:g,_fnBuildHead:m,_fnDrawHead:R,_fnDraw:j,_fnReDraw:H,_fnAddOptionsHtml:z,_fnDetectHeader:B,_fnGetUniqueThs:W,_fnFeatureHtmlFilter:G,_fnFilterComplete:X,_fnFilterCustom:V,_fnFilterColumn:Z,_fnFilter:K,_fnFilterCreateSearch:J,_fnEscapeRegex:Q,_fnFilterData:tt,_fnFeatureHtmlInfo:it,_fnUpdateInfo:rt,_fnInfoMacros:ot,_fnInitialise:at,_fnInitComplete:st,_fnLengthChange:lt,_fnFeatureHtmlLength:ut,_fnFeatureHtmlPaginate:ct,_fnPageChange:ht,_fnFeatureHtmlProcessing:dt,_fnProcessingDisplay:ft,_fnFeatureHtmlTable:pt,_fnScrollDraw:gt,_fnApplyToChildren:mt,_fnCalculateColumnWidths:vt,_fnThrottle:yt,_fnConvertToWidth:bt,_fnGetWidestNode:xt,_fnGetMaxLenString:wt,_fnStringToCss:St,_fnSortFlatten:_t,_fnSort:Ct,_fnSortAria:kt,_fnSortListener:Mt,_fnSortAttachListener:Tt,_fnSortingClasses:Dt,_fnSortData:At,_fnSaveState:Pt,_fnLoadState:Et,_fnSettingsFromNode:Ot,_fnLog:Lt,_fnMap:It,_fnBindAction:Ft,_fnCallbackReg:Rt,_fnCallbackFire:jt,_fnLengthOverflow:Ht,_fnRenderer:zt,_fnDataSource:Bt,_fnRowAttributes:d,_fnCalculateEnd:function(){}}),((O.fn.dataTable=Jt).$=O).fn.dataTableSettings=Jt.settings,O.fn.dataTableExt=Jt.ext,O.fn.DataTable=function(t){return O(this).dataTable(t).api()},O.each(Jt,function(t,e){O.fn.DataTable[t]=e}),O.fn.dataTable}),function(n){"function"==typeof define&&define.amd?define(["jquery","datatables.net"],function(t){return n(t,window,document)}):"object"==typeof exports?module.exports=function(t,e){return t||(t=window),e&&e.fn.dataTable||(e=require("datatables.net")(t,e).$),n(e,t,t.document)}:n(jQuery,window,document)}(function(b,t,i,e){"use strict";var r=b.fn.dataTable;return b.extend(!0,r.defaults,{dom:"<'row'<'col-sm-6'l><'col-sm-6'f>><'row'<'col-sm-12'tr>><'row'<'col-sm-5'i><'col-sm-7'p>>",renderer:"bootstrap"}),b.extend(r.ext.classes,{sWrapper:"dataTables_wrapper form-inline dt-bootstrap",sFilterInput:"form-control input-sm",sLengthSelect:"form-control input-sm",sProcessing:"dataTables_processing panel panel-default"}),r.ext.renderer.pageButton.bootstrap=function(s,t,l,e,u,c){var h,d,n,f=new r.Api(s),p=s.oClasses,g=s.oLanguage.oPaginate,m=s.oLanguage.oAria.paginate||{},v=0,y=function(t,e){function n(t){t.preventDefault(),b(t.currentTarget).hasClass("disabled")||f.page()==t.data.action||f.page(t.data.action).draw("page")}var i,r,o,a;for(i=0,r=e.length;i",{class:p.sPageButton+" "+d,id:0===l&&"string"==typeof a?s.sTableId+"_"+a:null}).append(b("",{href:"#","aria-controls":s.sTableId,"aria-label":m[a],"data-dt-idx":v,tabindex:s.iTabIndex}).html(h)).appendTo(t),s.oApi._fnBindAction(o,{action:a},n),v++)}};try{n=b(t).find(i.activeElement).data("dt-idx")}catch(t){}y(b(t).empty().html('
        ",{valign:"top",colSpan:M(t),class:t.oClasses.sRowEmpty}).html(n))[0];jt(t,"aoHeaderCallback","header",[O(t.nTHead).children("tr")[0],f(t),a,u,l]),jt(t,"aoFooterCallback","footer",[O(t.nTFoot).children("tr")[0],f(t),a,u,l]),(i=O(t.nTBody)).children().detach(),i.append(O(e)),jt(t,"aoDrawCallback","draw",[t]),t.bSorted=!1,t.bFiltered=!1,t.bDrawing=!1}}function H(t,e){var n=t.oFeatures,i=n.bFilter;n.bSort&&Ct(t),i?X(t,t.oPreviousSearch):t.aiDisplay=t.aiDisplayMaster.slice(),!0!==e&&(t._iDisplayStart=0),t._drawHold=e,j(t),t._drawHold=!1}function z(t){var e=t.oClasses,n=O(t.nTable),i=(n=O("
        ").insertBefore(n),t.oFeatures),r=O("
        ",{id:t.sTableId+"_wrapper",class:e.sWrapper+(t.nTFoot?"":" "+e.sNoFooter)});t.nHolding=n[0],t.nTableWrapper=r[0],t.nTableReinsertBefore=t.nTable.nextSibling;for(var o,a,s,l,u,c,h=t.sDom.split(""),d=0;d")[0],"'"==(l=h[d+1])||'"'==l){for(u="",c=2;h[d+c]!=l;)u+=h[d+c],c++;"H"==u?u=e.sJUIHeader:"F"==u&&(u=e.sJUIFooter),-1!=u.indexOf(".")?(l=u.split("."),s.id=l[0].substr(1,l[0].length-1),s.className=l[1]):"#"==u.charAt(0)?s.id=u.substr(1,u.length-1):s.className=u,d+=c}r.append(s),r=O(s)}else if(">"==a)r=r.parent();else if("l"==a&&i.bPaginate&&i.bLengthChange)o=ut(t);else if("f"==a&&i.bFilter)o=G(t);else if("r"==a&&i.bProcessing)o=dt(t);else if("t"==a)o=pt(t);else if("i"==a&&i.bInfo)o=it(t);else if("p"==a&&i.bPaginate)o=ct(t);else if(0!==Jt.ext.feature.length)for(c=0,l=(s=Jt.ext.feature).length;c',s=(s=i.sSearch).match(/_INPUT_/)?s.replace("_INPUT_",a):s+a,l=(t=O("
        ",{id:o.f?null:e+"_filter",class:t.sFilter}).append(O("
        ").addClass(t.sLength);return i.aanFeatures.l||(l[0].id=e+"_length"),l.children().append(i.oLanguage.sLengthMenu.replace("_MENU_",o[0].outerHTML)),O("select",l).val(i._iDisplayLength).bind("change.DT",function(){lt(i,O(this).val()),j(i)}),O(i.nTable).bind("length.dt.DT",function(t,e,n){i===e&&O("select",l).val(n)}),l[0]}function ct(t){function a(t){j(t)}var e=t.sPaginationType,s=Jt.ext.pager[e],l="function"==typeof s,u=(e=O("
        ").addClass(t.oClasses.sPaging+e)[0],t.aanFeatures);return l||s.fnInit(t,e,a),u.p||(e.id=t.sTableId+"_paginate",t.aoDrawCallback.push({fn:function(t){if(l){var e,n=t._iDisplayStart,i=t._iDisplayLength,r=t.fnRecordsDisplay(),o=(n=(o=-1===i)?0:Math.ceil(n/i),i=o?1:Math.ceil(r/i),r=s(n,i),0);for(e=u.p.length;o",{id:t.aanFeatures.r?null:t.sTableId+"_processing",class:t.oClasses.sProcessing}).html(t.oLanguage.sProcessing).insertBefore(t.nTable)[0]}function ft(t,e){t.oFeatures.bProcessing&&O(t.aanFeatures.r).css("display",e?"block":"none"),jt(t,null,"processing",[t,e])}function pt(t){(c=O(t.nTable)).attr("role","grid");var e=t.oScroll;if(""===e.sX&&""===e.sY)return t.nTable;var n=e.sX,i=e.sY,r=t.oClasses,o=c.children("caption"),a=o.length?o[0]._captionSide:null,s=O(c[0].cloneNode(!1)),l=O(c[0].cloneNode(!1)),u=c.children("tfoot");u.length||(u=null),s=O("
        ",{class:r.sScrollWrapper}).append(O("
        ",{class:r.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,width:n?n?St(n):null:"100%"}).append(O("
        ",{class:r.sScrollHeadInner}).css({"box-sizing":"content-box",width:e.sXInner||"100%"}).append(s.removeAttr("id").css("margin-left",0).append("top"===a?o:null).append(c.children("thead"))))).append(O("
        ",{class:r.sScrollBody}).css({position:"relative",overflow:"auto",width:n?St(n):null}).append(c)),u&&s.append(O("
        ",{class:r.sScrollFoot}).css({overflow:"hidden",border:0,width:n?n?St(n):null:"100%"}).append(O("
        ",{class:r.sScrollFootInner}).append(l.removeAttr("id").css("margin-left",0).append("bottom"===a?o:null).append(c.children("tfoot")))));var c,h=(c=s.children())[0],d=(r=c[1],u?c[2]:null);return n&&O(r).on("scroll.DT",function(){var t=this.scrollLeft;h.scrollLeft=t,u&&(d.scrollLeft=t)}),O(r).css(i&&e.bCollapse?"max-height":"height",i),t.nScrollHead=h,t.nScrollBody=r,t.nScrollFoot=d,t.aoDrawCallback.push({fn:gt,sName:"scrolling"}),s[0]}function gt(n){function t(t){(t=t.style).paddingTop="0",t.paddingBottom="0",t.borderTopWidth="0",t.borderBottomWidth="0",t.height=0}var e,i,r,o,a,s=(c=n.oScroll).sX,l=c.sXInner,u=c.sY,c=c.iBarWidth,h=O(n.nScrollHead),d=h[0].style,f=(g=h.children("div"))[0].style,p=g.children("table"),g=n.nScrollBody,m=O(g),v=g.style,y=O(n.nScrollFoot).children("div"),b=y.children("table"),x=O(n.nTHead),w=O(n.nTable),S=w[0],_=S.style,C=n.nTFoot?O(n.nTFoot):null,k=n.oBrowser,M=k.bScrollOversize,T=ce(n.aoColumns,"nTh"),D=[],A=[],P=[],E=[];i=g.scrollHeight>g.clientHeight,n.scrollBarVis!==i&&n.scrollBarVis!==L?(n.scrollBarVis=i,I(n)):(n.scrollBarVis=i,w.children("thead, tfoot").remove(),C&&(r=C.clone().prependTo(w),e=C.find("tr"),r=r.find("tr")),o=x.clone().prependTo(w),x=x.find("tr"),i=o.find("tr"),o.find("th, td").removeAttr("tabindex"),s||(v.width="100%",h[0].style.width="100%"),O.each(W(n,o),function(t,e){a=N(n,t),e.style.width=n.aoColumns[a].sWidth}),C&&mt(function(t){t.style.width=""},r),h=w.outerWidth(),""===s?(_.width="100%",M&&(w.find("tbody").height()>g.offsetHeight||"scroll"==m.css("overflow-y"))&&(_.width=St(w.outerWidth()-c)),h=w.outerWidth()):""!==l&&(_.width=St(l),h=w.outerWidth()),mt(t,i),mt(function(t){P.push(t.innerHTML),D.push(St(O(t).css("width")))},i),mt(function(t,e){-1!==O.inArray(t,T)&&(t.style.width=D[e])},x),O(i).height(0),C&&(mt(t,r),mt(function(t){E.push(t.innerHTML),A.push(St(O(t).css("width")))},r),mt(function(t,e){t.style.width=A[e]},e),O(r).height(0)),mt(function(t,e){t.innerHTML='
        '+P[e]+"
        ",t.style.width=D[e]},i),C&&mt(function(t,e){t.innerHTML='
        '+E[e]+"
        ",t.style.width=A[e]},r),w.outerWidth()g.offsetHeight||"scroll"==m.css("overflow-y")?h+c:h,M&&(g.scrollHeight>g.offsetHeight||"scroll"==m.css("overflow-y"))&&(_.width=St(e-c)),(""===s||""!==l)&&Lt(n,1,"Possible column misalignment",6)):e="100%",v.width=St(e),d.width=St(e),C&&(n.nScrollFoot.style.width=St(e)),!u&&M&&(v.height=St(S.offsetHeight+c)),s=w.outerWidth(),p[0].style.width=St(s),f.width=St(s),l=w.height()>g.clientHeight||"scroll"==m.css("overflow-y"),f[u="padding"+(k.bScrollbarLeft?"Left":"Right")]=l?c+"px":"0px",C&&(b[0].style.width=St(s),y[0].style.width=St(s),y[0].style[u]=l?c+"px":"0px"),w.children("colgroup").insertBefore(w.children("thead")),m.scroll(),!n.bSorted&&!n.bFiltered||n._drawHold||(g.scrollTop=0))}function mt(t,e,n){for(var i,r,o=0,a=0,s=e.length;a").appendTo(l.find("tbody"));for(l.find("thead, tfoot").remove(),l.append(O(t.nTHead).clone()).append(O(t.nTFoot).clone()),l.find("tfoot th, tfoot td").css("width",""),c=W(t,l.find("thead")[0]),e=0;e").css({width:n.sWidthOrig,margin:0,padding:0,border:0,height:1}));if(t.aoData.length)for(e=0;e").css(a||o?{position:"absolute",top:0,left:0,height:1,right:0,overflow:"hidden"}:{}).append(l).appendTo(d),a&&s?l.width(s):a?(l.css("width","auto"),l.removeAttr("width"),l.width()").css("width",St(t)).appendTo(e||y.body),i=n[0].offsetWidth;return n.remove(),i}function xt(t,e){var n=wt(t,e);if(n<0)return null;var i=t.aoData[n];return i.nTr?i.anCells[e]:O("
        ").html(E(t,n,e,"display"))[0]}function wt(t,e){for(var n,i=-1,r=-1,o=0,a=t.aoData.length;oi&&(i=n.length,r=o);return r}function St(t){return null===t?"0px":"number"==typeof t?t<0?"0px":t+"px":t.match(/\d$/)?t+"px":t}function _t(t){var e,n,i,r,o,a,s=[],l=t.aoColumns;e=t.aaSortingFixed,n=O.isPlainObject(e);var u=[];for(i=function(t){t.length&&!O.isArray(t[0])?u.push(t):O.merge(u,t)},O.isArray(e)&&i(e),n&&e.pre&&i(e.pre),i(t.aaSorting),n&&e.post&&i(e.post),t=0;t/g,"");var l=n.nTh;l.removeAttribute("aria-sort"),n.bSortable&&(e+="asc"===(n=0=i.length?[0,e[1]]:e)})),r.search!==L&&O.extend(n.oPreviousSearch,nt(r.search)),t=0,e=r.columns.length;t/g,ae=/^[\w\+\-]/,se=/[\w\+\-]$/,le=RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\|\\$|\\^|\\-)","g"),ue=/[',$£€¥%\u2009\u202F\u20BD\u20a9\u20BArfk]/gi,ce=function(t,e,n){var i=[],r=0,o=t.length;if(n!==L)for(;r")[0],me=ge.textContent!==L,ve=/<.*?>/g;Jt=function(p){this.$=function(t,e){return this.api(!0).$(t,e)},this._=function(t,e){return this.api(!0).rows(t,e).data()},this.api=function(t){return new te(t?Ot(this[Qt.iApiIndex]):this)},this.fnAddData=function(t,e){var n=this.api(!0),i=O.isArray(t)&&(O.isArray(t[0])||O.isPlainObject(t[0]))?n.rows.add(t):n.row.add(t);return(e===L||e)&&n.draw(),i.flatten().toArray()},this.fnAdjustColumnSizing=function(t){var e=this.api(!0).columns.adjust(),n=e.settings()[0],i=n.oScroll;t===L||t?e.draw(!1):(""!==i.sX||""!==i.sY)&>(n)},this.fnClearTable=function(t){var e=this.api(!0).clear();(t===L||t)&&e.draw()},this.fnClose=function(t){this.api(!0).row(t).child.hide()},this.fnDeleteRow=function(t,e,n){var i=this.api(!0),r=(t=i.rows(t)).settings()[0],o=r.aoData[t[0][0]];return t.remove(),e&&e.call(this,r,o),(n===L||n)&&i.draw(),o},this.fnDestroy=function(t){this.api(!0).destroy(t)},this.fnDraw=function(t){this.api(!0).draw(t)},this.fnFilter=function(t,e,n,i,r,o){r=this.api(!0),null===e||e===L?r.search(t,n,i,o):r.column(e).search(t,n,i,o),r.draw()},this.fnGetData=function(t,e){var n=this.api(!0);if(t===L)return n.data().toArray();var i=t.nodeName?t.nodeName.toLowerCase():"";return e!==L||"td"==i||"th"==i?n.cell(t,e).data():n.row(t).data()||null},this.fnGetNodes=function(t){var e=this.api(!0);return t!==L?e.row(t).node():e.rows().nodes().flatten().toArray()},this.fnGetPosition=function(t){var e=this.api(!0),n=t.nodeName.toUpperCase();return"TR"==n?e.row(t).index():"TD"==n||"TH"==n?[(t=e.cell(t).index()).row,t.columnVisible,t.column]:null},this.fnIsOpen=function(t){return this.api(!0).row(t).child.isShown()},this.fnOpen=function(t,e,n){return this.api(!0).row(t).child(e,n).show().child()[0]},this.fnPageChange=function(t,e){var n=this.api(!0).page(t);(e===L||e)&&n.draw(!1)},this.fnSetColumnVis=function(t,e,n){t=this.api(!0).column(t).visible(e),(n===L||n)&&t.columns.adjust().draw()},this.fnSettings=function(){return Ot(this[Qt.iApiIndex])},this.fnSort=function(t){this.api(!0).order(t).draw()},this.fnSortListener=function(t,e,n){this.api(!0).order.listener(t,e,n)},this.fnUpdate=function(t,e,n,i,r){var o=this.api(!0);return n===L||null===n?o.row(e).data(t):o.cell(e,n).data(t),(r===L||r)&&o.columns.adjust(),(i===L||i)&&o.draw(),0},this.fnVersionCheck=Qt.fnVersionCheck;var g=this,m=p===L,v=this.length;for(var t in m&&(p={}),this.oApi=this.internal=Qt.internal,Jt.ext.internal)t&&(this[t]=e(t));return this.each(function(){var t,e={},n=(e=1t<"F"ip>'),u.renderer?O.isPlainObject(u.renderer)&&!u.renderer.header&&(u.renderer.header="jqueryui"):u.renderer="jqueryui"):O.extend(i,Jt.ext.classes,e.oClasses),a.addClass(i.sTable),u.iInitDisplayStart===L&&(u.iInitDisplayStart=e.iDisplayStart,u._iDisplayStart=e.iDisplayStart),null!==e.iDeferLoading&&(u.bDeferLoading=!0,n=O.isArray(e.iDeferLoading),u._iRecordsDisplay=n?e.iDeferLoading[0]:e.iDeferLoading,u._iRecordsTotal=n?e.iDeferLoading[1]:e.iDeferLoading);var c=u.oLanguage;O.extend(!0,c,e.oLanguage),""!==c.sUrl&&(O.ajax({dataType:"json",url:c.sUrl,success:function(t){x(t),b(o.oLanguage,t),O.extend(!0,c,t),at(u)},error:function(){at(u)}}),r=!0),null===e.asStripeClasses&&(u.asStripeClasses=[i.sStripeOdd,i.sStripeEven]);n=u.asStripeClasses;var h=a.children("tbody").find("tr").eq(0);if(-1!==O.inArray(!0,O.map(n,function(t){return h.hasClass(t)}))&&(O("tbody tr",this).removeClass(n.join(" ")),u.asDestroyStripes=n.slice()),s=[],0!==(n=this.getElementsByTagName("thead")).length&&(B(u.aoHeader,n[0]),s=W(u)),null===e.aoColumns)for(l=[],n=0,t=s.length;n").appendTo(this)),u.nTHead=t[0],0===(t=a.children("tbody")).length&&(t=O("
        ").addClass("table-condensed")),e=K("
        ").addClass("timepicker-minutes").append(K("
        ").addClass("table-condensed")),n=K("
        ").addClass("timepicker-seconds").append(K("
        ").addClass("table-condensed")),i=[function(){var t=K(""),e=K(""),n=K("");return a("h")&&(t.append(K("
        ").append(K("").attr({href:"#",tabindex:"-1",title:u.tooltips.incrementHour}).addClass("btn").attr("data-action","incrementHours").append(K("").addClass(u.icons.up)))),e.append(K("").append(K("").addClass("timepicker-hour").attr({"data-time-component":"hours",title:u.tooltips.pickHour}).attr("data-action","showHours"))),n.append(K("").append(K("").attr({href:"#",tabindex:"-1",title:u.tooltips.decrementHour}).addClass("btn").attr("data-action","decrementHours").append(K("").addClass(u.icons.down))))),a("m")&&(a("h")&&(t.append(K("").addClass("separator")),e.append(K("").addClass("separator").html(":")),n.append(K("").addClass("separator"))),t.append(K("").append(K("").attr({href:"#",tabindex:"-1",title:u.tooltips.incrementMinute}).addClass("btn").attr("data-action","incrementMinutes").append(K("").addClass(u.icons.up)))),e.append(K("").append(K("").addClass("timepicker-minute").attr({"data-time-component":"minutes",title:u.tooltips.pickMinute}).attr("data-action","showMinutes"))),n.append(K("").append(K("").attr({href:"#",tabindex:"-1",title:u.tooltips.decrementMinute}).addClass("btn").attr("data-action","decrementMinutes").append(K("").addClass(u.icons.down))))),a("s")&&(a("m")&&(t.append(K("").addClass("separator")),e.append(K("").addClass("separator").html(":")),n.append(K("").addClass("separator"))),t.append(K("").append(K("").attr({href:"#",tabindex:"-1",title:u.tooltips.incrementSecond}).addClass("btn").attr("data-action","incrementSeconds").append(K("").addClass(u.icons.up)))),e.append(K("").append(K("").addClass("timepicker-second").attr({"data-time-component":"seconds",title:u.tooltips.pickSecond}).attr("data-action","showSeconds"))),n.append(K("").append(K("").attr({href:"#",tabindex:"-1",title:u.tooltips.decrementSecond}).addClass("btn").attr("data-action","decrementSeconds").append(K("").addClass(u.icons.down))))),E||(t.append(K("").addClass("separator")),e.append(K("").append(K("").addClass("separator"))),K("
        ").addClass("timepicker-picker").append(K("").addClass("table-condensed").append([t,e,n]))}()];return a("h")&&i.push(t),a("m")&&i.push(e),a("s")&&i.push(n),i}function e(){var t=K("
        ").addClass("bootstrap-datetimepicker-widget dropdown-menu"),e=K("
        ").addClass("datepicker").append(function(){var t=K("
        ").append(K("").append(K("").append(K("").append(K("
        ").addClass("prev").attr("data-action","previous").append(K("").addClass(u.icons.previous))).append(K("").addClass("picker-switch").attr("data-action","pickerSwitch").attr("colspan",u.calendarWeeks?"6":"5")).append(K("").addClass("next").attr("data-action","next").append(K("").addClass(u.icons.next)))),e=K("
        ").attr("colspan",u.calendarWeeks?"8":"7")));return[K("
        ").addClass("datepicker-days").append(K("").addClass("table-condensed").append(t).append(K(""))),K("
        ").addClass("datepicker-months").append(K("
        ").addClass("table-condensed").append(t.clone()).append(e.clone())),K("
        ").addClass("datepicker-years").append(K("
        ").addClass("table-condensed").append(t.clone()).append(e.clone())),K("
        ").addClass("datepicker-decades").append(K("
        ").addClass("table-condensed").append(t.clone()).append(e.clone()))]}()),n=K("
        ").addClass("timepicker").append(h()),i=K("
          ").addClass("list-unstyled"),r=K("
        • ").addClass("picker-switch"+(u.collapse?" accordion-toggle":"")).append(function(){var t=[];return u.showTodayButton&&t.push(K("
        ").append(K("").attr({"data-action":"today",title:u.tooltips.today}).append(K("").addClass(u.icons.today)))),!u.sideBySide&&c()&&l()&&t.push(K("").append(K("").attr({"data-action":"togglePicker",title:u.tooltips.selectTime}).append(K("").addClass(u.icons.time)))),u.showClear&&t.push(K("").append(K("").attr({"data-action":"clear",title:u.tooltips.clear}).append(K("").addClass(u.icons.clear)))),u.showClose&&t.push(K("").append(K("").attr({"data-action":"close",title:u.tooltips.close}).append(K("").addClass(u.icons.close)))),K("").addClass("table-condensed").append(K("").append(K("").append(t)))}());return u.inline&&t.removeClass("dropdown-menu"),E&&t.addClass("usetwentyfour"),a("s")&&!E&&t.addClass("wider"),u.sideBySide&&c()&&l()?(t.addClass("timepicker-sbs"),"top"===u.toolbarPlacement&&t.append(r),t.append(K("
        ").addClass("row").append(e.addClass("col-md-6")).append(n.addClass("col-md-6"))),"bottom"===u.toolbarPlacement&&t.append(r),t):("top"===u.toolbarPlacement&&i.append(r),c()&&i.append(K("
      • ").addClass(u.collapse&&l()?"collapse in":"").append(e)),"default"===u.toolbarPlacement&&i.append(r),l()&&i.append(K("
      • ").addClass(u.collapse&&c()?"collapse":"").append(n)),"bottom"===u.toolbarPlacement&&i.append(r),t.append(i))}function n(){var t,e=(H||o).position(),n=(H||o).offset(),i=u.widgetPositioning.vertical,r=u.widgetPositioning.horizontal;if(u.widgetParent)t=u.widgetParent.append(z);else if(o.is("input"))t=o.after(z).parent();else{if(u.inline)return void(t=o.append(z));(t=o).children().first().after(z)}if("auto"===i&&(i=n.top+1.5*z.height()>=K(window).height()+K(window).scrollTop()&&z.height()+o.outerHeight()K(window).width()?"right":"left"),"top"===i?z.addClass("top").removeClass("bottom"):z.addClass("bottom").removeClass("top"),"right"===r?z.addClass("pull-right"):z.removeClass("pull-right"),"relative"!==t.css("position")&&(t=t.parents().filter(function(){return"relative"===K(this).css("position")}).first()),0===t.length)throw new Error("datetimepicker component should be placed within a relative positioned container");z.css({top:"top"===i?"auto":e.top+o.outerHeight(),bottom:"top"===i?e.top+o.outerHeight():"auto",left:"left"===r?t===o?0:e.left:"auto",right:"left"===r?"auto":t.outerWidth()-o.outerWidth()-(t===o?0:e.left)})}function i(t){"dp.change"===t.type&&(t.date&&t.date.isSame(t.oldDate)||!t.date&&!t.oldDate)||o.trigger(t)}function r(t){"y"===t&&(t="YYYY"),i({type:"dp.update",change:t,viewDate:A.clone()})}function d(t){z&&(t&&(I=Math.max(B,Math.min(3,I+t))),z.find(".datepicker > div").hide().filter(".datepicker-"+W[I].clsName).show())}function f(t,e){if(!t.isValid())return!1;if(u.disabledDates&&"d"===e&&function(t){return!0===u.disabledDates[t.format("YYYY-MM-DD")]}(t))return!1;if(u.enabledDates&&"d"===e&&!function(t){return!0===u.enabledDates[t.format("YYYY-MM-DD")]}(t))return!1;if(u.minDate&&t.isBefore(u.minDate,e))return!1;if(u.maxDate&&t.isAfter(u.maxDate,e))return!1;if(u.daysOfWeekDisabled&&"d"===e&&-1!==u.daysOfWeekDisabled.indexOf(t.day()))return!1;if(u.disabledHours&&("h"===e||"m"===e||"s"===e)&&function(t){return!0===u.disabledHours[t.format("H")]}(t))return!1;if(u.enabledHours&&("h"===e||"m"===e||"s"===e)&&!function(t){return!0===u.enabledHours[t.format("H")]}(t))return!1;if(u.disabledTimeIntervals&&("h"===e||"m"===e||"s"===e)){var n=!1;if(K.each(u.disabledTimeIntervals,function(){if(t.isBetween(this[0],this[1]))return!(n=!0)}),n)return!1}return!0}function p(){var t,e,n,i,r=z.find(".datepicker-days"),o=r.find("th"),a=[];if(c()){for(o.eq(0).find("span").attr("title",u.tooltips.prevMonth),o.eq(1).attr("title",u.tooltips.selectMonth),o.eq(2).find("span").attr("title",u.tooltips.nextMonth),r.find(".disabled").removeClass("disabled"),o.eq(1).text(A.format(u.dayViewHeaderFormat)),f(A.clone().subtract(1,"M"),"M")||o.eq(0).addClass("disabled"),f(A.clone().add(1,"M"),"M")||o.eq(2).addClass("disabled"),t=A.clone().startOf("M").startOf("w").startOf("d"),i=0;i<42;i++)0===t.weekday()&&(e=K("
      • "),u.calendarWeeks&&e.append('"),a.push(e)),n="",t.isBefore(A,"M")&&(n+=" old"),t.isAfter(A,"M")&&(n+=" new"),t.isSame(D,"d")&&!j&&(n+=" active"),f(t,"d")||(n+=" disabled"),t.isSame(s(),"d")&&(n+=" today"),0!==t.day()&&6!==t.day()||(n+=" weekend"),e.append('"),t.add(1,"d");r.find("tbody").empty().append(a),function(){var t=z.find(".datepicker-months"),e=t.find("th"),n=t.find("tbody").find("span");e.eq(0).find("span").attr("title",u.tooltips.prevYear),e.eq(1).attr("title",u.tooltips.selectYear),e.eq(2).find("span").attr("title",u.tooltips.nextYear),t.find(".disabled").removeClass("disabled"),f(A.clone().subtract(1,"y"),"y")||e.eq(0).addClass("disabled"),e.eq(1).text(A.year()),f(A.clone().add(1,"y"),"y")||e.eq(2).addClass("disabled"),n.removeClass("active"),D.isSame(A,"y")&&!j&&n.eq(D.month()).addClass("active"),n.each(function(t){f(A.clone().month(t),"M")||K(this).addClass("disabled")})}(),function(){var t=z.find(".datepicker-years"),e=t.find("th"),n=A.clone().subtract(5,"y"),i=A.clone().add(6,"y"),r="";for(e.eq(0).find("span").attr("title",u.tooltips.prevDecade),e.eq(1).attr("title",u.tooltips.selectDecade),e.eq(2).find("span").attr("title",u.tooltips.nextDecade),t.find(".disabled").removeClass("disabled"),u.minDate&&u.minDate.isAfter(n,"y")&&e.eq(0).addClass("disabled"),e.eq(1).text(n.year()+"-"+i.year()),u.maxDate&&u.maxDate.isBefore(i,"y")&&e.eq(2).addClass("disabled");!n.isAfter(i,"y");)r+=''+n.year()+"",n.add(1,"y");t.find("td").html(r)}(),function(){var t=z.find(".datepicker-decades"),e=t.find("th"),n=J({y:A.year()-A.year()%100-1}),i=n.clone().add(100,"y"),r=n.clone(),o="";for(e.eq(0).find("span").attr("title",u.tooltips.prevCentury),e.eq(2).find("span").attr("title",u.tooltips.nextCentury),t.find(".disabled").removeClass("disabled"),(n.isSame(J({y:1900}))||u.minDate&&u.minDate.isAfter(n,"y"))&&e.eq(0).addClass("disabled"),e.eq(1).text(n.year()+"-"+i.year()),(n.isSame(J({y:2e3}))||u.maxDate&&u.maxDate.isBefore(i,"y"))&&e.eq(2).addClass("disabled");!n.isAfter(i,"y");)o+=''+(n.year()+1)+" - "+(n.year()+12)+"",n.add(12,"y");o+="",t.find("td").html(o),e.eq(1).text(r.year()+1+"-"+n.year())}()}}function t(){var t,e,n=z.find(".timepicker span[data-time-component]");E||(t=z.find(".timepicker [data-action=togglePeriod]"),e=D.clone().add(12<=D.hours()?-12:12,"h"),t.text(D.format("A")),f(e,"h")?t.removeClass("disabled"):t.addClass("disabled")),n.filter("[data-time-component=hours]").text(D.format(E?"HH":"hh")),n.filter("[data-time-component=minutes]").text(D.format("mm")),n.filter("[data-time-component=seconds]").text(D.format("ss")),function(){var t=z.find(".timepicker-hours table"),e=A.clone().startOf("d"),n=[],i=K("");for(11"),n.push(i)),i.append('"),e.add(1,"h");t.empty().append(n)}(),function(){for(var t=z.find(".timepicker-minutes table"),e=A.clone().startOf("h"),n=[],i=K(""),r=1===u.stepping?5:u.stepping;A.isSame(e,"h");)e.minute()%(4*r)==0&&(i=K(""),n.push(i)),i.append('"),e.add(r,"m");t.empty().append(n)}(),function(){for(var t=z.find(".timepicker-seconds table"),e=A.clone().startOf("m"),n=[],i=K("");A.isSame(e,"m");)e.second()%20==0&&(i=K(""),n.push(i)),i.append('"),e.add(5,"s");t.empty().append(n)}()}function g(){z&&(p(),t())}function m(t){var e=j?null:D;if(!t)return j=!0,P.val(""),o.data("date",""),i({type:"dp.change",date:!1,oldDate:e}),void g();t=t.clone().locale(u.locale),1!==u.stepping&&t.minutes(Math.round(t.minutes()/u.stepping)*u.stepping%60).seconds(0),f(t)?(A=(D=t).clone(),P.val(D.format(O)),o.data("date",D.format(O)),j=!1,g(),i({type:"dp.change",date:D.clone(),oldDate:e})):(u.keepInvalid||P.val(j?"":D.format(O)),i({type:"dp.error",date:t}))}function v(){var e=!1;return z?(z.find(".collapse").each(function(){var t=K(this).data("collapse");return!t||!t.transitioning||!(e=!0)}),e||(H&&H.hasClass("btn")&&H.toggleClass("active"),z.hide(),K(window).off("resize",n),z.off("click","[data-action]"),z.off("mousedown",!1),z.remove(),z=!1,i({type:"dp.hide",date:D.clone()}),P.blur()),R):R}function y(){m(null)}function b(t){return K(t.currentTarget).is(".disabled")||V[K(t.currentTarget).data("action")].apply(R,arguments),!1}function x(){var t;return P.prop("disabled")||!u.ignoreReadonly&&P.prop("readonly")||z||(void 0!==P.val()&&0!==P.val().trim().length?m(Z(P.val().trim())):u.useCurrent&&j&&(P.is("input")&&0===P.val().trim().length||u.inline)&&(t=s(),"string"==typeof u.useCurrent&&(t={year:function(t){return t.month(0).date(1).hours(0).seconds(0).minutes(0)},month:function(t){return t.date(1).hours(0).seconds(0).minutes(0)},day:function(t){return t.hours(0).seconds(0).minutes(0)},hour:function(t){return t.seconds(0).minutes(0)},minute:function(t){return t.seconds(0)}}[u.useCurrent](t)),m(t)),z=e(),function(){var t=K(""),e=A.clone().startOf("w").startOf("d");for(!0===u.calendarWeeks&&t.append(K("
        '+t.week()+"'+t.date()+"
        '+e.format(E?"HH":"hh")+"
        '+e.format("mm")+"
        '+e.format("ss")+"
        ").addClass("cw").text("#"));e.isBefore(A.clone().endOf("w"));)t.append(K("").addClass("dow").text(e.format("dd"))),e.add(1,"d");z.find(".datepicker-days thead").append(t)}(),function(){for(var t=[],e=A.clone().startOf("y").startOf("d");e.isSame(A,"y");)t.push(K("").attr("data-action","selectMonth").addClass("month").text(e.format("MMM"))),e.add(1,"M");z.find(".datepicker-months td").empty().append(t)}(),z.find(".timepicker-hours").hide(),z.find(".timepicker-minutes").hide(),z.find(".timepicker-seconds").hide(),g(),d(),K(window).on("resize",n),z.on("click","[data-action]",b),z.on("mousedown",!1),H&&H.hasClass("btn")&&H.toggleClass("active"),z.show(),n(),u.focusOnShow&&!P.is(":focus")&&P.focus(),i({type:"dp.show"})),R}function w(){return z?v():x()}function S(t){var e,n,i,r,o=null,a=[],s={},l=t.which;for(e in X[l]="p",X)X.hasOwnProperty(e)&&"p"===X[e]&&(a.push(e),parseInt(e,10)!==l&&(s[e]=!0));for(e in u.keyBinds)if(u.keyBinds.hasOwnProperty(e)&&"function"==typeof u.keyBinds[e]&&(i=e.split(" ")).length===a.length&&G[l]===i[i.length-1]){for(r=!0,n=i.length-2;0<=n;n--)if(!(G[i[n]]in s)){r=!1;break}if(r){o=u.keyBinds[e];break}}o&&(o.call(R,z),t.stopPropagation(),t.preventDefault())}function _(t){X[t.which]="r",t.stopPropagation(),t.preventDefault()}function C(t){var e=K(t.target).val().trim(),n=e?Z(e):null;return m(n),t.stopImmediatePropagation(),!1}function k(t){var e={};return K.each(t,function(){var t=Z(this);t.isValid()&&(e[t.format("YYYY-MM-DD")]=!0)}),!!Object.keys(e).length&&e}function M(t){var e={};return K.each(t,function(){e[this]=!0}),!!Object.keys(e).length&&e}function T(){var t=u.format||"L LT";O=t.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,function(t){return(D.localeData().longDateFormat(t)||t).replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,function(t){return D.localeData().longDateFormat(t)||t})}),(L=u.extraFormats?u.extraFormats.slice():[]).indexOf(t)<0&&L.indexOf(O)<0&&L.push(O),E=O.toLowerCase().indexOf("a")<1&&O.replace(/\[.*?\]/g,"").indexOf("h")<1,a("y")&&(B=2),a("M")&&(B=1),a("d")&&(B=0),I=Math.max(B,I),j||m(D)}var D,A,P,E,O,L,I,N,F,R={},j=!0,H=!1,z=!1,B=0,W=[{clsName:"days",navFnc:"M",navStep:1},{clsName:"months",navFnc:"y",navStep:1},{clsName:"years",navFnc:"y",navStep:10},{clsName:"decades",navFnc:"y",navStep:100}],$=["days","months","years","decades"],q=["top","bottom","auto"],U=["left","right","auto"],Y=["default","top","bottom"],G={up:38,38:"up",down:40,40:"down",left:37,37:"left",right:39,39:"right",tab:9,9:"tab",escape:27,27:"escape",enter:13,13:"enter",pageUp:33,33:"pageUp",pageDown:34,34:"pageDown",shift:16,16:"shift",control:17,17:"control",space:32,32:"space",t:84,84:"t",delete:46,46:"delete"},X={},V={next:function(){var t=W[I].navFnc;A.add(W[I].navStep,t),p(),r(t)},previous:function(){var t=W[I].navFnc;A.subtract(W[I].navStep,t),p(),r(t)},pickerSwitch:function(){d(1)},selectMonth:function(t){var e=K(t.target).closest("tbody").find("span").index(K(t.target));A.month(e),I===B?(m(D.clone().year(A.year()).month(A.month())),u.inline||v()):(d(-1),p()),r("M")},selectYear:function(t){var e=parseInt(K(t.target).text(),10)||0;A.year(e),I===B?(m(D.clone().year(A.year())),u.inline||v()):(d(-1),p()),r("YYYY")},selectDecade:function(t){var e=parseInt(K(t.target).data("selection"),10)||0;A.year(e),I===B?(m(D.clone().year(A.year())),u.inline||v()):(d(-1),p()),r("YYYY")},selectDay:function(t){var e=A.clone();K(t.target).is(".old")&&e.subtract(1,"M"),K(t.target).is(".new")&&e.add(1,"M"),m(e.date(parseInt(K(t.target).text(),10))),l()||u.keepOpen||u.inline||v()},incrementHours:function(){var t=D.clone().add(1,"h");f(t,"h")&&m(t)},incrementMinutes:function(){var t=D.clone().add(u.stepping,"m");f(t,"m")&&m(t)},incrementSeconds:function(){var t=D.clone().add(1,"s");f(t,"s")&&m(t)},decrementHours:function(){var t=D.clone().subtract(1,"h");f(t,"h")&&m(t)},decrementMinutes:function(){var t=D.clone().subtract(u.stepping,"m");f(t,"m")&&m(t)},decrementSeconds:function(){var t=D.clone().subtract(1,"s");f(t,"s")&&m(t)},togglePeriod:function(){m(D.clone().add(12<=D.hours()?-12:12,"h"))},togglePicker:function(t){var e,n=K(t.target),i=n.closest("ul"),r=i.find(".in"),o=i.find(".collapse:not(.in)");if(r&&r.length){if((e=r.data("collapse"))&&e.transitioning)return;r.collapse?(r.collapse("hide"),o.collapse("show")):(r.removeClass("in"),o.addClass("in")),n.is("span")?n.toggleClass(u.icons.time+" "+u.icons.date):n.find("span").toggleClass(u.icons.time+" "+u.icons.date)}},showPicker:function(){z.find(".timepicker > div:not(.timepicker-picker)").hide(),z.find(".timepicker .timepicker-picker").show()},showHours:function(){z.find(".timepicker .timepicker-picker").hide(),z.find(".timepicker .timepicker-hours").show()},showMinutes:function(){z.find(".timepicker .timepicker-picker").hide(),z.find(".timepicker .timepicker-minutes").show()},showSeconds:function(){z.find(".timepicker .timepicker-picker").hide(),z.find(".timepicker .timepicker-seconds").show()},selectHour:function(t){var e=parseInt(K(t.target).text(),10);E||(12<=D.hours()?12!==e&&(e+=12):12===e&&(e=0)),m(D.clone().hours(e)),V.showPicker.call(R)},selectMinute:function(t){m(D.clone().minutes(parseInt(K(t.target).text(),10))),V.showPicker.call(R)},selectSecond:function(t){m(D.clone().seconds(parseInt(K(t.target).text(),10))),V.showPicker.call(R)},clear:y,today:function(){var t=s();f(t,"d")&&m(t)},close:v},Z=function(t){return(t=void 0===u.parseInputDate?J.isMoment(t)||t instanceof Date?J(t):s(t):u.parseInputDate(t)).locale(u.locale),t};if(R.destroy=function(){v(),P.off({change:C,blur:blur,keydown:S,keyup:_,focus:u.allowInputToggle?v:""}),o.is("input")?P.off({focus:x}):H&&(H.off("click",w),H.off("mousedown",!1)),o.removeData("DateTimePicker"),o.removeData("date")},R.toggle=w,R.show=x,R.hide=v,R.disable=function(){return v(),H&&H.hasClass("btn")&&H.addClass("disabled"),P.prop("disabled",!0),R},R.enable=function(){return H&&H.hasClass("btn")&&H.removeClass("disabled"),P.prop("disabled",!1),R},R.ignoreReadonly=function(t){if(0===arguments.length)return u.ignoreReadonly;if("boolean"!=typeof t)throw new TypeError("ignoreReadonly () expects a boolean parameter");return u.ignoreReadonly=t,R},R.options=function(t){if(0===arguments.length)return K.extend(!0,{},u);if(!(t instanceof Object))throw new TypeError("options() options parameter should be an object");return K.extend(!0,u,t),K.each(u,function(t,e){if(void 0===R[t])throw new TypeError("option "+t+" is not recognized!");R[t](e)}),R},R.date=function(t){if(0===arguments.length)return j?null:D.clone();if(!(null===t||"string"==typeof t||J.isMoment(t)||t instanceof Date))throw new TypeError("date() parameter must be one of [null, string, moment or Date]");return m(null===t?null:Z(t)),R},R.format=function(t){if(0===arguments.length)return u.format;if("string"!=typeof t&&("boolean"!=typeof t||!1!==t))throw new TypeError("format() expects a sting or boolean:false parameter "+t);return u.format=t,O&&T(),R},R.timeZone=function(t){return 0===arguments.length?u.timeZone:(u.timeZone=t,R)},R.dayViewHeaderFormat=function(t){if(0===arguments.length)return u.dayViewHeaderFormat;if("string"!=typeof t)throw new TypeError("dayViewHeaderFormat() expects a string parameter");return u.dayViewHeaderFormat=t,R},R.extraFormats=function(t){if(0===arguments.length)return u.extraFormats;if(!1!==t&&!(t instanceof Array))throw new TypeError("extraFormats() expects an array or false parameter");return u.extraFormats=t,L&&T(),R},R.disabledDates=function(t){if(0===arguments.length)return u.disabledDates?K.extend({},u.disabledDates):u.disabledDates;if(!t)return u.disabledDates=!1,g(),R;if(!(t instanceof Array))throw new TypeError("disabledDates() expects an array parameter");return u.disabledDates=k(t),u.enabledDates=!1,g(),R},R.enabledDates=function(t){if(0===arguments.length)return u.enabledDates?K.extend({},u.enabledDates):u.enabledDates;if(!t)return u.enabledDates=!1,g(),R;if(!(t instanceof Array))throw new TypeError("enabledDates() expects an array parameter");return u.enabledDates=k(t),u.disabledDates=!1,g(),R},R.daysOfWeekDisabled=function(t){if(0===arguments.length)return u.daysOfWeekDisabled.splice(0);if("boolean"==typeof t&&!t)return u.daysOfWeekDisabled=!1,g(),R;if(!(t instanceof Array))throw new TypeError("daysOfWeekDisabled() expects an array parameter");if(u.daysOfWeekDisabled=t.reduce(function(t,e){return 6<(e=parseInt(e,10))||e<0||isNaN(e)||-1===t.indexOf(e)&&t.push(e),t},[]).sort(),u.useCurrent&&!u.keepInvalid){for(var e=0;!f(D,"d");){if(D.add(1,"d"),7===e)throw"Tried 7 times to find a valid date";e++}m(D)}return g(),R},R.maxDate=function(t){if(0===arguments.length)return u.maxDate?u.maxDate.clone():u.maxDate;if("boolean"==typeof t&&!1===t)return u.maxDate=!1,g(),R;"string"==typeof t&&("now"!==t&&"moment"!==t||(t=s()));var e=Z(t);if(!e.isValid())throw new TypeError("maxDate() Could not parse date parameter: "+t);if(u.minDate&&e.isBefore(u.minDate))throw new TypeError("maxDate() date parameter is before options.minDate: "+e.format(O));return u.maxDate=e,u.useCurrent&&!u.keepInvalid&&D.isAfter(t)&&m(u.maxDate),A.isAfter(e)&&(A=e.clone().subtract(u.stepping,"m")),g(),R},R.minDate=function(t){if(0===arguments.length)return u.minDate?u.minDate.clone():u.minDate;if("boolean"==typeof t&&!1===t)return u.minDate=!1,g(),R;"string"==typeof t&&("now"!==t&&"moment"!==t||(t=s()));var e=Z(t);if(!e.isValid())throw new TypeError("minDate() Could not parse date parameter: "+t);if(u.maxDate&&e.isAfter(u.maxDate))throw new TypeError("minDate() date parameter is after options.maxDate: "+e.format(O));return u.minDate=e,u.useCurrent&&!u.keepInvalid&&D.isBefore(t)&&m(u.minDate),A.isBefore(e)&&(A=e.clone().add(u.stepping,"m")),g(),R},R.defaultDate=function(t){if(0===arguments.length)return u.defaultDate?u.defaultDate.clone():u.defaultDate;if(!t)return u.defaultDate=!1,R;"string"==typeof t&&("now"!==t&&"moment"!==t||(t=s()));var e=Z(t);if(!e.isValid())throw new TypeError("defaultDate() Could not parse date parameter: "+t);if(!f(e))throw new TypeError("defaultDate() date passed is invalid according to component setup validations");return u.defaultDate=e,(u.defaultDate&&u.inline||""===P.val().trim())&&m(u.defaultDate),R},R.locale=function(t){if(0===arguments.length)return u.locale;if(!J.localeData(t))throw new TypeError("locale() locale "+t+" is not loaded from moment locales!");return u.locale=t,D.locale(u.locale),A.locale(u.locale),O&&T(),z&&(v(),x()),R},R.stepping=function(t){return 0===arguments.length?u.stepping:(t=parseInt(t,10),(isNaN(t)||t<1)&&(t=1),u.stepping=t,R)},R.useCurrent=function(t){var e=["year","month","day","hour","minute"];if(0===arguments.length)return u.useCurrent;if("boolean"!=typeof t&&"string"!=typeof t)throw new TypeError("useCurrent() expects a boolean or string parameter");if("string"==typeof t&&-1===e.indexOf(t.toLowerCase()))throw new TypeError("useCurrent() expects a string parameter of "+e.join(", "));return u.useCurrent=t,R},R.collapse=function(t){if(0===arguments.length)return u.collapse;if("boolean"!=typeof t)throw new TypeError("collapse() expects a boolean parameter");return u.collapse===t||(u.collapse=t,z&&(v(),x())),R},R.icons=function(t){if(0===arguments.length)return K.extend({},u.icons);if(!(t instanceof Object))throw new TypeError("icons() expects parameter to be an Object");return K.extend(u.icons,t),z&&(v(),x()),R},R.tooltips=function(t){if(0===arguments.length)return K.extend({},u.tooltips);if(!(t instanceof Object))throw new TypeError("tooltips() expects parameter to be an Object");return K.extend(u.tooltips,t),z&&(v(),x()),R},R.useStrict=function(t){if(0===arguments.length)return u.useStrict;if("boolean"!=typeof t)throw new TypeError("useStrict() expects a boolean parameter");return u.useStrict=t,R},R.sideBySide=function(t){if(0===arguments.length)return u.sideBySide;if("boolean"!=typeof t)throw new TypeError("sideBySide() expects a boolean parameter");return u.sideBySide=t,z&&(v(),x()),R},R.viewMode=function(t){if(0===arguments.length)return u.viewMode;if("string"!=typeof t)throw new TypeError("viewMode() expects a string parameter");if(-1===$.indexOf(t))throw new TypeError("viewMode() parameter must be one of ("+$.join(", ")+") value");return u.viewMode=t,I=Math.max($.indexOf(t),B),d(),R},R.toolbarPlacement=function(t){if(0===arguments.length)return u.toolbarPlacement;if("string"!=typeof t)throw new TypeError("toolbarPlacement() expects a string parameter");if(-1===Y.indexOf(t))throw new TypeError("toolbarPlacement() parameter must be one of ("+Y.join(", ")+") value");return u.toolbarPlacement=t,z&&(v(),x()),R},R.widgetPositioning=function(t){if(0===arguments.length)return K.extend({},u.widgetPositioning);if("[object Object]"!=={}.toString.call(t))throw new TypeError("widgetPositioning() expects an object variable");if(t.horizontal){if("string"!=typeof t.horizontal)throw new TypeError("widgetPositioning() horizontal variable must be a string");if(t.horizontal=t.horizontal.toLowerCase(),-1===U.indexOf(t.horizontal))throw new TypeError("widgetPositioning() expects horizontal parameter to be one of ("+U.join(", ")+")");u.widgetPositioning.horizontal=t.horizontal}if(t.vertical){if("string"!=typeof t.vertical)throw new TypeError("widgetPositioning() vertical variable must be a string");if(t.vertical=t.vertical.toLowerCase(),-1===q.indexOf(t.vertical))throw new TypeError("widgetPositioning() expects vertical parameter to be one of ("+q.join(", ")+")");u.widgetPositioning.vertical=t.vertical}return g(),R},R.calendarWeeks=function(t){if(0===arguments.length)return u.calendarWeeks;if("boolean"!=typeof t)throw new TypeError("calendarWeeks() expects parameter to be a boolean value");return u.calendarWeeks=t,g(),R},R.showTodayButton=function(t){if(0===arguments.length)return u.showTodayButton;if("boolean"!=typeof t)throw new TypeError("showTodayButton() expects a boolean parameter");return u.showTodayButton=t,z&&(v(),x()),R},R.showClear=function(t){if(0===arguments.length)return u.showClear;if("boolean"!=typeof t)throw new TypeError("showClear() expects a boolean parameter");return u.showClear=t,z&&(v(),x()),R},R.widgetParent=function(t){if(0===arguments.length)return u.widgetParent;if("string"==typeof t&&(t=K(t)),null!==t&&"string"!=typeof t&&!(t instanceof K))throw new TypeError("widgetParent() expects a string or a jQuery object parameter");return u.widgetParent=t,z&&(v(),x()),R},R.keepOpen=function(t){if(0===arguments.length)return u.keepOpen;if("boolean"!=typeof t)throw new TypeError("keepOpen() expects a boolean parameter");return u.keepOpen=t,R},R.focusOnShow=function(t){if(0===arguments.length)return u.focusOnShow;if("boolean"!=typeof t)throw new TypeError("focusOnShow() expects a boolean parameter");return u.focusOnShow=t,R},R.inline=function(t){if(0===arguments.length)return u.inline;if("boolean"!=typeof t)throw new TypeError("inline() expects a boolean parameter");return u.inline=t,R},R.clear=function(){return y(),R},R.keyBinds=function(t){return u.keyBinds=t,R},R.getMoment=function(t){return s(t)},R.debug=function(t){if("boolean"!=typeof t)throw new TypeError("debug() expects a boolean parameter");return u.debug=t,R},R.allowInputToggle=function(t){if(0===arguments.length)return u.allowInputToggle;if("boolean"!=typeof t)throw new TypeError("allowInputToggle() expects a boolean parameter");return u.allowInputToggle=t,R},R.showClose=function(t){if(0===arguments.length)return u.showClose;if("boolean"!=typeof t)throw new TypeError("showClose() expects a boolean parameter");return u.showClose=t,R},R.keepInvalid=function(t){if(0===arguments.length)return u.keepInvalid;if("boolean"!=typeof t)throw new TypeError("keepInvalid() expects a boolean parameter");return u.keepInvalid=t,R},R.datepickerInput=function(t){if(0===arguments.length)return u.datepickerInput;if("string"!=typeof t)throw new TypeError("datepickerInput() expects a string parameter");return u.datepickerInput=t,R},R.parseInputDate=function(t){if(0===arguments.length)return u.parseInputDate;if("function"!=typeof t)throw new TypeError("parseInputDate() sholud be as function");return u.parseInputDate=t,R},R.disabledTimeIntervals=function(t){if(0===arguments.length)return u.disabledTimeIntervals?K.extend({},u.disabledTimeIntervals):u.disabledTimeIntervals;if(!t)return u.disabledTimeIntervals=!1,g(),R;if(!(t instanceof Array))throw new TypeError("disabledTimeIntervals() expects an array parameter");return u.disabledTimeIntervals=t,g(),R},R.disabledHours=function(t){if(0===arguments.length)return u.disabledHours?K.extend({},u.disabledHours):u.disabledHours;if(!t)return u.disabledHours=!1,g(),R;if(!(t instanceof Array))throw new TypeError("disabledHours() expects an array parameter");if(u.disabledHours=M(t),u.enabledHours=!1,u.useCurrent&&!u.keepInvalid){for(var e=0;!f(D,"h");){if(D.add(1,"h"),24===e)throw"Tried 24 times to find a valid date";e++}m(D)}return g(),R},R.enabledHours=function(t){if(0===arguments.length)return u.enabledHours?K.extend({},u.enabledHours):u.enabledHours;if(!t)return u.enabledHours=!1,g(),R;if(!(t instanceof Array))throw new TypeError("enabledHours() expects an array parameter");if(u.enabledHours=M(t),u.disabledHours=!1,u.useCurrent&&!u.keepInvalid){for(var e=0;!f(D,"h");){if(D.add(1,"h"),24===e)throw"Tried 24 times to find a valid date";e++}m(D)}return g(),R},R.viewDate=function(t){if(0===arguments.length)return A.clone();if(!t)return A=D.clone(),R;if(!("string"==typeof t||J.isMoment(t)||t instanceof Date))throw new TypeError("viewDate() parameter must be one of [string, moment or Date]");return A=Z(t),r(),R},o.is("input"))P=o;else if(0===(P=o.find(u.datepickerInput)).size())P=o.find("input");else if(!P.is("input"))throw new Error('CSS class "'+u.datepickerInput+'" cannot be applied to non input element');if(o.hasClass("input-group")&&(H=0===o.find(".datepickerbutton").size()?o.find(".input-group-addon"):o.find(".datepickerbutton")),!u.inline&&!P.is("input"))throw new Error("Could not initialize DateTimePicker without an input element");return D=s(),A=D.clone(),K.extend(!0,u,(F={},(N=o.is("input")||u.inline?o.data():o.find("input").data()).dateOptions&&N.dateOptions instanceof Object&&(F=K.extend(!0,F,N.dateOptions)),K.each(u,function(t){var e="date"+t.charAt(0).toUpperCase()+t.slice(1);void 0!==N[e]&&(F[t]=N[e])}),F)),R.options(u),T(),P.on({change:C,blur:u.debug?"":v,keydown:S,keyup:_,focus:u.allowInputToggle?x:""}),o.is("input")?P.on({focus:x}):H&&(H.on("click",w),H.on("mousedown",!1)),P.prop("disabled")&&R.disable(),P.is("input")&&0!==P.val().trim().length?m(Z(P.val().trim())):u.defaultDate&&void 0===P.attr("placeholder")&&m(u.defaultDate),u.inline&&x(),R}K.fn.datetimepicker=function(e){return this.each(function(){var t=K(this);t.data("DateTimePicker")||(e=K.extend(!0,{},K.fn.datetimepicker.defaults,e),t.data("DateTimePicker",n(t,e)))})},K.fn.datetimepicker.defaults={timeZone:"Etc/UTC",format:!1,dayViewHeaderFormat:"MMMM YYYY",extraFormats:!1,stepping:1,minDate:!1,maxDate:!1,useCurrent:!0,collapse:!0,locale:J.locale(),defaultDate:!1,disabledDates:!1,enabledDates:!1,icons:{time:"glyphicon glyphicon-time",date:"glyphicon glyphicon-calendar",up:"glyphicon glyphicon-chevron-up",down:"glyphicon glyphicon-chevron-down",previous:"glyphicon glyphicon-chevron-left",next:"glyphicon glyphicon-chevron-right",today:"glyphicon glyphicon-screenshot",clear:"glyphicon glyphicon-trash",close:"glyphicon glyphicon-remove"},tooltips:{today:"Go to today",clear:"Clear selection",close:"Close the picker",selectMonth:"Select Month",prevMonth:"Previous Month",nextMonth:"Next Month",selectYear:"Select Year",prevYear:"Previous Year",nextYear:"Next Year",selectDecade:"Select Decade",prevDecade:"Previous Decade",nextDecade:"Next Decade",prevCentury:"Previous Century",nextCentury:"Next Century",pickHour:"Pick Hour",incrementHour:"Increment Hour",decrementHour:"Decrement Hour",pickMinute:"Pick Minute",incrementMinute:"Increment Minute",decrementMinute:"Decrement Minute",pickSecond:"Pick Second",incrementSecond:"Increment Second",decrementSecond:"Decrement Second",togglePeriod:"Toggle Period",selectTime:"Select Time"},useStrict:!1,sideBySide:!1,daysOfWeekDisabled:!1,calendarWeeks:!1,viewMode:"days",toolbarPlacement:"default",showTodayButton:!1,showClear:!1,showClose:!1,widgetPositioning:{horizontal:"auto",vertical:"auto"},widgetParent:null,ignoreReadonly:!1,keepOpen:!1,focusOnShow:!0,inline:!1,keepInvalid:!1,datepickerInput:".datepickerinput",keyBinds:{up:function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")?this.date(e.clone().subtract(7,"d")):this.date(e.clone().add(this.stepping(),"m"))}},down:function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")?this.date(e.clone().add(7,"d")):this.date(e.clone().subtract(this.stepping(),"m"))}else this.show()},"control up":function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")?this.date(e.clone().subtract(1,"y")):this.date(e.clone().add(1,"h"))}},"control down":function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")?this.date(e.clone().add(1,"y")):this.date(e.clone().subtract(1,"h"))}},left:function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")&&this.date(e.clone().subtract(1,"d"))}},right:function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")&&this.date(e.clone().add(1,"d"))}},pageUp:function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")&&this.date(e.clone().subtract(1,"M"))}},pageDown:function(t){if(t){var e=this.date()||this.getMoment();t.find(".datepicker").is(":visible")&&this.date(e.clone().add(1,"M"))}},enter:function(){this.hide()},escape:function(){this.hide()},"control space":function(t){t.find(".timepicker").is(":visible")&&t.find('.btn[data-action="togglePeriod"]').click()},t:function(){this.date(this.getMoment())},delete:function(){this.clear()}},debug:!1,allowInputToggle:!1,disabledTimeIntervals:!1,disabledHours:!1,enabledHours:!1,viewDate:!1}}),function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t("object"==typeof exports?require("jquery"):jQuery)}(function(n){var t=function(){if(n&&n.fn&&n.fn.select2&&n.fn.select2.amd)var t=n.fn.select2.amd;var e,r,u;return t&&t.requirejs||(t?r=t:t={},function(d){function f(t,e){return n.call(t,e)}function o(t,e){var n,i,r,o,a,s,l,u,c,h,d,f=e&&e.split("/"),p=w.map,g=p&&p["*"]||{};if(t&&"."===t.charAt(0))if(e){for(a=(t=t.split("/")).length-1,w.nodeIdCompat&&_.test(t[a])&&(t[a]=t[a].replace(_,"")),t=f.slice(0,f.length-1).concat(t),c=0;c":">",'"':""","'":"'","/":"/"};return"string"!=typeof t?t:String(t).replace(/[&<>"'\/\\]/g,function(t){return e[t]})},e.appendMany=function(t,e){if("1.7"===o.fn.jquery.substr(0,3)){var n=o();o.map(e,function(t){n=n.add(t)}),e=n}t.append(e)},e}),t.define("select2/results",["jquery","./utils"],function(d,t){function i(t,e,n){this.$element=t,this.data=n,this.options=e,i.__super__.constructor.call(this)}return t.Extend(i,t.Observable),i.prototype.render=function(){var t=d('
          ');return this.options.get("multiple")&&t.attr("aria-multiselectable","true"),this.$results=t},i.prototype.clear=function(){this.$results.empty()},i.prototype.displayMessage=function(t){var e=this.options.get("escapeMarkup");this.clear(),this.hideLoading();var n=d('
        • '),i=this.options.get("translations").get(t.message);n.append(e(i(t.args))),n[0].className+=" select2-results__message",this.$results.append(n)},i.prototype.hideMessages=function(){this.$results.find(".select2-results__message").remove()},i.prototype.append=function(t){this.hideLoading();var e=[];if(null!=t.results&&0!==t.results.length){t.results=this.sort(t.results);for(var n=0;n",{class:"select2-results__options select2-results__options--nested"});h.append(s),o.append(a),o.append(h)}else this.template(t,e);return d.data(e,"data",t),e},i.prototype.bind=function(e,t){var l=this,n=e.id+"-results";this.$results.attr("id",n),e.on("results:all",function(t){l.clear(),l.append(t.data),e.isOpen()&&(l.setClasses(),l.highlightFirstItem())}),e.on("results:append",function(t){l.append(t.data),e.isOpen()&&l.setClasses()}),e.on("query",function(t){l.hideMessages(),l.showLoading(t)}),e.on("select",function(){e.isOpen()&&(l.setClasses(),l.highlightFirstItem())}),e.on("unselect",function(){e.isOpen()&&(l.setClasses(),l.highlightFirstItem())}),e.on("open",function(){l.$results.attr("aria-expanded","true"),l.$results.attr("aria-hidden","false"),l.setClasses(),l.ensureHighlightVisible()}),e.on("close",function(){l.$results.attr("aria-expanded","false"),l.$results.attr("aria-hidden","true"),l.$results.removeAttr("aria-activedescendant")}),e.on("results:toggle",function(){var t=l.getHighlightedResults();0!==t.length&&t.trigger("mouseup")}),e.on("results:select",function(){var t=l.getHighlightedResults();if(0!==t.length){var e=t.data("data");"true"==t.attr("aria-selected")?l.trigger("close",{}):l.trigger("select",{data:e})}}),e.on("results:previous",function(){var t=l.getHighlightedResults(),e=l.$results.find("[aria-selected]"),n=e.index(t);if(0!==n){var i=n-1;0===t.length&&(i=0);var r=e.eq(i);r.trigger("mouseenter");var o=l.$results.offset().top,a=r.offset().top,s=l.$results.scrollTop()+(a-o);0===i?l.$results.scrollTop(0):a-o<0&&l.$results.scrollTop(s)}}),e.on("results:next",function(){var t=l.getHighlightedResults(),e=l.$results.find("[aria-selected]"),n=e.index(t)+1;if(!(n>=e.length)){var i=e.eq(n);i.trigger("mouseenter");var r=l.$results.offset().top+l.$results.outerHeight(!1),o=i.offset().top+i.outerHeight(!1),a=l.$results.scrollTop()+o-r;0===n?l.$results.scrollTop(0):rthis.$results.outerHeight()||o<0)&&this.$results.scrollTop(r)}},i.prototype.template=function(t,e){var n=this.options.get("templateResult"),i=this.options.get("escapeMarkup"),r=n(t,e);null==r?e.style.display="none":"string"==typeof r?e.innerHTML=i(r):d(e).append(r)},i}),t.define("select2/keys",[],function(){return{BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46}}),t.define("select2/selection/base",["jquery","../utils","../keys"],function(n,t,r){function i(t,e){this.$element=t,this.options=e,i.__super__.constructor.call(this)}return t.Extend(i,t.Observable),i.prototype.render=function(){var t=n('');return this._tabindex=0,null!=this.$element.data("old-tabindex")?this._tabindex=this.$element.data("old-tabindex"):null!=this.$element.attr("tabindex")&&(this._tabindex=this.$element.attr("tabindex")),t.attr("title",this.$element.attr("title")),t.attr("tabindex",this._tabindex),this.$selection=t},i.prototype.bind=function(t,e){var n=this,i=(t.id,t.id+"-results");this.container=t,this.$selection.on("focus",function(t){n.trigger("focus",t)}),this.$selection.on("blur",function(t){n._handleBlur(t)}),this.$selection.on("keydown",function(t){n.trigger("keypress",t),t.which===r.SPACE&&t.preventDefault()}),t.on("results:focus",function(t){n.$selection.attr("aria-activedescendant",t.data._resultId)}),t.on("selection:update",function(t){n.update(t.data)}),t.on("open",function(){n.$selection.attr("aria-expanded","true"),n.$selection.attr("aria-owns",i),n._attachCloseHandler(t)}),t.on("close",function(){n.$selection.attr("aria-expanded","false"),n.$selection.removeAttr("aria-activedescendant"),n.$selection.removeAttr("aria-owns"),n.$selection.focus(),n._detachCloseHandler(t)}),t.on("enable",function(){n.$selection.attr("tabindex",n._tabindex)}),t.on("disable",function(){n.$selection.attr("tabindex","-1")})},i.prototype._handleBlur=function(t){var e=this;window.setTimeout(function(){document.activeElement==e.$selection[0]||n.contains(e.$selection[0],document.activeElement)||e.trigger("blur",t)},1)},i.prototype._attachCloseHandler=function(t){n(document.body).on("mousedown.select2."+t.id,function(t){var e=n(t.target).closest(".select2");n(".select2.select2-container--open").each(function(){var t=n(this);this!=e[0]&&t.data("element").select2("close")})})},i.prototype._detachCloseHandler=function(t){n(document.body).off("mousedown.select2."+t.id)},i.prototype.position=function(t,e){e.find(".selection").append(t)},i.prototype.destroy=function(){this._detachCloseHandler(this.container)},i.prototype.update=function(t){throw new Error("The `update` method must be defined in child classes.")},i}),t.define("select2/selection/single",["jquery","./base","../utils","../keys"],function(t,e,n,i){function r(){r.__super__.constructor.apply(this,arguments)}return n.Extend(r,e),r.prototype.render=function(){var t=r.__super__.render.call(this);return t.addClass("select2-selection--single"),t.html(''),t},r.prototype.bind=function(e,t){var n=this;r.__super__.bind.apply(this,arguments);var i=e.id+"-container";this.$selection.find(".select2-selection__rendered").attr("id",i),this.$selection.attr("aria-labelledby",i),this.$selection.on("mousedown",function(t){1===t.which&&n.trigger("toggle",{originalEvent:t})}),this.$selection.on("focus",function(t){}),this.$selection.on("blur",function(t){}),e.on("focus",function(t){e.isOpen()||n.$selection.focus()}),e.on("selection:update",function(t){n.update(t.data)})},r.prototype.clear=function(){this.$selection.find(".select2-selection__rendered").empty()},r.prototype.display=function(t,e){var n=this.options.get("templateSelection");return this.options.get("escapeMarkup")(n(t,e))},r.prototype.selectionContainer=function(){return t("")},r.prototype.update=function(t){if(0!==t.length){var e=t[0],n=this.$selection.find(".select2-selection__rendered"),i=this.display(e,n);n.empty().append(i),n.prop("title",e.title||e.text)}else this.clear()},r}),t.define("select2/selection/multiple",["jquery","./base","../utils"],function(i,t,s){function r(t,e){r.__super__.constructor.apply(this,arguments)}return s.Extend(r,t),r.prototype.render=function(){var t=r.__super__.render.call(this);return t.addClass("select2-selection--multiple"),t.html('
            '),t},r.prototype.bind=function(t,e){var n=this;r.__super__.bind.apply(this,arguments),this.$selection.on("click",function(t){n.trigger("toggle",{originalEvent:t})}),this.$selection.on("click",".select2-selection__choice__remove",function(t){if(!n.options.get("disabled")){var e=i(this).parent().data("data");n.trigger("unselect",{originalEvent:t,data:e})}})},r.prototype.clear=function(){this.$selection.find(".select2-selection__rendered").empty()},r.prototype.display=function(t,e){var n=this.options.get("templateSelection");return this.options.get("escapeMarkup")(n(t,e))},r.prototype.selectionContainer=function(){return i('
          • ×
          • ')},r.prototype.update=function(t){if(this.clear(),0!==t.length){for(var e=[],n=0;n×
            ');n.data("data",e),this.$selection.find(".select2-selection__rendered").prepend(n)}},t}),t.define("select2/selection/search",["jquery","../utils","../keys"],function(i,t,a){function e(t,e,n){t.call(this,e,n)}return e.prototype.render=function(t){var e=i('');this.$searchContainer=e,this.$search=e.find("input");var n=t.call(this);return this._transferTabIndex(),n},e.prototype.bind=function(t,e,n){var i=this;t.call(this,e,n),e.on("open",function(){i.$search.trigger("focus")}),e.on("close",function(){i.$search.val(""),i.$search.removeAttr("aria-activedescendant"),i.$search.trigger("focus")}),e.on("enable",function(){i.$search.prop("disabled",!1),i._transferTabIndex()}),e.on("disable",function(){i.$search.prop("disabled",!0)}),e.on("focus",function(t){i.$search.trigger("focus")}),e.on("results:focus",function(t){i.$search.attr("aria-activedescendant",t.id)}),this.$selection.on("focusin",".select2-search--inline",function(t){i.trigger("focus",t)}),this.$selection.on("focusout",".select2-search--inline",function(t){i._handleBlur(t)}),this.$selection.on("keydown",".select2-search--inline",function(t){if(t.stopPropagation(),i.trigger("keypress",t),i._keyUpPrevented=t.isDefaultPrevented(),t.which===a.BACKSPACE&&""===i.$search.val()){var e=i.$searchContainer.prev(".select2-selection__choice");if(0this.maximumInputLength?void this.trigger("results:message",{message:"inputTooLong",args:{maximum:this.maximumInputLength,input:e.term,params:e}}):void t.call(this,e,n)},t}),t.define("select2/data/maximumSelectionLength",[],function(){function t(t,e,n){this.maximumSelectionLength=n.get("maximumSelectionLength"),t.call(this,e,n)}return t.prototype.query=function(n,i,r){var o=this;this.current(function(t){var e=null!=t?t.length:0;return 0=o.maximumSelectionLength?void o.trigger("results:message",{message:"maximumSelected",args:{maximum:o.maximumSelectionLength}}):void n.call(o,i,r)})},t}),t.define("select2/dropdown",["jquery","./utils"],function(e,t){function n(t,e){this.$element=t,this.options=e,n.__super__.constructor.call(this)}return t.Extend(n,t.Observable),n.prototype.render=function(){var t=e('');return t.attr("dir",this.options.get("dir")),this.$dropdown=t},n.prototype.bind=function(){},n.prototype.position=function(t,e){},n.prototype.destroy=function(){this.$dropdown.remove()},n}),t.define("select2/dropdown/search",["jquery","../utils"],function(r,t){function e(){}return e.prototype.render=function(t){var e=t.call(this),n=r('');return this.$searchContainer=n,this.$search=n.find("input"),e.prepend(n),e},e.prototype.bind=function(t,e,n){var i=this;t.call(this,e,n),this.$search.on("keydown",function(t){i.trigger("keypress",t),i._keyUpPrevented=t.isDefaultPrevented()}),this.$search.on("input",function(t){r(this).off("keyup")}),this.$search.on("keyup input",function(t){i.handleSearch(t)}),e.on("open",function(){i.$search.attr("tabindex",0),i.$search.focus(),window.setTimeout(function(){i.$search.focus()},0)}),e.on("close",function(){i.$search.attr("tabindex",-1),i.$search.val("")}),e.on("focus",function(){e.isOpen()&&i.$search.focus()}),e.on("results:all",function(t){null!=t.query.term&&""!==t.query.term||(i.showSearch(t)?i.$searchContainer.removeClass("select2-search--hide"):i.$searchContainer.addClass("select2-search--hide"))})},e.prototype.handleSearch=function(t){if(!this._keyUpPrevented){var e=this.$search.val();this.trigger("query",{term:e})}this._keyUpPrevented=!1},e.prototype.showSearch=function(t,e){return!0},e}),t.define("select2/dropdown/hidePlaceholder",[],function(){function t(t,e,n,i){this.placeholder=this.normalizePlaceholder(n.get("placeholder")),t.call(this,e,n,i)}return t.prototype.append=function(t,e){e.results=this.removePlaceholder(e.results),t.call(this,e)},t.prototype.normalizePlaceholder=function(t,e){return"string"==typeof e&&(e={id:"",text:e}),e},t.prototype.removePlaceholder=function(t,e){for(var n=e.slice(0),i=e.length-1;0<=i;i--){var r=e[i];this.placeholder.id===r.id&&n.splice(i,1)}return n},t}),t.define("select2/dropdown/infiniteScroll",["jquery"],function(r){function t(t,e,n,i){this.lastParams={},t.call(this,e,n,i),this.$loadingMore=this.createLoadingMore(),this.loading=!1}return t.prototype.append=function(t,e){this.$loadingMore.remove(),this.loading=!1,t.call(this,e),this.showLoadingMore(e)&&this.$results.append(this.$loadingMore)},t.prototype.bind=function(t,e,n){var i=this;t.call(this,e,n),e.on("query",function(t){i.lastParams=t,i.loading=!0}),e.on("query:append",function(t){i.lastParams=t,i.loading=!0}),this.$results.on("scroll",function(){var t=r.contains(document.documentElement,i.$loadingMore[0]);if(!i.loading&&t){var e=i.$results.offset().top+i.$results.outerHeight(!1);i.$loadingMore.offset().top+i.$loadingMore.outerHeight(!1)<=e+50&&i.loadMore()}})},t.prototype.loadMore=function(){this.loading=!0;var t=r.extend({},{page:1},this.lastParams);t.page++,this.trigger("query:append",t)},t.prototype.showLoadingMore=function(t,e){return e.pagination&&e.pagination.more},t.prototype.createLoadingMore=function(){var t=r('
          • '),e=this.options.get("translations").get("loadingMore");return t.html(e(this.lastParams)),t},t}),t.define("select2/dropdown/attachBody",["jquery","../utils"],function(p,s){function t(t,e,n){this.$dropdownParent=n.get("dropdownParent")||p(document.body),t.call(this,e,n)}return t.prototype.bind=function(t,e,n){var i=this,r=!1;t.call(this,e,n),e.on("open",function(){i._showDropdown(),i._attachPositioningHandler(e),r||(r=!0,e.on("results:all",function(){i._positionDropdown(),i._resizeDropdown()}),e.on("results:append",function(){i._positionDropdown(),i._resizeDropdown()}))}),e.on("close",function(){i._hideDropdown(),i._detachPositioningHandler(e)}),this.$dropdownContainer.on("mousedown",function(t){t.stopPropagation()})},t.prototype.destroy=function(t){t.call(this),this.$dropdownContainer.remove()},t.prototype.position=function(t,e,n){e.attr("class",n.attr("class")),e.removeClass("select2"),e.addClass("select2-container--open"),e.css({position:"absolute",top:-999999}),this.$container=n},t.prototype.render=function(t){var e=p(""),n=t.call(this);return e.append(n),this.$dropdownContainer=e},t.prototype._hideDropdown=function(t){this.$dropdownContainer.detach()},t.prototype._attachPositioningHandler=function(t,e){var n=this,i="scroll.select2."+e.id,r="resize.select2."+e.id,o="orientationchange.select2."+e.id,a=this.$container.parents().filter(s.hasScroll);a.each(function(){p(this).data("select2-scroll-position",{x:p(this).scrollLeft(),y:p(this).scrollTop()})}),a.on(i,function(t){var e=p(this).data("select2-scroll-position");p(this).scrollTop(e.y)}),p(window).on(i+" "+r+" "+o,function(t){n._positionDropdown(),n._resizeDropdown()})},t.prototype._detachPositioningHandler=function(t,e){var n="scroll.select2."+e.id,i="resize.select2."+e.id,r="orientationchange.select2."+e.id;this.$container.parents().filter(s.hasScroll).off(n),p(window).off(n+" "+i+" "+r)},t.prototype._positionDropdown=function(){var t=p(window),e=this.$dropdown.hasClass("select2-dropdown--above"),n=this.$dropdown.hasClass("select2-dropdown--below"),i=null,r=this.$container.offset();r.bottom=r.top+this.$container.outerHeight(!1);var o={height:this.$container.outerHeight(!1)};o.top=r.top,o.bottom=r.top+o.height;var a=this.$dropdown.outerHeight(!1),s=t.scrollTop(),l=t.scrollTop()+t.height(),u=sr.bottom+a,h={left:r.left,top:o.bottom},d=this.$dropdownParent;"static"===d.css("position")&&(d=d.offsetParent());var f=d.offset();h.top-=f.top,h.left-=f.left,e||n||(i="below"),c||!u||e?!u&&c&&e&&(i="below"):i="above",("above"==i||e&&"below"!==i)&&(h.top=o.top-f.top-a),null!=i&&(this.$dropdown.removeClass("select2-dropdown--below select2-dropdown--above").addClass("select2-dropdown--"+i),this.$container.removeClass("select2-container--below select2-container--above").addClass("select2-container--"+i)),this.$dropdownContainer.css(h)},t.prototype._resizeDropdown=function(){var t={width:this.$container.outerWidth(!1)+"px"};this.options.get("dropdownAutoWidth")&&(t.minWidth=t.width,t.position="relative",t.width="auto"),this.$dropdown.css(t)},t.prototype._showDropdown=function(t){this.$dropdownContainer.appendTo(this.$dropdownParent),this._positionDropdown(),this._resizeDropdown()},t}),t.define("select2/dropdown/minimumResultsForSearch",[],function(){function t(t,e,n,i){this.minimumResultsForSearch=n.get("minimumResultsForSearch"),this.minimumResultsForSearch<0&&(this.minimumResultsForSearch=1/0),t.call(this,e,n,i)}return t.prototype.showSearch=function(t,e){return!(function t(e){for(var n=0,i=0;i');return t.attr("dir",this.options.get("dir")),this.$container=t,this.$container.addClass("select2-container--"+this.options.get("theme")),t.data("element",this.$element),t},c}),t.define("jquery-mousewheel",["jquery"],function(t){return t}),t.define("jquery.select2",["jquery","jquery-mousewheel","./select2/core","./select2/defaults"],function(r,t,o,e){if(null==r.fn.select2){var a=["open","close","destroy"];r.fn.select2=function(e){if("object"==typeof(e=e||{}))return this.each(function(){var t=r.extend(!0,{},e);new o(r(this),t)}),this;if("string"!=typeof e)throw new Error("Invalid arguments for Select2: "+e);var n,i=Array.prototype.slice.call(arguments,1);return this.each(function(){var t=r(this).data("select2");null==t&&window.console&&console.error&&console.error("The select2('"+e+"') method was called on an element that is not using Select2."),n=t[e].apply(t,i)}),-1r;)c(U,e=n[r++])||e==B||e==p||i.push(e);return i}function l(t){for(var e,n=t===G,i=F(n?Y:M(t)),r=[],o=0;i.length>o;)!c(U,e=i[o++])||n&&!c(G,e)||r.push(U[e]);return r}var u=n(2),c=n(3),h=n(4),d=n(6),f=n(16),p=n(20).KEY,g=n(5),m=n(21),v=n(22),y=n(17),b=n(23),x=n(24),w=n(25),S=n(27),_=n(40),C=n(43),k=n(10),M=n(30),T=n(14),D=n(15),A=n(44),P=n(47),E=n(49),O=n(9),L=n(28),I=E.f,N=O.f,F=P.f,R=u.Symbol,j=u.JSON,H=j&&j.stringify,z="prototype",B=b("_hidden"),W=b("toPrimitive"),$={}.propertyIsEnumerable,q=m("symbol-registry"),U=m("symbols"),Y=m("op-symbols"),G=Object[z],X="function"==typeof R,V=u.QObject,Z=!V||!V[z]||!V[z].findChild,K=h&&g(function(){return 7!=A(N({},"a",{get:function(){return N(this,"a",{value:7}).a}})).a})?function(t,e,n){var i=I(G,e);i&&delete G[e],N(t,e,n),i&&t!==G&&N(G,e,i)}:N,J=X&&"symbol"==typeof R.iterator?function(t){return"symbol"==typeof t}:function(t){return t instanceof R},Q=function(t,e,n){return t===G&&Q(Y,e,n),k(t),e=T(e,!0),k(n),c(U,e)?(n.enumerable?(c(t,B)&&t[B][e]&&(t[B][e]=!1),n=A(n,{enumerable:D(0,!1)})):(c(t,B)||N(t,B,D(1,{})),t[B][e]=!0),K(t,e,n)):N(t,e,n)};X||(f((R=function(){if(this instanceof R)throw TypeError("Symbol is not a constructor!");var e=y(0et;)b(tt[et++]);for(tt=L(b.store),et=0;tt.length>et;)w(tt[et++]);d(d.S+d.F*!X,"Symbol",{for:function(t){return c(q,t+="")?q[t]:q[t]=R(t)},keyFor:function(t){if(J(t))return S(q,t);throw TypeError(t+" is not a symbol!")},useSetter:function(){Z=!0},useSimple:function(){Z=!1}}),d(d.S+d.F*!X,"Object",{create:function(t,e){return e===Xt?A(t):r(A(t),e)},defineProperty:Q,defineProperties:r,getOwnPropertyDescriptor:a,getOwnPropertyNames:s,getOwnPropertySymbols:l}),j&&d(d.S+d.F*(!X||g(function(){var t=R();return"[null]"!=H([t])||"{}"!=H({a:t})||"{}"!=H(Object(t))})),"JSON",{stringify:function(t){if(t!==Xt&&!J(t)){for(var e,n,i=[t],r=1;arguments.length>r;)i.push(arguments[r++]);return"function"==typeof(e=i[1])&&(n=e),!n&&C(e)||(e=function(t,e){if(n&&(e=n.call(this,t,e)),!J(e))return e}),i[1]=e,H.apply(j,i)}}}),R[z][W]||n(8)(R[z],W,R[z].valueOf),v(R,"Symbol"),v(Math,"Math",!0),v(u.JSON,"JSON",!0)},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof r&&(r=n)},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){t.exports=!n(5)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e,n){var g=n(2),m=n(7),v=n(8),y=n(16),b=n(18),x="prototype",w=function(t,e,n){var i,r,o,a,s=t&w.F,l=t&w.G,u=t&w.S,c=t&w.P,h=t&w.B,d=l?g:u?g[e]||(g[e]={}):(g[e]||{})[x],f=l?m:m[e]||(m[e]={}),p=f[x]||(f[x]={});for(i in l&&(n=e),n)o=((r=!s&&d&&d[i]!==Xt)?d:n)[i],a=h&&r?b(o,g):c&&"function"==typeof o?b(Function.call,o):o,d&&y(d,i,o,t&w.U),f[i]!=o&&v(f,i,a),c&&p[i]!=o&&(p[i]=o)};g.core=m,w.F=1,w.G=2,w.S=4,w.P=8,w.B=16,w.W=32,w.U=64,w.R=128,t.exports=w},function(t,e){var n=t.exports={version:"2.4.0"};"number"==typeof i&&(i=n)},function(t,e,n){var i=n(9),r=n(15);t.exports=n(4)?function(t,e,n){return i.f(t,e,r(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e,n){var i=n(10),r=n(12),o=n(14),a=Object.defineProperty;e.f=n(4)?Object.defineProperty:function(t,e,n){if(i(t),e=o(e,!0),i(n),r)try{return a(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e,n){var i=n(11);t.exports=function(t){if(!i(t))throw TypeError(t+" is not an object!");return t}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,n){t.exports=!n(4)&&!n(5)(function(){return 7!=Object.defineProperty(n(13)("div"),"a",{get:function(){return 7}}).a})},function(t,e,n){var i=n(11),r=n(2).document,o=i(r)&&i(r.createElement);t.exports=function(t){return o?r.createElement(t):{}}},function(t,e,n){var r=n(11);t.exports=function(t,e){if(!r(t))return t;var n,i;if(e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;if("function"==typeof(n=t.valueOf)&&!r(i=n.call(t)))return i;if(!e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;throw TypeError("Can't convert object to primitive value")}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,n){var o=n(2),a=n(8),s=n(3),l=n(17)("src"),i="toString",r=Function[i],u=(""+r).split(i);n(7).inspectSource=function(t){return r.call(t)},(t.exports=function(t,e,n,i){var r="function"==typeof n;r&&(s(n,"name")||a(n,"name",e)),t[e]!==n&&(r&&(s(n,l)||a(n,l,t[e]?""+t[e]:u.join(String(e)))),t===o?t[e]=n:i?t[e]?t[e]=n:a(t,e,n):(delete t[e],a(t,e,n)))})(Function.prototype,i,function(){return"function"==typeof this&&this[l]||r.call(this)})},function(t,e){var n=0,i=Math.random();t.exports=function(t){return"Symbol(".concat(t===Xt?"":t,")_",(++n+i).toString(36))}},function(t,e,n){var o=n(19);t.exports=function(i,r,t){if(o(i),r===Xt)return i;switch(t){case 1:return function(t){return i.call(r,t)};case 2:return function(t,e){return i.call(r,t,e)};case 3:return function(t,e,n){return i.call(r,t,e,n)}}return function(){return i.apply(r,arguments)}}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e,n){function i(t){s(t,r,{value:{i:"O"+ ++l,w:{}}})}var r=n(17)("meta"),o=n(11),a=n(3),s=n(9).f,l=0,u=Object.isExtensible||function(){return!0},c=!n(5)(function(){return u(Object.preventExtensions({}))}),h=t.exports={KEY:r,NEED:!1,fastKey:function(t,e){if(!o(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!a(t,r)){if(!u(t))return"F";if(!e)return"E";i(t)}return t[r].i},getWeak:function(t,e){if(!a(t,r)){if(!u(t))return!0;if(!e)return!1;i(t)}return t[r].w},onFreeze:function(t){return c&&h.NEED&&u(t)&&!a(t,r)&&i(t),t}}},function(t,e,n){var i=n(2),r="__core-js_shared__",o=i[r]||(i[r]={});t.exports=function(t){return o[t]||(o[t]={})}},function(t,e,n){var i=n(9).f,r=n(3),o=n(23)("toStringTag");t.exports=function(t,e,n){t&&!r(t=n?t:t.prototype,o)&&i(t,o,{configurable:!0,value:e})}},function(t,e,n){var i=n(21)("wks"),r=n(17),o=n(2).Symbol,a="function"==typeof o;(t.exports=function(t){return i[t]||(i[t]=a&&o[t]||(a?o:r)("Symbol."+t))}).store=i},function(t,e,n){e.f=n(23)},function(t,e,n){var i=n(2),r=n(7),o=n(26),a=n(24),s=n(9).f;t.exports=function(t){var e=r.Symbol||(r.Symbol=o?{}:i.Symbol||{});"_"==t.charAt(0)||t in e||s(e,t,{value:a.f(t)})}},function(t,e){t.exports=!1},function(t,e,n){var s=n(28),l=n(30);t.exports=function(t,e){for(var n,i=l(t),r=s(i),o=r.length,a=0;ar;)a(i,n=e[r++])&&(~l(o,n)||o.push(n));return o}},function(t,e,n){var i=n(31),r=n(33);t.exports=function(t){return i(r(t))}},function(t,e,n){var i=n(32);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==i(t)?t.split(""):Object(t)}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e){t.exports=function(t){if(t==Xt)throw TypeError("Can't call method on "+t);return t}},function(t,e,n){var l=n(30),u=n(35),c=n(37);t.exports=function(s){return function(t,e,n){var i,r=l(t),o=u(r.length),a=c(n,o);if(s&&e!=e){for(;aa;)o.call(t,i=r[a++])&&e.push(i);return e}},function(t,e){e.f=Object.getOwnPropertySymbols},function(t,e){e.f={}.propertyIsEnumerable},function(t,e,n){var i=n(32);t.exports=Array.isArray||function(t){return"Array"==i(t)}},function(t,e,i){function r(){}var o=i(10),a=i(45),s=i(39),l=i(38)("IE_PROTO"),u="prototype",c=function(){var t,e=i(13)("iframe"),n=s.length;for(e.style.display="none",i(46).appendChild(e),e.src="javascript:",(t=e.contentWindow.document).open(),t.write("