diff --git a/.eslintrc.json b/.eslintrc.json index 2e5ddae2a..767d4a86e 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -8,13 +8,13 @@ "jquery" : true }, "parserOptions": { - "ecmaVersion": 7, + "ecmaVersion": 6, "sourceType": "module", "ecmaFeatures": { "jsx": true } }, - "parser": "babel-eslint", + "parser": "esprima", "rules": { "node/exports-style": [ "error", diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a887aaa8..74839246f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,112 @@ # Change Log All notable changes to the Wazuh app for Splunk project will be documented in this file. +## Wazuh v3.9.0 - Splunk Enterprise v7.2.4 / v7.2.5 / v7.2.6 - Revision 25 + +### Added + +- Support for Wazuh v3.9.0 +- Edit master and worker configuration ( + [#525](https://github.com/wazuh/wazuh-splunk/pull/525), + [#534](https://github.com/wazuh/wazuh-splunk/pull/534) + [#572](https://github.com/wazuh/wazuh-splunk/pull/572) + ). +- Edit local rules, local decoders and CDB lists ( +[#525](https://github.com/wazuh/wazuh-splunk/pull/525), +[#532](https://github.com/wazuh/wazuhsplunk/pull/532), +[#501](https://github.com/wazuh/wazuhsplunk/pull/501) +[#572](https://github.com/wazuh/wazuh-splunk/pull/572) +) +- Dev Tools additions +- Added hotkey `[shift] + [enter]` for sending query ([#503](https://github.com/wazuh/wazuh-splunk/pull/503)). +- Added `Export JSON` button for the Dev Tools ([#503](https://github.com/wazuh/wazuh-splunk/pull/503)). +- Added configuration assessment information in "Agent > Configuration Assessments" ([#505](https://github.com/wazuh/wazuh-splunk/pull/505)). +- Restart master and worker nodes ( + [#564](https://github.com/wazuh/wazuh-splunk/pull/564) + [#545](https://github.com/wazuh/wazuh-splunk/pull/545) + [#535](https://github.com/wazuh/wazuh-splunk/pull/535) + [#563](https://github.com/wazuh/wazuh-splunk/pull/563) + ). +- Restart agents ([#556](https://github.com/wazuh/wazuh-splunk/pull/556)). +- Discover function on each section ([#529](https://github.com/wazuh/wazuh-splunk/pull/529)). +- Can pined filters ( + [#529](https://github.com/wazuh/wazuh-splunk/pull/529) + [#618](https://github.com/wazuh/wazuh-splunk/pull/618)). +- Expand visualizations on the dashboard ([#570](https://github.com/wazuh/wazuh-splunk/pull/570)). +- Reporting as admin extension ([#585](https://github.com/wazuh/wazuh-splunk/pull/585)). +- Delete rules, decoders and CDB lists files ([#589](https://github.com/wazuh/wazuh-splunk/pull/589)). +- Prevent overwrite a existing file ([#589](https://github.com/wazuh/wazuh-splunk/pull/589)). +- Unescape back slash for JSON raw content ([#599](https://github.com/wazuh/wazuh-splunk/pull/599)). +- Capability to edit rules and decoders files ( + [#597](https://github.com/wazuh/wazuh-splunk/pull/597) + [#613](https://github.com/wazuh/wazuh-splunk/pull/613) + ). +- Allow navigation throught url ([#596](https://github.com/wazuh/wazuh-splunk/pull/596)). +- Enable back button ([#596](https://github.com/wazuh/wazuh-splunk/pull/596)). +- Capability to hide or show columns ( + [#566](https://github.com/wazuh/wazuh-splunk/pull/566) + [#614](https://github.com/wazuh/wazuh-splunk/pull/614) + ). +- Can resize columns ( + [#566](https://github.com/wazuh/wazuh-splunk/pull/566) + [#614](https://github.com/wazuh/wazuh-splunk/pull/614) + ). +- Cabability to expand visualizations ([#567](https://github.com/wazuh/wazuh-splunk/pull/567)). +- Set the browser time zone to the report ([#619](https://github.com/wazuh/wazuh-splunk/pull/619)). +- View no local rules/decoders XML files ([#667](https://github.com/wazuh/wazuh-splunk/pull/667)). +- Added some Angular charts in Agents Preview and Agents SCA sections ([#668](https://github.com/wazuh/wazuh-splunk/pull/668)). +- Added Docker listener settings in configuration views ([#665](https://github.com/wazuh/wazuh-splunk/pull/665)). +- Added Docker dashboards for both Agents and Overview ([#665](https://github.com/wazuh/wazuh-splunk/pull/665)). +- New server module, it's a job queue so we can add delayed jobs to be run in background, this iteration only accepts delayed Wazuh API calls ([#629](https://github.com/wazuh/wazuh-splunk/pull/629)). +- Added a dynamic table columns selecto ([#668](https://github.com/wazuh/wazuh-splunk/pull/668)). +- Added resizable columns by dragging in tables ([#668](https://github.com/wazuh/wazuh-splunk/pull/668)). +- Added an info bar when Wazuh is not ready yet in order to prevent App fails. ([#636](https://github.com/wazuh/wazuh-splunk/pull/636)). +- Show follow symbolic link in the configuration ondemand ([#685](https://github.com/wazuh/wazuh-splunk/pull/685)). -## Wazuh v3.8.2 - Splunk Enterprise v7.2.3 / v7.2.4 / v7.2.5 - Revision 22 +### Changed + +- Changed empty results message for Wazuh tables ([#487](https://github.com/wazuh/wazuh-splunk/pull/487)). +- Escape XML special characters ([#496](https://github.com/wazuh/wazuh-splunk/pull/496)). +- Allowing the same query multiple times on the Dev Tools ([#503](https://github.com/wazuh/wazuh-splunk/pull/503)). +- Using full height for all containers when possible ([#575](https://github.com/wazuh/wazuh-splunk/pull/575)). +- Changed some visualizations for FIM, GDPR, PCI, Vulnerability and Security Events ([#527](https://github.com/wazuh/wazuh-splunk/pull/527)). +- New design for agent header view ([#575](https://github.com/wazuh/wazuh-splunk/pull/575)). +- Not fetching data the very first time the Dev Tools are opened ([#503](https://github.com/wazuh/wazuh-splunk/pull/503)). +- Store the API database into Splunk KVstore ([#537](https://github.com/wazuh/wazuh-splunk/pull/537)). +- Notification toast types and style([#570](https://github.com/wazuh/wazuh-splunk/pull/570)). +- UI changes for editing groups ([#478](https://github.com/wazuh/wazuh-splunk/pull/478)). +- Use new meaningful toasters ([#591](https://github.com/wazuh/wazuh-splunk/pull/591)). +- Change several descriptions ([#597](https://github.com/wazuh/wazuh-splunk/pull/597)). +- Redisign configuration view ([#597](https://github.com/wazuh/wazuh-splunk/pull/597)). +- Updated autocomplete list in DevTools ([#538](https://github.com/wazuh/wazuh-splunk/pull/538)). +- Modularize some functions ([#601](https://github.com/wazuh/wazuh-splunk/pull/601)). +- View logs as raw text ([#604](https://github.com/wazuh/wazuh-splunk/pull/604)). +- Show logs in a text box ([#604](https://github.com/wazuh/wazuh-splunk/pull/604)). +- Reviewed Osquery dashboards ([#668](https://github.com/wazuh/wazuh-splunk/pull/668)). +- Improve audit dashboards ([#668](https://github.com/wazuh/wazuh-splunk/pull/668)). + +### Fixed + +- Permit special charsets in API credentials([#578](https://github.com/wazuh/wazuh-splunk/pull/578)). +- Can download API response in Devtools ([#559](https://github.com/wazuh/wazuh-splunk/pull/559)). +- Do not lose the focus of the navbar ([#558](https://github.com/wazuh/wazuh-splunk/pull/558)). +- Polling agents state ([#548](https://github.com/wazuh/wazuh-splunk/pull/548)). +- Reporting ([#504](https://github.com/wazuh/wazuh-splunk/pull/504)). +- Refresh rule info afeter edit it ([#589](https://github.com/wazuh/wazuh-splunk/pull/589)). +- Change the selected index ([#580](https://github.com/wazuh/wazuh-splunk/pull/580)). +- More descriptive error when savinga file and get an error ([#601](https://github.com/wazuh/wazuh-splunk/pull/601)). +- Show success message when group configuration is saved ([#601](https://github.com/wazuh/wazuh-splunk/pull/601)). +- Error when trying to download a CSV file ([#604](https://github.com/wazuh/wazuh-splunk/pull/604)). +- Do not show pagination for one-page tables ([#668](https://github.com/wazuh/wazuh-splunk/pull/668)). +- Show email configuration on the configuration on demand ([#672](https://github.com/wazuh/wazuh-splunk/pull/672)). +- Unify timezone ([#673](https://github.com/wazuh/wazuh-splunk/pull/673)). +- Properly handling long messages on notifier service, until now, they were using out of the card space, also we replaced some API messages with more meaningful messages ([#570](https://github.com/wazuh/wazuh-splunk/pull/570)). +- Adapted Wazuh icon for multiple browsers where it was gone ([#475](https://github.com/wazuh/wazuh-splunk/pull/475)). + +## Wazuh v3.8.2 - Splunk Enterprise v7.2.3 - Revision 22 ### Added - Support for Wazuh v3.8.2 -- Support for Splunk v7.2.3 / v7.2.4 / v7.2.5 ### Changed @@ -53,6 +153,7 @@ All notable changes to the Wazuh app for Splunk project will be documented in th - Updated localfile values in the configuration of an agent ([#451](https://github.com/wazuh/wazuh-splunk/pull/451)). - Dev tools is now showing the response as it is, like curl does ([#461](https://github.com/wazuh/wazuh-splunk/pull/461)). - Removed `unknown` as valid node name ([#477](https://github.com/wazuh/wazuh-splunk/pull/477)). +- Agents header. ([#518](https://github.com/wazuh/wazuh-splunk/pull/518)). ### Fixed @@ -66,8 +167,6 @@ All notable changes to the Wazuh app for Splunk project will be documented in th - Fix Dev-tools behavior when parse json invalid blocks ([#430](https://github.com/wazuh/wazuh-splunk/pull/430)). - Fix rule details for `list` and `info` parameters ([#477](https://github.com/wazuh/wazuh-splunk/pull/477)). -## Wazuh v3.7.2 - Splunk Enterprise v7.2.1 - Revision 19 -There are no changes for Splunk app for Wazuh in this version. ## Wazuh v3.7.2 - Splunk Enterprise v7.2.1 - Revision 19 There are no changes for Splunk app for Wazuh in this version. @@ -98,6 +197,7 @@ There are no changes for Splunk app for Wazuh in this version. - Updated searches for AWS section ([#374](https://github.com/wazuh/wazuh-splunk/pull/374)). ## Wazuh v3.7.0 - Splunk Enterprise v7.2.0 / Splunk Enterprise v7.2.1 - Revision 17 + ### Added - Osquery integration ([#252](https://github.com/wazuh/wazuh-splunk/pull/252)). - Cluster monitoring ([#246](https://github.com/wazuh/wazuh-splunk/pull/246)). @@ -105,25 +205,31 @@ There are no changes for Splunk app for Wazuh in this version. - Added a node selector for _Management > Logs_ section when Wazuh cluster is enabled ([#299](https://github.com/wazuh/wazuh-splunk/pull/299)). ### Changed -- Configuration section ([#261](https://github.com/wazuh/wazuh-splunk/pull/261)) +- Configuration section ([#261](https://github.com/wazuh/wazuh-splunk/pull/261)). - FIM section ([#255](https://github.com/wazuh/wazuh-splunk/pull/255)). - Settings section ([#265](https://github.com/wazuh/wazuh-splunk/pull/265)). - The `wz-table` directive now checks if a request is aborted ([#301](https://github.com/wazuh/wazuh-splunk/pull/301)). ### Fixes - Minor fixes. + ## Wazuh v3.6.1 - Splunk Enterprise v7.1.3 - Revision 16 + ### Added - AWS integration ([#247](https://github.com/wazuh/wazuh-splunk/pull/247)). + ### Fixes - Support for SSL with reverse proxy configuration ([#248](https://github.com/wazuh/wazuh-splunk/pull/248)). - Minor fixes. + ## Wazuh v3.6.1 - Splunk Enterprise v7.1.3 - Revision 15 + ### Added - App log section ([#237](https://github.com/wazuh/wazuh-splunk/pull/237)). - Support for reverse proxy configuration ([#239](https://github.com/wazuh/wazuh-splunk/pull/239)). - Dev tools ([#233](https://github.com/wazuh/wazuh-splunk/pull/233)). - Agent inventory section ([#238](https://github.com/wazuh/wazuh-splunk/pull/238)). + ### Fixes - Minor fixes ([#241](https://github.com/wazuh/wazuh-splunk/pull/241)). @@ -132,13 +238,13 @@ There are no changes for Splunk app for Wazuh in this version. - Minor fixes. ## Wazuh v3.6.0 - Splunk Enterprise v7.1.2 - Revision 13 -- Minor fixes ([#229](https://github.com/wazuh/wazuh-splunk/pull/229)) +- Minor fixes ([#229](https://github.com/wazuh/wazuh-splunk/pull/229)). ## Wazuh v3.6.0 - Splunk Enterprise v7.1.2 - Revision 12 - Support for Wazuh 3.6.0 ## Wazuh v3.5.0 - Splunk Enterprise v7.1.2 - Revision 11 -- Minor fixes ([#211](https://github.com/wazuh/wazuh-splunk/pull/211)) +- Minor fixes ([#211](https://github.com/wazuh/wazuh-splunk/pull/211)). ## Wazuh v3.5.0 - Splunk Enterprise v7.1.2 - Revision 10 - Support for Wazuh v3.5.0 @@ -147,41 +253,48 @@ There are no changes for Splunk app for Wazuh in this version. There are no changes for Splunk app for Wazuh in this version. ## Wazuh v3.3.0/v3.3.1 - Splunk Enterprise v7.1.1 - Revision 8 + ### Added - Support for Wazuh v3.3.1 -- Redesigned agents summary dashboard ([#115](https://github.com/wazuh/wazuh-splunk/pull/115)) -- Manager status dashboard redesigned ([#117](https://github.com/wazuh/wazuh-splunk/pull/117)) -- Manager configuration dashboard redesigned ([#120](https://github.com/wazuh/wazuh-splunk/pull/120)) -- Agent group configuration dashboard redesigned ([#122](https://github.com/wazuh/wazuh-splunk/pull/122)) -- Groups configuration dashboard redesigned ([#125](https://github.com/wazuh/wazuh-splunk/pull/125)) -- Rules and decoders dashboards redesigned ([#128](https://github.com/wazuh/wazuh-splunk/pull/128)) -- Logs dashboard redesigned ([#130](https://github.com/wazuh/wazuh-splunk/pull/130)) -- Settings dashboard redesigned ([#133](https://github.com/wazuh/wazuh-splunk/pull/133)) +- Redesigned agents summary dashboard ([#115](https://github.com/wazuh/wazuh-splunk/pull/115)). +- Manager status dashboard redesigned ([#117](https://github.com/wazuh/wazuh-splunk/pull/117)). +- Manager configuration dashboard redesigned ([#120](https://github.com/wazuh/wazuh-splunk/pull/120)). +- Agent group configuration dashboard redesigned ([#122](https://github.com/wazuh/wazuh-splunk/pull/122)). +- Groups configuration dashboard redesigned ([#125](https://github.com/wazuh/wazuh-splunk/pull/125)). +- Rules and decoders dashboards redesigned ([#128](https://github.com/wazuh/wazuh-splunk/pull/128)). +- Logs dashboard redesigned ([#130](https://github.com/wazuh/wazuh-splunk/pull/130)). +- Settings dashboard redesigned ([#133](https://github.com/wazuh/wazuh-splunk/pull/133)). ### Fixed -- Fixed Firefox bug ([#114](https://github.com/wazuh/wazuh-splunk/pull/114)) -- Fixed table filters ([#131](https://github.com/wazuh/wazuh-splunk/pull/131)) -- Minor fixes ([#136](https://github.com/wazuh/wazuh-splunk/pull/136)) +- Fixed Firefox bug ([#114](https://github.com/wazuh/wazuh-splunk/pull/114)). +- Fixed table filters ([#131](https://github.com/wazuh/wazuh-splunk/pull/131)). +- Minor fixes ([#136](https://github.com/wazuh/wazuh-splunk/pull/136)). ## Wazuh v3.3.0 - Splunk Enterprise v7.1.1 - Revision 7 + ### Added -- Polling and index agent status data ([#101](https://github.com/wazuh/wazuh-splunk/pull/101)) +- Polling and index agent status data ([#101](https://github.com/wazuh/wazuh-splunk/pull/101)). + ### Changed -- Selecting 'wazuh' index when any other is selected ([#100](https://github.com/wazuh/wazuh-splunk/issues/100)) +- Selecting 'wazuh' index when any other is selected ([#100](https://github.com/wazuh/wazuh-splunk/issues/100)). + ### Fixed -- Extending response timeout in checking connection endpoint ([#509cb7b](https://github.com/wazuh/wazuh-splunk/pull/101/commits/509cb7bab923294dcd5c5d2f93fff9425356f056)) -- Deprecated interval field in manager configuration cluster section ([#93](https://github.com/wazuh/wazuh-splunk/issues/93)) +- Extending response timeout in checking connection endpoint ([#509cb7b](https://github.com/wazuh/wazuh-splunk/pull/101/commits/509cb7bab923294dcd5c5d2f93fff9425356f056)). +- Deprecated interval field in manager configuration cluster section ([#93](https://github.com/wazuh/wazuh-splunk/issues/93)). ## Wazuh v3.2.4 - Splunk Enterprise v7.1.1 - Revision 6 There are no changes for Splunk app for Wazuh in this version. ## Wazuh v3.2.3 - Splunk Enterprise v7.1.1 - Revision 6 + ### Added -- New About tab ([#67](https://github.com/wazuh/wazuh-splunk/pull/67)) -- New GDPR tabs ([#66](https://github.com/wazuh/wazuh-splunk/pull/66)) -- New multi Index support ([#79](https://github.com/wazuh/wazuh-splunk/pull/79)) +- New About tab ([#67](https://github.com/wazuh/wazuh-splunk/pull/67)). +- New GDPR tabs ([#66](https://github.com/wazuh/wazuh-splunk/pull/66)). +- New multi Index support ([#79](https://github.com/wazuh/wazuh-splunk/pull/79)). + ### Changed -- Multi-API support ([#65](https://github.com/wazuh/wazuh-splunk/pull/65)) +- Multi-API support ([#65](https://github.com/wazuh/wazuh-splunk/pull/65)). + ### Fixed - First API inserted is now selected by default [#47a1fe7](https://github.com/wazuh/wazuh-splunk/commit/47a1fe71f8b32c27b2ac51c3134b93447bd8d6f4) - Any API will be inserted if it hasn't connectivity [#47a1fe7](https://github.com/wazuh/wazuh-splunk/commit/47a1fe71f8b32c27b2ac51c3134b93447bd8d6f4) @@ -192,23 +305,28 @@ There are no changes for Splunk app for Wazuh in this version. ## Wazuh v3.2.3 - Splunk Enterprise v7.1.1 - Revision 5 There are no changes for Splunk app for Wazuh in this version. + ## Wazuh v3.2.2 - Splunk Enterprise v7.1.1 - Splunk app v3.2.2 + ### Added - Wazuh secured API connections are now supported ([#51](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/51)). - Error notifications with toasts ([#54](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/54)). - New agent group configuration tab added ([#50](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/50)). - Inputs need to be validated before being submitted ([#52](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/52)). + ### Changed - Styling improvements ([#57](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/57)). - Users can't navigate over the app without API successful connection. - Controllers logic refactor. + ### Fixed - Navigation navbar background color fixed. ## Wazuh v3.2.1 - Splunk Enterprise > v6.6.0 - Splunk app v2.2.0 + ### Added -- New Manager Configuration tab ([#32](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/32)) -- Dynamic tables([#37](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/37)) +- New Manager Configuration tab ([#32](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/32)). +- Dynamic tables([#37](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/37)). - Now the app uses dynamic tables improving the pagination and filtering. - Backend endpoints were adapted to pagination and better interaction with Wazuh API. @@ -226,13 +344,16 @@ There are no changes for Splunk app for Wazuh in this version. - Deleted redundant Agents summary views and compact them in just one tab - Deleted Search on Rules and Search on Decoders tab and compacting all functionalities in Ruleset and Decoders tabs - Tab names were renamed + ### Fixed - Ruleset and Decoders search tabs now are able to filter properly. - SSL Verification Error in lab environment fixed - Groups: now the content of each individual configuration file is showed up in pretty JSON format properly. - Splunk queries fixed: - Now a query is executed when a Splunk element such tables and tags are clicked + ## Wazuh v3.2.1 - Splunk Enterprise > v6.6.0 - Splunk app v2.1.0 + ### Added - New Configuration tab: - Now the whole configuration that the app needs is made by inputs. @@ -246,25 +367,27 @@ There are no changes for Splunk app for Wazuh in this version. - Credentials are now stored in KVStore database, values are getting from ajax when needed. - Each query now send parameters to streaming commands. - The app is now called 'Wazuh' instead 'SplunkAppForWazuh'. -- Some unused tabs were deleted (Splunk and Tools). +- Some unused tabs were deleted (Splunk and Tools) + ### Fixed - Ruleset and Decoders search tabs now are able to filter properly. ## Wazuh v3.2.1 - Splunk Enterprise > v6.6.0 - Splunk app v2.0.0 + ### Added -- New Manager Logs tab ([#6](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/6)): +- New Manager Logs tab ([#6](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/6)):. - New module implemented to show Manager logs. - Data is fetched directly from Wazuh API. -- Back-end ([#14](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/14)) +- Back-end ([#14](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/14)). - Now the Splunk App has its own backend in order to modularize any REST routes it might need. - Several code refactoring for a better handling of possible use cases. - All queries along the App where bootstrapped in order to use the new back-end instead using indexes. ### Changed -- Ruleset and Decoders data will be fetched from API ([#12](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/12)): +- Ruleset and Decoders data will be fetched from API ([#12](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/12)):. - Now the app will avoid indexing Ruleset and Decoders data. -- Manager info will be fetched from API ([#14](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/14)): +- Manager info will be fetched from API ([#14](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/14)):. - Now the app will avoid indexing Manager info data. -- Agents data will be fetched from API ([#15](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/15)): +- Agents data will be fetched from API ([#15](https://github.com/SplunkAppForWazuh/SplunkAppForWazuh-splunk/pull/15)):. - Now the app will avoid indexing Agents info data. - And the best thing, it's no longer needed any extra index and the TA-wazuh-api-connector anymore. diff --git a/README.md b/README.md index 80865cac1..eae9fe65f 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ | 7.2.3 | 3.8.2 | | | 7.2.4 | 3.8.2 | | | 7.2.5 | 3.8.2 | | +| 7.2.6 | 3.8.2 | | +| 7.2.6 | 3.9.0 | | ## Upgrade diff --git a/SplunkAppForWazuh/README.md b/SplunkAppForWazuh/README.md new file mode 100644 index 000000000..998a27323 --- /dev/null +++ b/SplunkAppForWazuh/README.md @@ -0,0 +1,67 @@ +# Splunk app for Wazuh + +[![Slack](https://img.shields.io/badge/slack-join-blue.svg)](https://wazuh.com/community/join-us-on-slack/) +[![Email](https://img.shields.io/badge/email-join-blue.svg)](https://groups.google.com/forum/#!forum/wazuh) +[![Documentation](https://img.shields.io/badge/docs-view-green.svg)](https://documentation.wazuh.com) +[![Documentation](https://img.shields.io/badge/web-view-green.svg)](https://wazuh.com) + + Wazuh app for Splunk offers an option to visualize _Wazuh Alerts_ and _API data_. Wazuh helps you to gain deeper security visibility into your infrastructure by monitoring hosts at an operating system and application level. +* * * +![](https://i.imgur.com/HkMjiwJ.png) +### Documentation + +- [Wazuh app for Splunk installation guide](https://documentation.wazuh.com/current/installing-splunk/index.html) + + +### Requisites +1. An already installed Wazuh Manager with access to the API. +2. __Splunk Universal Forwarder__ where Wazuh Manager is installed. +3. At least one __Splunk Enterprise indexer__. + +## Installation + +| Splunk version | Wazuh version | Installation | +| :------------: | :---------------: | :--------------------------------------------------------------------------------------------------------- | +| 7.0.3 | 3.2.1 | | +| 7.1.1 | 3.2.2 | | +| 7.1.1 | 3.2.3 | | +| 7.1.1 | 3.2.4 | | +| 7.1.1 | 3.3.0 | | +| 7.1.1 | 3.3.1 | | +| 7.1.2 | 3.4.0 | | +| 7.1.2 | 3.5.0 | | +| 7.1.2 | 3.6.0 | | +| 7.1.3 | 3.6.1 | | +| 7.2.0 | 3.7.0 | | +| 7.2.1 | 3.7.0 | | +| 7.2.1 | 3.7.1 | | +| 7.2.1 | 3.7.2 | | +| 7.2.3 | 3.8.0 | | + +## Upgrade + +Remove the app using splunk plugin tool + + $SPLUNK_HOME/bin/splunk remove app SplunkAppForWazuh + +Install the app + + $SPLUNK_HOME/bin/splunk install app + +## Contribute + +If you want to contribute to our project please don't hesitate to send a pull request. You can also join our users [mailing list](https://groups.google.com/d/forum/wazuh), by sending an email to , to ask questions and participate in discussions. + +## Copyright & License + +Copyright (C) 2015-2019 Wazuh, Inc. + +This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. + +Find more information about this on the [LICENSE](LICENSE) file. + +## References + +- [Wazuh website](https://wazuh.com) +- [Wazuh documentation](https://documentation.wazuh.com) +- [Splunk documentation](http://docs.splunk.com/Documentation) diff --git a/SplunkAppForWazuh/appserver/controllers/api.py b/SplunkAppForWazuh/appserver/controllers/api.py index 7b4b26dca..42400e13c 100644 --- a/SplunkAppForWazuh/appserver/controllers/api.py +++ b/SplunkAppForWazuh/appserver/controllers/api.py @@ -12,7 +12,6 @@ Find more information about this on the LICENSE file. """ - import jsonbak import requestsbak import csv @@ -22,8 +21,8 @@ from db import database from log import log from splunk.clilib import cli_common as cli - - +from requirements import pci_requirements,gdpr_requirements +import time class api(controllers.BaseController): @@ -43,6 +42,25 @@ def __init__(self): except Exception as e: self.logger.error("Error in API module constructor: %s" % (e)) + def get_credentials(self, the_id): + try: + api = self.db.get(the_id) + api = jsonbak.loads(api) + if api: + opt_username = api['data']["userapi"] + opt_password = api['data']["passapi"] + opt_base_url = api['data']["url"] + opt_base_port = api['data']["portapi"] + url = str(opt_base_url) + ":" + str(opt_base_port) + auth = requestsbak.auth.HTTPBasicAuth(opt_username, opt_password) + verify = False + cluster_enabled = True if api['data']['filterType'] == "cluster.name" else False + return url, auth, verify, cluster_enabled + else: + raise Exception('API not found') + except Exception as e: + raise e + def getSelfAdminStanza(self): """Get the configuration from a stanza. """ @@ -56,34 +74,42 @@ def getSelfAdminStanza(self): def clean_keys(self, response): """Hide sensible data from API response.""" try: - res = response["data"] hide = "********" - # Remove agent key - if "internal_key" in res: - res["internal_key"] = hide - # Remove cluster key (/come/cluster) - if "node_type" in res and "key" in res: - res["key"] = hide - # Remove cluster key (/manager/configuration) - if "cluster" in res: - if "node_type" in res["cluster"] and "key" in res["cluster"]: - res["cluster"]["key"] = hide - - # Remove AWS keys - if "wmodules" in res: - for wmod in res["wmodules"]: - if "aws-s3" in wmod: - if "buckets" in wmod["aws-s3"]: - for bucket in wmod["aws-s3"]["buckets"]: - bucket["access_key"] = hide - bucket["secret_key"] = hide - # Remove integrations keys - if "integration" in res: - for integ in res["integration"]: - integ["api_key"] = hide - response["data"] = res - return jsonbak.dumps(response) + if "data" in response and type(response["data"]) == dict: + # Remove agent key + if "internal_key" in response["data"]: + response["data"]["internal_key"] = hide + + # Remove cluster key (/come/cluster) + if "node_type" in response["data"]: + if "key" in response["data"]: + response["data"]["key"] = hide + + # Remove cluster key (/manager/configuration) + if "cluster" in response["data"]: + if "node_type" in response["data"]["cluster"] and "key" in response["data"]["cluster"]: + response["data"]["cluster"]["key"] = hide + + # Remove AWS keys + if "wmodules" in response["data"]: + for wmod in response["data"]["wmodules"]: + if "aws-s3" in wmod: + if "buckets" in wmod["aws-s3"]: + for bucket in wmod["aws-s3"]["buckets"]: + bucket["access_key"] = hide + bucket["secret_key"] = hide + if "services" in wmod["aws-s3"]: + for service in wmod["aws-s3"]["services"]: + service["access_key"] = hide + service["secret_key"] = hide + + # Remove integrations keys + if "integration" in response["data"]: + for integ in response["data"]["integration"]: + integ["api_key"] = hide + return response except Exception as e: + self.logger.error("Error while cleaning keys in request response: %s" % (e)) raise e def format_output(self, arr): @@ -117,9 +143,120 @@ def format_output(self, arr): except Exception as e: raise e - # /custom/SplunkAppForWazuh/api/node - # This will perform an HTTP request to Wazuh API - # It will return the full API response with including its error codes + def format_cdb_list_content(self, dic): + """Format the response of custom CDB list. + + Parameters + ---------- + dic : dic + A dic with the response. + """ + try: + items = dic["data"]["items"][0] + dic["data"]["items"] = [{"items": items}] + return dic + except Exception as e: + self.logger.error("Error formating CDB list: %s" % (e)) + raise e + + + def make_request(self, method, url, opt_endpoint, kwargs, auth, verify, counter = 3): + try: + socket_errors = (1013, 1014, 1017, 1018, 1019) + if method == 'GET': + request = self.session.get( + url + opt_endpoint, params=kwargs, auth=auth, + verify=verify).json() + if method == 'POST': + if 'origin' in kwargs: + if kwargs['origin'] == 'xmleditor': + headers = {'Content-Type': 'application/xml'} + elif kwargs['origin'] == 'json': + headers = {'Content-Type': 'application/json'} + elif kwargs['origin'] == 'raw': + headers = {'Content-Type': 'application/octet-stream'} + kwargs = str(kwargs['content']) + request = self.session.post(url + opt_endpoint, data=kwargs, auth=auth,verify=verify, headers=headers).json() + else: + request = self.session.post( + url + opt_endpoint, data=kwargs, auth=auth, + verify=verify).json() + if method == 'PUT': + request = self.session.put( + url + opt_endpoint, data=kwargs, auth=auth, + verify=verify).json() + if method == 'DELETE': + request = self.session.delete( + url + opt_endpoint, data=kwargs, auth=auth, + verify=verify).json() + if request['error'] and request['error'] in socket_errors: + if counter > 0: + time.sleep(0.5) + return self.make_request(method, url, opt_endpoint, kwargs, auth, verify, counter - 1) + else: + raise Exception("Tried to execute %s %s three times with no success, aborted." % (method, opt_endpoint)) + return self.clean_keys(request) + except Exception as e: + self.logger.error("Error while requesting to Wazuh API: %s" % (e)) + raise e + + def check_daemons(self, url, auth, verify, check_cluster): + """ Request to check the status of this daemons: execd, modulesd, wazuhdb and clusterd + + Parameters + ---------- + url: str + auth: str + verify: str + cluster_enabled: bool + """ + try: + request_cluster = self.session.get( + url + '/cluster/status', auth=auth, timeout=20, verify=verify).json() + # Try to get cluster is enabled if the request fail set to false + try: + cluster_enabled = request_cluster['data']['enabled'] == 'yes' + except Exception as e: + cluster_enabled = False + cc = check_cluster and cluster_enabled # Var to check the cluster demon or not + opt_endpoint = "/manager/status" + daemons_status = self.session.get( + url + opt_endpoint, auth=auth, + verify=verify).json() + if not daemons_status['error']: + d = daemons_status['data'] + daemons = {"execd": d['ossec-execd'], "modulesd": d['wazuh-modulesd'], "db": d['wazuh-db']} + if cc: + daemons['clusterd'] = d['wazuh-clusterd'] + values = list(daemons.values()) + wazuh_ready = len(set(values)) == 1 and values[0] == "running" # Checks all the status are equals, and running + return wazuh_ready + except Exception as e: + self.logger.error("Error checking daemons: %s" % (e)) + raise e + + + @expose_page(must_login=False, methods=['POST']) + def wazuh_ready(self, **kwargs): + """Endpoint to check daemons status. + + Parameters + ---------- + kwargs : dict + Request parameters + """ + try: + if 'id' not in kwargs: + return jsonbak.dumps({'error': 'Missing API ID.'}) + the_id = kwargs['id'] + url, auth, verify, cluster_enabled = self.get_credentials(the_id) + daemons_ready = self.check_daemons(url, auth, verify, cluster_enabled) + msg = "Wazuh is now ready." if daemons_ready else "Wazuh not ready yet." + return jsonbak.dumps({"status": "200", "ready": daemons_ready, "message": msg}) + except Exception as e: + self.logger.error("Error checking daemons: %s" % (e)) + return jsonbak.dumps({"status": "200", "ready": False, "message": "Error getting the Wazuh daemons status."}) + @expose_page(must_login=False, methods=['POST']) def request(self, **kwargs): """Make requests to the Wazuh API as a proxy backend. @@ -144,40 +281,15 @@ def request(self, **kwargs): method = kwargs['method'] del kwargs['method'] the_id = kwargs['id'] - api = self.db.get(the_id) - if api: - opt_username = api[0]["userapi"] - opt_password = api[0]["passapi"] - opt_base_url = api[0]["url"] - opt_base_port = api[0]["portapi"] - opt_endpoint = kwargs["endpoint"] - del kwargs['id'] - del kwargs['endpoint'] - url = opt_base_url + ":" + opt_base_port - auth = requestsbak.auth.HTTPBasicAuth(opt_username, opt_password) - verify = False - if method == 'GET': - request = self.session.get( - url + opt_endpoint, params=kwargs, auth=auth, - verify=verify).json() - if method == 'POST': - if 'origin' in kwargs and kwargs['origin'] == 'xmleditor': - headers = {'Content-Type': 'application/xml'} - kwargs = str(kwargs['content']) - request = self.session.post(url + opt_endpoint, data=kwargs, auth=auth,verify=verify, headers=headers).json() - else: - request = self.session.post( - url + opt_endpoint, data=kwargs, auth=auth, - verify=verify).json() - if method == 'PUT': - request = self.session.put( - url + opt_endpoint, data=kwargs, auth=auth, - verify=verify).json() - if method == 'DELETE': - request = self.session.delete( - url + opt_endpoint, data=kwargs, auth=auth, - verify=verify).json() - result = jsonbak.dumps(request) + url, auth, verify, cluster_enabled = self.get_credentials(the_id) + opt_endpoint = kwargs["endpoint"] + del kwargs['id'] + del kwargs['endpoint'] + daemons_ready = self.check_daemons(url, auth, verify, cluster_enabled) + if not daemons_ready: + return jsonbak.dumps({"status": "200", "error": 3099, "message": "Wazuh not ready yet."}) + request = self.make_request(method, url, opt_endpoint, kwargs, auth, verify) + result = jsonbak.dumps(request) except Exception as e: self.logger.error("Error making API request: %s" % (e)) return jsonbak.dumps({'error': str(e)}) @@ -187,12 +299,11 @@ def request(self, **kwargs): def autocomplete(self, **kwargs): """Provisional method for returning the full list of Wazuh API endpoints.""" try: - parsed_json = jsonbak.dumps([{"method":'PUT',"endpoints":[{"name":'/active-response/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/group/:group_id',"args":[{"name":':agent_id'},{"name":':group_id'}]},{"name":'/agents/:agent_id/restart',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/upgrade',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/upgrade_custom',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_name',"args":[{"name":':agent_name'}]},{"name":'/agents/groups/:group_id',"args":[{"name":':group_id'}]},{"name":'/agents/restart',"args":[]},{"name":'/rootcheck',"args":[]},{"name":'/rootcheck/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/syscheck',"args":[]},{"name":'/syscheck/:agent_id',"args":[{"name":':agent_id'}]}]},{"method":'DELETE',"endpoints":[{"name":'/agents',"args":[]},{"name":'/agents/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/group',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/group/:group_id',"args":[{"name":':agent_id'},{"name":':group_id'}]},{"name":'/agents/groups',"args":[]},{"name":'/agents/groups/:group_id',"args":[{"name":':group_id'}]},{"name":'/cache',"args":[]},{"name":'/cache',"args":[]},{"name":'/experimental/syscheck',"args":[]},{"name":'/rootcheck',"args":[]},{"name":'/rootcheck/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/syscheck/:agent_id',"args":[{"name":':agent_id'}]}]},{"method":'GET',"endpoints":[{"name":'/agents',"args":[]},{"name":'/agents/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/config/:component/:configuration',"args":[{"name":':agent_id'},{"name":':component'},{"name":':configuration'}]},{"name":'/agents/:agent_id/group/is_sync',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/key',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/upgrade_result',"args":[{"name":':agent_id'}]},{"name":'/agents/groups',"args":[]},{"name":'/agents/groups/:group_id',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/configuration',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/files',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/files/:filename',"args":[{"name":':group_id'},{"name":':filename'}]},{"name":'/agents/"name"/:agent_name',"args":[{"name":':agent_name'}]},{"name":'/agents/no_group',"args":[]},{"name":'/agents/outdated',"args":[]},{"name":'/agents/stats/distinct',"args":[]},{"name":'/agents/summary',"args":[]},{"name":'/agents/summary/os',"args":[]},{"name":'/cache',"args":[]},{"name":'/cache/config',"args":[]},{"name":'/ciscat/:agent_id/results',"args":[{"name":':agent_id'}]},{"name":'/cluster/:node_id/configuration',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/info',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/logs',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/logs/summary',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats/hourly',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats/weekly',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/status',"args":[{"name":':node_id'}]},{"name":'/cluster/config',"args":[]},{"name":'/cluster/healthcheck',"args":[]},{"name":'/cluster/node',"args":[]},{"name":'/cluster/nodes',"args":[]},{"name":'/cluster/nodes/:node_name',"args":[{"name":':node_name'}]},{"name":'/cluster/status',"args":[]},{"name":'/decoders',"args":[]},{"name":'/decoders/:decoder_name',"args":[{"name":':decoder_name'}]},{"name":'/decoders/files',"args":[]},{"name":'/decoders/parents',"args":[]},{"name":'/experimental/ciscat/results',"args":[]},{"name":'/experimental/syscollector/hardware',"args":[]},{"name":'/experimental/syscollector/netaddr',"args":[]},{"name":'/experimental/syscollector/netiface',"args":[]},{"name":'/experimental/syscollector/netproto',"args":[]},{"name":'/experimental/syscollector/os',"args":[]},{"name":'/experimental/syscollector/packages',"args":[]},{"name":'/experimental/syscollector/ports',"args":[]},{"name":'/experimental/syscollector/processes',"args":[]},{"name":'/manager/configuration',"args":[]},{"name":'/manager/info',"args":[]},{"name":'/manager/logs',"args":[]},{"name":'/manager/logs/summary',"args":[]},{"name":'/manager/stats',"args":[]},{"name":'/manager/stats/analysisd',"args":[]},{"name":'/manager/stats/hourly',"args":[]},{"name":'/manager/stats/remoted',"args":[]},{"name":'/manager/stats/weekly',"args":[]},{"name":'/manager/status',"args":[]},{"name":'/rootcheck/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/rootcheck/:agent_id/cis',"args":[{"name":':agent_id'}]},{"name":'/rootcheck/:agent_id/last_scan',"args":[{"name":':agent_id'}]},{"name":'/rootcheck/:agent_id/pci',"args":[{"name":':agent_id'}]},{"name":'/rules',"args":[]},{"name":'/rules/:rule_id',"args":[{"name":':rule_id'}]},{"name":'/rules/files',"args":[]},{"name":'/rules/gdpr',"args":[]},{"name":'/rules/groups',"args":[]},{"name":'/rules/pci',"args":[]},{"name":'/syscheck/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/syscheck/:agent_id/last_scan',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/hardware',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/netaddr',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/netiface',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/netproto',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/os',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/packages',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/ports',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/processes',"args":[{"name":':agent_id'}]}]},{"method":'POST',"endpoints":[{"name":'/agents',"args":[]},{"name":'/agents/insert',"args":[]},{"name":'/agents/restart',"args":[]}]}]) + parsed_json = jsonbak.dumps([{"method":'PUT',"endpoints":[{"name":'/active-response/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/group/:group_id',"args":[{"name":':agent_id'},{"name":':group_id'}]},{"name":'/agents/:agent_id/restart',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/upgrade',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/upgrade_custom',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_name',"args":[{"name":':agent_name'}]},{"name":'/agents/groups/:group_id',"args":[{"name":':group_id'}]},{"name":'/agents/restart',"args":[]},{"name":'/cluster/:node_id/restart',"args":[{"name":':node_id'}]},{"name":'/cluster/restart',"args":[]},{"name":'/manager/restart',"args":[]},{"name":'/rootcheck',"args":[]},{"name":'/rootcheck/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/syscheck',"args":[]},{"name":'/syscheck/:agent_id',"args":[{"name":':agent_id'}]}]},{"method":'DELETE',"endpoints":[{"name":'/agents',"args":[]},{"name":'/agents/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/group',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/group/:group_id',"args":[{"name":':agent_id'},{"name":':group_id'}]},{"name":'/agents/group/:group_id',"args":[{"name":':group_id'}]},{"name":'/agents/groups',"args":[]},{"name":'/agents/groups/:group_id',"args":[{"name":':group_id'}]},{"name":'/cache',"args":[]},{"name":'/cache',"args":[]},{"name":'/rootcheck',"args":[]},{"name":'/rootcheck/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/syscheck/:agent_id',"args":[{"name":':agent_id'}]}]},{"method":'GET',"endpoints":[{"name":'/agents',"args":[]},{"name":'/agents/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/config/:component/:configuration',"args":[{"name":':agent_id'},{"name":':component'},{"name":':configuration'}]},{"name":'/agents/:agent_id/group/is_sync',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/key',"args":[{"name":':agent_id'}]},{"name":'/agents/:agent_id/upgrade_result',"args":[{"name":':agent_id'}]},{"name":'/agents/groups',"args":[]},{"name":'/agents/groups/:group_id',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/configuration',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/files',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/files/:filename',"args":[{"name":':group_id'},{"name":':filename'}]},{"name":'/agents/name/:agent_name',"args":[{"name":':agent_name'}]},{"name":'/agents/no_group',"args":[]},{"name":'/agents/outdated',"args":[]},{"name":'/agents/stats/distinct',"args":[]},{"name":'/agents/summary',"args":[]},{"name":'/agents/summary/os',"args":[]},{"name":'/cache',"args":[]},{"name":'/cache/config',"args":[]},{"name":'/ciscat/:agent_id/results',"args":[{"name":':agent_id'}]},{"name":'/cluster/:node_id/configuration',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/configuration/validation',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/files',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/info',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/logs',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/logs/summary',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats/analysisd',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats/hourly',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats/remoted',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/stats/weekly',"args":[{"name":':node_id'}]},{"name":'/cluster/:node_id/status',"args":[{"name":':node_id'}]},{"name":'/cluster/config',"args":[]},{"name":'/cluster/configuration/validation',"args":[]},{"name":'/cluster/healthcheck',"args":[]},{"name":'/cluster/node',"args":[]},{"name":'/cluster/nodes',"args":[]},{"name":'/cluster/nodes/:node_name',"args":[{"name":':node_name'}]},{"name":'/cluster/status',"args":[]},{"name":'/manager/stats/remoted',"args":[]},{"name":'/sca/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/sca/:agent_id/checks/:id',"args":[{"name":':agent_id'},{"name":':id'}]},{"name":'/decoders',"args":[]},{"name":'/decoders/:decoder_name',"args":[{"name":':decoder_name'}]},{"name":'/decoders/files',"args":[]},{"name":'/decoders/parents',"args":[]},{"name":'/lists',"args":[]},{"name":'/lists/files',"args":[]},{"name":'/manager/configuration',"args":[]},{"name":'/manager/configuration/validation',"args":[]},{"name":'/manager/files',"args":[]},{"name":'/manager/info',"args":[]},{"name":'/manager/logs',"args":[]},{"name":'/manager/logs/summary',"args":[]},{"name":'/manager/stats',"args":[]},{"name":'/manager/stats/analysisd',"args":[]},{"name":'/manager/stats/hourly',"args":[]},{"name":'/manager/stats/remoted',"args":[]},{"name":'/manager/stats/weekly',"args":[]},{"name":'/manager/status',"args":[]},{"name":'/rootcheck/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/rootcheck/:agent_id/cis',"args":[{"name":':agent_id'}]},{"name":'/rootcheck/:agent_id/last_scan',"args":[{"name":':agent_id'}]},{"name":'/rootcheck/:agent_id/pci',"args":[{"name":':agent_id'}]},{"name":'/rules',"args":[]},{"name":'/rules/:rule_id',"args":[{"name":':rule_id'}]},{"name":'/rules/files',"args":[]},{"name":'/rules/gdpr',"args":[]},{"name":'/rules/groups',"args":[]},{"name":'/rules/pci',"args":[]},{"name":'/syscheck/:agent_id',"args":[{"name":':agent_id'}]},{"name":'/syscheck/:agent_id/last_scan',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/hardware',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/netaddr',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/netiface',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/netproto',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/os',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/packages',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/ports',"args":[{"name":':agent_id'}]},{"name":'/syscollector/:agent_id/processes',"args":[{"name":':agent_id'}]}]},{"method":'POST',"endpoints":[{"name":'/agents',"args":[]},{"name":'/agents/group/:group_id',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/configuration',"args":[{"name":':group_id'}]},{"name":'/agents/groups/:group_id/files/:file_name',"args":[{"name":':group_id'},{"name":':file_name'}]},{"name":'/agents/insert',"args":[]},{"name":'/agents/restart',"args":[]},{"name":'/cluster/:node_id/files',"args":[{"name":':node_id'}]},{"name":'/manager/files',"args":[]}]}]) except Exception as e: return jsonbak.dumps({'error': str(e)}) return parsed_json - # POST /api/csv : Generates a CSV file with the returned data from API @expose_page(must_login=False, methods=['POST']) def csv(self, **kwargs): @@ -223,14 +334,13 @@ def csv(self, **kwargs): the_id = kwargs['id'] api = self.db.get(the_id) - opt_username = api[0]["userapi"] - opt_password = api[0]["passapi"] - opt_base_url = api[0]["url"] - opt_base_port = api[0]["portapi"] + api = jsonbak.loads(api) + opt_username = api["data"]["userapi"] + opt_password = api["data"]["passapi"] + opt_base_url = api["data"]["url"] + opt_base_port = api["data"]["portapi"] opt_endpoint = kwargs['path'] - del kwargs['id'] - del kwargs['path'] - url = opt_base_url + ":" + opt_base_port + url = str(opt_base_url) + ":" + str(opt_base_port) auth = requestsbak.auth.HTTPBasicAuth(opt_username, opt_password) verify = False # init csv writer @@ -241,7 +351,11 @@ def csv(self, **kwargs): verify=verify).json() if ('items' in request['data'] and len(request['data']['items']) > 0): - final_obj = request["data"]["items"] + if "?path=etc/list" in opt_endpoint: + formatted = self.format_cdb_list_content(request) + final_obj = formatted["data"]["items"] + else : + final_obj = request["data"]["items"] if isinstance(final_obj, list): keys = final_obj[0].keys() self.format_output(keys) @@ -284,3 +398,75 @@ def csv(self, **kwargs): self.logger.error("Error in CSV generation!: %s" % (str(e))) return jsonbak.dumps({"error": str(e)}) return csv_result + + @expose_page(must_login=False, methods=['GET']) + def pci(self, **kwargs): + try: + if not 'requirement' in kwargs: + raise Exception('Missing requirement.') + pci_description = '' + requirement = kwargs['requirement'] + if requirement == 'all': + if not 'id' in kwargs: + return jsonbak.dumps(pci_requirements.pci) + the_id = kwargs['id'] + url,auth,verify = self.get_credentials(the_id) + opt_endpoint = '/rules/pci' + request = self.session.get( + url + opt_endpoint, params=kwargs, auth=auth, + verify=verify).json() + if request['error'] != 0: + return jsonbak.dumps({'error':request['error']}) + data = request['data']['items'] + result = {} + for item in data: + result[item] = pci_requirements.pci[item] + return jsonbak.dumps(result) + else: + if not requirement in pci_requirements.pci: + return jsonbak.dumps({'error':'Requirement not found.'}) + pci_description = pci_requirements.pci[requirement] + result = {} + result['pci'] = {} + result['pci']['requirement'] = requirement + result['pci']['description'] = pci_description + return jsonbak.dumps(result) + except Exception as e: + self.logger.error("Error getting PCI-DSS requirements: %s" % (str(e))) + return jsonbak.dumps({"error": str(e)}) + + @expose_page(must_login=False, methods=['GET']) + def gdpr(self, **kwargs): + try: + if not 'requirement' in kwargs: + raise Exception('Missing requirement.') + pci_description = '' + requirement = kwargs['requirement'] + if requirement == 'all': + if not 'id' in kwargs: + return jsonbak.dumps(gdpr_requirements.gdpr) + the_id = kwargs['id'] + url,auth,verify = self.get_credentials(the_id) + opt_endpoint = '/rules/gdpr' + request = self.session.get( + url + opt_endpoint, params=kwargs, auth=auth, + verify=verify).json() + if request['error'] != 0: + return jsonbak.dumps({'error':request['error']}) + data = request['data']['items'] + result = {} + for item in data: + result[item] = gdpr_requirements.gdpr[item] + return jsonbak.dumps(result) + else: + if not requirement in gdpr_requirements.gdpr: + return jsonbak.dumps({'error':'Requirement not found.'}) + pci_description = gdpr_requirements.gdpr[requirement] + result = {} + result['gdpr'] = {} + result['gdpr']['requirement'] = requirement + result['gdpr']['description'] = pci_description + return jsonbak.dumps(result) + except Exception as e: + self.logger.error("Error getting PCI-DSS requirements: %s" % (str(e))) + return jsonbak.dumps({"error": str(e)}) \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/controllers/manager.py b/SplunkAppForWazuh/appserver/controllers/manager.py index 4344bd04f..9ce52b870 100644 --- a/SplunkAppForWazuh/appserver/controllers/manager.py +++ b/SplunkAppForWazuh/appserver/controllers/manager.py @@ -24,7 +24,7 @@ from log import log -def getSelfConfStanza(file,stanza): +def getSelfConfStanza(file, stanza): """Get the configuration from a stanza. Parameters @@ -53,7 +53,8 @@ def diff_keys_dic_update_api(kwargs_dic): try: diff = [] kwargs_dic_keys = kwargs_dic.keys() - dic_keys = ['id', 'url', 'portapi', 'userapi', 'passapi'] + dic_keys = ['_key', 'url', 'portapi', 'userapi', + 'passapi', 'filterName', 'filterType', 'managerName'] for key in dic_keys: if key not in kwargs_dic_keys: diff.append(key) @@ -76,34 +77,6 @@ def __init__(self): except Exception as e: self.logger.error("Error in manager module constructor: %s" % (e)) - # /custom/SplunkAppForWazuh/manager/node - @expose_page(must_login=False, methods=['GET']) - def check_connection(self, **kwargs): - """Check API connection. - - Parameters - ---------- - kwargs : dict - The request's parameters - - """ - try: - opt_username = kwargs["user"] - opt_password = kwargs["pass"] - opt_base_url = kwargs["ip"] - opt_base_port = kwargs["port"] - url = opt_base_url + ":" + opt_base_port - auth = requestsbak.auth.HTTPBasicAuth(opt_username, opt_password) - verify = False - request_cluster = self.session.get( - url + '/version', auth=auth, timeout=8, verify=verify).json() - del kwargs['pass'] - result = jsonbak.dumps(request_cluster) - except Exception as e: - self.logger.error("Cannot connect to API : %s" % (e)) - return jsonbak.dumps({"status": "400", "error": str(e)}) - return result - @expose_page(must_login=False, methods=['GET']) def polling_state(self, **kwargs): """Check agent monitoring status. @@ -138,7 +111,24 @@ def extensions(self, **kwargs): """ try: - stanza = getSelfConfStanza("config","extensions") + stanza = getSelfConfStanza("config", "extensions") + data_temp = stanza + except Exception as e: + return jsonbak.dumps({'error': str(e)}) + return data_temp + + @expose_page(must_login=False, methods=['GET']) + def admin_extensions(self, **kwargs): + """Obtain extension from file. + + Parameters + ---------- + kwargs : dict + The request's parameters + + """ + try: + stanza = getSelfConfStanza("config", "admin_extensions") data_temp = stanza except Exception as e: return jsonbak.dumps({'error': str(e)}) @@ -200,8 +190,8 @@ def get_apis(self, **kwargs): """ try: - data_temp = self.db.all() - result = jsonbak.dumps(data_temp) + apis = self.db.all() + result = apis except Exception as e: self.logger.error(jsonbak.dumps({"error": str(e)})) return jsonbak.dumps({"error": str(e)}) @@ -218,18 +208,19 @@ def add_api(self, **kwargs): """ try: + record = kwargs - keys_list = ['url', 'portapi', 'userapi', 'passapi'] + keys_list = ['url', 'portapi', 'userapi', 'passapi', + 'managerName', 'filterType', 'filterName'] if set(record.keys()) == set(keys_list): - record['id'] = str(uuid.uuid4()) - self.db.insert(record) - parsed_data = jsonbak.dumps({'result': record['id']}) + key = self.db.insert(jsonbak.dumps(record)) + parsed_data = jsonbak.dumps({'result': key}) + return parsed_data else: - return jsonbak.dumps({'error': 'Invalid number of arguments'}) + raise Exception('Invalid number of arguments') except Exception as e: - self.logger.error({'error': str(e)}) + self.logger.error({'manager - add_api': str(e)}) return jsonbak.dumps({'error': str(e)}) - return parsed_data @expose_page(must_login=False, methods=['POST']) def remove_api(self, **kwargs): @@ -243,9 +234,9 @@ def remove_api(self, **kwargs): """ try: api_id = kwargs - if 'id' not in api_id: + if '_key' not in api_id: return jsonbak.dumps({'error': 'Missing ID'}) - self.db.remove(api_id['id']) + self.db.remove(api_id['_key']) parsed_data = jsonbak.dumps({'data': 'success'}) except Exception as e: self.logger.error("Error in remove_api endpoint: %s" % (e)) @@ -264,7 +255,9 @@ def update_api(self, **kwargs): """ try: entry = kwargs - keys_list = ['id', 'url', 'portapi', 'userapi', + if '_user' in kwargs: + del kwargs['_user'] + keys_list = ['_key', 'url', 'portapi', 'userapi', 'passapi', 'filterName', 'filterType', 'managerName'] if set(entry.keys()) == set(keys_list): self.db.update(entry) @@ -296,3 +289,82 @@ def get_log_lines(self, **kwargs): self.logger.error("Get_log_lines endpoint: %s" % (e)) return jsonbak.dumps({"error": str(e)}) return parsed_data + + @expose_page(must_login=False, methods=['GET']) + def check_connection(self, **kwargs): + """Check API connection. + + Parameters + ---------- + kwargs : dict + The request's parameters + + """ + try: + opt_username = kwargs["user"] + opt_password = kwargs["pass"] + opt_base_url = kwargs["ip"] + opt_base_port = kwargs["port"] + opt_cluster = kwargs["cluster"] == "true" + url = opt_base_url + ":" + opt_base_port + auth = requestsbak.auth.HTTPBasicAuth(opt_username, opt_password) + verify = False + request_manager = self.session.get( + url + '/agents/000?select=name', auth=auth, timeout=20, verify=verify).json() + request_cluster = self.session.get( + url + '/cluster/status', auth=auth, timeout=20, verify=verify).json() + request_cluster_name = self.session.get( + url + '/cluster/node', auth=auth, timeout=20, verify=verify).json() + output = {} + daemons_ready = self.check_daemons(url, auth, verify, opt_cluster) + # Pass the cluster status instead of always False + if not daemons_ready: + raise Exception("Daemons are not ready yet.") + output['managerName'] = request_manager['data'] + output['clusterMode'] = request_cluster['data'] + output['clusterName'] = request_cluster_name['data'] + del kwargs['pass'] + result = jsonbak.dumps(output) + except Exception as e: + if not daemons_ready: + self.logger.error("Cannot connect to API; Wazuh not ready yet.") + return jsonbak.dumps({"status": "200", "error": 3099, "message": "Wazuh not ready yet."}) + else: + self.logger.error("Cannot connect to API : %s" % (e)) + return jsonbak.dumps({"status": "400", "error": "Cannot connect to the API"}) + return result + + def check_daemons(self, url, auth, verify, check_cluster): + """ Request to check the status of this daemons: execd, modulesd, wazuhdb and clusterd + + Parameters + ---------- + url: str + auth: str + verify: str + cluster_enabled: bool + """ + try: + request_cluster = self.session.get( + url + '/cluster/status', auth=auth, timeout=20, verify=verify).json() + # Try to get cluster is enabled if the request fail set to false + try: + cluster_enabled = request_cluster['data']['enabled'] == 'yes' + except Exception as e: + cluster_enabled = False + cc = check_cluster and cluster_enabled # Var to check the cluster demon or not + opt_endpoint = "/manager/status" + daemons_status = self.session.get( + url + opt_endpoint, auth=auth, + verify=verify).json() + if not daemons_status['error']: + d = daemons_status['data'] + daemons = {"execd": d['ossec-execd'], "modulesd": d['wazuh-modulesd'], "db": d['wazuh-db']} + if cc: + daemons['clusterd'] = d['wazuh-clusterd'] + values = list(daemons.values()) + wazuh_ready = len(set(values)) == 1 and values[0] == "running" # Checks all the status are equals, and running + return wazuh_ready + except Exception as e: + self.logger.error("Error checking daemons: %s" % (e)) + raise e \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/controllers/queue.py b/SplunkAppForWazuh/appserver/controllers/queue.py new file mode 100644 index 000000000..5ee064a75 --- /dev/null +++ b/SplunkAppForWazuh/appserver/controllers/queue.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +""" +Wazuh app - API backend module. + +Copyright (C) 2015-2019 Wazuh, Inc. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +Find more information about this on the LICENSE file. +""" + +import jsonbak +import splunk.appserver.mrsparkle.controllers as controllers +from splunk.appserver.mrsparkle.lib.decorators import expose_page +from db import database +from log import log +from jobs_queue import JobsQueue + +import time + + +class Queue(controllers.BaseController): + + """Queue class. + + Handle Jobs queue methods + """ + + def __init__(self): + """Constructor.""" + try: + self.queue = JobsQueue() + self.logger = log() + controllers.BaseController.__init__(self) + except Exception as e: + self.logger.error( + "Error in Jobs queue module constructor: %s" % (e)) + + @expose_page(must_login=False, methods=['POST']) + def add_job(self, **kwargs): + """Add job to the queue. + + Parameters + ---------- + kwargs : dict + Request parameters + """ + try: + now = time.time() + exec_time = now + float(kwargs['delay']) + del kwargs['delay'] + job = {"job": kwargs, "added": now, "exec_time": exec_time, "done": 0} + self.queue.insert_job(job) + return jsonbak.dumps({"data": "Job added to the queue.", "error": 0}) + except Exception as e: + self.logger.error("Error adding job: %s" % (e)) + return jsonbak.dumps({'error': str(e)}) diff --git a/SplunkAppForWazuh/appserver/controllers/report.py b/SplunkAppForWazuh/appserver/controllers/report.py index e2ebb0c11..791eb0660 100644 --- a/SplunkAppForWazuh/appserver/controllers/report.py +++ b/SplunkAppForWazuh/appserver/controllers/report.py @@ -21,20 +21,20 @@ from log import log import base64 from fpdf import FPDF - +import math class PDF(FPDF): def header(self): # Logo - self.image('/opt/splunk/etc/apps/SplunkAppForWazuh/appserver/static/css/images/wazuh/png/logo.png', 10, 10, 40) + self.image('/opt/splunk/etc/apps/SplunkAppForWazuh/appserver/static/css/images/wazuh/png/logo.png', 10, 10, 65, 15) self.set_font('Arial', '', 11) - self.set_text_color(93, 188, 210) + self.set_text_color(75, 179, 204) #Contact info self.cell(150) #Move to the right - self.cell(0, 5, 'info@wazuh.com') + self.cell(0, 5, 'info@wazuh.com', 0, 0, 'R') self.ln() #Break line self.cell(150) #Move to the right - self.cell(0, 5, 'https://wazuh.com') + self.cell(0, 5, 'https://wazuh.com', 0, 0, 'R') # Page footer def footer(self): @@ -42,7 +42,7 @@ def footer(self): self.year = datetime.datetime.now().strftime('%Y') self.copyright = unicode('Copyright © ' + self.year + ' Wazuh, Inc.', 'utf-8') self.set_y(-15) - self.set_text_color(93, 188, 210) + self.set_text_color(75, 179, 204) self.set_font('Arial', 'B', 8) # Page number self.cell(100, 10, self.copyright, 0, 0, 'L') @@ -59,7 +59,6 @@ class report(controllers.BaseController): def __init__(self): """Constructor.""" self.logger = log() - self.images = [] try: self.path = '/opt/splunk/etc/apps/SplunkAppForWazuh/appserver/static/' controllers.BaseController.__init__(self) @@ -68,6 +67,7 @@ def __init__(self): def save_images(self, images): i = 0 + images_saved = [] while i in range(0, len(images)): path = str(self.path+str(images[i]['id'])+'.png') f = open(path, 'wb') @@ -78,13 +78,13 @@ def save_images(self, images): images[i]['element'].split(',')[1].encode())) f.close() image = {'title': title, 'path': path, 'width': width, 'height': height} - self.images.append(image) + images_saved.append(image) i += 1 + return images_saved - def delete_images(self): - for img in self.images: + def delete_images(self, images): + for img in images: os.remove(img['path']) - self.images = [] @expose_page(must_login=False, methods=['POST']) def generate(self, **kwargs): @@ -97,76 +97,81 @@ def generate(self, **kwargs): """ try: - self.pdf = PDF('P', 'mm', 'A4') - self.metrics_exists = False + pdf = PDF('P', 'mm', 'A4') + metrics_exists = False + first_page = True self.logger.info("Start generating report ") json_acceptable_string = kwargs['data'] data = jsonbak.loads(json_acceptable_string) #Replace "'" in images - self.clean_images = jsonbak.dumps(data['images']) - self.clean_images.replace("'", "\"") - data['images'] = jsonbak.loads(self.clean_images) - today = datetime.datetime.now().strftime('%Y.%m.%d %H:%M') + clean_images = jsonbak.dumps(data['images']) + clean_images.replace("'", "\"") + data['images'] = jsonbak.loads(clean_images) report_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') #Get filters and other information - self.filters = data['queryFilters'] - self.pdf_name = data['pdfName'] - self.time_range = data['timeRange'] - self.section_title = data['sectionTitle'] - self.metrics = data['metrics'] - self.tables = data['tableResults'] - if self.metrics: - self.metrics = jsonbak.loads(self.metrics) - self.agent_data = data['isAgents'] + filters = data['queryFilters'] + pdf_name = data['pdfName'] + time_range = data['timeRange'] + section_title = data['sectionTitle'] + metrics = data['metrics'] + tables = data['tableResults'] + time_diff = data['timeZone'] + today = datetime.datetime.utcnow() - datetime.timedelta(minutes=time_diff) + today = today.strftime('%Y.%m.%d %H:%M') + if metrics: + metrics = jsonbak.loads(metrics) + agent_data = data['isAgents'] #Save the images - self.save_images(data['images']) + saved_images = self.save_images(data['images']) parsed_data = jsonbak.dumps({'data': 'success'}) # Add title and filters - self.pdf.alias_nb_pages() - self.pdf.add_page() - self.pdf.ln(20) + pdf.alias_nb_pages() + pdf.add_page() + pdf.ln(20) #Color WazuhBlue - self.pdf.set_text_color(93, 188, 210) + pdf.set_text_color(75, 179, 204) # Title Arial Bold 20 - self.pdf.set_font('Arial', '', 25) - self.pdf.cell(0,0, self.section_title + ' report' , 0, 0, 'L') + pdf.set_font('Arial', '', 25) + pdf.cell(0,0, section_title + ' report' , 0, 0, 'L') #Date - self.pdf.set_font('Arial', '', 12) - self.pdf.cell(0,0, today , 0, 0, 'R') + pdf.set_font('Arial', '', 12) + pdf.cell(0,0, today , 0, 0, 'R') #Filters and search time range - if self.pdf_name != 'agents-inventory': # If the name of the PDF file is agents-inventory does not print date range or filters either - self.pdf.ln(7) - self.pdf.set_fill_color(93, 188, 210) - self.pdf.set_text_color(255,255,255) - self.pdf.set_font('Arial', '', 10) - self.pdf.cell(0, 5, ' Search time range: ' + self.time_range , 0, 0, 'L', 1) - self.pdf.ln(5) - self.pdf.cell(0, 5, ' Filters:' + self.filters , 0, 0, 'L', 1) + if pdf_name != 'agents-inventory': # If the name of the PDF file is agents-inventory does not print date range or filters either + pdf.ln(7) + pdf.set_fill_color(75, 179, 204) + pdf.set_text_color(255,255,255) + pdf.set_font('Arial', '', 10) + if time_range: + pdf.cell(0, 5, ' Search time range: ' + time_range , 0, 0, 'L', 1) + pdf.ln(5) + if filters: + pdf.cell(0, 5, ' Filters:' + filters , 0, 0, 'L', 1) #Check if is agent, print agent info - if self.agent_data and self.agent_data != 'inventory': - self.print_agent_info(self.agent_data, self.pdf) + if agent_data and agent_data != 'inventory': + self.print_agent_info(agent_data, pdf) #Check metrics and print if exist - if len(self.metrics) > 0: - self.pdf.set_text_color(255,255,255) - self.metrics_exists = True + if len(metrics) > 0: + pdf.set_text_color(255,255,255) + metrics_exists = True w = 5 line_width = 0 total_width = 190 - self.pdf.ln(10) - self.pdf.set_font('Arial', '', 8) - for key in self.metrics.keys(): - text = (str(key) +': '+ str(self.metrics[key])) - text_w = self.pdf.get_string_width(text) + w + pdf.ln(10) + pdf.set_font('Arial', '', 8) + for key in metrics.keys(): + text = (str(key) +': '+ str(metrics[key])) + text_w = pdf.get_string_width(text) + w line_width = line_width + text_w if line_width >= total_width: - self.pdf.cell((total_width - (line_width - text_w)), 4, '', 0, 0, 'L', 1)#Fill rest of the width - self.pdf.ln(4) + pdf.cell((total_width - (line_width - text_w)), 4, '', 0, 0, 'L', 1)#Fill rest of the width + pdf.ln(4) line_width = text_w - self.pdf.cell(text_w, 4, text, 0, 0, 'L', 1) + pdf.cell(text_w, 4, text, 0, 0, 'L', 1) if line_width < total_width: - self.pdf.cell((total_width - line_width), 4, '', 0, 0, 'L', 1)#Fill rest of the width in the last row + pdf.cell((total_width - line_width), 4, '', 0, 0, 'L', 1)#Fill rest of the width in the last row # Add visualizations - if self.images: + if saved_images: # Default sizes and margins values x = 30 y = 10 @@ -176,123 +181,223 @@ def generate(self, **kwargs): x_img = 50 # Count images for page break count = 0 - n_images = len(self.images) + n_images = len(saved_images) # Set top margin checking if metrics exist - self.pdf.set_text_color(93, 188, 210) - self.pdf.set_font('Arial', '', 14) - if self.metrics_exists: + pdf.set_text_color(75, 179, 204) + pdf.set_font('Arial', '', 14) + if metrics_exists: y_img = y_img + 10 - if self.agent_data: + if agent_data: y_img = y_img + 20 - self.pdf.ln(10) + pdf.ln(10) #Sort images by width size - images = sorted(self.images, key=itemgetter('width')) + images = sorted(saved_images, key=itemgetter('width')) #Insert images for img in images: #Change width and heigh - if img['width'] >= 420 and img['width'] <= 430 or img['width'] >= 580 and img['width'] <= 590: + if img['width'] == -1: + w = 0 + h = 0 + x_img = 80 + elif img['width'] <= 550: w = 118 - h = 62 - x_img = 48 - elif img['width'] >= 705 and img['width'] <= 725: - w = 145 h = 65 - x_img = 26 - elif img['width'] >= 895 and img['width'] <= 910 or img['width'] >= 1080 and img['width'] <= 1100 or img['width'] >= 1300 and img['width'] <= 1400: - w = 162 - h = 72 - x_img = 26 - elif img['width'] >= 1800 and img['width'] <= 1900: - w = 190 - h = 90 - x_img = 10 + x_img = 40 + else: + w = 189 + h = 55 + x_img = 12 #Insert image - self.pdf.cell(x , y, img['title'], 0, 1) - self.pdf.image(img['path'], x_img, y_img, w, h) - self.pdf.ln(80) - y_img = y_img + 90 + pdf.cell(x , y, img['title'], 0, 1) + pdf.image(img['path'], x_img, y_img, w,h) + pdf.ln(75) + y_img = y_img + 85 count = count + 1 n_images = n_images - 1 - if count == 2 and n_images >= 1: - self.pdf.add_page() - self.pdf.ln(20) - y_img = 50 + if count == 2 and n_images >= 1 and first_page: + pdf.add_page() + pdf.ln(15) + y_img = 45 + count = 0 + first_page = False + if count == 3 and n_images >= 1: + pdf.add_page() + pdf.ln(15) + y_img = 45 count = 0 #Add tables - if self.tablesHaveInfo(self.tables): #Check if any table has information, if not, prevent break page and not iterate in empties tables - if self.pdf_name != 'agents-inventory': # If the name of the PDF file is agents-inventory does not add page - self.pdf.add_page() - self.pdf.ln(20) + if self.tables_have_info(tables): #Check if any table has information, if not, prevent break page and not iterate in empties tables + if pdf_name != 'agents-inventory': # If the name of the PDF file is agents-inventory does not add page + pdf.add_page() + pdf.ln(20) rows_count = 12 # Set row_count with 12 for the agent information size - self.table_keys = self.tables.keys() - for key in self.table_keys: - if self.tables[key]:#Check if this table has information, if it has, process it + table_keys = tables.keys() + for key in table_keys: + if tables[key]:#Check if this table has information, if it has, process it table_title = key - self.pdf.ln(10) + pdf.ln(10) #Table title - self.pdf.set_text_color(93, 188, 210) - self.pdf.set_font('Arial', '', 14) + pdf.set_text_color(75, 179, 204) + pdf.set_font('Arial', '', 14) if rows_count > 60: - self.pdf.add_page() - self.pdf.ln(12) + pdf.add_page() + pdf.ln(18) rows_count = 0 - self.pdf.cell(0 , 5, table_title, 0, 1, 'L') + pdf.cell(0 , 5, table_title, 0, 1, 'L') rows_count = rows_count + 5 - self.pdf.ln() + pdf.ln() #Table content - self.pdf.set_font('Arial', '', 8) - self.pdf.set_fill_color(93, 188, 210) - self.pdf.set_text_color(255,255,255) - sizes_field = self.calculate_table_width(self.tables[key]) + pdf.set_font('Arial', '', 8) + pdf.set_fill_color(75, 179, 204) + pdf.set_text_color(255,255,255) + sizes_field = self.calculate_table_width(pdf, tables[key]) count = 0 - for field in self.tables[key]['fields']: + #Table head + for field in tables[key]['fields']: if rows_count > 60: - self.pdf.add_page() - self.pdf.ln(12) + pdf.add_page() + pdf.ln(15) rows_count = 0 if field != 'sparkline': - width = sizes_field[count] - self.pdf.cell(width, 4, str(field), 0, 0, 'L', 1) + x = 0 + #Check if the with is splitted in several rows + w = sizes_field[count] + width = w[0] if isinstance(w, list) else w + pdf.cell(width, 4, str(field), 0, 0, 'L', 1) count = count + 1 - self.pdf.ln() - self.pdf.set_text_color(93, 188, 210) - for row in self.tables[key]['rows']: + pdf.ln() + pdf.set_text_color(91, 91, 91) + pdf.set_draw_color(75, 179, 204) + #Table rows + for row in tables[key]['rows']: + first_field = True + bigger_y = 0 + reset_y = False + rh = 4 # Row heigth count = 0 if rows_count > 55: - self.pdf.add_page() - self.pdf.ln(12) + pdf.add_page() + pdf.ln(15) rows_count = 0 - rows_count = rows_count + 1 for value in row: + #Check that is not sparkline(sparkline field is an array) if not isinstance(value, list): - width = sizes_field[count] - self.pdf.cell(width, 4, str(value), 0, 0, 'L', 0) + #Check if the with is splitted in several rows + w = sizes_field[count] + width = w[0] if isinstance(w, list) else w + value = self.split_string(width, value) if isinstance(w, list) else value + if value and isinstance(value, list): + if first_field: + x = pdf.get_x() + first_field = False + y = pdf.get_y() + reset_y = y + bigger_y = y + else: + y = reset_y + rows_count = rows_count + len(value) + for v in value: + pdf.set_xy(x, y) + pdf.cell(width, rh, str(v), 0, 0, 'L', 0) + y = y + rh + x = x + width + bigger_y = y if y > bigger_y else bigger_y + else: + if reset_y: + pdf.set_xy(pdf.get_x(), reset_y) + pdf.cell(width, rh, str(value), 0, 0, 'L', 0) + y = pdf.get_y() count = count + 1 - self.pdf.ln() + rows_count = rows_count + 1 + y = (bigger_y if (bigger_y > pdf.get_y()) else (pdf.get_y() + rh)) + pdf.set_xy(10, y) + pdf.line(10, y, 200, y) #Save pdf - self.pdf.output(self.path+'wazuh-'+self.pdf_name+'-'+report_id+'.pdf', 'F') + pdf.output(self.path+'wazuh-'+pdf_name+'-'+report_id+'.pdf', 'F') #Delete the images - self.delete_images() + self.delete_images(saved_images) except Exception as e: self.logger.error("Error generating report: %s" % (e)) return jsonbak.dumps({"error": str(e)}) return parsed_data + #Cut value string + def cut_value(self, width, value_string): + num_characters = int(math.ceil(width / 1.50)) + value_splitted = list(str(value_string)) + if len(value_splitted) > num_characters: + final_string_arr = value_splitted[0:num_characters] + final_string_arr.append('...') + final_string = ''.join(str(e) for e in final_string_arr) + return str(final_string) + else: + return value_string + + #Split the string + def split_string(self, width, value_string): + splitted_str = [] + num_characters = int(math.ceil(width / 1.50)) # Number of characters to split the string + sm = num_characters # Var to sum and advance in the arr indexes + value_splitted = list(str(value_string)) + if len(value_splitted) > num_characters: + parts = int(math.ceil((float(len(value_splitted) / float(num_characters))))) + i = 0 # Position in the array + c = 0 # For count the parts travelled + for _ in range(parts): + c = c + 1 + string_arr = value_splitted[i:num_characters] + i = num_characters + num_characters = num_characters + sm + if len(string_arr) > 0 and c < parts: + string_arr.append('-') + if string_arr: + string = ''.join(str(e) for e in string_arr) + splitted_str.append(string) + #Clean possible "-" in the last string + last_str = splitted_str[-1] + if last_str.endswith("-"): + splitted_str[-1] = last_str[:-1] + return splitted_str + else: + return value_string + + #Sum arr of numbers + def sum_numbers_arr(self, arr): + total = 0 + for i in arr: + total = total + i + return total + + #Sum dic of numbers + def sum_numbers_dic(self, dic): + total = 0 + for key in dic.keys(): + total = total + dic[key] + return total + + #Excludes fields from dic + def exclude_fields(self, fields, dic): + dic_to_exclude = dic.copy() + for f in fields: + del dic_to_exclude[f] + return dic_to_exclude + + #Check if tables are not empties - def tablesHaveInfo(self, tables): + def tables_have_info(self, tables): for key in tables.keys(): if tables[key]: return True return False #Calculates the width of the fields - def calculate_table_width(self, table): + def calculate_table_width(self, pdf, table): sizes = {} total_width = 0 fields = table['fields'] for field in fields: if field != 'sparkline': - width = self.pdf.get_string_width(field) + 1 + width = pdf.get_string_width(field) + 1 sizes[field] = width for row in table['rows']: count = 0 @@ -301,7 +406,7 @@ def calculate_table_width(self, table): key = fields[count] prev_width = sizes[key] if value: # Check for possible undefined elements - width = self.pdf.get_string_width(value) + 1 + width = pdf.get_string_width(value) + 1 else: width = 1 if width > prev_width: @@ -319,7 +424,27 @@ def calculate_table_width(self, table): diff = diff / keys_num for key in sizes.keys(): # Sum the proporcional width difference to the fields sizes[key] = sizes[key] + diff - return self.sort_table_sizes(table['fields'], sizes) + # Check if the row is more wide and calculates the width + elif total_width > 190: + wide_fields = [] + for key in sizes.keys(): + if sizes[key] > 60: + wide_fields.append(key) + fields_to_sum = self.exclude_fields(wide_fields, sizes) + total_width_narrow_fields = self.sum_numbers_dic(fields_to_sum) + remaining_width = 190 - total_width_narrow_fields + wide_size = remaining_width / len(wide_fields) + for wf in wide_fields: + sizes_arr = [] + parts = int(math.ceil(sizes[wf]) / wide_size) + #Ensure minimun one part + if not parts: + parts = 1 + for _ in range(parts): + sizes_arr.append(wide_size) + sizes[wf] = sizes_arr + sizes = self.sort_table_sizes(table['fields'], sizes) + return sizes #Print agent info def print_agent_info(self, agent_info, pdf): @@ -345,18 +470,18 @@ def print_agent_info(self, agent_info, pdf): fields[key] = fields[key] + diff #Set color and print th pdf.set_font('Arial', '', 8) - pdf.set_fill_color(93, 188, 210) + pdf.set_fill_color(75, 179, 204) pdf.set_text_color(255,255,255) for key in sorted_fields: pdf.cell(fields[key], 4, str(key), 0, 0, 'L', 1) pdf.ln() #Change text color and print tr - self.pdf.set_text_color(93, 188, 210) + pdf.set_text_color(75, 179, 204) for key in sorted_fields: pdf.cell(fields[key], 4, str(agent_info[key]), 0, 0, 'L', 0) #Print the rest of the agent information pdf.ln(5) - self.pdf.set_text_color(169, 169, 169) + pdf.set_text_color(91, 91, 91) pdf.cell(0,6, "Registration date: " + str(agent_info['dateAdd']), 0, 0, 'L', 0) pdf.ln() pdf.cell(0,6, "Last keep alive: " + str(agent_info['lastKeepAlive']), 0, 0, 'L', 0) diff --git a/SplunkAppForWazuh/appserver/static/css/images/app_timelion.svg b/SplunkAppForWazuh/appserver/static/css/images/app_timelion.svg new file mode 100644 index 000000000..c470e746b --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/css/images/app_timelion.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/SplunkAppForWazuh/appserver/static/css/images/docker-black.svg b/SplunkAppForWazuh/appserver/static/css/images/docker-black.svg new file mode 100644 index 000000000..5882f47e5 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/css/images/docker-black.svg @@ -0,0 +1,11 @@ + + + + background + + + + Layer 1 + + + \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/css/images/docker.png b/SplunkAppForWazuh/appserver/static/css/images/docker.png new file mode 100644 index 000000000..d4f3c0ad2 Binary files /dev/null and b/SplunkAppForWazuh/appserver/static/css/images/docker.png differ diff --git a/SplunkAppForWazuh/appserver/static/css/images/groups.png b/SplunkAppForWazuh/appserver/static/css/images/groups.png index d8a595f16..c8de934df 100644 Binary files a/SplunkAppForWazuh/appserver/static/css/images/groups.png and b/SplunkAppForWazuh/appserver/static/css/images/groups.png differ diff --git a/SplunkAppForWazuh/appserver/static/css/images/loupe.png b/SplunkAppForWazuh/appserver/static/css/images/loupe.png new file mode 100644 index 000000000..83c9d7427 Binary files /dev/null and b/SplunkAppForWazuh/appserver/static/css/images/loupe.png differ diff --git a/SplunkAppForWazuh/appserver/static/css/images/reporting.png b/SplunkAppForWazuh/appserver/static/css/images/reporting.png index 09b8249f8..1967ab9e4 100644 Binary files a/SplunkAppForWazuh/appserver/static/css/images/reporting.png and b/SplunkAppForWazuh/appserver/static/css/images/reporting.png differ diff --git a/SplunkAppForWazuh/appserver/static/css/images/sca.png b/SplunkAppForWazuh/appserver/static/css/images/sca.png new file mode 100644 index 000000000..a1dd904b0 Binary files /dev/null and b/SplunkAppForWazuh/appserver/static/css/images/sca.png differ diff --git a/SplunkAppForWazuh/appserver/static/css/images/sca_no_scans.png b/SplunkAppForWazuh/appserver/static/css/images/sca_no_scans.png new file mode 100644 index 000000000..5a013d6e2 Binary files /dev/null and b/SplunkAppForWazuh/appserver/static/css/images/sca_no_scans.png differ diff --git a/SplunkAppForWazuh/appserver/static/css/styles/common.css b/SplunkAppForWazuh/appserver/static/css/styles/common.css index 4d8462233..707b6faf2 100644 --- a/SplunkAppForWazuh/appserver/static/css/styles/common.css +++ b/SplunkAppForWazuh/appserver/static/css/styles/common.css @@ -20,6 +20,10 @@ outline-color: transparent !important; } */ +.wzJsonXmlEditorBody, .wzJsonXmlEditorBody .CodeMirror{ + height: 100%; + min-height: 300px; +} /* * https://css-tricks.com/snippets/css/prevent-long-urls-from-breaking-out-of-container/ @@ -37,6 +41,23 @@ hyphens: auto; } +.md-toolbar-tools .md-button:not(.wz-menu-settings) { + margin-top: 0; + margin-bottom: 0; + height: 50px; + border-radius: 0; + line-height: 50px!important; + padding: 0px 16px; + margin: 0px; +} + +.wz-menu-settings{ + min-width: 30px; + border-radius: 100px; + margin-left: 5px; + margin-right: 5px !important; +} + .addGroupInput { max-height: 20px !important; max-width: 181px !important; @@ -51,6 +72,13 @@ min-height: 300px; } +.btns-separator{ + width: 0px; + height: 40px; + border: 1px solid #f2f4f5; + margin: 0px 9px; +} + .agreeBtn { min-height: 0px !important; max-height: 25px !important; @@ -82,7 +110,7 @@ } .groupContentViewer { - height: calc('100vh - 550px'); + height: calc(100vh - 345px) !important; min-height: 300px; } @@ -99,6 +127,22 @@ padding-left: 8px } +.wz-padding-left-15 { + padding-left: 15px +} + +.wz-padding-left-20 { + padding-left: 20px +} + +.wz-padding-top-7 { + padding-top: 7px; +} + +.wz-padding-20 { + padding: 20px; +} + .wz-back-btn-absolute{ position: absolute!important; top: 210px!important; @@ -201,7 +245,9 @@ md-dialog .md-actions, md-dialog md-dialog-actions{ border: none!important; } - +.md-padding-h{ + padding: 0 16px; +} md-dialog .md-button.md-primary:not(.md-cancel-button){ color: #ffffff; @@ -300,13 +346,17 @@ md-dialog .md-button.md-primary:not(.md-cancel-button):hover{ } /* Special fix to make Kibana search bar similar to the rest from the app */ - -.kuiLocalSearchInput, -.kuiLocalSearchInput:focus { +.kuiLocalSearchInput{ box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.1) !important; border: 1px solid #D9D9D9 !important; } +.kuiLocalSearchInput:focus { + border:none !important; + border-bottom: 1px solid rgb(64, 136, 231) !important; +} + + /* Custom loading ring styles */ div.uil-ring-css { @@ -364,8 +414,49 @@ div.uil-ring-css { top: -3px; } -.wz-margin-top-4 { - margin-top: 4px; +.text-black { + color: black !important; +} + +.wz-ruleset-subnav { + margin: 15px; + margin-right: 0px !important; + margin-left: 0px !important; +} + +.wz-margin-12 { + margin: 12px; +} + +.wz-margin-9 { + margin: 9px !important; +} + +.wz-margin-top-0 { + margin-top: 0px !important; +} + +.wz-margin-bottom--15 { + margin-bottom: -15px !important; +} + +.wz-height-35 { + height: 35px !important; +} +.wz-height-20 { + height: 20px !important; +} + +.wz-width-85 { + min-width: 85px; + width: 85px; + max-width: 85px; +} + +.wz-width-150 { + min-width: 150px; + width: 150px; + max-width: 150px; } /* Custom buttons styles */ @@ -373,7 +464,8 @@ div.uil-ring-css { .wz-button { color: white !important; transition: none !important; - background-color: rgb(0, 85, 113) !important; + background-color: rgb(0, 121, 165) !important; + border-color: rgb(0, 121, 165) !important; } .wz-button-flat { @@ -385,7 +477,9 @@ div.uil-ring-css { .wz-button.active, .wz-button:not([disabled]):hover, .wz-button-flat:not([disabled]):hover { - background-color: rgb(0, 121, 165) !important; + background-color: rgb(0, 85, 113) !important; + border-color: rgb(0, 85, 113) !important; + text-decoration: underline !important; color: white !important; } @@ -437,6 +531,10 @@ div.uil-ring-css { border-color: rgba(0,0,0,0.12) !important; } +.wz-input-container input.ng-invalid.ng-touched { + border-color: rgba(59, 70, 226, 0.904) !important; +} + .wz-autocomplete md-autocomplete-wrap { box-shadow: none !important; } @@ -478,10 +576,6 @@ div.uil-ring-css { background-color: grey; } -.wz-metric-color { - background-color: rgb(228, 242, 245); -} - .wz-background-transparent { background-color: transparent; } @@ -536,10 +630,10 @@ kbn-vis .vis-container { } .wz-dev-column-separator{ width: 14px; - margin-top: 25px; + margin-top: 29px; background: #dddddd; float: left; - height: calc(100vh - 110px); + height: calc(100vh - 145px); cursor: ew-resize; text-align: center; display:block!important; @@ -550,7 +644,7 @@ kbn-vis .vis-container { } .wz-dev-column-separator span { - height: calc(100vh - 110px); + height: calc(100vh - 150px); display: table-cell; vertical-align: middle; } @@ -560,15 +654,16 @@ kbn-vis .vis-container { min-width: calc(20% - 7px); max-width: calc(80% - 7px); float: left; - height: calc(100vh - 85px); + height: calc(100vh - 117px); } #wz-dev-right-column{ width: calc(70% - 7px); - min-width: calc(20% - 7px); - max-width: calc(80% - 7px); + min-width: calc(20% - 12px); + max-width: calc(80% - 18px); float: left; - height: calc(100vh - 85px); + margin-top: 3px; + height: calc(100vh - 119px); } .wz-question-dev-color { @@ -590,7 +685,7 @@ kbn-vis .vis-container { .wz-card-actions { margin: 0 !important; border-top: 1px solid #D9D9D9 !important; - background-color: rgb(228, 242, 245); + background-color: #dfeff8; } .wz-select-input { @@ -749,7 +844,7 @@ kbn-vis .vis-container { font-size: 14px; line-height: 0; color: #ffffff; - background-color: #666; + background-color: #0079a5; border: 0; border-radius: 0 4px 4px 0; } @@ -760,7 +855,7 @@ kbn-vis .vis-container { font-size: 14px; line-height: 0; color: #ffffff; - background-color: #666; + background-color: #0079a5; border: 0; border-radius: 0 4px 4px 0; } @@ -816,6 +911,16 @@ kbn-vis .vis-container { height: 35px !important; } +.btn-as-i { + background: transparent !important; + border: 0; + padding: 0!important; + margin: 0; + font-size: 18px; + -webkit-box-shadow: none!important; + box-shadow: none!important; +} + md-backdrop.md-opaque { opacity: 1!important; background-color: rgba(255, 255, 255, 0.8); @@ -860,6 +965,17 @@ md-dialog{ color: #005571!important; } +.edit-cancel-button { + border: none !important; + color: rgb(0, 121, 165) !important; + background: #fafafa !important; +} + +.edit-cancel-button:hover { + text-decoration: underline !important; +} + + .md-title { color: #1a1a1a; font-size: 24px; @@ -892,4 +1008,828 @@ md-dialog .md-button.md-primary:not(.md-cancel-button){ md-dialog .md-button.md-primary:not(.md-cancel-button):hover{ background-color: #005472!important; border-color: #004c68!important; +} + + +md-toast .toastTheme { + background-color: white; + animation: none!important; + transition: none!important; + transform: none!important; + bottom: 0; + right: 0;; + padding:0; + margin: 0; +} + +.md-toast-content { + color: #1a1a1a; + font-size: 24px; + font-weight: 500; +} + +md-toast { + margin: 15px; + padding: 0; + position:fixed; + animation: none!important; + transition: none!important; + transform: none!important; + max-width:600px; + box-shadow: 0 40px 64px 0 rgba(59, 79, 93, 0.3), + 0 24px 32px 0 rgba(59, 79, 93, 0.3), + 0 16px 16px 0 rgba(59, 79, 93, 0.3), + 0 8px 8px 0 rgba(59, 79, 93, 0.3), + 0 4px 4px 0 rgba(59, 79, 93, 0.3), + 0 2px 2px 0 rgba(59, 79, 93, 0.3)!important; +} +.fullscreen { + display: -webkit-box; + display: -webkit-flex; + display: -ms-flexbox; + display: flex; + z-index: 9999; + width: auto; + height: calc(100vh - 100px); + position: fixed; + top: 0; + left: 0; + right: 0; + background-color: white; + margin: 50px 10px 50px 10px; + outline: 50px solid rgba(0, 0, 0, 0.5)!important; + max-width: 100% !important; + } + +.wz-table-checkboxes { + width: 100%; + text-align: right; + padding-right: 10px; + text-align: left; +} + +.wz-text-truncatable-ellipsis { + white-space: nowrap; + overflow: hidden; + max-width: 1px; + text-overflow: ellipsis; + padding-right: 40px !important; +} + +.wz-text-truncatable { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.wz-text-sca { + width: calc(100% - 100px) !important; + line-height: initial; +} + +.wz-text-truncatable-container { + overflow: hidden; + width: auto; + display: grid; +} + +span.pass { + background-color: green !important; + color: white !important; + width: 50px !important; + display: inline-block !important; + text-align: center !important; +} + +span.wrong { + background-color: red !important; + color: white !important; + width: 50px !important; + display: inline-block !important; + text-align: center !important; +} +.overflow-auto { + overflow: auto; +} + +.configuration-margin-top{ + height: calc(100vh - 225); +} + +.boldText { + font-weight: bold; +} + +.expandedDiv { + margin-bottom: 20px; + padding-left: 20px; +} + +.pExpanded { + margin-bottom: -10px; + margin-top: 2px; + color: #696565; +} + +.blueLeftBorder { + border-left: 3px solid #0079a5; +} + +.backgroundSky { + background: #ebf6ff; +} + +.tSize16 { + font-size: 16px; + font-weight: 400; +} + +.noBorderBottom { + border-bottom: none !important; +} + +.littleStat { + height: 8px !important; + width: 8px !important; + display: inline-flex; + margin-right: -4px; +} + +.table-width-id{ + width: 60px !important; +} + +.table-width-filename{ + width: 250px !important; +} + +.daemons-card { + padding: 8px 5px !important; +} + +.daemon-label { + margin-top: 0; + margin-bottom: 0; + width: 165px; + float: left; + border-radius: 30px; + margin: 3px; +} + +.daemon-bullet { + float: left; + margin: 5px 0 0 8px; +} + +.daemon-name { + padding: 2px 10px 5px 28px; + margin-bottom: 0 !important; +} + +div.inline { + display: inline-block; +} + +.btn[disabled] { + opacity: .7 !important; + box-shadow: none !important; +} + +.btn[disabled]:hover { + opacity: .7 !important; + box-shadow: none !important; +} + +.md-actions-ruleset { + height: 45px; + border-top: 0px !important; + padding: 15px; +} + +.ruleset-csv-formater { + padding-bottom: 10px; + padding-right: 20px; + /*background: #e4f2f5;*/ + margin-top: -36px; + padding-top: 10px; +} + +.show-checkboxes { + background-color: rgb(228, 242, 245); + margin-left: -16px; + margin-right: -16px; + margin-top: -16px; + margin-bottom: 10px; + padding-top: 16px; +} + +.showing-checks { + margin-right: 15px; + margin-top: 5px +} + +.not-showing-checks { + margin-bottom: -21px; + margin-right: 0px; + font-size: 22px; + cursor: pointer; + z-index: 100; +} + +.no-margin-sides { + margin-right: 0; + margin-left: 0; +} + +.table-resizable >thead th:not(:first-child){ + border-left: 1px dashed #dfeff8; + min-width: 75px; +} + +.table-conf { + margin-left: 1%; + margin-right: 1%; + margin-top: 1%; + width: auto; + min-width: auto; +} + +.md-actions-conf { + height: 45px; + border-top: 0px !important; +} + +.btn-invisible-conf { + background: none; + border: none; + color: #0079a5; + height: 45px; + padding-left: 15px; +} + +.btn-invisible-sca { + background: none; + border: 0; + font-weight: bold; + color: #0079a5; +} + +tr.striped { + background-color: rgb(250,250,250); +} + +th.w-350 { + width: 350px; +} + +.medium-text { + font-size: 17px; +} + +.files-button { + padding-left: 10px; + margin-left: 20px; + height: 32px; +} + +.remove-filters { + padding: 10px; + margin-right: -30px; +} + +.wz-color-text { + color: #006eaa; +} + +.back-arrow { + margin-top: 4px; + margin-right: 12px; + margin-left: 5px; +} + +.wz-lh-32 { + line-height: 32px; +} + +.sca-switch-div { + margin: 10px; + margin-top: -30px; + height: 30px; +} + +.formatted-div-inventory { + margin-right: -10px; + margin-left: -10px; + margin-bottom: -8px; +} + +.agent-details-box{ + padding: 10px 0 0 10px; + font-size: 14px; +} + +.wz-no-padding-bottom { + padding-bottom: 0px !important; +} + +#wz-progress { + margin: 5px 0; + width: 100%; + background-color: #ddd; + margin: 20px; + margin-bottom: -5px; + height: 30px; +} + + #wz-progress-bar { + color: white; + font-weight: bold; + height: 20px; + padding: 5px; + background-color: #0079a5; + white-space: nowrap; +} + +.lateral-margin-15 { + margin-left: 15px; + margin-right: 15px; +} + +.input-new-group { + height: 20px !important; + font-size: 12px !important; + margin: 5px !important; + border: none !important; +} + +.save-group-button { + margin: 5px -1px!important; + border: none !important; + background-color: #e4f2f5 !important; + color: #0079a5 !important; + font-weight: bold !important; +} + +tfoot.no-border tr { + border: none !important; +} + +tfoot.no-border tr td { + border: none !important; +} + +.less-12-mr { + margin-right: -12px; +} + +.less-15-m { + margin: -15px; +} + +.less-15-side { + margin: 0px 15px 0px 15px; +} + +.less-25-side { + margin: 0px 25px 0px 25px; +} + +.wz-margin-right-600 { + margin-right: 600px; +} + +/* New buttons style */ +.wz-button-empty { + background: white !important; + border-color: rgb(0, 121, 165) !important; + color: rgb(0, 121, 165) !important; + font-weight: 400 !important; + border-width: 1px !important; +} + +.wz-button-empty.active, +.wz-button-empty:not([disabled]):hover, +.wz-button-empty-flat:not([disabled]):hover { + background-color: rgb(228, 242, 245) !important; + color: rgb(0, 121, 165) !important; +} + +.wz-button-empty-yellow { + background: white !important; + border-color: #a9600a !important; + color: #a9600a !important; + font-weight: 400 !important; + border-width: 1px !important; +} + +.wz-button-empty-yellow.active, +.wz-button-empty-yellow:not([disabled]):hover, +.wz-button-empty-yellow-flat:not([disabled]):hover { + background-color: rgb(228, 242, 245) !important; + color: #a9600a !important; +} + +.wz-button-empty-green { + background: white !important; + border-color: #08a74e !important; + color: #08a74e !important; + font-weight: 400 !important; + border-width: 1px !important; +} + +.wz-button-empty-green.active, +.wz-button-empty-green:not([disabled]):hover, +.wz-button-empty-green-flat:not([disabled]):hover { + background-color: rgb(228, 242, 245) !important; + color: #08a74e !important; +} + +.wz-button-empty-red { + background: white !important; + border-color: #930000 !important; + color: #930000 !important; + font-weight: 400 !important; + border-width: 1px !important; +} + +.wz-button-empty-red.active, +.wz-button-empty-red:not([disabled]):hover, +.wz-button-empty-red-flat:not([disabled]):hover { + background-color: rgb(228, 242, 245) !important; + color: #930000 !important; +} + +.wz-button-empty-blue { + background: white !important; + border-color: #006193 !important; + color: #006193 !important; + font-weight: 400 !important; + border-width: 1px !important; +} + +.wz-button-empty-blue.active, +.wz-button-empty-blue:not([disabled]):hover, +.wz-button-empty-blue-flat:not([disabled]):hover { + background-color: rgb(228, 242, 245) !important; + color: #006193 !important; +} + +.wz-button-cancel { + background: white !important; + border-color: #5c6773 !important; + color: #5c6773 !important; +} + +.wz-button-cancel.active, +.wz-button-cancel:not([disabled]):hover, +.wz-button-cancel-flat:not([disabled]):hover { + background-color: #e4e4e4 !important; + color: #5c6773 !important; +} + +.wz-button-report { + margin-right: 5px; + height: 32px; + margin-top: 5px; +} + +.wz-div-discover { + width:80px; + padding-top:10px; + cursor:pointer; + white-space: nowrap; + margin-right: 25px; + margin-top: -5px; +} + +input:focus { + height: 30px; + border-bottom: 2px solid #4198ec !important; +} + + +.wz-nowrap { + white-space: nowrap; +} + +#timePicker button { + min-width: 100% !important; + border: solid 1px #0079bb !important; + color: #0079bb !important; + background: white !important; +} + +#timePicker button:hover { + background: #e4f2f5 !important; +} + +#dropDownInput button { + border: solid 1px #0079bb !important; + color: #0079bb !important; + background: white !important; + } + +#dropDownInput button:hover { + background: #e4f2f5 !important; +} + +#dropDownInputAgent button { + min-width: 100% !important; + border: solid 1px #0079bb !important; + color: #0079bb !important; + background: white !important; + } + +#dropDownInputAgent button:hover { + background: #e4f2f5 !important; +} + +.dl-rules { + margin: 5px 0px!important; +} + +.dd-rules { + margin: 3px !important; +/* Head toaster */ +} + +.ht-info{ + height: 50px !important; + background-color: rgb(228, 242, 245) !important; + border-left: solid 3px !important; + border-color:rgb(0, 121, 165) !important; + color: #006193 !important; +} + +.ht-success { + height: 50px !important; + background-color: rgb(228, 245, 236) !important; + border-left: solid 3px !important; + border-color: #00f56d !important; + color: #08a74e !important; +} + +.ht-warning { + height: 50px !important; + background-color: #fef6e6 !important; + border-left: solid 3px !important; + border-color: #F5A700 !important; + color: #936400 !important; +} + +.ht-error{ + height: 50px !important; + background-color: rgb(245, 228, 228) !important; + border-left: solid 3px !important; + border-color: #f50000 !important; + color: #930000 !important; +} + +.wz-full-width { + width: 100% !important; +} + +.conf-node-selector { + margin-top: 5px !important; + margin-right: 50px !important; +} + +.settings-edit-ossec { + margin-right: -10px !important; + margin-top: -2px !important; + margin-left: 5px !important; +} + +.node-will-be-restarted { + color: #0079a5 !important; + line-height: 2 !important; +} + +.wc-sub-title { + font-weight: 100 !important; + font-size: 18px !important; +} + +.wc-title { + font-weight: 100 !important; + font-size: 21px !important; +} + +.wz-wc-item:hover { + background: #fafcfe; +} + +.wz-wc-item:hover h4 { + text-decoration: underline; +} + +.agentField { + font-weight: bold !important; + color: #006bb4 !important; +} + +.wz-margin-side-20 { + margin-left: 20px !important; + margin-right: 20px !important; +} + +.wz-width-100p { + width: 100% !important; +} + +.wz-input-text { + padding: 5px !important; + width: 100% !important; + word-wrap: break-word !important; + font-family: monospace !important; + background-color: #ffffff !important; + border: 1px solid #D9D9D9 !important; + -webkit-box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.1) !important; + box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.1) !important; +} + +.td-align-middle { + vertical-align: middle!important; +} + +.formatted-color { + color: #1278b0 !important; +} + +.switch-log { + margin: 5px 10px; +} + +.wz-text-align-right { + text-align: right; +} + +.table-condensed td { + padding: 5px !important; +} + +/* Loading bar */ + +.loader-bar { + margin-top: 10px; + margin-right: 20px; + margin-left: 20px; +} + +.loader { + height: 2px; + width: 100%; + position: relative; + overflow: hidden; + background-color: #ddd; +} +.loader:before{ + display: block; + position: absolute; + content: ""; + left: -200px; + width: 200px; + height: 2px; + background-color: #2980b9; + animation: loading 2s linear infinite; +} + +@keyframes loading { + from {left: -200px; width: 30%;} + 50% {width: 30%;} + 70% {width: 70%;} + 80% { left: 50%;} + 95% {left: 120%;} + to {left: 100%;} +} + + +/* eui spinner */ + +.euiLoadingSpinner--medium { + width: 16px; + height: 16px; + border-width: 1px; +} +.euiLoadingSpinner { + display: inline-block; + width: 32px; + height: 32px; + border-radius: 50%; + border: solid 2px #D3DAE6; + border-color: #006BB4 #D3DAE6 #D3DAE6 #D3DAE6; + -webkit-animation: euiLoadingSpinner .6s infinite linear; + animation: euiLoadingSpinner .6s infinite linear; +} + + +/* Do not show the last resize th */ +.table-resizable > thead th:last-child .ui-resizable-handle { + display: none !important; +} + + +.wz-breadcrumb-margin{ + margin-left:10px; + margin-top:12px; +} + + + +label.wz-icon-loupe { + position: relative; + width:100%; +} + +label.wz-icon-loupe:before { + content: ""; + position: absolute; + left: 10px; + bottom: 0; + width: 20px; + height: 40px; + background: url(/static/app/SplunkAppForWazuh/css/images/loupe.png) no-repeat; + background-size: 18px; +} + +label.wz-icon-loupe input { + padding: 0px 35px !important; + width:100%; +} + +.float_warning-icon { + margin-bottom: 5px; + margin-right: -5px; +} + +.noDot { + list-style-type: none !important; + margin-left: 0px !important; +} + +.orange { + color: #ff9999; +} + +.gray { + background-color: #5c6773 !important; +} + +.center { + margin: 0 auto !important; + text-align: center !important; +} + +.sca-title { + font-size: 16px !important; +} + +.sca-title-checks{ + font-size: 13px !important; +} + +.sca-hash { + margin: 10px 5px; + display: block; + color: gray; +} + +.wz-md-card:not(.fullscreen) .vis-sca #radialGauge > div > div > svg > path:nth-child(6) { + visibility: hidden !important; +} + +.wz-md-card:not(.fullscreen) .vis-sca #radialGauge > div > div > svg > path:nth-child(8) { + visibility: hidden !important; +} + +.wz-md-card:not(.fullscreen) .vis-sca #radialGauge > div > div > svg > path:nth-child(10) { + visibility: hidden !important; +} + +.wz-md-card:not(.fullscreen) .vis-sca #radialGauge > div > div > svg > path:nth-child(12) { + visibility: hidden !important; +} + +.wz-md-card:not(.fullscreen) .vis-sca #radialGauge > div > div > svg > path:nth-child(14) { + visibility: hidden !important; +} + +.wz-md-card:not(.fullscreen) .vis-sca #radialGauge > div > div > svg > path:nth-child(16) { + visibility: hidden !important; +} + +.wz-md-card:not(.fullscreen) .vis-sca #radialGauge > div > div > svg > text:nth-child(20) { + font-size: 25px !important; +} + +.wz-md-card:not(.fullscreen) .vis-sca #radialGauge > div > div > svg > text:not(:nth-child(20)) { + visibility: hidden !important; +} + +.vis-sca .viz-panel { + width: 15% !important; +} + +#scoreByPolicy .lazy-view-container { + height: 80% !important; } \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/css/styles/component.css b/SplunkAppForWazuh/appserver/static/css/styles/component.css index bc94a4799..d191bdb9c 100644 --- a/SplunkAppForWazuh/appserver/static/css/styles/component.css +++ b/SplunkAppForWazuh/appserver/static/css/styles/component.css @@ -93,7 +93,8 @@ md-dialog-actions button { } .wz-white-background { - background-color:white !important; + /*background-color:white !important;*/ + background-color: #fafafa; } /* Custom switch styles */ diff --git a/SplunkAppForWazuh/appserver/static/css/styles/height.css b/SplunkAppForWazuh/appserver/static/css/styles/height.css index ed1a2c6e1..bcb11e1cc 100644 --- a/SplunkAppForWazuh/appserver/static/css/styles/height.css +++ b/SplunkAppForWazuh/appserver/static/css/styles/height.css @@ -14,9 +14,14 @@ /* ------------------------ Wazuh heights stylesheet ------------------------ */ /* -------------------------------------------------------------------------- */ +.height-32 { + height: 32px !important; +} + .height-40 { height: 40px !important; } + .height-50 { height: 50px; } @@ -42,7 +47,7 @@ } .height-200 { - height: 200px; + height: 200px !important; } .height-213 { diff --git a/SplunkAppForWazuh/appserver/static/css/styles/jquery-ui.css b/SplunkAppForWazuh/appserver/static/css/styles/jquery-ui.css new file mode 100644 index 000000000..719287fe6 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/css/styles/jquery-ui.css @@ -0,0 +1,1536 @@ +/*! jQuery UI - v1.11.0 - 2014-06-26 +* http://jqueryui.com +* Includes: core.css, accordion.css, autocomplete.css, button.css, datepicker.css, dialog.css, draggable.css, menu.css, progressbar.css, resizable.css, selectable.css, selectmenu.css, slider.css, sortable.css, spinner.css, tabs.css, tooltip.css, theme.css +* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Verdana%2CArial%2Csans-serif&fwDefault=normal&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=cccccc&bgTextureHeader=highlight_soft&bgImgOpacityHeader=75&borderColorHeader=aaaaaa&fcHeader=222222&iconColorHeader=222222&bgColorContent=ffffff&bgTextureContent=flat&bgImgOpacityContent=75&borderColorContent=aaaaaa&fcContent=222222&iconColorContent=222222&bgColorDefault=e6e6e6&bgTextureDefault=glass&bgImgOpacityDefault=75&borderColorDefault=d3d3d3&fcDefault=555555&iconColorDefault=888888&bgColorHover=dadada&bgTextureHover=glass&bgImgOpacityHover=75&borderColorHover=999999&fcHover=212121&iconColorHover=454545&bgColorActive=ffffff&bgTextureActive=glass&bgImgOpacityActive=65&borderColorActive=aaaaaa&fcActive=212121&iconColorActive=454545&bgColorHighlight=fbf9ee&bgTextureHighlight=glass&bgImgOpacityHighlight=55&borderColorHighlight=fcefa1&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=fef1ec&bgTextureError=glass&bgImgOpacityError=95&borderColorError=cd0a0a&fcError=cd0a0a&iconColorError=cd0a0a&bgColorOverlay=aaaaaa&bgTextureOverlay=flat&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=aaaaaa&bgTextureShadow=flat&bgImgOpacityShadow=0&opacityShadow=30&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px +* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ + +/* Layout helpers +----------------------------------*/ +.ui-helper-hidden { + display: none; +} +.ui-helper-hidden-accessible { + border: 0; + clip: rect(0 0 0 0); + height: 1px; + margin: -1px; + overflow: hidden; + padding: 0; + position: absolute; + width: 1px; +} +.ui-helper-reset { + margin: 0; + padding: 0; + border: 0; + outline: 0; + line-height: 1.3; + text-decoration: none; + font-size: 100%; + list-style: none; +} +.ui-helper-clearfix:before, +.ui-helper-clearfix:after { + content: ''; + display: table; + border-collapse: collapse; +} +.ui-helper-clearfix:after { + clear: both; +} +.ui-helper-clearfix { + min-height: 0; /* support: IE7 */ +} +.ui-helper-zfix { + width: 100%; + height: 100%; + top: 0; + left: 0; + position: absolute; + opacity: 0; + filter: Alpha(Opacity=0); +} + +.ui-front { + z-index: 100; +} + +/* Interaction Cues +----------------------------------*/ +.ui-state-disabled { + cursor: default !important; +} + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { + display: block; + text-indent: -99999px; + overflow: hidden; + background-repeat: no-repeat; +} + +/* Misc visuals +----------------------------------*/ + +/* Overlays */ +.ui-widget-overlay { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; +} +.ui-accordion .ui-accordion-header { + display: block; + cursor: pointer; + position: relative; + margin: 2px 0 0 0; + padding: 0.5em 0.5em 0.5em 0.7em; + min-height: 0; /* support: IE7 */ + font-size: 100%; +} +.ui-accordion .ui-accordion-icons { + padding-left: 2.2em; +} +.ui-accordion .ui-accordion-icons .ui-accordion-icons { + padding-left: 2.2em; +} +.ui-accordion .ui-accordion-header .ui-accordion-header-icon { + position: absolute; + left: 0.5em; + top: 50%; + margin-top: -8px; +} +.ui-accordion .ui-accordion-content { + padding: 1em 2.2em; + border-top: 0; + overflow: auto; +} +.ui-autocomplete { + position: absolute; + top: 0; + left: 0; + cursor: default; +} +.ui-button { + display: inline-block; + position: relative; + padding: 0; + line-height: normal; + margin-right: 0.1em; + cursor: pointer; + vertical-align: middle; + text-align: center; + overflow: visible; /* removes extra width in IE */ +} +.ui-button, +.ui-button:link, +.ui-button:visited, +.ui-button:hover, +.ui-button:active { + text-decoration: none; +} +/* to make room for the icon, a width needs to be set here */ +.ui-button-icon-only { + width: 2.2em; +} +/* button elements seem to need a little more width */ +button.ui-button-icon-only { + width: 2.4em; +} +.ui-button-icons-only { + width: 3.4em; +} +button.ui-button-icons-only { + width: 3.7em; +} + +/* button text element */ +.ui-button .ui-button-text { + display: block; + line-height: normal; +} +.ui-button-text-only .ui-button-text { + padding: 0.4em 1em; +} +.ui-button-icon-only .ui-button-text, +.ui-button-icons-only .ui-button-text { + padding: 0.4em; + text-indent: -9999999px; +} +.ui-button-text-icon-primary .ui-button-text, +.ui-button-text-icons .ui-button-text { + padding: 0.4em 1em 0.4em 2.1em; +} +.ui-button-text-icon-secondary .ui-button-text, +.ui-button-text-icons .ui-button-text { + padding: 0.4em 2.1em 0.4em 1em; +} +.ui-button-text-icons .ui-button-text { + padding-left: 2.1em; + padding-right: 2.1em; +} +/* no icon support for input elements, provide padding by default */ +input.ui-button { + padding: 0.4em 1em; +} + +/* button icon element(s) */ +.ui-button-icon-only .ui-icon, +.ui-button-text-icon-primary .ui-icon, +.ui-button-text-icon-secondary .ui-icon, +.ui-button-text-icons .ui-icon, +.ui-button-icons-only .ui-icon { + position: absolute; + top: 50%; + margin-top: -8px; +} +.ui-button-icon-only .ui-icon { + left: 50%; + margin-left: -8px; +} +.ui-button-text-icon-primary .ui-button-icon-primary, +.ui-button-text-icons .ui-button-icon-primary, +.ui-button-icons-only .ui-button-icon-primary { + left: 0.5em; +} +.ui-button-text-icon-secondary .ui-button-icon-secondary, +.ui-button-text-icons .ui-button-icon-secondary, +.ui-button-icons-only .ui-button-icon-secondary { + right: 0.5em; +} + +/* button sets */ +.ui-buttonset { + margin-right: 7px; +} +.ui-buttonset .ui-button { + margin-left: 0; + margin-right: -0.3em; +} + +/* workarounds */ +/* reset extra padding in Firefox, see h5bp.com/l */ +input.ui-button::-moz-focus-inner, +button.ui-button::-moz-focus-inner { + border: 0; + padding: 0; +} +.ui-datepicker { + width: 17em; + padding: 0.2em 0.2em 0; + display: none; +} +.ui-datepicker .ui-datepicker-header { + position: relative; + padding: 0.2em 0; +} +.ui-datepicker .ui-datepicker-prev, +.ui-datepicker .ui-datepicker-next { + position: absolute; + top: 2px; + width: 1.8em; + height: 1.8em; +} +.ui-datepicker .ui-datepicker-prev-hover, +.ui-datepicker .ui-datepicker-next-hover { + top: 1px; +} +.ui-datepicker .ui-datepicker-prev { + left: 2px; +} +.ui-datepicker .ui-datepicker-next { + right: 2px; +} +.ui-datepicker .ui-datepicker-prev-hover { + left: 1px; +} +.ui-datepicker .ui-datepicker-next-hover { + right: 1px; +} +.ui-datepicker .ui-datepicker-prev span, +.ui-datepicker .ui-datepicker-next span { + display: block; + position: absolute; + left: 50%; + margin-left: -8px; + top: 50%; + margin-top: -8px; +} +.ui-datepicker .ui-datepicker-title { + margin: 0 2.3em; + line-height: 1.8em; + text-align: center; +} +.ui-datepicker .ui-datepicker-title select { + font-size: 1em; + margin: 1px 0; +} +.ui-datepicker select.ui-datepicker-month, +.ui-datepicker select.ui-datepicker-year { + width: 49%; +} +.ui-datepicker table { + width: 100%; + font-size: 0.9em; + border-collapse: collapse; + margin: 0 0 0.4em; +} +.ui-datepicker th { + padding: 0.7em 0.3em; + text-align: center; + font-weight: bold; + border: 0; +} +.ui-datepicker td { + border: 0; + padding: 1px; +} +.ui-datepicker td span, +.ui-datepicker td a { + display: block; + padding: 0.2em; + text-align: right; + text-decoration: none; +} +.ui-datepicker .ui-datepicker-buttonpane { + background-image: none; + margin: 0.7em 0 0 0; + padding: 0 0.2em; + border-left: 0; + border-right: 0; + border-bottom: 0; +} +.ui-datepicker .ui-datepicker-buttonpane button { + float: right; + margin: 0.5em 0.2em 0.4em; + cursor: pointer; + padding: 0.2em 0.6em 0.3em 0.6em; + width: auto; + overflow: visible; +} +.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { + float: left; +} + +/* with multiple calendars */ +.ui-datepicker.ui-datepicker-multi { + width: auto; +} +.ui-datepicker-multi .ui-datepicker-group { + float: left; +} +.ui-datepicker-multi .ui-datepicker-group table { + width: 95%; + margin: 0 auto 0.4em; +} +.ui-datepicker-multi-2 .ui-datepicker-group { + width: 50%; +} +.ui-datepicker-multi-3 .ui-datepicker-group { + width: 33.3%; +} +.ui-datepicker-multi-4 .ui-datepicker-group { + width: 25%; +} +.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header, +.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { + border-left-width: 0; +} +.ui-datepicker-multi .ui-datepicker-buttonpane { + clear: left; +} +.ui-datepicker-row-break { + clear: both; + width: 100%; + font-size: 0; +} + +/* RTL support */ +.ui-datepicker-rtl { + direction: rtl; +} +.ui-datepicker-rtl .ui-datepicker-prev { + right: 2px; + left: auto; +} +.ui-datepicker-rtl .ui-datepicker-next { + left: 2px; + right: auto; +} +.ui-datepicker-rtl .ui-datepicker-prev:hover { + right: 1px; + left: auto; +} +.ui-datepicker-rtl .ui-datepicker-next:hover { + left: 1px; + right: auto; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane { + clear: right; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane button { + float: left; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current, +.ui-datepicker-rtl .ui-datepicker-group { + float: right; +} +.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header, +.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { + border-right-width: 0; + border-left-width: 1px; +} +.ui-dialog { + overflow: hidden; + position: absolute; + top: 0; + left: 0; + padding: 0.2em; + outline: 0; +} +.ui-dialog .ui-dialog-titlebar { + padding: 0.4em 1em; + position: relative; +} +.ui-dialog .ui-dialog-title { + float: left; + margin: 0.1em 0; + white-space: nowrap; + width: 90%; + overflow: hidden; + text-overflow: ellipsis; +} +.ui-dialog .ui-dialog-titlebar-close { + position: absolute; + right: 0.3em; + top: 50%; + width: 20px; + margin: -10px 0 0 0; + padding: 1px; + height: 20px; +} +.ui-dialog .ui-dialog-content { + position: relative; + border: 0; + padding: 0.5em 1em; + background: none; + overflow: auto; +} +.ui-dialog .ui-dialog-buttonpane { + text-align: left; + border-width: 1px 0 0 0; + background-image: none; + margin-top: 0.5em; + padding: 0.3em 1em 0.5em 0.4em; +} +.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { + float: right; +} +.ui-dialog .ui-dialog-buttonpane button { + margin: 0.5em 0.4em 0.5em 0; + cursor: pointer; +} +.ui-dialog .ui-resizable-se { + width: 12px; + height: 12px; + right: -5px; + bottom: -5px; + background-position: 16px 16px; +} +.ui-draggable .ui-dialog-titlebar { + cursor: move; +} +.ui-draggable-handle { + -ms-touch-action: none; + touch-action: none; +} +.ui-menu { + list-style: none; + padding: 0; + margin: 0; + display: block; + outline: none; +} +.ui-menu .ui-menu { + position: absolute; +} +.ui-menu .ui-menu-item { + position: relative; + margin: 0; + padding: 3px 1em 3px 0.4em; + cursor: pointer; + min-height: 0; /* support: IE7 */ + /* support: IE10, see #8844 */ + list-style-image: url('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'); +} +.ui-menu .ui-menu-divider { + margin: 5px 0; + height: 0; + font-size: 0; + line-height: 0; + border-width: 1px 0 0 0; +} +.ui-menu .ui-state-focus, +.ui-menu .ui-state-active { + margin: -1px; +} + +/* icon support */ +.ui-menu-icons { + position: relative; +} +.ui-menu-icons .ui-menu-item { + padding-left: 2em; +} + +/* left-aligned */ +.ui-menu .ui-icon { + position: absolute; + top: 0; + bottom: 0; + left: 0.2em; + margin: auto 0; +} + +/* right-aligned */ +.ui-menu .ui-menu-icon { + left: auto; + right: 0; +} +.ui-progressbar { + height: 2em; + text-align: left; + overflow: hidden; +} +.ui-progressbar .ui-progressbar-value { + margin: -1px; + height: 100%; +} +.ui-progressbar-indeterminate .ui-progressbar-value { + background-image: none; +} +.ui-resizable { + position: relative; +} +.ui-resizable-handle { + position: absolute; + font-size: 0.1px; + display: block; + -ms-touch-action: none; + touch-action: none; +} +.ui-resizable-disabled .ui-resizable-handle, +.ui-resizable-autohide .ui-resizable-handle { + display: none; +} +.ui-resizable-handle:before { + background-color: transparent !important; + } +.ui-resizable-n { + cursor: n-resize; + height: 7px; + width: 100%; + top: -5px; + left: 0; +} +.ui-resizable-s { + cursor: s-resize; + height: 7px; + width: 100%; + bottom: -5px; + left: 0; +} +.ui-resizable-e { + cursor: e-resize; + width: 4px; + right: 0px; + top: 0; + height: 100%; + z-index: 10000 !important; +} +.ui-resizable-w { + cursor: w-resize; + width: 7px; + left: -5px; + top: 0; + height: 100%; +} +.ui-resizable-se { + cursor: se-resize; + width: 12px; + height: 12px; + right: 1px; + bottom: 1px; +} +.ui-resizable-sw { + cursor: sw-resize; + width: 9px; + height: 9px; + left: -5px; + bottom: -5px; +} +.ui-resizable-nw { + cursor: nw-resize; + width: 9px; + height: 9px; + left: -5px; + top: -5px; +} +.ui-resizable-ne { + cursor: ne-resize; + width: 9px; + height: 9px; + right: -5px; + top: -5px; +} +.ui-selectable { + -ms-touch-action: none; + touch-action: none; +} +.ui-selectable-helper { + position: absolute; + z-index: 100; + border: 1px dotted black; +} +.ui-selectmenu-menu { + padding: 0; + margin: 0; + position: absolute; + top: 0; + left: 0; + display: none; +} +.ui-selectmenu-menu .ui-menu { + overflow: auto; + /* Support: IE7 */ + overflow-x: hidden; + padding-bottom: 1px; +} +.ui-selectmenu-menu .ui-menu .ui-selectmenu-optgroup { + font-size: 1em; + font-weight: bold; + line-height: 1.5; + padding: 2px 0.4em; + margin: 0.5em 0 0 0; + height: auto; + border: 0; +} +.ui-selectmenu-open { + display: block; +} +.ui-selectmenu-button { + display: inline-block; + overflow: hidden; + position: relative; + text-decoration: none; + cursor: pointer; +} +.ui-selectmenu-button span.ui-icon { + right: 0.5em; + left: auto; + margin-top: -8px; + position: absolute; + top: 50%; +} +.ui-selectmenu-button span.ui-selectmenu-text { + text-align: left; + padding: 0.4em 2.1em 0.4em 1em; + display: block; + line-height: 1.4; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.ui-slider { + position: relative; + text-align: left; +} +.ui-slider .ui-slider-handle { + position: absolute; + z-index: 2; + width: 1.2em; + height: 1.2em; + cursor: default; + -ms-touch-action: none; + touch-action: none; +} +.ui-slider .ui-slider-range { + position: absolute; + z-index: 1; + font-size: 0.7em; + display: block; + border: 0; + background-position: 0 0; +} + +/* For IE8 - See #6727 */ +.ui-slider.ui-state-disabled .ui-slider-handle, +.ui-slider.ui-state-disabled .ui-slider-range { + filter: inherit; +} + +.ui-slider-horizontal { + height: 0.8em; +} +.ui-slider-horizontal .ui-slider-handle { + top: -0.3em; + margin-left: -0.6em; +} +.ui-slider-horizontal .ui-slider-range { + top: 0; + height: 100%; +} +.ui-slider-horizontal .ui-slider-range-min { + left: 0; +} +.ui-slider-horizontal .ui-slider-range-max { + right: 0; +} + +.ui-slider-vertical { + width: 0.8em; + height: 100px; +} +.ui-slider-vertical .ui-slider-handle { + left: -0.3em; + margin-left: 0; + margin-bottom: -0.6em; +} +.ui-slider-vertical .ui-slider-range { + left: 0; + width: 100%; +} +.ui-slider-vertical .ui-slider-range-min { + bottom: 0; +} +.ui-slider-vertical .ui-slider-range-max { + top: 0; +} +.ui-sortable-handle { + -ms-touch-action: none; + touch-action: none; +} +.ui-spinner { + position: relative; + display: inline-block; + overflow: hidden; + padding: 0; + vertical-align: middle; +} +.ui-spinner-input { + border: none; + background: none; + color: inherit; + padding: 0; + margin: 0.2em 0; + vertical-align: middle; + margin-left: 0.4em; + margin-right: 22px; +} +.ui-spinner-button { + width: 16px; + height: 50%; + font-size: 0.5em; + padding: 0; + margin: 0; + text-align: center; + position: absolute; + cursor: default; + display: block; + overflow: hidden; + right: 0; +} +/* more specificity required here to override default borders */ +.ui-spinner a.ui-spinner-button { + border-top: none; + border-bottom: none; + border-right: none; +} +/* vertically center icon */ +.ui-spinner .ui-icon { + position: absolute; + margin-top: -8px; + top: 50%; + left: 0; +} +.ui-spinner-up { + top: 0; +} +.ui-spinner-down { + bottom: 0; +} + +/* TR overrides */ +.ui-spinner .ui-icon-triangle-1-s { + /* need to fix icons sprite */ + background-position: -65px -16px; +} +.ui-tabs { + position: relative; /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ + padding: 0.2em; +} +.ui-tabs .ui-tabs-nav { + margin: 0; + padding: 0.2em 0.2em 0; +} +.ui-tabs .ui-tabs-nav li { + list-style: none; + float: left; + position: relative; + top: 0; + margin: 1px 0.2em 0 0; + border-bottom-width: 0; + padding: 0; + white-space: nowrap; +} +.ui-tabs .ui-tabs-nav .ui-tabs-anchor { + float: left; + padding: 0.5em 1em; + text-decoration: none; +} +.ui-tabs .ui-tabs-nav li.ui-tabs-active { + margin-bottom: -1px; + padding-bottom: 1px; +} +.ui-tabs .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor, +.ui-tabs .ui-tabs-nav li.ui-state-disabled .ui-tabs-anchor, +.ui-tabs .ui-tabs-nav li.ui-tabs-loading .ui-tabs-anchor { + cursor: text; +} +.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor { + cursor: pointer; +} +.ui-tabs .ui-tabs-panel { + display: block; + border-width: 0; + padding: 1em 1.4em; + background: none; +} +.ui-tooltip { + padding: 8px; + position: absolute; + z-index: 9999; + max-width: 300px; + -webkit-box-shadow: 0 0 5px #aaa; + box-shadow: 0 0 5px #aaa; +} +body .ui-tooltip { + border-width: 2px; +} + +/* Component containers +----------------------------------*/ +.ui-widget { + font-family: Verdana, Arial, sans-serif; + font-size: 1.1em; +} +.ui-widget .ui-widget { + font-size: 1em; +} +.ui-widget input, +.ui-widget select, +.ui-widget textarea, +.ui-widget button { + font-family: Verdana, Arial, sans-serif; + font-size: 1em; +} +.ui-widget-content { + border: 1px solid #aaaaaa; + color: #222222; +} +.ui-widget-content a { + color: #222222; +} +.ui-widget-header { + border: 1px solid #aaaaaa; + color: #222222; + font-weight: bold; +} +.ui-widget-header a { + color: #222222; +} + +/* Interaction states +----------------------------------*/ +.ui-state-default, +.ui-widget-content .ui-state-default, +.ui-widget-header .ui-state-default { + border: 1px solid #d3d3d3; + font-weight: normal; + color: #555555; +} +.ui-state-default a, +.ui-state-default a:link, +.ui-state-default a:visited { + color: #555555; + text-decoration: none; +} +.ui-state-hover, +.ui-widget-content .ui-state-hover, +.ui-widget-header .ui-state-hover, +.ui-state-focus, +.ui-widget-content .ui-state-focus, +.ui-widget-header .ui-state-focus { + border: 1px solid #999999; + font-weight: normal; + color: #212121; +} +.ui-state-hover a, +.ui-state-hover a:hover, +.ui-state-hover a:link, +.ui-state-hover a:visited, +.ui-state-focus a, +.ui-state-focus a:hover, +.ui-state-focus a:link, +.ui-state-focus a:visited { + color: #212121; + text-decoration: none; +} +.ui-state-active, +.ui-widget-content .ui-state-active, +.ui-widget-header .ui-state-active { + border: 1px solid #aaaaaa; + font-weight: normal; + color: #212121; +} +.ui-state-active a, +.ui-state-active a:link, +.ui-state-active a:visited { + color: #212121; + text-decoration: none; +} + +/* Interaction Cues +----------------------------------*/ +.ui-state-highlight, +.ui-widget-content .ui-state-highlight, +.ui-widget-header .ui-state-highlight { + border: 1px solid #fcefa1; + color: #363636; +} +.ui-state-highlight a, +.ui-widget-content .ui-state-highlight a, +.ui-widget-header .ui-state-highlight a { + color: #363636; +} +.ui-state-error, +.ui-widget-content .ui-state-error, +.ui-widget-header .ui-state-error { + border: 1px solid #cd0a0a; + color: #cd0a0a; +} +.ui-state-error a, +.ui-widget-content .ui-state-error a, +.ui-widget-header .ui-state-error a { + color: #cd0a0a; +} +.ui-state-error-text, +.ui-widget-content .ui-state-error-text, +.ui-widget-header .ui-state-error-text { + color: #cd0a0a; +} +.ui-priority-primary, +.ui-widget-content .ui-priority-primary, +.ui-widget-header .ui-priority-primary { + font-weight: bold; +} +.ui-priority-secondary, +.ui-widget-content .ui-priority-secondary, +.ui-widget-header .ui-priority-secondary { + opacity: 0.7; + filter: Alpha(Opacity=70); + font-weight: normal; +} +.ui-state-disabled, +.ui-widget-content .ui-state-disabled, +.ui-widget-header .ui-state-disabled { + opacity: 0.35; + filter: Alpha(Opacity=35); + background-image: none; +} +.ui-state-disabled .ui-icon { + filter: Alpha(Opacity=35); /* For IE8 - See #6059 */ +} + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { + width: 16px; + height: 16px; +} + +/* positioning */ +.ui-icon-blank { + background-position: 16px 16px; +} +.ui-icon-carat-1-n { + background-position: 0 0; +} +.ui-icon-carat-1-ne { + background-position: -16px 0; +} +.ui-icon-carat-1-e { + background-position: -32px 0; +} +.ui-icon-carat-1-se { + background-position: -48px 0; +} +.ui-icon-carat-1-s { + background-position: -64px 0; +} +.ui-icon-carat-1-sw { + background-position: -80px 0; +} +.ui-icon-carat-1-w { + background-position: -96px 0; +} +.ui-icon-carat-1-nw { + background-position: -112px 0; +} +.ui-icon-carat-2-n-s { + background-position: -128px 0; +} +.ui-icon-carat-2-e-w { + background-position: -144px 0; +} +.ui-icon-triangle-1-n { + background-position: 0 -16px; +} +.ui-icon-triangle-1-ne { + background-position: -16px -16px; +} +.ui-icon-triangle-1-e { + background-position: -32px -16px; +} +.ui-icon-triangle-1-se { + background-position: -48px -16px; +} +.ui-icon-triangle-1-s { + background-position: -64px -16px; +} +.ui-icon-triangle-1-sw { + background-position: -80px -16px; +} +.ui-icon-triangle-1-w { + background-position: -96px -16px; +} +.ui-icon-triangle-1-nw { + background-position: -112px -16px; +} +.ui-icon-triangle-2-n-s { + background-position: -128px -16px; +} +.ui-icon-triangle-2-e-w { + background-position: -144px -16px; +} +.ui-icon-arrow-1-n { + background-position: 0 -32px; +} +.ui-icon-arrow-1-ne { + background-position: -16px -32px; +} +.ui-icon-arrow-1-e { + background-position: -32px -32px; +} +.ui-icon-arrow-1-se { + background-position: -48px -32px; +} +.ui-icon-arrow-1-s { + background-position: -64px -32px; +} +.ui-icon-arrow-1-sw { + background-position: -80px -32px; +} +.ui-icon-arrow-1-w { + background-position: -96px -32px; +} +.ui-icon-arrow-1-nw { + background-position: -112px -32px; +} +.ui-icon-arrow-2-n-s { + background-position: -128px -32px; +} +.ui-icon-arrow-2-ne-sw { + background-position: -144px -32px; +} +.ui-icon-arrow-2-e-w { + background-position: -160px -32px; +} +.ui-icon-arrow-2-se-nw { + background-position: -176px -32px; +} +.ui-icon-arrowstop-1-n { + background-position: -192px -32px; +} +.ui-icon-arrowstop-1-e { + background-position: -208px -32px; +} +.ui-icon-arrowstop-1-s { + background-position: -224px -32px; +} +.ui-icon-arrowstop-1-w { + background-position: -240px -32px; +} +.ui-icon-arrowthick-1-n { + background-position: 0 -48px; +} +.ui-icon-arrowthick-1-ne { + background-position: -16px -48px; +} +.ui-icon-arrowthick-1-e { + background-position: -32px -48px; +} +.ui-icon-arrowthick-1-se { + background-position: -48px -48px; +} +.ui-icon-arrowthick-1-s { + background-position: -64px -48px; +} +.ui-icon-arrowthick-1-sw { + background-position: -80px -48px; +} +.ui-icon-arrowthick-1-w { + background-position: -96px -48px; +} +.ui-icon-arrowthick-1-nw { + background-position: -112px -48px; +} +.ui-icon-arrowthick-2-n-s { + background-position: -128px -48px; +} +.ui-icon-arrowthick-2-ne-sw { + background-position: -144px -48px; +} +.ui-icon-arrowthick-2-e-w { + background-position: -160px -48px; +} +.ui-icon-arrowthick-2-se-nw { + background-position: -176px -48px; +} +.ui-icon-arrowthickstop-1-n { + background-position: -192px -48px; +} +.ui-icon-arrowthickstop-1-e { + background-position: -208px -48px; +} +.ui-icon-arrowthickstop-1-s { + background-position: -224px -48px; +} +.ui-icon-arrowthickstop-1-w { + background-position: -240px -48px; +} +.ui-icon-arrowreturnthick-1-w { + background-position: 0 -64px; +} +.ui-icon-arrowreturnthick-1-n { + background-position: -16px -64px; +} +.ui-icon-arrowreturnthick-1-e { + background-position: -32px -64px; +} +.ui-icon-arrowreturnthick-1-s { + background-position: -48px -64px; +} +.ui-icon-arrowreturn-1-w { + background-position: -64px -64px; +} +.ui-icon-arrowreturn-1-n { + background-position: -80px -64px; +} +.ui-icon-arrowreturn-1-e { + background-position: -96px -64px; +} +.ui-icon-arrowreturn-1-s { + background-position: -112px -64px; +} +.ui-icon-arrowrefresh-1-w { + background-position: -128px -64px; +} +.ui-icon-arrowrefresh-1-n { + background-position: -144px -64px; +} +.ui-icon-arrowrefresh-1-e { + background-position: -160px -64px; +} +.ui-icon-arrowrefresh-1-s { + background-position: -176px -64px; +} +.ui-icon-arrow-4 { + background-position: 0 -80px; +} +.ui-icon-arrow-4-diag { + background-position: -16px -80px; +} +.ui-icon-extlink { + background-position: -32px -80px; +} +.ui-icon-newwin { + background-position: -48px -80px; +} +.ui-icon-refresh { + background-position: -64px -80px; +} +.ui-icon-shuffle { + background-position: -80px -80px; +} +.ui-icon-transfer-e-w { + background-position: -96px -80px; +} +.ui-icon-transferthick-e-w { + background-position: -112px -80px; +} +.ui-icon-folder-collapsed { + background-position: 0 -96px; +} +.ui-icon-folder-open { + background-position: -16px -96px; +} +.ui-icon-document { + background-position: -32px -96px; +} +.ui-icon-document-b { + background-position: -48px -96px; +} +.ui-icon-note { + background-position: -64px -96px; +} +.ui-icon-mail-closed { + background-position: -80px -96px; +} +.ui-icon-mail-open { + background-position: -96px -96px; +} +.ui-icon-suitcase { + background-position: -112px -96px; +} +.ui-icon-comment { + background-position: -128px -96px; +} +.ui-icon-person { + background-position: -144px -96px; +} +.ui-icon-print { + background-position: -160px -96px; +} +.ui-icon-trash { + background-position: -176px -96px; +} +.ui-icon-locked { + background-position: -192px -96px; +} +.ui-icon-unlocked { + background-position: -208px -96px; +} +.ui-icon-bookmark { + background-position: -224px -96px; +} +.ui-icon-tag { + background-position: -240px -96px; +} +.ui-icon-home { + background-position: 0 -112px; +} +.ui-icon-flag { + background-position: -16px -112px; +} +.ui-icon-calendar { + background-position: -32px -112px; +} +.ui-icon-cart { + background-position: -48px -112px; +} +.ui-icon-pencil { + background-position: -64px -112px; +} +.ui-icon-clock { + background-position: -80px -112px; +} +.ui-icon-disk { + background-position: -96px -112px; +} +.ui-icon-calculator { + background-position: -112px -112px; +} +.ui-icon-zoomin { + background-position: -128px -112px; +} +.ui-icon-zoomout { + background-position: -144px -112px; +} +.ui-icon-search { + background-position: -160px -112px; +} +.ui-icon-wrench { + background-position: -176px -112px; +} +.ui-icon-gear { + background-position: -192px -112px; +} +.ui-icon-heart { + background-position: -208px -112px; +} +.ui-icon-star { + background-position: -224px -112px; +} +.ui-icon-link { + background-position: -240px -112px; +} +.ui-icon-cancel { + background-position: 0 -128px; +} +.ui-icon-plus { + background-position: -16px -128px; +} +.ui-icon-plusthick { + background-position: -32px -128px; +} +.ui-icon-minus { + background-position: -48px -128px; +} +.ui-icon-minusthick { + background-position: -64px -128px; +} +.ui-icon-close { + background-position: -80px -128px; +} +.ui-icon-closethick { + background-position: -96px -128px; +} +.ui-icon-key { + background-position: -112px -128px; +} +.ui-icon-lightbulb { + background-position: -128px -128px; +} +.ui-icon-scissors { + background-position: -144px -128px; +} +.ui-icon-clipboard { + background-position: -160px -128px; +} +.ui-icon-copy { + background-position: -176px -128px; +} +.ui-icon-contact { + background-position: -192px -128px; +} +.ui-icon-image { + background-position: -208px -128px; +} +.ui-icon-video { + background-position: -224px -128px; +} +.ui-icon-script { + background-position: -240px -128px; +} +.ui-icon-alert { + background-position: 0 -144px; +} +.ui-icon-info { + background-position: -16px -144px; +} +.ui-icon-notice { + background-position: -32px -144px; +} +.ui-icon-help { + background-position: -48px -144px; +} +.ui-icon-check { + background-position: -64px -144px; +} +.ui-icon-bullet { + background-position: -80px -144px; +} +.ui-icon-radio-on { + background-position: -96px -144px; +} +.ui-icon-radio-off { + background-position: -112px -144px; +} +.ui-icon-pin-w { + background-position: -128px -144px; +} +.ui-icon-pin-s { + background-position: -144px -144px; +} +.ui-icon-play { + background-position: 0 -160px; +} +.ui-icon-pause { + background-position: -16px -160px; +} +.ui-icon-seek-next { + background-position: -32px -160px; +} +.ui-icon-seek-prev { + background-position: -48px -160px; +} +.ui-icon-seek-end { + background-position: -64px -160px; +} +.ui-icon-seek-start { + background-position: -80px -160px; +} +/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ +.ui-icon-seek-first { + background-position: -80px -160px; +} +.ui-icon-stop { + background-position: -96px -160px; +} +.ui-icon-eject { + background-position: -112px -160px; +} +.ui-icon-volume-off { + background-position: -128px -160px; +} +.ui-icon-volume-on { + background-position: -144px -160px; +} +.ui-icon-power { + background-position: 0 -176px; +} +.ui-icon-signal-diag { + background-position: -16px -176px; +} +.ui-icon-signal { + background-position: -32px -176px; +} +.ui-icon-battery-0 { + background-position: -48px -176px; +} +.ui-icon-battery-1 { + background-position: -64px -176px; +} +.ui-icon-battery-2 { + background-position: -80px -176px; +} +.ui-icon-battery-3 { + background-position: -96px -176px; +} +.ui-icon-circle-plus { + background-position: 0 -192px; +} +.ui-icon-circle-minus { + background-position: -16px -192px; +} +.ui-icon-circle-close { + background-position: -32px -192px; +} +.ui-icon-circle-triangle-e { + background-position: -48px -192px; +} +.ui-icon-circle-triangle-s { + background-position: -64px -192px; +} +.ui-icon-circle-triangle-w { + background-position: -80px -192px; +} +.ui-icon-circle-triangle-n { + background-position: -96px -192px; +} +.ui-icon-circle-arrow-e { + background-position: -112px -192px; +} +.ui-icon-circle-arrow-s { + background-position: -128px -192px; +} +.ui-icon-circle-arrow-w { + background-position: -144px -192px; +} +.ui-icon-circle-arrow-n { + background-position: -160px -192px; +} +.ui-icon-circle-zoomin { + background-position: -176px -192px; +} +.ui-icon-circle-zoomout { + background-position: -192px -192px; +} +.ui-icon-circle-check { + background-position: -208px -192px; +} +.ui-icon-circlesmall-plus { + background-position: 0 -208px; +} +.ui-icon-circlesmall-minus { + background-position: -16px -208px; +} +.ui-icon-circlesmall-close { + background-position: -32px -208px; +} +.ui-icon-squaresmall-plus { + background-position: -48px -208px; +} +.ui-icon-squaresmall-minus { + background-position: -64px -208px; +} +.ui-icon-squaresmall-close { + background-position: -80px -208px; +} +.ui-icon-grip-dotted-vertical { + background-position: 0 -224px; +} +.ui-icon-grip-dotted-horizontal { + background-position: -16px -224px; +} +.ui-icon-grip-solid-vertical { + background-position: -32px -224px; +} +.ui-icon-grip-solid-horizontal { + background-position: -48px -224px; +} +.ui-icon-gripsmall-diagonal-se { + background-position: -64px -224px; +} +.ui-icon-grip-diagonal-se { + background-position: -80px -224px; +} + +/* Misc visuals +----------------------------------*/ + +/* Corner radius */ +.ui-corner-all, +.ui-corner-top, +.ui-corner-left, +.ui-corner-tl { + border-top-left-radius: 4px; +} +.ui-corner-all, +.ui-corner-top, +.ui-corner-right, +.ui-corner-tr { + border-top-right-radius: 4px; +} +.ui-corner-all, +.ui-corner-bottom, +.ui-corner-left, +.ui-corner-bl { + border-bottom-left-radius: 4px; +} +.ui-corner-all, +.ui-corner-bottom, +.ui-corner-right, +.ui-corner-br { + border-bottom-right-radius: 4px; +} + +/* Overlays */ +.ui-widget-overlay { + opacity: 0.3; + filter: Alpha(Opacity=30); +} +.ui-widget-shadow { + margin: -8px 0 0 -8px; + padding: 8px; + opacity: 0.3; + filter: Alpha(Opacity=30); + border-radius: 8px; +} \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/css/styles/kbn.css b/SplunkAppForWazuh/appserver/static/css/styles/kbn.css new file mode 100644 index 000000000..586fc1c22 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/css/styles/kbn.css @@ -0,0 +1,104 @@ +.euiSwitch { + position: relative; + display: inline-block; + min-height: 20px; + } + + .euiSwitch .euiSwitch__input, .euiSwitch .euiSwitch__input[disabled] { + position: absolute; + opacity: 0; + width: 100%; + height: 100%; + cursor: pointer; +} + +.euiSwitch .euiSwitch__body { + pointer-events: none; + width: 44px; + height: 20px; + background-color: #006BB4; + display: inline-block; + position: relative; + border-radius: 20px; + vertical-align: middle; +} + +.euiSwitch .euiSwitch__thumb { + -webkit-box-shadow: 0 2px 2px -1px rgba(152, 162, 179, 0.3); + box-shadow: 0 2px 2px -1px rgba(152, 162, 179, 0.3); + padding: 9px; + border: 1px solid #c9cbcd; + background: #FFF no-repeat center; + border-radius: 18px; + -webkit-transition: background-color 150ms ease-in, border-color 150ms ease-in; + transition: background-color 150ms ease-in, border-color 150ms ease-in; + position: absolute; + display: inline-block; + left: 24px; + -webkit-transition: border-color 250ms cubic-bezier(0.34, 1.61, 0.7, 1), background-color 250ms cubic-bezier(0.34, 1.61, 0.7, 1), left 250ms cubic-bezier(0.34, 1.61, 0.7, 1), -webkit-transform 250ms cubic-bezier(0.34, 1.61, 0.7, 1); + transition: border-color 250ms cubic-bezier(0.34, 1.61, 0.7, 1), background-color 250ms cubic-bezier(0.34, 1.61, 0.7, 1), left 250ms cubic-bezier(0.34, 1.61, 0.7, 1), -webkit-transform 250ms cubic-bezier(0.34, 1.61, 0.7, 1); + transition: border-color 250ms cubic-bezier(0.34, 1.61, 0.7, 1), background-color 250ms cubic-bezier(0.34, 1.61, 0.7, 1), left 250ms cubic-bezier(0.34, 1.61, 0.7, 1), transform 250ms cubic-bezier(0.34, 1.61, 0.7, 1); + transition: border-color 250ms cubic-bezier(0.34, 1.61, 0.7, 1), background-color 250ms cubic-bezier(0.34, 1.61, 0.7, 1), left 250ms cubic-bezier(0.34, 1.61, 0.7, 1), transform 250ms cubic-bezier(0.34, 1.61, 0.7, 1), -webkit-transform 250ms cubic-bezier(0.34, 1.61, 0.7, 1); +} + +.euiSwitch .euiSwitch__track { + position: absolute; + left: 0; + top: 0; + right: 0; + bottom: 0; + overflow: hidden; + border-radius: 20px; +} + +.euiSwitch .euiSwitch__icon { + position: absolute; + right: -34px; + top: 2px; + bottom: 0; + width: 42px; + height: 16px; + -webkit-transition: left 250ms cubic-bezier(0.34, 1.61, 0.7, 1), right 250ms cubic-bezier(0.34, 1.61, 0.7, 1); + transition: left 250ms cubic-bezier(0.34, 1.61, 0.7, 1), right 250ms cubic-bezier(0.34, 1.61, 0.7, 1); + fill: #2D2D2D; +} + +.euiIcon--medium { + width: 16px; + height: 16px; +} +.euiIcon { + display: inline-block; + vertical-align: middle; + fill: currentColor; +} + +.euiSwitch .euiSwitch__icon--checked { + right: auto; + left: -8px; + fill: #FFF; +} + +.euiSwitch .euiSwitch__label { + padding-left: 8px; + line-height: 20px; + font-size: 14px; + vertical-align: middle; +} + +.euiSwitch .euiSwitch__input:not(:checked):not(:disabled) ~ .euiSwitch__body { + background-color: rgba(152, 162, 179, 0.2); +} + +.euiSwitch .euiSwitch__input:not(:checked) ~ .euiSwitch__body .euiSwitch__thumb { + left: 0; +} + +.euiSwitch .euiSwitch__input:not(:checked) ~ .euiSwitch__body .euiSwitch__icon { + right: -8px; +} + +.euiSwitch .euiSwitch__input:not(:checked) ~ .euiSwitch__body .euiSwitch__icon.euiSwitch__icon--checked { + right: auto; + left: -34px; +} \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/css/styles/layout.css b/SplunkAppForWazuh/appserver/static/css/styles/layout.css index 65b7b410d..8094bfef6 100644 --- a/SplunkAppForWazuh/appserver/static/css/styles/layout.css +++ b/SplunkAppForWazuh/appserver/static/css/styles/layout.css @@ -65,6 +65,10 @@ margin-left: 7px; } +.wz-margin-left-10 { + margin-left: 10px !important; +} + .no-margin-left { margin-left: 0px; } @@ -73,6 +77,10 @@ margin-bottom: 10px; } +.wz-margin-bottom-15 { + margin-bottom: 15px; +} + .wz-margin-bottom-40 { margin-bottom: 40px; } @@ -88,6 +96,10 @@ padding-top: 0px !important; } +.wz-padding-top-2 { + padding-top: 2px !important; +} + .wz-padding-top-5 { padding-top: 5px !important; } @@ -112,9 +124,16 @@ padding-right: 8px; } +.wz-padding-right-15 { + padding-right: 15px; +} + .wz-padding-right-17 { padding-right: 17px; } +.wz-padding-right-25 { + padding-right: 25px; +} .wz-padding-metric { line-height: 16px; @@ -153,4 +172,38 @@ display: flex; flex-direction: column; flex: 1 1 100%; +} + + +/* -------------------------------------------------------------------------- */ +/* ------------------------ md-dialog stylesheet ------------------------ */ +/* -------------------------------------------------------------------------- */ + +md-dialog.modalTheme { + animation: none!important; + transition: none!important; + transform: none!important; + bottom: 0; + right: 0; + position: fixed; + width: 350px; + margin-bottom: 10px; + margin-right: 10px; +} + +.md-dialog-body{ + top: 0!important; + width: 100vw!important; +} +.md-dialog-body{ + top: 0!important; + width: 100vw!important; +} +.md-dialog-body .md-scroll-mask{ + display: none!important; +} +.md-dialog-body .md-dialog-container{ + height: 0!important; + width: 0!important; + } \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/css/styles/loader.css b/SplunkAppForWazuh/appserver/static/css/styles/loader.css index 398a0c6c9..3785b2346 100644 --- a/SplunkAppForWazuh/appserver/static/css/styles/loader.css +++ b/SplunkAppForWazuh/appserver/static/css/styles/loader.css @@ -8,6 +8,8 @@ @import "table_decorations.css"; @import "layout.css"; @import "common.css"; +@import "jquery-ui.css"; +@import "kbn.css"; @import "component.css"; @import "typography.css"; @import "height.css"; @@ -18,4 +20,5 @@ @import "../../js/directives/wz-tag-filter/wz-tag-filter.css"; @import "wz_tooltips.css"; @import "xml-editor.css"; -@import "wz-multiple-selector.css"; \ No newline at end of file +@import "wz-multiple-selector.css"; +@import "wz-add-filter-chip.css"; \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/css/styles/typography.css b/SplunkAppForWazuh/appserver/static/css/styles/typography.css index 2ba61df1c..cb34f6e3c 100644 --- a/SplunkAppForWazuh/appserver/static/css/styles/typography.css +++ b/SplunkAppForWazuh/appserver/static/css/styles/typography.css @@ -24,8 +24,8 @@ } -.wz-headline-title { - font-size: 15px; +.wz-dev-headline-title { + font-size: 17px; } /* Override font size of md-headline class */ @@ -87,14 +87,34 @@ text-overflow: ellipsis; } +.font-size-15 { + font-size: 15px; +} + +.font-size-16 { + font-size: 16px; +} + .font-size-16-pt { font-size: 16pt; } +.font-size-17 { + font-size: 17px; +} + .font-size-18 { font-size: 18px; } +.font-size-20 { + font-size: 20px; +} + +.font-size-21 { + font-size: 21px; +} + .font-size-25 { font-size: 25px; } diff --git a/SplunkAppForWazuh/appserver/static/css/styles/wazuh_decorations.css b/SplunkAppForWazuh/appserver/static/css/styles/wazuh_decorations.css index a35b61df5..43765e665 100644 --- a/SplunkAppForWazuh/appserver/static/css/styles/wazuh_decorations.css +++ b/SplunkAppForWazuh/appserver/static/css/styles/wazuh_decorations.css @@ -71,6 +71,13 @@ background-color: #0079a5 !important; } +.btn-ruleset { + width: auto !important; + height: 30px !important; + margin-left: 10px !important; + margin-top: 10px !important; +} + /* Classes for custom widths */ .wz-width-15 { @@ -119,7 +126,7 @@ } .wz-margin-left-10 { - margin-left: 10px; + margin-left: 10px !important; } .wz-margin-left-16 { @@ -163,7 +170,11 @@ } .wz-margin-bottom-10 { - margin-bottom: 10px; + margin-bottom: 10px !important; +} + +.wz-margin-top--20 { + margin-top: -20px !important; } /* Classes for custom shadows for dashboard cells */ @@ -387,24 +398,56 @@ table span.badge { background-color: white !important; padding: 10px !important; } -.wz-margin-top-20 { - margin-top: 20px; + +.wz-margin-top-4 { + margin-top: 4px !important; +} + +.wz-margin-top-5 { + margin-top: 5px !important; } .wz-margin-top-10 { - margin-top: 10px; + margin-top: 10px !important; +} + +.wz-margin-top-15 { + margin-top: 15px !important; +} + +.wz-margin-top-20 { + margin-top: 20px !important; +} + +.wz-margin-top--15{ + margin-top: -15px !important; +} + +.wz-margin-right-10 { + margin-right: 10px !important; +} + +.wz-margin-left-20 { + margin-left: 20px !important; +} + +.wz-margin-left--10 { + margin-left: -10px !important; } .wz-margin-5 { - margin: 5px; + margin: 5px !important; } .wz-margin-10 { - margin: 10px; + margin: 10px !important; } +.wz-margin-20 { + margin: 20px !important; +} .wz-padding-5 { - padding: 5px; + padding: 5px !important; } .wz-table-element-pull-left{ @@ -434,5 +477,8 @@ table span.badge { } .wz-metric-color { - background-color: #e4f2f5; + margin: 0 !important; + background-color: #ecf6fb !important; + border: 1px solid #dfeff8 !important; + box-shadow: none !important; } \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/css/styles/wz-add-filter-chip.css b/SplunkAppForWazuh/appserver/static/css/styles/wz-add-filter-chip.css new file mode 100644 index 000000000..8d5a6588e --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/css/styles/wz-add-filter-chip.css @@ -0,0 +1,40 @@ +/* -------------------------------------------------------------------------- */ +/* ------------------ Wazuh add chip filter stylesheet ---------------------- */ +/* -------------------------------------------------------------------------- */ + +.open-chips{ + position: relative; + right: 20px; + width: 0; +} + +.chips-dropdown{ + width: 200px!important; + position: absolute; + margin-left: -200px!important; + margin-top: 12px!important; +} + +.chips-dropdown .dropdown-menu{ + display: block !important; +} + +.ui-select-choices-row:hover{ + background: #f3f3f3; +} + +.ui-select-choices-row-inner { + cursor: pointer; + display: block; + padding: 3px 20px; + clear: both; + font-weight: 400; + line-height: 1.42857143; + color: #333; + white-space: nowrap; +} + +.filter-icon { + margin-top: 14px !important; + color: #00445a !important; +} \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/css/styles/xml-editor.css b/SplunkAppForWazuh/appserver/static/css/styles/xml-editor.css index e476068fa..158519120 100644 --- a/SplunkAppForWazuh/appserver/static/css/styles/xml-editor.css +++ b/SplunkAppForWazuh/appserver/static/css/styles/xml-editor.css @@ -14,10 +14,10 @@ /* ------------------ Wazuh XML file editor stylesheet ---------------------- */ /* -------------------------------------------------------------------------- */ -.wzXmlEditor{ + .wzXmlEditor{ background: #fff; width: 100%; - height: min-content; + height: inherit; top: 0; border: 1px solid #d9d9d9; -webkit-box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.1) !important; @@ -28,11 +28,36 @@ padding: 15px; } - .wzXmlEditorHeader b{ +.wzXmlEditorHeader b{ font-weight: 600; } - .wzXmlEditorBody, .wzXmlEditorBody .CodeMirror{ - height: calc('100vh - 475px'); - min-height: 300px; +.wzXmlEditorBody, .wzXmlEditorBody .CodeMirror{ + height: calc(100% - 25px); +} + +.wzXmlEditorDivContent { + width: calc(100vw - 32px); + margin-left: auto; + margin-right: 18px; +} + + +.wzXmlEditorError{ + border-bottom: inherit; +} + +.wzXmlEditorError b{ + font-weight: 600; +} + +.mdListXmlError { + padding-bottom: 25px; + padding-top: 0px; +} +.extraHeaderInfo{ + background: #ecf6fb; + border-top: 1px solid #dfeff8 !important; + color: #0079a5 !important; + padding: 12px 15px; } \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/app.js b/SplunkAppForWazuh/appserver/static/js/app.js index 94ac65fa8..d3f4a600a 100644 --- a/SplunkAppForWazuh/appserver/static/js/app.js +++ b/SplunkAppForWazuh/appserver/static/js/app.js @@ -8,7 +8,9 @@ define([ './controllers/index', './filters/index', './run/index', - './config/index' + './config/index', + 'chart', + 'angularChart' ], function(ng) { 'use strict' return ng.module('wazuhApp', [ diff --git a/SplunkAppForWazuh/appserver/static/js/config/routes/agents-states.js b/SplunkAppForWazuh/appserver/static/js/config/routes/agents-states.js index 3f2db030f..d1654900b 100644 --- a/SplunkAppForWazuh/appserver/static/js/config/routes/agents-states.js +++ b/SplunkAppForWazuh/appserver/static/js/config/routes/agents-states.js @@ -20,7 +20,7 @@ define(['../module'], function(module) { agentData: [ '$requestService', '$state', - async ($requestService, $state) => { + async $requestService => { try { const responseStatus = await $requestService.apiReq( '/cluster/status' @@ -51,9 +51,7 @@ define(['../module'], function(module) { : Promise.resolve(false), $requestService.apiReq('/agents/groups', {}) ]) - } catch (err) { - $state.go('settings.api') - } + } catch (err) {} //eslint-disable-line } ] } @@ -101,13 +99,21 @@ define(['../module'], function(module) { } } ], + isAdmin: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.isAdmin() + } catch (error) { + return false + } + } + ], extensions: [ '$currentDataService', async $currentDataService => { try { - const id = $currentDataService.getApi().id - const result = await $currentDataService.getExtensionsById(id) - return result + return await $currentDataService.getCurrentExtensions() } catch (err) { return false } @@ -173,6 +179,12 @@ define(['../module'], function(module) { $state.go('agents') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } ] } }) @@ -235,6 +247,22 @@ define(['../module'], function(module) { $state.go('agents') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } ] } }) @@ -278,6 +306,12 @@ define(['../module'], function(module) { $state.go('agents') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } ] } }) @@ -315,6 +349,12 @@ define(['../module'], function(module) { $state.go('agents') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } ] } }) @@ -352,6 +392,22 @@ define(['../module'], function(module) { $state.go('agents') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } ] } }) @@ -389,6 +445,22 @@ define(['../module'], function(module) { $state.go('agents') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } ] } }) @@ -426,6 +498,22 @@ define(['../module'], function(module) { $state.go('agents') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } ] } }) @@ -488,6 +576,12 @@ define(['../module'], function(module) { $state.go('agents') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } ] } }) @@ -525,6 +619,42 @@ define(['../module'], function(module) { $state.go('agents') } } + ], + gdprTabs: [ + '$requestService', + '$state', + async ($requestService, $state) => { + try { + const gdprTabs = [] + const data = await $requestService.httpReq( + 'GET', + '/api/gdpr?requirement=all' + ) + if (!data) return [] + for (const key in data.data) { + gdprTabs.push({ title: key, content: data.data[key] }) + } + return gdprTabs + } catch (err) { + $state.go('settings.api') + } + } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + pciExtensionEnabled: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.extensionIsEnabled('pci') + } catch (err) { + return false + } + } ] } }) @@ -562,6 +692,98 @@ define(['../module'], function(module) { $state.go('agents') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } + ] + } + }) + + // agents - configuration assessments + .state('ag-ca', { + templateUrl: + BASE_URL + + 'static/app/SplunkAppForWazuh/js/controllers/agents/configuration-assessment/agents-ca.html', + onEnter: $navigationService => { + $navigationService.storeRoute('ag-ca') + }, + controller: 'agentsConfigurationAssessmentsCtrl', + params: { id: null }, + resolve: { + agent: [ + '$requestService', + '$stateParams', + '$currentDataService', + '$state', + async ( + $requestService, + $stateParams, + $currentDataService, + $state + ) => { + try { + const id = + $stateParams.id || + $currentDataService.getCurrentAgent() || + $state.go('agents') + const result = await $requestService.apiReq(`/agents/${id}`) + return result + } catch (err) { + $state.go('agents') + } + } + ], + configAssess: [ + '$requestService', + '$stateParams', + '$currentDataService', + '$state', + async ( + $requestService, + $stateParams, + $currentDataService, + $state + ) => { + try { + const id = + $stateParams.id || + $currentDataService.getCurrentAgent() || + $state.go('agents') + const result = await $requestService.apiReq(`/sca/${id}`) + return result + } catch (err) { + $state.go('agents') + } + } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } ] } }) @@ -599,6 +821,42 @@ define(['../module'], function(module) { $state.go('agents') } } + ], + pciTabs: [ + '$requestService', + '$state', + async ($requestService, $state) => { + try { + const pciTabs = [] + const data = await $requestService.httpReq( + 'GET', + '/api/pci?requirement=all' + ) + if (!data) return [] + for (const key in data.data) { + pciTabs.push({ title: key, content: data.data[key] }) + } + return pciTabs + } catch (err) { + $state.go('settings.api') + } + } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + gdprExtensionEnabled: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.extensionIsEnabled('gdpr') + } catch (err) { + return false + } + } ] } }) @@ -636,6 +894,22 @@ define(['../module'], function(module) { $state.go('settings.api') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } ] } }) @@ -673,6 +947,73 @@ define(['../module'], function(module) { $state.go('agents') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } + ] + } + }) + // =========== Docker listener =========== // + .state('ag-docker', { + templateUrl: + BASE_URL + + 'static/app/SplunkAppForWazuh/js/controllers/agents/docker/agents-docker.html', + onEnter: $navigationService => { + $navigationService.storeRoute('ag-docker') + }, + controller: 'agentsDockerCtrl', + resolve: { + agent: [ + '$requestService', + '$stateParams', + '$currentDataService', + '$state', + async ( + $requestService, + $stateParams, + $currentDataService, + $state + ) => { + try { + const id = + $stateParams.id || + $currentDataService.getCurrentAgent() || + $state.go('agents') + const result = await $requestService.apiReq(`/agents/${id}`) + return result + } catch (err) { + $state.go('agents') + } + } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } ] } }) diff --git a/SplunkAppForWazuh/appserver/static/js/config/routes/management-states.js b/SplunkAppForWazuh/appserver/static/js/config/routes/management-states.js index f1c585e6b..dda3957c4 100644 --- a/SplunkAppForWazuh/appserver/static/js/config/routes/management-states.js +++ b/SplunkAppForWazuh/appserver/static/js/config/routes/management-states.js @@ -6,7 +6,6 @@ define(['../module'], function(module) { 'BASE_URL', function($stateProvider, BASE_URL) { $stateProvider - // Manager .state('manager', { templateUrl: @@ -81,7 +80,19 @@ define(['../module'], function(module) { $navigationService.storeRoute('mg-rules') }, controller: 'managerRulesetCtrl', - params: { filters: null } + params: { filters: null }, + resolve: { + isAdmin: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.isAdmin() + } catch (error) { + return false + } + } + ] + } }) // Manager - Ruleset/:id .state('mg-rules-id', { @@ -108,6 +119,16 @@ define(['../module'], function(module) { $state.go('settings.api') } } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } ] } }) @@ -120,9 +141,20 @@ define(['../module'], function(module) { $navigationService.storeRoute('mg-decoders') }, controller: 'managerDecodersCtrl', - params: { filters: null } + params: { filters: null }, + resolve: { + isAdmin: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.isAdmin() + } catch (error) { + return false + } + } + ] + } }) - // Manager - Decoders/:id .state('mg-decoders-id', { templateUrl: @@ -148,6 +180,84 @@ define(['../module'], function(module) { $state.go('settings.api') } } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } + ] + } + }) + + // Manager - CDB List + .state('mg-cdb', { + templateUrl: + BASE_URL + + 'static/app/SplunkAppForWazuh/js/controllers/management/cdb/manager-cdb.html', + onEnter: $navigationService => { + $navigationService.storeRoute('mg-cdb') + }, + controller: 'managerCdbCtrl', + params: { filters: null }, + resolve: { + isAdmin: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.isAdmin() + } catch (error) { + return false + } + } + ] + } + }) + + // Manager - CDB List/:id + .state('mg-cdb-id', { + templateUrl: + BASE_URL + + 'static/app/SplunkAppForWazuh/js/controllers/management/cdb/manager-cdb-id.html', + onEnter: $navigationService => { + $navigationService.storeRoute('mg-cdb') + }, + controller: 'managerCdbIdCtrl', + params: { name: null, path: null }, + resolve: { + isAdmin: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.isAdmin() + } catch (error) { + return false + } + } + ], + cdbInfo: [ + '$cdbEditor', + '$stateParams', + '$state', + async ($cdbEditor, $stateParams, $state) => { + try { + const result = await $cdbEditor.getConfiguration( + $stateParams.name, + $stateParams.path + ) + return { + file: $stateParams.name, + path: $stateParams.path, + content: result + } + } catch (error) { + $state.go('settings.api') + } + } ] } }) @@ -167,9 +277,7 @@ define(['../module'], function(module) { '$currentDataService', async $currentDataService => { try { - const id = $currentDataService.getApi().id - const result = await $currentDataService.getExtensionsById(id) - return result + return await $currentDataService.getCurrentExtensions() } catch (err) { return false } @@ -178,7 +286,7 @@ define(['../module'], function(module) { } }) - // Manager - Groups + // Manager - Configuration .state('mg-conf', { templateUrl: BASE_URL + @@ -186,7 +294,100 @@ define(['../module'], function(module) { onEnter: $navigationService => { $navigationService.storeRoute('mg-conf') }, - controller: 'configurationCtrl' + controller: 'configurationCtrl', + resolve: { + isAdmin: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.isAdmin() + } catch (error) { + return false + } + } + ], + clusterInfo: [ + '$requestService', + '$state', + async ($requestService, $state) => { + try { + const info = {} + const clusterStatus = await $requestService.apiReq( + '/cluster/status' + ) + if ( + clusterStatus.data.data.enabled === 'yes' && + clusterStatus.data.data.running === 'yes' + ) { + const nodesList = await $requestService.apiReq( + '/cluster/nodes' + ) + Object.assign(info, { + clusterEnabled: true, + nodes: nodesList + }) + } else { + Object.assign(info, { clusterEnabled: false }) + } + return info + } catch (error) { + return false + } + } + ] + } + }) + + // Manager - EditConfig + .state('mg-editConfig', { + templateUrl: + BASE_URL + + 'static/app/SplunkAppForWazuh/js/controllers/management/edition/edition.html', + onEnter: $navigationService => { + $navigationService.storeRoute('mg-editConfig') + }, + controller: 'editionCtrl', + resolve: { + isAdmin: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.isAdmin() + } catch (error) { + return false + } + } + ], + clusterInfo: [ + '$requestService', + '$state', + async ($requestService, $state) => { + try { + const info = {} + const clusterStatus = await $requestService.apiReq( + '/cluster/status' + ) + if ( + clusterStatus.data.data.enabled === 'yes' && + clusterStatus.data.data.running === 'yes' + ) { + const nodesList = await $requestService.apiReq( + '/cluster/nodes' + ) + Object.assign(info, { + clusterEnabled: true, + nodes: nodesList + }) + } else { + Object.assign(info, { clusterEnabled: false }) + } + return info + } catch (error) { + $state.go('manager') + } + } + ] + } }) // Manager - Status @@ -199,6 +400,16 @@ define(['../module'], function(module) { }, controller: 'statusCtrl', resolve: { + isAdmin: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.isAdmin() + } catch (error) { + return false + } + } + ], statusData: [ '$requestService', '$state', diff --git a/SplunkAppForWazuh/appserver/static/js/config/routes/overview-states.js b/SplunkAppForWazuh/appserver/static/js/config/routes/overview-states.js index 2e71823bb..fc00a973a 100644 --- a/SplunkAppForWazuh/appserver/static/js/config/routes/overview-states.js +++ b/SplunkAppForWazuh/appserver/static/js/config/routes/overview-states.js @@ -36,22 +36,18 @@ define(['../module'], function(module) { agentsInfo: [ '$requestService', '$state', - async ($requestService, $state) => { + async $requestService => { try { const result = await $requestService.apiReq('/agents/summary') return result - } catch (err) { - $state.go('settings.api') - } + } catch (err) {} //eslint-disable-line } ], extensions: [ '$currentDataService', async $currentDataService => { try { - const id = $currentDataService.getApi().id - const result = await $currentDataService.getExtensionsById(id) - return result + return await $currentDataService.getCurrentExtensions() } catch (err) { return false } @@ -84,6 +80,22 @@ define(['../module'], function(module) { $state.go('settings.api') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + awsExtensionEnabled: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.extensionIsEnabled('aws') + } catch (err) { + return false + } + } ] } }) @@ -95,7 +107,52 @@ define(['../module'], function(module) { onEnter: $navigationService => { $navigationService.storeRoute('ow-pm') }, - controller: 'overviewPolicyMonitoringCtrl' + controller: 'overviewPolicyMonitoringCtrl', + resolve: { + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } + ] + } + })// Overview - SCA Security Configuration Assessment + .state('ow-sca', { + templateUrl: + BASE_URL + + 'static/app/SplunkAppForWazuh/js/controllers/overview/sca/overview-sca.html', + onEnter: $navigationService => { + $navigationService.storeRoute('ow-sca') + }, + controller: 'overviewSCACtrl', + resolve: { + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } + ] + } }) // Overview - FIM .state('ow-fim', { @@ -105,9 +162,27 @@ define(['../module'], function(module) { onEnter: $navigationService => { $navigationService.storeRoute('ow-fim') }, - controller: 'overviewFimCtrl' + controller: 'overviewFimCtrl', + resolve: { + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + awsExtensionEnabled: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.extensionIsEnabled('aws') + } catch (err) { + return false + } + } + ] + } }) - // Overview - OSQUERy + // Overview - Osquery .state('ow-osquery', { templateUrl: BASE_URL + @@ -130,6 +205,22 @@ define(['../module'], function(module) { $state.go('settings.api') } } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } ] } }) @@ -141,7 +232,25 @@ define(['../module'], function(module) { onEnter: $navigationService => { $navigationService.storeRoute('ow-audit') }, - controller: 'overviewAuditCtrl' + controller: 'overviewAuditCtrl', + resolve: { + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } + ] + } }) // Overview - OpenSCAP .state('ow-os', { @@ -151,7 +260,25 @@ define(['../module'], function(module) { onEnter: $navigationService => { $navigationService.storeRoute('ow-os') }, - controller: 'overviewOpenScapCtrl' + controller: 'overviewOpenScapCtrl', + resolve: { + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } + ] + } }) // Overview - PCI-DSS .state('ow-pci', { @@ -161,7 +288,45 @@ define(['../module'], function(module) { onEnter: $navigationService => { $navigationService.storeRoute('ow-pci') }, - controller: 'overviewPciCtrl' + controller: 'overviewPciCtrl', + resolve: { + pciTabs: [ + '$requestService', + '$state', + async ($requestService, $state) => { + try { + const pciTabs = [] + const data = await $requestService.httpReq( + 'GET', + '/api/pci?requirement=all' + ) + if (!data) return [] + for (const key in data.data) { + pciTabs.push({ title: key, content: data.data[key] }) + } + return pciTabs + } catch (err) { + $state.go('settings.api') + } + } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + gdprExtensionEnabled: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.extensionIsEnabled('gdpr') + } catch (err) { + return false + } + } + ] + } }) // Overview - GDPR .state('ow-gdpr', { @@ -171,8 +336,47 @@ define(['../module'], function(module) { onEnter: $navigationService => { $navigationService.storeRoute('ow-gdpr') }, - controller: 'overviewGdprCtrl' + controller: 'overviewGdprCtrl', + resolve: { + gdprTabs: [ + '$requestService', + '$state', + async ($requestService, $state) => { + try { + const gdprTabs = [] + const data = await $requestService.httpReq( + 'GET', + '/api/gdpr?requirement=all' + ) + if (!data) return [] + for (const key in data.data) { + gdprTabs.push({ title: key, content: data.data[key] }) + } + return gdprTabs + } catch (err) { + $state.go('settings.api') + } + } + ], + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + pciExtensionEnabled: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.extensionIsEnabled('pci') + } catch (err) { + return false + } + } + ] + } }) + // Overview - Vulnerabilities .state('ow-vul', { templateUrl: @@ -181,7 +385,25 @@ define(['../module'], function(module) { onEnter: $navigationService => { $navigationService.storeRoute('ow-vul') }, - controller: 'overviewVulnerabilitiesCtrl' + controller: 'overviewVulnerabilitiesCtrl', + resolve: { + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } + ] + } }) // Overview - CIS-CAT .state('ow-ciscat', { @@ -191,7 +413,25 @@ define(['../module'], function(module) { onEnter: $navigationService => { $navigationService.storeRoute('ow-ciscat') }, - controller: 'ciscatCtrl' + controller: 'ciscatCtrl', + resolve: { + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } + ] + } }) // Overview - VirusTotal .state('ow-virustotal', { @@ -201,7 +441,25 @@ define(['../module'], function(module) { onEnter: $navigationService => { $navigationService.storeRoute('ow-virustotal') }, - controller: 'overviewVirusTotal' + controller: 'overviewVirusTotal', + resolve: { + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } + ] + } }) // =========== AWS =========== // .state('ow-aws', { @@ -211,7 +469,43 @@ define(['../module'], function(module) { onEnter: $navigationService => { $navigationService.storeRoute('ow-aws') }, - controller: 'awsCtrl' + controller: 'awsCtrl', + resolve: { + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ] + } + }) + // =========== Docker listener =========== // + .state('ow-docker', { + templateUrl: + BASE_URL + + 'static/app/SplunkAppForWazuh/js/controllers/overview/docker/overview-docker.html', + onEnter: $navigationService => { + $navigationService.storeRoute('ow-docker') + }, + controller: 'dockerCtrl', + resolve: { + reportingEnabled: [ + '$currentDataService', + async $currentDataService => { + return await $currentDataService.getReportingStatus() + } + ], + extensions: [ + '$currentDataService', + async $currentDataService => { + try { + return await $currentDataService.getCurrentExtensions() + } catch (err) { + return false + } + } + ] + } }) } ]) diff --git a/SplunkAppForWazuh/appserver/static/js/config/routes/settings-states.js b/SplunkAppForWazuh/appserver/static/js/config/routes/settings-states.js index cdf4b09ba..77eecf4d8 100644 --- a/SplunkAppForWazuh/appserver/static/js/config/routes/settings-states.js +++ b/SplunkAppForWazuh/appserver/static/js/config/routes/settings-states.js @@ -79,11 +79,7 @@ define(['../module'], function(module) { '$currentDataService', async ($state, $currentDataService) => { try { - const id = $currentDataService.getApi().id - const currentExtensions = await $currentDataService.getExtensionsById( - id - ) - return currentExtensions + return await $currentDataService.getCurrentExtensions() } catch (err) { $state.reload() } @@ -137,11 +133,7 @@ define(['../module'], function(module) { '$currentDataService', async ($state, $currentDataService) => { try { - const id = $currentDataService.getApi().id - const currentExtensions = await $currentDataService.getExtensionsById( - id - ) - return await currentExtensions + return await $currentDataService.getCurrentExtensions() } catch (err) { $state.go('settings.api') } @@ -156,7 +148,12 @@ define(['../module'], function(module) { onEnter: $navigationService => { $navigationService.storeRoute('discover') }, - params: { id: null } + controller: 'discoverCtrl', + params: { + fromDashboard: null, + previousState: null, + breadcrumbs: null + } }) } ]) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/agents/agents.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/agents/agents.html index b637f2c8e..671264b30 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/agents/agents.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/agents/agents.html @@ -1,78 +1,134 @@
-
- - - Status + +
+ +
+
+ + Status + -
-
-
-

Active

-

{{agentsCountActive}}

+
+ +
+
+ There are no agents yet. +
+
+ +
+
+
+ + Details + + +
+
+ +
+
+

Active

+
+

{{agentsCountActive}}

-
-

Disconnected

-

{{agentsCountDisconnected}}

+
+
+ +
+
+

Disconnected

+
+

{{agentsCountDisconnected}}

-
-
-

Never connected

-

{{agentsCountNeverConnected}}

+
+ +
+
+

Never connected

+
+

{{agentsCountNeverConnected}}

-
-

Agents coverage

-

{{(agentsCoverity | number:2)}}%

-

0

+
+
+ +
+
+

Agents coverage

+
+

{{(agentsCoverity | number:2)}}%

- - - - - Top - -
-

Last registered agent

- - -
-
-

Higher activity

- - +
+
+ +
+
+

Last registered agent

+
+ +

+ -

+
+
+
+ +
+
+

Most active agent

+
+ +

+ -

+
+
- - +
+ +
+
+
-
- -
- + + + +
+ +
+ + + +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/agents/agentsCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/agents/agentsCtrl.js index 28dddb78a..51d32d407 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/agents/agentsCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/agents/agentsCtrl.js @@ -14,7 +14,7 @@ define([ '../../module', '../../../services/visualizations/search/search-handler', 'FileSaver' -], function(app, SearchHandler) { +], function (app, SearchHandler) { 'use strict' class Agents { @@ -40,7 +40,8 @@ define([ $tableFilterService, agentData, $mdDialog, - $groupHandler + $groupHandler, + $dateDiffService ) { this.scope = $scope this.submittedTokenModel = $urlTokenModel.getSubmittedTokenModel() @@ -49,59 +50,66 @@ define([ this.api = this.currentDataService.getApi() this.apiReq = $requestService.apiReq this.state = $state - this.toast = $notificationService.showSimpleToast + this.notification = $notificationService this.currentClusterInfo = this.currentDataService.getClusterInfo() this.filters = this.currentDataService.getSerializedFilters() this.csvReq = $csvRequestService this.wzTableFilter = $tableFilterService this.$mdDialog = $mdDialog this.groupHandler = $groupHandler - const parsedResult = agentData.map(item => - item && item.data && item.data.data ? item.data.data : false - ) - let [ - summary, - lastAgent, - platforms, - versions, - nodes, - groups - ] = parsedResult + this.setBrowserOffset = $dateDiffService.setBrowserOffset + + try { + const parsedResult = agentData.map(item => + item && item.data && item.data.data ? item.data.data : false + ) + let [ + summary, + lastAgent, + platforms, + versions, + nodes, + groups + ] = parsedResult - this.scope.agentsCountActive = summary.Active - 1 - this.scope.lastAgent = lastAgent.items[0] ? lastAgent.items[0] : 'Unknown' - const os = platforms - ? platforms.items.map(item => item.os).filter(item => !!item) - : false - versions = versions - ? versions.items.map(item => item.version).filter(item => !!item) - : false - nodes = - nodes && nodes.items - ? nodes.items.map(item => item['node_name']).filter(item => !!item) + this.scope.agentsCountActive = summary.Active - 1 + this.scope.lastAgent = lastAgent.items[0] + ? lastAgent.items[0] + : 'Unknown' + const os = platforms + ? platforms.items.map(item => item.os).filter(item => !!item) + : false + versions = versions + ? versions.items.map(item => item.version).filter(item => !!item) + : false + nodes = + nodes && nodes.items + ? nodes.items.map(item => item['node_name']).filter(item => !!item) + : false + groups = groups + ? groups.items.map(item => item.name).filter(item => !!item) : false - groups = groups - ? groups.items.map(item => item.name).filter(item => !!item) - : false - this.scope.agentsCountDisconnected = summary.Disconnected - this.scope.agentsCountNeverConnected = summary['Never connected'] - const agentsCountTotal = summary.Total - 1 - this.scope.agentsCoverity = agentsCountTotal - ? (this.scope.agentsCountActive / agentsCountTotal) * 100 - : 0 + this.scope.agentsCountDisconnected = summary.Disconnected + this.scope.agentsCountNeverConnected = summary['Never connected'] + const agentsCountTotal = summary.Total - 1 + this.scope.agentsCoverity = agentsCountTotal + ? (this.scope.agentsCountActive / agentsCountTotal) * 100 + : 0 - this.scope.searchBarModel = { - status: ['Active', 'Disconnected', 'Never connected'], - group: groups ? groups : [], - version: versions ? versions : [], - 'os.platform': os ? os.map(x => x.platform) : [], - 'os.version': os ? os.map(x => x.version) : [], - 'os.name': os ? os.map(x => x.name) : [] - } + this.scope.searchBarModel = { + name: [], + status: ['Active', 'Disconnected', 'Never connected'], + group: groups ? groups : [], + version: versions ? versions : [], + 'os.platform': os ? os.map(x => x.platform) : [], + 'os.version': os ? os.map(x => x.version) : [], + 'os.name': os ? os.map(x => x.name) : [] + } - if (this.clusterInfo && this.clusterInfo.status === 'enabled') { - this.scope.searchBarModel.node_name = nodes || [] - } + if (this.clusterInfo && this.clusterInfo.status === 'enabled') { + this.scope.searchBarModel.node_name = nodes || [] + } + } catch (error) { } //eslint-disable-line this.topAgent = new SearchHandler( 'searchTopAgent', @@ -134,6 +142,44 @@ define([ this.scope.$on('$destroy', () => { this.topAgent.destroy() }) + this.scope.reloadList = () => this.reloadList() + + this.scope.offsetTimestamp = (text, time) => { + try { + return text + this.setBrowserOffset(time) + } catch (error) { + return '' + } + } + + this.scope.loadCharts = (id) => { + setTimeout(() => { + const chart = new Chart(document.getElementById(id), + { + type: "doughnut", + data: { + labels: ["Active", "Disconected", "Never connected"], + datasets: [ + { + backgroundColor: ['#46BFBD', '#F7464A', '#949FB1'], + data: [this.scope.agentsCountActive, this.scope.agentsCountDisconnected, this.scope.agentsCountNeverConnected], + } + ] + }, + options: { + cutoutPercentage: 85, + legend: { + display: true, + position: "right", + }, + tooltips: { + displayColors: false + } + } + }); + chart.update(); + }, 250); + } } /** @@ -141,8 +187,10 @@ define([ */ async downloadCsv() { try { - this.toast('Your download should begin automatically...') - const currentApi = this.api.id + this.notification.showSimpleToast( + 'Your download should begin automatically...' + ) + const currentApi = this.api['_key'] const output = await this.csvReq.fetch( '/agents', currentApi, @@ -152,7 +200,7 @@ define([ saveAs(blob, 'agents.csv') // eslint-disable-line return } catch (error) { - this.toast('Error downloading CSV') + this.notification.showErrorToast('Error downloading CSV') } return } @@ -181,7 +229,7 @@ define([ !agentInfo.data.data || agentInfo.data.error ) { - throw Error('Error') + throw Error('Error fetching agent data') } if (agentInfo.data.data.id !== '000') { this.state.go(`agent-overview`, { id: agentInfo.data.data.id }) @@ -190,9 +238,18 @@ define([ throw Error('Cannot fetch agent name') } } catch (err) { - this.toast(err.message || 'Error fetching agent data') + this.notification.showErrorToast( + err.message || 'Error fetching agent data' + ) } } + + /** + * Reload list of agents + */ + reloadList() { + this.scope.$broadcast('wazuhSearch', { term: '' }) + } } app.controller('agentsCtrl', Agents) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/audit/agents-audit.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/audit/agents-audit.html index 61997bb23..ba7a91363 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/audit/agents-audit.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/audit/agents-audit.html @@ -1,149 +1,142 @@ - + -
- -
+
+
Agents / - {{agent.name}} ({{agent.id}}) + {{agent.name}} ({{agent.id}}) Unknown agent / Audit -
-
- {{formatAgentStatus(agent.status)}} + + {{formatAgentStatus(agent.status)}} +
- - - -
Waiting for reporting information
+
+ + + +
-
Generating report
+
{{reportStatus}}
+ + + + Policy monitoring + + SCA + System auditing + OpenSCAP + CIS-CAT + - -
- - -
New files: - -
-
Read files: - -
-
Modified files: - -
-
Removed files: - -
-
-
-
- -
- - - Groups - -
-
-
- - - Agents - -
-
-
- - - Directories - -
-
-
- - - Files - -
-
-
-
- -
- - - Alerts over time - -
-
-
+
+
+ Fetching data...
+
+
+ +
+ + +
New files: + +
+
Read files: + +
+
Modified files: + +
+
Removed files: + +
+
+
+
-
-
- - - File read access +
+ + + Groups + + + + -
+
+
+
+ + + Commands + + + + + +
+
+
+ + + Files + + + + + +
-
- - - File write access +
+ + + Alerts over time + + + + -
+
- -
- - - Commands + +
+ + + Alerts summary + + + + -
+
-
- - - Created files - -
-
-
- - - Removed files - -
-
-
-
-
- - - Alerts summary - -
-
-
-
- \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/audit/agentsAuditCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/audit/agentsAuditCtrl.js index 24689d6fb..4840e6eb7 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/audit/agentsAuditCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/audit/agentsAuditCtrl.js @@ -29,7 +29,7 @@ define([ Table, TimePicker, SearchHandler, - rawTableDataService + RawTableDataService ) { 'use strict' @@ -50,11 +50,15 @@ define([ $currentDataService, $state, agent, - $reportingService + $reportingService, + reportingEnabled, + extensions ) { this.state = $state this.currentDataService = $currentDataService this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions this.reportingService = $reportingService this.tableResults = {} this.urlTokenModel = $urlTokenModel @@ -65,8 +69,23 @@ define([ this.submittedTokenModel = this.urlTokenModel.getSubmittedTokenModel() this.agent = agent this.currentDataService.addFilter( - `{"rule.groups":"audit", "implicit":true}` + `{"rule.groups{}":"audit", "implicit":true}` ) + this.scope.expandArray = [ + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false + ] + this.scope.expand = (i, id) => this.expand(i, id) + if ( this.agent && this.agent.data && @@ -77,11 +96,12 @@ define([ `{"agent.id":"${this.agent.data.data.id}", "implicit":true}` ) this.filters = this.currentDataService.getSerializedFilters() - this.scope.$on('deletedFilter', () => { + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) @@ -130,22 +150,16 @@ define([ */ new PieChart( 'groupsVizz', - `${this.filters} sourcetype=wazuh | top rule.groups`, + `${this.filters} sourcetype=wazuh | top rule.groups{}`, 'groupsVizz', this.scope ), - new ColumnChart( - 'agentsVizz', - `${this.filters} sourcetype=wazuh agent.name=* | top agent.name`, - 'agentsVizz', - this.scope - ), new PieChart( - 'directoriesVizz', + 'commandsVizz', `${ this.filters - } sourcetype=wazuh audit.directory.name=* | top audit.directory.name`, - 'directoriesVizz', + } sourcetype=wazuh | top limit=5 data.audit.command`, + 'commandsVizz', this.scope ), new PieChart( @@ -164,44 +178,6 @@ define([ 'alertsOverTimeVizz', this.scope ), - new PieChart( - 'fileReadAccessVizz', - `${ - this.filters - } sourcetype=wazuh rule.id=80784 | top audit.file.name`, - 'fileReadAccessVizz', - this.scope - ), - new PieChart( - 'fileWriteAccessVizz', - `${ - this.filters - } sourcetype=wazuh rule.id=80781 | top audit.file.name`, - 'fileWriteAccessVizz', - this.scope - ), - new BarChart( - 'comandsVizz', - `${this.filters} sourcetype=wazuh | top audit.command`, - 'comandsVizz', - this.scope - ), - new BarChart( - 'createdVizz', - `${ - this.filters - } sourcetype=wazuh rule.id=80790 | top audit.file.name`, - 'createdVizz', - this.scope - ), - new PieChart( - 'removedFilesVizz', - `${ - this.filters - } sourcetype=wazuh rule.id=80791 | top audit.file.name`, - 'removedFilesVizz', - this.scope - ), new Table( 'alertsSummaryVizz', `${ @@ -209,24 +185,19 @@ define([ } sourcetype=wazuh | stats count sparkline by agent.name,rule.description, audit.exe, audit.type, audit.euid | sort count DESC | rename agent.name as "Agent name", rule.description as Description, audit.exe as Command, audit.type as Type, audit.euid as "Effective user id"`, 'alertsSummaryVizz', this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh | stats count sparkline by agent.name,rule.description, audit.exe, audit.type, audit.euid | sort count DESC | rename agent.name as "Agent name", rule.description as Description, audit.exe as Command, audit.type as Type, audit.euid as "Effective user id"`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' ) ] - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } sourcetype=wazuh | stats count sparkline by agent.name,rule.description, audit.exe, audit.type, audit.euid | sort count DESC | rename agent.name as "Agent name", rule.description as Description, audit.exe as Command, audit.type as Type, audit.euid as "Effective user id"`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) - - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) - // Set agent info try { this.agentReportData = { @@ -254,15 +225,9 @@ define([ this.filters, [ 'groupsVizz', - 'agentsVizz', - 'directoriesVizz', + 'commandsVizz', 'filesVizz', 'alertsOverTimeVizz', - 'fileReadAccessVizz', - 'fileWriteAccessVizz', - 'comandsVizz', - 'createdVizz', - 'removedFilesVizz', 'alertsSummaryVizz' ], this.reportMetrics, @@ -282,6 +247,11 @@ define([ this.scope.loadingVizz = false this.setReportMetrics() } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) this.scope.loadingVizz = true } if (!this.scope.$$phase) this.scope.$digest() @@ -300,6 +270,7 @@ define([ * On controller loads */ $onInit() { + this.scope.loadingVizz = true this.scope.agent = this.agent && this.agent.data && this.agent.data.data ? this.agent.data.data @@ -347,6 +318,29 @@ define([ 'Removed files': this.scope.filesDeleted } } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('agentsAuditCtrl', AgentsAudit) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/ciscat/agents-ciscat.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/ciscat/agents-ciscat.html index 5397a18c2..d35ddd828 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/ciscat/agents-ciscat.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/ciscat/agents-ciscat.html @@ -1,105 +1,144 @@ - -
- -
+ +
+
Agents / - {{agent.name}} ({{agent.id}}) + {{agent.name}} ({{agent.id}}) Unknown agent / CIS-CAT -
-
- {{formatAgentStatus(agent.status)}} + + {{formatAgentStatus(agent.status)}} +
- - - -
Waiting for reporting information
+
+ + + +
-
Generating report
+
{{reportStatus}}
+ + + + Policy monitoring + + SCA + System auditing + OpenSCAP + CIS-CAT + - - - -
- - -
Last not checked: - -
-
Last pass: - -
-
Last scan score: - -
-
Last scan date: - -
-
-
-
-
- - -
Last errors: - -
-
Last fails: - -
-
Last unknown: - -
-
Last scan benchmark: - -
-
-
+ +
+
+ Fetching data...
+
- -
-
- - - Top 5 CIS-CAT groups - -
+
+ + + +
+ + +
Last not checked: + +
+
Last pass: + +
+
Last scan score: + +
+
Last scan date: + +
- -
- - - Scan result evolution - -
+
+ + +
Last errors: + +
+
Last fails: + +
+
Last unknown: + +
+
Last scan benchmark: + +
- -
- -
-
- - - Alerts summary - -
-
-
+ +
+
+ + + Top 5 CIS-CAT groups + + + + + +
+
+
+
+ +
+ + + Scan result evolution + + + + + +
+
+
+
+
+ +
+
+ + + Alerts summary + + + + + +
+
+
+
- \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/ciscat/agentsCiscatCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/ciscat/agentsCiscatCtrl.js index 3fd3e7002..bc4a2f685 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/ciscat/agentsCiscatCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/ciscat/agentsCiscatCtrl.js @@ -13,7 +13,7 @@ define([ Table, TimePicker, SearchHandler, - rawTableDataService + RawTableDataService ) { 'use strict' @@ -33,16 +33,23 @@ define([ $state, $currentDataService, agent, - $reportingService + $reportingService, + reportingEnabled, + extensions ) { this.state = $state this.currentDataService = $currentDataService + this.currentDataService.addFilter( + `{"rule.groups{}":"ciscat", "implicit":true, "onlyShow":true}` + ) this.reportingService = $reportingService this.tableResults = {} if (!this.currentDataService.getCurrentAgent()) { this.state.go('overview') } this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions this.urlTokenModel = $urlTokenModel this.timePicker = new TimePicker( '#timePicker', @@ -50,6 +57,10 @@ define([ ) this.submittedTokenModel = this.urlTokenModel.getSubmittedTokenModel() this.agent = agent + + this.scope.expandArray = [false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + if ( this.agent && this.agent.data && @@ -145,7 +156,7 @@ define([ `lastScanBenchmark`, `${ this.filters - } rule.groups=ciscat | search data.cis.benchmark=* | table data.cis.benchmark | head 1`, + } rule.groups{}=ciscat | search data.cis.benchmark=* | table data.cis.benchmark | head 1`, 'lastScanBenchmark', '$result.data.cis.benchmark$', 'lastScanBenchmark', @@ -159,7 +170,7 @@ define([ 'topCiscatGroups', `${ this.filters - } sourcetype=wazuh rule.groups="ciscat" | top data.cis.group`, + } sourcetype=wazuh rule.groups{}="ciscat" | top data.cis.group`, 'topCiscatGroups', this.scope ), @@ -167,7 +178,7 @@ define([ 'scanResultEvolution', `${ this.filters - } sourcetype=wazuh rule.groups="ciscat" | timechart count by data.cis.result usenull=f`, + } sourcetype=wazuh rule.groups{}="ciscat" | timechart count by data.cis.result usenull=f`, 'scanResultEvolution', this.scope ), @@ -175,27 +186,22 @@ define([ 'alertsSummary', `${ this.filters - } sourcetype=wazuh rule.groups="ciscat" | stats count sparkline by data.cis.rule_title, data.cis.remediation,data.cis.group | sort count desc | rename "data.cis.rule_title" as "Title", "data.cis.remediation" as "Remediation", "data.cis.group" as "Group" `, + } sourcetype=wazuh rule.groups{}="ciscat" | stats count sparkline by data.cis.rule_title, data.cis.remediation,data.cis.group | sort count desc | rename "data.cis.rule_title" as "Title", "data.cis.remediation" as "Remediation", "data.cis.group" as "Group" `, 'alertsSummary', this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh rule.groups{}="ciscat" | stats count sparkline by data.cis.rule_title, data.cis.remediation,data.cis.group | sort count desc | rename "data.cis.rule_title" as "Title", "data.cis.remediation" as "Remediation", "data.cis.group" as "Group" `, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' ) ] - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } sourcetype=wazuh rule.groups="ciscat" | stats count sparkline by data.cis.rule_title, data.cis.remediation,data.cis.group | sort count desc | rename "data.cis.rule_title" as "Title", "data.cis.remediation" as "Remediation", "data.cis.group" as "Group" `, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) - - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) - // Set agent info try { this.agentReportData = { @@ -239,6 +245,11 @@ define([ this.scope.loadingVizz = false this.setReportMetrics() } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) this.scope.loadingVizz = true } if (!this.scope.$$phase) this.scope.$digest() @@ -249,6 +260,7 @@ define([ * On controller loads */ $onInit() { + this.scope.loadingVizz = true this.scope.agent = this.agent && this.agent.data && this.agent.data.data ? this.agent.data.data @@ -257,11 +269,13 @@ define([ this.formatAgentStatus(agentStatus) this.scope.getAgentStatusClass = agentStatus => this.getAgentStatusClass(agentStatus) - this.scope.$on('deletedFilter', () => { + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) @@ -305,6 +319,29 @@ define([ } } + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } + /** * Gets the filters and launches the search */ diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/configuration-assessment/agents-ca.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/configuration-assessment/agents-ca.html new file mode 100644 index 000000000..07da66dc0 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/configuration-assessment/agents-ca.html @@ -0,0 +1,190 @@ + + +
+ +
+ Agents + / + {{agent.name}} + ({{agent.id}}) + Unknown agent + / + Configuration assessment + + {{formatAgentStatus(agent.status)}} + +
+
+ +
+ Waiting for reporting information + + +
+
+
+ + +
{{reportStatus}}
+ + + + Policy monitoring + + SCA + System auditing + OpenSCAP + CIS-CAT + + + +
+
+
+
+ {{policy.name}} + + +
+
+
+ +
+
+
+ + This agent is never connected. +
+
+
+ +
+ + + Configuration assessment + + + + + + + + + + + + + + + + + + + + + + +
PolicyDescriptionLast scanPassFailNot applicableScore
{{policy.description}}{{policy.end_scan}}{{policy.pass}}{{policy.fail}}{{policy.invalid}}{{policy.score}}%
+
+
+
+ +
+ + + + + No scans available. + + + + + +
+
+ + +
+ +
+
+
+ + This agent is never connected. +
+
+
+ +
+ + + + + + Back to Configuration assessment + + + {{policy.name}}  + + Pass: {{policy.pass}}   + Failed: {{policy.fail}}   + Not applicable: {{policy.invalid}}   + Score: {{policy.score}}%   + + + + Policy checksum: {{policy.hash_file}} +
+
+ +
+ +
+ + + +
+
+
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/configuration-assessment/agentsConfigurationAssessmentsCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/configuration-assessment/agentsConfigurationAssessmentsCtrl.js new file mode 100644 index 000000000..faa5753ea --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/configuration-assessment/agentsConfigurationAssessmentsCtrl.js @@ -0,0 +1,323 @@ +/* + * Wazuh app - Agents controller + * Copyright (C) 2015-2019 Wazuh, Inc. + * + * This program is free software you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation either version 2 of the License, or + * (at your option) any later version. + * + * Find more information about this on the LICENSE file. + */ + +define([ + '../../module', + '../../../services/visualizations/chart/pie-chart', + '../../../services/visualizations/inputs/time-picker' +], function (app, PieChart, TimePicker) { + 'use strict' + + class AgentsCA { + /** + * Class Agents Policy-Monitoring + * @param {Object} $urlTokenModel + * @param {Object} $scope + * @param {Object} $state + * @param {Object} $currentDataService + * @param {Object} agent + * @param {*} $reportingService + * @param {*} $requestService + * @param {*} $notificationService + * @param {*} $csvRequestService + */ + + constructor( + $urlTokenModel, + $rootScope, + $scope, + $state, + $currentDataService, + agent, + configAssess, + $requestService, + $notificationService, + $csvRequestService, + $tableFilterService, + reportingEnabled, + BASE_URL, + extensions, + $dateDiffService + ) { + this.urlTokenModel = $urlTokenModel + this.rootScope = $rootScope + this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions + this.apiReq = $requestService.apiReq + this.state = $state + this.tableResults = {} + this.currentDataService = $currentDataService + this.agent = agent + this.configAssess = configAssess + this.notification = $notificationService + this.api = $currentDataService.getApi() + this.setBrowserOffset = $dateDiffService.setBrowserOffset + this.csvReq = $csvRequestService + + this.scope.offsetTimestamp = (text, time) => { + try { + return text + this.setBrowserOffset(time) + } catch (error) { + return '' + } + } + + this.wzTableFilter = $tableFilterService + this.baseUrl = BASE_URL + this.scope.noScansPng = `${ + this.baseUrl + }/static/app/SplunkAppForWazuh/css/images/sca_no_scans.png` + this.currentDataService.addFilter( + `{"rule.groups{}":"sca", "implicit":true}` + ) + this.scope.expandArray = [false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + + if ( + this.agent && + this.agent.data && + this.agent.data.data && + this.agent.data.data.id + ) + this.currentDataService.addFilter( + `{"agent.id":"${this.agent.data.data.id}", "implicit":true}` + ) + + if ( + this.configAssess && + this.configAssess.data && + this.configAssess.data.data && + this.configAssess.data.data.items && + this.configAssess.data.error === 0 + ) { + this.configAssess = this.configAssess.data.data.items + this.scope.configAssess = this.configAssess + } + + this.filters = this.currentDataService.getSerializedFilters() + this.timePicker = new TimePicker( + '#timePicker', + this.urlTokenModel.handleValueChange + ) + + this.scope.$on('deletedFilter', event => { + event.stopPropagation() + this.launchSearches() + }) + + this.scope.$on('barFilter', event => { + event.stopPropagation() + this.launchSearches() + }) + + + this.vizz = [ + /** + * Visualizations + */ + new PieChart( + 'resultDistribution', + `${ + this.filters + } rule.groups{}="sca" | stats count by data.sca.policy,data.sca.check.result `, + 'resultDistribution', + this.scope, + { 'trellisEnabled': true } + ) + ] + + /** + * Generates report + */ + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'agents-ca', + 'Configuration assessment', + this.filters, + [ + 'resultDistribution' + ], + {}, //Metrics, + this.tableResults, + this.agentReportData + ) + + /** + * When controller is destroyed + */ + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) + } + + $onInit() { + this.scope.searchRootcheck = (term, specificFilter) => + this.scope.$broadcast('wazuhSearch', { term, specificFilter }) + this.scope.downloadCsv = () => this.downloadCsv() + + this.scope.switchVisualizations = () => this.switchVisualizations() + this.scope.loadPolicyChecks = (id, name) => + this.loadPolicyChecks(id, name) + this.scope.backToConfAssess = () => this.backToConfAssess() + + this.scope.agent = + this.agent && this.agent.data && this.agent.data.data + ? this.agent.data.data + : { error: true } + this.scope.getAgentStatusClass = agentStatus => + this.getAgentStatusClass(agentStatus) + this.scope.formatAgentStatus = agentStatus => + this.formatAgentStatus(agentStatus) + + this.scope.refreshScans = () => this.refreshScans() + this.scope.search = term => this.search(term) + + + this.scope.loadCharts = (policy) => { + setTimeout(function () { + const chart = new Chart(document.getElementById(policy.policy_id), + { + type: "doughnut", + data: { + labels: ["pass", "fail", "not applicable"], + datasets: [ + { + backgroundColor: ['#46BFBD', '#F7464A', '#949FB1'], + data: [policy.pass, policy.fail, policy.invalid], + } + ] + }, + options: { + cutoutPercentage: 85, + legend: { + display: true, + position: "right", + }, + tooltips: { + displayColors: false + } + } + }); + chart.update(); + }, 250); + } + } + + /** + * Returns a class depending of the agent state + * @param {String} agentStatus + */ + getAgentStatusClass(agentStatus) { + return agentStatus === 'Active' ? 'teal' : 'red' + } + + /** + * Checks and returns agent status + * @param {Array} agentStatus + */ + formatAgentStatus(agentStatus) { + return ['Active', 'Disconnected'].includes(agentStatus) + ? agentStatus + : 'Never connected' + } + + /** + * Searches for a term + * @param {String} term + */ + search(term) { + this.scope.$broadcast('wazuhSearch', { term }) + } + + /** + * Exports the table in CSV format + */ + async downloadCsv() { + try { + this.notification.showSimpleToast( + 'Your download should begin automatically...' + ) + const currentApi = this.api.id + const output = await this.csvReq.fetch( + '/agents', + currentApi, + this.wzTableFilter.get() + ) + const blob = new Blob([output], { type: 'text/csv' }) // eslint-disable-line + saveAs(blob, 'agents.csv') // eslint-disable-line + return + } catch (error) { + this.notification.showErrorToast('Error downloading CSV') + } + return + } + + /** + * Gets filters and launches search + */ + launchSearches() { + this.filters = this.currentDataService.getSerializedFilters() + this.state.reload() + } + + /** + * Loads policies checks + */ + async loadPolicyChecks(policy) { + this.scope.showPolicyChecks = true + this.scope.policy = policy + const agentId = this.agent.data.data.id + this.scope.wzTablePath = `/sca/${agentId}/checks/${policy.policy_id}` + } + + /** + * + * Backs to config assessment + */ + backToConfAssess() { + this.scope.showPolicyChecks = false + } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '280px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '280px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } + + /** + * Refresh SCA scans + */ + refreshScans() { + this.state.reload() + } + } + app.controller('agentsConfigurationAssessmentsCtrl', AgentsCA) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/configuration/agentConfigCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/configuration/agentConfigCtrl.js index 49c41898e..165cd4ac5 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/configuration/agentConfigCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/configuration/agentConfigCtrl.js @@ -67,6 +67,9 @@ define(['../../module', '../../../utils/config-handler'], function( * On controller loads */ $onInit() { + this.$scope.showingInfo = false + this.$scope.showInfo = () => this.showInfo() + this.$scope.goToEdition = false this.$scope.agent = this.agent && this.agent.data && this.agent.data.data ? this.agent.data.data @@ -96,15 +99,21 @@ define(['../../module', '../../../utils/config-handler'], function( configurationTab, sections, this.$scope, - this.id + this.id, // Send the agent id + false // Send node as false ) this.$scope.switchWodle = wodleName => this.configurationHandler.switchWodle(wodleName, this.$scope, this.id) - this.$scope.switchConfigurationTab = configurationTab => + this.$scope.switchConfigurationTab = async configurationTab => { + if (configurationTab === 'welcome') { + this.$scope.isSynchronized = await this.checkAgentSync() + } this.configurationHandler.switchConfigurationTab( configurationTab, this.$scope ) + } + this.$scope.switchConfigurationSubTab = configurationSubTab => this.configurationHandler.switchConfigurationSubTab( configurationSubTab, @@ -139,6 +148,28 @@ define(['../../module', '../../../utils/config-handler'], function( this.errorHandler.showSimpleToast('Error fetching group data') } } + + /** + * Show or hide sidebar with info + */ + showInfo() { + this.$scope.showingInfo = !this.$scope.showingInfo + this.$scope.$applyAsync() + } + + /** + * Checks if the agent is synchronized + */ + async checkAgentSync() { + try { + const sync = await this.apiReq.apiReq( + `/agents/${this.$scope.agent.id}/group/is_sync` + ) + return sync.data.data.synced + } catch (error) { + return false + } + } } controllers.controller('configurationAgentCtrl', ConfigurationController) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/docker/agents-docker.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/docker/agents-docker.html new file mode 100644 index 000000000..0a17764e3 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/docker/agents-docker.html @@ -0,0 +1,130 @@ + + +
+ +
+ Agents + / + {{agent.name}} ({{agent.id}}) + Unknown agent + / + Docker listener +
+
+ {{formatAgentStatus(agent.status)}} +
+
+ +
+ + + +
+
+
+ + +
{{reportStatus}}
+ + + + + Vulnerabilities + Osquery + VirusTotal + Docker listener + + + + + +
+
+ Fetching data...
+
+
+
+ +
+ + + + Top 5 images + + + + + +
+
+
+ + + + Top 5 events + + + + + +
+
+
+ + + + Resource usage over time + + + + + +
+
+
+
+ + +
+ + + + Events ocurred evolution + + + + + +
+
+
+
+ + +
+ + + + Alerts summary + + + + + +
+
+
+
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/docker/agentsDockerCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/docker/agentsDockerCtrl.js new file mode 100644 index 000000000..9e027f5b7 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/docker/agentsDockerCtrl.js @@ -0,0 +1,276 @@ +/* + * Wazuh app - Agents controller + * Copyright (C) 2015-2019 Wazuh, Inc. + * + * This program is free software you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation either version 2 of the License, or + * (at your option) any later version. + * + * Find more information about this on the LICENSE file. + */ + +define([ + '../../module', + '../../../services/visualizations/chart/pie-chart', + '../../../services/visualizations/chart/linear-chart', + '../../../services/visualizations/table/table', + '../../../services/visualizations/inputs/time-picker', + '../../../services/rawTableData/rawTableDataService' +], function( + app, + PieChart, + LinearChart, + Table, + TimePicker, + RawTableDataService +) { + 'use strict' + + class DockerAgents { + /** + * Class Agents Docker + * @param {Object} $urlTokenModel + * @param {Object} $state + * @param {Object} $scope + * @param {Object} $currentDataService + * @param {Object} $notificationService + * @param {Object} agent + * @param {*} $reportingService + */ + + constructor( + $urlTokenModel, + $scope, + agent, + $notificationService, + $currentDataService, + $state, + $reportingService, + reportingEnabled, + extensions + ) { + this.state = $state + this.currentDataService = $currentDataService + this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions + this.urlTokenModel = $urlTokenModel + this.notification = $notificationService + this.tableResults = {} + this.reportingService = $reportingService + this.currentDataService.addFilter( + `{"rule.groups{}":"docker", "implicit":true}` + ) + this.scope.expandArray = [false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + this.agent = agent + if ( + this.agent && + this.agent.data && + this.agent.data.data && + this.agent.data.data.id + ) + this.currentDataService.addFilter( + `{"agent.id":"${this.agent.data.data.id}", "implicit":true}` + ) + this.filters = this.currentDataService.getSerializedFilters() + this.timePicker = new TimePicker( + '#timePicker', + this.urlTokenModel.handleValueChange + ) + + this.scope.$on('deletedFilter', event => { + event.stopPropagation() + this.launchSearches() + }) + + this.scope.$on('barFilter', event => { + event.stopPropagation() + this.launchSearches() + }) + + this.vizz = [ + //`${this.filters} sourcetype=wazuh | timechart span=1h count`, + /** + * Visualizations + */ + new PieChart( + 'top5images', + `${this.filters} sourcetype=wazuh | stats count by data.docker.id`, + 'top5images', + this.scope + ), + new LinearChart( + 'eventsOcurred', + `${ + this.filters + } sourcetype=wazuh | timechart span=1h count by data.docker.Action`, + 'eventsOcurred', + this.scope + ), + new PieChart( + 'top5actions', + `${this.filters} sourcetype=wazuh | top data.docker.Action limit=5`, + 'top5actions', + this.scope + ), + new Table( + 'alertsSummary', + `${ + this.filters + } sourcetype=wazuh | stats count sparkline by data.docker.Actor.Attributes.image, data.docker.Actor.Attributes.name, data.docker.Action, timestamp | sort count DESC | rename data.docker.Actor.Attributes.image as Image, data.docker.Actor.Attributes.name as Container, data.docker.Action as Action, timestamp as Date, count as Count, sparkline as Sparkline`, + 'alertsSummary', + this.scope + ), + new LinearChart( + 'resourceUsage', + `${ + this.filters + } sourcetype=wazuh | timechart span=1h count by data.docker.Type`, + 'resourceUsage', + this.scope + ), + new RawTableDataService( + 'alertsSummaryRawTable', + `${ + this.filters + } sourcetype=wazuh | stats count sparkline by data.docker.Actor.Attributes.image, data.docker.Actor.Attributes.name, data.docker.Action, timestamp | sort count DESC | rename data.docker.Actor.Attributes.image as Image, data.docker.Actor.Attributes.name as Container, data.docker.Action as Action, timestamp as Date, count as Count`, + 'alertsSummaryRawTableToken', + '$result$', + this.scope, + 'Alerts summary' + ) + ] + + // Set agent info + try { + this.agentReportData = { + ID: this.agent.data.data.id, + Name: this.agent.data.data.name, + IP: this.agent.data.data.ip, + Version: this.agent.data.data.version, + Manager: this.agent.data.data.manager, + OS: this.agent.data.data.os.name, + dateAdd: this.agent.data.data.dateAdd, + lastKeepAlive: this.agent.data.data.lastKeepAlive, + group: this.agent.data.data.group.toString() + } + } catch (error) { + this.agentReportData = false + } + + // Set agent info + try { + this.agentReportData = { + ID: this.agent.data.data.id, + Name: this.agent.data.data.name, + IP: this.agent.data.data.ip, + Version: this.agent.data.data.version, + Manager: this.agent.data.data.manager, + OS: this.agent.data.data.os.name, + dateAdd: this.agent.data.data.dateAdd, + lastKeepAlive: this.agent.data.data.lastKeepAlive, + group: this.agent.data.data.group.toString() + } + } catch (error) { + this.agentReportData = false + } + + /** + * Generates report + */ + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'ag-docker', + 'Docker', + this.filters, + ['top5images', 'eventsOcurred', 'top5actions', 'resourceUsage'], + {}, //Metrics + this.tableResults, + this.agentReportData + ) + + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) + + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) + + /* + * When controller is destroyed + */ + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) + } + + /** + * On controller loads + */ + $onInit() { + this.scope.loadingVizz = true + this.scope.agent = + this.agent && this.agent.data && this.agent.data.data + ? this.agent.data.data + : { error: true } + + this.scope.getAgentStatusClass = agentStatus => + agentStatus === 'Active' ? 'teal' : 'red' + this.scope.formatAgentStatus = agentStatus => { + return ['Active', 'Disconnected'].includes(agentStatus) + ? agentStatus + : 'Never connected' + } + } + + /** + * Get filters and launches the search + */ + launchSearches() { + this.filters = this.currentDataService.getSerializedFilters() + this.state.reload() + } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } + } + + app.controller('agentsDockerCtrl', DockerAgents) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/fim/agents-fim.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/fim/agents-fim.html index 34119b676..8ab2c593f 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/fim/agents-fim.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/fim/agents-fim.html @@ -2,217 +2,296 @@ -
- -
+
+
Agents / - {{agent.name}} + {{agent.name}} ({{agent.id}}) Unknown agent / File integrity monitoring -
-
- {{formatAgentStatus(agent.status)}} + + {{formatAgentStatus(agent.status)}} +
- - - -
Waiting for reporting information
+
+ + + +
-
Generating report
+
{{reportStatus}}
+ + + + Security + events + Integrity monitoring + Inventory + data + -
- Show files - -
-
- - + +
+
+ Fetching data...
+
+
+
+ +
+
+   + Show files +
+ +
+ +
+ + + + Most active users + + + + + +
+
+
+
+
+ + + + Actions + + + + + +
+
+
+
+
+ + + + Events + + + + + +
+
+
+
+
+
+
+ + + + Files added + + + + + +
+
+
+
+
+ + + + Files modified + + + + + +
+
+
+
+
+ + + + Files deleted + + + + + +
+
+
+
+
+ + +
+ - Events over time + Alerts summary + + + + -
+
+ +
+
+ +
+
+   + Show alerts
-
- +
+ - Top group owners + Windows registry -
+
+ + +
+
+ + +
+
+ + +
+
-
- - - - Top user owners + +
+ + + Files -
+
+ + +
+
+ + +
+
-
- -
- - - - Top file changes - -
-
-
- - - - Root user file changes - -
-
-
- - -
- - -
- - - - Events summary - -
-
-
- -
-
- -
- Show alerts - -
- - -
- - -
-
- - -
- -
-
- -
-
- -
-
- - - Windows registry - -
- - -
-
- - -
- -
-
-
- -
- - - Files - -
- - -
-
- - -
- -
-
-
- -
- - - Files - -
- - -
-
- - -
- -
-
+
+ + + Files + +
+ + +
+
+ + +
+ +
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/fim/agentsFimCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/fim/agentsFimCtrl.js index 86f72ff00..f9ec847fa 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/fim/agentsFimCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/fim/agentsFimCtrl.js @@ -14,7 +14,7 @@ define([ Table, AreaChart, TimePicker, - rawTableDataService + RawTableDataService ) { 'use strict' @@ -39,7 +39,8 @@ define([ $tableFilterService, $csvRequestService, $notificationService, - $reportingService + $reportingService, + reportingEnabled ) { this.state = $state this.wzTableFilter = $tableFilterService @@ -47,13 +48,29 @@ define([ this.agent = agent this.api = this.currentDataService.getApi() this.csvReq = $csvRequestService - this.toast = $notificationService.showSimpleToast + this.notification = $notificationService this.reportingService = $reportingService this.tableResults = {} this.scope = $scope + this.scope.reportingEnabled = reportingEnabled this.showFiles = false this.scope.showFiles = this.showFiles this.urlTokenModel = $urlTokenModel + this.currentDataService.addFilter( + `{"rule.groups{}":"syscheck", "implicit":true, "onlyShow":true}` + ) + this.scope.expandArray = [ + false, + false, + false, + false, + false, + false, + false, + false, + false + ] + this.scope.expand = (i, id) => this.expand(i, id) if ( this.agent && this.agent.data && @@ -71,11 +88,13 @@ define([ ) this.submittedTokenModel = this.urlTokenModel.getSubmittedTokenModel() - this.scope.$on('deletedFilter', () => { + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) @@ -87,7 +106,7 @@ define([ 'eventsOverTimeElement', `${ this.filters - } sourcetype="wazuh" "rule.groups"="syscheck" | timechart span=12h count by rule.description`, + } sourcetype="wazuh" "rule.groups{}"="syscheck" | timechart span=12h count by rule.description`, 'eventsOverTimeElement', this.scope ), @@ -107,6 +126,14 @@ define([ 'topUserOwnersElement', this.scope ), + new PieChart( + 'topActions', + `${ + this.filters + } sourcetype="wazuh" | stats count by "syscheck.event"`, + 'topActions', + this.scope + ), new PieChart( 'topFileChangesElement', `${ @@ -127,7 +154,7 @@ define([ 'wordWritableFilesElement', `${ this.filters - } sourcetype="wazuh" rule.groups="syscheck" "syscheck.perm_after"=* | top "syscheck.perm_after" showcount=false showperc=false | head 1`, + } sourcetype="wazuh" rule.groups{}="syscheck" "syscheck.perm_after"=* | top "syscheck.perm_after" showcount=false showperc=false | head 1`, 'wordWritableFilesElement', this.scope ), @@ -135,27 +162,46 @@ define([ 'eventsSummaryElement', `${ this.filters - } sourcetype="wazuh" rule.groups="syscheck" |stats count sparkline by agent.name, syscheck.path syscheck.event, rule.description | sort count DESC | rename agent.name as Agent, syscheck.path as File, syscheck.event as Event, rule.description as Description, count as Count`, + } sourcetype="wazuh" rule.groups{}="syscheck" |stats count sparkline by agent.name, syscheck.path syscheck.event, rule.description | sort count DESC | rename agent.name as Agent, syscheck.path as File, syscheck.event as Event, rule.description as Description, count as Count`, 'eventsSummaryElement', this.scope + ), + new RawTableDataService( + 'eventsSummaryTable', + `${ + this.filters + } sourcetype="wazuh" rule.groups{}="syscheck" |stats count sparkline by agent.name, syscheck.path syscheck.event, rule.description | sort count DESC | rename agent.name as Agent, syscheck.path as File, syscheck.event as Event, rule.description as Description, count as Count`, + 'eventsSummaryTableToken', + '$result$', + this.scope, + 'Events Summary' + ), + new PieChart( + 'topNewFiles', + `${ + this.filters + } sourcetype=wazuh syscheck.event=added | stats count by syscheck.path | top syscheck.path limit=5`, + 'topNewFiles', + this.scope + ), + new PieChart( + 'topModifiedFiles', + `${ + this.filters + } sourcetype=wazuh syscheck.event=modified | stats count by syscheck.path | top syscheck.path limit=5`, + 'topModifiedFiles', + this.scope + ), + new PieChart( + 'topDeletedFiles', + `${ + this.filters + } sourcetype=wazuh syscheck.event=deleted | stats count by syscheck.path | top syscheck.path limit=5`, + 'topDeletedFiles', + this.scope ) ] - this.eventsSummaryTable = new rawTableDataService( - 'eventsSummaryTable', - `${ - this.filters - } sourcetype="wazuh" rule.groups="syscheck" |stats count sparkline by agent.name, syscheck.path syscheck.event, rule.description | sort count DESC | rename agent.name as Agent, syscheck.path as File, syscheck.event as Event, rule.description as Description, count as Count`, - 'eventsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.eventsSummaryTable) - - this.eventsSummaryTable.getSearch().on('result', result => { - this.tableResults['Events Summary'] = result - }) - // Set agent info try { this.agentReportData = { @@ -182,8 +228,12 @@ define([ 'File integrity monitoring', this.filters, [ + 'topNewFiles', + 'topModifiedFiles', + 'topDeletedFiles', 'eventsOverTimeElement', 'topGroupOwnersElement', + 'topActions', 'topUserOwnersElement', 'topFileChangesElement', 'rootUserFileChangesElement', @@ -205,6 +255,11 @@ define([ if (this.vizzReady) { this.scope.loadingVizz = false } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) this.scope.loadingVizz = true } if (!this.scope.$$phase) this.scope.$digest() @@ -223,6 +278,7 @@ define([ * On controller loads */ $onInit() { + this.scope.loadingVizz = true this.show() this.scope.show = () => this.show() this.scope.agent = @@ -271,8 +327,10 @@ define([ */ async downloadCsv(path, name) { try { - this.toast('Your download should begin automatically...') - const currentApi = this.api.id + this.notification.showSimpleToast( + 'Your download should begin automatically...' + ) + const currentApi = this.api['_key'] const output = await this.csvReq.fetch( path, currentApi, @@ -282,7 +340,7 @@ define([ saveAs(blob, name) // eslint-disable-line return } catch (error) { - this.toast('Error downloading CSV') + this.notification.showErrorToast('Error downloading CSV') } return } @@ -294,6 +352,29 @@ define([ this.filters = this.currentDataService.getSerializedFilters() this.state.reload() } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('agentsFimCtrl', AgentsFim) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/gdpr/agents-gdpr.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/gdpr/agents-gdpr.html index 2e996c6f9..0c86449b9 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/gdpr/agents-gdpr.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/gdpr/agents-gdpr.html @@ -1,92 +1,143 @@ -
- -
+
+
Agents / - {{agent.name}} ({{agent.id}}) + {{agent.name}} ({{agent.id}}) Unknown agent / GDPR -
-
- {{formatAgentStatus(agent.status)}} + + {{formatAgentStatus(agent.status)}} +
- - - -
Waiting for reporting information
+
+ + + +
-
Generating report
+
{{reportStatus}}
+ + + + PCI DSS + GDPR + -
- - - -
- GDPR Requirement: {{tab.rule}} - -
-
{{tab.description}}
-
-
-
-
-
-
-
- - - GDPR Requirements - -
-
-
- - - Groups - -
-
-
+
+
+ Fetching data...
+
+
+
+ + + +
+ GDPR Requirement: {{tab.title}} + +
+
{{tab.content}}
+
+
+
+
+
+
-
- - - Agents - -
-
-
- - - Requirements by agent - -
-
-
-
+ +
+ + + Top 5 rule groups + + + + + +
+
+
-
- - - Alerts summary - -
-
-
-
+ + + Top 5 rules + + + + + +
+
+
+ + + + Top 5 GDPR requirements + + + + + +
+
+
+ + +
+ + + +
+ + + GDPR Requirements + + + + + +
+
+
+
+ +
+ + + Alerts summary + + + + + +
+
+
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/gdpr/agentsGdprCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/gdpr/agentsGdprCtrl.js index 9279afa54..078cedf7c 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/gdpr/agentsGdprCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/gdpr/agentsGdprCtrl.js @@ -13,7 +13,7 @@ define([ Table, TimePicker, Dropdown, - rawTableDataService + RawTableDataService ) { 'use strict' @@ -34,14 +34,31 @@ define([ $scope, $state, agent, - $reportingService + $reportingService, + gdprTabs, + reportingEnabled, + pciExtensionEnabled ) { this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.pciExtensionEnabled = pciExtensionEnabled this.state = $state this.currentDataService = $currentDataService this.reportingService = $reportingService this.tableResults = {} this.agent = agent + this.scope.expandArray = [ + false, + false, + false, + false, + false, + false, + false, + false + ] + this.scope.expand = (i, id) => this.expand(i, id) + if ( this.agent && this.agent.data && @@ -77,14 +94,14 @@ define([ $urlTokenModel.handleValueChange(this.dropdownInstance) } }) - - this.scope.gdprTabs = false - - this.scope.$on('deletedFilter', () => { + this.scope.gdprTabs = gdprTabs ? gdprTabs : false + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) @@ -104,10 +121,26 @@ define([ 'groupsVizz', `${ this.filters - } sourcetype=wazuh rule.gdpr{}="$gdpr$" | stats count by rule.groups`, + } sourcetype=wazuh rule.gdpr{}="$gdpr$" | top limit=5 rule.groups{}`, 'groupsVizz', this.scope ), + new PieChart( + 'top5GDPR', + `${ + this.filters + } sourcetype=wazuh rule.gdpr{}="$gdpr$" | top limit=5 rule.gdpr{} `, + 'top5GDPR', + this.scope + ), + new PieChart( + 'rulesVizz', + `${ + this.filters + } sourcetype=wazuh | top limit=5 rule.description `, + 'rulesVizz', + this.scope + ), new PieChart( 'agentsVizz', `${ @@ -131,24 +164,19 @@ define([ } sourcetype=wazuh rule.gdpr{}="$gdpr$" | stats count sparkline by agent.name, rule.gdpr{}, rule.description | sort count DESC | rename agent.name as "Agent Name", rule.gdpr{} as Requirement, rule.description as "Rule description", count as Count`, 'alertsSummaryVizz', this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh rule.gdpr{}="$gdpr$" | stats count sparkline by agent.name, rule.gdpr{}, rule.description | sort count DESC | rename agent.name as "Agent Name", rule.gdpr{} as Requirement, rule.description as "Rule description", count as Count`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' ) ] - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } sourcetype=wazuh rule.gdpr{}="$gdpr$" | stats count sparkline by agent.name, rule.gdpr{}, rule.description | sort count DESC | rename agent.name as "Agent Name", rule.gdpr{} as Requirement, rule.description as "Rule description", count as Count`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) - - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) - // Set agent info try { this.agentReportData = { @@ -177,6 +205,8 @@ define([ [ 'gdprRequirementsVizz', 'groupsVizz', + 'top5GDPR', + 'rulesVizz', 'agentsVizz', 'requirementsByAgentVizz', 'alertsSummaryVizz' @@ -197,10 +227,16 @@ define([ if (this.vizzReady) { this.scope.loadingVizz = false } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) this.scope.loadingVizz = true } if (!this.scope.$$phase) this.scope.$digest() }) + /** * When controller is destroyed */ @@ -215,6 +251,7 @@ define([ * On controller loads */ $onInit() { + this.scope.loadingVizz = true this.scope.agent = this.agent && this.agent.data && this.agent.data.data ? this.agent.data.data @@ -250,6 +287,29 @@ define([ this.filters = this.getFilters() this.state.reload() } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('agentsGdprCtrl', AgentsGdpr) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/general/agents-general.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/general/agents-general.html index c450ba941..654650719 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/general/agents-general.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/general/agents-general.html @@ -1,180 +1,157 @@ -
- -
+
+
Agents / - {{agentInfo.name}} - ({{agentInfo.id}}) - Unknown agent + {{agentInfo.name}} + ({{agentInfo.id}}) + Unknown agent / General -
-
- {{formatAgentStatus(agentInfo.status)}} + + {{formatAgentStatus(agentInfo.status)}} +
- - - -
Waiting for reporting information
+
+ + + +
- - -
Generating report
+
{{reportStatus}}
+ + + + Security events + Integrity monitoring + + Inventory + data + - - -
- - -
- Name: - {{ agentInfo.name }} - - Full name: {{ agentInfo.name || 'Unknown'}} - -
-
- IP: - {{ agentInfo.ip || 'Unknown'}} -
- -
- Version: - {{ agentInfo.version || 'Unknown'}} -
-
- OS: - {{ agentInfo.agentOS || 'Unknown'}} - - Full OS name: {{ agentInfo.agentOS || 'Unknown'}} - -
-
-
-
-
- - -
- Groups: {{ group }}  -
-
-
+ +
+
+ Fetching data...
+
-
- - -
Last keep alive: - {{agentInfo.lastKeepAlive || 'Unknown' }} -
-
Registration date: - {{agentInfo.dateAdd || 'Unknown'}} -
-
Last syscheck scan: - Scan in progress -
-
Last syscheck scan: - {{agentInfo.syscheck.end || 'Unknown'}} - - Start time: {{ agentInfo.syscheck.start || 'Unknown'}} -
End time: {{ agentInfo.syscheck.end || 'Unknown'}} -
Duration time: {{ agentInfo.syscheck.duration +' minutes' || 'Unknown'}} -
-
-
Last rootcheck scan: - Scan in progress -
-
Last rootcheck scan: - {{agentInfo.rootcheck.end || 'Unknown'}} - - Start time: {{ agentInfo.rootcheck.start || 'Unknown'}} -
End time: {{ agentInfo.rootcheck.end || 'Unknown'}} -
Duration time: {{ agentInfo.rootcheck.duration +' minutes' || 'Unknown'}} -
+
+ +
+ + + + Alert level evolution + + + + + +
+
+
+ + + + Alerts + + + + + +
+
+
- - -
- - + +
+ + + + Top 5 alerts + + + + + +
+
+
+ + + + Top 5 rule groups + + + + + +
+
+
+ + + + Top 5 PCI DSS Requirements + + + + + +
+
+
+
- -
- - - - Top 5 alerts - -
-
-
- - - - Top 5 groups - -
-
-
- - - - Top 5 PCI DSS Requirements - -
-
-
-
-
- - - - Alert level evolution - -
-
-
- - - - Alerts - -
-
-
-
+ +
+ + + Agents summary + + + + + +
+
+
- -
- - - - Agents summary - -
-
-
- -
+ + + Agents summary + + + + + +
+
+
- +
+
+ \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/general/agentsGeneralCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/general/agentsGeneralCtrl.js index 69a0d99b4..aca496b87 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/general/agentsGeneralCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/general/agentsGeneralCtrl.js @@ -25,7 +25,7 @@ define([ PieChart, Table, TimePicker, - rawTableDataService + RawTableDataService ) { 'use strict' @@ -53,18 +53,22 @@ define([ agent, $state, $dateDiffService, - $reportingService + $reportingService, + reportingEnabled ) { this.state = $state this.urlTokenModel = $urlTokenModel this.scope = $scope + this.scope.reportingEnabled = reportingEnabled this.requestService = $requestService this.tableResults = {} - this.notificationService = $notificationService + this.notification = $notificationService this.stateParams = $stateParams this.agent = agent this.currentDataService = $currentDataService this.reportingService = $reportingService + this.scope.expandArray = [false, false, false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) if ( this.agent && this.agent.length && @@ -82,11 +86,13 @@ define([ this.urlTokenModel.handleValueChange ) - this.scope.$on('deletedFilter', () => { + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) @@ -102,7 +108,7 @@ define([ ), new PieChart( 'top5GroupsVizz', - `${this.filters} sourcetype=wazuh | top rule.groups limit=5`, + `${this.filters} sourcetype=wazuh | top rule.groups{} limit=5`, 'top5GroupsVizz', this.scope ), @@ -130,27 +136,40 @@ define([ 'agentsSummaryVizz', `${ this.filters - } sourcetype=wazuh |stats count sparkline by rule.id, rule.description, rule.level | sort rule.level DESC | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, + } sourcetype=wazuh |stats count sparkline by rule.id, rule.description, rule.level | sort count DESC | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, 'agentsSummaryVizz', this.scope + ), + new Table( + 'groupsSummaryVizz', + `${ + this.filters + } sourcetype=wazuh | stats count by rule.groups{} | sort count DESC | rename rule.groups{} as "Group", count as Count`, + 'groupsSummaryVizz', + this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh |stats count sparkline by rule.id, rule.description, rule.level | sort count DESC | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' + ), + new RawTableDataService( + 'groupsSummaryTable', + `${ + this.filters + } sourcetype=wazuh | stats count by rule.groups{} | sort count DESC | rename rule.groups{} as "Group", count as Count`, + 'groupsSummaryTableToken', + '$result$', + this.scope, + 'Groups Summary' ) ] - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } sourcetype=wazuh |stats count sparkline by rule.id, rule.description, rule.level | sort rule.level DESC | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) - - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) - this.scope.$on('loadingReporting', (event, data) => { this.scope.loadingReporting = data.status }) @@ -162,6 +181,11 @@ define([ if (this.vizzReady) { this.scope.loadingVizz = false } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) this.scope.loadingVizz = true } if (!this.scope.$$phase) this.scope.$digest() @@ -181,6 +205,7 @@ define([ */ $onInit() { try { + this.scope.loadingVizz = true this.agentInfo = { name: this.agent[0].data.data.name, id: this.agent[0].data.data.id, @@ -259,7 +284,8 @@ define([ 'top5PCIreqVizz', 'alertLevelEvoVizz', 'alertsVizz', - 'agentsSummaryVizz' + 'agentsSummaryVizz', + 'groupsSummaryVizz' ], this.reportMetrics, this.tableResults, @@ -320,7 +346,7 @@ define([ } this.state.go(`mg-groups`, { group: this.groupData[0] }) } catch (err) { - this.notificationService.showSimpleToast('Error fetching group data') + this.notification.showErrorToast('Error fetching group data') } } @@ -349,6 +375,29 @@ define([ this.filters = this.currentDataService.getSerializedFilters() this.state.reload() } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('agentsGeneralCtrl', AgentsGeneral) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/index.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/index.js index 2171d466e..f73ff566e 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/index.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/index.js @@ -8,10 +8,12 @@ define([ './general/agentsGeneralCtrl', './inventory/inventoryCtrl', './osquery/osqueryCtrl', + './docker/agentsDockerCtrl', './overview/agentsOverviewCtrl', './pcidss/agentsPciCtrl', './policy-monitoring/agentsPolicyMonitoringCtrl', './scap/agentsOpenScapCtrl', './ciscat/agentsCiscatCtrl', - './vulnerabilities/agentsVulnerabilitiesCtrl' + './vulnerabilities/agentsVulnerabilitiesCtrl', + './configuration-assessment/agentsConfigurationAssessmentsCtrl' ], function() {}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/inventory/inventory.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/inventory/inventory.html index 4b5c8f572..0d4a4950d 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/inventory/inventory.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/inventory/inventory.html @@ -1,7 +1,7 @@ - + -
-
+
+
Agents / {{agent.name}} @@ -9,18 +9,32 @@ Unknown agent / Inventory data + + {{formatAgentStatus(agent.status)}} +
-
- {{formatAgentStatus(agent.status)}} -
+ - +
+ +
{{reportStatus}}
+ + + + + Security events + Integrity monitoring + Inventory data + +
@@ -48,8 +62,8 @@
-
- +
+
Cores: {{ syscollector.hardware.cpu.cores }}
Memory: {{ (syscollector.hardware.ram.total / 1024) | number: 2 }} @@ -65,25 +79,33 @@ Packages - Last scan: {{syscollector.packagesDate}} + Last scan: {{setBrowserOffset(syscollector.packagesDate)}}
- -
+ row-sizes="[10,8,6]" extra-limit="100" keys="[{value:'name',size:2},'architecture','version',{value:'vendor',size:2},{value:'description',size:3}]"> + row-sizes="[10,8,6]" extra-limit="100" keys="[{value:'name',size:3},'architecture','version',{value:'vendor',size:2}]">
+
@@ -91,25 +113,33 @@ Processes - Last scan: {{syscollector.processesDate}} + Last scan: {{setBrowserOffset(syscollector.processesDate)}}
- -
+ row-sizes="[10,8,6]" extra-limit="100" keys="['name','cmd','priority','nlwp']"> + row-sizes="[10,8,6]" extra-limit="100" keys="['name','euser','nice','state']"> -
+
@@ -121,7 +151,7 @@ Network interfaces - Last scan: {{syscollector.netiface.items[0].scan.time}} + Last scan: {{setBrowserOffset(syscollector.netiface.items[0].scan.time)}} @@ -169,7 +199,7 @@ Network ports - Last scan: {{syscollector.ports.items[0].scan.time}} + Last scan: {{setBrowserOffset(syscollector.ports.items[0].scan_time)}} @@ -181,14 +211,14 @@ -
+
No network addresses scan available - Network addresses + Network settings diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/inventory/inventoryCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/inventory/inventoryCtrl.js index e2f3ab691..e0b3ebc16 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/inventory/inventoryCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/inventory/inventoryCtrl.js @@ -10,7 +10,7 @@ * Find more information about this on the LICENSE file. */ -define(['../../module'], function(module) { +define(['../../module', 'FileSaver'], function(module) { 'use strict' class Inventory { /** @@ -28,20 +28,28 @@ define(['../../module'], function(module) { $rootScope, $notificationService, $scope, - $reportingService + $reportingService, + reportingEnabled, + $currentDataService, + $csvRequestService, + $dateDiffService ) { this.scope = $scope + this.scope.reportingEnabled = reportingEnabled this.data = syscollector this.httpReq = $requestService.httpReq this.apiReq = $requestService.apiReq this.root = $rootScope - this.toast = $notificationService.showSimpleToast + this.notification = $notificationService this.netifaceResponse = false this.ports = {} this.packagesDate = {} this.processesDate = {} this.netaddrResponse = false this.reportingService = $reportingService + this.api = $currentDataService.getApi() + this.csvReq = $csvRequestService + this.setBrowserOffset = $dateDiffService.setBrowserOffset } /** @@ -58,6 +66,8 @@ define(['../../module'], function(module) { */ $onInit() { try { + this.setBrowserOffset("2019/04/24 10:59:03") + this.scope.downloadCsv = (path, name) => this.downloadCsv(path, name) this.scope.hasSize = obj => obj && typeof obj === 'object' && Object.keys(obj).length @@ -103,24 +113,17 @@ define(['../../module'], function(module) { this.init() this.scope.startVis2Png = () => - this.reportingService.reportInventoryData( - 'agents-inventory', - 'Inventory Data', - '', //Filters, - [], //Visualizations, - {}, //Metrics, - {}, //tableResults - 'inventory', //isAgent - this.scope.agent.id //agentId - ) + this.reportingService.reportInventoryData(this.scope.agent.id) this.scope.$on('loadingReporting', (event, data) => { this.scope.loadingReporting = data.status }) + this.scope.setBrowserOffset = date => this.setBrowserOffset(date) + return } catch (error) { - this.toast(error.message || error) + this.notification.showErrorToast(error.message || error) } } @@ -164,12 +167,32 @@ define(['../../module'], function(module) { ? this.processesDate.items[0].scan_time : 'Unknown' } - if (!this.scope.$$phase) this.scope.$digest() + console.log("tss ", this.scope.syscollector) + this.scope.$applyAsync() return } catch (error) { throw new Error(error.message || error) } } + + /** + * Exports the table in CSV format + */ + async downloadCsv(path, name) { + try { + this.notification.showSimpleToast( + 'Your download should begin automatically...' + ) + const currentApi = this.api['_key'] + const output = await this.csvReq.fetch(path, currentApi) + const blob = new Blob([output], { type: 'text/csv' }) // eslint-disable-line + saveAs(blob, name) // eslint-disable-line + return + } catch (error) { + this.notification.showErrorToast('Error downloading CSV') + } + return + } } // Logs controller module.controller('inventoryCtrl', Inventory) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/osquery/osquery.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/osquery/osquery.html index 72ca7f961..857259084 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/osquery/osquery.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/osquery/osquery.html @@ -1,82 +1,126 @@ -
- -
- Agents - / - {{agent.name}} ({{agent.id}}) - Unknown agent - / - Osquery -
-
- {{formatAgentStatus(agent.status)}} -
-
+
+
+ Agents + / + {{agent.name}} ({{agent.id}}) + Unknown agent + / + Osquery + + {{formatAgentStatus(agent.status)}} + +
+
- - - -
Waiting for reporting information
-
+
+ + +
- - -
Generating report
- - - - - -
- - - - Most common packs - -
-
-
- - - - Evolution of Osquery events per pack over time - -
-
-
+
- -
- - - Most common Osquery actions - -
-
-
- - - - Most common rules - -
-
-
- + + +
{{reportStatus}}
+ + + + + Vulnerabilities + Osquery + VirusTotal + Docker listener + + + + +
+
+ Fetching data...
+
-
- - +
+ +
+ + + Most common Osquery actions + + + + + +
+
+
+ - Evolution of Osquery events over time + Evolution of Osquery events per pack over time + + + + -
+
- - +
+ +
+ + + Most common Osquery packs being used + + + + + +
+
+
+ + + + Most common rules + + + + + +
+
+
+ +
+
+ + + + Alerts summary + + + + + +
+
+
+ + +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/osquery/osqueryCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/osquery/osqueryCtrl.js index 005d9cbee..a9c78eb9d 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/osquery/osqueryCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/osquery/osqueryCtrl.js @@ -17,7 +17,7 @@ define([ '../../../services/visualizations/table/table', '../../../services/visualizations/inputs/time-picker', '../../../services/rawTableData/rawTableDataService' -], function(app, PieChart, AreaChart, Table, TimePicker, rawTableDataService) { +], function(app, PieChart, AreaChart, Table, TimePicker, RawTableDataService) { 'use strict' class OsqueryAgents { @@ -41,19 +41,25 @@ define([ $currentDataService, $state, osquery, - $reportingService + $reportingService, + reportingEnabled, + extensions ) { this.state = $state this.currentDataService = $currentDataService this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions this.urlTokenModel = $urlTokenModel - this.notificationService = $notificationService + this.notification = $notificationService this.tableResults = {} this.reportingService = $reportingService this.osquery = osquery this.currentDataService.addFilter( - `{"rule.groups":"osquery", "implicit":true}` + `{"rule.groups{}":"osquery", "implicit":true}` ) + this.scope.expandArray = [false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) this.agent = agent if ( this.agent && @@ -71,11 +77,13 @@ define([ ) this.scope.osqueryWodle = null - this.scope.$on('deletedFilter', () => { + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) @@ -101,7 +109,7 @@ define([ 'mostCommonActions', `${ this.filters - } sourcetype=wazuh | top "data.osquery.action" limit=5`, + } sourcetype=wazuh | top data.osquery.action limit=5`, 'mostCommonActions', this.scope ), @@ -118,24 +126,37 @@ define([ `${this.filters} sourcetype=wazuh | timechart span=1h count`, 'alertsOverTime', this.scope + ), + new RawTableDataService( + 'topRulesTable', + `${ + this.filters + } sourcetype=wazuh | top rule.id, rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule description", count as Count, percent as Percent`, + 'topRulesTableToken', + '$result$', + this.scope, + 'Top Rules' + ), + new Table( + 'alertsSummary', + `${ + this.filters + } sourcetype=wazuh | stats count by data.osquery.name, data.osquery.action,agent.name,data.osquery.pack | rename data.osquery.name as Name, data.osquery.action as Action, agent.name as Agent, data.osquery.pack as Pack, count as Count`, + 'alertsSummary', + this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh | stats count by data.osquery.name, data.osquery.action,agent.name,data.osquery.pack | rename data.osquery.name as Name, data.osquery.action as Action, agent.name as Agent, data.osquery.pack as Pack, count as Count`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts summary' ) ] - this.topRulesTable = new rawTableDataService( - 'topRulesTable', - `${ - this.filters - } sourcetype=wazuh | top rule.id, rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule description", count as Count, percent as Percent`, - 'topRulesTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.topRulesTable) - - this.topRulesTable.getSearch().on('result', result => { - this.tableResults['Top Rules'] = result - }) - // Set agent info try { this.agentReportData = { @@ -166,7 +187,8 @@ define([ 'alertsPacksOverTime', 'mostCommonActions', 'topRules', - 'alertsOverTime' + 'alertsOverTime', + 'alertsSummary' ], {}, //Metrics, this.tableResults, @@ -184,6 +206,11 @@ define([ if (this.vizzReady) { this.scope.loadingVizz = false } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) this.scope.loadingVizz = true } if (!this.scope.$$phase) this.scope.$digest() @@ -202,6 +229,7 @@ define([ * On controller loads */ $onInit() { + this.scope.loadingVizz = true this.scope.agent = this.agent && this.agent.data && this.agent.data.data ? this.agent.data.data @@ -212,7 +240,7 @@ define([ item => item.osquery )[0].osquery } catch (err) { - this.notificationService.showSimpleToast( + this.notification.showErrorToast( 'Cannot load wodle configuration. Osquery not configured.' ) } @@ -233,6 +261,29 @@ define([ this.filters = this.currentDataService.getSerializedFilters() this.state.reload() } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('osqueryAgentCtrl', OsqueryAgents) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/overview/agentsOverviewCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/overview/agentsOverviewCtrl.js index 466db735d..edd987702 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/overview/agentsOverviewCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/overview/agentsOverviewCtrl.js @@ -10,7 +10,7 @@ * Find more information about this on the LICENSE file. */ -define(['../../module'], function(app) { +define(['../../module'], function (app) { 'use strict' class AgentsOverview { @@ -33,6 +33,7 @@ define(['../../module'], function(app) { $notificationService, agent, groups, + isAdmin, $mdDialog, $groupHandler, $dateDiffService @@ -41,15 +42,18 @@ define(['../../module'], function(app) { this.scope = $scope this.requestService = $requestService this.state = $state - this.notificationService = $notificationService + this.notification = $notificationService this.agent = agent this.extensions = extensions this.dateDiffService = $dateDiffService this.scope.editGroup = false + this.scope.showRootcheckScan = false this.scope.addingGroupToAgent = false this.groups = groups this.$mdDialog = $mdDialog this.groupHandler = $groupHandler + this.scope.restartInProgress = false + this.scope.isAdmin = isAdmin } /** @@ -57,6 +61,7 @@ define(['../../module'], function(app) { */ $onInit() { try { + this.scope.confirmingRestart = false if ( this.agent.length && typeof this.agent[0] === 'object' && @@ -67,27 +72,27 @@ define(['../../module'], function(app) { this.scope.agentOS = this.scope.agent && - this.scope.agent.os && - this.scope.agent.os.name && - this.scope.agent.os.codename && - this.scope.agent.os.version + this.scope.agent.os && + this.scope.agent.os.name && + this.scope.agent.os.codename && + this.scope.agent.os.version ? `${this.scope.agent.os.name || '-'} ${this.scope.agent.os - .codename || '-'} ${this.scope.agent.os.version || '-'}` + .codename || '-'} ${this.scope.agent.os.version || '-'}` : 'Unknown' this.scope.syscheck = this.agent.length > 0 && - typeof this.agent[1] === 'object' && - typeof this.agent[1].data === 'object' && - !this.agent[1].data.error + typeof this.agent[1] === 'object' && + typeof this.agent[1].data === 'object' && + !this.agent[1].data.error ? this.agent[1].data.data : (this.scope.syscheck = { start: 'Unknown', end: 'Unknown' }) this.scope.id = this.stateParams.id this.scope.rootcheck = this.agent.length > 1 && - typeof this.agent[2] === 'object' && - typeof this.agent[2].data === 'object' && - !this.agent[2].data.error + typeof this.agent[2] === 'object' && + typeof this.agent[2].data === 'object' && + !this.agent[2].data.error ? this.agent[2].data.data : { start: 'Unknown', end: 'Unknown' } if (!this.scope.agent.error) { @@ -111,6 +116,12 @@ define(['../../module'], function(app) { this.getAgentStatusClass(agentStatus) this.scope.goGroups = group => this.goGroups(group) + this.scope.searchRootcheck = (term, specificFilter) => + this.scope.$broadcast('wazuhSearch', { term, specificFilter }) + + this.scope.launchRootcheckScan = () => this.launchRootcheckScan() + this.scope.launchSyscheckScan = () => this.launchSyscheckScan() + this.scope.syscheck.duration = this.dateDiffService.getDateDiff( this.scope.syscheck.start, this.scope.syscheck.end @@ -139,9 +150,21 @@ define(['../../module'], function(app) { : group } + + this.scope.offsetTimestamp = (text, time) => { + try { + return text + this.dateDiffService.setBrowserOffset(time) + } catch (error) { + return '' + } + } + this.scope.cancelAddGroup = () => (this.scope.addingGroupToAgent = false) + this.scope.restart = () => this.restartAgent() + this.scope.switchRestart = () => this.switchRestart() + this.scope.confirmAddGroup = group => { this.groupHandler .addAgentToGroup(group, this.scope.agent.id) @@ -154,16 +177,23 @@ define(['../../module'], function(app) { item => !agent.data.data.group.includes(item) ) this.scope.addingGroupToAgent = false - this.notificationService.showSimpleToast( - `Group ${group} has been added.` + this.scope.editGroup = false + this.notification.showSuccessToast( + `Agent ${this.scope.agent.name}(${ + this.scope.agent.id + }) has been added to group ${group}.` ) if (!this.scope.$$phase) this.scope.$digest() }) .catch(error => { + if (!this.scope.agent) { + if ((error || {}).status === -1) { + this.scope.emptyAgent = 'Wazuh API timeout.' + } + } + this.scope.editGroup = false this.scope.addingGroupToAgent = false - this.notificationService.showSimpleToast( - error.message || error - ) + this.notification.showErrorToast(error.message || error) }) } } @@ -223,9 +253,10 @@ define(['../../module'], function(app) { } this.scope.adminMode = this.extensions['admin'] === 'true' } catch (err) { - console.error('err ', err) + this.scope.load = false this.scope.adminMode = false - this.notificationService.showSimpleToast('Error loading agent data.') + this.notification.showErrorToast('Error loading agent data.') + this.scope.$applyAsync() } } @@ -253,7 +284,7 @@ define(['../../module'], function(app) { } this.state.go(`mg-groups`, { group: this.groupData[0] }) } catch (err) { - this.notificationService.showSimpleToast( + this.notification.showErrorToast( 'Error fetching group data.', err.message || err ) @@ -275,13 +306,50 @@ define(['../../module'], function(app) { * @param {String} agentStatus */ getAgentStatusClass(agentStatus) { - agentStatus === 'Active' ? 'teal' : 'red' + return agentStatus === 'Active' ? 'teal' : 'red' } + /** + * Switch editing group + */ switchGroupEdit() { this.scope.editGroup = !!!this.scope.editGroup if (!this.scope.$$phase) this.scope.$digest() } + + /** + * Restart the agent + */ + async restartAgent() { + try { + this.scope.restartInProgress = true + const id = this.scope.agent.id + const name = this.scope.agent.name + const result = await this.requestService.apiReq( + `/agents/${id}/restart`, + {}, + 'PUT' + ) + if (result && result.data.error === 0 && !result.data.failed_ids) { + this.notification.showSimpleToast( + `Agent ${name}(${id}) is restarting.` + ) + } else { + this.notification.showErrorToast( + `Agent ${name}(${id}) could not be restarted.` + ) + } + this.scope.restartInProgress = false + } catch (error) { + this.scope.restartInProgress = false + this.notification.showErrorToast(`Error restarting agent: ${error}`) + } + } + + switchRestart() { + this.scope.confirmingRestart = !this.scope.confirmingRestart + this.scope.$applyAsync() + } } app.controller('agentsOverviewCtrl', AgentsOverview) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/overview/overview.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/overview/overview.html index 3bba35514..3c2e85128 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/overview/overview.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/overview/overview.html @@ -1,132 +1,192 @@
-
- -
+
+
Agents / {{agent.name}} ({{agent.id}}) Unknown agent - / - Welcome -
-
- {{formatAgentStatus(agent.status)}} + + {{formatAgentStatus(agent.status)}} +
- - Agent overview +
+ + {{ agent.name || '-' }} + + + + +
+ The {{ agent.name}}({{agent.id}}) will be restarted. + + +
+
+ +
+
+
+ + +
+
+
+
+

ID

+
+

{{ agent.id || '-' }}

+
+
+
+
+
+

IP

+
+

{{ agent.ip || '-'}}

+
+
+
+
+
+

Version

+
+

{{ agent.version || '-'}}

+
+
+
+
+
+

OS

+
+

{{ agentOS || '-'}}

+
+
+
+
+
+

Registration date

+
+

{{offsetTimestamp('', agent.dateAdd) || '-'}}

+
+
+
+
+
+

Last keep alive

+
+

{{offsetTimestamp('', agent.lastKeepAlive) || '-'}}

+
+
+
+
+
+

Last syscheck scan

+
+

Scan + in progress

+

+ {{offsetTimestamp('', syscheck.end) || '-'}} + + Start time: {{offsetTimestamp('', syscheck.start) || '-'}}
+ End time: {{offsetTimestamp('', syscheck.end) || '-'}}
+ Duration time: {{syscheck.duration +' minutes' || '-'}} +
+

+
+
+
+
+
+

Last rootcheck scan

+
+

Scan + in progress

+

{{offsetTimestamp('', rootcheck.end) + || '-'}} + + Start time: {{offsetTimestamp('', rootcheck.start) || '-'}}
+ End time: {{offsetTimestamp('', rootcheck.end) || '-'}}
+ Duration time: {{rootcheck.duration + ' minutes' || '-'}} +
+

+
+
+
+
+
+
- -
- - -
- Name: - {{ agent.name }} - - Full name: {{ agent.name }} - -
-
- IP: - {{ agent.ip }} -
- -
- Version: - {{ agent.version }} -
-
- OS: - {{ agentOS }} - - Full OS name: {{ agentOS }} - -
-
-
-
-
- - -
-  Groups:  - {{ - group }}  +
+ + + +
+ Groups + + +
-
+ +
Available groups:
- There are no more groups available. + No more groups available. Create a new group at Management > Groups.
-
-
+
{{ - group }}  + group }} 
-
+
- Group {{addingGroupToAgent}} will be added to agent - {{agent.id}} + Agent {{agent.name}}({{agent.id}}) will be added to group + {{addingGroupToAgent}}.
- - Cancel - Cancel + Confirm
- - -
- - -
- - -
Last keep alive: - {{agent.lastKeepAlive || 'Unknown' }} -
-
Registration date: - {{agent.dateAdd}} -
-
Last syscheck scan: - Scan in progress -
-
Last syscheck scan: - {{syscheck.end || 'Unknown'}} - - Start time: {{ syscheck.start || 'Unknown'}} -
End time: {{ syscheck.end || 'Unknown'}} -
Duration time: {{ syscheck.duration +' minutes' || 'Unknown'}} -
-
-
Last rootcheck scan: - Scan in progress -
-
Last rootcheck scan: - {{rootcheck.end || 'Unknown'}} - - Start time: {{ rootcheck.start || 'Unknown'}} -
End time: {{ rootcheck.end || 'Unknown'}} -
Duration time: {{ rootcheck.duration +' minutes' || 'Unknown'}} -
+
+ {{ + group + }} 
+
@@ -149,34 +209,58 @@
-

Security Information Management

+

Security Information Management

+ sub-title="'Security events'" ui-sref='ag-general({id:agent.id})' current-tab="'general'" + description="'Browse through your security alerts, identifying issues and threats in your environment.'"> + - - + sub-title="'Integrity monitoring'" ui-sref='ag-fim({id:agent.id})' current-tab="'fim'" + description="'Alerts related to file changes, including permissions, content, ownership and attributes.'"> + + + +
-

Auditing and Policy Monitoring

+

Auditing and Policy Monitoring

- + + + + - - + sub-title="'System auditing'" ui-sref='ag-audit({id:agent.id})' ng-if="audit && isLinux" + current-tab="'audit'" + description="'Audit users behavior, monitoring command execution and alerting on access to critical files.'"> + + + + +
@@ -187,29 +271,44 @@

Auditing and Policy Monitoring

-

Threat Detection and Response

+

Threat Detection and Response

- - - - + sub-title="'Vulnerabilities'" ui-sref='ag-vul({id:agent.id})' current-tab="'vuls'" + description="'Discover what applications are affected by well-known vulnerabilities'"> + + + + + +
-

Regulatory Compliance

+

Regulatory Compliance

- - + + + +
diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/pcidss/agents-pci.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/pcidss/agents-pci.html index b9749835a..0ab33f8cc 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/pcidss/agents-pci.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/pcidss/agents-pci.html @@ -1,94 +1,152 @@ -
- -
+
+
Agents / - {{agent.name}} ({{agent.id}}) + {{agent.name}} ({{agent.id}}) Unknown agent / PCI-DSS -
-
- {{formatAgentStatus(agent.status)}} + + {{formatAgentStatus(agent.status)}} +
- - - -
Waiting for reporting information
+
+ + + +
-
Generating report
+
{{reportStatus}}
+ + + + PCI DSS + GDPR + - -
- - - -
- PCI-DSS Requirement: {{tab.rule}} - -
-
{{tab.description}}
-
-
-
-
-
-
-
- - - PCI Requirements - -
-
-
- - - Groups - -
-
-
+
+
+ Fetching data...
+
+
+ +
+ + + +
+ PCI-DSS Requirement: {{tab.title}} + +
+

{{tab.content}}

+
+
+
+
+
+
+ + + +
+ + + Top 5 rule groups + + + + + +
+
+
+ + + Top 5 rules + + + + + +
+
+
+ + + Top 5 PCI DSS requirements + + + + + +
+
+
+
-
- - - Agents - -
-
-
- - - Requirements by agent - -
-
-
-
-
- - - Alerts summary - -
-
-
-
+
+ + + PCI Requirements + + + + + +
+
+
+ + + Rule level distribution + + + + + +
+
+
+
+ +
+ + + Alerts summary + + + + + +
+
+
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/pcidss/agentsPciCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/pcidss/agentsPciCtrl.js index 0ae6e23ff..ee24d2f0a 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/pcidss/agentsPciCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/pcidss/agentsPciCtrl.js @@ -13,7 +13,7 @@ define([ Table, TimePicker, Dropdown, - rawTableDataService + RawTableDataService ) { 'use strict' @@ -33,24 +33,32 @@ define([ $state, $currentDataService, agent, - $reportingService + $reportingService, + pciTabs, + reportingEnabled, + gdprExtensionEnabled ) { this.state = $state this.reportingService = $reportingService this.tableResults = {} this.currentDataService = $currentDataService this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.gdprExtensionEnabled = gdprExtensionEnabled + this.scope.pciTabs = pciTabs ? pciTabs : false this.urlTokenModel = $urlTokenModel this.timePicker = new TimePicker( '#timePicker', this.urlTokenModel.handleValueChange ) this.submittedTokenModel = this.urlTokenModel.getSubmittedTokenModel() - this.scope.$on('deletedFilter', () => { + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) @@ -60,6 +68,9 @@ define([ this.vizz.map(vizz => vizz.destroy()) }) + this.scope.expandArray = [false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + this.dropdown = new Dropdown( 'dropDownInput', `${ @@ -103,16 +114,32 @@ define([ 'groupsVizz', `${ this.filters - } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count by rule.groups`, + } sourcetype=wazuh rule.pci_dss{}="$pci$" | top limit=5 rule.groups{}`, 'groupsVizz', this.scope ), new PieChart( - 'agentsVizz', + 'topRules', + `${ + this.filters + } sourcetype=wazuh rule.pci_dss{}="$pci$" | top limit=5 rule.description`, + 'topRules', + this.scope + ), + new PieChart( + 'top5Pcidss', `${ this.filters - } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count by agent.name`, - 'agentsVizz', + } sourcetype=wazuh rule.pci_dss{}="$pci$" | top limit=5 rule.pci_dss{}`, + 'top5Pcidss', + this.scope + ), + new PieChart( + 'ruleLevelDistribution', + `${ + this.filters + } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count by rule.level`, + 'ruleLevelDistribution', this.scope ), new ColumnChart( @@ -130,24 +157,19 @@ define([ } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count sparkline by agent.name, rule.pci_dss{}, rule.description | sort count DESC | rename agent.name as "Agent Name", rule.pci_dss{} as Requirement, rule.description as "Rule description", count as Count`, 'alertsSummaryVizz', this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count sparkline by agent.name, rule.pci_dss{}, rule.description | sort count DESC | rename agent.name as "Agent Name", rule.pci_dss{} as Requirement, rule.description as "Rule description", count as Count`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' ) ] - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count sparkline by agent.name, rule.pci_dss{}, rule.description | sort count DESC | rename agent.name as "Agent Name", rule.pci_dss{} as Requirement, rule.description as "Rule description", count as Count`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) - - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) - // Set agent info try { this.agentReportData = { @@ -175,8 +197,10 @@ define([ this.filters, [ 'pciReqSearchVizz', + 'ruleLevelDistribution', + 'top5Pcidss', 'groupsVizz', - 'agentsVizz', + 'topRules', 'reqByAgentsVizz', 'alertsSummaryVizz' ], @@ -196,6 +220,11 @@ define([ if (this.vizzReady) { this.scope.loadingVizz = false } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) this.scope.loadingVizz = true } if (!this.scope.$$phase) this.scope.$digest() @@ -206,6 +235,7 @@ define([ * On controller loads */ $onInit() { + this.scope.loadingVizz = true this.scope.agent = this.agent && this.agent.data && this.agent.data.data ? this.agent.data.data @@ -241,6 +271,29 @@ define([ ? agentStatus : 'Never connected' } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('agentsPciCtrl', AgentsPCI) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/policy-monitoring/agents-pm.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/policy-monitoring/agents-pm.html index c76904503..2147af5e7 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/policy-monitoring/agents-pm.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/policy-monitoring/agents-pm.html @@ -1,79 +1,133 @@ -
- -
+
+
Agents / - {{agent.name}} ({{agent.id}}) + {{agent.name}} + ({{agent.id}}) Unknown agent / Policy monitoring -
-
- {{formatAgentStatus(agent.status)}} + + {{formatAgentStatus(agent.status)}} +
- - - -
Waiting for reporting information
+
+ + + +
-
Generating report
+
{{reportStatus}}
+ + + + Policy monitoring + SCA + System auditing + OpenSCAP + CIS-CAT + - -
- - - Events over time - -
-
-
+
+
+ Fetching data...
+
+
+
+ +
+ + +
+ +
+ + + Alerts over time + + + + + +
+
+
- - - Top 5 CIS Requirements - -
-
-
+ + + Top 5 CIS Requirements + + + + + +
+
+
- - - Top 5 PCI DSS Requirements - -
-
-
-
+ + + Top 5 PCI DSS Requirements + + + + + +
+
+
+
-
- - - Events per agent evolution - -
-
-
-
+
+ + + Events per agent evolution + + + + + +
+
+
+
-
- - - Alerts summary - -
-
-
+
+ + + Alerts summary + + + + + +
+
+
+
- \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/policy-monitoring/agentsPolicyMonitoringCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/policy-monitoring/agentsPolicyMonitoringCtrl.js index 6f9404c1c..e33c3dc72 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/policy-monitoring/agentsPolicyMonitoringCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/policy-monitoring/agentsPolicyMonitoringCtrl.js @@ -17,7 +17,7 @@ define([ '../../../services/visualizations/table/table', '../../../services/visualizations/inputs/time-picker', '../../../services/rawTableData/rawTableDataService' -], function(app, PieChart, AreaChart, Table, TimePicker, rawTableDataService) { +], function(app, PieChart, AreaChart, Table, TimePicker, RawTableDataService) { 'use strict' class AgentsPM { @@ -29,26 +29,47 @@ define([ * @param {Object} $currentDataService * @param {Object} agent * @param {*} $reportingService + * @param {*} $requestService + * @param {*} $notificationService + * @param {*} $csvRequestService */ constructor( $urlTokenModel, + $rootScope, $scope, $state, $currentDataService, agent, - $reportingService + $reportingService, + $requestService, + $notificationService, + $csvRequestService, + $tableFilterService, + reportingEnabled, + extensions ) { this.urlTokenModel = $urlTokenModel + this.rootScope = $rootScope this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions + this.apiReq = $requestService.apiReq + this.scope.showPolicies = false this.state = $state this.reportingService = $reportingService this.tableResults = {} this.currentDataService = $currentDataService this.agent = agent + this.notification = $notificationService + this.api = $currentDataService.getApi() + this.csvReq = $csvRequestService + this.wzTableFilter = $tableFilterService this.currentDataService.addFilter( - `{"rule.groups":"rootcheck", "implicit":true}` + `{"rule.groups{}":"rootcheck", "implicit":true}` ) + this.scope.expandArray = [false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) if ( this.agent && this.agent.data && @@ -58,17 +79,20 @@ define([ this.currentDataService.addFilter( `{"agent.id":"${this.agent.data.data.id}", "implicit":true}` ) + this.filters = this.currentDataService.getSerializedFilters() this.timePicker = new TimePicker( '#timePicker', this.urlTokenModel.handleValueChange ) - this.scope.$on('deletedFilter', () => { + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) @@ -113,24 +137,19 @@ define([ } sourcetype=wazuh |stats count sparkline by agent.name, rule.description, title | sort count DESC | rename rule.description as "Rule description", agent.name as Agent, title as Control`, 'alertsSummary', this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh |stats count sparkline by agent.name, rule.description, title | sort count DESC | rename rule.description as "Rule description", agent.name as Agent, title as Control`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' ) ] - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } sourcetype=wazuh |stats count sparkline by agent.name, rule.description, title | sort count DESC | rename rule.description as "Rule description", agent.name as Agent, title as Control`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) - - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) - // Set agent info try { this.agentReportData = { @@ -179,6 +198,11 @@ define([ if (this.vizzReady) { this.scope.loadingVizz = false } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) this.scope.loadingVizz = true } if (!this.scope.$$phase) this.scope.$digest() @@ -194,6 +218,13 @@ define([ } $onInit() { + this.scope.loadingVizz = true + this.scope.searchRootcheck = (term, specificFilter) => + this.scope.$broadcast('wazuhSearch', { term, specificFilter }) + this.scope.downloadCsv = () => this.downloadCsv() + this.scope.launchRootcheckScan = () => this.launchRootcheckScan() + this.scope.launchSyscheckScan = () => this.launchSyscheckScan() + this.scope.agent = this.agent && this.agent.data && this.agent.data.data ? this.agent.data.data @@ -222,6 +253,29 @@ define([ : 'Never connected' } + /** + * Exports the table in CSV format + */ + async downloadCsv() { + try { + this.notification.showSimpleToast( + 'Your download should begin automatically...' + ) + const currentApi = this.api.id + const output = await this.csvReq.fetch( + '/agents', + currentApi, + this.wzTableFilter.get() + ) + const blob = new Blob([output], { type: 'text/csv' }) // eslint-disable-line + saveAs(blob, 'agents.csv') // eslint-disable-line + return + } catch (error) { + this.notification.showErrorToast('Error downloading CSV') + } + return + } + /** * Gets filters and launches search */ @@ -229,7 +283,51 @@ define([ this.filters = this.currentDataService.getSerializedFilters() this.state.reload() } - } + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } + + /** + * Launches a rootcheck scan + */ + async launchRootcheckScan() { + try { + const result = await this.apiReq( + `/rootcheck/${this.scope.agent.id}`, + {}, + 'PUT' + ) + if (result && result.data && result.data.error === 0) { + this.notification.showSuccessToast( + `Policy monitoring scan launched successfully on agent ${ + this.scope.agent.id + }` + ) + } + } catch (error) { + this.notification.showErrorToast(error.message || error) + } + } + } app.controller('agentsPolicyMonitoringCtrl', AgentsPM) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/scap/agents-openscap.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/scap/agents-openscap.html index 5a85d8657..f872f657a 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/scap/agents-openscap.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/scap/agents-openscap.html @@ -1,117 +1,177 @@ - + -
- -
+
+
Agents / - {{agent.name}} ({{agent.id}}) + {{agent.name}} + ({{agent.id}}) / OpenSCAP -
-
- {{formatAgentStatus(agent.status)}} + + {{formatAgentStatus(agent.status)}} +
- - - -
Waiting for reporting information
+
+ + + +
-
Generating report
+
{{reportStatus}}
+ + + + Policy monitoring + + SCA + System auditing + OpenSCAP + CIS-CAT + - -
- - -
Last score: - {{ scapLastScore | number:2}} -
-
Highest score: - {{scapHighestScore | number:2}} -
-
Lowest score: - {{scapLowestScore | number:2}} -
-
-
-
-
- - - Agents - -
-
-
- - - Profiles - -
-
-
- - - Content - -
-
-
- - - Severity - -
-
-
+
+
+ Fetching data...
+
+
+ +
+ + +
Last score: + {{ scapLastScore | number:2}} +
+
Highest score: + {{scapHighestScore | number:2}} +
+
Lowest score: + {{scapLowestScore | number:2}} +
+
+
+
-
- - - Top 5 Agents - Severity high - -
-
-
-
+
+ + + Top 5 scans + + + + + +
+
+
+ + + Top 5 profiles + + + + + +
+
+
+ + + Top 5 content + + + + + +
+
+
+ + + Top 5 severity + + + + + +
+
+
+
-
- - - Top 10 - Alerts - -
-
-
+
+ + + Top 5 Agents - Severity high + + + + + +
+
+
+
- - - Top 10 - High risk alerts - -
-
-
-
+
+ + + Top 5 - Alerts + + + + + +
+
+
-
- - - Alerts summary - -
-
-
-
+ + + Top 5 - High risk alerts + + + + + +
+
+
+
+
+ + + Alerts summary + + + + + +
+
+
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/scap/agentsOpenScapCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/scap/agentsOpenScapCtrl.js index 30341ad9c..9778d9ff6 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/scap/agentsOpenScapCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/scap/agentsOpenScapCtrl.js @@ -29,7 +29,7 @@ define([ TimePicker, Dropdown, SearchHandler, - rawTableDataService + RawTableDataService ) { 'use strict' @@ -50,18 +50,35 @@ define([ $currentDataService, $state, agent, - $reportingService + $reportingService, + reportingEnabled, + extensions ) { this.urlTokenModel = $urlTokenModel this.scope = $scope + this.scope.reportingEnabled = reportingEnabled this.currentDataService = $currentDataService this.reportingService = $reportingService + this.scope.extensions = extensions this.tableResults = {} this.state = $state this.agent = agent this.currentDataService.addFilter( - `{"rule.groups":"oscap", "implicit":true}` + `{"rule.groups{}":"oscap", "implicit":true}` ) + + this.scope.expandArray = [ + false, + false, + false, + false, + false, + false, + false, + false, + false + ] + this.scope.expand = (i, id) => this.expand(i, id) if ( this.agent && this.agent.data && @@ -80,8 +97,8 @@ define([ 'dropDownInput', `${ this.filters - } sourcetype=wazuh rule.groups!="syslog" oscap.scan.profile.title=* | stats count by oscap.scan.profile.title | sort oscap.scan.profile.title ASC|fields - count`, - 'oscap.scan.profile.title', + } sourcetype=wazuh rule.groups{}!="syslog" data.oscap.scan.profile.title=* | stats count by data.oscap.scan.profile.title | sort data.oscap.scan.profile.title ASC|fields - count`, + 'data.oscap.scan.profile.title', '$form.profile$', 'dropDownInput', this.scope @@ -102,9 +119,9 @@ define([ `lastScapScore`, `${ this.filters - } sourcetype=wazuh oscap.scan.score=* | stats latest(oscap.scan.score)`, + } sourcetype=wazuh data.oscap.scan.score=* | stats latest(data.oscap.scan.score)`, `latestScapScore`, - '$result.latest(oscap.scan.score)$', + '$result.latest(data.oscap.scan.score)$', 'scapLastScore', this.submittedTokenModel, this.scope @@ -113,9 +130,9 @@ define([ `maxScapScore`, `${ this.filters - } sourcetype=wazuh oscap.scan.score=* | stats max(oscap.scan.score)`, + } sourcetype=wazuh data.oscap.scan.score=* | stats max(data.oscap.scan.score)`, `maxScapScore`, - '$result.max(oscap.scan.score)$', + '$result.max(data.oscap.scan.score)$', 'scapHighestScore', this.submittedTokenModel, this.scope @@ -124,9 +141,9 @@ define([ `scapLowest`, `${ this.filters - } sourcetype=wazuh oscap.scan.score=* | stats min(oscap.scan.score)`, + } sourcetype=wazuh data.oscap.scan.score=* | stats min(data.oscap.scan.score)`, `minScapScore`, - '$result.min(oscap.scan.score)$', + '$result.min(data.oscap.scan.score)$', 'scapLowestScore', this.submittedTokenModel, this.scope @@ -136,18 +153,18 @@ define([ * Visualizations */ new PieChart( - 'agentsVizz', + 'top5Scans', `${ this.filters - } sourcetype=wazuh oscap.check.result="fail" rule.groups!="syslog" oscap.scan.profile.title="$profile$" | top agent.name`, - 'agentsVizz', + } sourcetype=wazuh data.oscap.check.result="fail" rule.groups{}!="syslog" data.oscap.scan.profile.title="$profile$" | top limit=5 data.oscap.scan.id`, + 'top5Scans', this.scope ), new PieChart( 'profilesVizz', `${ this.filters - } sourcetype=wazuh oscap.check.result="fail" rule.groups!="syslog" oscap.scan.profile.title="$profile$" | top oscap.scan.profile.title`, + } sourcetype=wazuh data.oscap.check.result="fail" rule.groups{}!="syslog" data.oscap.scan.profile.title="$profile$" | top limit=5 data.oscap.scan.profile.title`, 'profilesVizz', this.scope ), @@ -155,7 +172,7 @@ define([ 'contentVizz', `${ this.filters - } sourcetype=wazuh oscap.check.result="fail" rule.groups!="syslog" oscap.scan.profile.title="$profile$" | top oscap.scan.content`, + } sourcetype=wazuh data.oscap.check.result="fail" rule.groups{}!="syslog" data.oscap.scan.profile.title="$profile$" | top limit=5 data.oscap.scan.content`, 'contentVizz', this.scope ), @@ -163,7 +180,7 @@ define([ 'severityVizz', `${ this.filters - } sourcetype=wazuh oscap.check.result="fail" rule.groups!="syslog" oscap.scan.profile.title="$profile$" | top oscap.check.severity`, + } sourcetype=wazuh data.oscap.check.result="fail" rule.groups{}!="syslog" data.oscap.scan.profile.title="$profile$" | top limit=5 data.oscap.check.severity`, 'severityVizz', this.scope ), @@ -171,51 +188,46 @@ define([ 'top5AgentsSHVizz', `${ this.filters - } sourcetype=wazuh oscap.scan.profile.title="$profile$" oscap.check.severity="high" | chart count by agent.name`, + } sourcetype=wazuh data.oscap.scan.profile.title="$profile$" data.oscap.check.severity="high" | chart count by agent.name`, 'top5AgentsSHVizz', this.scope ), new PieChart( - 'top10AleertsVizz', + 'top5AlertsVizz', `${ this.filters - } sourcetype=wazuh oscap.check.result="fail" rule.groups="oscap-result" oscap.scan.profile.title="$profile$" | top oscap.check.title`, - 'top10AleertsVizz', + } sourcetype=wazuh data.oscap.check.result="fail" rule.groups{}="oscap-result" data.oscap.scan.profile.title="$profile$" | top limit=5 data.oscap.check.title`, + 'top5AlertsVizz', this.scope ), new PieChart( - 'top10HRAlertsVizz', + 'top5HRAlertsVizz', `${ this.filters - } sourcetype=wazuh oscap.check.result="fail" rule.groups="oscap-result" oscap.check.severity="high" oscap.scan.profile.title="$profile$" | top oscap.check.title`, - 'top10HRAlertsVizz', + } sourcetype=wazuh data.oscap.check.result="fail" rule.groups{}="oscap-result" data.oscap.check.severity="high" data.oscap.scan.profile.title="$profile$" | top limit=5 data.oscap.check.title`, + 'top5HRAlertsVizz', this.scope ), new Table( 'alertsSummaryVizz', `${ this.filters - } sourcetype=wazuh oscap.check.result="fail" oscap.scan.profile.title="$profile$" | stats count by agent.name, oscap.check.title, oscap.scan.profile.title, oscap.scan.id, oscap.scan.content | sort count DESC | rename agent.name as "Agent name", oscap.check.title as Title, oscap.scan.profile.title as Profile, oscap.scan.id as "Scan ID", oscap.scan.content as Content`, + } sourcetype=wazuh data.oscap.check.result="fail" data.oscap.scan.profile.title="$profile$" | stats count by agent.name, data.oscap.check.title, data.oscap.scan.profile.title, data.oscap.scan.id, data.oscap.scan.content | sort count DESC | rename agent.name as "Agent name", data.oscap.check.title as Title, data.oscap.scan.profile.title as Profile, data.oscap.scan.id as "Scan ID", data.oscap.scan.content as Content`, 'alertsSummaryVizz', this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh data.oscap.check.result="fail" data.oscap.scan.profile.title="$profile$" | stats count by agent.name, data.oscap.check.title, data.oscap.scan.profile.title, data.oscap.scan.id, data.oscap.scan.content | sort count DESC | rename agent.name as "Agent name", data.oscap.check.title as Title, data.oscap.scan.profile.title as Profile, oscap.scan.id as "Scan ID", data.oscap.scan.content as Content`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' ) ] - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } sourcetype=wazuh oscap.check.result="fail" oscap.scan.profile.title="$profile$" | stats count by agent.name, oscap.check.title, oscap.scan.profile.title, oscap.scan.id, oscap.scan.content | sort count DESC | rename agent.name as "Agent name", oscap.check.title as Title, oscap.scan.profile.title as Profile, oscap.scan.id as "Scan ID", oscap.scan.content as Content`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) - - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) - // Set agent info try { this.agentReportData = { @@ -242,13 +254,13 @@ define([ 'Open SCAP', this.filters, [ - 'agentsVizz', + 'top5Scans', 'profilesVizz', 'contentVizz', 'severityVizz', 'top5AgentsSHVizz', - 'top10AleertsVizz', - 'top10HRAlertsVizz', + 'top5AlertsVizz', + 'top5HRAlertsVizz', 'alertsSummaryVizz' ], this.reportMetrics, @@ -268,6 +280,11 @@ define([ this.scope.loadingVizz = false this.setReportMetrics() } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) this.scope.loadingVizz = true } if (!this.scope.$$phase) this.scope.$digest() @@ -287,6 +304,7 @@ define([ * On controller loads */ $onInit() { + this.scope.loadingVizz = true this.scope.agent = this.agent && this.agent.data && this.agent.data.data ? this.agent.data.data @@ -333,6 +351,29 @@ define([ this.filters = this.currentDataService.getSerializedFilters() this.state.reload() } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('agentsOpenScapCtrl', AgentsOpenScap) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/virustotal/agents-virustotal.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/virustotal/agents-virustotal.html index 38964453e..a37e77b3f 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/virustotal/agents-virustotal.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/virustotal/agents-virustotal.html @@ -1,100 +1,122 @@ -
- -
+
+
Agents / - {{agent.name}} ({{agent.id}}) + {{agent.name}} ({{agent.id}}) Unknown agent / VirusTotal -
-
- {{formatAgentStatus(agent.status)}} + + {{formatAgentStatus(agent.status)}} +
- - - -
Waiting for reporting information
+
+ + + +
-
Generating report
- +
{{reportStatus}}
+ + + + + Vulnerabilities + Osquery + VirusTotal + Docker listener + + - -
- - - -
Files added: - {{filesAdded}} -
-
Files modified: - {{filesModified}} -
-
Files deleted: - {{filesDeleted}} -
-
-
-
- - -
- - - - VirusTotal alerts volume - -
-
-
- - - Events summary - -
-
-
-
- - -
- - - - Events over time - -
-
-
- - - Top 5 Rules - -
-
-
+ +
+
+ Fetching data...
+
- - -
- - - Files Affected - -
-
-
+
+ +
+ + + +
Files added: + {{filesAdded}} +
+
Files modified: + {{filesModified}} +
+
Files deleted: + {{filesDeleted}} +
+
+
+
+ + + +
+ + + + Last Scanned files + + + + + +
+
+
+ + + Malicious files alerts Evolution + + + + + +
+
+
+
+ + + +
+ + + Last Files + + + + + +
+
+
+
+
- - \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/virustotal/agentsVirusTotalCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/virustotal/agentsVirusTotalCtrl.js index 8395279a7..853fb034f 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/virustotal/agentsVirusTotalCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/virustotal/agentsVirusTotalCtrl.js @@ -5,7 +5,7 @@ define([ '../../../services/visualizations/chart/area-chart', '../../../services/visualizations/inputs/time-picker', '../../../services/rawTableData/rawTableDataService' -], function(app, PieChart, Table, AreaChart, TimePicker, rawTableDataService) { +], function(app, PieChart, Table, AreaChart, TimePicker, RawTableDataService) { 'use strict' class AgentsVirusTotal { @@ -25,18 +25,25 @@ define([ $scope, $currentDataService, agent, - $reportingService + $reportingService, + reportingEnabled, + extensions ) { this.state = $state this.currentDataService = $currentDataService this.reportingService = $reportingService this.tableResults = {} this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions //Add filer for VirusTotal this.currentDataService.addFilter( - `{"rule.groups":"virustotal", "implicit":true}` + `{"rule.groups{}":"virustotal", "implicit":true}` ) this.agent = agent + this.scope.expandArray = [false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + if ( this.agent && this.agent.data && @@ -56,11 +63,13 @@ define([ ) this.submittedTokenModel = this.urlTokenModel.getSubmittedTokenModel() - this.scope.$on('deletedFilter', () => { + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) @@ -68,91 +77,41 @@ define([ /** * Visualizations */ - new AreaChart( - 'eventsOverTimeElement', - `${this.filters} | timechart span=12h count by rule.id`, - 'eventsOverTimeElement', - this.scope - ), - new Table( - 'eventsSummaryElement', + + new PieChart( + 'lastScannedFiles', `${ this.filters - } | stats count sparkline by rule.description | sort count DESC | rename agent.name as Agent, rule.description as Description, count as Count`, - 'eventsSummaryElement', + } | top limit=5 data.virustotal.source.file`, + 'lastScannedFiles', this.scope ), - new Table( - 'top5Rules', - `${ - this.filters - } | stats count sparkline by rule.id, rule.description | sort count DESC | head 5 | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, - 'top5Rules', + new AreaChart( + 'maliciousEventsOverTimeElement', + `${this.filters} data.virustotal.positives="*" | timechart span=12h count by data.virustotal.positives`, + 'maliciousEventsOverTimeElement', this.scope ), - new PieChart( - 'alertsVolume', + new Table( + 'lastFiles', `${ this.filters - } | stats count by rule.description | rename "rule.description" as "Description"`, - 'alertsVolume', + } | stats count by data.virustotal.source.file,data.virustotal.permalink | sort count DESC | rename data.virustotal.source.file as File,data.virustotal.permalink as Link, count as Count`, + 'lastFiles', this.scope ), - new Table( - 'filesAffected', + new RawTableDataService( + 'lastFilesTable', `${ this.filters - } rule.level=12 | top data.virustotal.source.file | rename data.virustotal.source.file as "File" | fields - percent | fields - count`, - 'filesAffected', - this.scope + } | stats count by data.virustotal.source.file,data.virustotal.permalink as Count | sort count DESC | rename data.virustotal.source as File, data.virustotal.permalink as Link`, + 'lastFilesToken', + '$result$', + this.scope, + 'Last Files' ) ] - this.eventsSummaryTable = new rawTableDataService( - 'eventsSummaryTable', - `${ - this.filters - } | stats count sparkline by rule.description | sort count DESC | rename agent.name as Agent, rule.description as Description, count as Count`, - 'eventsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.eventsSummaryTable) - - this.eventsSummaryTable.getSearch().on('result', result => { - this.tableResults['Events Summary'] = result - }) - - this.top5RulesTable = new rawTableDataService( - 'top5RulesTable', - `${ - this.filters - } | stats count sparkline by rule.id, rule.description | sort count DESC | head 5 | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, - 'top5RulesTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.top5RulesTable) - - this.top5RulesTable.getSearch().on('result', result => { - this.tableResults['Top 5 Rules'] = result - }) - - this.filesAffectedTable = new rawTableDataService( - 'filesAffectedTable', - `${ - this.filters - } rule.level=12 | top data.virustotal.source.file | rename data.virustotal.source.file as "File" | fields - percent | fields - count`, - 'filesAffectedTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.filesAffectedTable) - - this.filesAffectedTable.getSearch().on('result', result => { - this.tableResults['Files Affected'] = result - }) - // Set agent info try { this.agentReportData = { @@ -179,11 +138,9 @@ define([ 'VirusTotal', this.filters, [ - 'alertsVolume', - 'eventsSummaryElement', - 'eventsOverTimeElement', - 'top5Rules', - 'filesAffected' + 'lastScannedFiles', + 'maliciousEventsOverTimeElement', + 'lastFiles', ], this.reportMetrics, this.tableResults, @@ -202,6 +159,11 @@ define([ this.scope.loadingVizz = false this.setReportMetrics() } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) this.scope.loadingVizz = true } if (!this.scope.$$phase) this.scope.$digest() @@ -220,6 +182,7 @@ define([ * On controller loads */ $onInit() { + this.scope.loadingVizz = true this.scope.agent = this.agent && this.agent.data && this.agent.data.data ? this.agent.data.data @@ -251,6 +214,29 @@ define([ 'Files deleted': this.scope.filesDeleted } } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('agentsVirusTotalCtrl', AgentsVirusTotal) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/vulnerabilities/agents-vulnerabilities.html b/SplunkAppForWazuh/appserver/static/js/controllers/agents/vulnerabilities/agents-vulnerabilities.html index 23e47f71e..c3e0b962d 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/vulnerabilities/agents-vulnerabilities.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/vulnerabilities/agents-vulnerabilities.html @@ -1,102 +1,154 @@ -
- -
+
+
Agents / - {{agent.name}} ({{agent.id}}) + {{agent.name}} ({{agent.id}}) Unknown agent / Vulnerabilities -
-
- {{formatAgentStatus(agent.status)}} + + {{formatAgentStatus(agent.status)}} +
- - - -
Waiting for reporting information
+
+ + + +
-
Generating report
+
{{reportStatus}}
+ + + + Vulnerabilities + + Osquery + VirusTotal + Docker listener + - -
- - -
Critical severity alerts: - -
-
High severity alerts: - -
-
Medium severity alerts: - -
-
Low severity alerts: - -
-
-
-
- - - -
- - - Alerts severity over time - -
-
-
- - - Most common rules - -
-
-
-
-
- - - Most common CVEs - -
-
-
- - - Severity distribution - -
-
-
- - - Commonly affected packages - -
-
-
+ +
+
+ Fetching data...
+
-
- - - Alerts summary - -
-
-
+
+ +
+ + +
Critical severity alerts: + +
+
High severity alerts: + +
+
Medium severity alerts: + +
+
Low severity alerts: + +
+
+
+
+ + + +
+ + + Alerts severity over time + + + + + +
+
+
+ + + Most common rules + + + + + +
+
+
+
+
+ + + Most common CVEs + + + + + +
+
+
+ + + Severity distribution + + + + + +
+
+
+ + + Commonly affected packages + + + + + +
+
+
+
+
+ + + Alerts summary + + + + + +
+
+
+
- \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/agents/vulnerabilities/agentsVulnerabilitiesCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/agents/vulnerabilities/agentsVulnerabilitiesCtrl.js index a2e27282b..48c015b74 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/agents/vulnerabilities/agentsVulnerabilitiesCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/agents/vulnerabilities/agentsVulnerabilitiesCtrl.js @@ -25,7 +25,7 @@ define([ Table, TimePicker, SearchHandler, - rawTableDataService + RawTableDataService ) { 'use strict' @@ -46,15 +46,25 @@ define([ $currentDataService, $state, agent, - $reportingService + $reportingService, + reportingEnabled, + extensions ) { this.urlTokenModel = $urlTokenModel this.scope = $scope + ;(this.scope.reportingEnabled = reportingEnabled), + (this.scope.extensions = extensions) this.currentDataService = $currentDataService + this.currentDataService.addFilter( + `{"rule.groups{}":"vulnerability-detector", "implicit":true, "onlyShow":true}` + ) this.reportingService = $reportingService this.tableResults = {} this.state = $state this.agent = agent + this.scope.expandArray = [false, false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + if ( this.agent && this.agent.data && @@ -74,11 +84,13 @@ define([ ) this.submittedTokenModel = this.urlTokenModel.getSubmittedTokenModel() - this.scope.$on('deletedFilter', () => { + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) @@ -129,7 +141,7 @@ define([ 'alertsSeverityOverTimeVizz', `${ this.filters - } sourcetype=wazuh rule.groups=vulnerability-detector data.vulnerability.severity=* | timechart count by data.vulnerability.severity`, + } sourcetype=wazuh rule.groups{}=vulnerability-detector data.vulnerability.severity=* | timechart count by data.vulnerability.severity`, 'alertsSeverityOverTimeVizz', this.scope ), @@ -137,7 +149,7 @@ define([ 'commonRules', `${ this.filters - } rule.groups="vulnerability-detector" | top rule.id,rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule Description", count as Count, percent as Percent`, + } rule.groups{}="vulnerability-detector" | top rule.id,rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule Description", count as Count, percent as Percent`, 'commonRules', this.scope ), @@ -145,7 +157,7 @@ define([ 'commonCves', `${ this.filters - } rule.groups="vulnerability-detector" | top data.vulnerability.cve limit=5`, + } rule.groups{}="vulnerability-detector" | top data.vulnerability.cve limit=5`, 'commonCves', this.scope ), @@ -153,7 +165,7 @@ define([ 'severityDistribution', `${ this.filters - } rule.groups="vulnerability-detector" | top data.vulnerability.severity limit=5`, + } rule.groups{}="vulnerability-detector" | top data.vulnerability.severity limit=5`, 'severityDistribution', this.scope ), @@ -167,42 +179,32 @@ define([ 'alertsSummaryVizz', `${ this.filters - } | stats count sparkline by data.vulnerability.title, data.vulnerability.severity | rename data.vulnerability.title as Title, data.vulnerability.severity as Severity, count as Count, sparkline as Sparkline `, + } | stats count sparkline by data.vulnerability.title, data.vulnerability.severity | sort count DESC | rename data.vulnerability.title as Title, data.vulnerability.severity as Severity, count as Count, sparkline as Sparkline `, 'alertsSummaryVizz', this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } | stats count sparkline by data.vulnerability.title | rename data.vulnerability.title as Title, count as Count, sparkline as Sparkline`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' + ), + new RawTableDataService( + 'commonRulesTable', + `${ + this.filters + } rule.groups{}="vulnerability-detector" | top rule.id,rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule description", count as Count, percent as Percent`, + 'commonRulesTableToken', + '$result$', + this.scope, + 'Common Rules' ) ] - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } | stats count sparkline by data.vulnerability.title | rename data.vulnerability.title as Title, count as Count, sparkline as Sparkline`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) - - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) - - this.commonRulesTable = new rawTableDataService( - 'commonRulesTable', - `${ - this.filters - } rule.groups="vulnerability-detector" | top rule.id,rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule description", count as Count, percent as Percent`, - 'commonRulesTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.commonRulesTable) - - this.commonRulesTable.getSearch().on('result', result => { - this.tableResults['Common Rules'] = result - }) - // Set agent info try { this.agentReportData = { @@ -253,6 +255,11 @@ define([ this.scope.loadingVizz = false this.setReportMetrics() } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) this.scope.loadingVizz = true } if (!this.scope.$$phase) this.scope.$digest() @@ -271,6 +278,7 @@ define([ * On controller loads */ $onInit() { + this.scope.loadingVizz = true this.scope.agent = this.agent && this.agent.data && this.agent.data.data ? this.agent.data.data @@ -318,6 +326,29 @@ define([ 'Low severity alerts': this.scope.lowSeverity } } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('agentsVulnerabilitiesCtrl', AgentsVulnerabilities) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/dev-tools/dev-tools.html b/SplunkAppForWazuh/appserver/static/js/controllers/dev-tools/dev-tools.html index 89505cbc3..6734384cb 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/dev-tools/dev-tools.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/dev-tools/dev-tools.html @@ -1,18 +1,29 @@ -
+
- Console Console
︙
- - + + + + +
diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/dev-tools/devToolsCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/dev-tools/devToolsCtrl.js index e49db1e4f..557f3a96f 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/dev-tools/devToolsCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/dev-tools/devToolsCtrl.js @@ -22,7 +22,8 @@ define([ '../../libs/codemirror-conv/mark-selection', '../../libs/codemirror-conv/show-hint', '../../libs/codemirror-conv/querystring-browser/bundle', - '../../utils/excluded-devtools-autocomplete-keys' + '../../utils/excluded-devtools-autocomplete-keys', + 'FileSaver' ], function( app, $, @@ -63,13 +64,14 @@ define([ this.request = $requestService this.$window = $window this.appState = $navigationService - this.toast = $notificationService.showSimpleToast + this.notification = $notificationService this.$document = $document this.groups = [] this.linesWithClass = [] this.widgets = [] + this.multipleKeyPressed = [] try { - this.admin = extensions['admin'] === 'true' ? true : false + this.admin = extensions['admin'] === 'true' } catch (err) { this.admin = false } @@ -79,71 +81,109 @@ define([ * When controller loads */ $onInit() { - this.apiInputBox = CodeMirror.fromTextArea( - this.$document[0].getElementById('api_input'), - { - lineNumbers: true, - matchBrackets: true, - mode: { name: 'javascript', json: true }, - theme: 'ttcn', - foldGutter: true, - styleSelectedText: true, - gutters: ['CodeMirror-foldgutter'] - } - ) - // Register plugin for code mirror - CodeMirror.commands.autocomplete = function(cm) { - CodeMirror.showHint(cm, CodeMirror.hint.dictionaryHint, { - completeSingle: false + try { + $(this.$document[0]).keydown(e => { + if (!this.multipleKeyPressed.includes(e.which)) { + this.multipleKeyPressed.push(e.which) + } + if ( + this.multipleKeyPressed.includes(13) && + this.multipleKeyPressed.includes(16) && + this.multipleKeyPressed.length === 2 + ) { + e.preventDefault() + return this.send() + } }) - } - this.apiInputBox.on('change', () => { - this.groups = this.analyzeGroups() - const currentState = this.apiInputBox.getValue().toString() - this.appState.setCurrentDevTools(currentState) - const currentGroup = this.calculateWhichGroup() - if (currentGroup) { - const hasWidget = this.widgets.filter( - item => item.start === currentGroup.start - ) - if (hasWidget.length) - this.apiInputBox.removeLineWidget(hasWidget[0].widget) - setTimeout(() => this.checkJsonParseError(), 150) + // eslint-disable-next-line + $(this.$document[0]).keyup(e => { + this.multipleKeyPressed = [] + }) + this.apiInputBox = CodeMirror.fromTextArea( + this.$document[0].getElementById('api_input'), + { + lineNumbers: true, + matchBrackets: true, + mode: { name: 'javascript', json: true }, + theme: 'ttcn', + foldGutter: true, + styleSelectedText: true, + gutters: ['CodeMirror-foldgutter'] + } + ) + // Register plugin for code mirror + CodeMirror.commands.autocomplete = function(cm) { + CodeMirror.showHint(cm, CodeMirror.hint.dictionaryHint, { + completeSingle: false + }) } - }) - this.apiInputBox.on('cursorActivity', () => { - const currentGroup = this.calculateWhichGroup() - this.highlightGroup(currentGroup) - this.checkJsonParseError() - }) - - this.apiOutputBox = CodeMirror.fromTextArea( - this.$document[0].getElementById('api_output'), - { - lineNumbers: true, - matchBrackets: true, - mode: { name: 'javascript', json: true }, - readOnly: true, - lineWrapping: true, - styleActiveLine: true, - theme: 'ttcn', - foldGutter: true, - gutters: ['CodeMirror-foldgutter'] - } - ) + this.apiInputBox.on('change', () => { + this.groups = this.analyzeGroups() + const currentState = this.apiInputBox.getValue().toString() + this.appState.setCurrentDevTools(currentState) + const currentGroup = this.calculateWhichGroup() + if (currentGroup) { + const hasWidget = this.widgets.filter( + item => item.start === currentGroup.start + ) + if (hasWidget.length) + this.apiInputBox.removeLineWidget(hasWidget[0].widget) + setTimeout(() => this.checkJsonParseError(), 150) + } + }) - this.$scope.send = firstTime => this.send(firstTime) + this.apiInputBox.on('cursorActivity', () => { + const currentGroup = this.calculateWhichGroup() + this.highlightGroup(currentGroup) + this.checkJsonParseError() + }) - this.$scope.help = () => { - this.$window.open( - 'https://documentation.wazuh.com/current/user-manual/api/reference.html' + this.apiOutputBox = CodeMirror.fromTextArea( + this.$document[0].getElementById('api_output'), + { + lineNumbers: true, + matchBrackets: true, + mode: { name: 'javascript', json: true }, + readOnly: true, + lineWrapping: true, + styleActiveLine: true, + theme: 'ttcn', + foldGutter: true, + gutters: ['CodeMirror-foldgutter'] + } ) + + this.$scope.send = firstTime => this.send(firstTime) + + this.$scope.help = () => { + this.$window.open( + 'https://documentation.wazuh.com/current/user-manual/api/reference.html' + ) + } + + this.init() + this.$scope.send(true) + this.$scope.exportOutput = () => this.exportOutput() + } catch (error) { + this.notification.showErrorToast(error) } + } - this.init() - this.$scope.send(true) + /** + * Exports results in JSON format + */ + exportOutput() { + try { + // eslint-disable-next-line + const blob = new Blob([this.apiOutputBox.getValue()], { + type: 'application/json' + }) + saveAs(blob, 'export.json') // eslint-disable-line + } catch (error) { + this.notification.showErrorToast(error.message || error) + } } /** @@ -160,7 +200,7 @@ define([ .filter(item => item.replace(/\s/g, '').length) let start = 0 let end = 0 - + let starts = [] const slen = splitted.length for (let i = 0; i < slen; i++) { let tmp = splitted[i].split('\n') @@ -172,6 +212,26 @@ define([ if (cursor.findNext()) start = cursor.from().line else return [] + /** + * Prevents from user frustation when there are duplicated queries. + * We want to look for the next query when available, even if it + * already exists but it's not the selected query. + */ + if (tmp.length) { + // It's a safe loop since findNext method returns null if there is no next query. + while ( + this.apiInputBox.getLine(cursor.from().line) !== tmp[0] && + cursor.findNext() + ) { + start = cursor.from().line + } + // It's a safe loop since findNext method returns null if there is no next query. + while (starts.includes(start) && cursor.findNext()) { + start = cursor.from().line + } + } + starts.push(start) + end = start + tmp.length const tmpRequestText = tmp[0] @@ -210,7 +270,7 @@ define([ end }) } - + starts = [] return tmpgroups } catch (error) { return [] @@ -547,23 +607,32 @@ define([ for (const key in extra) JSONraw[key] = extra[key] const path = req.includes('?') ? req.split('?')[0] : req //if (typeof JSONraw === 'object') JSONraw.devTools = true - const output = await this.request.apiReq(path, JSONraw, method) - const result = - output.data && output.data.data && !output.data.error - ? JSON.stringify((output || {}).data, null, 2) + if (!firstTime) { + const output = await this.request.apiReq(path, JSONraw, method) + const result = output.data + ? JSON.stringify((output || {}).data || {}, null, 2).replace( + /\\\\/g, + '\\' + ) : output.data.message || 'Unkown error' - this.apiOutputBox.setValue(result) - } else { - this.apiOutputBox.setValue('Welcome!') + this.apiOutputBox.setValue(result) + } } + ;(firstTime || !desiredGroup) && this.apiOutputBox.setValue('Welcome!') // eslint-disable-line } catch (error) { - const parsedError = this.toast(error) - if (typeof parsedError === 'string') { - return this.apiOutputBox.setValue(parsedError) - } else if (error && error.data && typeof error.data === 'object') { - return this.apiOutputBox.setValue(JSON.stringify(error.data)) + if ((error || {}).status === -1) { + return this.apiOutputBox.setValue( + "Wazuh API don't reachable. Reason: timeout." + ) } else { - return this.apiOutputBox.setValue('Empty') + this.notification.showErrorToast(error) + if (typeof error === 'string') { + return this.apiOutputBox.setValue(error) + } else if (error && error.data && typeof error.data === 'object') { + return this.apiOutputBox.setValue(JSON.stringify(error)) + } else { + return this.apiOutputBox.setValue('Empty') + } } } } diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/discover/discover.html b/SplunkAppForWazuh/appserver/static/js/controllers/discover/discover.html index 038180159..a7be7bc21 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/discover/discover.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/discover/discover.html @@ -1,26 +1,58 @@ - + +
+
+
- +
+
+ +
+ {{breadcrumbs.section}} + / {{breadcrumbs.agentName}} ({{breadcrumbs.agentId}}) + / {{breadcrumbs.subSection}} + / {{breadcrumbs.subSection}} +
+ +
+ +  Dashboard + + Back to the dashboard. + + +
+
+ + +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/discover/discoverCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/discover/discoverCtrl.js new file mode 100644 index 000000000..93566af5e --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/discover/discoverCtrl.js @@ -0,0 +1,132 @@ +define(['../module', 'jquery'], function(app, $) { + 'use strict' + + class Discover { + /** + * Class Discover + */ + constructor( + $scope, + $state, + $stateParams, + $document, + $currentDataService, + $notificationService + ) { + this.scope = $scope + this.state = $state + this.stateParams = $stateParams + this.iframe = $($document[0]).find('#searchAndReporting') + this.scope.loadingRing = true + this.currentDataService = $currentDataService + this.notification = $notificationService + } + + /** + * On controller loads + */ + $onInit() { + try { + this.scope.fromDashboard = this.stateParams.fromDashboard + this.scope.breadcrumbs = this.stateParams.breadcrumbs + this.loadIframeContent() + this.scope.backToDashboard = () => this.backToDashboard() + + this.scope.$on('loading', (event, data) => { + if (data.status === true) { + this.scope.loadingRing = true + if (!this.scope.$$phase) this.scope.$digest() + } + }) + } catch (error) { + this.notification.showErrorToast('Cannot load discover.') + } + } + + loadIframeContent() { + try { + const url = localStorage.getItem('urlDiscover') + this.iframe.attr('src', url) + const interval = setInterval(() => { + if (this.iframe.contents().find('header')) { + const header = this.iframe.contents().find('header') + header.hide() + if (header.is(':hidden')) { + clearInterval(interval) + this.scope.loadingRing = false + if (!this.scope.$$phase) this.scope.$digest() + } + } + }, 500) + } catch (error) { + throw new Error(error) + } + } + + backToDashboard() { + try { + //Get the filters + const filters = this.fetchWrittenFilters() + //Add the filters + filters.map(fil => { + this.currentDataService.addFilter(fil) + }) + //Back to the dashboard + this.state.go(this.stateParams.previousState) + } catch (error) { + this.notification.showErrorToast(error) + } + } + + fetchWrittenFilters() { + try { + let filtersFormatted = [] + //Delete the last div of the input, this div contains a hidden string that is not needed + const divX = this.iframe + .contents() + .find('.search-field-wrapper pre div:last') + divX.remove() + //Get the filters + let filtersStr = this.iframe + .contents() + .find('.search-field-wrapper') + .text() + filtersStr = filtersStr + .split('|', 1) + .toString() + .trim() + const filtersArr = filtersStr.split(' ') + //Format the filters + filtersArr.map(fil => { + const f = fil.split('=') + const key = this.cleanQuotes(f[0]) + const value = this.cleanQuotes(f[1]) + filtersFormatted.push(`{"${key}":"${value}"}`) + }) + return filtersFormatted + } catch (error) { + return [] + } + } + + cleanQuotes(str) { + try { + const firstChar = str.substring(0, 1) + const lastChar = str.substring(str.length - 1) + if ( + firstChar === '"' || + (firstChar === "'" && lastChar === '"') || + lastChar === "'" + ) { + const cleanStr = str.substring(1, str.length - 1) + return cleanStr + } else { + return str + } + } catch (error) { + return str + } + } + } + app.controller('discoverCtrl', Discover) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/index.js b/SplunkAppForWazuh/appserver/static/js/controllers/index.js index 30942f149..cf0432027 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/index.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/index.js @@ -10,5 +10,7 @@ define([ //Dev-tools './dev-tools/devToolsCtrl', // Main - './main/mainCtrl' + './main/mainCtrl', + //Discover + './discover/discoverCtrl' ], function() {}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/cdb/manager-cdb-id.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/cdb/manager-cdb-id.html new file mode 100644 index 000000000..38d669625 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/cdb/manager-cdb-id.html @@ -0,0 +1,190 @@ +
+
+
+ Management + / Ruleset + / CDB Lists + / {{currentList.details.file}} +
+
+
+
+ + + + Rules + + Decoders + + Lists + + + + +
+ + + + + Back to CDB lists + + + {{currentList.details.file}} +
+ + +
+ + +
Name: audit-keys
+
Path: etc/lists
+
+
+
+ +
+ +
+ + + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + +
KeyValueActions
+ + + + + +
{{item[0]}} +
+ +
+
+ {{item[1]}} +
+
+
+ + + + + Cancel + + + + + Apply + + + + +
+
+ This entry will be + removed +
+
+ Cancel + Confirm +
+
+
+
+ {{ totalItems }} items + +
+
+ +
+
+
+
+
+ +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/cdb/manager-cdb.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/cdb/manager-cdb.html new file mode 100644 index 000000000..579b89d25 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/cdb/manager-cdb.html @@ -0,0 +1,216 @@ +
+
+
+ Management + / Ruleset + / CDB Lists +
+
+
+
+
+ + + + Rules + Decoders + Lists + + +
+
+
+
+ + +
+
+
+ + + Add new list + + + + + + File: {{getFilter('file')}} + + + + + Path: {{getFilter('path')}} + + + + + Level: {{getFilter('level')}} + + + + + Group: {{getFilter('group')}} + + + + + PCI control: {{getFilter('pci')}} + + + + + GDPR: {{getFilter('gdpr')}} + + + + +
+ + +
+ +
+
+
+ + +
+ +
+
+ +
+ + + + +
+ + + +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
KeyValueActions
+ + + + + +
{{item[0]}} +
+ +
+
+ {{item[1]}} +
+
+
+ + + + + Cancel + + + + + Apply + + + + + + +
+
+ This entry will be + removed +
+
+ Cancel + Confirm +
+
+
+
+ {{ totalItems }} items + +
+
+
+
+
+
+ +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/cdb/managerCdbCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/cdb/managerCdbCtrl.js new file mode 100644 index 000000000..036015267 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/cdb/managerCdbCtrl.js @@ -0,0 +1,370 @@ +define([ + '../../module', + '../rules/ruleset', + '../../../directives/wz-table/lib/pagination', + '../../../directives/wz-table/lib/check-gap' +], function(controllers, Ruleset, pagination, checkGap) { + 'use strict' + class CDBList extends Ruleset { + /** + * Class cdb + * @param {*} $scope + * @param {*} $sce + * @param {*} $notificationService + * @param {*} $currentDataService + * @param {*} $tableFilterService + * @param {*} $csvRequestService + */ + constructor( + $scope, + $sce, + $notificationService, + $currentDataService, + $tableFilterService, + $csvRequestService, + isAdmin, + $cdbEditor, + $restartService + ) { + super( + $scope, + $sce, + $notificationService, + 'cbd', + $currentDataService, + $tableFilterService, + $csvRequestService, + $restartService + ) + this.pagination = pagination + this.checkGap = checkGap + this.isAdmin = isAdmin + this.cdbEditor = $cdbEditor + this.restartService = $restartService + } + + /** + * On controller load + */ + $onInit() { + this.scope.overwrite = false + this.scope.downloadCsv = (path, name) => this.downloadCsv(path, name) + this.scope.$broadcast('wazuhSearch', { term: '', removeFilters: true }) + this.scope.selectedNavTab = 'cdbList' + this.scope.adminMode = this.isAdmin + + /** + * Functions to edit a CDB lists binded to the scope + */ + this.scope.addEntry = (key, value) => this.addEntry(key, value) + this.scope.setEditingKey = (key, value) => this.setEditingKey(key, value) + this.scope.cancelEditingKey = () => this.cancelEditingKey() + this.scope.showConfirmRemoveEntry = (ev, key) => + this.showConfirmRemoveEntry(ev, key) + this.scope.editKey = (key, value) => this.editKey(key, value) + this.scope.cancelRemoveEntry = () => this.cancelRemoveEntry() + this.scope.confirmRemoveEntry = key => this.confirmRemoveEntry(key) + this.scope.cancelCdbListEdition = () => this.cancelCdbListEdition() + this.scope.addNewFile = () => this.addNewFile() + this.scope.saveList = () => this.saveList() + this.scope.enableSave = () => this.enableSave() + + /** + * Pagination variables and functions + */ + this.scope.items = this.cdbToArr() + this.contentToFilter = this.scope.items + this.scope.totalItems = this.scope.items.length + this.scope.itemsPerPage = 10 + this.scope.pagedItems = [] + this.scope.currentPage = 0 + this.scope.gap = 0 + this.scope.searchTable = () => + this.pagination.searchTable(this.scope, this.scope.items) + this.scope.groupToPages = () => this.pagination.groupToPages(this.scope) + //this.initPagination() + this.scope.range = (size, start, end) => + this.pagination.range(size, start, end, this.scope.gap) + this.scope.prevPage = () => this.pagination.prevPage(this.scope) + this.scope.nextPage = async currentPage => + this.pagination.nextPage( + currentPage, + this.scope, + this.notification, + null + ) + this.scope.setPage = n => { + this.scope.currentPage = n + this.scope.nextPage(n) + } + this.scope.filterContent = filter => this.filterContent(filter) + + this.scope.restart = () => this.restart() + this.scope.closeRestartConfirmation = () => + this.closeRestartConfirmation() + + this.scope.$on('loadedTable', event => { + event.stopPropagation() + try { + if (window.localStorage.cdb) { + const parsedFilter = JSON.parse(window.localStorage.cdb) + this.scope.appliedFilters = parsedFilter + if (this.filter.length > 0) { + this.scope.$broadcast('wazuhFilter', { filter: this.filter }) + } + } + } catch (err) { + this.notification.showErrorToast('Error applying filter') + } + }) + } + + /** + * Filters the content of CDB lists + * @param {*} filter + */ + async filterContent(filter) { + this.scope.items = this.filter('filter')(this.contentToFilter, filter) + this.initPagination() + } + + /** + * Adds new CDB list file + */ + addNewFile() { + try { + this.scope.overwrite = false + this.scope.addingNewFile = true + this.scope.currentList = { + list: {}, + details: { + file: '', + path: 'etc/lists' + } + } + } catch (error) { + this.notification.showErrorToast('Cannot add new CDB list file.') + } + } + + /** + * Cancels CDB list edition + */ + cancelCdbListEdition() { + this.scope.currentList = false + this.scope.addingNewFile = false + this.scope.items = null + this.scope.totalItems = null + this.scope.pagedItems = null + this.scope.currentPage = 0 + this.scope.gap = 0 + this.cancelEditingKey() + } + + /** + * Adds new entry field + * @param {String} key + * @param {String} value + */ + async addEntry(key, value) { + try { + if (!key) { + this.notification.showWarningToast('Cannot send empty fields.') + } else { + if (!this.scope.currentList.list[key]) { + value = value ? value : '' + this.scope.currentList.list[key] = value + this.scope.newKey = '' + this.scope.newValue = '' + this.refreshCdbList() + } else { + this.notification.showErrorToast( + 'Error adding new entry, the key exists.' + ) + } + } + } catch (error) { + this.notification.showErrorToast('Error adding entry.') + } + } + + /** + * Enable edition for a given key + * @param {String} key Entry key + */ + setEditingKey(key, value) { + this.scope.editingKey = key + this.scope.editingNewValue = value + } + + /** + * Cancel edition of an entry + */ + cancelEditingKey() { + this.scope.editingKey = false + this.scope.editingNewValue = '' + } + + /** + * Shows confirmation to remove a field + * @param {*} ev + * @param {String} key + */ + showConfirmRemoveEntry(ev, key) { + this.scope.removingEntry = key + } + + /** + * Sets a new value for a field + * @param {String} key + * @param {String} newValue + */ + async editKey(key, newValue) { + try { + this.scope.currentList.list[key] = newValue + this.cancelEditingKey() + this.refreshCdbList() + } catch (error) { + this.notification.showErrorToast('Error editing value.') + } + } + + /** + * Cancels the removing of a entry + */ + cancelRemoveEntry() { + this.scope.removingEntry = false + } + + /** + * Confirms if wants to remove a entry + * @param {String} key + */ + async confirmRemoveEntry(key) { + try { + delete this.scope.currentList.list[key] + this.scope.removingEntry = false + this.refreshCdbList() + } catch (error) { + this.notification.showErrorToast('Error deleting entry.') + } + } + + /** + * Refreshs CDB list fields + */ + refreshCdbList() { + this.scope.items = this.cdbToArr() + this.initPagination() + this.scope.$applyAsync() + } + + /** + * Saves the CDB list content + */ + async saveList() { + try { + const constainsBlanks = /.* .*/ + const fileName = this.scope.currentList.details.file + if (fileName) { + if (constainsBlanks.test(fileName)) { + this.notification.showErrorToast( + 'Error creating a new file. The filename can not contain white spaces.' + ) + } else { + this.scope.saveIncomplete = true + const path = this.scope.currentList.details.path + const content = this.objToString(this.scope.currentList.list) + const result = await this.cdbEditor.sendConfiguration( + fileName, + path, + content + ) + if (result && result.data && result.data.error === 0) { + this.notification.showSuccessToast('File saved successfully.') + this.scope.saveIncomplete = false + this.scope.$applyAsync() + } else if (result.data.error === 1905) { + this.notification.showWarningToast( + result.data.message || 'File already exists.' + ) + this.scope.overwrite = true + this.scope.saveIncomplete = false + this.scope.$applyAsync() + } else { + throw new Error(result.data.message || 'Cannot send this file.') + } + } + } else { + this.notification.showWarningToast( + 'Please set a name for the new CDB list.' + ) + } + } catch (error) { + this.scope.saveIncomplete = false + this.notification.showErrorToast(error) + } + } + + /** + * Enables save button + */ + enableSave() { + this.scope.overwrite = false + } + + /** + * Converts string to object + * @param {String} string + */ + stringToObj(string) { + let result = {} + const splitted = string.split('\n') + splitted.forEach(element => { + const keyValue = element.split(':') + if (keyValue[0]) result[keyValue[0]] = keyValue[1] + }) + return result + } + + /** + * Converts object to string + * @param {Object} obj + */ + objToString(obj) { + let raw = '' + for (var key in obj) { + raw = raw.concat(`${key}:${obj[key]}\n`) + } + return raw + } + + /** + * Converts objecto to array + */ + cdbToArr() { + try { + const obj = this.scope.currentList.list + let items = [] + for (var property in obj) { + let o = [property, obj[property]] + items.push(o) + } + return items + } catch (error) { + return [] + } + } + + /** + * Init the table pagination + */ + initPagination() { + this.scope.totalItems = this.scope.items.length + this.checkGap(this.scope, this.scope.items) + this.scope.searchTable() + } + } + controllers.controller('managerCdbCtrl', CDBList) + return CDBList +}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/cdb/managerCdbIdCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/cdb/managerCdbIdCtrl.js new file mode 100644 index 000000000..6a4093c9b --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/cdb/managerCdbIdCtrl.js @@ -0,0 +1,278 @@ +define([ + '../../module', + '../rules/ruleset', + '../../../directives/wz-table/lib/pagination', + '../../../directives/wz-table/lib/check-gap' +], function(controllers, Ruleset, pagination, checkGap) { + 'use strict' + class CdbListId extends Ruleset { + /** + * Class CdbList-ID + * @param {*} $scope + * @param {*} $sce + * @param {*} $notificationService + * @param {*} $state + * @param {*} $currentDataService + * @param {*} $tableFilterService + * @param {*} $csvRequestService + */ + constructor( + $scope, + $sce, + $notificationService, + $state, + $currentDataService, + $tableFilterService, + $csvRequestService, + isAdmin, + $cdbEditor, + cdbInfo, + $restartService + ) { + super( + $scope, + $sce, + $notificationService, + 'cdb', + $currentDataService, + $tableFilterService, + $csvRequestService, + $restartService + ) + this.state = $state + this.isAdmin = isAdmin + this.cdbEditor = $cdbEditor + this.cdbInfo = cdbInfo + this.notification = $notificationService + this.pagination = pagination + this.checkGap = checkGap + this.restartService = $restartService + try { + this.filters = JSON.parse(window.localStorage.cdb) || [] + } catch (err) { + this.filters = [] + } + } + + /** + * On controller load + */ + $onInit() { + try { + this.scope.downloadCsv = (path, name) => this.downloadCsv(path, name) + this.scope.addDetailFilter = (name, value) => + this.addDetailFilter(name, value) + + //Scope methods + this.scope.addEntry = (key, value) => this.addEntry(key, value) + this.scope.setEditingKey = (key, value) => + this.setEditingKey(key, value) + this.scope.cancelEditingKey = () => this.cancelEditingKey() + this.scope.showConfirmRemoveEntry = (ev, key) => + this.showConfirmRemoveEntry(ev, key) + this.scope.editKey = (key, value) => this.editKey(key, value) + this.scope.cancelRemoveEntry = () => this.cancelRemoveEntry() + this.scope.confirmRemoveEntry = key => this.confirmRemoveEntry(key) + this.scope.firstPage = () => this.firstPage() + + // Edit cdb lists + this.scope.currentList = { + details: { + file: this.cdbInfo.file, + path: this.cdbInfo.path + } + } + this.cdbInfo.content = this.stringToObj(this.cdbInfo.content) + + this.scope.currentList.list = this.cdbInfo.content + this.scope.adminMode = this.isAdmin + this.scope.saveList = () => this.saveList() + + /** + * Pagination variables and functions + */ + this.scope.items = this.cdbToArr() + this.contentToFilter = this.scope.items + this.scope.totalItems = this.scope.items.length + this.scope.itemsPerPage = 10 + this.scope.pagedItems = [] + this.scope.currentPage = 0 + this.scope.gap = 0 + this.scope.searchTable = () => + this.pagination.searchTable(this.scope, this.scope.items) + this.scope.groupToPages = () => this.pagination.groupToPages(this.scope) + this.initPagination() + this.scope.range = (size, start, end) => + this.pagination.range(size, start, end, this.scope.gap) + this.scope.prevPage = () => this.pagination.prevPage(this.scope) + this.scope.nextPage = async currentPage => + this.pagination.nextPage( + currentPage, + this.scope, + this.notification, + null + ) + this.scope.setPage = n => { + this.scope.currentPage = n + this.scope.nextPage(n) + } + + this.scope.restart = () => this.restart() + this.scope.closeRestartConfirmation = () => + this.closeRestartConfirmation() + } catch (error) { + this.notification.showErrorToast('Error editing CDB list') + } + } + + async fetchFile(fileName, path) { + try { + const result = await this.cdbEditor.getConfiguration(fileName, path) + return result + } catch (error) { + return Promise.reject(error) + } + } + + async addEntry(key, value) { + try { + if (!key) { + this.notification.showWarningToast('Cannot send empty fields.') + } else { + if (!this.scope.currentList.list[key]) { + value = value ? value : '' + this.scope.currentList.list[key] = value + this.scope.newKey = '' + this.scope.newValue = '' + this.refreshCdbList() + } else { + this.notification.showErrorToast( + 'Error adding new entry, the key exists.' + ) + } + } + } catch (error) { + this.notification.showErrorToast('Error adding entry.') + } + } + + firstPage() { + this.scope.setPage(1) + this.scope.prevPage() + } + + /** + * Enable edition for a given key + * @param {String} key Entry key + */ + setEditingKey(key, value) { + this.scope.editingKey = key + this.scope.editingNewValue = value + } + + /** + * Cancel edition of an entry + */ + cancelEditingKey() { + this.scope.editingKey = false + this.scope.editingNewValue = '' + } + + showConfirmRemoveEntry(ev, key) { + this.scope.removingEntry = key + } + + async editKey(key, newValue) { + try { + this.scope.currentList.list[key] = newValue + this.cancelEditingKey() + this.refreshCdbList() + } catch (error) { + this.notification.showErrorToast('Error editing value.') + } + } + + cancelRemoveEntry() { + this.scope.removingEntry = false + } + + async confirmRemoveEntry(key) { + try { + let currentPage = this.scope.currentPage + delete this.scope.currentList.list[key] + this.scope.removingEntry = false + this.refreshCdbList() + currentPage = + this.scope.pagedItems.length - 1 >= currentPage + ? currentPage + : currentPage - 1 + this.scope.setPage(currentPage) + } catch (error) { + this.notification.showErrorToast('Error deleting entry.') + } + } + + refreshCdbList() { + this.scope.items = this.cdbToArr() + this.initPagination() + if (!this.scope.$$phase) this.scope.$digest() + } + + async saveList() { + try { + this.scope.saveIncomplete = true + const fileName = this.scope.currentList.details.file + const path = this.scope.currentList.details.path + const content = this.objToString(this.scope.currentList.list) + await this.cdbEditor.sendConfiguration(fileName, path, content, true) + const cdbUpdated = await this.fetchFile(fileName, path) + this.scope.currentList.list = this.stringToObj(cdbUpdated) + // Re-init pagination + this.scope.items = this.cdbToArr() + this.contentToFilter = this.scope.items + this.initPagination() + this.notification.showSuccessToast('File saved successfully.') + this.scope.saveIncomplete = false + if (!this.scope.$$phase) this.scope.$digest() + } catch (error) { + this.scope.saveIncomplete = false + this.notification.showErrorToast(error || `Cannot send this file.`) + } + } + + stringToObj(string) { + let result = {} + const splitted = string.split('\n') + splitted.forEach(element => { + const keyValue = element.split(':') + if (keyValue[0]) result[keyValue[0]] = keyValue[1] + }) + return result + } + + objToString(obj) { + let raw = '' + for (var key in obj) { + raw = raw.concat(`${key}:${obj[key]}\n`) + } + return raw + } + + cdbToArr() { + const obj = this.scope.currentList.list + let items = [] + for (var property in obj) { + let o = [property, obj[property]] + items.push(o) + } + return items + } + + initPagination() { + this.scope.totalItems = this.scope.items.length + this.checkGap(this.scope, this.scope.items) + this.scope.searchTable() + } + } + controllers.controller('managerCdbIdCtrl', CdbListId) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/active-response/active-response.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/active-response/active-response.html index f15c1070d..bd602967f 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/active-response/active-response.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/active-response/active-response.html @@ -5,7 +5,7 @@
Active response
- Active threat addressing by inmmediate response + Active threat addressing by inmmediate response
@@ -17,11 +17,10 @@ name="commands">Commands - - -
-
-
+ +
+
+
@@ -31,11 +30,11 @@ -
+
- +
Active response definitions @@ -95,63 +94,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- + + + + + + More info about this section Active @@ -165,248 +120,5 @@
- -
- - - - - - - -
- - - - -
-
- Command definitions -
- Find here all the currently defined commands used for - Active - response -
-
- - JSON -  ·  - XML -
- - - -
- - -
- - - {{item.name}} - - -
- - - -
- -
- - - - - - - - - - -
- -
- -
- -
-
- - - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- - -
- - - - - - More info about this section - Active - response documentation - Commands - reference - - - - -
- - - -
- -
-
- - - - - -
- - - -
-
- Active response settings -
- Find here all the Active response settings for this - agent -
-
- - JSON -  ·  - XML -
- - -
- - - - - - - - -
- -
-
- - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - -
-
-
- -
-
- - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - -
-
{{ XMLContent }}
-
- -
-
- -
- - - - - More info about this section - Active - response documentation - Active - response reference - - - -
-
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/active-response/agents-active-response.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/active-response/agents-active-response.html index 3c56f2d17..1ba435909 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/active-response/agents-active-response.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/active-response/agents-active-response.html @@ -1,308 +1,87 @@ -
+
- -
-
- Active response -
- Active threat addressing by inmmediate response + +
+
+ Active response
- - - - - Active response - Commands - - - - -
-
-
- -
- - - - - - - -
- - - - -
-
- Active response settings -
- Find here all the Active response settings for this agent -
-
- - JSON -  ·  - XML -
- - - -
- - - - - - - - - - -
- - -
-
- - - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- - -
- - - - - - More info about this section - Active response documentation - Active response reference - - - + Active threat addressing by inmmediate response +
+ + +
+
- -
+
- - + + -
- - - - -
-
- Command definitions -
- Find here all the currently defined commands used for Active response -
-
- - JSON -  ·  - XML -
- - - -
- - -
- - - {{item.name}} - - -
- - - -
- -
- - - - - - - - - - -
- -
- -
- -
-
- - - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
+ + + + +
+
+ Active response settings +
+ Find here all the Active response settings for this agent +
+
+ + JSON +  ·  + XML +
+ + + +
+ + + + + + + + + + +
+ + +
+
+ + +
- - - More info about this section - Active response documentation - Commands reference - + + + + + + + + More info about this section + Active + response documentation + Active + response reference + -
- +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/agentless/agentless.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/agentless/agentless.html index e1bdb76f7..f4110578c 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/agentless/agentless.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/agentless/agentless.html @@ -4,28 +4,28 @@
Agentless
- Run integrity checks on devices such as routers, firewalls or switches. + Run integrity checks on devices such as routers, firewalls or switches.
- -
-
-
+ +
+
+
- + -
+
- +
Devices list @@ -79,63 +79,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- + + + + + + More info about this section How diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/alerts/alerts.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/alerts/alerts.html index 13afcbe00..bc13e04d1 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/alerts/alerts.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/alerts/alerts.html @@ -1,5 +1,5 @@
- +
@@ -7,8 +7,8 @@ Alerts Labels
- Settings related to the alerts and their format - User-defined information about the agent included + Settings related to the alerts and their format + User-defined information about the agent included in alerts
@@ -25,24 +25,24 @@ - -
-
-
+ +
+
+
- + -
+
- +
Main settings @@ -99,63 +99,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- + + + + + + More info about this section How @@ -183,7 +139,7 @@ - +
Main settings @@ -214,63 +170,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- + + + + + + More info about this section Use @@ -287,8 +199,7 @@
- + @@ -297,7 +208,7 @@ - +
Defined labels @@ -331,63 +242,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- + + + + + + More info about this section Labels @@ -413,7 +280,7 @@ - +
Main settings @@ -477,63 +344,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- + + + + + + More info about this section How @@ -560,7 +383,7 @@ - +
Main settings @@ -609,63 +432,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- + + + + + + More info about this section How @@ -679,6 +458,4 @@
-
- - +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/amazon-s3/amazon-s3.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/amazon-s3/amazon-s3.html index 292f40345..db56cbf9f 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/amazon-s3/amazon-s3.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/amazon-s3/amazon-s3.html @@ -4,9 +4,11 @@
Amazon S3 - Enabled + Enabled + Disabled
- Security events related to Amazon AWS services, collected directly via AWS API + Security events related to Amazon AWS services, collected directly via AWS API
@@ -14,13 +16,14 @@ General Buckets + Services - -
-
-
+ +
+
+
@@ -31,7 +34,7 @@ -
+
@@ -40,7 +43,7 @@ - +
Buckets @@ -103,9 +106,76 @@ + + + +
+
+ Services +
+ Amazon services from where logs are read +
+
+ + JSON +  ·  + XML +
+ + + +
+ + +
+ + + {{item.type}} + + + +
+ + + +
+
+ + + + + + + + + + + + +
+ +
+ +
+ +
+
+ + + - +
Main settings @@ -140,64 +210,21 @@ - - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- + + +
- + + + + + + More info about this section Using diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/both-configuration.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/both-configuration.html index d6771ec7a..6411988c6 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/both-configuration.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/both-configuration.html @@ -1,4 +1,5 @@
+
@@ -11,8 +12,10 @@ + + @@ -21,4 +24,5 @@ +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/breadcrumbs/breadcrumbs.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/breadcrumbs/breadcrumbs.html index 95cd0de40..4aa666acd 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/breadcrumbs/breadcrumbs.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/breadcrumbs/breadcrumbs.html @@ -1,10 +1,11 @@ -
-
+
+ -
+ +
-
+
Management @@ -19,47 +20,47 @@ / {{ configurationTab }}
+ +
+ + +
-
+
Agents / {{currentAgent.name}} ({{currentAgent.id}}) -
-
- {{formatAgentStatus(currentAgent.status)}} -
- / - -
- Configuration -
- -
- Configuration / - {{ configurationTab === 'alerts' ? 'Labels' : configurationTab }} -
+ + Configuration + + + Configuration + / + {{ configurationTab === 'alerts' ? 'Labels' : configurationTab }} +
+
+ +
+ {{formatAgentStatus(currentAgent.status)}} +
- - - - - -
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/cis-cat/cis-cat.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/cis-cat/cis-cat.html index e69025c46..009095a5d 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/cis-cat/cis-cat.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/cis-cat/cis-cat.html @@ -1,5 +1,5 @@
- +
@@ -8,7 +8,7 @@ Disabled
- Configuration assessment using CIS scanner and SCAP checks + Configuration assessment using CIS scanner and SCAP checks
@@ -19,10 +19,10 @@ - -
-
-
+ +
+
+
@@ -33,7 +33,7 @@ -
+
@@ -41,7 +41,7 @@ - +
Benchmarks @@ -84,7 +84,7 @@ - +
Main settings @@ -143,63 +143,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- + + + + + + More info about this section CIS-CAT diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/client-buffer/client-buffer.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/client-buffer/client-buffer.html index 508510306..96c37737a 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/client-buffer/client-buffer.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/client-buffer/client-buffer.html @@ -1,136 +1,92 @@
- -
-
- Anti-flooding settings - Enabled - Disabled -
- Agent bucket parameters to avoid event flooding + +
+
+ Anti-flooding settings + Enabled + Disabled
- - - -
-
-
- - -
- - - - - - - -
- - - - -
-
- Main settings -
- These settings determine the event processing rate for - the agent -
-
- - JSON -  ·  - XML -
- - - -
- - - - - - - - -
- -
-
- - - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
+ Agent bucket parameters to avoid event flooding +
+ + + +
+
+
+ + +
+ + + + + + + +
+ + + + +
+
+ Main settings +
+ These settings determine the event processing rate for + the agent
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
- - - - - -
- - - - - - More info about this section - Anti-flooding - mechanism - Client - buffer reference - - - - + + JSON +  ·  + XML +
+ + + +
+ + + + + + + + +
+ + + + + + +
- - -
\ No newline at end of file + + + + + + + + + + + More info about this section + Anti-flooding + mechanism + Client + buffer reference + + + + +
+ + +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/client/client.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/client/client.html index 0145cc10b..f9c0f60c4 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/client/client.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/client/client.html @@ -1,166 +1,122 @@
- -
-
- Client configuration -
- Settings related to the connection with the manager + +
+
+ Client configuration
- - - -
-
-
- - -
- - - - - - -
- - - - -
-
- Main settings -
- Basic manager-agent communication settings -
-
- - JSON -  ·  - XML -
- - - -
- - - - - - - - - - - - - - -
- - -
- Server settings + Settings related to the connection with the manager +
+ + + +
+
+
+ + +
+ + + + + + +
+ + + + +
+
+ Main settings
- List of managers to connect + Basic manager-agent communication settings
- - - -
- - - - - - - - - - - - - - -
AddressPortProtocol
{{ item.address || '---' }}{{ item.port || '1514' }}{{ item.protocol || 'udp' }}
- -
- - - - - - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
+ + JSON +  ·  + XML +
+ + + +
+ + + + + + + + + + + + + + +
+ + +
+ Server settings +
+ List of managers to connect
- - - - - -
- - - - - - More info about this section - Checking - connection with manager - Client - reference - - - - +
+ + + +
+ + + + + + + + + + + + + + +
AddressPortProtocol
{{ item.address || '---' }}{{ item.port || '1514' }}{{ item.protocol || 'udp' }}
+ +
+ +
+
+ + + +
- - -
\ No newline at end of file + + + + + + + + + + + More info about this section + Checking + connection with manager + Client + reference + + + + +
+ + +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/cluster/cluster.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/cluster/cluster.html index e854f21df..0e100b209 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/cluster/cluster.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/cluster/cluster.html @@ -1,5 +1,5 @@
- +
@@ -10,10 +10,10 @@
- -
-
-
+ +
+
+
@@ -23,11 +23,11 @@ -
+
- +
Master node settings @@ -65,63 +65,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- + + + + + + More info about this section How diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/configurationCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/configurationCtrl.js index 4e73dd880..10846343b 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/configurationCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/configurationCtrl.js @@ -9,53 +9,153 @@ define(['../../module', '../../../utils/config-handler'], function( $scope, $requestService, $beautifierJson, - $notificationService + $notificationService, + isAdmin, + clusterInfo ) { - this.$scope = $scope - this.errorHandler = $notificationService + this.scope = $scope + this.notification = $notificationService this.apiReq = $requestService - this.$scope.load = false - this.$scope.isArray = Array.isArray + this.scope.load = false + this.scope.isArray = Array.isArray this.configurationHandler = new ConfigHandler( this.apiReq, $beautifierJson, - this.errorHandler + this.notification ) - this.$scope.currentConfig = null - this.$scope.configurationTab = '' - this.$scope.configurationSubTab = '' - this.$scope.integrations = {} - this.$scope.selectedItem = 0 + this.scope.currentConfig = null + this.scope.configurationTab = '' + this.scope.configurationSubTab = '' + this.scope.integrations = {} + this.scope.selectedItem = 0 + this.scope.isAdmin = isAdmin + this.clusterInfo = clusterInfo + + // Save current sections, configTabs and woodles + this.currentConfigTab = false + this.currentSections = false + this.currentWodle = false + this.currentSubTab = false } $onInit() { - //Loads html - this.$scope.getXML = () => this.configurationHandler.getXML(this.$scope) - this.$scope.getJSON = () => this.configurationHandler.getJSON(this.$scope) - this.$scope.isString = item => typeof item === 'string' - this.$scope.hasSize = obj => - obj && typeof obj === 'object' && Object.keys(obj).length - this.$scope.switchConfigTab = (configurationTab, sections) => - this.configurationHandler.switchConfigTab( - configurationTab, - sections, - this.$scope - ) - this.$scope.switchWodle = wodleName => - this.configurationHandler.switchWodle(wodleName, this.$scope) - this.$scope.switchConfigurationTab = configurationTab => - this.configurationHandler.switchConfigurationTab( - configurationTab, - this.$scope - ) - this.$scope.switchConfigurationSubTab = configurationSubTab => - this.configurationHandler.switchConfigurationSubTab( - configurationSubTab, - this.$scope + try { + if (this.clusterInfo && this.clusterInfo.clusterEnabled) { + this.scope.clusterEnabled = this.clusterInfo.clusterEnabled + if (this.clusterInfo.clusterEnabled) { + this.scope.selectedNode = this.clusterInfo.nodes.data.data.items[0].name + this.scope.nodes = this.clusterInfo.nodes.data.data.items + } + this.changeNode(this.scope.selectedNode) + } else { + this.scope.selectedNode = false // If cluster is disabled there is not a node selected + } + + this.scope.goToEdition = true + this.scope.showingInfo = false + this.scope.showInfo = () => this.showInfo() + this.scope.getXML = () => this.configurationHandler.getXML(this.scope) + this.scope.getJSON = () => this.configurationHandler.getJSON(this.scope) + this.scope.isString = item => typeof item === 'string' + this.scope.changeNode = node => this.changeNode(node) + this.scope.hasSize = obj => + obj && typeof obj === 'object' && Object.keys(obj).length + this.scope.switchConfigTab = (configurationTab, sections) => { + this.currentConfigTab = configurationTab + this.currentSections = sections + this.currentWodle = false + this.configurationHandler.switchConfigTab( + configurationTab, + sections, + this.scope, + false, //Send agent.id as false + this.scope.selectedNode // Send selected node + ) + } + this.scope.switchWodle = wodleName => { + this.currentConfigTab = false + this.currentSections = false + this.currentWodle = wodleName + this.configurationHandler.switchWodle( + wodleName, + this.scope, + false, //Send agent.id as false + this.scope.selectedNode // Send selected node + ) + } + + this.scope.switchConfigurationTab = configurationTab => { + this.currentConfigTab = false + this.currentSections = false + this.currentSubTab = false + this.currentWodle = false + this.configurationHandler.switchConfigurationTab( + configurationTab, + this.scope + ) + } + + this.scope.switchConfigurationSubTab = configurationSubTab => { + this.currentSubTab = configurationSubTab + this.configurationHandler.switchConfigurationSubTab( + configurationSubTab, + this.scope + ) + } + this.scope.updateSelectedItem = i => (this.scope.selectedItem = i) + this.scope.getIntegration = list => + this.configurationHandler.getIntegration(list, this.scope) + } catch (error) { + this.notification.showErrorToast(error) + } + } + + /** + * Show or hide sidebar with info + */ + showInfo() { + this.scope.showingInfo = !this.scope.showingInfo + this.scope.$applyAsync() + } + + /** + * Changes the selected node + * + * @param {String} node + */ + changeNode(node) { + try { + this.scope.selectedNode = node + if (this.currentConfigTab && !this.currentWodle) { + this.configurationHandler.switchConfigTab( + this.currentConfigTab, + this.currentSections, + this.scope, + false, //Send agent.id as false + node // Send selected node + ) + } else if (!this.currentConfigTab && this.currentWodle) { + this.configurationHandler.switchWodle( + this.currentWodle, + this.scope, + false, //Send agent.id as false + node // Send selected node + ) + } + // If the current config tab or wodle have sub tabs, this initializes the nav bar and loads the data + if (this.currentSubTab) { + this.configurationHandler.switchConfigurationSubTab( + this.currentSubTab, + this.scope + ) + } + this.scope.$applyAsync() + //this.notification.showSimpleToast(`Node selected: ${node}`) + } catch (error) { + this.notification.showErrorToast( + error || `Cannot load ${node} configuration.` ) - this.$scope.updateSelectedItem = i => (this.$scope.selectedItem = i) - this.$scope.getIntegration = list => - this.configurationHandler.getIntegration(list, this.$scope) + } } } diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/database-output/database-output.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/database-output/database-output.html index ab13827f8..8ab054006 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/database-output/database-output.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/database-output/database-output.html @@ -1,139 +1,87 @@
- -
-
- Database output -
- MySQL and PostgreSQL database output configuration + +
+
+ Database output
- + MySQL and PostgreSQL database output configuration +
+ - -
-
-
- - -
- - - - - - -
- - - - -
-
- Main settings -
- These settings indicate the database where alerts are stored -
-
- - JSON -  ·  - XML -
- - - -
- - - - - - - - - - -
- -
-
- - - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- - -
- + +
+
+
- - - - More info about this section - Database output reference - - - + +
+ + + + + + +
+ + + + +
+
+ Main settings +
+ These settings indicate the database where alerts are + stored +
+
+ + JSON +  ·  + XML +
+ + + +
+ + + + + + + + + + +
+ +
+
+ + +
- - -
+ + + + + + + + + + + More info about this section + Database + output reference + + + + +
+ + +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/docker-listener/docker-listener.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/docker-listener/docker-listener.html new file mode 100644 index 000000000..d581f8b0e --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/docker-listener/docker-listener.html @@ -0,0 +1,83 @@ +
+ + +
+
+ Docker listerner + Enabled + Disabled +
+ Collects events on Docker containers such as starting, stopping or pausing. +
+ + + +
+
+
+ + +
+ + + + + + +
+ + + + +
+
+ Main settings +
+ General Docker listener settings +
+
+ + JSON +  ·  + XML +
+ + + +
+ + + + + + + +
+ + +
+
+ + + + +
+ + + + + + More info about this section + Docker + information + Docker listener + module reference + + + + +
+ + +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/edit-configuration/editGroupsCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/edit-configuration/editGroupsCtrl.js new file mode 100644 index 000000000..a5ed9a24b --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/edit-configuration/editGroupsCtrl.js @@ -0,0 +1,154 @@ +define(['../../../module'], function(controllers) { + 'use strict' + + class EditGroupsCtrl { + /** + * Class Status + * @param {*} $scope + * @param {Array} groups + * @param {Boolean} isAdmin + */ + constructor( + $scope, + $notificationService, + $fileEditor, + isAdmin, + groups, + $requestService, + $groupHandler + ) { + this.scope = $scope + this.isAdmin = isAdmin + this.groups = groups + this.notification = $notificationService + this.fileEditor = $fileEditor + this.apiReq = $requestService.apiReq + this.groupHandler = $groupHandler + } + /** + * On controller loads + */ + $onInit() { + try { + this.scope.editingGroup = false + + this.scope.editGroupAgentConfig = group => + this.editGroupAgentConfig(group) + this.scope.closeEditingFile = () => this.closeEditingFile() + this.scope.xmlIsValid = valid => this.xmlIsValid(valid) + this.scope.doSaveGroupAgentConfig = () => this.doSaveGroupAgentConfig() + this.scope.saveGroupAgentConfig = content => + this.saveGroupAgentConfig(content) + + this.scope.groups = this.groups.data.data.items + this.scope.adminMode = this.isAdmin + + //Add groups + this.scope.switchAddingGroup = () => { + this.scope.addingGroup = !this.scope.addingGroup + } + this.scope.createGroup = async name => { + try { + this.scope.addingGroup = false + await this.groupHandler.createGroup(name) + this.notification.showSuccessToast( + `Success. Group ${name} has been created` + ) + } catch (error) { + this.notification.showErrorToast(`${error.message || error}`) + } + this.scope.$broadcast('wazuhSearch', {}) + } + + //Search for a group + this.scope.search = term => { + this.scope.$broadcast('wazuhSearch', { term }) + } + + //Edit groups + this.scope.$on('openGroupFromList', (ev, parameters) => { + ev.stopPropagation() + const groupName = parameters.group.name + this.scope.editingFile = true + this.scope.groupsSelectedTab = 'files' + this.editGroupAgentConfig(groupName) + }) + } catch (error) { + console.error(error) + } + } + + //Groups + async editGroupAgentConfig(groupName) { + try { + this.scope.editingFile = true + this.scope.fetchedXML = await this.fetchFile(groupName) + this.scope.$broadcast('fetchedFile', { data: this.scope.fetchedXML }) + } catch (error) { + this.scope.fetchedXML = null + this.notification.showErrorToast(error.message || error) + } + if (!this.scope.$$phase) this.scope.$digest() + return + } + + async saveGroupAgentConfig(content) { + try { + const result = await this.apiReq.request( + 'POST', + `/agents/groups/${this.scope.currentGroup.name}/configuration`, + { content, origin: 'xmleditor' } + ) + if ( + !result || + !result.data || + !result.data.data || + result.data.data.error !== 0 + ) { + throw new Error('Error sending file.') + } + this.scope.$emit('updateGroupInformation', { + group: this.scope.currentGroup.name + }) + } catch (error) { + this.notification.showErrorToast(error.message || error) + } + return + } + + async fetchFile(groupName) { + try { + this.scope.currentGroup = { name: groupName } + const data = await this.apiReq( + `/agents/groups/${groupName}/files/agent.conf`, + { format: 'xml' } + ) + const xml = ((data || {}).data || {}).data || false + if (!xml) { + throw new Error('Could not fetch agent.conf file') + } + return xml + } catch (error) { + return Promise.reject(error) + } + } + closeEditingFile() { + this.scope.editingFile = false + this.scope.currentGroup = false + if (!this.scope.$$phase) this.scope.$digest() + } + + xmlIsValid(valid) { + this.scope.xmlHasErrors = valid + if (!this.scope.$$phase) this.scope.$digest() + } + + doSaveGroupAgentConfig() { + this.scope.$broadcast('saveXmlFile', { + group: this.scope.currentGroup.name + }) + } + } + + controllers.controller('editGroupsCtrl', EditGroupsCtrl) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/edit-configuration/manager-edit-groups.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/edit-configuration/manager-edit-groups.html new file mode 100644 index 000000000..fc7e073e8 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/edit-configuration/manager-edit-groups.html @@ -0,0 +1,147 @@ + +
+
+ + Edit the groups + +
+
+ + +
+
+ List and check your groups, its agents and files +
+
+ + +
+ + +
+ + Go back + + + + +
+ + {{currentGroup.name}} +
+ +
+ Agents + {{ currentGroup.count }} +
+
+ Content + {{ totalFiles }} files +
+
+ Configuration sum + {{ currentGroup.configSum }} +
+
+ Merged sum + {{ currentGroup.mergedSum }} +
+
+
+ + +
+ + + Agents + Content + + + +
+
+ + + +
+
+ + +
+
+ + +
+
+ + + It is not + possible to apply changes of more than 500 additions or deletions +
+ + +
+ + +
+ + + +
+ + +
+ + + +
+
+
+ {{ filename }} + + +
+
+
+
+
+
+ +
+
+ +{{currentAdding}} -{{currentDeleting}} + + +
+
+
+ +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/global-configuration/global-configuration.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/global-configuration/global-configuration.html index 4094378ef..87223d8f5 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/global-configuration/global-configuration.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/global-configuration/global-configuration.html @@ -1,368 +1,280 @@
- - -
-
- Global configuration -
- Global and remote settings -
- - - - - Global - Remote - - - - -
-
-
- -
- - - - - - - - -
- - - - -
-
- Main settings -
- Basic alerts and logging settings -
-
- - JSON -  ·  - XML -
- - - -
- - - - - - - - - - - - - - - - - - - - -
- - -
- Email settings -
- Basic email settings (needed for granular email settings) -
-
- - - -
- - - - - - - - - - - - - - - - - -
- - -
- Other settings + +
+
+ Global configuration +
+ Global and remote settings +
+ + + + + Global + Remote + + + + +
+
+
+ +
+ + + + + + + + +
+ + + + +
+
+ Main settings
- Settings not directly related to any specific component -
-
- - - -
- - - - - - - - - - - - - - -
- - -
- Prelude and ZeroMQ output -
- - - -
- - - - - - - - -
- - - - - - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
+ Basic alerts and logging settings
- - JSON -  ·  - XML -
- - - -
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML + + JSON +  ·  + XML +
+ + + +
+ + + + + + + + + + + + + + + + + + + + +
+ + +
+ Email settings +
+ Basic email settings (needed for granular email settings)
- - - -
-
{{ XMLContent }}
+
+ + + +
+ + + + + + + + + + + + + + + + + + +
+ + +
+ Other settings +
+ Settings not directly related to any specific component
- - - - - -
- - - - - - More info about this section - Global - reference - Logging - reference - - - +
+ + + +
+ + + + + + + + + + + + + + +
+ + +
+ Prelude and ZeroMQ output +
+ + + +
+ + + + + + + + +
+ +
+
+ + +
- - -
- - - - - - - -
- - - - -
-
- Remote settings -
- Configuration to listen for events from the agents or a syslog - client -
-
- - JSON -  ·  - XML -
- - - -
- - - - - - - - - - - - - - - - - - - - - - - - -
ConnectionPortProtocolIPv6Allowed IPsDenied IPsLocal IPQueue size
{{ item.connection || '---' }}{{ item.port || '---' }}{{ item.protocol || 'udp' }}{{ item.ipv6 || '-' }} -
    -
  • {{ ip }}
  • -
- - -
-
    -
  • {{ ip }}
  • -
- - -
{{ item.local_ip || 'All interfaces' }}{{ item.queue_size || '16384' }}
- -
- -
-
- - - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
+ + + + + + + + + + + More info about this section + Global + reference + Logging + reference + + + + +
+ + +
+ + + + + + + +
+ + + + +
+
+ Remote settings +
+ Configuration to listen for events from the agents or a syslog + client
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
- - - - - -
- - - - - - More info about this section - Remote - daemon reference - Remote - configuration reference - - - + + JSON +  ·  + XML +
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
ConnectionPortProtocolIPv6Allowed IPsDenied IPsLocal IPQueue size
{{ item.connection || '---' }}{{ item.port || '---' }}{{ item.protocol || 'udp' }}{{ item.ipv6 || '-' }} +
    +
  • {{ ip }}
  • +
+ - +
+
    +
  • {{ ip }}
  • +
+ - +
{{ item.local_ip || 'All interfaces' }}{{ item.queue_size || '16384' }}
+ +
+ + + + + +
- -
\ No newline at end of file + + + + + + + + + + + More info about this section + Remote + daemon reference + Remote + configuration reference + + + + +
+ +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/integrations/integrations.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/integrations/integrations.html index db755f89c..7c6932fd8 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/integrations/integrations.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/integrations/integrations.html @@ -5,28 +5,28 @@
Integrations
- Slack, VirusTotal and PagerDuty integrations with external APIs + Slack, VirusTotal and PagerDuty integrations with external APIs
- -
-
-
+ +
+
+
- + -
+
- +
VirusTotal @@ -111,64 +111,22 @@ + + + - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
-
- + + + + + + More info about this section How diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/integrity-monitoring/integrity-monitoring.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/integrity-monitoring/integrity-monitoring.html index 90ec7d657..2a93504ff 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/integrity-monitoring/integrity-monitoring.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/integrity-monitoring/integrity-monitoring.html @@ -18,7 +18,7 @@ && isString(currentConfig['syscheck-syscheck']))" class="wz-agent-status-indicator small red">Disabled
- Identify changes in content, permissions, ownership and attributes of files + Identify changes in content, permissions, ownership and attributes of files
@@ -33,27 +33,22 @@ - -
-
-
+ +
+
+
- - - - - -
+
- +
General @@ -105,12 +100,13 @@ + ng-if="((agent || {}).os || {}).platform !== 'windows' && configurationSubTab === 'fim-ignored' && currentConfig && currentConfig['syscheck-syscheck'] + && currentConfig['syscheck-syscheck'].syscheck && !currentConfig['syscheck-syscheck'].syscheck.ignore.length"> + - - - + +
Ignored files and directories @@ -150,7 +146,7 @@ - +
Ignored @@ -192,7 +188,7 @@ - +
Monitored directories @@ -260,6 +256,8 @@ + +
@@ -275,7 +273,7 @@ - +
Monitored @@ -318,7 +316,7 @@ - +
No diff directories @@ -359,7 +357,7 @@ - +
Who-data audit keys @@ -377,6 +375,14 @@
+ + +
+
+ No audit keys were found. Visit the documentation on + this link to enable it. +
+
@@ -388,73 +394,26 @@
Keys
-
- No audit keys were found. Visit the - documentation on this - link to enable it. -
+ + + - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
-
- + + + + + + More info about this section Integrity diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/log-collection/log-collection.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/log-collection/log-collection.html index 5fb195f06..88381bee0 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/log-collection/log-collection.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/log-collection/log-collection.html @@ -1,45 +1,55 @@ -
+
Log collection
- Log analysis from text files, Windows events or syslog outputs + Log analysis from text files, Windows events or syslog outputs
- - Localfiles - Sockets + + Logs + + Commands + + Sockets +
-
+ +
- - + + -
+
- +
Logs files and command monitoring
- List of log files that will be analyzed + List of log files that will be analyzed
- JSON + JSON  ·  XML
@@ -52,38 +62,40 @@
- - {{ item.file || item.alias || item.command }} - {{ item.logformat }} - {{ item.targetStr }} - + + {{ item.file || item.alias || + item.command }} + {{ item.logformat }} - {{ + item.targetStr }}
-
+
- + - + - + - + - + - - - - - - - - - +
@@ -95,90 +107,161 @@ - - - + + +
+ + + + + + + + + + + More info about this section + Log + data collection documentation + Localfile + reference + + + + +
+ + + + +
+ + + + + + + + +
+ + + +
- JSON viewer + Command monitoring
- View this configuration in raw JSON format + All output from these commands will be read as one or more + log messages depending on whether command or full_command is used.
- JSON + JSON  ·  XML
- -
-
-
- -
-
- + +
+ + +
+ + + + {{ item.file || item.alias || + item.command }} + {{ item.logformat }} - {{ + item.targetStr }} + - - - -
-
- XML viewer -
- View this configuration in raw XML format -
- - JSON -  ·  - XML -
- + + + +
- -
-
{{ XMLContent }}
+
+ + + + + + + + + + +
+ +
+
- +
- + + +
- + + + + + + More info about this section - Log + Log data collection documentation - Localfile + Localfile reference
-
- - + + + -
+
- +
Output sockets @@ -187,7 +270,8 @@
- JSON + JSON  ·  XML
@@ -200,7 +284,8 @@
- {{ + {{ item.name }} @@ -211,13 +296,17 @@
- + - + - + - +
@@ -229,74 +318,31 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- + - - - - - More info about this section - Using - multiple outputs - Socket - reference - - - -
+ + + + + + + + + More info about this section + + Using + multiple outputs + Socket + reference + + +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/open-scap/open-scap.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/open-scap/open-scap.html index e95a0fe8a..30f083bc1 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/open-scap/open-scap.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/open-scap/open-scap.html @@ -8,7 +8,7 @@ Disabled
- Configuration assessment and automation of compliance monitoring using SCAP checks + Configuration assessment and automation of compliance monitoring using SCAP checks
@@ -19,13 +19,13 @@ - -
-
-
+ +
+
+
-
+
@@ -42,7 +42,7 @@ - +
Evaluations @@ -71,7 +71,7 @@ {{item.path}} -
    +
    • {{profile}}
    - @@ -90,7 +90,7 @@ - +
    Main settings @@ -122,63 +122,22 @@ - - - -
    -
    - JSON viewer -
    - View this configuration in raw JSON format -
    -
    - - JSON -  ·  - XML -
    - - - -
    -
    -
    - -
    -
    - + + + - - - -
    -
    - XML viewer -
    - View this configuration in raw XML format -
    -
    - - JSON -  ·  - XML -
    - - - -
    -
    {{ XMLContent }}
    -
    - -
    -
    -
    - + + + + + + More info about this section OpenSCAP diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/osquery/osquery.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/osquery/osquery.html index 0f5ce207a..fbd12ee22 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/osquery/osquery.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/osquery/osquery.html @@ -8,14 +8,14 @@ Disabled
    - Expose an operating system as a high-performance relational database + Expose an operating system as a high-performance relational database
- -
-
-
+ +
+
+
@@ -26,11 +26,11 @@ -
+
- +
Main settings @@ -98,63 +98,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- + + + + + + More info about this section Osquery diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/policy-monitoring/policy-monitoring.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/policy-monitoring/policy-monitoring.html index 5e5bb1208..d5505fdb3 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/policy-monitoring/policy-monitoring.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/policy-monitoring/policy-monitoring.html @@ -1,5 +1,6 @@ -
- +
+
@@ -18,22 +19,26 @@ && isString(currentConfig['syscheck-rootcheck']))" class="wz-agent-status-indicator small red">Disabled
- Configuration to ensure compliance with security policies, standards and hardening + Configuration to ensure compliance with security policies, standards and hardening guides
- General - System audit + General + System audit + Configuration + assessment - -
-
-
+ +
+
+
@@ -44,16 +49,16 @@ -
+
- + - +
UNIX audit files @@ -91,7 +96,7 @@ - +
All settings @@ -158,64 +163,91 @@ + - - - + + + + + + +
- JSON viewer + Configuration assessment
- View this configuration in raw JSON format
- - JSON -  ·  - XML
- -
-
+
+
+ + + + + + + + + + +
- - - - + - - - -
-
- XML viewer -
- View this configuration in raw XML format + +
+
+
+ Policies +
+
- - JSON -  ·  - XML -
- + - -
-
{{ XMLContent }}
+
+ + + + + + + + + + +
Name
+ {{policy}} +
+ + +
- + + + + - + + + +
- + + + + + + More info about this section Anomaly diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/registration-service/registration-service.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/registration-service/registration-service.html index 95a0390dc..32b1e2cd0 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/registration-service/registration-service.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/registration-service/registration-service.html @@ -1,5 +1,5 @@
- +
@@ -8,27 +8,28 @@ class="wz-agent-status-indicator small teal">Enabled Disabled
- Automatic agent registration service + Automatic agent registration service
- -
-
-
+ +
+
+
+ - + -
+
- +
Main settings @@ -94,63 +95,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- + + + + + + More info about this section How diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/ruleset/ruleset.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/ruleset/ruleset.html index c35360adb..2739ff92e 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/ruleset/ruleset.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/ruleset/ruleset.html @@ -1,333 +1,286 @@
- -
-
- Ruleset -
- Current rules, decoders and CDB lists loaded in the cluster -
- - - - - Rules - Decoders - CDB lists - - - - -
-
+ +
+
+ Ruleset
+ Current rules, decoders and CDB lists loaded in the cluster +
+ + + + + Rules + Decoders + CDB lists + + + + +
+
+
- -
+ +
- - - + + + - -
- - - -
+ +
+ + + +
- Rules directories -
- Folders with rules to load -
+ Rules directories +
+ Folders with rules to load +
JSON  ·  XML -
- +
+ - -
+ +
- - - - - - - - - - - - - - + + + + + + + + + + + + + +
PathPattern
testtest
testtest
PathPattern
testtest
testtest
-
- +
+ -
Included rules files
-
+
Included rules files
+
Specific rules files to include in load -
- +
+ - -
+ +
- - - - - - - - - - - + + + + + + + + + + +
Path
test
test
Path
test
test
-
- +
+ -
Excluded rules files
-
+
Excluded rules files
+
Specific rules files to exclude from load -
- +
+ - -
+ +
- - - - - - - - - - - + + + + + + + + + + +
Path
test
test
Path
test
test
-
- - - - - - - -
+
+ +
+
+ + + + +
- Decoders directories -
- Folders with decoders to load -
+ Decoders directories +
+ Folders with decoders to load +
JSON  ·  XML -
- +
+ - -
+ +
- - - - - - - - - - - - - - + + + + + + + + + + + + + +
PathPattern
testtest
testtest
PathPattern
testtest
testtest
-
- +
+ -
Included decoders files
-
+
Included decoders files
+
Specific decoders files to include in load -
- +
+ - -
+ +
- - - - - - - - - - - + + + + + + + + + + +
Path
test
test
Path
test
test
-
- +
+ -
Excluded decoders files
-
+
Excluded decoders files
+
Specific decoders files to exclude from load -
- +
+ - -
+ +
- - - - - - - - - - - + + + + + + + + + + +
Path
test
test
Path
test
test
-
- - - - - - - -
+
+ +
+
+ + + + +
- CDB lists -
- Constant databases references used by other rules -
+ CDB lists +
+ Constant databases references used by other rules +
JSON  ·  XML -
- +
+ - -
+ +
- - - - - - - - - - - + + + + + + + + + + +
Path
test
test
Path
test
test
-
- - - - - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
+ + + + +
- - - More info about this section - Ruleset documentation - Ruleset reference - + + + + + + + + More info about this section + Ruleset + documentation + Ruleset + reference + -
- +
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/syscollector/syscollector.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/syscollector/syscollector.html index 26ccdf4be..e53b97561 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/syscollector/syscollector.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/syscollector/syscollector.html @@ -1,164 +1,120 @@
- -
-
- Inventory data - Enabled - Disabled -
- Gather relevant information about system OS, hardware and packages. + +
+
+ Inventory data + Enabled + Disabled
- - - -
-
-
- - -
- - - - - - - -
- - - - -
-
- Main settings -
- General settings applied to all the scans -
-
- - JSON -  ·  - XML -
- - - -
- - - - - - - - -
- - -
- Scan settings + Gather relevant information about system OS, hardware and packages. +
+ + + +
+
+
+ + +
+ + + + + + + +
+ + + + +
+
+ Main settings
- Specific inventory scans to collect -
-
- - - -
- - - - - - - - - - - - - - - - -
- - - - - - - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
+ General settings applied to all the scans
- - JSON -  ·  - XML
- - - -
-
{{ XMLContent }}
+ + JSON +  ·  + XML +
+ + + +
+ + + + + + + + +
+ + +
+ Scan settings +
+ Specific inventory scans to collect
- - - - - -
- - - - - - More info about this section - Syscollector - module documentation - Syscollector - module reference - - - - +
+ + + +
+ + + + + + + + + + + + + + + + +
+ + +
+
+ + + +
- - -
\ No newline at end of file + + + + + + + + + + + More info about this section + Syscollector + module documentation + Syscollector + module reference + + + + +
+ + +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/vulnerabilities/vulnerabilities.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/vulnerabilities/vulnerabilities.html index cee7a52c2..096646579 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/vulnerabilities/vulnerabilities.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/vulnerabilities/vulnerabilities.html @@ -9,7 +9,7 @@ Disabled
- Discover what applications are affected by well-known vulnerabilities + Discover what applications are affected by well-known vulnerabilities
@@ -20,10 +20,10 @@ - -
-
-
+ +
+
+
@@ -34,7 +34,7 @@ -
+
@@ -43,7 +43,7 @@ - +
Feeds @@ -91,7 +91,7 @@ - +
Main settings @@ -108,7 +108,6 @@
- @@ -117,7 +116,6 @@ -
@@ -125,63 +123,22 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- + + + - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
-
- + + + + + + More info about this section Vulnerability diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/wazuh-commands/wazuh-commands.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/wazuh-commands/wazuh-commands.html index 670f2c0af..4db8133f2 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/wazuh-commands/wazuh-commands.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/wazuh-commands/wazuh-commands.html @@ -6,11 +6,11 @@ -
+
- +
Command definitions @@ -63,63 +63,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- - + + + + + + + More info about this section Active @@ -142,14 +98,14 @@
Commands
- Configuration options of the Command wodle + Configuration options of the Command wodle
- -
-
-
+ +
+
+
@@ -164,7 +120,7 @@ - +
Command definitions @@ -228,63 +184,19 @@ - - - -
-
- JSON viewer -
- View this configuration in raw JSON format -
-
- - JSON -  ·  - XML -
- - - -
-
-
- -
-
- - - - - -
-
- XML viewer -
- View this configuration in raw XML format -
-
- - JSON -  ·  - XML -
- - - -
-
{{ XMLContent }}
-
- -
-
- +
- + + + + + + More info about this section Command diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/welcome/welcome.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/welcome/welcome.html index e891a6b9a..49efd168f 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/welcome/welcome.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/configuration/welcome/welcome.html @@ -1,6 +1,6 @@
-
- +
+
Groups: {{ @@ -10,263 +10,222 @@
-
-
+
Configuration SYNCHRONIZED NOT SYNCHRONIZED -
- - Configuration
- +
- - - - Main configurations - - - - - -
- -

Global and remote settings

-
-
- -
- -

Master node configuration

-
-
- -
- -

Automatic agent registration using service

-
-
- - - - -
- -

Logging settings that apply to the agent

-
-
- -
- -

Settings related to the connection with the manager

-
-
- -
- -

Agent bucket parameters to avoid event flooding

-
-
- -
- -

User-defined information about the agent included in alerts

-
-
- -
- -
-
- - - - - - Alerts and output management - - - -
- -

Settings related to the alerts and their format

-
-
- -
- -

Slack, VirusTotal and PagerDuty integrations with external APIs

-
-
- -
- -
-
- - - + + + + - Auditing and policy monitoring - - - - -
- -

Configuration to ensure compliance with security policies, standards and hardening guides

-
-
- -
- -

Configuration assessment and automation of compliance monitoring using SCAP checks

-
-
- -
- -

Configuration assessment using CIS scanner and SCAP checks

-
-
-
+ + + + + + + + + + + + + + + + + + + + + +
Main configuration
NameDescription
Global configurationGlobal and remote settings
ClusterMaster node configuration
Registration serviceAutomatic agent registration using service
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Main configuration
NameDescription
Global configurationLogging settings that apply to the agent
Client configurationSettings related to the connection with the manager
Anti-flooding settingsAgent bucket parameters to avoid event flooding
LabelsUser-defined information about the agent included in alerts
+ + + + + + + + + + + + + + + + + + + +
Alerts and output management
NameDescription
AlertsSettings related to the alerts and their format
IntegrationsSlack, VirusTotal and PagerDuty integrations with external APIs
+ + + + + + + + + + + + + + + + + + + + + + + +
Auditing and policy monitoring
NameDescription
Policy monitoringConfiguration to ensure compliance with security policies, standards and hardening guides
OpenSCAPConfiguration assessment and automation of compliance monitoring using SCAP checks
CIS-CATConfiguration assessment using CIS scanner and SCAP checks
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
System threats and incident response
NameDescription
VulnerabilitiesDiscover what applications are affected by well-known vulnerabilities
OsqueryExpose an operating system as a high-performance relational database
Inventory dataGather relevant information about system OS, hardware and packages
Active responseActive threat addressing by inmmediate response
Active responseActive threat addressing by inmmediate response
CommandsConfiguration options of the Command wodle
Docker listenerCollects events on Docker containers such as starting, stopping or pausing.
+ + + + + + + + + + + + + + + + + + + + + + + +
Log data analysis
NameDescription
Log collectionLog analysis from text files, Windows events or syslog outputs
Integrity monitoringIdentify changes in content, permissions, ownership and attributes of files
AgentlessRun integrity checks on devices such as routers, firewalls or switches
+ + + + + + + + + + + + + + + +
Cloud security monitoring
NameDescription
Amazon S3Security events related to Amazon AWS services, collected directly via AWS API
+
- - - - - - System threats and incident response - - - - -
- -

Discover what applications are affected by well-known vulnerabilities

-
-
- -
- -

Expose an operating system as a high-performance relational database

-
-
- -
- -

Gather relevant information about system OS, hardware and packages.

-
-
- -
- -

Active threat addressing by inmmediate response

-
-
- -
- -

Active threat addressing by inmmediate response

-
-
- -
- -

Configuration options of the Command wodle

-
-
-
- -
-
- - - - - - Log data analysis - - - - -
- -

Log analysis from text files, Windows events or syslog outputs

-
-
- -
- -

Identify changes in content, permissions, ownership, and attributes of files

-
-
- -
- -

Run integrity checks on devices such as routers, firewalls or switches.

-
-
-
- -
-
- - - - - - Cloud security monitoring - - - - -
- -

Security events related to Amazon AWS services, collected directly via AWS API

-
-
-
- -
-
- +
- + - + + + + + + More info about this section Wazuh @@ -282,5 +241,4 @@
- -
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/manager-decoders-id.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/manager-decoders-id.html index 90fa392f2..8bd5ff9ac 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/manager-decoders-id.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/manager-decoders-id.html @@ -1,151 +1,205 @@ -
-
-
- Management - / Decoders -
-
-
-
- -
- - Decoders - Review all your current rules and decoders -
- - -
- - - - - Back - - - -

{{currentDecoder.name}}

-
- - - -
- - -
Position: - {{currentDecoder.position}} -
-
File: - {{currentDecoder.file}} - - Filter by this file - - -
-
Path: - {{currentDecoder.path}} - - Filter by this path - - -
-
-
-
- - - -
- -
- - - - - - Details - - -
- {{key}} - {{value}} - - - -
-
-
- - - - - - - Regex - -
-
- -
-
-
-
- - -
- -
- - - - - - Match - -
-
- {{item}} -
-
-
-
- - - - - - - Prematch - -
-
- {{item}} -
-
-
-
- - -
- - -
-

- Related decoders

-
-
- - -
- - -
- +
+
+
+ Management + / Ruleset + / Decoders + / {{currentDecoder.name}} +
+
+
+
+ + + + Rules + + Decoders + + Lists + + + + +
+ + + + + Back + + + +

{{currentDecoder.name}}

+
+ + + +
+ + +
+ Position: + {{currentDecoder.position}} +
+
File: + {{currentDecoder.file}} + + Filter by this file + + +
+
Path: + {{currentDecoder.path}} + + Filter by this path + + +
+
+
+
+ + + +
+ +
+ + +
+ +
+ + + + + + Details + + +
+ {{key}} + {{value}} + + + +
+
+
+ + + + + + + Regex + +
+
+ +
+
+
+
+ + +
+ +
+ + + + + + Match + +
+
+ {{item}} +
+
+
+
+ + + + + + + Prematch + +
+
+ {{item}} +
+
+
+
+ + +
+ + +

+ Related decoders +

+ + +
+ +
+
+ + +
+ +
+
+ + +
+
+ + Cancel + + +
+
+ + +
+
+ +
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/manager-decoders.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/manager-decoders.html index 7579193b4..58e52bb01 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/manager-decoders.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/manager-decoders.html @@ -1,67 +1,156 @@
-
+
Management + / Ruleset / Decoders
- -
- - Decoders - Review all your current rules and decoders -
- -
-
+
- - + + + Rules + Decoders + Lists + -
- +
+
+
+
+ +
+ +
+
+ +
+
+ +
+ +
- - - Rules - - - Decoders -
+
+ + + + Add new decoders file + + Manage decoders files + + + + + + + + + File: {{ getFilter('file') }} + + + + + Path: {{ getFilter('path') }} + + + + +
+ + + + + + + + +
+ +
+
+
+
+
- - - File: {{ getFilter('file') }} - - - - - Path: {{ getFilter('path') }} - - - - +
-
- - -
- + +
+
+ + + + +
+
+ + +
+
+ + +
+
+ + + + +
+
+ +
+
-
\ No newline at end of file + +
+ + +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/managerDecodersCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/managerDecodersCtrl.js index c4dda5394..87086c871 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/managerDecodersCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/managerDecodersCtrl.js @@ -17,7 +17,10 @@ define(['../../module', '../rules/ruleset'], function(controllers, Ruleset) { $notificationService, $currentDataService, $tableFilterService, - $csvRequestService + $csvRequestService, + $restartService, + isAdmin, + $fileEditor ) { super( $scope, @@ -26,32 +29,37 @@ define(['../../module', '../rules/ruleset'], function(controllers, Ruleset) { 'decoders', $currentDataService, $tableFilterService, - $csvRequestService + $csvRequestService, + $restartService, + $fileEditor ) this.scope.typeFilter = 'all' + this.isAdmin = isAdmin + this.restartService = $restartService } /** * On controller load */ $onInit() { + this.scope.adminMode = this.isAdmin + this.scope.localFilter = false // Reloading event listener this.scope.$broadcast('wazuhSearch', { term: '', removeFilters: true }) this.scope.downloadCsv = (path, name) => this.downloadCsv(path, name) - this.scope.$on('decodersIsReloaded', () => { - this.scope.viewingDetail = false - if (!this.scope.$$phase) this.scope.$digest() - }) - this.scope.onlyParents = typeFilter => this.onlyParents(typeFilter) + this.scope.addNewFile = () => this.addNewFile() + this.scope.saveRuleConfig = (fileName, dir, overwrite) => + this.saveRuleConfig(fileName, dir, overwrite) - this.scope.$on('wazuhShowDecoder', (event, parameters) => { - this.scope.currentDecoder = parameters.decoder - this.scope.viewingDetail = true - if (!this.scope.$$phase) this.scope.$digest() - }) + this.scope.selectedNavTab = 'decoders' - this.scope.$on('loadedTable', () => { + this.scope.restart = () => this.restart() + this.scope.closeRestartConfirmation = () => + this.closeRestartConfirmation() + + this.scope.$on('loadedTable', event => { + event.stopPropagation() try { if (window.localStorage.decoders) { const parsedFilter = JSON.parse(window.localStorage.decoders) @@ -60,7 +68,7 @@ define(['../../module', '../rules/ruleset'], function(controllers, Ruleset) { this.scope.$broadcast('wazuhFilter', { filter: this.filter }) } } catch (err) { - this.toast('Error applying filter') + this.notification.showErrorToast('Error applying filter') } }) } @@ -74,12 +82,59 @@ define(['../../module', '../rules/ruleset'], function(controllers, Ruleset) { if (window.localStorage.decoders) { delete window.localStorage.decoders } - if (typeFilter === 'all') + if (typeFilter === 'all') { + this.scope.onlyParentDecoders = false this.scope.$broadcast('wazuhUpdateInstancePath', { path: '/decoders' }) - else + } else { + this.scope.onlyParentDecoders = true this.scope.$broadcast('wazuhUpdateInstancePath', { path: '/decoders/parents' }) + } + } + + /** + * Open the editor for a new file + */ + addNewFile() { + this.scope.overwrite = false + this.scope.addingNewFile = true + this.scope.editingFile = { + file: ``, + dir: `decoders` + } + this.scope.fetchedXML = `` + } + + /** + * Save the new content + * @param {String} fileName + * @param {String} dir + */ + saveRuleConfig(fileName, dir, overwrite = false) { + try { + const containsBlanks = /.* .*/ + fileName = this.scope.editingFile.file + fileName = fileName.endsWith('.xml') ? fileName : `${fileName}.xml` + if (containsBlanks.test(fileName)) { + this.notification.showErrorToast( + 'Error creating a new file. The filename can not contain white spaces.' + ) + } else { + if (fileName !== '.xml') { + this.scope.saveIncomplete = true + this.scope.$broadcast('saveXmlFile', { + file: fileName, + dir, + overwrite + }) + } else { + throw new Error('The name cannot be ".xml"') + } + } + } catch (error) { + this.notification.showWarningToast('Please set a valid name') + } } } controllers.controller('managerDecodersCtrl', Decoders) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/managerDecodersIdCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/managerDecodersIdCtrl.js index d56503aa3..a32cb945b 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/managerDecodersIdCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/decoders/managerDecodersIdCtrl.js @@ -21,7 +21,11 @@ define(['../../module', '../rules/ruleset'], function(controllers, Ruleset) { currentDecoder, $currentDataService, $tableFilterService, - $csvRequestService + $csvRequestService, + extensions, + $fileEditor, + $restartService, + $requestService ) { super( $scope, @@ -30,25 +34,44 @@ define(['../../module', '../rules/ruleset'], function(controllers, Ruleset) { 'decoders', $currentDataService, $tableFilterService, - $csvRequestService + $csvRequestService, + $restartService ) this.state = $state - try { - this.filters = JSON.parse(window.localStorage.decoders) || [] - } catch (err) { - this.filters = [] - } - - this.scope.currentDecoder = currentDecoder.data.data.items[0] + this.extensions = extensions + this.fileEditor = $fileEditor + this.restartService = $restartService + this.requestService = $requestService + this.currentDecoder = currentDecoder } /** * On controller load */ $onInit() { - this.scope.downloadCsv = (path, name) => this.downloadCsv(path, name) - this.scope.addDetailFilter = (name, value) => - this.addDetailFilter(name, value) + try { + try { + this.filters = JSON.parse(window.localStorage.decoders) || [] + } catch (error) { + this.filters = [] + } + this.scope.currentDecoder = this.currentDecoder.data.data.items[0] + this.scope.downloadCsv = (path, name) => this.downloadCsv(path, name) + this.scope.addDetailFilter = (name, value) => + this.addDetailFilter(name, value) + this.scope.adminMode = this.extensions['admin'] === 'true' + this.scope.isLocal = this.scope.currentDecoder.path === 'etc/decoders' + this.scope.saveDecoderConfig = fileName => + this.saveDecoderConfig(fileName) + this.scope.closeEditingFile = () => this.closeEditingFile() + this.scope.editDecoder = fileName => this.editDecoder(fileName) + + this.scope.restart = () => this.restart() + this.scope.closeRestartConfirmation = () => + this.closeRestartConfirmation() + } catch (error) { + this.state.go('mg-decoders') + } } /** @@ -63,7 +86,58 @@ define(['../../module', '../rules/ruleset'], function(controllers, Ruleset) { window.localStorage.setItem('decoders', JSON.stringify(this.filters)) this.state.go('mg-decoders') } catch (err) { - this.toast(err.message || err) + this.notification.showErrorToast(err.message || err) + } + } + + async closeEditingFile() { + try { + //Refresh decoder info + const result = await this.requestService.apiReq( + `/decoders/${this.scope.currentDecoder.name}` + ) + if (result.data.data.totalItems === 0) { + this.state.go('mg-decoders') + } + this.scope.currentDecoder = result.data.data.items[0] + } catch (error) { + this.state.go('mg-decoders') + } + this.scope.editingFile = false + this.scope.$applyAsync() + } + + saveDecoderConfig(fileName) { + this.scope.saveIncomplete = true + this.scope.$broadcast('saveXmlFile', { + file: fileName, + dir: 'decoders', + overwrite: true + }) + } + + async editDecoder(fileName) { + try { + this.scope.editingFile = true + this.scope.fetchedXML = await this.fetchFileContent(fileName) + this.scope.$broadcast('fetchedFile', { data: this.scope.fetchedXML }) + } catch (error) { + this.scope.fetchedXML = null + this.notification.showErrorToast(error.message || error) + } + if (!this.scope.$$phase) this.scope.$digest() + return + } + + async fetchFileContent(fileName) { + try { + const result = await this.fileEditor.getConfiguration( + fileName, + 'decoders' + ) + return result + } catch (error) { + return Promise.reject(error) } } } diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/edition/edition.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/edition/edition.html new file mode 100644 index 000000000..d12fd6734 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/edition/edition.html @@ -0,0 +1,115 @@ + +
+ + +
+ +
+ Management + / + Configuration +
+ +
+ Management + / + Configuration +
+ +
+ +
+ +
+ + + + Manager configuration + Cluster configuration +
+ +
+
+ + + + + + + +
+
+ + +
+
+ {{editingNode}} will be restarted + + + +
+
+ + +
+ +
+ + + + + + +
+
+ + +
+
+ + + +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/edition/editionCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/edition/editionCtrl.js new file mode 100644 index 000000000..58c70041f --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/edition/editionCtrl.js @@ -0,0 +1,155 @@ +define(['../../module'], function(controllers) { + 'use strict' + + class Edition { + /** + * Class Status + * @param {*} $scope + * @param {Array} clusterInfo + * @param {Boolean} isAdmin + */ + constructor( + $scope, + isAdmin, + $notificationService, + clusterInfo, + $fileEditor, + $restartService, + $interval, + $rootScope, + $state + ) { + this.scope = $scope + this.clusterInfo = clusterInfo + this.isAdmin = isAdmin + this.notification = $notificationService + this.clusterInfo = clusterInfo + this.fileEditor = $fileEditor + this.restartService = $restartService + this.interval = $interval + this.rootScope = $rootScope + this.state = $state + } + /** + * On controller loads + */ + $onInit() { + try { + this.scope.restartInProgress = false + this.scope.editingNode = false + this.scope.editNode = nodeName => this.editNode(nodeName) + this.scope.cancelEditNode = () => this.cancelEditNode() + this.scope.saveOssecConfig = () => this.saveOssecConfig() + this.scope.xmlIsValid = valid => this.xmlIsValid(valid) + this.scope.changeNode = node => this.changeNode(node) + this.scope.restart = node => this.restart(node) + this.scope.switchRestart = () => this.switchRestart() + this.scope.closeRestartConfirmation = () => + this.closeRestartConfirmation() + + if (this.clusterInfo && this.clusterInfo.clusterEnabled) { + this.scope.clusterEnabled = this.clusterInfo.clusterEnabled + if (this.clusterInfo.clusterEnabled) { + this.scope.selectedNode = this.clusterInfo.nodes.data.data.items[0].name + this.scope.nodes = this.clusterInfo.nodes.data.data.items + } + this.editNode(this.scope.selectedNode) + } else { + this.editNode() + } + this.scope.isAdmin = this.isAdmin + + /** + * Listeners + */ + + this.scope.$on('saveComplete', event => { + event.stopPropagation() + this.scope.saveIncomplete = false + }) + } catch (error) { + this.notification.showErrorToast(error) + this.state.go('manager') + } + } + + async editNode(nodeName = 'manager') { + try { + const file = 'ossec.conf' + const dir = false + const content = !this.clusterInfo.clusterEnabled + ? await this.fileEditor.getConfiguration(file, dir) + : await this.fileEditor.getConfiguration(file, dir, nodeName) + this.scope.editingNode = nodeName + this.scope.fetchedXML = content + this.scope.$broadcast('fetchedFile', { data: content }) + if (!this.scope.$$phase) this.scope.$digest() + } catch (error) { + this.notification.showErrorToast(`Error editing node: ${error}`) + } + } + + changeNode(node) { + this.editNode(node) + } + + saveOssecConfig() { + const node = + this.scope.editingNode === 'manager' ? false : this.scope.editingNode + this.scope.saveIncomplete = true + this.scope.$broadcast('saveXmlFile', { + file: 'ossec.conf', + dir: false, + node: node, + overwrite: true + }) + } + + xmlIsValid(valid) { + this.scope.xmlHasErrors = valid + if (!this.scope.$$phase) this.scope.$digest() + } + + async restart(node = false) { + try { + this.scope.$broadcast('removeRestartMsg', {}) + + this.scope.restartInProgress = true + let result = '' + if (this.clusterInfo.clusterEnabled && node) { + result = await this.restartService.restartNode(node) + } else { + result = await this.restartService.restart() + } + if (result.startsWith('Restarting cluster')) { + this.rootScope.$broadcast('showHeadToaster', { + type: 'info', + msg: result, + delay: true, + spinner: false + }) + } else { + this.rootScope.$broadcast('wazuhNotReadyYet', { msg: result }) + } + //this.notification.showSimpleToast(result) + this.scope.restartInProgress = false + } catch (error) { + this.rootScope.$broadcast('showHeadToaster', { + type: 'error', + msg: error || `Cannot restart.`, + delay: false, + spinner: false + }) + //this.notification.showErrorToast(error) + this.scope.restartInProgress = false + } + } + + switchRestart() { + this.scope.confirmingRestart = !this.scope.confirmingRestart + this.scope.$applyAsync() + } + } + + controllers.controller('editionCtrl', Edition) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/groups/groups.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/groups/groups.html index 7d3deef83..cdf525851 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/groups/groups.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/groups/groups.html @@ -1,214 +1,208 @@
-
+
Management / Groups / {{currentGroup.name}}
- -
-
+ +
+
- -
-
- - Groups - -
-
- - -
-
- List and check your groups, its agents and files + +
+
+ + Groups + +
+
+ + +
+
+ List and check your groups, its agents and files +
-
- +
- - Go back - - - - -
- - {{currentGroup.name}} -
- -
- Agents - {{ currentGroup.count }} -
-
- Content - {{ totalFiles }} files -
-
- Configuration sum - {{ currentGroup.configSum }} -
-
- Merged sum - {{ currentGroup.mergedSum }} -
-
-
- - +
+ + {{currentGroup.name}} +
- Agents Content -
-
+
+
- Cancel - +
-
- +
+
-
-
- - Cancel - +
+ + It is not possible to apply changes of more than 500 additions or deletions
-
- - +
+ +
-
- - + +
+ + + + Agents ({{err.id}}{{$last ? '): ' : ', '}} + {{groupErr[0].message}} + + +
+ + +
+ + +
+ -
- - -
- + + + - - - +
+ +
+ +
+ -
- -
- -
- + + + + +
+ + +
+ + + + +
+ + + - - - - -
- - -
- - - - - -
+ +
+
+
+ {{ filename }} + + +
-
- {{ filename }} - - -
-
-
-
+
- -
-
- +{{currentAdding}} -{{currentDeleting}} - -
+ +
+
+ +{{currentAdding}} -{{currentDeleting}} + +
- +
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/groups/groupsCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/groups/groupsCtrl.js index 2f09d0b9f..45441ba84 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/groups/groupsCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/groups/groupsCtrl.js @@ -35,7 +35,7 @@ define(['../../module', 'FileSaver'], function(controllers) { this.csvReq = $csvRequestService this.wzTableFilter = $tableFilterService this.apiReq = $requestService.apiReq - this.toast = $notificationService.showSimpleToast + this.notification = $notificationService this.mainGroup = '' this.scope.lookingGroup = false this.scope.editingFile = false @@ -54,7 +54,6 @@ define(['../../module', 'FileSaver'], function(controllers) { loadedAll: false } this.scope.addMultipleAgents(false) - this.scope.$broadcast('closeEditXmlFile', {}) if (!value) { this.scope.file = false this.scope.filename = false @@ -71,17 +70,29 @@ define(['../../module', 'FileSaver'], function(controllers) { if (!this.scope.$$phase) this.scope.$digest() }) + // Come from the pencil icon on the groups table + this.scope.$on('openGroupFromList', (ev, parameters) => { + ev.stopPropagation() + this.scope.editingFile = true + this.scope.groupsSelectedTab = 'files' + return this.scope + .loadGroup(parameters.group) + .then(() => this.scope.editGroupAgentConfig()) + }) + this.scope.$on('wazuhShowGroup', (event, parameters) => { + event.stopPropagation() this.goBackToAgents() return this.loadGroup(parameters.group) }) - this.scope.$on('configurationSuccess',() => { + this.scope.$on('configurationSuccess', () => { this.scope.editingFile = false - if(!this.scope.$$phase) this.scope.$digest() + if (!this.scope.$$phase) this.scope.$digest() }) this.scope.$on('wazuhShowGroupFile', (event, parameters) => { + event.stopPropagation() if ( ((parameters || {}).fileName || '').includes('agent.conf') && this.scope.adminMode @@ -93,6 +104,7 @@ define(['../../module', 'FileSaver'], function(controllers) { this.scope.$on('updateGroupInformation', async (event, parameters) => { try { + event.stopPropagation() if (this.scope.currentGroup) { const result = await Promise.all([ await this.apiReq(`/agents/groups/${parameters.group}`, { @@ -116,11 +128,25 @@ define(['../../module', 'FileSaver'], function(controllers) { } } } catch (error) { - this.toast(error.message || error) + this.notification.showErrorToast(error.message || error) } if (!this.scope.$$phase) this.scope.$digest() return }) + + this.scope.$on('openGroupFromList', (ev, parameters) => { + ev.stopPropagation() + this.scope.editingFile = true + this.scope.groupsSelectedTab = 'files' + return this.scope + .loadGroup(parameters.group) + .then(() => this.scope.editGroupAgentConfig()) + }) + + this.scope.$on('saveComplete', event => { + event.stopPropagation() + this.scope.saveIncomplete = false + }) } /** @@ -140,9 +166,15 @@ define(['../../module', 'FileSaver'], function(controllers) { try { this.scope.addingGroup = false await this.groupHandler.createGroup(name) - this.toast(`Success. Group ${name} has been created`) + this.notification.showSuccessToast( + `Success. Group ${name} has been created` + ) + // refresh the table when a new group is created + this.scope.search = term => { + this.scope.$broadcast('wazuhSearch', { term }) + } } catch (error) { - this.toast(`${error.message || error}`) + this.notification.showErrorToast(`${error.message || error}`) } this.scope.$broadcast('wazuhSearch', {}) } @@ -203,7 +235,7 @@ define(['../../module', 'FileSaver'], function(controllers) { } catch (err) { console.error('err ', err) this.scope.adminMode = true - this.toast('Error loading groups information') + this.notification.showErrorToast('Error loading groups information') } } @@ -212,8 +244,10 @@ define(['../../module', 'FileSaver'], function(controllers) { */ async downloadCsv(path, name) { try { - this.toast('Your download should begin automatically...') - const currentApi = this.api.id + this.notification.showSimpleToast( + 'Your download should begin automatically...' + ) + const currentApi = this.api['_key'] const output = await this.csvReq.fetch( path, currentApi, @@ -223,7 +257,7 @@ define(['../../module', 'FileSaver'], function(controllers) { saveAs(blob, name) // eslint-disable-line return } catch (error) { - this.toast('Error downloading CSV') + this.notification.showErrorToast('Error downloading CSV') } return } @@ -233,6 +267,7 @@ define(['../../module', 'FileSaver'], function(controllers) { * @param {Boolean} firstLoad */ async loadGroup(group, firstLoad) { + this.scope.load = true try { if (!firstLoad) this.scope.lookingGroup = true const count = await this.apiReq(`/agents/groups/${group.name}/files`, { @@ -244,8 +279,9 @@ define(['../../module', 'FileSaver'], function(controllers) { this.mainGroup = group if (!this.scope.$$phase) this.scope.$digest() } catch (error) { - this.toast('Cannot load group data') + this.notification.showErrorToast('Cannot load group data') } + this.scope.load = false return } @@ -287,7 +323,7 @@ define(['../../module', 'FileSaver'], function(controllers) { this.scope.multipleSelectorLoading = false if (!this.scope.$$phase) this.scope.$digest() } catch (error) { - this.toast(error.message || error) + this.notification.showErrorToast(error.message || error) } } @@ -324,7 +360,7 @@ define(['../../module', 'FileSaver'], function(controllers) { this.scope.selectedAgents.loadedAll = true } } catch (error) { - this.toast(error.message || error) + this.notification.showErrorToast(error.message || error) } this.scope.selectedAgents.loaded = true } @@ -370,12 +406,13 @@ define(['../../module', 'FileSaver'], function(controllers) { } } } catch (error) { - this.toast(error.message || error) + this.notification.showErrorToast(error.message || error) } } async addMultipleAgents(toggle) { try { + if (toggle) this.scope.errorsEditingGroup = false this.scope.addingAgents = toggle if (toggle && !this.scope.availableAgents.loaded) { this.scope.availableAgents = { @@ -400,7 +437,7 @@ define(['../../module', 'FileSaver'], function(controllers) { this.scope.multipleSelectorLoading = false } } catch (err) { - this.toast('Error adding agents.') + this.notification.showErrorToast('Error adding agents.') } if (!this.scope.$$phase) this.scope.$digest() return @@ -432,51 +469,66 @@ define(['../../module', 'FileSaver'], function(controllers) { } } } catch (error) { - this.toast(error.message || error, 'Groups') + this.notification.showErrorToast(error.message || error, 'Groups') } if (!this.scope.$$phase) this.scope.$digest() return } async saveAddAgents() { + this.scope.errorsEditingGroup = false const itemsToSave = this.getItemsToSave() const failedIds = [] + let response try { this.scope.multipleSelectorLoading = true + // Adds agents to a group if (itemsToSave.addedIds.length) { - const addResponse = await this.apiReq( + response = await this.apiReq( `/agents/group/${this.scope.currentGroup.name}`, { ids: itemsToSave.addedIds }, 'POST' ) - if (addResponse.data.error !== 0) { - throw new Error(addResponse.data.error) + if (response.data.error !== 0) { + throw new Error(response.data.error) } - if (addResponse.data.data.failed_ids) { - failedIds.push(...addResponse.data.data.failed_ids) + if (response.data.data.failed_ids) { + failedIds.push(...response.data.data.failed_ids) } } + // Delete agents from a group if (itemsToSave.deletedIds.length) { - const deleteResponse = await this.apiReq( + response = await this.apiReq( `/agents/group/${this.scope.currentGroup.name}`, { ids: itemsToSave.deletedIds }, 'DELETE' ) - if (deleteResponse.data.error !== 0) { - throw new Error(deleteResponse.data.error) + if (response.data.error !== 0) { + throw new Error(response.data.error) } - if (deleteResponse.data.data.failed_ids) { - failedIds.push(...deleteResponse.data.data.failed_ids) + if (response.data.data.failed_ids) { + failedIds.push(...response.data.data.failed_ids) } } if (failedIds.length) { - this.toast( - `Warning. Group has been updated but an error has occurred with the following agents ${failedIds}` + const failedErrors = failedIds.map(item => ({ + id: (item || {}).id, + message: ((item || {}).error || {}).message + })) + const groupedFailedIds = + this.groupBy(failedErrors, 'message') || false + this.scope.errorsEditingGroup = groupedFailedIds + this.notification.showWarningToast( + `Group has been updated but an error has occurred with ${ + failedIds.length + } agents` ) } else { - this.toast('Success. Group has been updated') + this.notification.showSuccessToast( + response.data.data.msg || 'Success. Group has been updated' + ) } this.scope.addMultipleAgents(false) this.scope.multipleSelectorLoading = false @@ -485,7 +537,10 @@ define(['../../module', 'FileSaver'], function(controllers) { }) } catch (err) { this.scope.multipleSelectorLoading = false - this.toast(err.message || err, 'Error applying changes') + this.notification.showErrorToast( + err.message || err, + 'Error applying changes' + ) } if (!this.scope.$$phase) this.scope.$digest() return @@ -498,7 +553,7 @@ define(['../../module', 'FileSaver'], function(controllers) { this.scope.$broadcast('fetchedFile', { data: this.scope.fetchedXML }) } catch (error) { this.scope.fetchedXML = null - this.toast(error.message || error) + this.notification.showErrorToast(error.message || error) } if (!this.scope.$$phase) this.scope.$digest() return @@ -523,10 +578,8 @@ define(['../../module', 'FileSaver'], function(controllers) { group: this.scope.currentGroup.name }) } catch (error) { - this.toast(error.message || error) + this.notification.showErrorToast(error.message || error) } - this.scope.editingFile = false - if (!this.scope.$$phase) this.scope.$digest() return } @@ -581,7 +634,7 @@ define(['../../module', 'FileSaver'], function(controllers) { closeEditingFile() { this.scope.editingFile = false - this.scope.$broadcast('closeEditXmlFile', {}) + if (!this.scope.$$phase) this.scope.$digest() } xmlIsValid(valid) { @@ -590,6 +643,7 @@ define(['../../module', 'FileSaver'], function(controllers) { } doSaveGroupAgentConfig() { + this.scope.saveIncomplete = true this.scope.$broadcast('saveXmlFile', { group: this.scope.currentGroup.name }) @@ -621,6 +675,7 @@ define(['../../module', 'FileSaver'], function(controllers) { * Navigates to files */ goBackFiles() { + this.scope.errorsEditingGroup = false this.scope.groupsSelectedTab = 'files' this.scope.addingAgents = false this.scope.editingAgents = false @@ -635,6 +690,7 @@ define(['../../module', 'FileSaver'], function(controllers) { * Navigates to groups */ goBackGroups() { + this.scope.errorsEditingGroup = false this.scope.currentGroup = false this.scope.lookingGroup = false this.scope.editingFile = false @@ -657,10 +713,33 @@ define(['../../module', 'FileSaver'], function(controllers) { this.scope.filename = fileName if (!this.scope.$$phase) this.scope.$digest() } catch (error) { - this.toast('Error showing file ') + this.notification.showErrorToast('Error showing file ') } return } + + /** + * Group by any key + * @param {Obj} collection + * @param {String} property + */ + groupBy(collection, property) { + try { + const values = [] + const result = [] + for (const item of collection) { + const index = values.indexOf(item[property]) + if (index > -1) result[index].push(item) + else { + values.push(item[property]) + result.push([item]) + } + } + return result.length ? result : false + } catch (error) { + return false + } + } } controllers.controller('groupsCtrl', Groups) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/index.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/index.js index 0536da274..351f8b651 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/index.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/index.js @@ -8,5 +8,10 @@ define([ './reporting/reportingCtrl', './rules/managerRulesetCtrl', './rules/managerRulesetIdCtrl', - './status/statusCtrl' + './status/statusCtrl', + './edition/editionCtrl', + './cdb/managerCdbCtrl', + './cdb/managerCdbIdCtrl', + './status/statusCtrl', + './configuration/edit-configuration/editGroupsCtrl' ], function() {}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/logs/manager-logs.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/logs/manager-logs.html index 435a2125e..2664a2548 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/logs/manager-logs.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/logs/manager-logs.html @@ -1,75 +1,121 @@
-
+
Management / Logs
- -
- - Logs - Review the logs of all Wazuh manager daemons -
- - - -
- - - - - - - - - - - - - Play realtime - - - - Stop realtime - -
- -
- - - -
- - - -
- - + +
+ + + + Status + + Logs + Cluster + + Reporting + + + + +
+ + + + + + + + + + + + +
+ +
+ + + + + +
+
-
- - Formatted - - +
+
+
+ + + +
+ + +
+
+ +
+ + + +
+
+
+ + No results match your search criteria +
+
+
+ + \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/logs/managerLogsCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/logs/managerLogsCtrl.js index 124c68632..eb18fd3e9 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/logs/managerLogsCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/logs/managerLogsCtrl.js @@ -23,14 +23,20 @@ define(['../../module', 'FileSaver'], function(app) { ) { this.scope = $scope this.apiReq = $requestService.apiReq - this.toast = $notificationService.showSimpleToast + this.notification = $notificationService this.scope.type_log = 'all' this.scope.category = 'all' + this.scope.sortFilter = false this.api = $currentDataService.getApi() this.logs = logs this.csvReq = $csvRequestService this.wzTableFilter = $tableFilterService this.path = '/manager/logs' + this.scope.$on('scrolledToBottom', (ev, parameters) => { + ev.stopPropagation() + if (!this.scope.realtime) + this.scope.$broadcast('increaseLogs', { lines: parameters.lines }) + }) } /** @@ -38,6 +44,7 @@ define(['../../module', 'FileSaver'], function(app) { */ $onInit() { try { + this.scope.selectedNavTab = 'logs' this.scope.search = term => this.search(term) this.scope.filter = term => this.filter(term) this.scope.changeNode = node => this.changeNode(node) @@ -46,18 +53,62 @@ define(['../../module', 'FileSaver'], function(app) { this.scope.summary = this.logs.data.data this.scope.downloadCsv = () => this.downloadCsv() this.initialize() + + this.scope.sort = () => this.sort() + this.scope.$on('wazuhFetched', (ev, params) => { + ev.stopPropagation() + this.scope.emptyResults = false + if (params.items.length < 1) { + this.scope.emptyResults = true + } else { + this.scope.XMLContent = this.parseLogsToText(params.items) + this.scope.$broadcast('XMLContentReady', { + data: this.scope.XMLContent + }) + } + this.scope.$applyAsync() + }) } catch (err) { - this.toast('Cannot fetch logs data from server') + this.notification.showErrorToast('Cannot fetch logs data from server') + } + } + + /** + * Parse json logs to plane text + * @param {Object} logs + */ + parseLogsToText(logs) { + try { + let result = '' + logs.map(log => { + if (log) { + result += `${log.timestamp} ${log.tag} ${( + log.level || '' + ).toUpperCase()}: ${log.description}\n` + } + }) + return result + } catch (error) { + this.notification.showErrorToast('Cannot parse logs.') } } + /** + * Sorts logs by timestamp + */ + sort() { + this.scope.$broadcast('wazuhSort', { field: 'timestamp' }) + } + /** * Exports the table in CSV format */ async downloadCsv() { try { - this.toast('Your download should begin automatically...') - const currentApi = this.api.id + this.notification.showSimpleToast( + 'Your download should begin automatically...' + ) + const currentApi = this.api['_key'] if (this.clusterEnabled) { this.path = `/cluster/${this.scope.selectedNode}/logs` } @@ -70,11 +121,11 @@ define(['../../module', 'FileSaver'], function(app) { const blob = new Blob([output], { type: 'text/csv' }) // eslint-disable-line saveAs(blob, 'logs.csv') // eslint-disable-line } else { - this.toast('Empty results.') + this.notification.showWarningToast('Empty results.') } return } catch (error) { - this.toast('Error downloading CSV') + this.notification.showErrorToast('Error downloading CSV') } return } @@ -124,7 +175,7 @@ define(['../../module', 'FileSaver'], function(app) { if (!this.scope.$$phase) this.scope.$digest() return } catch (err) { - this.toast('Error initializing data') + this.notification.showErrorToast('Error initializing data') } return } @@ -149,7 +200,7 @@ define(['../../module', 'FileSaver'], function(app) { })) if (!this.scope.$$phase) this.scope.$digest() } catch (error) { - this.toast('Error at fetching logs') + this.notification.showErrorToast('Error at fetching logs') } } diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/monitoring/monitoring.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/monitoring/monitoring.html index 72f68fe01..f9c0628b8 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/monitoring/monitoring.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/monitoring/monitoring.html @@ -1,39 +1,39 @@ -
+
-
+
-
+
Management / - Monitoring + Cluster / {{ currentApi }}
-
+
Management / - Monitoring + Cluster / {{ currentApi }} / Overview
-
+
Management / - Monitoring + Cluster / {{ currentApi }} / Nodes
-
+
Management / - Monitoring + Cluster / {{ currentApi }} / @@ -42,104 +42,119 @@ {{ currentNode.name }}
-
+
- - -
- Monitoring - Visualize your Wazuh cluster nodes and its agents -
- -
-
- - - - Overview - -
- IP - {{configuration.nodes[0] || 'Unknown'}} -
-
- Running - {{ status || 'no' }} -
-
- Version - {{version}} -
-
-
- - - - - - Information - - -
- Nodes - - Click to open the list of nodes - - - {{nodesCount}} - - Click to open the list of nodes - - -
- -
- Agents - - Click to open the list of agents - - - {{agentsCount}} - - Click to open the list of agents - - -
-
-
-
-
- - - Cluster alerts summary - -
-
-
- - - Alerts by node summary - -
-
-
-
+
+ + + + Status + + Logs + Cluster + + Reporting + + +
+
+ + + + Overview + +
+ IP + {{configuration.nodes[0] || 'Unknown'}} +
+
+ Running + {{ status || 'no' }} +
+
+ Version + {{version}} +
+
+
+ + + + + + Information + + +
+ Nodes + + Click to open the list of nodes + + + {{nodesCount}} + + Click to open the list of nodes + + +
+ +
+ Agents + + Click to open the list of agents + + + {{agentsCount}} + + Click to open the list of agents + + +
+
+
- - -
- - - +
+ - Top 5 nodes + Cluster alerts summary -
+
- - + + Alerts by node summary + +
+
+
+
+
+ + +
+
+ + + + + Back + + +
+
+ + + + Top 5 nodes + +
+
+
+ + + Cluster configuration @@ -179,188 +194,224 @@
- -
- - -
- - - {{ currentNode.name }} alerts summary - -
-
-
-
- - - -
- - - - - Node information - -
- IP - {{currentNode.healthCheck.info.ip}} -
-
- Version - {{currentNode.healthCheck.info.version}} -
-
- Type - {{currentNode.healthCheck.info.type}} -
-
- Name - {{currentNode.healthCheck.info.name}} -
-
- Active agents - {{ currentNode.healthCheck.info.n_active_agents }} -
-
-
- - - - - Last files integrity synchronization - -
- Last sync - {{currentNode.healthCheck.status.last_sync_integrity.date_end_master}} -
-
- Duration - {{currentNode.healthCheck.status.last_sync_integrity.duration}} -
-
- Total shared files - {{currentNode.healthCheck.status.last_sync_integrity.total_files.shared}} -
-
- Total missing files - {{currentNode.healthCheck.status.last_sync_integrity.total_files.missing}} -
-
- Total extra but valid files - {{currentNode.healthCheck.status.last_sync_integrity.total_files.extra_valid}} -
-
- Total extra files - {{currentNode.healthCheck.status.last_sync_integrity.total_files.extra}} -
-
-
-
- - - - -
- - - - - Last agents information synchronization - -
- Last sync - {{currentNode.healthCheck.status.last_sync_agentinfo.date_end_master}} -
-
- Duration - {{currentNode.healthCheck.status.last_sync_agentinfo.duration}} -
-
- Total agent info - {{currentNode.healthCheck.status.last_sync_agentinfo.total_agentinfo}} -
-
-
- - - - - Last agents groups synchronization - -
- Last sync - {{currentNode.healthCheck.status.last_sync_agentgroups.date_end_master}} -
-
- Duration - {{currentNode.healthCheck.status.last_sync_agentgroups.duration}} -
-
- Total agent info - {{currentNode.healthCheck.status.last_sync_agentgroups.total_agentgroups}} -
-
-
+
+ +
+
+ + + + + Back + +
- + + +
+ + + {{ currentNode.name }} alerts summary + +
+
+
- -
-
- - -
-
- -
+ + + +
+ + + + + Node information + +
+ IP + {{currentNode.healthCheck.info.ip}} +
+
+ Version + {{currentNode.healthCheck.info.version}} +
+
+ Type + {{currentNode.healthCheck.info.type}} +
+
+ Name + {{currentNode.healthCheck.info.name}} +
+
+ Active agents + {{ currentNode.healthCheck.info.n_active_agents }} +
+
+
+ + + + + Last files integrity + synchronization + +
+ Last sync + {{currentNode.healthCheck.status.last_sync_integrity.date_end_master}} +
+
+ Duration + {{currentNode.healthCheck.status.last_sync_integrity.duration}} +
+
+ Total shared files + {{currentNode.healthCheck.status.last_sync_integrity.total_files.shared}} +
+
+ Total missing files + {{currentNode.healthCheck.status.last_sync_integrity.total_files.missing}} +
+
+ Total extra but valid files + {{currentNode.healthCheck.status.last_sync_integrity.total_files.extra_valid}} +
+
+ Total extra files + {{currentNode.healthCheck.status.last_sync_integrity.total_files.extra}} +
+
+
+
+ + + + +
+ + + + + Last agents information + synchronization + +
+ Last sync + {{currentNode.healthCheck.status.last_sync_agentinfo.date_end_master}} +
+
+ Duration + {{currentNode.healthCheck.status.last_sync_agentinfo.duration}} +
+
+ Total agent info + {{currentNode.healthCheck.status.last_sync_agentinfo.total_agentinfo}} +
+
+
+ + + + + Last agents groups + synchronization + +
+ Last sync + {{currentNode.healthCheck.status.last_sync_agentgroups.date_end_master}} +
+
+ Duration + {{currentNode.healthCheck.status.last_sync_agentgroups.duration}} +
+
+ Total agent info + {{currentNode.healthCheck.status.last_sync_agentgroups.total_agentgroups}} +
+
+
+
+ +
+ +
+
+ + + + + + Back + + + + + +
+
+
- +
- Management + Management / - Monitoring + Manager
- -
- Monitoring - Visualize your Wazuh cluster nodes and its agents -
- - + + + Status + + Logs + Cluster + + Reporting + + + +
- Cluster disabled + Cluster + disabled
-

The cluster is disabled. Visit the documentation on this link to learn about how to enable it. +

The cluster is disabled. Visit the documentation on this link to + learn about how to enable it.

- +
- Cluster not running + Cluster not + running

@@ -371,5 +422,5 @@

- -
+ +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/monitoring/monitoringCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/monitoring/monitoringCtrl.js index c0545ca4f..a134de1ff 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/monitoring/monitoringCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/monitoring/monitoringCtrl.js @@ -40,7 +40,10 @@ define([ this.urlTokenModel.handleValueChange ) - this.toast = $notificationService.showSimpleToast + this.scope.expandArray = [false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + + this.notification = $notificationService this.apiReq = $requestService.apiReq this.vizz = [ new LinearChart( @@ -101,15 +104,18 @@ define([ * On controller load */ $onInit() { + this.scope.selectedNavTab = 'monitoring' this.scope.currentApi = this.currentApi.clusterName || this.currentApi.managerName this.scope.search = term => this.search(term) this.scope.status = 'yes' this.scope.reset = () => this.reset() this.scope.goConfiguration = () => this.goConfiguration() + this.scope.goBack = () => this.goBack() this.scope.goNodes = () => this.goNodes() this.scope.$on('wazuhShowClusterNode', async (event, parameters) => { + event.stopPropagation() try { if (this.checkStatus()) { this.scope.currentNode = parameters.node @@ -186,7 +192,7 @@ define([ } if (!this.scope.$$phase) this.scope.$digest() } catch (error) { - this.toast(error.message || error) + this.notification.showErrorToast(error.message || error) } }) @@ -254,6 +260,10 @@ define([ setBooleans(component) { this.scope.showConfig = component === 'showConfig' this.scope.showNodes = component === 'showNodes' + if(component === 'showClusterMonitoring'){ + this.scope.showConfig = false + this.scope.showNodes = false + } this.scope.currentNode = null if (!this.scope.$$phase) this.scope.$digest() } @@ -272,6 +282,13 @@ define([ this.setBooleans('showNodes') } + /** + * Navigates to cluster monitoring + */ + goBack() { + this.setBooleans('showClusterMonitoring') + } + /** * Launches the searches */ @@ -282,6 +299,29 @@ define([ } sourcetype=wazuh | timechart span=2h count` ) } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('monitoringCtrl', Monitoring) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/reporting/reporting.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/reporting/reporting.html index ab7fb8d60..56807a79d 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/reporting/reporting.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/reporting/reporting.html @@ -1,23 +1,26 @@
-
+
Management / Reporting
- -
-
-
- + +
+
+
+ +
+ + + + Status + Logs + Cluster + Reporting + - -
- Reporting - List and download all the Wazuh app reports -
-
@@ -33,15 +36,27 @@
- -
- Refresh +
+ + + + + + + + + Refresh + + Refresh + +
- +
@@ -52,23 +67,38 @@ - + - +
File Size
{{item.name}} {{item.size / 1024 | number: 2}}KB{{item.date}}{{offsetTimestamp(item.date)}} - + + + Download report + - + + + Delete report +
@@ -88,5 +118,3 @@ - - \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/reporting/reportingCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/reporting/reportingCtrl.js index 24a5f41c2..8a35c3748 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/reporting/reportingCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/reporting/reportingCtrl.js @@ -9,9 +9,9 @@ define(['../../module'], function(app) { * @param {Object} $requestService * @param {Array} reportsList */ - constructor($scope, $notificationService, $requestService, reportsList) { + constructor($scope, $notificationService, $requestService, reportsList, $dateDiffService) { this.scope = $scope - this.toast = $notificationService.showSimpleToast + this.notification = $notificationService this.genericReq = $requestService.httpReq this.loading = true this.itemsPerPage = 15 @@ -20,18 +20,28 @@ define(['../../module'], function(app) { this.items = [] this.scope.gap = 0 this.items = reportsList.data.data + this.setBrowserOffset = $dateDiffService.setBrowserOffset } /** * On controller loads */ $onInit() { + this.scope.selectedNavTab = 'reporting' this.scope.setPage = n => this.setPage(n) this.scope.nextPage = n => this.nextPage(n) this.scope.prevPage = () => this.prevPage() this.scope.load = () => this.load() this.scope.deleteReport = name => this.deleteReport(name) this.load() + + this.scope.offsetTimestamp = time => { + try { + return this.setBrowserOffset(time) + } catch (error) { + return '' + } + } } /** @@ -52,9 +62,9 @@ define(['../../module'], function(app) { this.loading = true await this.genericReq('GET', '/report/remove', { name: name }) await this.load() - this.toast('Deleted report') + this.notification.showSuccessToast('Deleted report.') } catch (error) { - this.toast('Reporting error') + this.notification.showErrorToast('Cannot delete the report.') } } @@ -150,7 +160,7 @@ define(['../../module'], function(app) { this.loading = false if (!this.scope.$$phase) this.scope.$digest() } catch (error) { - this.toast('Error loading reports') + this.notification.showErrorToast('Error loading reports.') } } } diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/manager-ruleset-id.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/manager-ruleset-id.html index 64f6ba79f..35d538d63 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/manager-ruleset-id.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/manager-ruleset-id.html @@ -1,220 +1,299 @@ -
-
-
- Management - / Ruleset -
-
-
-
- -
- - Ruleset - Review all your current rules and decoders -
- -
- - -
- - - - - Back - - - -

- -
- - - -
- - -
ID: - {{ruleInfo.id}} -
-
Level: - {{ruleInfo.level}} - - Filter by this level - - -
-
File: - {{ruleInfo.file}} - - Filter by this file - - -
-
Path: - {{ruleInfo.path}} - - Filter by this path - - -
- -
-
-
- - - -
- -
- - - - - - Groups - -
- - {{item}} - - Filter by this group - - -
-
-
- - - - - - Details - -
- {{key}} - {{value}} - - {{key}}: {{value}} | - -
-
-
- - -
- -
- - - - - - PCI - -
- - {{item}} - - Filter by this requirement - - -
-
-
- - - - - - - GDPR - -
- - {{item}} - - Filter by this requirement - - -
-
-
- - -
- -
- - - - - - Regex - -
-
- {{item}} -
-
-
-
- - - - - - - Match - -
-
- {{item}} -
-
-
-
- - - - - - - Prematch - -
-
- {{item}} -
-
-
-
- - -
- - -
-

- Related rules

-
-
- - -
- - -
- - -
- +
+
+
+ Management + + / Ruleset + + / Rules + / {{ ruleInfo.id }} +
+
+
+
+ +
+ + + Rules + + Decoders + + Lists + + + + +
+ + + + + Back + + + +

+
+ + + +
+ + +
+ ID: + {{ ruleInfo.id }} +
+
+ Level: + {{ ruleInfo.level }} + + Filter by this level + + +
+
+ File: + {{ ruleInfo.file }} + + Filter by this file + + +
+
+ Path: + {{ ruleInfo.path }} + + Filter by this path + + +
+
+
+
+ + + +
+ +
+ + +
+
+ + + + + Details + +
+
+
+
{{ key }}
+
+
+ {{ value }} + + {{ key }}: {{ value }} | + + +
+ + {{ v }}{{ $last ? "" : ", " }} + +
+
+
+
+
+ {{ key }} + {{ v }}{{ $last ? "" : ", " }} +
+
+
+ + + + + + + Groups + +
+
+
+ + {{ item }} + + Filter by this group + + +
+
+
+
+
+ + + + + + + Compliance + + +
+
+
+
PCI DSS
+
+ + {{ item }} + +
+
+
+
+
+
+
+
GDPR
+
+ + {{ item }} + +
+
+
+
+
+
+ +
+ +
+ + + + + + Regex + +
+
+ {{ item }} +
+
+
+
+ + + + + + + Match + +
+
+ {{ item }} +
+
+
+
+ + + + + + + + Prematch + +
+
+ {{ item }} +
+
+
+
+ +
+ + + + +
+

+ + Related rules +

+
+
+ + +
+ +
+
+ + +
+
+ + Cancel + +
+
+ + +
+
+ + +
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/manager-ruleset.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/manager-ruleset.html index 88e98fe00..c3315c087 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/manager-ruleset.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/manager-ruleset.html @@ -1,81 +1,179 @@
-
+
Management - / Ruleset + / Ruleset + / Rules
- -
- - Ruleset - Review all your current rules and decoders -
- +
+ + + + Rules + Decoders + Lists + -
-
+
+
+
- - +
+
+ +
+
+ +
+ + +
- - - Rules - - - - Decoders -
+ + - - - File: {{getFilter('file')}} - - - - - Path: {{getFilter('path')}} - - - - - Level: {{getFilter('level')}} - + + Add new rules file + + Manage rules files - - - Group: {{getFilter('group')}} - - - - - PCI control: {{getFilter('pci')}} - - - - - GDPR: {{getFilter('gdpr')}} - + + + + + + + + File: {{getFilter('file')}} + + + + + Path: {{getFilter('path')}} + + + + + Level: {{getFilter('level')}} + + + + + Group: {{getFilter('group')}} + + + + + PCI control: {{getFilter('pci')}} + + + + + GDPR: {{getFilter('gdpr')}} + + + + +
+ + + + + + + + +
+ +
+
+
+ + +
+
+ + + + +
+
+ + +
+
+ + + +
+
+ + + +
-
- - Formatted - - +
+ +
+
+ + +
+ +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/managerRulesetCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/managerRulesetCtrl.js index 1b484521e..27cf10790 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/managerRulesetCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/managerRulesetCtrl.js @@ -17,7 +17,10 @@ define(['../../module', './ruleset'], function(controllers, Ruleset) { $notificationService, $currentDataService, $tableFilterService, - $csvRequestService + $csvRequestService, + $restartService, + isAdmin, + $fileEditor ) { super( $scope, @@ -26,17 +29,29 @@ define(['../../module', './ruleset'], function(controllers, Ruleset) { 'ruleset', $currentDataService, $tableFilterService, - $csvRequestService + $csvRequestService, + $restartService, + $fileEditor ) + this.isAdmin = isAdmin } /** * On controller load */ $onInit() { + this.scope.adminMode = this.isAdmin + this.scope.localFilter = false this.scope.downloadCsv = (path, name) => this.downloadCsv(path, name) this.scope.$broadcast('wazuhSearch', { term: '', removeFilters: true }) - this.scope.$on('loadedTable', () => { + this.scope.addNewFile = () => this.addNewFile() + this.scope.saveRuleConfig = (fileName, dir, overwrite) => + this.saveRuleConfig(fileName, dir, overwrite) + + this.scope.selectedNavTab = 'rules' + + this.scope.$on('loadedTable', event => { + event.stopPropagation() try { if (window.localStorage.ruleset) { const parsedFilter = JSON.parse(window.localStorage.ruleset) @@ -46,19 +61,53 @@ define(['../../module', './ruleset'], function(controllers, Ruleset) { } } } catch (err) { - this.toast('Error applying filter') + this.notification.showErrorToast('Error applying filter') } }) + } - this.scope.$on('rulesetIsReloaded', () => { - this.scope.viewingDetail = false - if (!this.scope.$$phase) this.scope.$digest() - }) + /** + * Open the editor for a new file + */ + addNewFile() { + this.scope.overwrite = false + this.scope.editingFile = { + file: ``, + dir: `rules` + } + this.scope.addingNewFile = true + this.scope.fetchedXML = `` + } - this.scope.$on('wazuhShowRule', () => { - this.scope.viewingDetail = true - if (!this.scope.$$phase) this.scope.$digest() - }) + /** + * Save the new content + * @param {String} fileName + * @param {String} dir + */ + saveRuleConfig(fileName, dir, overwrite = false) { + try { + const containsBlanks = /.* .*/ + fileName = this.scope.editingFile.file + fileName = fileName.endsWith('.xml') ? fileName : `${fileName}.xml` + if (containsBlanks.test(fileName)) { + this.notification.showErrorToast( + 'Error creating a new file. The filename can not contain white spaces.' + ) + } else { + if (fileName !== '.xml') { + this.scope.saveIncomplete = true + this.scope.$broadcast('saveXmlFile', { + file: fileName, + dir, + overwrite + }) + } else { + throw new Error('The name cannot be ".xml"') + } + } + } catch (error) { + this.notification.showWarningToast('Please set a valid name') + } } } controllers.controller('managerRulesetCtrl', Rules) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/managerRulesetIdCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/managerRulesetIdCtrl.js index b5781110e..3d6c07e8c 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/managerRulesetIdCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/managerRulesetIdCtrl.js @@ -12,6 +12,7 @@ define(['../../module', './ruleset'], function(controllers, Ruleset) { * @param {*} $currentDataService * @param {*} $tableFilterService * @param {*} $csvRequestService + * @param {*} $fileEditor */ constructor( $scope, @@ -21,7 +22,11 @@ define(['../../module', './ruleset'], function(controllers, Ruleset) { ruleInfo, $currentDataService, $tableFilterService, - $csvRequestService + $csvRequestService, + extensions, + $fileEditor, + $restartService, + $requestService ) { super( $scope, @@ -30,16 +35,28 @@ define(['../../module', './ruleset'], function(controllers, Ruleset) { 'ruleset', $currentDataService, $tableFilterService, - $csvRequestService + $csvRequestService, + $restartService ) this.state = $state + this.extensions = extensions + this.fileEditor = $fileEditor + this.restartService = $restartService + this.requestService = $requestService try { this.filters = JSON.parse(window.localStorage.ruleset) || [] } catch (err) { this.filters = [] } - this.scope.ruleInfo = ruleInfo.data.data.items[0] + //Check if the rule is overwritted + const response = (((ruleInfo || {}).data || {}).data || {}).items || [] + if (response.length) { + const result = response.filter(rule => rule.details.overwrite) + this.scope.ruleInfo = result.length ? result[0] : response[0] + } else { + this.scope.ruleInfo = false + } if ( !(Object.keys((this.scope.ruleInfo || {}).details || {}) || []).length ) { @@ -55,6 +72,14 @@ define(['../../module', './ruleset'], function(controllers, Ruleset) { this.scope.downloadCsv = (path, name) => this.downloadCsv(path, name) this.scope.addDetailFilter = (name, value) => this.addDetailFilter(name, value) + this.scope.adminMode = this.extensions['admin'] === 'true' + this.scope.isLocal = this.scope.ruleInfo.path === 'etc/rules' + this.scope.saveRuleConfig = fileName => this.saveRuleConfig(fileName) + this.scope.closeEditingFile = () => this.closeEditingFile() + this.scope.editRule = fileName => this.editRule(fileName) + this.scope.restart = () => this.restart() + this.scope.closeRestartConfirmation = () => + this.closeRestartConfirmation() } /** @@ -69,7 +94,63 @@ define(['../../module', './ruleset'], function(controllers, Ruleset) { window.localStorage.setItem('ruleset', JSON.stringify(this.filters)) this.state.go('mg-rules') } catch (err) { - this.toast(err.message || err) + this.notification.showErrorToast(err.message || err) + } + } + + async closeEditingFile() { + try { + //Refresh rule info + const ruleReloaded = await this.requestService.apiReq( + `/rules/${this.scope.ruleInfo.id}` + ) + if (ruleReloaded.data.data.totalItems === 0) { + this.state.go('mg-rules') + } + //Check if the rule is overwritted + const response = + (((ruleReloaded || {}).data || {}).data || {}).items || [] + if (response.length) { + const result = response.filter(rule => rule.details.overwrite) + this.scope.ruleInfo = result.length ? result[0] : response[0] + } else { + this.scope.ruleInfo = false + } + } catch (error) { + this.state.go('mg-rules') + } + this.scope.editingFile = false + this.scope.$applyAsync() + } + + saveRuleConfig(fileName) { + this.scope.saveIncomplete = true + this.scope.$broadcast('saveXmlFile', { + file: fileName, + dir: 'rules', + overwrite: true + }) + } + + async editRule(fileName) { + try { + this.scope.editingFile = true + this.scope.fetchedXML = await this.fetchFileContent(fileName) + this.scope.$broadcast('fetchedFile', { data: this.scope.fetchedXML }) + } catch (error) { + this.scope.fetchedXML = null + this.notification.showErrorToast(error.message || error) + } + if (!this.scope.$$phase) this.scope.$digest() + return + } + + async fetchFileContent(fileName) { + try { + const result = await this.fileEditor.getConfiguration(fileName, 'rules') + return result + } catch (error) { + return Promise.reject(error) } } } diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/ruleset.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/ruleset.js index 912075558..022c958da 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/ruleset.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/rules/ruleset.js @@ -11,6 +11,7 @@ define(['../../module', 'FileSaver'], function(app) { * @param {*} $currentDataService * @param {*} $tableFilterService * @param {*} $csvRequestService + * @param {*} $restartService */ constructor( $scope, @@ -19,15 +20,18 @@ define(['../../module', 'FileSaver'], function(app) { view, $currentDataService, $tableFilterService, - $csvRequestService + $csvRequestService, + $restartService, + $fileEditor ) { this.scope = $scope this.view = view - this.toast = $notificationService.showSimpleToast + this.notification = $notificationService this.api = $currentDataService.getApi() this.wzTableFilter = $tableFilterService this.csvReq = $csvRequestService this.sce = $sce + this.restartService = $restartService this.colors = [ '#004A65', '#00665F', @@ -60,6 +64,7 @@ define(['../../module', 'FileSaver'], function(app) { '#25B23B', 'E045E5' ] + this.fileEditor = $fileEditor this.scope.appliedFilters = [] try { this.filter = JSON.parse(window.localStorage[`${this.view}`]) || [] @@ -76,6 +81,8 @@ define(['../../module', 'FileSaver'], function(app) { * On controller load */ initialize() { + this.scope.rulesetFiles = false + this.setInitialCustomFilters() this.view === 'decoders' ? delete window.localStorage.ruleset : delete window.localStorage.decoders @@ -92,6 +99,49 @@ define(['../../module', 'FileSaver'], function(app) { this.scope.colorRegex = regex => this.colorRegex(regex) } this.scope.colorOrder = order => this.colorOrder(order) + this.scope.restart = () => this.restart() + this.scope.closeRestartConfirmation = () => + this.closeRestartConfirmation() + + this.scope.enableSave = () => this.enableSave() + + this.scope.switchFiles = () => this.switchFiles() + + this.scope.closeEditingFile = () => this.closeEditingFile() + this.scope.xmlIsValid = valid => this.xmlIsValid(valid) + this.scope.saveFile = file => this.saveFile(file) + + this.scope.$on('configSavedSuccessfully', event => { + event.stopPropagation() + this.scope.overwrite = false + }) + this.scope.$on('saveComplete', event => { + event.stopPropagation() + this.scope.saveIncomplete = false + }) + this.scope.$on('fileAlreadyExists', event => { + event.stopPropagation() + this.scope.saveIncomplete = false + this.scope.overwrite = true + this.scope.$applyAsync() + }) + + this.scope.$on('editFile', (ev, params) => { + ev.stopPropagation() + this.editFile(params.file, params.path, params.readOnly) + }) + + this.scope.$on('performRestart', event => { + event.stopPropagation() + this.restart() + }) + } + + /** + * Switch between rules or files table + */ + switchFiles() { + this.scope.rulesetFiles = !this.scope.rulesetFiles } /** @@ -99,8 +149,10 @@ define(['../../module', 'FileSaver'], function(app) { */ async downloadCsv(path, name) { try { - this.toast('Your download should begin automatically...') - const currentApi = this.api.id + this.notification.showSimpleToast( + 'Your download should begin automatically...' + ) + const currentApi = this.api['_key'] const output = await this.csvReq.fetch( path, currentApi, @@ -110,7 +162,7 @@ define(['../../module', 'FileSaver'], function(app) { saveAs(blob, name) // eslint-disable-line return } catch (error) { - this.toast('Error downloading CSV') + this.notification.showErrorToast('Error downloading CSV') } return } @@ -120,22 +172,25 @@ define(['../../module', 'FileSaver'], function(app) { * @param {*} regex */ colorRegex(regex) { - regex = regex.toString() - let valuesArray = regex.match(/\(((?!<\/span>).)*?\)(?!<\/span>)/gim) - let coloredString = regex - if (valuesArray && valuesArray.length) { - for (let i = 0, len = valuesArray.length; i < len; i++) { - coloredString = coloredString.replace( - /\(((?!<\/span>).)*?\)(?!<\/span>)/im, - '' + - valuesArray[i] + - '' - ) + if (regex) { + regex = regex.toString() + let valuesArray = regex.match(/\(((?!<\/span>).)*?\)(?!<\/span>)/gim) + let coloredString = regex + if (valuesArray && valuesArray.length) { + for (let i = 0, len = valuesArray.length; i < len; i++) { + coloredString = coloredString.replace( + /\(((?!<\/span>).)*?\)(?!<\/span>)/im, + '' + + valuesArray[i] + + '' + ) + } } + return this.sce.trustAsHtml(coloredString) } - return this.sce.trustAsHtml(coloredString) + return } /** @@ -179,6 +234,7 @@ define(['../../module', 'FileSaver'], function(app) { * @param {String} term */ search(term) { + let clearInput = true if (!term) term = '' if ( this.view === 'ruleset' && @@ -257,8 +313,15 @@ define(['../../module', 'FileSaver'], function(app) { this.scope.appliedFilters.push(filter) this.scope.$broadcast('wazuhFilter', { filter }) } else { + clearInput = false this.scope.$broadcast('wazuhSearch', { term, removeFilters: false }) } + if (clearInput) { + const searchBar = $('#search-input-rules') + searchBar.val('') + } + this.scope.$applyAsync() + this.applyCustomFilters() return } @@ -298,9 +361,62 @@ define(['../../module', 'FileSaver'], function(app) { } }) } + this.applyCustomFilters() return this.scope.$broadcast('wazuhRemoveFilter', { filterName }) } catch (err) { - this.toast('Error removing the filter') + this.notification.showErrorToast('Error removing the filter') + } + } + + /** + * Gets the path from the state name + */ + getPathFromState() { + try { + const state = window.sessionStorage.getItem('params') + if (state === 'mg-rules') { + return 'etc/rules' + } else if (state === 'mg-decoders') { + return 'etc/decoders' + } + return false + } catch (error) { + return false + } + } + + /** + * Sets initial filters + */ + setInitialCustomFilters() { + try { + const path = this.getPathFromState() + if (path) { + this.scope.appliedCustomFilters = [{ name: 'path', value: path }] + } + } catch (error) { + this.notification.showErrorToast('Cannot initialize custom filters.') + } + } + + /** + * Adds or remove filters for the local rules or decoders + */ + applyCustomFilters() { + try { + const path = this.getPathFromState() + if (path) { + const filters = [{ name: 'path', value: path }] + const restFilters = this.scope.appliedFilters.filter( + item => item.name !== 'path' + ) + filters.push(...restFilters) + this.scope.appliedCustomFilters = filters + } + } catch (error) { + this.notification.showErrorToast( + 'Cannot apply filter for custom rules or decoders files.' + ) } } @@ -314,6 +430,120 @@ define(['../../module', 'FileSaver'], function(app) { .map(item => item.name) .includes(filterName) } + + /** + * Restarts the manager or cluster + */ + async restart() { + try { + const result = await this.restartService.restart() + this.notification.showSimpleToast(result) + } catch (error) { + this.notification.showErrorToast(error) + } + } + + /** + * Enables save button + */ + enableSave() { + this.scope.overwrite = false + } + + /** + * Close editor + */ + closeEditingFile() { + this.scope.editingRulesetFile = false + this.scope.editingFile = false + this.scope.addingNewFile = false + this.scope.overwrite = false + this.scope.fetchedXML = '' + this.scope.XMLContent = false + } + + /** + * Check if XML is valid + * @param {Boolean} valid + */ + xmlIsValid(valid) { + this.scope.xmlHasErrors = valid + this.scope.$applyAsync() + } + + /** + * Open xml editior box + * @param {String} file + */ + async editFile(file, path, readOnly = false) { + try { + if (readOnly) { + this.scope.XMLContent = await this.fetchFileContent( + `${path}/${file}`, + readOnly + ) + this.scope.$broadcast('XMLContentReady', { + data: this.scope.XMLContent + }) + this.scope.fileName = file + } else { + this.scope.editingRulesetFile = { + file, + path: `${path}/${file}` + } + this.scope.fetchedXML = await this.fetchFileContent(`${path}/${file}`) + this.scope.$broadcast('fetchedFile', { data: this.scope.fetchedXML }) + } + } catch (error) { + this.scope.fetchedXML = null + this.notification.showErrorToast(error.message || error) + } + this.scope.$applyAsync() + return + } + + /** + * Saves the file content + * @param {String} file + */ + saveFile(file) { + this.scope.saveIncomplete = true + this.scope.$broadcast('saveXmlFile', { + file, + overwrite: true + }) + } + + /** + * Fetchs file content + * @param {String} file + */ + async fetchFileContent(file, readOnly = false) { + try { + const result = await this.fileEditor.getConfiguration( + file, + null, + null, + readOnly + ) + return result + } catch (error) { + return Promise.reject(error) + } + } + + /** + * Fetchs readable file content + * @param {String} file + */ + async fetchReadableFileContent(file) { + try { + const result = await this.fileEditor.getConfiguration(file) + return result + } catch (error) { + return Promise.reject(error) + } + } } app.controller('managerRulesetCtrl', Ruleset) return Ruleset diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/status/status.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/status/status.html index 5bbb1fc9b..2fd1af00b 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/status/status.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/status/status.html @@ -1,53 +1,85 @@
-
+
Management / Status
-
- + + +
+
+
+ The {{clusterEnabled ? "cluster" : "manager"}} will be restarted. + + +
+
+ + +
+
- -
- - Status - Check the status of all Wazuh manager daemons -
- - -
-
-
- -
-
+
+
- - {{clusterError}} + + {{clusterError}}
+
-
-
- - -
-

-

{{k}}

-
+
+ + +
+

+

{{daemon.key}}

+
- + -
- +
+
Total agents: {{agentsCountTotal}} @@ -69,13 +101,14 @@
- +
- {{nodeId}} information Manager information + {{nodeId}} information Manager + information
Version @@ -112,7 +145,7 @@ - + @@ -149,10 +182,10 @@
Operating system - {{agentInfo.os.name ? agentInfo.os.name + agentInfo.os.version : agentInfo.os.uname ? agentInfo.os.uname : '-'}} + {{agentInfo.os.name ? agentInfo.os.name + agentInfo.os.version : + agentInfo.os.uname ? agentInfo.os.uname : '-'}}
-
-
\ No newline at end of file +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/status/statusCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/management/status/statusCtrl.js index e67196f24..90cfcd731 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/status/statusCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/status/statusCtrl.js @@ -9,18 +9,22 @@ define(['../../module'], function(controllers) { * @param {*} $notificationService * @param {Array} statusData * @param {Object} agentInfo + * @param {Boolean} isAdmin + * @param {*} $restartService */ constructor( $scope, $requestService, $notificationService, statusData, - agentInfo + agentInfo, + isAdmin, + $restartService ) { this.scope = $scope this.scope.load = true this.apiReq = $requestService.apiReq - this.toast = $notificationService.showSimpleToast + this.notification = $notificationService const parsedStatusData = statusData.map(item => item && item.data && item.data.data ? item.data.data : item ) @@ -44,12 +48,19 @@ define(['../../module'], function(controllers) { this.decoders = decoders this.scope.clusterEnabled = masterNode || false this.agentInfo = agentInfo.data.data + this.isAdmin = isAdmin + this.restartService = $restartService } /** * On controller loads */ $onInit() { + this.scope.selectedNavTab = 'status' + this.scope.confirmingRestart = false + this.scope.isAdmin = this.isAdmin + this.scope.switchRestart = () => this.switchRestart() + this.scope.restartInProgress = false if (this.masterNode && this.masterNode.name) { const masterNodeName = this.masterNode.name this.scope.nodeId = masterNodeName @@ -65,16 +76,29 @@ define(['../../module'], function(controllers) { this.scope.load = false if (!this.scope.$$phase) this.scope.$digest() } + this.scope.changeNode = node => this.changeNode(node) + this.scope.restart = () => this.restart() this.bindStatus() + if (this.nodeStatus) { - this.scope.daemons = this.nodeStatus + this.scope.daemons = this.objToArr(this.nodeStatus) } if (this.nodeInfo) { this.scope.managerInfo = this.nodeInfo } } + /** + * Transforms objects to arrays + * @param {Object} : obj + */ + objToArr(obj) { + const arr = [] + for (const key in obj) arr.push({ key, value: obj[key] }) + return arr + } + /** * Change of cluster node, reloads information * @param {String} : node name @@ -103,15 +127,13 @@ define(['../../module'], function(controllers) { 'This cluster is enabled but not running. Please check your cluster health.' ) } - this.scope.daemons = daemonResult[0].data.data + this.scope.daemons = this.objToArr(daemonResult[0].data.data) this.scope.managerInfo = daemonResult[1].data.data - this.scope.load = false - if (!this.scope.$$phase) this.scope.$digest() } catch (err) { - this.scope.load = false this.scope.clusterError = err.message || err - if (!this.scope.$$phase) this.scope.$digest() } + this.scope.load = false + if (!this.scope.$$phase) this.scope.$digest() } /** @@ -135,13 +157,31 @@ define(['../../module'], function(controllers) { this.scope.totalRules = this.rules.totalItems this.scope.totalDecoders = this.decoders.totalItems this.scope.agentInfo = this.agentInfo - this.scope.load = false - - if (!this.scope.$$phase) this.scope.$digest() } catch (err) { - this.scope.load = false - this.toast(err.message || err) + this.notification.showErrorToast(err.message || err) } + this.scope.load = false + if (!this.scope.$$phase) this.scope.$digest() + } + + /** + * Function to restart the manager or cluster + */ + async restart() { + try { + this.scope.restartInProgress = true + this.scope.confirmingRestart = false + const result = await this.restartService.restart() + this.notification.showSimpleToast(result) + } catch (error) { + this.notification.showErrorToast(error) + this.scope.confirmingRestart = false + } + this.scope.restartInProgress = false + } + + switchRestart() { + this.scope.confirmingRestart = !this.scope.confirmingRestart } } diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/management/welcome/manager-welcome.html b/SplunkAppForWazuh/appserver/static/js/controllers/management/welcome/manager-welcome.html index be983e1fe..6b6a37b5c 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/management/welcome/manager-welcome.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/management/welcome/manager-welcome.html @@ -1,18 +1,4 @@
-
-
- Management - / Welcome -
-
-
-
- -
- - Management -
- @@ -20,29 +6,31 @@
-

Administration

+

Administration

- - - + + + +
-

Status and reports

+

Status and reports

- - - - +
diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/audit/overview-audit.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/audit/overview-audit.html index dd077f1aa..3fef9ab5e 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/audit/overview-audit.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/audit/overview-audit.html @@ -1,140 +1,140 @@ - -
-
+ +
+
Overview / Audit
- - - -
Waiting for reporting information
+
+ + +
-
Generating report
+
{{reportStatus}}
+ + + + Policy monitoring + + SCA + System auditing + OpenSCAP + CIS-CAT + - -
- - -
New files: - -
-
Read files: - -
-
Modified files: - -
-
Removed files: - -
-
-
-
- -
- - - Groups - -
-
-
- - - Agents - -
-
-
- - - Directories - -
-
-
- - - Files - -
-
-
-
- -
- - - Alerts over time - -
-
-
+ +
+
+ Fetching data...
+
- -
-
- - - File read access +
+
+ + +
New files: + +
+
Read files: + +
+
Modified files: + +
+
Removed files: + +
+
+
+
+ +
+ + + Groups + + + + + +
+
+
+ + + Agents + + + + + +
+
+
+ + + Commands + + + + -
+
+
+
+ + + Files + + + + + +
- -
- - - File write access + +
+ + + Alerts over time + + + + -
+
- -
- - - Commands +
+ + + Alerts summary + + + + -
+
-
- - - Created files - -
-
-
- - - Removed files - -
-
-
-
-
- - - Alerts summary - -
-
-
-
- \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/audit/overviewAuditCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/audit/overviewAuditCtrl.js index 5c11b1e8f..af30a2290 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/audit/overviewAuditCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/audit/overviewAuditCtrl.js @@ -15,7 +15,7 @@ define([ Table, TimePicker, SearchHandler, - rawTableDataService + RawTableDataService ) { 'use strict' class Audit { @@ -32,13 +32,20 @@ define([ $scope, $currentDataService, $state, - $reportingService + $reportingService, + reportingEnabled, + extensions ) { this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions this.state = $state this.tableResults = {} this.reportingService = $reportingService this.currentDataService = $currentDataService + this.currentDataService.addFilter( + `{"rule.groups{}":"audit", "implicit":true, "onlyShow":true}` + ) this.getFilters = this.currentDataService.getSerializedFilters this.filters = this.getFilters() this.submittedTokenModel = $urlTokenModel.getSubmittedTokenModel() @@ -47,11 +54,13 @@ define([ $urlTokenModel.handleValueChange ) - this.scope.$on('deletedFilter', () => { + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) @@ -63,6 +72,21 @@ define([ this.vizz.map(vizz => vizz.destroy()) }) + this.scope.expandArray = [ + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false + ] + this.scope.expand = (i, id) => this.expand(i, id) + this.vizz = [ /** * Metrics @@ -110,7 +134,7 @@ define([ 'groupsElement', `${ this.filters - } sourcetype=wazuh rule.groups="audit" | top rule.groups`, + } sourcetype=wazuh rule.groups{}="audit" | top limit=5 rule.groups{}`, 'groupsElement', this.scope ), @@ -118,23 +142,23 @@ define([ 'agentsElement', `${ this.filters - } sourcetype=wazuh rule.groups="audit" agent.name=* | top agent.name`, + } sourcetype=wazuh rule.groups{}="audit" agent.name=* | top limit=5 agent.name`, 'agentsElement', this.scope ), new PieChart( - 'directoriesElement', + 'commandsVizz', `${ this.filters - } sourcetype=wazuh rule.groups="audit" data.audit.directory.name=* | top data.audit.directory.name`, - 'directoriesElement', + } sourcetype=wazuh rule.groups{}="audit" | top limit=5 data.audit.command`, + 'commandsVizz', this.scope ), new PieChart( 'filesElement', `${ this.filters - } sourcetype=wazuh rule.groups="audit" data.audit.file.name=* | top data.audit.file.name`, + } sourcetype=wazuh rule.groups{}="audit" data.audit.file.name=* | top limit=5 data.audit.file.name`, 'filesElement', this.scope ), @@ -142,121 +166,82 @@ define([ 'alertsOverTime', `${ this.filters - } sourcetype=wazuh rule.groups="audit" | timechart limit=10 count by rule.description`, + } sourcetype=wazuh rule.groups{}="audit" | timechart limit=10 count by rule.description`, 'alertsOverTimeElement', this.scope ), - new PieChart( - 'fileReadAccess', - `${ - this.filters - } sourcetype=wazuh rule.groups="audit" rule.id=80784 | top data.audit.file.name`, - 'fileReadAccessElement', - this.scope - ), - new PieChart( - 'fileWriteAccess', - `${ - this.filters - } sourcetype=wazuh rule.groups="audit" rule.id=80781 | top data.audit.file.name`, - 'fileWriteAccessElement', - this.scope - ), - new ColumnChart( - 'commands', - `${ - this.filters - } sourcetype=wazuh rule.groups="audit" | top data.audit.command`, - 'commandsElement', - this.scope - ), - new ColumnChart( - 'createdFiles', - `${ - this.filters - } sourcetype=wazuh rule.groups="audit" rule.id=80790 | top data.audit.file.name`, - 'createdFilesElement', - this.scope - ), - new PieChart( - 'removedFiles', - `${ - this.filters - } sourcetype=wazuh rule.groups="audit" rule.id=80791 | top data.audit.file.name`, - 'removedFilesElement', - this.scope - ), new Table( 'alertsSummary', `${ this.filters - } sourcetype=wazuh rule.groups="audit" | stats count sparkline by agent.name,rule.description, data.audit.exe, data.audit.type, data.audit.euid | sort count DESC | rename agent.name as "Agent name", rule.description as Description, data.audit.exe as Command, data.audit.type as Type, data.audit.euid as "Effective user id"`, + } sourcetype=wazuh rule.groups{}="audit" | stats count sparkline by agent.name,rule.description, data.audit.exe, data.audit.type, data.audit.euid | sort count DESC | rename agent.name as "Agent name", rule.description as Description, data.audit.exe as Command, data.audit.type as Type, data.audit.euid as "Effective user id"`, 'alertsSummaryElement', this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh rule.groups{}="audit" | stats count sparkline by agent.name,rule.description, data.audit.exe, data.audit.type, data.audit.euid | sort count DESC | rename agent.name as "Agent name", rule.description as Description, data.audit.exe as Command, data.audit.type as Type, data.audit.euid as "Effective user id"`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' ) ] + } - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } sourcetype=wazuh rule.groups="audit" | stats count sparkline by agent.name,rule.description, data.audit.exe, data.audit.type, data.audit.euid | sort count DESC | rename agent.name as "Agent name", rule.description as Description, data.audit.exe as Command, data.audit.type as Type, data.audit.euid as "Effective user id"`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) - - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) - this.reportMetrics = { - 'New files': this.scope.newFiles, - 'Read files': this.scope.readFiles, - 'Modified files': this.scope.filesModifiedToken, - 'Deleted files': this.scope.filesDeleted - } - - /** - * Generates report - */ - this.scope.startVis2Png = () => - this.reportingService.startVis2Png( - 'overview-audit', - 'Audit', - this.filters, - [ - 'groupsElement', - 'agentsElement', - 'directoriesElement', - 'filesElement', - 'alertsOverTimeElement', - 'fileReadAccessElement', - 'fileWriteAccessElement', - 'commandsElement', - 'createdFilesElement', - 'removedFilesElement', - 'alertsSummaryElement' - ], - this.reportMetrics, - this.tableResults - ) - - this.scope.$on('loadingReporting', (event, data) => { - this.scope.loadingReporting = data.status - }) - - this.scope.$on('checkReportingStatus', () => { - this.vizzReady = !this.vizz.filter(v => { - return v.finish === false - }).length - if (this.vizzReady) { - this.scope.loadingVizz = false - } else { - this.scope.loadingVizz = true + $onInit() { + try { + this.scope.loadingVizz = true + this.reportMetrics = { + 'New files': this.scope.newFiles, + 'Read files': this.scope.readFiles, + 'Modified files': this.scope.filesModifiedToken, + 'Deleted files': this.scope.filesDeleted } - if (!this.scope.$$phase) this.scope.$digest() - }) + + /** + * Generates report + */ + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'overview-audit', + 'Audit', + this.filters, + [ + 'groupsElement', + 'agentsElement', + 'commandsVizz', + 'filesElement', + 'alertsOverTimeElement', + 'alertsSummaryElement' + ], + this.reportMetrics, + this.tableResults + ) + + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) + + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) + } catch (error) {} } /** @@ -266,6 +251,29 @@ define([ this.filters = this.currentDataService.getSerializedFilters() this.state.reload() } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('overviewAuditCtrl', Audit) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/aws/aws.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/aws/aws.html index 8e4731602..4e7824422 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/aws/aws.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/aws/aws.html @@ -1,98 +1,170 @@ -
-
+
+
Overview / Amazon Web Services
- - - -
Waiting for reporting information
+
+ + +
-
Generating report
+
{{reportStatus}}
+ + + + Security + events + Integrity monitoring + + Amazon AWS + - -
- - - - Sources - -
-
-
- - - - Accounts - -
-
-
- - - - S3 buckets - -
-
-
- - - - Regions - -
-
-
+
+
+ Fetching data...
+
+
+ +
+ + + + Sources + + + + + +
+
+
+ + + + Accounts + + + + + +
+
+
+ + + + S3 buckets + + + + + +
+
+
+ + + + Regions + + + + + +
+
+
+
- -
- - - - Events by source over time - -
-
-
- - - - Events by S3 over time - -
-
-
-
+ +
+ + + + Events by source over time + + + + + +
+
+
+ + + + Events by S3 over time + + + + + +
+
+
+
+ + +
+ + + + Geolocation map + + + + + +
+
+
+ +
- -
- - - - Top 5 buckets - -
-
-
- - - - Top 5 rules - -
-
-
+ + +
+ + + + Top 5 buckets + + + + + +
+
+
+ + + + Top 5 rules + + + + + +
+
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/aws/awsCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/aws/awsCtrl.js index 2857f78b8..da1018b6b 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/aws/awsCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/aws/awsCtrl.js @@ -4,211 +4,263 @@ define([ '../../../services/visualizations/chart/area-chart', '../../../services/visualizations/chart/column-chart', '../../../services/visualizations/table/table', + '../../../services/visualizations/map/map', '../../../services/visualizations/inputs/time-picker', '../../../services/rawTableData/rawTableDataService' -], function( +], function ( app, PieChart, AreaChart, ColumnChart, Table, + Map, TimePicker, - rawTableDataService + RawTableDataService ) { - 'use strict' + 'use strict' - class AWS { - /** - * Class constructor - * @param {*} $rootScope - * @param {*} $scope - * @param {*} $currentDataService - * @param {*} $state - * @param {*} $notificationService - * @param {*} $reportingService - */ - constructor( - $urlTokenModel, - $scope, - $currentDataService, - $state, - $notificationService, - $reportingService - ) { - this.scope = $scope - this.urlTokenModel = $urlTokenModel - this.state = $state - this.toast = $notificationService.showSimpleToast - this.reportingService = $reportingService - this.currentDataService = $currentDataService - this.tableResults = {} - this.currentDataService.addFilter( - `{"rule.groups":"amazon", "implicit":true}` - ) - this.getFilters = this.currentDataService.getSerializedFilters - this.filters = this.getFilters() - this.submittedTokenModel = this.urlTokenModel.getSubmittedTokenModel() - this.timePicker = new TimePicker( - '#timePicker', - this.urlTokenModel.handleValueChange - ) + class AWS { + /** + * Class constructor + * @param {*} $rootScope + * @param {*} $scope + * @param {*} $currentDataService + * @param {*} $state + * @param {*} $notificationService + * @param {*} $reportingService + */ + constructor( + $urlTokenModel, + $scope, + $currentDataService, + $state, + $notificationService, + $reportingService, + reportingEnabled + ) { + this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.urlTokenModel = $urlTokenModel + this.state = $state + this.notification = $notificationService + this.reportingService = $reportingService + this.currentDataService = $currentDataService + this.tableResults = {} + this.currentDataService.addFilter( + `{"rule.groups{}":"amazon", "implicit":true}` + ) + this.getFilters = this.currentDataService.getSerializedFilters + this.filters = this.getFilters() + this.submittedTokenModel = this.urlTokenModel.getSubmittedTokenModel() + this.timePicker = new TimePicker( + '#timePicker', + this.urlTokenModel.handleValueChange + ) + this.scope.expandArray = [ + false, + false, + false, + false, + false, + false, + false, + false + ] + this.scope.expand = (i, id) => this.expand(i, id) - this.vizz = [ - /** - * Visualizations - */ - new AreaChart( - 'eventsBySourceVizz', - `${ + this.vizz = [ + /** + * Visualizations + */ + new AreaChart( + 'eventsBySourceVizz', + `${ this.filters - } sourcetype=wazuh | timechart count by data.aws.source usenull=f`, - 'eventsBySourceVizz', - this.scope - ), - new ColumnChart( - 'eventsByS3BucketsVizz', - `${ + } sourcetype=wazuh | timechart count by data.aws.source usenull=f`, + 'eventsBySourceVizz', + this.scope + ), + new ColumnChart( + 'eventsByS3BucketsVizz', + `${ this.filters - } sourcetype=wazuh | timechart count by data.aws.log_info.s3bucket usenull=f`, - 'eventsByS3BucketsVizz', - this.scope - ), - new PieChart( - 'sourcesVizz', - `${this.filters} sourcetype=wazuh | stats count BY data.aws.source`, - 'sourcesVizz', - this.scope - ), - new PieChart( - 'accountsVizz', - `${ + } sourcetype=wazuh | timechart count by data.aws.log_info.s3bucket usenull=f`, + 'eventsByS3BucketsVizz', + this.scope + ), + new PieChart( + 'sourcesVizz', + `${this.filters} sourcetype=wazuh | stats count BY data.aws.source`, + 'sourcesVizz', + this.scope + ), + new PieChart( + 'accountsVizz', + `${ this.filters - } sourcetype=wazuh | top data.aws.responseElements.instancesSet.items.instanceId`, - 'accountsVizz', - this.scope - ), - new PieChart( - 's3BucketsVizz', - `${ + } sourcetype=wazuh | top data.aws.responseElements.instancesSet.items.instanceId`, + 'accountsVizz', + this.scope + ), + new PieChart( + 's3BucketsVizz', + `${ this.filters - } sourcetype=wazuh | stats count by data.aws.log_info.s3bucket`, - 's3BucketsVizz', - this.scope - ), - new PieChart( - 'regionsVizz', - `${this.filters} sourcetype=wazuh | top data.aws.awsRegion`, - 'regionsVizz', - this.scope - ), - new Table( - 'top5Buckets', - `${ + } sourcetype=wazuh | stats count by data.aws.log_info.s3bucket`, + 's3BucketsVizz', + this.scope + ), + new PieChart( + 'regionsVizz', + `${this.filters} sourcetype=wazuh | top data.aws.awsRegion`, + 'regionsVizz', + this.scope + ), + new Table( + 'top5Buckets', + `${ this.filters - } sourcetype=wazuh | top data.aws.source limit=5 | rename data.aws.source as Source, count as Count, percent as Percent`, - 'top5Buckets', - this.scope - ), - new Table( - 'top5Rules', - `${ + } sourcetype=wazuh | top data.aws.source limit=5 | rename data.aws.source as Source, count as Count, percent as Percent`, + 'top5Buckets', + this.scope + ), + new Table( + 'top5Rules', + `${ this.filters - } sourcetype=wazuh | top rule.id, rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule description", count as Count, percent as Percent`, - 'top5Rules', - this.scope - ) - ] + } sourcetype=wazuh | top rule.id, rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule description", count as Count, percent as Percent`, + 'top5Rules', + this.scope + ), + new RawTableDataService( + 'top5BucketsTable', + `${ + this.filters + } sourcetype=wazuh | top data.aws.source limit=5 | rename data.aws.source as Source, count as Count, percent as Percent`, + 'top5BucketsTableToken', + '$result$', + this.scope, + 'Top 5 buckets' + ), + new RawTableDataService( + 'top5RulesTable', + `${ + this.filters + } sourcetype=wazuh | top rule.id, rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule description", count as Count, percent as Percent`, + 'top5RulesTableToken', + '$result$', + this.scope, + 'Top 5 Rules' + ), + new Map( + 'map', + `${ + this.filters + } sourcetype=wazuh | stats count by data.aws.service.action.portProbeAction.portProbeDetails.remoteIpDetails.geoLocation.lat, data.aws.service.action.portProbeAction.portProbeDetails.remoteIpDetails.geoLocation.lon | rename data.aws.service.action.portProbeAction.portProbeDetails.remoteIpDetails.geoLocation.lon as "lon" | rename data.aws.service.action.portProbeAction.portProbeDetails.remoteIpDetails.geoLocation.lat as "lat" | geostats count`, + 'map', + this.scope + ) + ] + } - this.top5BucketsTable = new rawTableDataService( - 'top5BucketsTable', - `${ - this.filters - } sourcetype=wazuh | top data.aws.source limit=5 | rename data.aws.source as Source, count as Count, percent as Percent`, - 'top5BucketsTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.top5BucketsTable) + $onInit() { + try { - this.top5BucketsTable.getSearch().on('result', result => { - this.tableResults['Top 5 buckets'] = result - }) + this.scope.loadingVizz = true + this.scope.$on('deletedFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.top5RulesTable = new rawTableDataService( - 'top5RulesTable', - `${ - this.filters - } sourcetype=wazuh | top rule.id, rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule description", count as Count, percent as Percent`, - 'top5RulesTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.top5RulesTable) + this.scope.$on('barFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.top5RulesTable.getSearch().on('result', result => { - this.tableResults['Top 5 rules'] = result - }) + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'overview-aws', + 'AWS', + this.filters, + [ + 'sourcesVizz', + 'accountsVizz', + 's3BucketsVizz', + 'regionsVizz', + 'eventsBySourceVizz', + 'eventsByS3BucketsVizz', + 'map', + 'top5Buckets', + 'top5Rules' + ], + {}, //Metrics + this.tableResults + ) - this.scope.$on('deletedFilter', () => { - this.launchSearches() - }) + /** + * On controller destroy + */ + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) - this.scope.$on('barFilter', () => { - this.launchSearches() - }) + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) - this.scope.startVis2Png = () => - this.reportingService.startVis2Png( - 'overview-aws', - 'AWS', - this.filters, - [ - 'sourcesVizz', - 'accountsVizz', - 's3BucketsVizz', - 'regionsVizz', - 'eventsBySourceVizz', - 'eventsByS3BucketsVizz', - 'top5Buckets', - 'top5Rules' - ], - {}, //Metrics - this.tableResults - ) + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) + } catch (error) { + console.error('error on init ', error) + } + } /** - * On controller destroy + * Gets filters and launches search */ - this.scope.$on('$destroy', () => { - this.timePicker.destroy() - this.vizz.map(vizz => vizz.destroy()) - }) - - this.scope.$on('loadingReporting', (event, data) => { - this.scope.loadingReporting = data.status - }) + launchSearches() { + this.filters = this.getFilters() + this.state.reload() + } - this.scope.$on('checkReportingStatus', () => { - this.vizzReady = !this.vizz.filter(v => { - return v.finish === false - }).length - if (this.vizzReady) { - this.scope.loadingVizz = false - } else { - this.scope.loadingVizz = true - } - if (!this.scope.$$phase) this.scope.$digest() - }) - } + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') - /** - * Gets filters and launches search - */ - launchSearches() { - this.filters = this.getFilters() - this.state.reload() + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } - } - app.controller('awsCtrl', AWS) -}) + app.controller('awsCtrl', AWS) + }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/ciscat/ciscatCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/ciscat/ciscatCtrl.js index b1788614d..2a573fa1b 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/ciscat/ciscatCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/ciscat/ciscatCtrl.js @@ -13,7 +13,7 @@ define([ Table, TimePicker, SearchHandler, - rawTableDataService + RawTableDataService ) { 'use strict' class Ciscat { @@ -29,9 +29,13 @@ define([ $scope, $currentDataService, $state, - $reportingService + $reportingService, + reportingEnabled, + extensions ) { this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions this.state = $state this.reportingService = $reportingService this.addFilter = $currentDataService.addFilter @@ -45,11 +49,16 @@ define([ $urlTokenModel.handleValueChange ) - this.scope.$on('deletedFilter', () => { + this.scope.expandArray = [false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) @@ -138,7 +147,7 @@ define([ `lastScanBenchmark`, `${ this.filters - } rule.groups=ciscat | search data.cis.benchmark=* | table data.cis.benchmark | head 1`, + } rule.groups{}=ciscat | search data.cis.benchmark=* | table data.cis.benchmark | head 1`, 'lastScanBenchmark', '$result.data.cis.benchmark$', 'lastScanBenchmark', @@ -152,7 +161,7 @@ define([ 'topCiscatGroups', `${ this.filters - } sourcetype=wazuh rule.groups="ciscat" | top data.cis.group`, + } sourcetype=wazuh rule.groups{}="ciscat" | top data.cis.group`, 'topCiscatGroups', this.scope ), @@ -160,7 +169,7 @@ define([ 'scanResultEvolution', `${ this.filters - } sourcetype=wazuh rule.groups="ciscat" | timechart count by data.cis.result usenull=f`, + } sourcetype=wazuh rule.groups{}="ciscat" | timechart count by data.cis.result usenull=f`, 'scanResultEvolution', this.scope ), @@ -168,27 +177,22 @@ define([ 'alertsSummary', `${ this.filters - } sourcetype=wazuh rule.groups="ciscat" | stats count sparkline by data.cis.rule_title, data.cis.remediation,data.cis.group | sort count desc | rename "data.cis.rule_title" as "Title", "data.cis.remediation" as "Remediation", "data.cis.group" as "Group" `, + } sourcetype=wazuh rule.groups{}="ciscat" | stats count sparkline by data.cis.rule_title, data.cis.remediation,data.cis.group | sort count desc | rename "data.cis.rule_title" as "Title", "data.cis.remediation" as "Remediation", "data.cis.group" as "Group" `, 'alertsSummary', this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh rule.groups{}="ciscat" | stats count sparkline by data.cis.rule_title, data.cis.remediation,data.cis.group | sort count desc | rename "data.cis.rule_title" as "Title", "data.cis.group" as "Group" | fields - data.cis.remediation`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' ) ] - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } sourcetype=wazuh rule.groups="ciscat" | stats count sparkline by data.cis.rule_title, data.cis.remediation,data.cis.group | sort count desc | rename "data.cis.rule_title" as "Title", "data.cis.group" as "Group" | fields - data.cis.remediation`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) - - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) - /** * Generates report */ @@ -214,6 +218,11 @@ define([ this.scope.loadingVizz = false this.setReportMetrics() } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) this.scope.loadingVizz = true } if (!this.scope.$$phase) this.scope.$digest() @@ -224,7 +233,8 @@ define([ * On controller loads */ $onInit() { - this.addFilter(`{"rule.groups":"ciscat", "implicit":true}`) + this.addFilter(`{"rule.groups{}":"ciscat", "implicit":true}`) + this.scope.loadingVizz = true /** * On controller destroy @@ -258,6 +268,29 @@ define([ this.filters = this.currentDataService.getSerializedFilters() this.state.reload() } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('ciscatCtrl', Ciscat) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/ciscat/overview-ciscat.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/ciscat/overview-ciscat.html index 3db4330a8..7298b3d6b 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/ciscat/overview-ciscat.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/ciscat/overview-ciscat.html @@ -1,97 +1,132 @@ - -
-
+ +
+
Overview / CIS-CAT
- - - -
Waiting for reporting information
-
+ +
+ + +
-
Generating report
+
{{reportStatus}}
+ + + + Policy monitoring + + SCA + System auditing + OpenSCAP + CIS-CAT + - - - -
- - -
Last not checked: - -
-
Last pass: - -
-
Last scan score: - -
-
Last scan date: - -
-
-
-
-
- - -
Last errors: - -
-
Last fails: - -
-
Last unknown: - -
-
Last scan benchmark: - -
-
-
+
+
+ Fetching data...
+
+
+ -
-
- - - Top 5 CIS-CAT groups - -
+
+ + +
Last not checked: + +
+
Last pass: + +
+
Last scan score: + +
+
Last scan date: + +
- -
- - - Scan result evolution - -
+
+ + +
Last errors: + +
+
Last fails: + +
+
Last unknown: + +
+
Last scan benchmark: + +
- -
- -
-
- - - Alerts summary - -
-
-
+ +
+
+ + + Top 5 CIS-CAT groups + + + + + +
+
+
+
+ +
+ + + Scan result evolution + + + + + +
+
+
+
+ +
+ +
+
+ + + Alerts summary + + + + + +
+
+
+
- \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/docker/dockerCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/docker/dockerCtrl.js new file mode 100644 index 000000000..837014bd6 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/docker/dockerCtrl.js @@ -0,0 +1,204 @@ +define([ + '../../module', + '../../../services/visualizations/chart/pie-chart', + '../../../services/visualizations/chart/linear-chart', + '../../../services/visualizations/table/table', + '../../../services/visualizations/inputs/time-picker', + '../../../services/rawTableData/rawTableDataService' +], function( + app, + PieChart, + LinearChart, + Table, + TimePicker, + RawTableDataService +) { + 'use strict' + + class Docker { + /** + * Class Docker + * @param {*} $urlTokenModel + * @param {*} $scope + * @param {*} $currentDataService + * @param {*} $state + * @param {*} $notificationService + * @param {*} $reportingService + */ + constructor( + $urlTokenModel, + $scope, + $currentDataService, + $state, + $notificationService, + $reportingService, + reportingEnabled, + extensions + ) { + this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions + this.state = $state + this.currentDataService = $currentDataService + this.reportingService = $reportingService + this.tableResults = {} + this.currentDataService.addFilter( + `{"rule.groups{}":"docker", "implicit":true}` + ) + this.getFilters = this.currentDataService.getSerializedFilters + this.filters = this.getFilters() + this.scope.$on('deletedFilter', event => { + event.stopPropagation() + this.launchSearches() + }) + + this.scope.$on('barFilter', event => { + event.stopPropagation() + this.launchSearches() + }) + + this.scope.expandArray = [false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + + this.timePicker = new TimePicker( + '#timePicker', + $urlTokenModel.handleValueChange + ) + this.notification = $notificationService + this.vizz = [ + //`${this.filters} sourcetype=wazuh | timechart span=1h count`, + /** + * Visualizations + */ + new PieChart( + 'top5images', + `${this.filters} sourcetype=wazuh | stats count by data.docker.id`, + 'top5images', + this.scope + ), + new LinearChart( + 'eventsOcurred', + `${ + this.filters + } sourcetype=wazuh | timechart span=1h count by data.docker.Action`, + 'eventsOcurred', + this.scope + ), + new PieChart( + 'top5actions', + `${this.filters} sourcetype=wazuh | top data.docker.Action limit=5`, + 'top5actions', + this.scope + ), + new Table( + 'alertsSummary', + `${ + this.filters + } sourcetype=wazuh | stats count sparkline by data.docker.Actor.Attributes.image, data.docker.Actor.Attributes.name, data.docker.Action, timestamp | sort count DESC | rename data.docker.Actor.Attributes.image as Image, data.docker.Actor.Attributes.name as Container, data.docker.Action as Action, timestamp as Date, count as Count, sparkline as Sparkline`, + 'alertsSummary', + this.scope + ), + new LinearChart( + 'resourceUsage', + `${ + this.filters + } sourcetype=wazuh | timechart span=1h count by data.docker.Type`, + 'resourceUsage', + this.scope + ), + new RawTableDataService( + 'alertsSummaryRawTable', + `${ + this.filters + } sourcetype=wazuh | stats count sparkline by data.docker.Actor.Attributes.image, data.docker.Actor.Attributes.name, data.docker.Action, timestamp | sort count DESC | rename data.docker.Actor.Attributes.image as Image, data.docker.Actor.Attributes.name as Container, data.docker.Action as Action, timestamp as Date, count as Count`, + 'alertsSummaryRawTableToken', + '$result$', + this.scope, + 'Alerts summary' + ) + ] + + /** + * Generates report + */ + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'ow-docker', + 'Docker', + this.filters, + ['top5images', 'eventsOcurred', 'top5actions', 'resourceUsage'], + {}, //Metrics + this.tableResults + ) + + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) + + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) + + /** + * On controller destroy + */ + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) + } + + /** + * On controller loads + */ + $onInit() { + this.scope.loadingVizz = true + } + + /** + * Get filters and launches search + */ + launchSearches() { + this.filters = this.getFilters() + this.state.reload() + } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } + } + + app.controller('dockerCtrl', Docker) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/docker/overview-docker.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/docker/overview-docker.html new file mode 100644 index 000000000..54488e89a --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/docker/overview-docker.html @@ -0,0 +1,117 @@ + +
+
+ Overview + / Docker listener +
+
+ +
+ + +
+
+
+ + +
{{reportStatus}}
+ + + + + Vulnerabilities + Osquery + VirusTotal + Docker listener + + + + + +
+
+ Fetching data...
+
+
+
+ +
+ + + + Top 5 images + + + + + +
+
+
+ + + + Top 5 events + + + + + +
+
+
+ + + + Resource usage over time + + + + + +
+
+
+
+ + +
+ + + + Events ocurred evolution + + + + + +
+
+
+
+ + +
+ + + + Alerts summary + + + + + +
+
+
+
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/fim/overview-fim.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/fim/overview-fim.html index bb4331e24..51b7cf8fd 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/fim/overview-fim.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/fim/overview-fim.html @@ -1,95 +1,133 @@ - -
-
+ +
+
Overview / File integrity monitoring
- - - -
Waiting for reporting information
+
+ + + +
-
Generating report
+
{{reportStatus}}
+ + + + Security + events + Integrity monitoring + Amazon AWS + - -
- - - Top 5 agents with deleted files - -
-
-
- - - Top 5 agents with new files - -
-
-
- - - Top 5 agents with modified files - -
-
-
-
- -
- - - FIM Alerts volume - -
-
-
- - - Events summary - -
-
-
+ +
+
+ Fetching data...
+
- -
-
- - - Top 5 rules +
+ +
+ + + Alerts by action over time + + + + -
+
- -
- - - Whodata usage + + +
+ + + Top 5 agents + + + + -
+
-
- -
- - - Top 5 users + + + Events summary + + + + -
+
+ + + +
+
+ + + Rule distribution + + + + + +
+
+
+
+ +
+ + + Top actions + + + + + +
+
+
+
+ +
+ + + Top 5 users + + + + + +
+
+
+
+ +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/fim/overviewFimCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/fim/overviewFimCtrl.js index 819d255b1..c6bdaf03f 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/fim/overviewFimCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/fim/overviewFimCtrl.js @@ -6,212 +6,208 @@ define([ '../../../services/visualizations/chart/linear-chart', '../../../services/visualizations/inputs/time-picker', '../../../services/rawTableData/rawTableDataService' -], function( +], function ( app, ColumnChart, PieChart, Table, LinearChart, - TimePicker, - rawTableDataService + TimePicker ) { - 'use strict' + 'use strict' - class OverviewFIM { - /** - * Class File Integrity Monitoring (syscheck) - * @param {*} $urlTokenModel - * @param {*} $scope - * @param {*} $currentDataService - * @param {*} $state - * @param {*} $reportingService - */ - constructor( - $urlTokenModel, - $scope, - $currentDataService, - $state, - $reportingService - ) { - this.scope = $scope - this.state = $state - this.reportingService = $reportingService - this.getFilters = $currentDataService.getSerializedFilters - this.filters = this.getFilters() - this.tableResults = {} - this.submittedTokenModel = $urlTokenModel.getSubmittedTokenModel() - this.timePicker = new TimePicker( - '#timePicker', - $urlTokenModel.handleValueChange - ) + class OverviewFIM { + /** + * Class File Integrity Monitoring (syscheck) + * @param {*} $urlTokenModel + * @param {*} $scope + * @param {*} $currentDataService + * @param {*} $state + * @param {*} $reportingService + */ + constructor( + $urlTokenModel, + $scope, + $currentDataService, + $state, + $reportingService, + reportingEnabled, + awsExtensionEnabled + ) { + this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.awsExtensionEnabled = awsExtensionEnabled + this.state = $state + this.reportingService = $reportingService + $currentDataService.addFilter( + `{"rule.groups{}":"syscheck", "implicit":true, "onlyShow":true}` + ) + this.getFilters = $currentDataService.getSerializedFilters + this.filters = this.getFilters() + this.tableResults = {} + this.submittedTokenModel = $urlTokenModel.getSubmittedTokenModel() + this.timePicker = new TimePicker( + '#timePicker', + $urlTokenModel.handleValueChange + ) - this.vizz = [ - /** - * Visualizations - */ - new PieChart( - 'deletedFiles', - `${ - this.filters - } sourcetype=wazuh syscheck.event=deleted | top agent.name limit=5`, - 'deletedFiles', - this.scope - ), - new ColumnChart( - 'whodataUsage', - `${this.filters} sourcetype=wazuh rule.groups=syscheck - | eval WHODATA=if(isnotnull('syscheck.audit.effective_user.id'), "WHODATA", "NOWHO") - | stats count BY WHODATA - | addcoltotals count labelfield=WHODATA label=Total - | where NOT WHODATA="NOWHO"`, - 'whodataUsage', - this.scope - ), - new PieChart( - 'alertsVolume', - `${ + this.scope.expandArray = [false, false, false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + + this.vizz = [ + /** + * Visualizations + */ + + new LinearChart( + 'alertsByActionOverTime', + `${ this.filters - } sourcetype=wazuh rule.groups=syscheck | eval SYSCHECK=if(isnotnull('syscheck.event'), "SYSCHECK", "NO") - | stats count BY SYSCHECK - | addcoltotals count labelfield=SYSCHECK label=Total - | where NOT SYSCHECK="NO"`, - 'alertsVolume', - this.scope - ), - new PieChart( - 'newFiles', - `${ + } sourcetype=wazuh rule.groups{}=syscheck | timechart count by syscheck.event`, + 'alertsByActionOverTime', + this.scope + ), + new PieChart( + 'top5Agents', + `${ this.filters - } sourcetype=wazuh syscheck.event=added | top agent.name limit=5`, - 'newFiles', - this.scope - ), - new PieChart( - 'modifiedFiles', - `${ + } sourcetype=wazuh rule.groups{}=syscheck | top agent.name limit=5`, + 'top5Agents', + this.scope + ), + new LinearChart( + 'eventsSummary', + `${ this.filters - } sourcetype=wazuh syscheck.event=modified | top agent.name limit=5`, - 'modifiedFiles', - this.scope - ), - new LinearChart( - 'eventsSummary', - `${ + } sourcetype=wazuh rule.groups{}=syscheck | timechart count`, + 'eventsSummary', + this.scope + ), + new PieChart( + 'ruleDistribution', + `${ this.filters - } sourcetype=wazuh rule.groups=syscheck | timechart count`, - 'eventsSummary', - this.scope - ), - new Table( - 'topRules', - `${ + } sourcetype=wazuh rule.groups{}=syscheck | top limit=5 rule.description`, + 'ruleDistribution', + this.scope + ), + new PieChart( + 'topActions', + `${ this.filters - } sourcetype=wazuh rule.groups=syscheck |stats count sparkline by rule.id, rule.description | sort count DESC | head 5 | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, - 'topRules', - this.scope - ), - new Table( - 'topUsers', - `${ + } sourcetype=wazuh rule.groups{}=syscheck | top limit=5 syscheck.event`, + 'topActions', + this.scope + ), + new Table( + 'topUsers', + `${ this.filters - } sourcetype=wazuh syscheck.audit.effective_user.id=* | top syscheck.audit.effective_user.name limit=5 | rename syscheck.audit.effective_user.name as Username, count as Count, percent as Percent`, - 'topUsers', - this.scope - ) - ] + } sourcetype=wazuh rule.groups{}=syscheck | top limit=5 agent.id,agent.name,syscheck.uname_after | rename agent.id as "Agent ID", agent.name as "Agent name", syscheck.uname_after as "Top User", count as "Count"`, + 'topUsers', + this.scope + ) + ] - this.topRulesTable = new rawTableDataService( - 'topRulesTable', - `${ - this.filters - } sourcetype=wazuh rule.groups=syscheck |stats count sparkline by rule.id, rule.description | sort count DESC | head 5 | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, - 'topRulesTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.topRulesTable) + } - this.topRulesTable.getSearch().on('result', result => { - this.tableResults['Top rules'] = result - }) + $onInit() { + try { + this.scope.loadingVizz = true + this.scope.$on('deletedFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.topUsersTable = new rawTableDataService( - 'topUsersTable', - `${ - this.filters - } sourcetype=wazuh syscheck.audit.effective_user.id=* | top syscheck.audit.effective_user.name limit=5 | rename syscheck.audit.effective_user.name as Username, count as Count, percent as Percent`, - 'topUsersTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.topUsersTable) + this.scope.$on('barFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.topUsersTable.getSearch().on('result', result => { - this.tableResults['Top users'] = result - }) + /** + * Generates report + */ + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'overview-fim', + 'File integrity monitoring', + this.filters, + [ + 'alertsByActionOverTime', + 'top5Agents', + 'eventsSummary', + 'ruleDistribution', + 'topActions', + 'topUsers' + ], + {}, //Metrics + this.tableResults + ) - this.scope.$on('deletedFilter', () => { - this.launchSearches() - }) + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) - this.scope.$on('barFilter', () => { - this.launchSearches() - }) + /** + * On controller destroy + */ + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) - /** - * Generates report - */ - this.scope.startVis2Png = () => - this.reportingService.startVis2Png( - 'overview-fim', - 'File integrity monitoring', - this.filters, - [ - 'deletedFiles', - 'newFiles', - 'modifiedFiles', - 'alertsVolume', - 'eventsSummary', - 'topRules', - 'whodataUsage', - 'topUsers' - ], - {}, //Metrics - this.tableResults - ) + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) - this.scope.$on('checkReportingStatus', () => { - this.vizzReady = !this.vizz.filter(v => { - return v.finish === false - }).length - if (this.vizzReady) { - this.scope.loadingVizz = false - } else { - this.scope.loadingVizz = true + } catch (error) { + console.error('error on init ', error) } - if (!this.scope.$$phase) this.scope.$digest() - }) + } /** - * On controller destroy + * Get filters and launches the search */ - this.scope.$on('$destroy', () => { - this.timePicker.destroy() - this.vizz.map(vizz => vizz.destroy()) - }) + launchSearches() { + this.filters = this.getFilters() + this.state.reload() + } - this.scope.$on('loadingReporting', (event, data) => { - this.scope.loadingReporting = data.status - }) - } + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') - /** - * Get filters and launches the search - */ - launchSearches() { - this.filters = this.getFilters() - this.state.reload() + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } - } - app.controller('overviewFimCtrl', OverviewFIM) -}) + app.controller('overviewFimCtrl', OverviewFIM) + }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/gdpr/overview-gdpr.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/gdpr/overview-gdpr.html index 39d24d4c1..5cb0a4b86 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/gdpr/overview-gdpr.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/gdpr/overview-gdpr.html @@ -1,85 +1,127 @@ - -
-
+ +
+
Overview / GDPR
- - - -
Waiting for reporting information
+
+ + +
-
Generating report
+
{{reportStatus}}
+ + + + PCI DSS + GDPR + - -
- - - -
- GDPR Requirement: {{tab.rule}} - -
-
{{tab.description}}
-
-
-
-
-
+
+
+ Fetching data...
+
+
+ +
+ + + +
+ GDPR Requirement: {{tab.title}} + +
+
{{tab.content}}
+
+
+
+
+
+
-
- - - GDPR Requirements - -
-
-
- - - Groups - -
-
-
-
+
+ + + GDPR Requirements + + + + + +
+
+
+ + + Top 10 agents by alerts number + + + + + +
+
+
+
-
- - - Agents - -
-
-
- - - Requirements by agent - -
-
-
-
+
+ + + Top requirements over time + + + + + +
+
+
+
-
- - - Alerts summary - -
-
-
+
+ + + Requirements by agent + + + + + +
+
+
+
+ +
+ + + Alerts summary + + + + + +
+
+
+
- \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/gdpr/overviewGdprCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/gdpr/overviewGdprCtrl.js index d7bcd0bb2..897d669ec 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/gdpr/overviewGdprCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/gdpr/overviewGdprCtrl.js @@ -1,161 +1,210 @@ define([ '../../module', + '../../../services/visualizations/chart/linear-chart', '../../../services/visualizations/chart/column-chart', '../../../services/visualizations/chart/pie-chart', + '../../../services/visualizations/table/table', '../../../services/visualizations/inputs/time-picker', '../../../services/visualizations/inputs/dropdown-input' -], function(app, ColumnChart, PieChart, TimePicker, Dropdown) { - 'use strict' - class OverviewGDPR { - /** - * Class GDPR - * @param {*} $urlTokenModel - * @param {*} $scope - * @param {*} $currentDataService - * @param {*} $state - * @param {*} $reportingService - */ - constructor( - $urlTokenModel, - $scope, - $currentDataService, - $state, - $reportingService - ) { - this.scope = $scope - this.state = $state - this.getFilters = $currentDataService.getSerializedFilters - this.reportingService = $reportingService - this.tableResults = {} - this.filters = this.getFilters() - this.scope.$on('deletedFilter', () => { - this.launchSearches() - }) +], function ( + app, + LinearChart, + ColumnChart, + PieChart, + Table, + TimePicker, + Dropdown +) { + 'use strict' + class OverviewGDPR { + /** + * Class GDPR + * @param {*} $urlTokenModel + * @param {*} $scope + * @param {*} $currentDataService + * @param {*} $state + * @param {*} $reportingService + */ + constructor( + $urlTokenModel, + $scope, + $currentDataService, + $state, + $reportingService, + gdprTabs, + reportingEnabled, + pciExtensionEnabled + ) { + this.scope = $scope + ; (this.scope.reportingEnabled = reportingEnabled), + (this.scope.pciExtensionEnabled = pciExtensionEnabled) + this.state = $state + this.getFilters = $currentDataService.getSerializedFilters + this.reportingService = $reportingService + this.tableResults = {} + this.filters = this.getFilters() + this.scope.gdprTabs = gdprTabs ? gdprTabs : false + this.scope.$on('deletedFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.scope.$on('barFilter', () => { - this.launchSearches() - }) + this.scope.$on('barFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.timePicker = new TimePicker( - '#timePicker', - $urlTokenModel.handleValueChange - ) - this.dropdown = new Dropdown( - 'dropDownInputAgent', - `${ + this.timePicker = new TimePicker( + '#timePicker', + $urlTokenModel.handleValueChange + ) + this.dropdown = new Dropdown( + 'dropDownInputAgent', + `${ this.filters - } sourcetype=wazuh rule.gdpr{}="*"| stats count by "rule.gdpr{}" | spath "rule.gdpr{}" | fields - count`, - 'rule.gdpr{}', - '$form.gdpr$', - 'dropDownInput', - this.scope - ) + } sourcetype=wazuh rule.gdpr{}="*"| stats count by "rule.gdpr{}" | spath "rule.gdpr{}" | fields - count`, + 'rule.gdpr{}', + '$form.gdpr$', + 'dropDownInput', + this.scope + ) - this.dropdownInstance = this.dropdown.getElement() - this.dropdownInstance.on('change', newValue => { - if (newValue && this.dropdownInstance) { - $urlTokenModel.handleValueChange(this.dropdownInstance) - } - }) + this.dropdownInstance = this.dropdown.getElement() + this.dropdownInstance.on('change', newValue => { + if (newValue && this.dropdownInstance) { + $urlTokenModel.handleValueChange(this.dropdownInstance) + } + }) - this.vizz = [ - /** - * Visualizations - */ - new ColumnChart( - 'gdprRequirements', - `${ + this.scope.expandArray = [false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + + this.vizz = [ + /** + * Visualizations + */ + new ColumnChart( + 'gdprRequirements', + `${ this.filters - } sourcetype=wazuh rule.gdpr{}="$gdpr$" | stats count by rule.gdpr{}`, - 'gdprRequirements', - this.scope - ), - new PieChart( - 'groupsViz', - `${ + } sourcetype=wazuh rule.gdpr{}="$gdpr$" | stats count by rule.gdpr{}`, + 'gdprRequirements', + this.scope + ), + new LinearChart( + 'evoViz', + `${ this.filters - } sourcetype=wazuh rule.gdpr{}="$gdpr$" | stats count by rule.groups`, - 'groupsViz', - this.scope - ), - new PieChart( - 'agentsViz', - `${ + } sourcetype=wazuh rule.gdpr{}="*" | timechart count by rule.gdpr{}`, + 'evoViz', + this.scope + ), + new PieChart( + 'agentsViz', + `${ this.filters - } sourcetype=wazuh rule.gdpr{}="$gdpr$" | stats count by agent.name`, - 'agentsViz', - this.scope - ), - new ColumnChart( - 'requirementsByAgents', - `${ + } sourcetype=wazuh rule.gdpr{}="$gdpr$" | stats count by agent.name`, + 'agentsViz', + this.scope + ), + new ColumnChart( + 'requirementsByAgents', + `${ this.filters - } sourcetype=wazuh rule.gdpr{}="$gdpr$" agent.name=*| chart count(rule.gdpr{}) by rule.gdpr{},agent.name`, - 'requirementsByAgents', - this.scope - ), - new ColumnChart( - 'alertsSummaryViz', - `${ + } sourcetype=wazuh rule.gdpr{}="$gdpr$" agent.name=*| chart count(rule.gdpr{}) by rule.gdpr{},agent.name`, + 'requirementsByAgents', + this.scope + ), + new Table( + 'alertsSummaryViz', + `${ this.filters - } sourcetype=wazuh rule.gdpr{}="$gdpr$" | stats count sparkline by agent.name, rule.gdpr{}, rule.description | sort count DESC | rename agent.name as "Agent Name", rule.gdpr{} as Requirement, rule.description as "Rule description", count as Count`, - 'alertsSummaryViz', - this.scope - ) - ] + } sourcetype=wazuh rule.gdpr{}="$gdpr$" | stats count sparkline by agent.name, rule.gdpr{}, rule.description | sort count DESC | rename agent.name as "Agent Name", rule.gdpr{} as Requirement, rule.description as "Rule description", count as Count`, + 'alertsSummaryViz', + this.scope + ) + ] + } - /** - * Generates report - */ - this.scope.startVis2Png = () => - this.reportingService.startVis2Png( - 'overview-gdpr', - 'GDPR', - this.filters, - [ - 'gdprRequirements', - 'groupsViz', - 'agentsViz', - 'requirementsByAgents', - 'alertsSummaryViz' - ], - {}, //Metrics, - this.tableResults - ) + $onInit() { + try { + this.scope.loadingVizz = true + /** + * Generates report + */ + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'overview-gdpr', + 'GDPR', + this.filters, + [ + 'gdprRequirements', + 'groupsViz', + 'agentsViz', + 'requirementsByAgents', + 'alertsSummaryViz' + ], + {}, //Metrics, + this.tableResults + ) - this.scope.$on('loadingReporting', (event, data) => { - this.scope.loadingReporting = data.status - }) + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) - this.scope.$on('checkReportingStatus', () => { - this.vizzReady = !this.vizz.filter(v => { - return v.finish === false - }).length - if (this.vizzReady) { - this.scope.loadingVizz = false - } else { - this.scope.loadingVizz = true - } - if (!this.scope.$$phase) this.scope.$digest() - }) + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + } else { + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) + + /** + * When controller is destroyed + */ + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.dropdown.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) + } catch (error) { } //eslint-disable-line + } /** - * When controller is destroyed + * Get filters and launches the search */ - this.scope.$on('$destroy', () => { - this.timePicker.destroy() - this.dropdown.destroy() - this.vizz.map(vizz => vizz.destroy()) - }) - } + launchSearches() { + this.filters = this.getFilters() + this.state.reload() + } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') - /** - * Get filters and launches the search - */ - launchSearches() { - this.filters = this.getFilters() - this.state.reload() + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } - } - app.controller('overviewGdprCtrl', OverviewGDPR) -}) + app.controller('overviewGdprCtrl', OverviewGDPR) + }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/general/overview-general.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/general/overview-general.html index 3e93262f4..b06644495 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/general/overview-general.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/general/overview-general.html @@ -1,143 +1,181 @@ -
-
+
+
Overview / General
- - - -
Waiting for reporting information
+
+ + +
- + -
Generating report
+
{{reportStatus}}
+ + + + Security events + Integrity monitoring + + Amazon AWS + - - -
- - - -
Alerts: - -
-
Level 12 or above alerts: - -
-
Authentication failure: - -
-
Authentication success: - -
-
-
+
+
+ Fetching data...
+
+
+ +
- -
- - - - Alert level evolution - -
-
-
- - - - Alerts - -
-
-
-
+ + +
Alerts: + +
+
Level 12 or above alerts: + +
+
Authentication failure: + +
+
Authentication success: + +
+
+
+
- -
- - - - Top 5 agents - -
-
-
- - - - Alerts evolution - Top 5 agents - -
-
-
- - - - Agents status - -
-
- - Agents status - -
-
-
-
-

Total

-

{{agentsCountTotal}}

-
-
-
-

Active

-

{{agentsCountActive}}

-
-
-

Disconnected

-

{{agentsCountDisconnected}}

-
-
-

Never connected

-

{{agentsCountNeverConnected}}

-
-
-

Agents coverage

-

{{(agentsCoverity | number:2)}}%

+ +
+ + + + Alert level evolution + + + + + +
+
+
+ + + + Alerts + + + + + +
+
+
+
+ + +
+ + + + Top 5 agents + + + + + +
+
+
+ + + + Top 5 rule groups + + + + + +
+
+
+ + + + Agents status + + + + + +
+
+ + Agents status + +
+
+
+
+

Total

+

{{agentsCountTotal}}

+
+
+
+

Active

+

{{agentsCountActive}}

+
+
+

Disconnected

+

{{agentsCountDisconnected}}

+
+
+

Never connected

+

{{agentsCountNeverConnected}}

+
+
+

Agents coverage

+

{{(agentsCoverity | number:2)}}%

+
-
- - -
+ + +
- -
+ +
- - - Agents summary - -
-
-
+ + + Agents summary + + + + + +
+
+
+
- -
-
-
{{reportStatus}}
-
- - \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/general/overviewGeneralCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/general/overviewGeneralCtrl.js index 46351b3fc..467156fe7 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/general/overviewGeneralCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/general/overviewGeneralCtrl.js @@ -17,7 +17,7 @@ define([ Table, TimePicker, SearchHandler, - rawTableDataService + RawTableDataService ) { 'use strict' @@ -43,13 +43,17 @@ define([ $requestService, pollingState, $reportingService, - $rootScope + $rootScope, + reportingEnabled, + awsExtensionEnabled ) { this.currentDataService = $currentDataService this.rootScope = $rootScope this.filters = this.currentDataService.getSerializedFilters() this.scope = $scope + this.scope.reportingEnabled = reportingEnabled this.reportingService = $reportingService + this.scope.awsExtensionEnabled = awsExtensionEnabled this.apiReq = $requestService.apiReq this.tableResults = {} this.timePicker = new TimePicker( @@ -58,22 +62,33 @@ define([ ) this.submittedTokenModel = $urlTokenModel.getSubmittedTokenModel() this.state = $state - this.pollingEnabled = - pollingState && - pollingState.data && - (pollingState.data.error || pollingState.data.disabled === 'true') - ? false - : true - this.toast = $notificationService.showSimpleToast - this.scope.$on('deletedFilter', () => { + try { + this.pollingEnabled = + pollingState && + pollingState.data && + (pollingState.data.error || pollingState.data.disabled === 'true') + ? false + : true + } catch (error) { + console.error('e', error) + } + + this.notification = $notificationService + + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) + this.scope.expandArray = [false, false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + this.vizz = [ /** * Metrics @@ -100,7 +115,7 @@ define([ `searchAuthFailure`, `${ this.filters - } sourcetype=wazuh "rule.groups"="authentication_fail*" | stats count`, + } sourcetype=wazuh "rule.groups{}"="authentication_fail*" | stats count`, `authFailureToken`, '$result.count$', 'authFailure', @@ -111,7 +126,7 @@ define([ `searchAuthSuccess`, `${ this.filters - } sourcetype=wazuh "rule.groups"="authentication_success" | stats count`, + } sourcetype=wazuh "rule.groups{}"="authentication_success" | stats count`, `authSuccessToken`, '$result.count$', 'authSuccess', @@ -129,143 +144,157 @@ define([ 'alertLevEvoVizz', this.scope ), - new ColumnChart( + new LinearChart( 'alertsVizz', `${this.filters} sourcetype=wazuh | timechart span=2h count`, 'alertsVizz', this.scope ), new PieChart( - 'top5AgentsVizz', - `${this.filters} sourcetype=wazuh | top agent.name`, - 'top5AgentsVizz', - this.scope - ), - new AreaChart( 'alertsEvoTop5Agents', `${ this.filters - } sourcetype=wazuh | timechart span=1h limit=5 useother=f count by agent.name`, + } cluster.name=wazuh index=wazuh sourcetype=wazuh | stats count by agent.name`, 'alertsEvoTop5Agents', this.scope ), + new PieChart( + 'top5ruleGroups', + `${this.filters} sourcetype=wazuh | top rule.groups{} limit=5`, + 'top5ruleGroups', + this.scope + ), new Table( 'agentsSummaryVizz', `${ this.filters - } sourcetype=wazuh |stats count sparkline by rule.id, rule.description, rule.level | sort rule.level DESC | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, + } sourcetype=wazuh |stats count sparkline by rule.id, rule.description, rule.level | sort count DESC | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, 'agentsSummaryVizz', this.scope - ) + ), + (this.agentsSummaryTable = new RawTableDataService( + 'agentsSummaryTable', + `${ + this.filters + } sourcetype=wazuh |stats count sparkline by rule.id, rule.description, rule.level | sort count DESC | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, + 'agentsSummaryTableToken', + '$result$', + this.scope, + 'Agents Summary' + )) ] - - this.agentsSummaryTable = new rawTableDataService( - 'agentsSummaryTable', - `${ - this.filters - } sourcetype=wazuh |stats count sparkline by rule.id, rule.description, rule.level | sort rule.level DESC | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, - 'agentsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.agentsSummaryTable) - - this.agentsSummaryTable.getSearch().on('result', result => { - this.tableResults['Agents Summary'] = result - }) } /** * On controller loads */ $onInit() { - if (!this.pollingEnabled) { - this.scope.wzMonitoringEnabled = false - this.apiReq(`/agents/summary`) - .then(data => { - this.scope.agentsCountTotal = data.data.data.Total - 1 - this.scope.agentsCountActive = data.data.data.Active - 1 - this.scope.agentsCountDisconnected = data.data.data.Disconnected - this.scope.agentsCountNeverConnected = - data.data.data['Never connected'] - this.scope.agentsCoverity = this.scope.agentsCountTotal - ? (this.scope.agentsCountActive / this.scope.agentsCountTotal) * - 100 - : 0 - if (!this.scope.$$phase) this.scope.$digest() - }) - .catch(error => { - this.toast(`Cannot fetch agent status data: ${error}`) - }) - } else { - this.scope.wzMonitoringEnabled = true - - //Filters for agents Status - this.clusOrMng = Object.keys(this.currentDataService.getFilters()[0])[0] - if (this.clusOrMng == 'manager.name') { - this.mngName = this.currentDataService.getFilters()[0]['manager.name'] - this.agentsStatusFilter = `manager.name=${ - this.mngName - } index=wazuh-monitoring-3x` + try { + this.scope.loadingVizz = true + if (!this.pollingEnabled) { + this.scope.wzMonitoringEnabled = false + this.apiReq(`/agents/summary`) + .then(data => { + this.scope.agentsCountTotal = data.data.data.Total - 1 + this.scope.agentsCountActive = data.data.data.Active - 1 + this.scope.agentsCountDisconnected = data.data.data.Disconnected + this.scope.agentsCountNeverConnected = + data.data.data['Never connected'] + this.scope.agentsCoverity = this.scope.agentsCountTotal + ? (this.scope.agentsCountActive / this.scope.agentsCountTotal) * + 100 + : 0 + if (!this.scope.$$phase) this.scope.$digest() + }) + .catch(error => { + this.notification.showErrorToast( + `Cannot fetch agent status data: ${error}` + ) + }) } else { - this.clusName = this.currentDataService.getFilters()[0][ - 'cluster.name' - ] - this.agentsStatusFilter = `cluster.name=${ - this.clusName - } index=wazuh-monitoring-3x` - } + this.scope.wzMonitoringEnabled = true - this.spanTime = '1h' - this.vizz.push( - new LinearChart( - `agentStatusHistory`, - `${this.agentsStatusFilter} status=* | timechart span=${ - this.spanTime - } cont=FALSE count by status usenull=f`, - `agentStatus`, - this.scope + //Filters for agents Status + try { + this.clusOrMng = Object.keys( + this.currentDataService.getFilters()[0] + )[0] + + if (this.clusOrMng == 'manager.name') { + this.mngName = this.currentDataService.getFilters()[0][ + 'manager.name' + ] + this.agentsStatusFilter = `manager.name=${ + this.mngName + } index=wazuh-monitoring-3x` + } else { + this.clusName = this.currentDataService.getFilters()[0][ + 'cluster.name' + ] + this.agentsStatusFilter = `cluster.name=${ + this.clusName + } index=wazuh-monitoring-3x` + } + } catch (error) {} //eslint-disable-line + + this.spanTime = '15m' + this.vizz.push( + new LinearChart( + `agentStatusHistory`, + `${this.agentsStatusFilter} status=* | timechart span=${ + this.spanTime + } cont=FALSE count by status usenull=f`, + `agentStatus`, + this.scope + ) ) - ) - } + } - this.scope.startVis2Png = () => - this.reportingService.startVis2Png( - 'overview-general', - 'Security events', - this.filters, - [ - 'alertLevEvoVizz', - 'alertsVizz', - 'top5AgentsVizz', - 'alertsEvoTop5Agents', - 'agentsSummaryVizz' - ], - this.reportMetrics, - this.tableResults - ) + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'overview-general', + 'Security events', + this.filters, + [ + 'alertLevEvoVizz', + 'alertsVizz', + 'alertsEvoTop10Agents', + 'top10ruleGroups', + 'agentsSummaryVizz' + ], + this.reportMetrics, + this.tableResults + ) - this.scope.$on('$destroy', () => { - this.timePicker.destroy() - this.vizz.map(vizz => vizz.destroy()) - }) + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) - this.scope.$on('loadingReporting', (event, data) => { - this.scope.loadingReporting = data.status - }) + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) - this.scope.$on('checkReportingStatus', () => { - this.vizzReady = !this.vizz.filter(v => { - return v.finish === false - }).length - if (this.vizzReady) { - this.scope.loadingVizz = false - this.setReportMetrics() - } else { - this.scope.loadingVizz = true - } - if (!this.scope.$$phase) this.scope.$digest() - }) + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + this.setReportMetrics() + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) + } catch (error) { + console.error('error on init ', error) + } } /** @@ -287,6 +316,29 @@ define([ 'Authentication success': this.scope.authSuccess } } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('overviewGeneralCtrl', OverviewGeneral) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/index.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/index.js index 4a605f35f..64da1b347 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/index.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/index.js @@ -6,10 +6,12 @@ define([ './virustotal/overviewVirusTotalCtrl', './aws/awsCtrl', './osquery/osqueryCtrl', + './docker/dockerCtrl', './scap/overviewOpenScapCtrl', './gdpr/overviewGdprCtrl', './pci/overviewPciCtrl', './ciscat/ciscatCtrl', './policy-monitoring/overviewPolicyMonitoringCtrl', - './vulnerabilities/overviewVulnerabilitiesCtrl' + './vulnerabilities/overviewVulnerabilitiesCtrl', + './sca/overviewSCACtrl' ], function() {}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/osquery/osquery.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/osquery/osquery.html index 8ed307469..bca7c621a 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/osquery/osquery.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/osquery/osquery.html @@ -1,106 +1,127 @@ -
-
+
+
Overview / Osquery
- - - -
Waiting for reporting information
-
+ +
+ + +
-
Generating report
+
{{reportStatus}}
+ + + + + Vulnerabilities + Osquery + VirusTotal + Docker listener + - - -
- - - Wodle configuration - -
-
-
-
-

Add labels

-

{{osqueryWodle.add_labels}}

-
-
-
-

Configuration path

-

{{osqueryWodle.config_path}}

-
-
-

Disabled

-

{{osqueryWodle.disabled}}

-
-
-

Log path

-

{{osqueryWodle.log_path}}

-
-
-

Run daemon

-

{{(osqueryWodle.run_daemon)}}

-
-
-
-
-
- - - - Alerts over time - -
-
-
- -
- - -
- - - - Most common packs - -
-
-
- - - - Alerts evolution - Top 5 agents - -
-
-
- + +
+
+ Fetching data...
+
-
- - - - Top 5 packs - -
-
-
- - - - Top 5 rules - -
-
-
+
+ +
+ + + Top 5 Osquery events added + + + + + +
+
+
+ + + + Top 5 Osquery events removed + + + + + +
+
+
+ + + + Evolution of Osquery events per pack over time + + + + + +
+
+
+ +
+ + +
+ + + Most common packs + + + + + +
+
+
+ + + Top 5 rules + + + + + +
+
+
+
+ + +
+ + + Alerts summary + + + + + +
+
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/osquery/osqueryCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/osquery/osqueryCtrl.js index d03607dbd..139df317f 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/osquery/osqueryCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/osquery/osqueryCtrl.js @@ -5,7 +5,7 @@ define([ '../../../services/visualizations/table/table', '../../../services/visualizations/inputs/time-picker', '../../../services/rawTableData/rawTableDataService' -], function(app, PieChart, AreaChart, Table, TimePicker, rawTableDataService) { +], function (app, PieChart, AreaChart, Table, TimePicker, RawTableDataService) { 'use strict' class Osquery { @@ -26,147 +26,110 @@ define([ $state, $notificationService, osquery, - $reportingService + $reportingService, + reportingEnabled, + extensions ) { this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions this.osquery = osquery this.state = $state this.currentDataService = $currentDataService this.reportingService = $reportingService this.tableResults = {} this.currentDataService.addFilter( - `{"rule.groups":"osquery", "implicit":true}` + `{"rule.groups{}":"osquery", "implicit":true}` ) this.getFilters = this.currentDataService.getSerializedFilters this.filters = this.getFilters() this.scope.osqueryWodle = false - this.scope.$on('deletedFilter', () => { + this.scope.$on('deletedFilter', event => { + event.stopPropagation() this.launchSearches() }) - this.scope.$on('barFilter', () => { + this.scope.$on('barFilter', event => { + event.stopPropagation() this.launchSearches() }) + this.scope.expandArray = [false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + this.timePicker = new TimePicker( '#timePicker', $urlTokenModel.handleValueChange ) - this.toast = $notificationService.showSimpleToast + this.notification = $notificationService this.vizz = [ /** * Visualizations */ new AreaChart( - 'alertsOverTime', - `${this.filters} sourcetype=wazuh | timechart span=1h count`, - 'alertsOverTime', + 'alertsPacksOverTime', + `${ + this.filters + } sourcetype=wazuh | timechart span=1h count by data.osquery.pack`, + 'alertsPacksOverTime', this.scope ), - new AreaChart( - 'alertsEvolution', - `${ - this.filters - } sourcetype=wazuh | timechart span=1h limit=5 useother=f count by agent.name`, - 'alertsEvolution', + new PieChart( + 'topOsqueryAdded', + `${this.filters} sourcetype=wazuh data.osquery.action="added" | top data.osquery.name limit=5`, + 'topOsqueryAdded', this.scope ), new PieChart( - 'mostCommonEvents', - `${this.filters} sourcetype=wazuh | top data.osquery.name limit=5`, - 'mostCommonEvents', + 'topOsqueryRemoved', + `${this.filters} sourcetype=wazuh data.osquery.action="removed" | top data.osquery.name limit=5`, + 'topOsqueryRemoved', + this.scope + ), + new PieChart( + 'mostCommonPacks', + `${this.filters} sourcetype=wazuh | top data.osquery.pack limit=5`, + 'mostCommonPacks', this.scope ), new Table( - 'topPacks', + 'alertsSummary', `${ - this.filters - } sourcetype=wazuh | top "data.osquery.pack" limit=5 | rename data.osquery.pack as Pack, count as Count, percent as Percent`, - 'topPacks', + this.filters + } sourcetype=wazuh | stats count by data.osquery.name, data.osquery.action,agent.name,data.osquery.pack | rename data.osquery.name as Name, data.osquery.action as Action, agent.name as Agent, data.osquery.pack as Pack, count as Count`, + 'alertsSummary', this.scope ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh | stats count by data.osquery.name, data.osquery.action,agent.name,data.osquery.pack | rename data.osquery.name as Name, data.osquery.action as Action, agent.name as Agent, data.osquery.pack as Pack, count as Count`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts summary' + ), new Table( 'topRules', `${ - this.filters + this.filters } sourcetype=wazuh | top rule.id, rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule description", count as Count, percent as Percent`, 'topRules', this.scope - ) - ] - - this.topRulesTable = new rawTableDataService( - 'topRulesTable', - `${ - this.filters - } sourcetype=wazuh | top rule.id, rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule description", count as Count, percent as Percent`, - 'topRulesTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.topRulesTable) - - this.topRulesTable.getSearch().on('result', result => { - this.tableResults['Top 5 Rules'] = result - }) + ), - this.topPacksTable = new rawTableDataService( - 'topPacksTable', - `${ + new RawTableDataService( + 'topRulesTable', + `${ this.filters - } sourcetype=wazuh | top "data.osquery.pack" limit=5 | rename data.osquery.pack as Pack, count as Count, percent as Percent`, - 'topPacksTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.topPacksTable) - - this.topPacksTable.getSearch().on('result', result => { - this.tableResults['Top 5 Packs'] = result - }) - - /** - * Generates report - */ - this.scope.startVis2Png = () => - this.reportingService.startVis2Png( - 'ow-osquery', - 'Osquery', - this.filters, - [ - 'alertsOverTime', - 'mostCommonEvents', - 'alertsEvolution', - 'topPacks', - 'topRules' - ], - {}, //Metrics - this.tableResults + } sourcetype=wazuh | top rule.id, rule.description limit=5 | rename rule.id as "Rule ID", rule.description as "Rule description", count as Count, percent as Percent`, + 'topRulesTableToken', + '$result$', + this.scope, + 'Top 5 Rules' ) - - this.scope.$on('loadingReporting', (event, data) => { - this.scope.loadingReporting = data.status - }) - - this.scope.$on('checkReportingStatus', () => { - this.vizzReady = !this.vizz.filter(v => { - return v.finish === false - }).length - if (this.vizzReady) { - this.scope.loadingVizz = false - } else { - this.scope.loadingVizz = true - } - if (!this.scope.$$phase) this.scope.$digest() - }) - - /** - * On controller destroy - */ - this.scope.$on('$destroy', () => { - this.timePicker.destroy() - this.vizz.map(vizz => vizz.destroy()) - }) + ] } /** @@ -174,10 +137,59 @@ define([ */ $onInit() { try { + this.scope.loadingVizz = true const wodles = this.osquery.data.data.wmodules this.scope.osqueryWodle = wodles.filter(item => item.osquery)[0].osquery + /** + * Generates report + */ + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'ow-osquery', + 'Osquery', + this.filters, + [ + 'alertsPacksOverTime', + 'topOsqueryAdded', + 'topOsqueryRemoved', + 'mostCommonPacks', + 'alertsSummary', + 'topRules' + ], + {}, //Metrics + this.tableResults + ) + + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) + + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) + + /** + * On controller destroy + */ + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) } catch (err) { - this.toast( + this.notification.showErrorToast( 'Cannot load wodle configuration. Osquery is not configured.' ) } @@ -190,6 +202,29 @@ define([ this.filters = this.getFilters() this.state.reload() } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('osqueryCtrl', Osquery) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/pci/overview-pci.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/pci/overview-pci.html index 70c5e82ac..0ba4e6e3e 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/pci/overview-pci.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/pci/overview-pci.html @@ -1,84 +1,125 @@ - -
-
+ +
+
Overview / PCI-DSS
- - - -
Waiting for reporting information
+
+ + +
-
Generating report
+
{{reportStatus}}
+ + + PCI DSS + GDPR + - -
- - - -
- PCI-DSS Requirement: {{tab.rule}} - -
-
{{tab.description}}
-
-
-
-
-
-
-
- - - PCI Requirements - -
-
-
- - - Groups - -
-
-
-
-
- - - Agents - -
-
-
- - - Requirements by agent - -
-
-
+
+
+ Fetching data...
+
+
+ +
+ + + +
+ PCI-DSS Requirement: {{tab.title}} + +
+
{{tab.content}}
+
+
+
+
+
+
+
+ + + PCI Requirements + + + + + +
+
+
+ + + Top 10 Agents by alerts number + + + + + +
+
+
+
-
- - - Alerts summary - -
-
-
-
+
+ + + Top requirements over time + + + + +
+
+
+
+
+ + + Requirements by agent + + + + + +
+
+
+
+ +
+ + + Alerts summary + + + + + +
+
+
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/pci/overviewPciCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/pci/overviewPciCtrl.js index 909cb9dc4..5ef918f68 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/pci/overviewPciCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/pci/overviewPciCtrl.js @@ -1,180 +1,224 @@ define([ '../../module', + '../../../services/visualizations/chart/linear-chart', '../../../services/visualizations/chart/column-chart', '../../../services/visualizations/chart/pie-chart', '../../../services/visualizations/table/table', '../../../services/visualizations/inputs/time-picker', '../../../services/visualizations/inputs/dropdown-input', '../../../services/rawTableData/rawTableDataService' -], function( +], function ( app, + LinearChart, ColumnChart, PieChart, Table, TimePicker, Dropdown, - rawTableDataService + RawTableDataService ) { - 'use strict' + 'use strict' - class PCI { - /** - * Class PCI-DSS - * @param {*} $urlTokenModel - * @param {*} $scope - * @param {*} $currentDataService - * @param {*} $state - * @param {*} $reportingService - */ - constructor( - $urlTokenModel, - $scope, - $currentDataService, - $state, - $reportingService - ) { - this.scope = $scope - this.state = $state - this.reportingService = $reportingService - this.tableResults = {} - this.getFilters = $currentDataService.getSerializedFilters - this.filters = this.getFilters() - this.submittedTokenModel = $urlTokenModel.getSubmittedTokenModel() + class PCI { + /** + * Class PCI-DSS + * @param {*} $urlTokenModel + * @param {*} $scope + * @param {*} $currentDataService + * @param {*} $state + * @param {*} $reportingService + */ + constructor( + $urlTokenModel, + $scope, + $currentDataService, + $state, + $reportingService, + pciTabs, + reportingEnabled, + gdprExtensionEnabled + ) { + this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.gdprExtensionEnabled = gdprExtensionEnabled + this.state = $state + this.scope.pciTabs = pciTabs ? pciTabs : false + this.reportingService = $reportingService + this.tableResults = {} + this.getFilters = $currentDataService.getSerializedFilters + this.filters = this.getFilters() + this.submittedTokenModel = $urlTokenModel.getSubmittedTokenModel() - this.scope.$on('deletedFilter', () => { - this.launchSearches() - }) + this.scope.$on('deletedFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.scope.$on('barFilter', () => { - this.launchSearches() - }) + this.scope.$on('barFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.scope.$on('$destroy', () => { - this.dropdown.destroy() - this.timePicker.destroy() - this.vizz.map(vizz => vizz.destroy()) - }) - this.timePicker = new TimePicker( - '#timePicker', - $urlTokenModel.handleValueChange - ) - this.dropdown = new Dropdown( - 'dropDownInput', - `${ - this.filters - } sourcetype=wazuh rule.pci_dss{}="*"| stats count by "rule.pci_dss{}" | sort "rule.pci_dss{}" ASC | fields - count`, - 'rule.pci_dss{}', - '$form.pci$', - 'dropDownInput', - this.scope - ) - this.dropdownInstance = this.dropdown.getElement() - this.vizz = [ - new ColumnChart( - 'pciReqVizz', + this.scope.$on('$destroy', () => { + this.dropdown.destroy() + this.timePicker.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) + this.timePicker = new TimePicker( + '#timePicker', + $urlTokenModel.handleValueChange + ) + + this.scope.expandArray = [false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + + this.dropdown = new Dropdown( + 'dropDownInput', `${ - this.filters - } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count by rule.pci_dss{}`, - 'pciReqVizz', + this.filters + } sourcetype=wazuh rule.pci_dss{}="*"| stats count by "rule.pci_dss{}" | sort "rule.pci_dss{}" ASC | fields - count`, + 'rule.pci_dss{}', + '$form.pci$', + 'dropDownInput', this.scope - ), - new PieChart( - 'groupsVizz', - `${ + ) + this.dropdownInstance = this.dropdown.getElement() + + this.dropdownInstance.on('change', newValue => { + if (newValue && this.dropdownInstance) + $urlTokenModel.handleValueChange(this.dropdownInstance) + }) + + this.vizz = [ + new ColumnChart( + 'pciReqVizz', + `${ this.filters - } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count by rule.groups`, - 'groupsVizz', - this.scope - ), - new PieChart( - 'agentsVizz', - `${ + } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count by rule.pci_dss{}`, + 'pciReqVizz', + this.scope + ), + new LinearChart( + 'evoVizz', + `${ this.filters - } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count by agent.name`, - 'agentsVizz', - this.scope - ), - new ColumnChart( - 'requirementsByAgentVizz', - `${ + } sourcetype=wazuh rule.pci_dss{}="*" | timechart count by rule.pci_dss{}`, + 'evoVizz', + this.scope + ), + new PieChart( + 'agentsVizz', + `${ this.filters - } sourcetype=wazuh rule.pci_dss{}="$pci$" agent.name=*| chart count(rule.pci_dss{}) by rule.pci_dss{},agent.name`, - 'requirementsByAgentVizz', - this.scope - ), - new Table( - 'alertsSummaryViz', - `${ + } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count by agent.name`, + 'agentsVizz', + this.scope + ), + new ColumnChart( + 'requirementsByAgentVizz', + `${ this.filters - } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count sparkline by agent.name, rule.pci_dss{}, rule.description | sort count DESC | rename agent.name as "Agent Name", rule.pci_dss{} as Requirement, rule.description as "Rule description", count as Count`, - 'alertsSummaryViz', - this.scope - ) - ] + } sourcetype=wazuh rule.pci_dss{}="$pci$" agent.name=*| chart count(rule.pci_dss{}) by rule.pci_dss{},agent.name`, + 'requirementsByAgentVizz', + this.scope + ), + new Table( + 'alertsSummaryViz', + `${ + this.filters + } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count sparkline by agent.name, rule.pci_dss{}, rule.description | sort count DESC | rename agent.name as "Agent Name", rule.pci_dss{} as Requirement, rule.description as "Rule description", count as Count`, + 'alertsSummaryViz', + this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count sparkline by agent.name, rule.pci_dss{}, rule.description | sort count DESC | rename agent.name as "Agent Name", rule.pci_dss{} as Requirement, rule.description as "Rule description", count as Count`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' + ) + ] + } - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } sourcetype=wazuh rule.pci_dss{}="$pci$" | stats count sparkline by agent.name, rule.pci_dss{}, rule.description | sort count DESC | rename agent.name as "Agent Name", rule.pci_dss{} as Requirement, rule.description as "Rule description", count as Count`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) + $onInit() { + try { + this.scope.loadingVizz = true + /** + * Generates report + */ + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'overview-pci', + 'PCI DSS', + this.filters, + [ + 'pciReqVizz', + 'groupsVizz', + 'agentsVizz', + 'requirementsByAgentVizz', + 'alertsSummaryViz' + ], + {}, //Metrics + this.tableResults + ) - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) - /** - * Generates report - */ - this.scope.startVis2Png = () => - this.reportingService.startVis2Png( - 'overview-pci', - 'PCI DSS', - this.filters, - [ - 'pciReqVizz', - 'groupsVizz', - 'agentsVizz', - 'requirementsByAgentVizz', - 'alertsSummaryViz' - ], - {}, //Metrics - this.tableResults - ) + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) - this.scope.$on('loadingReporting', (event, data) => { - this.scope.loadingReporting = data.status - }) + } catch (error) {} + } - this.scope.$on('checkReportingStatus', () => { - this.vizzReady = !this.vizz.filter(v => { - return v.finish === false - }).length - if (this.vizzReady) { - this.scope.loadingVizz = false - } else { - this.scope.loadingVizz = true - } - if (!this.scope.$$phase) this.scope.$digest() - }) + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') - this.dropdownInstance.on('change', newValue => { - if (newValue && this.dropdownInstance) - $urlTokenModel.handleValueChange(this.dropdownInstance) - }) - } + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } - /** - * Get filters and launches the search - */ - launchSearches() { - this.filters = this.getFilters() - this.state.reload() + /** + * Get filters and launches the search + */ + launchSearches() { + this.filters = this.getFilters() + this.state.reload() + } } - } - app.controller('overviewPciCtrl', PCI) -}) + app.controller('overviewPciCtrl', PCI) + }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/policy-monitoring/overview-pm.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/policy-monitoring/overview-pm.html index c30d28570..e6b6d36ab 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/policy-monitoring/overview-pm.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/policy-monitoring/overview-pm.html @@ -1,71 +1,113 @@ - -
-
+ +
+
Overview / Policy monitoring
- - - -
Waiting for reporting information
+
+ + +
- -
Generating report
+
{{reportStatus}}
+ + + + Policy monitoring + SCA + System auditing + OpenSCAP + CIS-CAT + +
+
+ Fetching data...
+
+
+
+
+ + + Events over time + + + + + +
+
+
-
- - - Events over time - -
-
-
- - - - Top 5 CIS Requirements - -
-
-
+ + + Top 5 CIS Requirements + + + + + +
+
+
- - - Top 5 PCI DSS Requirements - -
-
-
-
+ + + Top 5 PCI DSS Requirements + + + + + +
+
+
+
-
- - - Events per agent evolution - -
-
-
-
+
+ + + Events per control type evolution + + + + + +
+
+
+
-
- - - Alerts summary - -
-
-
+
+ + + Alerts summary + + + + + +
+
+
+
- \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/policy-monitoring/overviewPolicyMonitoringCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/policy-monitoring/overviewPolicyMonitoringCtrl.js index fec5f555e..4d258d3b7 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/policy-monitoring/overviewPolicyMonitoringCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/policy-monitoring/overviewPolicyMonitoringCtrl.js @@ -5,7 +5,7 @@ define([ '../../../services/visualizations/table/table', '../../../services/visualizations/inputs/time-picker', '../../../services/rawTableData/rawTableDataService' -], function(app, PieChart, AreaChart, Table, TimePicker, rawTableDataService) { +], function(app, PieChart, AreaChart, Table, TimePicker, RawTableDataService) { 'use strict' class PM { /** @@ -21,19 +21,29 @@ define([ $scope, $currentDataService, $state, - $reportingService + $reportingService, + reportingEnabled, + extensions ) { this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions this.urlTokenModel = $urlTokenModel this.state = $state this.reportingService = $reportingService this.tableResults = {} + $currentDataService.addFilter( + `{"rule.groups{}":"rootcheck", "implicit":true}` + ) this.getFilters = $currentDataService.getSerializedFilters this.filters = this.getFilters() this.timePicker = new TimePicker( '#timePicker', this.urlTokenModel.handleValueChange ) + this.scope.expandArray = [false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) + this.vizz = [ /** * Visualizations @@ -42,15 +52,13 @@ define([ 'elementOverTime', `${ this.filters - } sourcetype=wazuh "rule.groups"="rootcheck" rule.description=* | timechart span=1h count by rule.description`, + } sourcetype=wazuh rule.description=* | timechart span=1h count by rule.description`, 'elementOverTime', this.scope ), new PieChart( 'cisRequirements', - `${ - this.filters - } sourcetype=wazuh "rule.groups"="rootcheck" rule.cis{}=* | top rule.cis{}`, + `${this.filters} sourcetype=wazuh rule.cis{}=* | top rule.cis{}`, 'cisRequirements', this.scope ), @@ -58,7 +66,7 @@ define([ 'topPciDss', `${ this.filters - } sourcetype=wazuh "rule.groups"="rootcheck" rule.pci_dss{}=* | top rule.pci_dss{}`, + } sourcetype=wazuh rule.pci_dss{}=* | top rule.pci_dss{}`, 'topPciDss', this.scope ), @@ -66,7 +74,7 @@ define([ 'eventsPerAgent', `${ this.filters - } sourcetype=wazuh "rule.groups"="rootcheck" | timechart span=2h count by agent.name`, + } sourcetype=wazuh | timechart span=2h count by data.title`, 'eventsPerAgent', this.scope ), @@ -74,76 +82,83 @@ define([ 'alertsSummary', `${ this.filters - } sourcetype=wazuh "rule.groups"="rootcheck" |stats count sparkline by agent.name, rule.description, title | sort count DESC | rename rule.description as "Rule description", agent.name as Agent, title as Control`, + } sourcetype=wazuh |stats count sparkline by agent.name, rule.description, title | sort count DESC | rename rule.description as "Rule description", agent.name as Agent, title as Control`, 'alertsSummary', this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh |stats count sparkline by agent.name, rule.description, title | sort count DESC | rename rule.description as "Rule description", agent.name as Agent, title as Control`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' ) ] + } - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } sourcetype=wazuh "rule.groups"="rootcheck" |stats count sparkline by agent.name, rule.description, title | sort count DESC | rename rule.description as "Rule description", agent.name as Agent, title as Control`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) - - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) - - this.scope.$on('deletedFilter', () => { - this.launchSearches() - }) - - this.scope.$on('barFilter', () => { - this.launchSearches() - }) - /** - * On controller destroy - */ - this.scope.$on('$destroy', () => { - this.timePicker.destroy() - this.vizz.map(vizz => vizz.destroy()) - }) - - /** - * Generates report - */ - this.scope.startVis2Png = () => - this.reportingService.startVis2Png( - 'overview-pm', - 'Policity monitoring', - this.filters, - [ - 'elementOverTime', - 'cisRequirements', - 'topPciDss', - 'eventsPerAgent', - 'alertsSummary' - ], - {}, //Metrics - this.tableResults - ) - - this.scope.$on('loadingReporting', (event, data) => { - this.scope.loadingReporting = data.status - }) - - this.scope.$on('checkReportingStatus', () => { - this.vizzReady = !this.vizz.filter(v => { - return v.finish === false - }).length - if (this.vizzReady) { - this.scope.loadingVizz = false - } else { - this.scope.loadingVizz = true - } - if (!this.scope.$$phase) this.scope.$digest() - }) + $onInit() { + try { + this.scope.loadingVizz = true + this.scope.$on('deletedFilter', event => { + event.stopPropagation() + this.launchSearches() + }) + + this.scope.$on('barFilter', event => { + event.stopPropagation() + this.launchSearches() + }) + /** + * On controller destroy + */ + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) + + /** + * Generates report + */ + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'overview-pm', + 'Policity monitoring', + this.filters, + [ + 'elementOverTime', + 'cisRequirements', + 'topPciDss', + 'eventsPerAgent', + 'alertsSummary' + ], + {}, //Metrics + this.tableResults + ) + + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) + + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) + } catch (error) {} //eslint-disable-line } /** @@ -153,6 +168,29 @@ define([ this.filters = this.getFilters() this.state.reload() } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('overviewPolicyMonitoringCtrl', PM) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/sca/overview-sca.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/sca/overview-sca.html new file mode 100644 index 000000000..4a5948198 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/sca/overview-sca.html @@ -0,0 +1,161 @@ + + +
+
+ Overview + / Security Configuration Assessment +
+
+ +
+ + + +
+
+
+ + +
{{reportStatus}}
+ + + + + Policy monitoring + + SCA + System auditing + OpenSCAP + CIS-CAT + + + + + +
+
+ Fetching data...
+
+
+
+ +
+ + + +
+ + + Score by policy + + + + + +
+
+
+
+ + +
+ + + Results distribution + + + + + +
+
+
+ + + Top 5 passed checks + + + + + +
+
+
+ + + Top 5 failed checks + + + + + +
+
+
+ +
+ + + +
+ + + Top 5 agents + + + + + +
+
+
+ + + Result distribution by policy + + + + + +
+
+
+ + + Score evolution over time + + + + + +
+
+
+
+ + +
+ + + Alerts summary + + + + + +
+
+
+
+
+ \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/sca/overviewSCACtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/sca/overviewSCACtrl.js new file mode 100644 index 000000000..00089e5c8 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/sca/overviewSCACtrl.js @@ -0,0 +1,341 @@ +/* + * Wazuh app - Overview SCA controller + * Copyright (C) 2015-2019 Wazuh, Inc. + * + * This program is free software you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation either version 2 of the License, or + * (at your option) any later version. + * + * Find more information about this on the LICENSE file. + */ + +define([ + '../../module', + '../../../services/visualizations/chart/column-chart', + '../../../services/visualizations/chart/single-value', + '../../../services/visualizations/chart/gauge-chart', + '../../../services/visualizations/chart/pie-chart', + '../../../services/visualizations/chart/area-chart', + '../../../services/visualizations/chart/linear-chart', + '../../../services/visualizations/table/table', + '../../../services/visualizations/inputs/time-picker', +], function( + app, + ColumnChart, + SingleValue, + GaugeChart, + PieChart, + AreaChart, + LinearChart, + Table, + TimePicker, +) { + 'use strict' + + class overviewSCA { + /** + * Class Overview SCA + * @param {Object} $urlTokenModel + * @param {Object} $scope + * @param {Object} $state + * @param {Object} $currentDataService + * @param {*} $reportingService + * @param {*} $requestService + * @param {*} $notificationService + * @param {*} $csvRequestService + */ + + constructor( + $urlTokenModel, + $rootScope, + $scope, + $state, + $currentDataService, + $reportingService, + $requestService, + $notificationService, + $csvRequestService, + $tableFilterService, + reportingEnabled, + BASE_URL, + extensions + ) { + this.urlTokenModel = $urlTokenModel + this.rootScope = $rootScope + this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions + this.apiReq = $requestService.apiReq + this.state = $state + this.reportingService = $reportingService + this.tableResults = {} + this.currentDataService = $currentDataService + this.notification = $notificationService + this.api = $currentDataService.getApi() + this.csvReq = $csvRequestService + this.wzTableFilter = $tableFilterService + this.baseUrl = BASE_URL + this.scope.noScansPng = `${ + this.baseUrl + }/static/app/SplunkAppForWazuh/css/images/sca_no_scans.png` + this.currentDataService.addFilter( + `{"rule.groups{}":"sca", "implicit":true}` + ) + this.scope.expandArray = [false, false, false, false, false,false,false] + this.scope.expand = (i, id) => this.expand(i, id) + + + this.filters = this.currentDataService.getSerializedFilters() + this.timePicker = new TimePicker( + '#timePicker', + this.urlTokenModel.handleValueChange + ) + + this.scope.$on('deletedFilter', (event) => { + event.stopPropagation() + this.launchSearches() + }) + + this.scope.$on('barFilter', (event) => { + event.stopPropagation() + this.launchSearches() + }) + + this.vizz = [ + /** + * Visualizations + */ + new GaugeChart( + 'scoreByPolicy', + `${ + this.filters + } | stats values(data.sca.score) by data.sca.policy_id `, + 'scoreByPolicy', + { trellisEnabled : true, + gaugeType : 'radialGauge'}, + this.scope + ), + new PieChart( + 'resultDistribution', + `${ + this.filters + } | stats count by data.sca.check.result `, + 'resultDistribution', + this.scope + ), + new ColumnChart( + 'resultDistributionByPolicy', + `${ + this.filters + } | stats sum(data.sca.failed) as failed, sum(data.sca.passed) as passed by data.sca.policy`, + 'resultDistributionByPolicy', + this.scope + ), + new PieChart( + 'top5Passed', + `${ + this.filters + } data.sca.check.result="passed" | top limit=5 data.sca.check.title`, + 'top5Passed', + this.scope + ), + new PieChart( + 'top5Failed', + `${ + this.filters + } data.sca.check.result="failed" | top limit=5 data.sca.check.title`, + 'top5Failed', + this.scope + ), + new PieChart( + 'top5Agents', + `${ + this.filters + } | top agent.name limit=5`, + 'top5Agents', + this.scope + ), + new AreaChart( + 'alertLevelEvolution', + `${ + this.filters + } | timechart span=1h count by rule.level`, + 'alertLevelEvolution', + this.scope + ), + new LinearChart( + 'overTimePolicy', + `${ + this.filters + } | timechart count by data.sca.policy`, + 'overTimePolicy', + this.scope + ), + new Table( + 'alertsSummary', + `${ + this.filters + } | stats count by data.sca.policy,data.sca.passed,data.sca.failed | fields - count | rename data.sca.policy as Policy data.sca.passed as Passed data.sca.failed as Failed | sort - Passed`, + 'alertsSummary', + this.scope + ) + ] + /** + * Generates report + */ + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'overview-sca', + 'Configuration assessment', + this.filters, + [ + 'scoreByPolicy', + 'resultDistribution', + 'alertsOverTime', + 'resultDistributionByPolicy', + 'top5Failed', + 'top5Passed', + 'alertsSummary' + ], + {}, //Metrics, + this.tableResults, + this.agentReportData + ) + + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) + + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) + + /** + * When controller is destroyed + */ + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) + } + + $onInit() { + this.scope.loadingVizz = true + this.scope.searchRootcheck = (term, specificFilter) => + this.scope.$broadcast('wazuhSearch', { term, specificFilter }) + this.scope.downloadCsv = () => this.downloadCsv() + + this.scope.switchVisualizations = () => this.switchVisualizations() + this.scope.loadPolicyChecks = (id, name) => + this.loadPolicyChecks(id, name) + this.scope.backToConfAssess = () => this.backToConfAssess() + + this.scope.agent = + this.agent && this.agent.data && this.agent.data.data + ? this.agent.data.data + : { error: true } + this.scope.getAgentStatusClass = agentStatus => + this.getAgentStatusClass(agentStatus) + this.scope.formatAgentStatus = agentStatus => + this.formatAgentStatus(agentStatus) + } + + /** + * Returns a class depending of the agent state + * @param {String} agentStatus + */ + getAgentStatusClass(agentStatus) { + return agentStatus === 'Active' ? 'teal' : 'red' + } + + /** + * Checks and returns agent status + * @param {Array} agentStatus + */ + formatAgentStatus(agentStatus) { + return ['Active', 'Disconnected'].includes(agentStatus) + ? agentStatus + : 'Never connected' + } + + /** + * Exports the table in CSV format + */ + async downloadCsv() { + try { + this.notification.showSimpleToast( + 'Your download should begin automatically...' + ) + const currentApi = this.api.id + const output = await this.csvReq.fetch( + '/agents', + currentApi, + this.wzTableFilter.get() + ) + const blob = new Blob([output], { type: 'text/csv' }) // eslint-disable-line + saveAs(blob, 'agents.csv') // eslint-disable-line + return + } catch (error) { + this.notification.showErrorToast('Error downloading CSV') + } + return + } + + /** + * Gets filters and launches search + */ + launchSearches() { + this.filters = this.currentDataService.getSerializedFilters() + this.state.reload() + } + + /** + * Loads policies checks + */ + async loadPolicyChecks(id, name) { + this.scope.showPolicyChecks = name + this.scope.policyId = id + const agentId = this.agent.data.data.id + this.scope.wzTablePath = `/sca/${agentId}/checks/${id}` + } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } + + } + app.controller('overviewSCACtrl', overviewSCA) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/scap/overview-openscap.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/scap/overview-openscap.html index f47e516f0..feeae0351 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/scap/overview-openscap.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/scap/overview-openscap.html @@ -1,107 +1,165 @@ - -
-
+ +
+
Overview / OpenSCAP
- - - -
Waiting for reporting information
+ +
+ + +
-
Generating report
+
{{reportStatus}}
+ + + + Policy monitoring + + SCA + System auditing + OpenSCAP + CIS-CAT + -
- - -
Last score: - -
-
Highest score: - -
-
Lowest score: - -
-
-
-
-
- - - Agents - -
-
-
- - - Profiles - -
-
-
- - - Content - -
-
-
- - - Severity - -
-
-
+
+
+ Fetching data...
+
+
+
+ + +
Last score: + +
+
Highest score: + +
+
Lowest score: + +
+
+
+
-
- - - Top 5 Agents - Severity high - -
-
-
-
+
+ + + Top 5 Agents + + + + + +
+
+
+ + + Top 5 Profiles + + + + + +
+
+
+ + + Top 5 Content + + + + + +
+
+
+ + + Top 5 Severity + + + + + +
+
+
+
-
- - - Top 10 - Alerts - -
-
-
+
+ + + Top 5 Agents - Severity high + + + + + +
+
+
+
- - - Top 10 - High risk alerts - -
-
-
-
+
+ + + Top 10 - Alerts + + + + + +
+
+
-
- - - Alerts summary - -
-
-
-
+ + + Top 10 - High risk alerts + + + + + +
+
+
+
+
+ + + Alerts summary + + + + + +
+
+
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/scap/overviewOpenScapCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/scap/overviewOpenScapCtrl.js index f5ee6f6e0..c743a632d 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/scap/overviewOpenScapCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/scap/overviewOpenScapCtrl.js @@ -9,7 +9,7 @@ define([ '../../../services/visualizations/inputs/dropdown-input', '../../../services/visualizations/search/search-handler', '../../../services/rawTableData/rawTableDataService' -], function( +], function ( app, LinearChart, ColumnChart, @@ -19,245 +19,293 @@ define([ TimePicker, Dropdown, SearchHandler, - rawTableDataService + RawTableDataService ) { - 'use strict' + 'use strict' - class OpenSCAP { - /** - * OpenSCAP class - * @param {*} $urlTokenModel - * @param {*} $scope - * @param {*} $currentDataService - * @param {*} $state - */ - constructor( - $urlTokenModel, - $scope, - $currentDataService, - $state, - $reportingService - ) { - this.scope = $scope - this.state = $state - this.reportingService = $reportingService - this.tableResults = {} - this.currentDataService = $currentDataService - this.currentDataService.addFilter( - `{"rule.groups":"oscap", "implicit":true}` - ) - this.getFilters = this.currentDataService.getSerializedFilters - this.filters = this.getFilters() - this.submittedTokenModel = $urlTokenModel.getSubmittedTokenModel() - this.scope.$on('deletedFilter', () => { - this.launchSearches() - }) + class OpenSCAP { + /** + * OpenSCAP class + * @param {*} $urlTokenModel + * @param {*} $scope + * @param {*} $currentDataService + * @param {*} $state + */ + constructor( + $urlTokenModel, + $scope, + $currentDataService, + $state, + $reportingService, + reportingEnabled, + extensions + ) { + this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.state = $state + this.reportingService = $reportingService + this.scope.extensions = extensions + this.tableResults = {} + this.currentDataService = $currentDataService + this.currentDataService.addFilter( + `{"rule.groups{}":"oscap", "implicit":true}` + ) + this.getFilters = this.currentDataService.getSerializedFilters + this.filters = this.getFilters() + this.submittedTokenModel = $urlTokenModel.getSubmittedTokenModel() + this.scope.$on('deletedFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.scope.$on('barFilter', () => { - this.launchSearches() - }) + this.scope.$on('barFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.scope.$on('$destroy', () => { - this.timePicker.destroy() - this.dropdown.destroy() - this.vizz.map(vizz => vizz.destroy()) - }) - this.timePicker = new TimePicker( - '#timePicker', - $urlTokenModel.handleValueChange - ) - this.dropdown = new Dropdown( - 'dropDownInput', - `${ - this.filters - } sourcetype=wazuh rule.groups="oscap" rule.groups!="syslog" oscap.scan.profile.title=* | stats count by oscap.scan.profile.title | sort oscap.scan.profile.title ASC|fields - count`, - 'oscap.scan.profile.title', - '$form.profile$', - 'dropDownInput', - this.scope - ) - this.vizz = [ - /** - * Metrics - */ - new SearchHandler( - `lastScapScore`, - `${ - this.filters - } sourcetype=wazuh oscap.scan.score=* | stats latest(oscap.scan.score)`, - `latestScapScore`, - '$result.latest(oscap.scan.score)$', - 'scapLastScore', - this.submittedTokenModel, - this.scope - ), - new SearchHandler( - `maxScapScore`, - `${ - this.filters - } sourcetype=wazuh oscap.scan.score=* | stats max(oscap.scan.score)`, - `maxScapScore`, - '$result.max(oscap.scan.score)$', - 'scapHighestScore', - this.submittedTokenModel, - this.scope - ), - new SearchHandler( - `scapLowest`, - `${ - this.filters - } sourcetype=wazuh oscap.scan.score=* | stats min(oscap.scan.score)`, - `minScapScore`, - '$result.min(oscap.scan.score)$', - 'scapLowestScore', - this.submittedTokenModel, - this.scope - ), + this.scope.expandArray = [ + false, + false, + false, + false, + false, + false, + false, + false + ] + this.scope.expand = (i, id) => this.expand(i, id) - /** - * Visualizations - */ - new PieChart( - 'agentsVizz', - `${ - this.filters - } sourcetype=wazuh oscap.check.result="fail" rule.groups="oscap" rule.groups!="syslog" oscap.scan.profile.title="$profile$" | top agent.name`, - 'agentsVizz', - this.scope - ), - new LinearChart( - 'profilesVizz', - `${ - this.filters - } sourcetype=wazuh rule.level=*| timechart count by rule.level`, - 'profilesVizz', - this.scope - ), - new ColumnChart( - 'contentVizz', - `${this.filters} sourcetype=wazuh | timechart span=2h count`, - 'contentVizz', - this.scope - ), - new PieChart( - 'severityVizz', - `${this.filters} sourcetype=wazuh | top agent.name`, - 'severityVizz', - this.scope - ), - new AreaChart( - 'top5AgentsVizz', + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.dropdown.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) + this.timePicker = new TimePicker( + '#timePicker', + $urlTokenModel.handleValueChange + ) + this.dropdown = new Dropdown( + 'dropDownInput', `${ - this.filters - } sourcetype=wazuh | timechart span=1h limit=5 useother=f count by agent.name`, - 'top5AgentsVizz', + this.filters + } sourcetype=wazuh rule.groups{}="oscap" rule.groups{}!="syslog" oscap.scan.profile.title=* | stats count by oscap.scan.profile.title | sort oscap.scan.profile.title ASC|fields - count`, + 'oscap.scan.profile.title', + '$form.profile$', + 'dropDownInput', this.scope - ), - new PieChart( - 'top10AlertsVizz', - `${ + ) + + this.dropdownInstance = this.dropdown.getElement() + this.dropdownInstance.on('change', newValue => { + if (newValue && this.dropdownInstance) + $urlTokenModel.handleValueChange(this.dropdownInstance) + }) + + this.vizz = [ + /** + * Metrics + */ + new SearchHandler( + `lastScapScore`, + `${ this.filters - } sourcetype=wazuh oscap.check.result="fail" rule.groups="oscap" rule.groups="oscap-result" oscap.scan.profile.title="$profile$" | top oscap.check.title`, - 'top10AlertsVizz', - this.scope - ), - new PieChart( - 'top10HRisk', - `${ + } sourcetype=wazuh oscap.scan.score=* | stats latest(oscap.scan.score)`, + `latestScapScore`, + '$result.latest(oscap.scan.score)$', + 'scapLastScore', + this.submittedTokenModel, + this.scope + ), + new SearchHandler( + `maxScapScore`, + `${ this.filters - } sourcetype=wazuh oscap.check.result="fail" rule.groups="oscap" rule.groups="oscap-result" oscap.check.severity="high" oscap.scan.profile.title="$profile$" | top oscap.check.title`, - 'top10HRisk', - this.scope - ), - new Table( - 'alertsSummaryVizz', - `${ + } sourcetype=wazuh oscap.scan.score=* | stats max(oscap.scan.score)`, + `maxScapScore`, + '$result.max(oscap.scan.score)$', + 'scapHighestScore', + this.submittedTokenModel, + this.scope + ), + new SearchHandler( + `scapLowest`, + `${ this.filters - } sourcetype=wazuh |stats count sparkline by rule.id, rule.description, rule.level | sort rule.level DESC | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, - 'alertsSummaryVizz', - this.scope - ) - ] - - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } sourcetype=wazuh |stats count sparkline by rule.id, rule.description, rule.level | sort rule.level DESC | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) + } sourcetype=wazuh oscap.scan.score=* | stats min(oscap.scan.score)`, + `minScapScore`, + '$result.min(oscap.scan.score)$', + 'scapLowestScore', + this.submittedTokenModel, + this.scope + ), - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) - - /** - * Generates report - */ - this.scope.startVis2Png = () => - this.reportingService.startVis2Png( - 'overview-oscap', - 'Open SCAP', - this.filters, - [ + /** + * Visualizations + */ + new PieChart( + 'agentsVizz', + `${ + this.filters + } sourcetype=wazuh oscap.check.result="fail" rule.groups{}="oscap" rule.groups{}!="syslog" oscap.scan.profile.title="$profile$" | top agent.name`, 'agentsVizz', + this.scope + ), + new LinearChart( 'profilesVizz', + `${ + this.filters + } sourcetype=wazuh rule.level=*| timechart count by rule.level`, + 'profilesVizz', + this.scope + ), + new ColumnChart( + 'contentVizz', + `${this.filters} sourcetype=wazuh | timechart span=2h count`, 'contentVizz', + this.scope + ), + new PieChart( 'severityVizz', + `${this.filters} sourcetype=wazuh | top agent.name`, + 'severityVizz', + this.scope + ), + new AreaChart( 'top5AgentsVizz', + `${ + this.filters + } sourcetype=wazuh | timechart span=1h limit=5 useother=f count by agent.name`, + 'top5AgentsVizz', + this.scope + ), + new PieChart( + 'top10AlertsVizz', + `${ + this.filters + } sourcetype=wazuh oscap.check.result="fail" rule.groups{}="oscap" rule.groups{}="oscap-result" oscap.scan.profile.title="$profile$" | top oscap.check.title`, 'top10AlertsVizz', + this.scope + ), + new PieChart( 'top10HRisk', - 'alertsSummaryVizz' - ], - this.reportMetrics, - this.tableResults - ) - - this.scope.$on('loadingReporting', (event, data) => { - this.scope.loadingReporting = data.status - }) + `${ + this.filters + } sourcetype=wazuh oscap.check.result="fail" rule.groups{}="oscap" rule.groups{}="oscap-result" oscap.check.severity="high" oscap.scan.profile.title="$profile$" | top oscap.check.title`, + 'top10HRisk', + this.scope + ), + new Table( + 'alertsSummaryVizz', + `${ + this.filters + } sourcetype=wazuh |stats count sparkline by rule.id, rule.description, rule.level | sort count DESC | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, + 'alertsSummaryVizz', + this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } sourcetype=wazuh |stats count sparkline by rule.id, rule.description, rule.level | sort count DESC | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' + ) + ] + } - this.scope.$on('checkReportingStatus', () => { - this.vizzReady = !this.vizz.filter(v => { - return v.finish === false - }).length - if (this.vizzReady) { - this.scope.loadingVizz = false - this.setReportMetrics() - } else { + $onInit() { + try { this.scope.loadingVizz = true - } - if (!this.scope.$$phase) this.scope.$digest() - }) + /** + * Generates report + */ + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'overview-oscap', + 'Open SCAP', + this.filters, + [ + 'agentsVizz', + 'profilesVizz', + 'contentVizz', + 'severityVizz', + 'top5AgentsVizz', + 'top10AlertsVizz', + 'top10HRisk', + 'alertsSummaryVizz' + ], + this.reportMetrics, + this.tableResults + ) - this.dropdownInstance = this.dropdown.getElement() - this.dropdownInstance.on('change', newValue => { - if (newValue && this.dropdownInstance) - $urlTokenModel.handleValueChange(this.dropdownInstance) - }) - } + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) + + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + this.setReportMetrics() + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) - /** - * Set report metrics - */ - setReportMetrics() { - this.reportMetrics = { - 'Last score': this.scope.scapLastScore, - 'Highest score': this.scope.scapHighestScore, - 'Lowest score': this.scope.scapLowestScore + } catch (error) { } + } + + /** + * Set report metrics + */ + setReportMetrics() { + this.reportMetrics = { + 'Last score': this.scope.scapLastScore, + 'Highest score': this.scope.scapHighestScore, + 'Lowest score': this.scope.scapLowestScore + } } - } - /** - * Get filters and launches the search - */ - launchSearches() { - this.filters = this.getFilters() - this.state.reload() + /** + * Get filters and launches the search + */ + launchSearches() { + this.filters = this.getFilters() + this.state.reload() + } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } - } - app.controller('overviewOpenScapCtrl', OpenSCAP) -}) + app.controller('overviewOpenScapCtrl', OpenSCAP) + }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/virustotal/overview-virustotal.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/virustotal/overview-virustotal.html index 17378a3a8..deb951499 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/virustotal/overview-virustotal.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/virustotal/overview-virustotal.html @@ -1,66 +1,118 @@ - -
-
+ +
+
Overview / VirusTotal
- - - -
Waiting for reporting information
+
+ + +
-
Generating report
+
{{reportStatus}}
+ + + + + Vulnerabilities + Osquery + VirusTotal + Docker listener + - -
- - - Top 5 agents with engines detected - -
-
-
- - - Events summary - -
-
-
-
- -
- - - Top 5 agents with no positives found - -
-
-
- - - Alerts per agent - -
-
-
+
+
+ Fetching data...
+
- -
- - - Top 5 rules - -
-
-
+
+ + +
+ + + Unique malicious files per agent + + + + + +
+
+
+ + + Last scanned files + + + + + +
+
+
+
+ + +
+ + + Top 10 agents with positive scans + + + + + +
+
+
+
+ + +
+ + + Malicious files alerts evolution + + + + + +
+
+
+
+ + + +
+ + + Last files + + + + + +
+
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/virustotal/overviewVirusTotalCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/virustotal/overviewVirusTotalCtrl.js index e3c1c95c5..496f0222a 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/virustotal/overviewVirusTotalCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/virustotal/overviewVirusTotalCtrl.js @@ -2,6 +2,8 @@ define([ '../../module', + '../../../services/visualizations/chart/column-chart', + '../../../services/visualizations/chart/area-chart', '../../../services/visualizations/chart/pie-chart', '../../../services/visualizations/table/table', '../../../services/visualizations/chart/linear-chart', @@ -10,12 +12,14 @@ define([ '../../../services/rawTableData/rawTableDataService' ], function( app, + ColumnChart, + AreaChart, PieChart, Table, LinearChart, TimePicker, BarChart, - rawTableDataService + RawTableDataService ) { 'use strict' @@ -33,15 +37,19 @@ define([ $scope, $currentDataService, $state, - $reportingService + $reportingService, + reportingEnabled, + extensions ) { this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions this.state = $state this.reportingService = $reportingService this.tableResults = {} //Add filer for VirusTotal $currentDataService.addFilter( - `{"rule.groups":"virustotal", "implicit":true}` + `{"rule.groups{}":"virustotal", "implicit":true}` ) this.getFilters = $currentDataService.getSerializedFilters this.filters = this.getFilters() @@ -50,21 +58,37 @@ define([ '#timePicker', $urlTokenModel.handleValueChange ) + this.scope.expandArray = [false, false, false, false, false] + this.scope.expand = (i, id) => this.expand(i, id) this.vizz = [ /** * Visualizations */ - new PieChart( - 'top5AgentsPositive', - `${this.filters} rule.id=87105 | top agent.name limit=5`, - 'top5AgentsPositive', + new ColumnChart( + 'top10AgentsPositive', + `${this.filters} | stats count(data.virustotal.positives) by agent.name | rename agent.name as "Agent name", count(data.virustotal.positives) as "Positives"`, + 'top10AgentsPositive', this.scope ), new PieChart( - 'top5AgentsNoPositive', + 'top10AgentsNoPositive', `${this.filters} rule.id=87104 | top agent.name limit=5`, - 'top5AgentsNoPositive', + 'top10AgentsNoPositive', + this.scope + ), + new AreaChart( + 'maliciousEventsOverTimeElement', + `${this.filters} data.virustotal.malicious="*" | timechart span=12h count by data.virustotal.malicious`, + 'maliciousEventsOverTimeElement', + this.scope + ), + new PieChart( + 'lastScannedFiles', + `${ + this.filters + } | top limit=5 data.virustotal.source.file`, + 'lastScannedFiles', this.scope ), new Table( @@ -75,6 +99,24 @@ define([ 'top5Rules', this.scope ), + new Table( + 'MaliciousFilesPerAgent', + `${ + this.filters + }| stats count(data.virustotal.malicious) by agent.name,data.virustotal.source.md5 | rename agent.name as "Agent name", count(data.virustotal.malicious) as Count, data.virustotal.source.md5 as md5`, + 'MaliciousFilesPerAgent', + this.scope + ), + new RawTableDataService( + 'MaliciousFilesPerAgentTable', + `${ + this.filters + }| stats count(data.virustotal.malicious) by agent.name,data.virustotal.source.md5 | rename agent.name as "Agent name", count(data.virustotal.malicious) as Count, data.virustotal.source.md5 as md5`, + 'MaliciousFilesPerAgentTableToken', + '$result$', + this.scope, + 'Unique malicious files per agent' + ), new LinearChart( 'eventsSummary', `${this.filters} | timechart count`, @@ -86,74 +128,103 @@ define([ `${this.filters} | top agent.name`, 'alertsPerAgent', this.scope + ), + new Table( + 'lastFiles', + `${ + this.filters + } | stats count by data.virustotal.source.file,data.virustotal.permalink | sort count DESC | rename data.virustotal.source.file as File,data.virustotal.permalink as Link, count as Count`, + 'lastFiles', + this.scope + ), + new RawTableDataService( + 'lastFilesTable', + `${ + this.filters + } | stats count by data.virustotal.source.file,data.virustotal.permalink as Count | sort count DESC | rename data.virustotal.source as File, data.virustotal.permalink as Link`, + 'lastFilesToken', + '$result$', + this.scope, + 'Last Files' + ), + new RawTableDataService( + 'top5RulesTable', + `${ + this.filters + } |stats count sparkline by rule.id, rule.description | sort count DESC | head 5 | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, + 'top5RulesTableToken', + '$result$', + this.scope, + 'Top 5 Rules' ) ] + } - this.top5RulesTable = new rawTableDataService( - 'top5RulesTable', - `${ - this.filters - } |stats count sparkline by rule.id, rule.description | sort count DESC | head 5 | rename rule.id as "Rule ID", rule.description as "Description", rule.level as Level, count as Count`, - 'top5RulesTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.top5RulesTable) - - this.top5RulesTable.getSearch().on('result', result => { - this.tableResults['Top 5 Rules'] = result - }) - + $onInit() { + try { + this.scope.loadingVizz = true /** * Generates report */ this.scope.startVis2Png = () => - this.reportingService.startVis2Png( - 'overview-virustotal', - 'VirusTotal', - this.filters, - [ - 'top5AgentsPositive', - 'eventsSummary', - 'top5AgentsNoPositive', - 'alertsPerAgent', - 'top5Rules' - ], - {}, //Metrics - this.tableResults - ) + this.reportingService.startVis2Png( + 'overview-virustotal', + 'VirusTotal', + this.filters, + [ + 'lastFiles', + 'maliciousEventsOverTimeElement', + 'MaliciousFilesPerAgent', + 'lastScannedFiles', + 'top10AgentsPositive', + 'eventsSummary', + 'top10AgentsNoPositive', + 'alertsPerAgent', + 'top5Rules' + ], + {}, //Metrics + this.tableResults + ) - this.scope.$on('loadingReporting', (event, data) => { - this.scope.loadingReporting = data.status - }) + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) - this.scope.$on('checkReportingStatus', () => { - this.vizzReady = !this.vizz.filter(v => { - return v.finish === false - }).length - if (this.vizzReady) { - this.scope.loadingVizz = false - } else { - this.scope.loadingVizz = true - } - if (!this.scope.$$phase) this.scope.$digest() - }) + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) - this.scope.$on('deletedFilter', () => { - this.launchSearches() - }) + this.scope.$on('deletedFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.scope.$on('barFilter', () => { - this.launchSearches() - }) + this.scope.$on('barFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - /** - * On controller destroy - */ - this.scope.$on('$destroy', () => { - this.timePicker.destroy() - this.vizz.map(vizz => vizz.destroy()) - }) + /** + * On controller destroy + */ + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) + } catch (error) {} //eslint-disable-line } /** @@ -163,6 +234,29 @@ define([ this.filters = this.getFilters() this.state.reload() } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } app.controller('overviewVirusTotal', OverviewVirusTotal) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/vulnerabilities/overview-vulnerabilities.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/vulnerabilities/overview-vulnerabilities.html index 5774bf7e2..668d93747 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/vulnerabilities/overview-vulnerabilities.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/vulnerabilities/overview-vulnerabilities.html @@ -1,94 +1,152 @@ - -
-
+ +
+
Overview / Vulnerabilities
- - - -
Waiting for reporting information
+
+ + +
- -
Generating report
+
{{reportStatus}}
+ + + + Vulnerabilities + + Osquery + VirusTotal + Docker listener + -
- - -
Critical severity alerts: - -
-
High severity alerts: - -
-
Medium severity alerts: - -
-
Low severity alerts: - -
-
-
+
+
+ Fetching data...
+
+
+
+ + +
Critical severity alerts: + +
+
High severity alerts: + +
+
Medium severity alerts: + +
+
Low severity alerts: + +
+
+
+
-
- - - Most affected agents - -
-
-
- - - Alerts evolution over time - -
-
-
-
+
+ + + Most affected agents + + + + + +
+
+
+ + + Alerts severity + + + + + +
+
+
+
-
- - - Severity distribution - -
-
-
- - - Commonly affectected packages - -
-
-
- - - Most common CVEs - -
-
-
-
+
+ + + Severity distribution + + + + + +
+
+
+ + + Commonly affectected packages + + + + + +
+
+
+ + + Most common CVEs + + + + + +
+
+
+ + + Most common CWEs + + + + + +
+
+
+
-
- - - Alerts summary - -
-
-
+
+ + + Alerts summary + + + + + +
+
+
+
- \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/vulnerabilities/overviewVulnerabilitiesCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/vulnerabilities/overviewVulnerabilitiesCtrl.js index 57228a435..3fbe0d58f 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/vulnerabilities/overviewVulnerabilitiesCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/vulnerabilities/overviewVulnerabilitiesCtrl.js @@ -8,7 +8,7 @@ define([ '../../../services/visualizations/inputs/time-picker', '../../../services/visualizations/search/search-handler', '../../../services/rawTableData/rawTableDataService' -], function( +], function ( app, BarChart, ColumnChart, @@ -17,203 +17,252 @@ define([ Table, TimePicker, SearchHandler, - rawTableDataService + RawTableDataService ) { - 'use strict' - class OverviewVulnerabilities { - /** - * - * @param {*} $urlTokenModel - * @param {*} $scope - * @param {*} $currentDataService - * @param {*} $state - * @param {*} $reportingService - */ - constructor( - $urlTokenModel, - $scope, - $currentDataService, - $state, - $reportingService - ) { - this.scope = $scope - this.state = $state - this.reportingService = $reportingService - this.tableResults = {} - this.timePicker = new TimePicker( - '#timePicker', - $urlTokenModel.handleValueChange - ) - this.submittedTokenModel = $urlTokenModel.getSubmittedTokenModel() - this.getFilters = $currentDataService.getSerializedFilters - this.filters = this.getFilters() + 'use strict' + class OverviewVulnerabilities { + /** + * + * @param {*} $urlTokenModel + * @param {*} $scope + * @param {*} $currentDataService + * @param {*} $state + * @param {*} $reportingService + */ + constructor( + $urlTokenModel, + $scope, + $currentDataService, + $state, + $reportingService, + reportingEnabled, + extensions + ) { + this.scope = $scope + this.scope.reportingEnabled = reportingEnabled + this.scope.extensions = extensions + this.state = $state + this.reportingService = $reportingService + this.tableResults = {} + this.timePicker = new TimePicker( + '#timePicker', + $urlTokenModel.handleValueChange + ) + this.submittedTokenModel = $urlTokenModel.getSubmittedTokenModel() + $currentDataService.addFilter( + `{"rule.groups{}":"vulnerability-detector", "implicit":true, "onlyShow":true}` + ) + this.getFilters = $currentDataService.getSerializedFilters + this.filters = this.getFilters() - this.scope.$on('deletedFilter', () => { - this.launchSearches() - }) + this.scope.$on('deletedFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.scope.$on('barFilter', () => { - this.launchSearches() - }) + this.scope.$on('barFilter', event => { + event.stopPropagation() + this.launchSearches() + }) - this.vizz = [ - /** - * Metrics - */ - new SearchHandler( - `criticalSeveritySearch`, - `${this.filters} data.vulnerability.severity=critical | stats count`, - `criticalSeverityToken`, - `$result.count$`, - `criticalSeverity`, - this.submittedTokenModel, - this.scope - ), - new SearchHandler( - `highSeveritySeach`, - `${this.filters} data.vulnerability.severity=high | stats count`, - `highSeverityToken`, - `$result.count$`, - `highSeverity`, - this.submittedTokenModel, - this.scope - ), - new SearchHandler( - `mediumSeveritySeach`, - `${this.filters} data.vulnerability.severity=medium | stats count`, - `mediumSeverityToken`, - `$result.count$`, - `mediumSeverity`, - this.submittedTokenModel, - this.scope - ), - new SearchHandler( - `lowSeveritySeach`, - `${this.filters} data.vulnerability.severity=low | stats count`, - `lowSeverityToken`, - `$result.count$`, - `lowSeverity`, - this.submittedTokenModel, - this.scope - ), - /** - * Visualizations - */ - new PieChart( - 'affectedAgents', - `${ + this.scope.expandArray = [false, false, false, false, false, false,false,false] + this.scope.expand = (i, id) => this.expand(i, id) + + this.vizz = [ + /** + * Metrics + */ + new SearchHandler( + `criticalSeveritySearch`, + `${this.filters} data.vulnerability.severity=critical | stats count`, + `criticalSeverityToken`, + `$result.count$`, + `criticalSeverity`, + this.submittedTokenModel, + this.scope + ), + new SearchHandler( + `highSeveritySeach`, + `${this.filters} data.vulnerability.severity=high | stats count`, + `highSeverityToken`, + `$result.count$`, + `highSeverity`, + this.submittedTokenModel, + this.scope + ), + new SearchHandler( + `mediumSeveritySeach`, + `${this.filters} data.vulnerability.severity=medium | stats count`, + `mediumSeverityToken`, + `$result.count$`, + `mediumSeverity`, + this.submittedTokenModel, + this.scope + ), + new SearchHandler( + `lowSeveritySeach`, + `${this.filters} data.vulnerability.severity=low | stats count`, + `lowSeverityToken`, + `$result.count$`, + `lowSeverity`, + this.submittedTokenModel, + this.scope + ), + /** + * Visualizations + */ + new PieChart( + 'affectedAgents', + `${ this.filters - } rule.groups=vulnerability-detector | top agent.name limit=5`, - 'affectedAgents', - this.scope - ), - new AreaChart( - 'alertsEvolution', - `${ + } rule.groups{}=vulnerability-detector | top agent.name limit=5`, + 'affectedAgents', + this.scope + ), + new AreaChart( + 'alertsEvolution', + `${ this.filters - } rule.groups=vulnerability-detector data.vulnerability.severity=* | timechart count by data.vulnerability.severity`, - 'alertsEvolution', - this.scope - ), - new ColumnChart( - 'severityDist', - `${ + } rule.groups{}=vulnerability-detector data.vulnerability.severity=* | timechart count by data.vulnerability.severity`, + 'alertsEvolution', + this.scope + ), + new ColumnChart( + 'severityDist', + `${ this.filters - } data.vulnerability.severity=* | spath "agent.name" | search "agent.name"=* | rename agent.id AS RootObject.agent.id agent.ip AS RootObject.agent.ip agent.name AS RootObject.agent.name data.vulnerability.cve AS RootObject.data.vulnerability.cve data.vulnerability.package.condition AS RootObject.data.vulnerability.package.condition data.vulnerability.package.name AS RootObject.data.vulnerability.package.name data.vulnerability.package.version AS RootObject.data.vulnerability.package.version data.vulnerability.published AS RootObject.data.vulnerability.published data.vulnerability.reference AS RootObject.data.vulnerability.reference data.vulnerability.severity AS RootObject.data.vulnerability.severity data.vulnerability.state AS RootObject.data.vulnerability.state data.vulnerability.title AS RootObject.data.vulnerability.title data.vulnerability.updated AS RootObject.data.vulnerability.updated date_hour AS RootObject.date_hour date_mday AS RootObject.date_mday date_minute AS RootObject.date_minute date_month AS RootObject.date_month date_second AS RootObject.date_second date_wday AS RootObject.date_wday date_year AS RootObject.date_year date_zone AS RootObject.date_zone decoder.name AS RootObject.decoder.name id AS RootObject.id index AS RootObject.index linecount AS RootObject.linecount location AS RootObject.location manager.name AS RootObject.manager.name rule.description AS RootObject.rule.description rule.firedtimes AS RootObject.rule.firedtimes "rule.gdpr{}" AS "RootObject.rule.gdpr{}" rule.groups AS RootObject.rule.groups "rule.groups{}" AS "RootObject.rule.groups{}" rule.id AS RootObject.rule.id rule.level AS RootObject.rule.level rule.mail AS RootObject.rule.mail splunk_server AS RootObject.splunk_server timeendpos AS RootObject.timeendpos timestamp AS RootObject.timestamp timestartpos AS RootObject.timestartpos | fields "_time" "host" "source" "sourcetype" "RootObject.agent.id" "RootObject.agent.ip" "RootObject.agent.name" "RootObject.data.vulnerability.cve" "RootObject.data.vulnerability.package.condition" "RootObject.data.vulnerability.package.name" "RootObject.data.vulnerability.package.version" "RootObject.data.vulnerability.published" "RootObject.data.vulnerability.reference" "RootObject.data.vulnerability.severity" "RootObject.data.vulnerability.state" "RootObject.data.vulnerability.title" "RootObject.data.vulnerability.updated" "RootObject.date_hour" "RootObject.date_mday" "RootObject.date_minute" "RootObject.date_month" "RootObject.date_second" "RootObject.date_wday" "RootObject.date_year" "RootObject.date_zone" "RootObject.decoder.name" "RootObject.id" "RootObject.index" "RootObject.linecount" "RootObject.location" "RootObject.manager.name" "RootObject.rule.description" "RootObject.rule.firedtimes" ""RootObject.rule.gdpr{}"" "RootObject.rule.groups" ""RootObject.rule.groups{}"" "RootObject.rule.id" "RootObject.rule.level" "RootObject.rule.mail" "RootObject.splunk_server" "RootObject.timeendpos" "RootObject.timestamp" "RootObject.timestartpos" | eval "RootObject.data.vulnerability.severity"='RootObject.data.vulnerability.severity', "agent.name"='RootObject.agent.name' | chart dedup_splitvals=t limit=100 useother=t count AS "Count of 1532686833.50" by agent.name RootObject.data.vulnerability.severity format=$$VAL$$:::$$AGG$$ | sort limit=100 RootObject.agent.name | fields - _span | fields agent.name *`, - 'severityDist', - this.scope - ), - new PieChart( - 'commonAffectedPackages', - `${this.filters} | top 5 data.vulnerability.package.name`, - 'commonAffectedPackages', - this.scope - ), - new BarChart( - 'commonCves', - `${ + } data.vulnerability.severity=* | spath "agent.name" | search "agent.name"=* | rename agent.id AS RootObject.agent.id agent.ip AS RootObject.agent.ip agent.name AS RootObject.agent.name data.vulnerability.cve AS RootObject.data.vulnerability.cve data.vulnerability.package.condition AS RootObject.data.vulnerability.package.condition data.vulnerability.package.name AS RootObject.data.vulnerability.package.name data.vulnerability.package.version AS RootObject.data.vulnerability.package.version data.vulnerability.published AS RootObject.data.vulnerability.published data.vulnerability.reference AS RootObject.data.vulnerability.reference data.vulnerability.severity AS RootObject.data.vulnerability.severity data.vulnerability.state AS RootObject.data.vulnerability.state data.vulnerability.title AS RootObject.data.vulnerability.title data.vulnerability.updated AS RootObject.data.vulnerability.updated date_hour AS RootObject.date_hour date_mday AS RootObject.date_mday date_minute AS RootObject.date_minute date_month AS RootObject.date_month date_second AS RootObject.date_second date_wday AS RootObject.date_wday date_year AS RootObject.date_year date_zone AS RootObject.date_zone decoder.name AS RootObject.decoder.name id AS RootObject.id index AS RootObject.index linecount AS RootObject.linecount location AS RootObject.location manager.name AS RootObject.manager.name rule.description AS RootObject.rule.description rule.firedtimes AS RootObject.rule.firedtimes "rule.gdpr{}" AS "RootObject.rule.gdpr{}" rule.groups{} AS RootObject.rule.groups{} "rule.groups{}{}" AS "RootObject.rule.groups{}{}" rule.id AS RootObject.rule.id rule.level AS RootObject.rule.level rule.mail AS RootObject.rule.mail splunk_server AS RootObject.splunk_server timeendpos AS RootObject.timeendpos timestamp AS RootObject.timestamp timestartpos AS RootObject.timestartpos | fields "_time" "host" "source" "sourcetype" "RootObject.agent.id" "RootObject.agent.ip" "RootObject.agent.name" "RootObject.data.vulnerability.cve" "RootObject.data.vulnerability.package.condition" "RootObject.data.vulnerability.package.name" "RootObject.data.vulnerability.package.version" "RootObject.data.vulnerability.published" "RootObject.data.vulnerability.reference" "RootObject.data.vulnerability.severity" "RootObject.data.vulnerability.state" "RootObject.data.vulnerability.title" "RootObject.data.vulnerability.updated" "RootObject.date_hour" "RootObject.date_mday" "RootObject.date_minute" "RootObject.date_month" "RootObject.date_second" "RootObject.date_wday" "RootObject.date_year" "RootObject.date_zone" "RootObject.decoder.name" "RootObject.id" "RootObject.index" "RootObject.linecount" "RootObject.location" "RootObject.manager.name" "RootObject.rule.description" "RootObject.rule.firedtimes" ""RootObject.rule.gdpr{}"" "RootObject.rule.groups{}" ""RootObject.rule.groups{}{}"" "RootObject.rule.id" "RootObject.rule.level" "RootObject.rule.mail" "RootObject.splunk_server" "RootObject.timeendpos" "RootObject.timestamp" "RootObject.timestartpos" | eval "RootObject.data.vulnerability.severity"='RootObject.data.vulnerability.severity', "agent.name"='RootObject.agent.name' | chart dedup_splitvals=t limit=100 useother=t count AS "Count of 1532686833.50" by agent.name RootObject.data.vulnerability.severity format=$$VAL$$:::$$AGG$$ | sort limit=100 RootObject.agent.name | fields - _span | fields agent.name *`, + 'severityDist', + this.scope + ), + new PieChart( + 'commonAffectedPackages', + `${this.filters} | top 5 data.vulnerability.package.name`, + 'commonAffectedPackages', + this.scope + ), + new PieChart( + 'commonCves', + `${ this.filters - } rule.groups=vulnerability-detector | top data.vulnerability.cve limit=5`, - 'commonCves', - this.scope - ), - new Table( - 'alertsSummary', - `${ + } rule.groups{}=vulnerability-detector | top data.vulnerability.cve limit=5`, + 'commonCves', + this.scope + ), + new PieChart( + 'commonCwes', + `${ this.filters - } | stats count sparkline by data.vulnerability.title, data.vulnerability.severity, data.vulnerability.reference | rename data.vulnerability.title as Title, data.vulnerability.severity as Severity, data.vulnerability.reference as Reference, count as Count, sparkline as Sparkline`, - 'alertsSummary', - this.scope - ) - ] - - this.alertsSummaryTable = new rawTableDataService( - 'alertsSummaryTable', - `${ - this.filters - } | stats count sparkline by data.vulnerability.title, data.vulnerability.severity | rename data.vulnerability.title as Title, data.vulnerability.severity as Severity, count as Count, sparkline as Sparkline`, - 'alertsSummaryTableToken', - '$result$', - this.scope - ) - this.vizz.push(this.alertsSummaryTable) + } rule.groups{}=vulnerability-detector | top data.vulnerability.cwe_reference limit=5`, + 'commonCwes', + this.scope + ), + new Table( + 'alertsSummary', + `${ + this.filters + } | stats count sparkline by data.vulnerability.title, data.vulnerability.severity, data.vulnerability.reference | sort count DESC | rename data.vulnerability.title as Title, data.vulnerability.severity as Severity, data.vulnerability.reference as Reference, count as Count, sparkline as Sparkline`, + 'alertsSummary', + this.scope + ), + new RawTableDataService( + 'alertsSummaryTable', + `${ + this.filters + } | stats count sparkline by data.vulnerability.title, data.vulnerability.severity | sort count DESC | rename data.vulnerability.title as Title, data.vulnerability.severity as Severity, count as Count, sparkline as Sparkline`, + 'alertsSummaryTableToken', + '$result$', + this.scope, + 'Alerts Summary' + ) + ] + } - this.alertsSummaryTable.getSearch().on('result', result => { - this.tableResults['Alerts Summary'] = result - }) + $onInit() { + try { + this.scope.loadingVizz = true + /** + * Generates report + */ + this.scope.startVis2Png = () => + this.reportingService.startVis2Png( + 'overview-vulnerabilities', + 'Vulnerabilities', + this.filters, + [ + 'affectedAgents', + 'alertsEvolution', + 'severityDist', + 'commonAffectedPackages', + 'commonCves', + 'commonCwes', + 'alertsSummary' + ], + {}, //Metrics + this.tableResults + ) - /** - * Generates report - */ - this.scope.startVis2Png = () => - this.reportingService.startVis2Png( - 'overview-vulnerabilities', - 'Vulnerabilities', - this.filters, - [ - 'affectedAgents', - 'alertsEvolution', - 'severityDist', - 'commonAffectedPackages', - 'commonCves', - 'alertsSummary' - ], - {}, //Metrics - this.tableResults - ) + this.scope.$on('loadingReporting', (event, data) => { + this.scope.loadingReporting = data.status + }) - this.scope.$on('loadingReporting', (event, data) => { - this.scope.loadingReporting = data.status - }) + this.scope.$on('checkReportingStatus', () => { + this.vizzReady = !this.vizz.filter(v => { + return v.finish === false + }).length + if (this.vizzReady) { + this.scope.loadingVizz = false + } else { + this.vizz.map(v => { + if (v.constructor.name === 'RawTableData') { + this.tableResults[v.name] = v.results + } + }) + this.scope.loadingVizz = true + } + if (!this.scope.$$phase) this.scope.$digest() + }) - this.scope.$on('checkReportingStatus', () => { - this.vizzReady = !this.vizz.filter(v => { - return v.finish === false - }).length - if (this.vizzReady) { - this.scope.loadingVizz = false - } else { - this.scope.loadingVizz = true - } - if (!this.scope.$$phase) this.scope.$digest() - }) + /** + * On controller destroy + */ + this.scope.$on('$destroy', () => { + this.timePicker.destroy() + this.vizz.map(vizz => vizz.destroy()) + }) + } catch (error) { } //eslint-disable-line + } /** - * On controller destroy + * Get filters and launches the search */ - this.scope.$on('$destroy', () => { - this.timePicker.destroy() - this.vizz.map(vizz => vizz.destroy()) - }) - } + launchSearches() { + this.filters = this.getFilters() + this.state.reload() + } + + expand(i, id) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + let vis = $( + '#' + id + ' .panel-body .splunk-view .shared-reportvisualizer' + ) + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') - /** - * Get filters and launches the search - */ - launchSearches() { - this.filters = this.getFilters() - this.state.reload() + let vis_header = $('.wz-headline-title') + vis_header.dblclick(e => { + if (this.scope.expandArray[i]) { + this.scope.expandArray[i] = !this.scope.expandArray[i] + this.scope.expandArray[i] + ? vis.css('height', 'calc(100vh - 200px)') + : vis.css('height', '250px') + this.scope.$applyAsync() + } else { + e.preventDefault() + } + }) + } } - } - app.controller('overviewVulnerabilitiesCtrl', OverviewVulnerabilities) -}) + app.controller('overviewVulnerabilitiesCtrl', OverviewVulnerabilities) + }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/welcome/overview-welcome.html b/SplunkAppForWazuh/appserver/static/js/controllers/overview/welcome/overview-welcome.html index 09bb0c839..4cbbbb862 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/welcome/overview-welcome.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/welcome/overview-welcome.html @@ -1,20 +1,7 @@
-
-
- Overview - / Welcome -
-
-
-
- -
- - Overview -
-
- +
+
Total agents: @@ -40,32 +27,35 @@
-

Security Information Management

+

Security Information Management

+ sub-title="'Security events'" ui-sref='ow-general' current-tab="'general'" description="'Browse through your security alerts, identifying issues and threats in your environment.'"> + sub-title="'File integrity monitoring'" ui-sref='ow-fim' current-tab="'fim'" description="'Alerts related to file changes, including permissions, content, ownership and attributes.'"> + sub-title="'Amazon Web Services'" ui-sref='ow-aws' current-tab="'aws'" description="'Security events related to your Amazon AWS services, collected directly via AWS API.'">
-

Auditing and Policy Monitoring

+

Auditing and Policy Monitoring

- + sub-title="'Policy monitoring'" ui-sref='ow-pm' current-tab="'pm'" description="'Verify that your systems are configured according to your security policies baseline.'"> + + + sub-title="'Open SCAP'" ui-sref='ow-os' current-tab="'oscap'" description="'Configuration assessment and automation of compliance monitoring using SCAP checks.'"> + sub-title="'CIS-CAT'" ui-sref='ow-ciscat' current-tab="'oscap'" description="'Configuration assessment using Center of Internet Security scanner and SCAP checks.'">
@@ -77,28 +67,30 @@

Auditing and Policy Monitoring

-

Threat Detection and Response

+

Threat Detection and Response

- - - + +
-

Regulatory Compliance

+

Regulatory Compliance

+ sub-title="'PCI DSS'" ui-sref='ow-pci' current-tab="'pci'" description="'Global security standard for entities that process, store or transmit payment cardholder data.'"> + sub-title="'GDPR'" ui-sref='ow-gdpr' current-tab="'gdpr'" description="'General Data Protection Regulation (GDPR) sets guidelines for processing of personal data.'">
diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/overview/welcome/overviewWelcomeCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/overview/welcome/overviewWelcomeCtrl.js index 01fae998c..845838791 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/overview/welcome/overviewWelcomeCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/overview/welcome/overviewWelcomeCtrl.js @@ -10,12 +10,17 @@ define(['../../module'], function(controllers) { */ constructor($scope, agentsInfo, extensions) { this.scope = $scope - this.scope.agentsCountTotal = agentsInfo.data.data.Total - 1 - this.scope.agentsCountActive = agentsInfo.data.data.Active - 1 - this.scope.agentsCountDisconnected = agentsInfo.data.data.Disconnected - this.scope.agentsCountNeverConnected = - agentsInfo.data.data['Never Connected'] - this.extensions = extensions + try { + this.scope.agentsCountTotal = agentsInfo.data.data.Total - 1 + this.scope.agentsCountActive = agentsInfo.data.data.Active - 1 + this.scope.agentsCountDisconnected = agentsInfo.data.data.Disconnected + this.scope.agentsCountNeverConnected = + agentsInfo.data.data['Never Connected'] + } catch (error) {} //eslint-disable-line + + try { + this.extensions = extensions + } catch (error) {} //eslint-disable-line } /** diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/settings/about/about.html b/SplunkAppForWazuh/appserver/static/js/controllers/settings/about/about.html index 75d59ae60..79986e266 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/settings/about/about.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/settings/about/about.html @@ -1,7 +1,7 @@ -
Welcome to the Splunk app for Wazuh -
- +
Wazuh Splunk plugin description +
+
App version: @@ -16,61 +16,35 @@
-
- - - -
-
- The Wazuh Splunk app provides management and monitoring capabilities, giving users control over the Wazuh infrastructure. Using this app you can monitor your agents status and configuration, query and visualize your alert data and monitor manager rules and configuration. Additionally this user interface provides a number of extensions listed below. -
-
-
-
- Wazuh plugin main extensions: -
-
-
    -
  • Linux Audit system integration
  • -
  • PCI DSS regulatory compliance
  • -
  • GDPR regulatory compliance
  • -
  • OpenSCAP configuration and vulnerability assessment
  • -
  • Amazon Web Services (AWS) integration
  • -
-
+
+ + + Welcome to + the + Wazuh app for Splunk {{appInfo.splunk_version}} + +
+ Wazuh Splunk plugin provides management and monitoring capabilities, giving users control + over the Wazuh infrastructure. Using this plugin you can monitor your agents status and + configuration, query and visualize your alert data and monitor manager rules and + configuration.
-
-
- Wazuh plugin main sections: -
-
-
    -
  • Manager status and configuration monitoring
  • -
  • Ruleset management and agent groups
  • -
  • Agent configuration management
  • -
  • Security Information Management
  • -
  • Auditing and Policy monitoring
  • -
  • Threat Detection and Response
  • -
  • Regulatory Compliance
  • -
-
+ + + + + Community + +
+ Enjoy your Wazuh experience and please don't hesitate to give us your feedback.
-
-
- Enjoy your Wazuh experience and please don't hesitate to give us your feedback. -
-
- - - - Mailing list - - - Wazuh Splunk app repository - - - Wazuh core repository - - - +
+ + + + +
+ + +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/settings/api/api.html b/SplunkAppForWazuh/appserver/static/js/controllers/settings/api/api.html index 395cb86b1..0f4aebc19 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/settings/api/api.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/settings/api/api.html @@ -1,9 +1,100 @@
+
+ + + + + + Welcome to + the + Wazuh app for Splunk + +
+ Wazuh Splunk plugin provides management and monitoring capabilities, giving users control + over the Wazuh infrastructure. Using this plugin you can monitor your agents status and + configuration, query and visualize your alert data and monitor manager rules and + configuration. +
+
+
+ + + + + + Community + +
+ Enjoy your Wazuh experience and please don't hesitate to give us your feedback. +
+ + +
+
+
+
- API configuration + Wazuh API configuration Use Wazuh API settings to connect the Splunk app to your Wazuh manager or cluster
@@ -28,37 +119,47 @@

- {{ (entry.filterType === 'cluster.name') ? entry.filterName : 'Disabled'}} - - This is the default Manager - -

+ + {{ (entry.filterType === 'cluster.name') ? entry.filterName : 'Disabled'}} + + This is the default Manager + +

{{entry.managerName}}

{{entry.url}}

{{entry.portapi}}

{{entry.userapi}}

- - - - +

@@ -67,44 +168,54 @@
- - Add new Wazuh API entry - +
-
+
- + - + - + - +

{{messageError}}

-
- - Save Wazuh API entry - - - Update Wazuh API entry - +
+
+
    +
  • {{ err }}
  • +
+
+
+ + +
diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/settings/api/settingsApiCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/settings/api/settingsApiCtrl.js index 9ca7dadea..fd5e325db 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/settings/api/settingsApiCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/settings/api/settingsApiCtrl.js @@ -25,7 +25,7 @@ define(['../../module'], function(controllers) { this.portRegEx = new RegExp(/^[0-9]{2,5}$/) this.apiList = apiList this.currentDataService = $currentDataService - this.toast = $notificationService.showSimpleToast + this.notification = $notificationService this.savingApi = false } @@ -54,16 +54,18 @@ define(['../../module'], function(controllers) { this.currentDataService.removeCurrentApi() this.scope.$emit('updatedAPI', () => {}) } - - this.scope.apiList = this.apiList - + // Get the current selected API let currentApi = this.currentDataService.getApi() - + // If there is API, then show it as selected + if (currentApi) { + this.setYellowStar(currentApi['_key']) + } + this.scope.apiList = this.apiList if (!currentApi && Array.isArray(this.scope.apiList)) { for (const apiEntry of this.scope.apiList) { try { - await this.selectManager(apiEntry.id) - // setAPI + await this.selectManager(apiEntry['_key']) + // Set API currentApi = this.currentDataService.getApi() break } catch (error) { @@ -71,20 +73,8 @@ define(['../../module'], function(controllers) { } } } - - this.scope.apiList.map(item => { - delete item.selected - }) - - if (currentApi) { - this.scope.apiList.map(item => { - if (item.id === currentApi.id) { - item.selected = true - } - }) - } } catch (err) { - this.toast('Error loading data') + this.notification.showErrorToast('Error loading data') } } @@ -96,12 +86,19 @@ define(['../../module'], function(controllers) { try { const index = this.scope.apiList.indexOf(entry) if (index > -1) { - this.scope.apiList.splice(index, 1) await this.currentDataService.remove(entry) + const usedApi = this.currentDataService.getApi() + if (entry._key === usedApi._key) { + this.currentDataService.removeCurrentApi() + } + this.scope.apiList.splice(index, 1) + this.notification.showSuccessToast('Manager was removed') + this.scope.$emit('updatedAPI', () => {}) } - this.toast('Manager was removed') } catch (err) { - this.toast('Cannot remove API:', err.message || err) + this.notification.showErrorToast( + `Cannot remove API: ${err.message || err}` + ) } } @@ -112,19 +109,19 @@ define(['../../module'], function(controllers) { async checkManager(entry) { try { const connectionData = await this.currentDataService.checkApiConnection( - entry.id + entry._key ) for (let i = 0; i < this.scope.apiList.length; i++) { - if (this.scope.apiList[i].id === entry.id) { + if (this.scope.apiList[i]._key === entry._key) { this.scope.apiList[i] = connectionData this.scope.apiList[i].selected = entry.selected // Check if the API was selected, if it was, set the yellow star break } } - this.toast('Established connection') + this.notification.showSuccessToast('Connection established') if (!this.scope.$$phase) this.scope.$digest() } catch (err) { - this.toast('Unreachable API') + this.notification.showErrorToast('Unreachable API') } } @@ -144,7 +141,7 @@ define(['../../module'], function(controllers) { try { this.scope.edit = !this.scope.edit this.scope.showForm = false - this.scope.currentEntryKey = entry.id + this.scope.currentEntryKey = entry['_key'] this.scope.url = entry.url this.scope.pass = entry.pass this.scope.port = entry.portapi @@ -154,7 +151,7 @@ define(['../../module'], function(controllers) { this.scope.filterName = entry.filterName this.scope.entry.url = entry } catch (err) { - this.toast('Could not open API form') + this.notification.showErrorToast('Could not open API form') } } @@ -165,7 +162,7 @@ define(['../../module'], function(controllers) { async updateEntry() { try { if (this.savingApi) { - this.toast('Please, wait for success message') + this.notification.showWarningToast('Please, wait for success message') return } this.savingApi = true @@ -178,17 +175,17 @@ define(['../../module'], function(controllers) { this.scope.entry.filterType = this.scope.filterType this.scope.entry.filterName = this.scope.filterName this.scope.entry.managerName = this.scope.managerName - this.scope.entry.id = this.scope.currentEntryKey + this.scope.entry['_key'] = this.scope.currentEntryKey delete this.scope.entry['$$hashKey'] await this.currentDataService.checkRawConnection(this.scope.entry) await this.currentDataService.update(this.scope.entry) const updatedApi = await this.currentDataService.checkApiConnection( - this.scope.entry.id + this.scope.entry['_key'] ) for (let i = 0; i < this.scope.apiList.length; i++) { - if (this.scope.apiList[i].id === updatedApi.id) { + if (this.scope.apiList[i]['_key'] === updatedApi['_key']) { this.scope.apiList[i] = updatedApi } } @@ -196,46 +193,35 @@ define(['../../module'], function(controllers) { if ( this.currentDataService.getApi() && - this.currentDataService.getApi().id === this.scope.entry.id + this.currentDataService.getApi()['_key'] === this.scope.entry['_key'] ) { - this.selectManager(updatedApi.id) + this.selectManager(updatedApi['_key']) } this.scope.edit = false - this.toast('Updated API') + this.notification.showSuccessToast('Updated API') } catch (err) { - this.toast('Cannot update API:', err.message || err) + this.notification.showErrorToast('Cannot update API') } this.savingApi = false } /** * Select an API as the default one - * @param {Object} entry + * @param {String} key */ - async selectManager(entry) { + async selectManager(key) { try { - const connectionData = await this.currentDataService.checkApiConnection( - entry - ) - await this.currentDataService.chose(entry) - this.scope.apiList.map(api => (api.selected = false)) - for (let item of this.scope.apiList) { - if (item.id === entry) { - if (connectionData.cluster) { - item.cluster = connectionData.cluster - } else { - item.cluster = 'Disabled' - } - item.managerName = connectionData.managerName - item.selected = true - } - } - this.toast('API selected') + // checking if the api is up + await this.currentDataService.checkApiConnection(key) + // Selecting API + await this.currentDataService.chose(key) + this.setYellowStar(key) + this.notification.showSuccessToast('API selected') this.scope.$emit('updatedAPI', () => {}) if (!this.scope.$$phase) this.scope.$digest() } catch (err) { - this.toast('Could not select manager') + this.notification.showErrorToast('Could not select manager') } } @@ -244,11 +230,13 @@ define(['../../module'], function(controllers) { */ async submitApiForm() { try { + this.scope.validatingError = [] if (this.savingApi) { - this.toast('Please, wait for success message') + this.notification.showWarningToast('Please, wait for success message') return } this.savingApi = true + // When the Submit button is clicked, get all the form fields by accessing to the input values const form_url = this.scope.url const form_apiport = this.scope.port @@ -274,38 +262,24 @@ define(['../../module'], function(controllers) { } // If connected to the API then continue - await this.currentDataService.checkRawConnection(record) + const api = await this.currentDataService.addApi(record) - // Get the new API database ID - const { result } = await this.currentDataService.insert(record) - const id = result - try { - // Get the full API info - const api = await this.currentDataService.checkApiConnection(id) - // Empties the form fields - this.clearForm() + // Empties the form fields + this.clearForm() - // If the only one API in the list, then try to select it - this.scope.apiList.push(api) - if (this.scope.apiList && this.scope.apiList.length === 1) { - await this.selectManager(id) - } - this.scope.showForm = false - if (!this.scope.$$phase) this.scope.$digest() - this.toast('API was added') - } catch (err) { - this.currentDataService - .remove(id) - .then(() => {}) - .catch(err => { - this.toast(`Unexpected error: ${err}`) - }) - this.toast('Unreachable API') - this.savingApi = false + // Push to te API list + this.scope.apiList.push(api) + + // If the only one API in the list, then try to select it + if (this.scope.apiList.length === 1) { + this.selectManager(api['_key']) } + + this.scope.showForm = false + if (!this.scope.$$phase) this.scope.$digest() + this.notification.showSuccessToast('New API was added') } catch (err) { - this.toast(err.message) - this.savingApi = false + this.notification.showErrorToast(err.message) } this.savingApi = false } @@ -315,7 +289,12 @@ define(['../../module'], function(controllers) { * @param {String} url */ validUrl(url) { - return this.urlRegEx.test(url) || this.urlRegExIP.test(url) + if (this.urlRegEx.test(url) || this.urlRegExIP.test(url)) { + return true + } else { + this.scope.validatingError.push('Invalid url format') + return false + } } /** @@ -323,7 +302,12 @@ define(['../../module'], function(controllers) { * @param {String} port */ validPort(port) { - return this.portRegEx.test(port) + if (this.portRegEx.test(port)) { + return true + } else { + this.scope.validatingError.push('Invalid port format') + return false + } } /** @@ -331,7 +315,12 @@ define(['../../module'], function(controllers) { * @param {String} user */ validUsername(user) { - return this.userRegEx.test(user) + if (this.userRegEx.test(user)) { + return true + } else { + this.scope.validatingError.push('Invalid username format, it must have a length between 3 and 100 characters.') + return false + } } /** @@ -339,7 +328,12 @@ define(['../../module'], function(controllers) { * @param {String} pass */ validPassword(pass) { - return this.passRegEx.test(pass) + if (this.passRegEx.test(pass)) { + return true + } else { + this.scope.validatingError.push('Invalid password format, it must have a length between 3 and 100 characters.') + return false + } } /** @@ -351,6 +345,12 @@ define(['../../module'], function(controllers) { this.scope.user = '' this.scope.pass = '' } + + setYellowStar(key) { + this.apiList.map(api => { + api['_key'] === key ? (api.selected = true) : (api.selected = false) + }) + } } controllers.controller('settingsApiCtrl', SettingsApi) }) diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/settings/extensions/extensions.html b/SplunkAppForWazuh/appserver/static/js/controllers/settings/extensions/extensions.html index d2eef4f89..0b313d9dc 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/settings/extensions/extensions.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/settings/extensions/extensions.html @@ -1,179 +1,254 @@
- +
Wazuh extensions - A Wazuh extension is used to enable visualizations and dashboards that are specific to a particular use case. + A Wazuh extension is used to enable visualizations and dashboards that are specific to a + particular use case.
- +
- + PCI DSS
-

The Payment Card Industry Data Security Standard (PCI DSS) is a proprietary information security standard for organizations that handle branded credit cards from the major card schemes including Visa, MasterCard, American Express, Discover, and JCB.

-

The PCI Standard is mandated by the card brands and administered by the Payment Card Industry Security Standards Council. The standard was created to increase controls around cardholder data to reduce credit card fraud.

+

The Payment Card Industry Data Security Standard (PCI DSS) is a + proprietary information security standard for organizations that handle branded credit cards from the major + card schemes including Visa, MasterCard, American Express, Discover, and JCB.

+

The PCI Standard is mandated by the card brands and administered by + the Payment Card Industry Security Standards Council. The standard was created to increase controls around + cardholder data to reduce credit card fraud.

- +
- + More info
- + GDPR
-

The General Data Protection Regulation (GDPR) is a regulation in EU law on data protection and privacy for all individuals within the European Union. It also addresses the export of personal data outside the EU.

-

The GDPR aims primarily to give control to citizens and residents over their personal data and to simplify the regulatory environment for international business by unifying the regulation within the EU.

+

The General Data Protection Regulation (GDPR) is a regulation in EU + law on data protection and privacy for all individuals within the European Union. It also addresses the + export of personal data outside the EU.

+

The GDPR aims primarily to give control to citizens and residents over + their personal data and to simplify the regulatory environment for international business by unifying the + regulation within the EU.

- +
- + More info
- + System auditing
-

The Linux Audit system provides a way to track security-relevant information on your system.

-

Based on pre-configured rules, Audit generates log entries to record as much information about the events that are happening on your system as possible.

+

The Linux Audit system provides a way to track security-relevant + information on your system.

+

Based on pre-configured rules, Audit generates log entries to record + as much information about the events that are happening on your system as possible.

- +
- + More info
- + OpenSCAP
-

OpenSCAP is an OVAL (Open Vulnerability Assessment Language) interpreter, that is used for system configuration and vulnerability assessment.

-

Developed and supported by RedHat, it is recognized as a standardized compliance and hardening checking solution for enterprise-level infrastructure.

+

OpenSCAP is an OVAL (Open Vulnerability Assessment Language) + interpreter, that is used for system configuration and vulnerability assessment.

+

Developed and supported by RedHat, it is recognized as a standardized + compliance and hardening checking solution for enterprise-level infrastructure.

- +
- + More info
- + CIS-CAT
-

CIS (Center for Internet Security) is an entity dedicated to safeguard private and public organizations against cyber threats. This entity provides CIS benchmarks guidelines, which are a recognized global standard and best practices for securing IT systems and data against cyberattacks.

+

CIS (Center for Internet Security) is an entity dedicated to safeguard + private and public organizations against cyber threats. This entity provides CIS benchmarks guidelines, + which are a recognized global standard and best practices for securing IT systems and data against + cyberattacks.

- +
- + More info
- + Osquery
-

Osquery can be used to expose an operating system as a high-performance relational database. This allows you to write SQL-based queries to explore operating system data.

+

Osquery can be used to expose an operating system as a + high-performance relational database. This allows you to write SQL-based queries to explore operating + system data.

- +
- + More info
- + Amazon AWS
-

Wazuh provides an agent module that can be used to retrieve data from S3 buckets. In combination with log analysis rules, this module provides the ability to analyze and alert on AWS Cloudtrail, GuardDuty, Macie, IAM, VPC Flow and other Amazon AWS services data.

+

Wazuh provides an agent module that can be used to retrieve data from + S3 buckets. In combination with log analysis rules, this module provides the ability to analyze and alert + on AWS Cloudtrail, GuardDuty, Macie, IAM, VPC Flow and other Amazon AWS services data.

- +
- + More info
- + VirusTotal
-

VirusTotal is an online service that analyzes files and URLs enabling the identification of viruses, worms, trojans, and other kinds of malicious content detected by antivirus engines and website scanners. Virustotal is commonly used as a threat intelligence source to help with security analysis and incident response.

+

VirusTotal is an online service that analyzes files and URLs enabling + the identification of viruses, worms, trojans, and other kinds of malicious content detected by antivirus + engines and website scanners. Virustotal is commonly used as a threat intelligence source to help with + security analysis and incident response.

- +
- + More info
+ + + + + Docker listener + +
+

Collects events on Docker containers such as starting, stopping or pausing.

+
+ +
+ +
+
+ + + More info + + +
+ + + +
- -
+ +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/settings/extensions/extensionsCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/settings/extensions/extensionsCtrl.js index 59e2701c7..cfc81cf22 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/settings/extensions/extensionsCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/settings/extensions/extensionsCtrl.js @@ -5,8 +5,7 @@ define(['../../module'], function(controllers) { constructor($scope, $currentDataService, $notificationService, extensions) { this.scope = $scope this.scope.extensions = {} - this.toast = $notificationService.showSimpleToast - this.setExtensions = $currentDataService.setExtensions + this.notification = $notificationService this.currentApi = $currentDataService.getApi() this.getExtensions = $currentDataService.getExtensions this.setExtensions = $currentDataService.setExtensions @@ -14,7 +13,7 @@ define(['../../module'], function(controllers) { } $onInit() { - const id = this.currentApi.id + const id = this.currentApi['_key'] this.scope.toggleExtension = (extension, state) => this.toggleExtension(extension, state) this.currentExtensions = this.extensions.data || this.extensions @@ -30,12 +29,12 @@ define(['../../module'], function(controllers) { toggleExtension(extension, state) { try { - const api = this.currentApi.id + const api = this.currentApi['_key'] this.currentExtensions[extension] = state.toString() this.setExtensions(api, this.currentExtensions) if (!this.scope.$$phase) this.scope.$digest() } catch (error) { - this.toast(error) + this.notification.showErrorToast(error) } } } diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/settings/index/index.html b/SplunkAppForWazuh/appserver/static/js/controllers/settings/index/index.html index 96bdef122..1ee998013 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/settings/index/index.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/settings/index/index.html @@ -1,12 +1,24 @@
- - - - Chose an index, so Wazuh can use it to retrieve data from indices for queries and visualizations. - -
-
-
-
-
+
+ + + + +  Index + + Choose and index , so Wazuh can use it to retrieve data from indices for + queries and visualizations. + + +
+

Note: The chosen index will contain the data to feed the APP..

+
+
+
+
+
+
+
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/settings/index/settingsIndexCtrl.js b/SplunkAppForWazuh/appserver/static/js/controllers/settings/index/settingsIndexCtrl.js index ec4852962..473cbdef9 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/settings/index/settingsIndexCtrl.js +++ b/SplunkAppForWazuh/appserver/static/js/controllers/settings/index/settingsIndexCtrl.js @@ -10,10 +10,16 @@ define([ * @param {Object} $urlTokenModel */ - constructor($scope, $currentDataService, $urlTokenModel) { + constructor( + $scope, + $currentDataService, + $urlTokenModel, + $notificationService + ) { this.scope = $scope - this.$currentDataService = $currentDataService + this.currentDataService = $currentDataService this.urlTokenModel = $urlTokenModel + this.notification = $notificationService this.dropdown = new Dropdown( 'inputIndexes', @@ -34,8 +40,15 @@ define([ $onInit() { this.dropdownInstance = this.dropdown.getElement() this.dropdownInstance.on('change', newValue => { - if (newValue && this.dropdownInstance) - this.urlTokenModel.handleValueChange(this.dropdownInstance) + try { + if (newValue && this.dropdownInstance) { + this.currentDataService.setIndex(newValue) + this.scope.$emit('updatedAPI', {}) + this.urlTokenModel.handleValueChange(this.dropdownInstance) + } + } catch (error) { + this.notification.showErrorToast(error) + } }) this.scope.$on('$destroy', () => { diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/settings/logs/logs.html b/SplunkAppForWazuh/appserver/static/js/controllers/settings/logs/logs.html index e167a276a..6ccc2ddb0 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/settings/logs/logs.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/settings/logs/logs.html @@ -2,11 +2,11 @@
Wazuh Splunk plugin log messages - Log file located at /opt/splunk/var/log/splunk/SplunkAppForWazuh.log + Log file located at /opt/splunk/var/log/splunk/SplunkAppForWazuh.log
- Refresh + Refresh
diff --git a/SplunkAppForWazuh/appserver/static/js/controllers/settings/main/settings.html b/SplunkAppForWazuh/appserver/static/js/controllers/settings/main/settings.html index fc4ac64c6..7c909215f 100644 --- a/SplunkAppForWazuh/appserver/static/js/controllers/settings/main/settings.html +++ b/SplunkAppForWazuh/appserver/static/js/controllers/settings/main/settings.html @@ -1,10 +1,10 @@
- - - +
@@ -12,8 +12,8 @@ API Extensions Index - About Logs + About
diff --git a/SplunkAppForWazuh/appserver/static/js/directives/index.js b/SplunkAppForWazuh/appserver/static/js/directives/index.js index a73a1d741..9b668850b 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/index.js +++ b/SplunkAppForWazuh/appserver/static/js/directives/index.js @@ -11,5 +11,11 @@ define([ './wz-tag-filter/wz-tag-filter', './wz-data-table/wz-data-table', './wz-xml-file-editor/wz-xml-file-editor', - './wz-multiple-selector/wz-multiple-selector' + './wz-multiple-selector/wz-multiple-selector', + './wz-config-viewer/wz-config-viewer', + './wz-discover/wz-discover', + './wz-svg/wz-svg', + './wz-add-filter-chip/wz-add-filter-chip', + './wz-head-toaster/wz-head-toaster', + './wz-kbn-switch/wz-kbn-switch' ], function() {}) diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-add-filter-chip/wz-add-filter-chip.html b/SplunkAppForWazuh/appserver/static/js/directives/wz-add-filter-chip/wz-add-filter-chip.html new file mode 100644 index 000000000..8e527c8fe --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-add-filter-chip/wz-add-filter-chip.html @@ -0,0 +1,15 @@ +
+ +
+
+ +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-add-filter-chip/wz-add-filter-chip.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-add-filter-chip/wz-add-filter-chip.js new file mode 100644 index 000000000..fab8c22d8 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-add-filter-chip/wz-add-filter-chip.js @@ -0,0 +1,36 @@ +/* + * Wazuh app - Wazuh no configuration card directive + * Copyright (C) 2015-2019 Wazuh, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Find more information about this on the LICENSE file. + */ + +define(['../module'], function(directives) { + 'use strict' + directives.directive('wzAddFilterChip', function(BASE_URL) { + return { + restrict: 'E', + scope: { + idInput: '@', + options: '=' + }, + controller($scope) { + $scope.showDropdown = false + $scope.select = chip => { + $scope.showDropdown = false + const searchBar = $(`#${$scope.idInput}`) + searchBar.val(`${chip.value}: `) + searchBar.focus() + } + }, + templateUrl: + BASE_URL + + '/static/app/SplunkAppForWazuh/js/directives/wz-add-filter-chip/wz-add-filter-chip.html' + } + }) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-bar/wz-bar.html b/SplunkAppForWazuh/appserver/static/js/directives/wz-bar/wz-bar.html index b481defc0..5c089cd0a 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-bar/wz-bar.html +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-bar/wz-bar.html @@ -7,9 +7,23 @@
- - {{ $chip }} - + + + {{ $chip }} + + + + {{ $chip }} + + \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-bar/wz-bar.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-bar/wz-bar.js index f40a90d90..73b757d2e 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-bar/wz-bar.js +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-bar/wz-bar.js @@ -25,7 +25,10 @@ define(['../module'], function(directives) { if (uglyFilters && uglyFilters.length > 0) { for (const filter of uglyFilters) { const key = Object.keys(filter)[0] - prettyFilters.push(`${key}:${filter[key]}`) + const cleanKey = key.replace('{}', '') + if (key !== 'index') { + prettyFilters.push(`${cleanKey}:${filter[key]}`) + } } } return prettyFilters @@ -38,15 +41,24 @@ define(['../module'], function(directives) { * @param {String} filter * @returns {Boolean} */ - $scope.filterStatic = filter => { + function filterStatic(filter) { + let keyStatic = false const key = filter.split(':')[0] const staticTrue = $currentDataService .getFilters() .filter(item => !!item.implicit) - const isIncluded = staticTrue.filter( - item => typeof item[key] !== 'undefined' + staticTrue.map( + item => { + let k = Object.keys(item)[0] + if (k.endsWith('{}')) { + k = k.substring(0, k.length - 2) + } + if (k === key) { + keyStatic = item['implicit'] + } + } ) - return !!isIncluded.length + return keyStatic } /** @@ -84,7 +96,66 @@ define(['../module'], function(directives) { $scope.$emit('barFilter', {}) if (!$scope.$$phase) $scope.$digest() } catch (err) { - $notificationService.showSimpleToast(err.message || err) + $notificationService.showErrorToast(err.message || err) + } + } + + /** + * Change chip showing pin and trash icons + * @param {Object | String} chip + */ + $scope.editChip = chip => { + const chipIsStatic = filterStatic(chip) + if (!chipIsStatic) { + $scope.editingChip = chip + } + } + + /** + * Cancel edition mode + * @param {Object | String} chip + */ + $scope.finishChipEdition = () => { + $scope.editingChip = false + } + + /** + * Check if the filter is pined + * @param {Object | String} chip + */ + function filterPined(filter) { + const key = filter.split(':')[0] + const staticTrue = $currentDataService + .getFilters() + .filter(item => !!item.pined) + const isIncluded = staticTrue.filter( + item => typeof item[key] !== 'undefined' + ) + return !!isIncluded.length + } + $scope.filterPined = chip => filterPined(chip) + + /** + * Pin the filter + * @param {Object | String} chip + */ + $scope.pinFilter = filter => { + try { + const key = filter.split(':')[0] + const value = filter.split(':')[1] + if (filterPined(filter)) { + $currentDataService.pinFilter( + `{"${key}":"${value}", "pined":true}` + ) + } else { + $currentDataService.pinFilter( + `{"${key}":"${value}", "pined":false}` + ) + } + $scope.filters = getPrettyFilters() + if (!$scope.$$phase) $scope.$digest() + } catch (err) { + $notificationService.showErrorToast(err.message || err) } } }, diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-config-item/wz-config-item.html b/SplunkAppForWazuh/appserver/static/js/directives/wz-config-item/wz-config-item.html index efd2b8599..8a764c050 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-config-item/wz-config-item.html +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-config-item/wz-config-item.html @@ -1,12 +1,12 @@
-
+
{{ label }}
{{ value }}
-
    +
    • {{ item }}
diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-config-viewer/wz-config-viewer.html b/SplunkAppForWazuh/appserver/static/js/directives/wz-config-viewer/wz-config-viewer.html new file mode 100644 index 000000000..a4138e0c1 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-config-viewer/wz-config-viewer.html @@ -0,0 +1,55 @@ +
+ + + +
+
+ JSON viewer +
+ View this configuration in raw JSON format +
+
+ + JSON +  ·  + XML +
+ + + +
+ +
+ +
+
+ + + + + +
+
+ XML viewer +
+ View this configuration in raw XML format +
+
+ + JSON +  ·  + XML +
+ +
+ Viewing {{noLocal}} file +
+ +
+ +
+ +
+
+ +
\ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-config-viewer/wz-config-viewer.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-config-viewer/wz-config-viewer.js new file mode 100644 index 000000000..a23d34aec --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-config-viewer/wz-config-viewer.js @@ -0,0 +1,137 @@ +/* + * Wazuh app - Wazuh config viewer directive + * Copyright (C) 2018 Wazuh, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Find more information about this on the LICENSE file. + */ +define(['../module', '../../libs/codemirror-conv/lib/codemirror'], function( + app, + CodeMirror +) { + 'use strict' + class WzConfigViewer { + /** + * Class constructor + */ + constructor(BASE_URL) { + this.restrict = 'E' + this.scope = { + getjson: '&', + getxml: '&', + jsoncontent: '=', + xmlcontent: '=', + hideHeader: '=', + noLocal: '=' + } + this.templateUrl = + BASE_URL + + '/static/app/SplunkAppForWazuh/js/directives/wz-config-viewer/wz-config-viewer.html' + } + + controller($scope, $document) { + const setJsonBox = () => { + $scope.jsonCodeBox = CodeMirror.fromTextArea( + $document[0].getElementById('viewer_json_box'), + { + lineNumbers: true, + autoRefresh: true, + matchClosing: true, + matchBrackets: true, + mode: { name: 'javascript', json: true }, + readOnly: true, + theme: 'ttcn', + foldGutter: true, + styleSelectedText: true, + gutters: ['CodeMirror-foldgutter'] + } + ) + } + + const setXmlBox = () => { + $scope.xmlCodeBox = CodeMirror.fromTextArea( + $document[0].getElementById('viewer_xml_box'), + { + lineNumbers: true, + autoRefresh: true, + lineWrapping: true, + matchClosing: true, + matchBrackets: true, + mode: 'text/xml', + readOnly: true, + theme: 'ttcn', + foldGutter: true, + styleSelectedText: true, + gutters: ['CodeMirror-foldgutter'] + } + ) + bindXmlListener() + } + + const bindXmlListener = () => { + const scrollElement = $scope.xmlCodeBox.getScrollerElement() + $(scrollElement).bind('scroll', function(e) { + var element = $(e.currentTarget)[0] + if ( + element.scrollHeight - element.scrollTop === + element.clientHeight + ) { + $scope.$emit('scrolledToBottom', { + lines: $scope.xmlCodeBox.lineCount() + }) + } + }) + } + + const init = () => {} + + const refreshJsonBox = json => { + $scope.jsoncontent = json + if (!$scope.jsonCodeBox) { + setJsonBox() + } + if ($scope.jsoncontent != false) { + $scope.jsonCodeBox.setValue($scope.jsoncontent.replace(/\\\\/g, '\\')) + setTimeout(function() { + $scope.jsonCodeBox.refresh() + $scope.$applyAsync() + }, 300) + } + } + + const refreshXmlBox = xml => { + $scope.xmlcontent = xml + if (!$scope.xmlCodeBox) { + setXmlBox() + } + if ($scope.xmlcontent != false) { + $scope.xmlCodeBox.setValue($scope.xmlcontent) + setTimeout(function() { + $scope.xmlCodeBox.refresh() + $scope.$applyAsync() + }, 300) + } + } + + $scope.callgetjson = () => $scope.getjson() + + $scope.callgetxml = () => $scope.getxml() + + $scope.$on('JSONContentReady', (ev, params) => { + refreshJsonBox(params.data) + }) + + $scope.$on('XMLContentReady', (ev, params) => { + refreshXmlBox(params.data) + }) + + init() + } + } + + app.directive('wzConfigViewer', BASE_URL => new WzConfigViewer(BASE_URL)) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-data-table/wz-data-table.html b/SplunkAppForWazuh/appserver/static/js/directives/wz-data-table/wz-data-table.html index 0b23f1eb5..ce9678138 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-data-table/wz-data-table.html +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-data-table/wz-data-table.html @@ -1,10 +1,12 @@
-
-
-
+ +
- + +
@@ -28,17 +30,17 @@
{{ totalItems }} items - - \ No newline at end of file + \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-menu/wz-menu.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-menu/wz-menu.js index 08caecd62..0763e8c6a 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-menu/wz-menu.js +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-menu/wz-menu.js @@ -28,16 +28,23 @@ define(['../module'], function(directives) { if (!$scope.$$phase) $scope.$digest() } - $scope.dumpHtml = item => { - $scope.menuNavItem = item + $scope.openDiscover = agentId => { + $scope.menuNavItem = 'discover' $scope.$broadcast('stateChanged', 'discover') if (!$scope.$$phase) $scope.$digest() + const index = $currentDataService.getIndex().index || 'wazuh' //Generate url - let filters = $currentDataService.getSerializedFilters() - let url = `${BASE_URL}/app/search/search?q=${filters}` + let url = `${BASE_URL}/app/search/search?q=index=${index}` + url = agentId ? `${url} agent.id=${agentId}` : url localStorage.setItem('urlDiscover', url) - $state.go('discover') + $state.go('discover', { fromDashboard: false }) } + + $scope.$on('openDiscover', (event, data) => { + event.stopPropagation() + $scope.openDiscover(data) + }) + const checkLastState = (prefix, state) => { if ( ($navigationService.getLastState() && @@ -52,12 +59,10 @@ define(['../module'], function(directives) { } const update = () => { - $scope.currentIndex = !$currentDataService.getIndex() - ? 'wazuh' - : $currentDataService.getIndex().index - $scope.currentAPI = !$currentDataService.getApi() - ? '---' - : $currentDataService.getApi().managerName + const index = $currentDataService.getIndex() + const api = $currentDataService.getApi() + $scope.currentIndex = !index ? 'wazuh' : index.index + $scope.currentAPI = !api ? '---' : api.managerName $scope.theresAPI = $scope.currentAPI === '---' ? false : true if (checkLastState('ow-', 'overview')) { @@ -73,11 +78,11 @@ define(['../module'], function(directives) { } else if (checkLastState('discover', 'discover')) { $scope.menuNavItem = 'discover' } - //else if ($navigationService.getLastState() && $navigationService.getLastState() !== '' && $navigationService.getLastState().includes('dev-tools')) { $scope.menuNavItem = 'dev-tools' } if (!$scope.$$phase) $scope.$digest() } // Listens for changes in the selected API - $scope.$on('updatedAPI', () => { + $scope.$on('updatedAPI', event => { + event.stopPropagation() update() }) diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-multiple-selector/wz-multiple-selector.html b/SplunkAppForWazuh/appserver/static/js/directives/wz-multiple-selector/wz-multiple-selector.html index 1b26833dc..d4f616053 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-multiple-selector/wz-multiple-selector.html +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-multiple-selector/wz-multiple-selector.html @@ -1,55 +1,60 @@
-
-
-
+ +
+
+
-
+
{{titleAvailableItems}}
-
+ class='pull-right cursor-pointer'> + +
+
-
-
+
- - - -
+
-
+
{{titleSelectedItems}} ({{totalSelectedItems}})
-
+
- diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-no-config/wz-no-config.html b/SplunkAppForWazuh/appserver/static/js/directives/wz-no-config/wz-no-config.html index c1f634599..46630d49f 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-no-config/wz-no-config.html +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-no-config/wz-no-config.html @@ -10,11 +10,7 @@

There was a problem while fetching the configuration for this section.

-

Check the links on the right sidebar to learn more about how to configure it.

- {{ error }} -
-
-

Click on the icon on the top right corner to send feedback or ask for help.

+

Click on the icon to open the right sidebar and learn more about how to configure it.

diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-svg/wz-svg.html b/SplunkAppForWazuh/appserver/static/js/directives/wz-svg/wz-svg.html new file mode 100644 index 000000000..2828be5c2 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-svg/wz-svg.html @@ -0,0 +1,232 @@ +
+ + + + {{svgTooltip}} + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + {{svgTooltip}} + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-svg/wz-svg.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-svg/wz-svg.js new file mode 100644 index 000000000..5df6509aa --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-svg/wz-svg.js @@ -0,0 +1,29 @@ +/* + * Wazuh app - Wazuh no configuration card directive + * Copyright (C) 2015-2019 Wazuh, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Find more information about this on the LICENSE file. + */ + +define(['../module'], function (directives) { + 'use strict' + directives.directive('wzSvg', function (BASE_URL) { + return { + restrict: 'E', + scope: { + icon: '@', + color: '@', + svgTooltip: '@' + }, + controller(){}, + templateUrl: + BASE_URL + + '/static/app/SplunkAppForWazuh/js/directives/wz-svg/wz-svg.html' + } + }) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/click-action.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/click-action.js index ebdcf549a..9f0f9f0d8 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/click-action.js +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/click-action.js @@ -49,8 +49,10 @@ define([], function() { }) } else if (instance.path === '/rules') { $state.go('mg-rules-id', { id: item.id }) - } else if (instance.path.includes('/decoders')) { + } else if (instance.path === '/decoders') { $state.go('mg-decoders-id', { file: item.file, name: item.name }) + } else if (instance.path === '/lists/files') { + $state.go('mg-cdb-id', { name: item.name, path: item.path }) } else if (instance.path === '/cluster/nodes') { $scope.$emit('wazuhShowClusterNode', { node: item }) } diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/data.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/data.js index aa81da6a3..5e125203d 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/data.js +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/data.js @@ -32,7 +32,7 @@ define([], function() { } catch (error) { $scope.wazuhTableLoading = false $scope.error = `Error searching - ${error.message || error}.` - $notificationService.showSimpleToast( + $notificationService.showErrorToast( `Error searching. ${error.message || error}` ) } @@ -79,7 +79,7 @@ define([], function() { $scope.error = `Error filtering by ${ filter ? filter.value : 'undefined' }. ${error.message || error}.` - $notificationService.showSimpleToast( + $notificationService.showErrorToast( `Error filtering by ${ filter ? filter.value : 'undefined' }. ${error.message || error}` @@ -116,7 +116,7 @@ define([], function() { $scope.error = `Query error ${ query ? query.value : 'undefined' } - ${error.message || error}.` - errorHandler.showSimpleToast( + errorHandler.showErrorToast( `Query error ${query ? query.value : 'undefined'}. ${error.message || error}` ) diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/init.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/init.js index 68e3ab43f..e5a54c38f 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/init.js +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/init.js @@ -55,7 +55,7 @@ define(['../../../utils/filter-handler'], function(FilterHandler) { $scope.wazuhTableLoading = false } catch (error) { $scope.wazuhTableLoading = false - $scope.error = `Error while init table - ${error.message || error}.` + $scope.error = `Error while init table.` errorHandler.showSimpleToast( `Error while init table. ${error.message || error}` ) diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/pagination.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/pagination.js index aacddf2ec..cee0e7f14 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/pagination.js +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/pagination.js @@ -12,7 +12,7 @@ define([], function() { 'use strict' return { - nextPage: async (currentPage, $scope, errorHandler, fetch) => { + nextPage: async (currentPage, $scope, errorHandler, fetch, last) => { try { $scope.error = false if ( @@ -23,15 +23,24 @@ define([], function() { $scope.currentPage++ } if ( - $scope.pagedItems[currentPage || $scope.currentPage].includes(null) + ($scope.pagedItems[currentPage || $scope.currentPage] || []).includes( + null + ) ) { const copy = $scope.currentPage $scope.wazuhTableLoading = true - const currentNonNull = $scope.items.filter(item => !!item) - await fetch({ offset: currentNonNull.length }) + let currentNonNull = $scope.items.filter(item => !!item) + if (!last) { + await fetch({ offset: currentNonNull.length }) + } else { + while (currentNonNull.length < $scope.items.length) { + await fetch({ offset: currentNonNull.length }) + currentNonNull = $scope.items.filter(item => !!item) + } + } $scope.wazuhTableLoading = false $scope.currentPage = copy - if (!$scope.$$phase) $scope.$digest() + $scope.$applyAsync() } } catch (error) { $scope.wazuhTableLoading = false diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/parse-value.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/parse-value.js index 7eb6ba15c..609d30759 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/parse-value.js +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/lib/parse-value.js @@ -42,7 +42,46 @@ define([], function() { * @param {String} item * @param {String} instancePath */ - return function parseValue(ProcessEquivalence, key, item, instancePath) { + return function parseValue( + ProcessEquivalence, + key, + item, + instancePath, + $sce = null, + dateDiffService = null + ) { + if ( + (key === 'event' || (key.value && key.value === 'event')) && + instancePath.includes('rootcheck') && + $sce + ) { + if (typeof (item || {}).event === 'string') { + const urlRegex = new RegExp( + /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/, + 'g' + ) + + const matched = item.event.match(urlRegex) + if (matched) { + item.event = item.event.replace( + matched, + `${matched}` + ) + item.event = $sce.trustAsHtml(item.event) + } + } + } + + if (key.offset && dateDiffService) { + const date = (item || {})[key.value]; + if (!item[`${key.value}offset`]) { + item[`${key.value}offset`] = date; + } + if (date) { + item[key.value] = dateDiffService.setBrowserOffset(item[`${key.value}offset`]); + } + } + if (key === 'state' && instancePath.includes('processes')) { return ProcessEquivalence[item.state] || 'Unknown' } diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/wz-table-directive.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/wz-table-directive.js index 9eaa792e8..e2ad5417e 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/wz-table-directive.js +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/wz-table-directive.js @@ -29,7 +29,8 @@ define([ './lib/listeners', './lib/data', './lib/click-action', - './lib/check-gap' + './lib/check-gap', + 'JqueryUI' ], function( app, calcTableRows, @@ -52,7 +53,10 @@ define([ implicitFilter: '=implicitFilter', rowSizes: '=rowSizes', extraLimit: '=extraLimit', - adminMode: '=adminMode' + adminMode: '=adminMode', + emptyResults: '=emptyResults', + customColumns: '=customColumns', + implicitSort: '=implicitSort' }, controller( $rootScope, @@ -66,17 +70,74 @@ define([ $notificationService, $tableFilterService, $window, - $groupHandler + $groupHandler, + $sce, + $fileEditor, + $dateDiffService ) { /** * Init variables */ + + $scope.showingChecks = false let realTime = false - const instance = new $dataService($scope.path, $scope.implicitFilter) + const instance = new $dataService( + $scope.path, + $scope.implicitFilter, + $scope.implicitSort + ) $scope.keyEquivalence = $keyEquivalenceService.equivalences() $scope.totalItems = 0 $scope.wazuhTableLoading = true $scope.items = [] + $scope.customEmptyResults = + $scope.emptyResults && typeof $scope.emptyResults === 'string' + ? $scope.emptyResults + : 'Empty results for this table.' + + $scope.originalkeys = $scope.keys.map((key, idx) => ({ key, idx })) + $scope.scapepath = $scope.path.split('/').join('') + + $scope.updateColumns = key => { + const cleanArray = $scope.keys.map(item => item.value || item) + if (cleanArray.includes(key)) { + const idx = cleanArray.indexOf(key) + if (idx > -1) { + $scope.keys.splice(idx, 1) + } + } else { + let originalKey = $scope.originalkeys.filter(k => k.key.value === key || k.key === key) + originalKey = originalKey[0].key + + const originalIdx = $scope.originalkeys.findIndex( + item => item.key === originalKey + ) + if (originalIdx >= 0) { + $scope.keys.splice(originalIdx, 0, originalKey) + } else { + $scope.keys.push(originalKey) + } + } + //updateStoredKeys($scope.keys) + } + + $scope.setColResizable = () => { + try { + if ($scope.customColumns) { + $(`#table${$scope.scapepath} th`).resizable({ + handles: 'e', + minWidth: 75, + start: () => { + $scope.resizingColumns = true + }, + end: () => { + $scope.resizingColumns = false + } + }) + $scope.$applyAsync() + } + } catch (error) {} // eslint-disable-line + } /** * Resizing. Calculate number of table rows depending on the screen height @@ -85,14 +146,17 @@ define([ let doit let resizing = false $window.onresize = () => { - if (resizing) return + if (resizing || $scope.resizingColumns) return resizing = true clearTimeout(doit) doit = setTimeout(() => { $scope.rowsPerPage = calcTableRows($window.innerHeight, rowSizes) $scope.itemsPerPage = $scope.rowsPerPage init() - .then(() => (resizing = false)) + .then(() => { + $scope.setColResizable() + resizing = false + }) .catch(() => (resizing = false)) }, 150) } @@ -112,19 +176,56 @@ define([ state ) + /* Deprecated at the moment + const getStoredKeys = () => { + try { + if ($scope.customColumns) { + if (sessionStorage[$scope.path]) { + $scope.keys = sessionStorage[$scope.path].split(';') + } else { + updateStoredKeys($scope.keys) + } + $scope.$applyAsync() + } + } catch (error) {} // eslint-disable-line + } + + const updateStoredKeys = keys => { + try { + if ($scope.customColumns) { + let stringKeys = keys[0] + for (var i = 1; i < keys.length; i++) { + let tmp = keys[i].value || keys[i] + stringKeys += ';' + tmp + } + sessionStorage[$scope.path] = stringKeys || '' + $scope.$applyAsync() + } + } catch (error) {} // eslint-disable-line + } + */ + /** * Fetchs data from API * @param {Object} options */ const fetch = async (options = {}) => { try { + if ((instance.filters || []).length) { + $scope.customEmptyResults = + 'No results match your search criteria' + } else { + $scope.customEmptyResults = + $scope.emptyResults || 'Empty results for this table.' + } const result = await instance.fetch(options) - items = options.realTime ? result.items.slice(0, 10) : result.items + items = result.items $scope.time = result.time $scope.totalItems = items.length $scope.items = items checkGap($scope, items) $scope.searchTable() + $scope.$emit('wazuhFetched', { items }) return } catch (error) { if ( @@ -147,7 +248,11 @@ define([ * @param {String} term * @param {Boolean} removeFilters */ - const search = async (term, removeFilters) => + const search = async (term, removeFilters) => { + if (term && typeof term === 'string') { + $scope.customEmptyResults = 'No results match your search criteria.' + } + data.searchData( term, removeFilters, @@ -157,6 +262,7 @@ define([ $tableFilterService, $notificationService ) + } /** * Queries to the API @@ -196,7 +302,7 @@ define([ try { $scope.error = false while (realTime) { - await fetch({ realTime: true, limit: 10 }) + await fetch({ realTime: true }) if (!$scope.$$phase) $scope.$digest() await $timeout(1000) } @@ -217,7 +323,9 @@ define([ $keyEquivalenceService.equivalences(), key, item, - instance.path + instance.path, + $sce, + $dateDiffService ) /** @@ -226,16 +334,19 @@ define([ const init = async () => { try { $scope.error = false - $scope.wazuhTableLoading = true await fetch() + //getStoredKeys() $tableFilterService.set(instance.filters) $scope.wazuhTableLoading = false $scope.$emit('loadedTable') if (!$scope.$$phase) $scope.$digest() + setTimeout(() => { + $scope.setColResizable() + }, 100) } catch (error) { $scope.wazuhTableLoading = false - $scope.error = `Error while init table. ${error.message || error}.` - $notificationService.showSimpleToast( + $scope.error = `Error while init table.` + $notificationService.showErrorToast( `Error while init table. ${error.message || error}` ) } @@ -255,16 +366,33 @@ define([ $scope.range = (size, start, end) => pagination.range(size, start, end, $scope.gap) $scope.prevPage = () => pagination.prevPage($scope) - $scope.nextPage = async currentPage => - pagination.nextPage(currentPage, $scope, $notificationService, fetch) - $scope.setPage = function() { - $scope.currentPage = this.n - $scope.nextPage(this.n) + $scope.nextPage = async (currentPage, last) => + pagination.nextPage( + currentPage, + $scope, + $notificationService, + fetch, + last + ) + $scope.setPage = function(page = false, last = false, first = false) { + $scope.currentPage = page || this.n + if (!first) { + $scope.nextPage(this.n, last) + } + } + $scope.firstPage = () => { + $scope.setPage(1, false, true) + $scope.prevPage() } /** * Event listeners */ + + $scope.$on('increaseLogs', async (event, parameters) => { + $scope.setPage(parseInt(parameters.lines / $scope.itemsPerPage)) + }) + $scope.$on('wazuhUpdateInstancePath', (event, parameters) => listeners.wazuhUpdateInstancePath(parameters, instance, init) ) @@ -277,6 +405,10 @@ define([ listeners.wazuhSearch(parameters, instance, search) ) + $scope.$on('wazuhSort', (event, parameters) => + $scope.sort(parameters.field) + ) + $scope.$on('wazuhRemoveFilter', (event, parameters) => listeners.wazuhRemoveFilter( parameters, @@ -341,15 +473,22 @@ define([ $scope.removingGroup = null } + $scope.editGroup = group => { + $scope.$emit('openGroupFromList', { group }) + } + $scope.confirmRemoveAgent = async agent => { try { const group = instance.path.split('/').pop() - await $groupHandler.removeAgentFromGroup(group, agent) - $notificationService.showSimpleToast( - `Success. Agent ${agent} has been removed from ${group}` + const result = await $groupHandler.removeAgentFromGroup( + group, + agent + ) + $notificationService.showSuccessToast( + result || `Success. Agent ${agent} has been removed from ${group}` ) } catch (error) { - $notificationService.showSimpleToast(`${error.message || error}`) + $notificationService.showErrorToast(`${error.message || error}`) } $scope.removingAgent = null return init() @@ -358,15 +497,152 @@ define([ $scope.confirmRemoveGroup = async group => { try { await $groupHandler.removeGroup(group) - $notificationService.showSimpleToast( + $notificationService.showSuccessToast( `Success. Group ${group} has been removed` ) } catch (error) { - $notificationService.showSimpleToast(`${error.message || error}`) + $notificationService.showErrorToast(`${error.message || error}`) } $scope.removingGroup = null return init() } + + $scope.isPolicyMonitoring = () => { + return ( + instance.path.includes('sca') && instance.path.includes('/checks') + ) + } + + $scope.expandPolicyMonitoringCheck = item => { + if (item.expanded) item.expanded = false + else { + $scope.pagedItems[$scope.currentPage].map( + item => (item.expanded = false) + ) + item.expanded = true + } + } + + /** + * Edits a file + */ + $scope.editFile = (file, path, readOnly = false) => { + $scope.$emit('editFile', { file, path, readOnly }) + } + + /** + * Removes a file + */ + + $scope.showConfirmRemoveFile = (ev, item) => { + $scope.removingFile = item + } + + $scope.confirmRemoveFile = async item => { + try { + $scope.removingFile = false + const result = await $fileEditor.removeFile(item) + $notificationService.showSuccessToast(result) + init() + $scope.$applyAsync() + } catch (error) { + $notificationService.showErrorToast( + error || `Cannot delete ${item.file || item.name}` + ) + } + } + + $scope.cancelRemoveFile = () => { + $scope.removingFile = null + return init() + } + + $scope.getWitdh = key => { + try { + if (key.includes('id') || key.includes('level')) { + return 'wz-width-85' + } + if (key.includes('pci') || key.includes('gdpr')) { + return 'wz-width-150' + } + } catch (error) {} // eslint-disable-line + } + + /** + * Removes a file + */ + $scope.showConfirmRemoveFile = (ev, item) => { + $scope.removingFile = item + } + + $scope.isSyschecks = () => { + return instance.path.startsWith('/syscheck') + } + + $scope.isWindows = () => { + try { + const agent = $scope.$parent.$parent.$parent.$parent.agent + return (agent.os || {}).platform === 'windows' + } catch (error) { + return false + } + } + + $scope.expandItem = item => { + if (item.expanded) item.expanded = false + else { + $scope.pagedItems[$scope.currentPage].map( + item => (item.expanded = false) + ) + item.expanded = true + } + } + + /** + * Show a checkbox for each key to show or hide it + */ + const cleanKeys = () => { + if ($scope.customColumns && sessionStorage[$scope.path]) { + $scope.cleanKeys = {} + $scope.keys.map(key => { + const k = key.value || key + let storedKeys = sessionStorage[$scope.path].split(';') + $scope.cleanKeys[k] = storedKeys.indexOf(k) !== -1 + }) + } else { + $scope.cleanKeys = {} + $scope.keys.map(key => { + const k = key.value || key + $scope.cleanKeys[k] = true + }) + } + } + + /** + * Launch an event to open the discover with the agent id + */ + $scope.launchAgentDiscover = agentId => { + $scope.$emit('openDiscover', agentId) + } + + cleanKeys() + + $scope.getEquivalence = key => { + return $scope.keyEquivalence[key] + } + + $scope.showCheckbox = () => { + $scope.showingChecks = !$scope.showingChecks + } + + $scope.switchKey = key => { + $scope.cleanKeys[key] = !$scope.cleanKeys[key] + } + + $scope.showKey = item => { + const it = item.value || item + return $scope.cleanKeys[it] + } }, templateUrl: BASE_URL + diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/wz-table.html b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/wz-table.html index 92e51b2c5..865af97a7 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-table/wz-table.html +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-table/wz-table.html @@ -1,126 +1,314 @@
-
-
+ +
+
+ + +
+
+
+ + {{getEquivalence(key) ? getEquivalence(key) : key}} + +
+
+
+ + Show or hide columns + + +
-
- + + + +
+
- - + + - - + - - - + + + + + + + + + +
{{ path === '/agents/groups' && (key.value || key) === 'count' ? 'Agents' : keyEquivalence[key.value || key] || key.value || key }} - ActionsActions + Actions +
- {{ - parseValue(key,item) | limitTo: extraLimit ? 100 : 25 - }} - ... - +
+
{{ + parseValue(key,item) + }}
+
+ + {{parseValue(key,item)}} + +
+ {{ parseValue(key,item) }}
- - {{ item.id }} - - - - {{ - parseValue(key,item) | limitTo: extraLimit ? 100 : 25 - }} - - ... - + +
{{ + parseValue(key,item) + }}
+
+ + {{parseValue(key,item)}} + +
+ {{ parseValue(key,item) }}
- {{ - parseValue(key,item) | limitTo: extraLimit ? 100 : 25 - }} - ... - + +
+
+ + {{parseValue(key,item)}} + +
+
{{ + parseValue(key,item) + }}
+
+ {{ parseValue(key,item) }}
-

- Open Discover panel for this agent" - - Open Configuration for this agent" + + + +
- - - Remove this group - + + + + + + + + + + +
+
+ This file will be removed +
+
+ + Cancel + Confirm +
+
+
+ + + + -
Group {{item.name}} will be removed
- + Cancel Confirm
-
-
+ + - - - - - - Remove this agent from the group - -
+
- - The agent {{item.id}} will be removed from this group + The agent {{item.id}} will be removed from + this group
Cancel + class='fa fa-fw fa-close'> + Cancel Confirm
-
+ {{ totalItems }} items ({{time | number: 2}} + seconds) + +
+
+ +
+ + + + + + + + + + + - - +
+ {{ path === '/agents/groups' && (key.value || key) === 'count' ? 'Agents' : keyEquivalence[key.value || + key] || key.value || key }} + + Actions
+ +

   +
+ + {{ + key === 'result' && !item.result ? item.status : parseValue(key,item) + }} + +
+ +
+ Check not applicable due to: +

{{ item.reason }}

+
+
+ Rationale +

{{item.rationale}}

+
+
+ Remediation +

{{item.remediation}}

+
+
+ Description +

{{item.description}}

+
+
+ Path(s) +

{{ item.directory }}

+
+
+ Checks +
    +
  • + {{r.rule}} +
  • +
+
+
+ Compliance +

{{c.key}}/{{c.value}}

+
+
+
- {{ totalItems }} items ({{time | number: 2}} seconds) -
+ {{ totalItems }} items ({{time | number: 2}} + seconds) + @@ -129,17 +317,91 @@
+ + +
+ + + + + + + + + + + + + + + +
+ {{ keyEquivalence[key.value || key] || key.value || key }} + +
+ + {{ + parseValue(key,item) + }} + +
+ + + + + + + + +
{{keyEquivalence[key] || key}}{{value}}
+
+
+ {{ totalItems }} items ({{time | number: 2}} + seconds) + +
+
- - No results match your search criteria + {{customEmptyResults}}
@@ -147,10 +409,12 @@
- diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-tag-filter/wz-tag-filter.css b/SplunkAppForWazuh/appserver/static/js/directives/wz-tag-filter/wz-tag-filter.css index 53b46c74e..02b1bfb5b 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-tag-filter/wz-tag-filter.css +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-tag-filter/wz-tag-filter.css @@ -41,20 +41,21 @@ display: flex; } .wz-tags > ul li .grouped { - background: #d9d9d9; + background: #e4f2f5; border-radius: 3px; padding: 3px; - height: 36px; + height: 30px; margin-top: -3px; display: flex; } .wz-tag-item { - color: white; + color: #0079a5; border-radius: 3px; display: inline-block; padding: 3px 5px; - background: #0079a5; + background: white; margin: 1px 3px; + border: solid 1px #0079a5 !important; } .wz-tag-item-connector { font-size: 10px; @@ -63,6 +64,11 @@ font-weight: bold; padding: 0px 5px; } + +.wz-tag-item-connector:hover { + text-decoration: underline; +} + .wz-tag-remove-button { color: #005571; } @@ -71,7 +77,7 @@ color: gray; } .wz-search-filter-bar-input { - border: none; + border: none !important; padding: 5px; width: auto; margin-left: 5px; @@ -92,6 +98,10 @@ font-weight: 700; padding: 10px; } +.wz-search-filter-bar-autocomplete ul { + list-style: none!important; + margin: 0; +} .wz-search-filter-bar-autocomplete ul li { color: white; padding: 0 10px; diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-tag-filter/wz-tag-filter.html b/SplunkAppForWazuh/appserver/static/js/directives/wz-tag-filter/wz-tag-filter.html index ce64e78a3..3be51d319 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-tag-filter/wz-tag-filter.html +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-tag-filter/wz-tag-filter.html @@ -1,4 +1,4 @@ -
+
    @@ -9,18 +9,29 @@ {{tag.value.name}} : {{tag.value.value}} - × + ×
- OR + {{connectors[$parent.$index].subgroup[$index].value + === + ';' ? 'AND' : 'OR' }}
- × + ×
- AND + + {{connectors[$index].value === ';' ? 'AND' : 'OR'}} + -
+ + + Remove all filters + + +

{{autocompleteContent.title}}

  • diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-tag-filter/wz-tag-filter.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-tag-filter/wz-tag-filter.js index 0cd76127c..ab87bfa35 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-tag-filter/wz-tag-filter.js +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-tag-filter/wz-tag-filter.js @@ -26,6 +26,7 @@ define(['../module'], function(app) { $scope.newTag = '' $scope.isAutocomplete = false $scope.dataModel = [] + $scope.connectors = [] /** * Adds a new tag @@ -60,7 +61,13 @@ define(['../module'], function(app) { return x.type === 'search' }) if (!isFilter && idxSearch) { - $scope.removeTag(idxSearch.id, false) + $scope.removeTag( + idxSearch.id, + false, + $scope.searchIdx, + undefined, + true + ) } if ( !$scope.tagList.find(function(x) { @@ -74,13 +81,14 @@ define(['../module'], function(app) { ) { $scope.tagList.push(tag) $scope.groupedTagList = groupBy($scope.tagList, 'key') + $scope.connectors = addConnectors($scope.groupedTagList) buildQuery($scope.groupedTagList) } $scope.showAutocomplete(flag) $scope.newTag = '' } } catch (error) { - $notificationService.showSimpleToast(error, 'Error adding filter') + $notificationService.showErrorToast(error, 'Error adding filter') } } @@ -90,49 +98,93 @@ define(['../module'], function(app) { */ const buildQuery = groups => { try { - let queryObj = { + const queryObj = { query: '', search: '' } - let first = true - groups.forEach(function(group) { - const search = group.find(function(x) { - return x.type === 'search' - }) + groups.forEach((group, idx) => { + const search = group.find(x => x.type === 'search') if (search) { + $scope.searchIdx = idx queryObj.search = search.value.name + if (idx === groups.length - 1) + queryObj.query = queryObj.query.substring( + 0, + queryObj.query.length - 1 + ) } else { - if (!first) { - queryObj.query += ';' - } const twoOrMoreElements = group.length > 1 if (twoOrMoreElements) { queryObj.query += '(' } group - .filter(function(x) { - return x.type === 'filter' - }) - .forEach(function(tag, idx2) { + .filter(x => x.type === 'filter') + .forEach((tag, idx2) => { queryObj.query += tag.key + '=' + tag.value.value if (idx2 != group.length - 1) { - queryObj.query += ',' + queryObj.query += + $scope.connectors[idx].subgroup[idx2].value } }) if (twoOrMoreElements) { queryObj.query += ')' } - first = false + if (idx !== groups.length - 1) { + queryObj.query += $scope.connectors[idx].value + } } }) + $scope.$applyAsync() $scope.queryFn({ q: queryObj.query, search: queryObj.search }) } catch (error) { - $notificationService.showSimpleToast( - error, - 'Error in query request' - ) + $notificationService.showErrorToast(error, 'Error in query request') } } + + const addConnectors = groups => { + const result = [] + groups.forEach((group, index) => { + result.push({}) + const subGroup = [] + group.forEach((tag, idx) => { + if (idx != group.length - 1) { + subGroup.push({ + value: + ( + ((($scope.connectors || [])[index] || {}).subgroup || [])[ + idx + ] || {} + ).value || ',' + }) + } + }) + if (subGroup.length > 0) result[index].subgroup = subGroup + if (index != groups.length - 1) { + result[index].value = + (($scope.connectors || [])[index] || {}).value || ';' + } + }) + return result + } + + $scope.changeConnector = (parentIdx, idx) => { + if ( + (parentIdx === $scope.searchIdx - 1 || + parentIdx === $scope.searchIdx) && + idx === undefined + ) { + $scope.connectors[parentIdx].value = ';' + } else { + if (idx !== undefined) { + $scope.connectors[parentIdx].subgroup[idx].value = ',' + } else { + const value = $scope.connectors[parentIdx].value + $scope.connectors[parentIdx].value = value === ';' ? ',' : ';' + buildQuery($scope.groupedTagList) + } + } + } + const groupBy = (collection, property) => { let i = 0, val, @@ -163,23 +215,50 @@ define(['../module'], function(app) { $scope.newTag += value $scope.addTag() } - $scope.removeTag = (id, deleteGroup) => { + $scope.removeTag = ( + id, + deleteGroup, + parentIdx, + idx, + overwrite = false + ) => { if (deleteGroup) { - $scope.tagList = $scope.tagList.filter(function(x) { - return x.key !== id - }) + $scope.tagList = $scope.tagList.filter(x => x.key !== id) + $scope.connectors.splice(parentIdx, 1) } else { - $scope.tagList.splice( - $scope.tagList.findIndex(function(x) { - return x.id === id - }), - 1 - ) + $scope.tagList.splice($scope.tagList.findIndex(x => x.id === id), 1) + if (idx < 0) { + idx = 0 + } + if ( + $scope.connectors[parentIdx] && + $scope.connectors[parentIdx].subgroup + ) { + $scope.connectors[parentIdx].subgroup.splice(idx, 1) + } else $scope.connectors.splice(parentIdx, 1) + } + if ($scope.tagList.length <= 1) { + $scope.connectors = [{}] } $scope.groupedTagList = groupBy($scope.tagList, 'key') + const search = $scope.tagList.find(x => x.type === 'search') + if (!search) { + $scope.searchIdx = false + } + $scope.connectors = addConnectors($scope.groupedTagList) + if (!overwrite) buildQuery($scope.groupedTagList) + $scope.showAutocomplete(false) + } + + $scope.removeAll = () => { + $scope.tagList = [] + $scope.connectors = [] + $scope.groupedTagList = [] + $scope.searchIdx = false buildQuery($scope.groupedTagList) $scope.showAutocomplete(false) } + $scope.showAutocomplete = flag => { if (flag) { $scope.getAutocompleteContent() @@ -307,6 +386,7 @@ define(['../module'], function(app) { } } }) + $('#wz-search-filter-bar-input').attr('autocomplete', 'off') load() }, templateUrl: diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-welcome-card/wz-welcome-card.html b/SplunkAppForWazuh/appserver/static/js/directives/wz-welcome-card/wz-welcome-card.html index 4c1784ffc..470949851 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-welcome-card/wz-welcome-card.html +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-welcome-card/wz-welcome-card.html @@ -1,14 +1,14 @@ -
    +
    - +

    - {{ description }} + {{ description }}

    diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-welcome-card/wz-welcome-card.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-welcome-card/wz-welcome-card.js index 9c144e598..7f0cd0b69 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-welcome-card/wz-welcome-card.js +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-welcome-card/wz-welcome-card.js @@ -15,7 +15,7 @@ define(['../module'], function(directives) { return { restrict: 'E', scope: { - title: '=title', + subTitle: '=subTitle', description: '=description', logo: '=logo', switchTab: '&', diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-xml-file-editor/wz-xml-file-editor.html b/SplunkAppForWazuh/appserver/static/js/directives/wz-xml-file-editor/wz-xml-file-editor.html index 3ab37ab9e..8a02d3b55 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-xml-file-editor/wz-xml-file-editor.html +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-xml-file-editor/wz-xml-file-editor.html @@ -1,10 +1,24 @@
    + +
    + + + {{err}} + + +
    +
    - Edit configuration of {{targetName}} group + Edit {{fileName}} of {{targetName}} +
    +
    +   + Changes will not take effect until a restart is performed. + + Restart now
    -
    -
    - -
    +
    +
    \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/directives/wz-xml-file-editor/wz-xml-file-editor.js b/SplunkAppForWazuh/appserver/static/js/directives/wz-xml-file-editor/wz-xml-file-editor.js index 237ad079c..c19f1b394 100644 --- a/SplunkAppForWazuh/appserver/static/js/directives/wz-xml-file-editor/wz-xml-file-editor.js +++ b/SplunkAppForWazuh/appserver/static/js/directives/wz-xml-file-editor/wz-xml-file-editor.js @@ -31,9 +31,16 @@ define([ fileName: '@fileName', validFn: '&', data: '=data', - targetName: '=targetName' + targetName: '=targetName', + closeFn: '&' }, - controller($scope, $document, $notificationService, $groupHandler) { + controller( + $scope, + $document, + $notificationService, + $groupHandler, + $fileEditor + ) { /** * Custom .replace method. Instead of using .replace which * evaluates regular expressions. @@ -54,7 +61,13 @@ define([ const lines = oDOM.documentElement.textContent.split('\n') for (const line of lines) { - const sanitized = line.trim().xmlReplace('&', '&') + const sanitized = line + .trim() + .xmlReplace('&', '&') + .xmlReplace(//g, '>') // eslint-disable-line + .xmlReplace(/"/g, '"') // eslint-disable-line + .xmlReplace(/'/g, ''') // eslint-disable-line /** * Do not remove this condition. We don't want to replace * non-sanitized lines. @@ -89,7 +102,7 @@ define([ !xml.length }) } catch (error) { - $notificationService.showSimpleToast(error, 'Error validating XML') + $notificationService.showErrorToast(error, 'Error validating XML') } checkingXmlError = false if (!$scope.$$phase) $scope.$digest() @@ -161,18 +174,62 @@ define([ const saveFile = async params => { try { + $scope.showErrorMessages = false + $scope.errorInfo = false const text = $scope.xmlCodeBox.getValue() const xml = replaceIllegalXML(text) - await $groupHandler.sendConfiguration(params.group, xml) - $notificationService.showSimpleToast( - 'Success. Group has been updated' - ) - $scope.$emit('configurationSuccess') + if (params && params.group) { + await $groupHandler.sendConfiguration(params.group, xml) + $scope.$emit('saveComplete', {}) + $notificationService.showSuccessToast( + `Group ${params.group} saved successfully.` + ) + } else if (params && params.file) { + const result = await $fileEditor.sendConfiguration( + params.file, + params.dir, + params.node, + xml, + params.overwrite + ) + if (result === 'fileAlreadyExists') { + $scope.showErrorMessages = true + $scope.errorInfo = ['File already exists.'] + $scope.$emit('fileAlreadyExists', {}) + } else { + $scope.$emit('saveComplete', {}) + $scope.$emit('configSavedSuccessfully', {}) + $scope.restartBtn = true + let msg = null + if (params.file === 'ossec.conf') { + if (params.node) { + msg = `Succes. Node(${ + params.node + }) configuration has been updated.` + } else { + msg = 'Succes. Manager configuration has been updated.' + } + } else { + msg = 'Configuration saved successfully.' + } + $notificationService.showSuccessToast(msg) + } + } + //$scope.closeFn() } catch (error) { - $notificationService.showSimpleToast( - error.message || error, - 'Send file error' - ) + $scope.$emit('saveComplete', {}) + if (error.badConfig) { + $scope.showErrorMessages = true + $scope.errorInfo = error.errMsg + $notificationService.showWarningToast( + 'Configuration saved, but some errors were found.' + ) + } else { + $notificationService.showErrorToast( + error.message || error, + 'Error sending file.' + ) + } } return } @@ -180,6 +237,7 @@ define([ $document[0].getElementById('xml_box'), { lineNumbers: true, + lineWrapping: true, matchClosing: true, matchBrackets: true, mode: 'text/xml', @@ -190,19 +248,28 @@ define([ } ) + $scope.doRestart = () => { + $scope.restartBtn = false + $scope.$emit('performRestart', {}) + } + const init = (data = false) => { try { $scope.xmlCodeBox.setValue(autoFormat(data || $scope.data)) firstTime = false - $scope.xmlCodeBox.refresh() + setTimeout(() => { + $scope.xmlCodeBox.refresh() + }, 1) + //autoFormat() } catch (error) { - $notificationService.showSimpleToast('Fetching original file') + $notificationService.showErrorToast('Error fetching xml content.') } } init() $scope.$on('fetchedFile', (ev, params) => { + $scope.restartBtn = false if (!firstTime) { init(params.data) } @@ -212,6 +279,11 @@ define([ checkXmlParseError() }) + $scope.$on('removeRestartMsg', () => { + $scope.restartBtn = false + $scope.$applyAsync() + }) + $scope.$on('saveXmlFile', (ev, params) => saveFile(params)) }, templateUrl: diff --git a/SplunkAppForWazuh/appserver/static/js/libs/angular-chart.js b/SplunkAppForWazuh/appserver/static/js/libs/angular-chart.js new file mode 100644 index 000000000..27704b432 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/libs/angular-chart.js @@ -0,0 +1,399 @@ +/*! + * angular-chart.js - An angular.js wrapper for Chart.js + * http://jtblin.github.io/angular-chart.js/ + * Version: 1.1.1 + * + * Copyright 2016 Jerome Touffe-Blin + * Released under the BSD-2-Clause license + * https://github.com/jtblin/angular-chart.js/blob/master/LICENSE + */ +(function (factory) { + 'use strict'; + if (typeof exports === 'object') { + // Node/CommonJS + module.exports = factory( + typeof angular !== 'undefined' ? angular : require('angular'), + typeof Chart !== 'undefined' ? Chart : require('chart')); + } else if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['angular', 'chart'], factory); + } else { + // Browser globals + if (typeof angular === 'undefined') { + throw new Error('AngularJS framework needs to be included, see https://angularjs.org/'); + } else if (typeof Chart === 'undefined') { + throw new Error('Chart.js library needs to be included, see http://jtblin.github.io/angular-chart.js/'); + } + factory(angular, Chart); + } +}(function (angular, Chart) { + 'use strict'; + Chart.defaults.global.multiTooltipTemplate = '<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= value %>'; + Chart.defaults.global.tooltips.mode = 'label'; + Chart.defaults.global.elements.line.borderWidth = 2; + Chart.defaults.global.elements.rectangle.borderWidth = 2; + Chart.defaults.global.legend.display = false; + Chart.defaults.global.colors = [ + '#97BBCD', // blue + '#DCDCDC', // light grey + '#F7464A', // red + '#46BFBD', // green + '#FDB45C', // yellow + '#949FB1', // grey + '#4D5360' // dark grey + ]; + + var useExcanvas = typeof window.G_vmlCanvasManager === 'object' && + window.G_vmlCanvasManager !== null && + typeof window.G_vmlCanvasManager.initElement === 'function'; + + if (useExcanvas) Chart.defaults.global.animation = false; + + return angular.module('chart.js', []) + .provider('ChartJs', ChartJsProvider) + .factory('ChartJsFactory', ['ChartJs', '$timeout', ChartJsFactory]) + .directive('chartBase', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory(); }]) + .directive('chartLine', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('line'); }]) + .directive('chartBar', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('bar'); }]) + .directive('chartHorizontalBar', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('horizontalBar'); }]) + .directive('chartRadar', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('radar'); }]) + .directive('chartDoughnut', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('doughnut'); }]) + .directive('chartPie', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('pie'); }]) + .directive('chartPolarArea', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('polarArea'); }]) + .directive('chartBubble', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('bubble'); }]) + .name; + + /** + * Wrapper for chart.js + * Allows configuring chart js using the provider + * + * angular.module('myModule', ['chart.js']).config(function(ChartJsProvider) { + * ChartJsProvider.setOptions({ responsive: false }); + * ChartJsProvider.setOptions('Line', { responsive: true }); + * }))) + */ + function ChartJsProvider () { + var options = { responsive: true }; + var ChartJs = { + Chart: Chart, + getOptions: function (type) { + var typeOptions = type && options[type] || {}; + return angular.extend({}, options, typeOptions); + } + }; + + /** + * Allow to set global options during configuration + */ + this.setOptions = function (type, customOptions) { + // If no type was specified set option for the global object + if (! customOptions) { + customOptions = type; + options = angular.merge(options, customOptions); + } else { + // Set options for the specific chart + options[type] = angular.merge(options[type] || {}, customOptions); + } + + angular.merge(ChartJs.Chart.defaults, options); + }; + + this.$get = function () { + return ChartJs; + }; + } + + function ChartJsFactory (ChartJs, $timeout) { + return function chart (type) { + return { + restrict: 'CA', + scope: { + chartGetColor: '=?', + chartType: '=', + chartData: '=?', + chartLabels: '=?', + chartOptions: '=?', + chartSeries: '=?', + chartColors: '=?', + chartClick: '=?', + chartHover: '=?', + chartDatasetOverride: '=?' + }, + link: function (scope, elem/*, attrs */) { + if (useExcanvas) window.G_vmlCanvasManager.initElement(elem[0]); + + // Order of setting "watch" matter + scope.$watch('chartData', watchData, true); + scope.$watch('chartSeries', watchOther, true); + scope.$watch('chartLabels', watchOther, true); + scope.$watch('chartOptions', watchOther, true); + scope.$watch('chartColors', watchOther, true); + scope.$watch('chartDatasetOverride', watchOther, true); + scope.$watch('chartType', watchType, false); + + scope.$on('$destroy', function () { + destroyChart(scope); + }); + + scope.$on('$resize', function () { + if (scope.chart) scope.chart.resize(); + }); + + function watchData (newVal, oldVal) { + if (! newVal || ! newVal.length || (Array.isArray(newVal[0]) && ! newVal[0].length)) { + destroyChart(scope); + return; + } + var chartType = type || scope.chartType; + if (! chartType) return; + + if (scope.chart && canUpdateChart(newVal, oldVal)) + return updateChart(newVal, scope); + + createChart(chartType, scope, elem); + } + + function watchOther (newVal, oldVal) { + if (isEmpty(newVal)) return; + if (angular.equals(newVal, oldVal)) return; + var chartType = type || scope.chartType; + if (! chartType) return; + + // chart.update() doesn't work for series and labels + // so we have to re-create the chart entirely + createChart(chartType, scope, elem); + } + + function watchType (newVal, oldVal) { + if (isEmpty(newVal)) return; + if (angular.equals(newVal, oldVal)) return; + createChart(newVal, scope, elem); + } + } + }; + }; + + function createChart (type, scope, elem) { + var options = getChartOptions(type, scope); + if (! hasData(scope) || ! canDisplay(type, scope, elem, options)) return; + + var cvs = elem[0]; + var ctx = cvs.getContext('2d'); + + scope.chartGetColor = getChartColorFn(scope); + var data = getChartData(type, scope); + // Destroy old chart if it exists to avoid ghost charts issue + // https://github.com/jtblin/angular-chart.js/issues/187 + destroyChart(scope); + + scope.chart = new ChartJs.Chart(ctx, { + type: type, + data: data, + options: options + }); + scope.$emit('chart-create', scope.chart); + bindEvents(cvs, scope); + } + + function canUpdateChart (newVal, oldVal) { + if (newVal && oldVal && newVal.length && oldVal.length) { + return Array.isArray(newVal[0]) ? + newVal.length === oldVal.length && newVal.every(function (element, index) { + return element.length === oldVal[index].length; }) : + oldVal.reduce(sum, 0) > 0 ? newVal.length === oldVal.length : false; + } + return false; + } + + function sum (carry, val) { + return carry + val; + } + + function getEventHandler (scope, action, triggerOnlyOnChange) { + var lastState = { + point: void 0, + points: void 0 + }; + return function (evt) { + var atEvent = scope.chart.getElementAtEvent || scope.chart.getPointAtEvent; + var atEvents = scope.chart.getElementsAtEvent || scope.chart.getPointsAtEvent; + if (atEvents) { + var points = atEvents.call(scope.chart, evt); + var point = atEvent ? atEvent.call(scope.chart, evt)[0] : void 0; + + if (triggerOnlyOnChange === false || + (! angular.equals(lastState.points, points) && ! angular.equals(lastState.point, point)) + ) { + lastState.point = point; + lastState.points = points; + scope[action](points, evt, point); + } + } + }; + } + + function getColors (type, scope) { + var colors = angular.copy(scope.chartColors || + ChartJs.getOptions(type).chartColors || + Chart.defaults.global.colors + ); + var notEnoughColors = colors.length < scope.chartData.length; + while (colors.length < scope.chartData.length) { + colors.push(scope.chartGetColor()); + } + // mutate colors in this case as we don't want + // the colors to change on each refresh + if (notEnoughColors) scope.chartColors = colors; + return colors.map(convertColor); + } + + function convertColor (color) { + // Allows RGB and RGBA colors to be input as a string: e.g.: "rgb(159,204,0)", "rgba(159,204,0, 0.5)" + if (typeof color === 'string' && color[0] === 'r') return getColor(rgbStringToRgb(color)); + // Allows hex colors to be input as a string. + if (typeof color === 'string' && color[0] === '#') return getColor(hexToRgb(color.substr(1))); + // Allows colors to be input as an object, bypassing getColor() entirely + if (typeof color === 'object' && color !== null) return color; + return getRandomColor(); + } + + function getRandomColor () { + var color = [getRandomInt(0, 255), getRandomInt(0, 255), getRandomInt(0, 255)]; + return getColor(color); + } + + function getColor (color) { + var alpha = color[3] || 1; + color = color.slice(0, 3); + return { + backgroundColor: rgba(color, 0.2), + pointBackgroundColor: rgba(color, alpha), + pointHoverBackgroundColor: rgba(color, 0.8), + borderColor: rgba(color, alpha), + pointBorderColor: '#fff', + pointHoverBorderColor: rgba(color, alpha) + }; + } + + function getRandomInt (min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; + } + + function rgba (color, alpha) { + // rgba not supported by IE8 + return useExcanvas ? 'rgb(' + color.join(',') + ')' : 'rgba(' + color.concat(alpha).join(',') + ')'; + } + + // Credit: http://stackoverflow.com/a/11508164/1190235 + function hexToRgb (hex) { + var bigint = parseInt(hex, 16), + r = (bigint >> 16) & 255, + g = (bigint >> 8) & 255, + b = bigint & 255; + + return [r, g, b]; + } + + function rgbStringToRgb (color) { + var match = color.match(/^rgba?\(([\d,.]+)\)$/); + if (! match) throw new Error('Cannot parse rgb value'); + color = match[1].split(','); + return color.map(Number); + } + + function hasData (scope) { + return scope.chartData && scope.chartData.length; + } + + function getChartColorFn (scope) { + return typeof scope.chartGetColor === 'function' ? scope.chartGetColor : getRandomColor; + } + + function getChartData (type, scope) { + var colors = getColors(type, scope); + return Array.isArray(scope.chartData[0]) ? + getDataSets(scope.chartLabels, scope.chartData, scope.chartSeries || [], colors, scope.chartDatasetOverride) : + getData(scope.chartLabels, scope.chartData, colors, scope.chartDatasetOverride); + } + + function getDataSets (labels, data, series, colors, datasetOverride) { + return { + labels: labels, + datasets: data.map(function (item, i) { + var dataset = angular.extend({}, colors[i], { + label: series[i], + data: item + }); + if (datasetOverride && datasetOverride.length >= i) { + angular.merge(dataset, datasetOverride[i]); + } + return dataset; + }) + }; + } + + function getData (labels, data, colors, datasetOverride) { + var dataset = { + labels: labels, + datasets: [{ + data: data, + backgroundColor: colors.map(function (color) { + return color.pointBackgroundColor; + }), + hoverBackgroundColor: colors.map(function (color) { + return color.backgroundColor; + }) + }] + }; + if (datasetOverride) { + angular.merge(dataset.datasets[0], datasetOverride); + } + return dataset; + } + + function getChartOptions (type, scope) { + return angular.extend({}, ChartJs.getOptions(type), scope.chartOptions); + } + + function bindEvents (cvs, scope) { + cvs.onclick = scope.chartClick ? getEventHandler(scope, 'chartClick', false) : angular.noop; + cvs.onmousemove = scope.chartHover ? getEventHandler(scope, 'chartHover', true) : angular.noop; + } + + function updateChart (values, scope) { + if (Array.isArray(scope.chartData[0])) { + scope.chart.data.datasets.forEach(function (dataset, i) { + dataset.data = values[i]; + }); + } else { + scope.chart.data.datasets[0].data = values; + } + + scope.chart.update(); + scope.$emit('chart-update', scope.chart); + } + + function isEmpty (value) { + return ! value || + (Array.isArray(value) && ! value.length) || + (typeof value === 'object' && ! Object.keys(value).length); + } + + function canDisplay (type, scope, elem, options) { + // TODO: check parent? + if (options.responsive && elem[0].clientHeight === 0) { + $timeout(function () { + createChart(type, scope, elem); + }, 50, false); + return false; + } + return true; + } + + function destroyChart(scope) { + if(! scope.chart) return; + scope.chart.destroy(); + scope.$emit('chart-destroy', scope.chart); + } + } +})); diff --git a/SplunkAppForWazuh/appserver/static/js/libs/chart.js b/SplunkAppForWazuh/appserver/static/js/libs/chart.js new file mode 100644 index 000000000..1bbf6c8da --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/libs/chart.js @@ -0,0 +1,14680 @@ +/*! + * Chart.js v2.8.0 + * https://www.chartjs.org + * (c) 2019 Chart.js Contributors + * Released under the MIT License + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(function() { try { return require('moment'); } catch(e) { } }()) : +typeof define === 'function' && define.amd ? define(['require'], function(require) { return factory(function() { try { return require('moment'); } catch(e) { } }()); }) : +(global.Chart = factory(global.moment)); +}(this, (function (moment) { 'use strict'; + +moment = moment && moment.hasOwnProperty('default') ? moment['default'] : moment; + +/* MIT license */ + +var conversions = { + rgb2hsl: rgb2hsl, + rgb2hsv: rgb2hsv, + rgb2hwb: rgb2hwb, + rgb2cmyk: rgb2cmyk, + rgb2keyword: rgb2keyword, + rgb2xyz: rgb2xyz, + rgb2lab: rgb2lab, + rgb2lch: rgb2lch, + + hsl2rgb: hsl2rgb, + hsl2hsv: hsl2hsv, + hsl2hwb: hsl2hwb, + hsl2cmyk: hsl2cmyk, + hsl2keyword: hsl2keyword, + + hsv2rgb: hsv2rgb, + hsv2hsl: hsv2hsl, + hsv2hwb: hsv2hwb, + hsv2cmyk: hsv2cmyk, + hsv2keyword: hsv2keyword, + + hwb2rgb: hwb2rgb, + hwb2hsl: hwb2hsl, + hwb2hsv: hwb2hsv, + hwb2cmyk: hwb2cmyk, + hwb2keyword: hwb2keyword, + + cmyk2rgb: cmyk2rgb, + cmyk2hsl: cmyk2hsl, + cmyk2hsv: cmyk2hsv, + cmyk2hwb: cmyk2hwb, + cmyk2keyword: cmyk2keyword, + + keyword2rgb: keyword2rgb, + keyword2hsl: keyword2hsl, + keyword2hsv: keyword2hsv, + keyword2hwb: keyword2hwb, + keyword2cmyk: keyword2cmyk, + keyword2lab: keyword2lab, + keyword2xyz: keyword2xyz, + + xyz2rgb: xyz2rgb, + xyz2lab: xyz2lab, + xyz2lch: xyz2lch, + + lab2xyz: lab2xyz, + lab2rgb: lab2rgb, + lab2lch: lab2lch, + + lch2lab: lch2lab, + lch2xyz: lch2xyz, + lch2rgb: lch2rgb +}; + + +function rgb2hsl(rgb) { + var r = rgb[0]/255, + g = rgb[1]/255, + b = rgb[2]/255, + min = Math.min(r, g, b), + max = Math.max(r, g, b), + delta = max - min, + h, s, l; + + if (max == min) + h = 0; + else if (r == max) + h = (g - b) / delta; + else if (g == max) + h = 2 + (b - r) / delta; + else if (b == max) + h = 4 + (r - g)/ delta; + + h = Math.min(h * 60, 360); + + if (h < 0) + h += 360; + + l = (min + max) / 2; + + if (max == min) + s = 0; + else if (l <= 0.5) + s = delta / (max + min); + else + s = delta / (2 - max - min); + + return [h, s * 100, l * 100]; +} + +function rgb2hsv(rgb) { + var r = rgb[0], + g = rgb[1], + b = rgb[2], + min = Math.min(r, g, b), + max = Math.max(r, g, b), + delta = max - min, + h, s, v; + + if (max == 0) + s = 0; + else + s = (delta/max * 1000)/10; + + if (max == min) + h = 0; + else if (r == max) + h = (g - b) / delta; + else if (g == max) + h = 2 + (b - r) / delta; + else if (b == max) + h = 4 + (r - g) / delta; + + h = Math.min(h * 60, 360); + + if (h < 0) + h += 360; + + v = ((max / 255) * 1000) / 10; + + return [h, s, v]; +} + +function rgb2hwb(rgb) { + var r = rgb[0], + g = rgb[1], + b = rgb[2], + h = rgb2hsl(rgb)[0], + w = 1/255 * Math.min(r, Math.min(g, b)), + b = 1 - 1/255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +} + +function rgb2cmyk(rgb) { + var r = rgb[0] / 255, + g = rgb[1] / 255, + b = rgb[2] / 255, + c, m, y, k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + return [c * 100, m * 100, y * 100, k * 100]; +} + +function rgb2keyword(rgb) { + return reverseKeywords[JSON.stringify(rgb)]; +} + +function rgb2xyz(rgb) { + var r = rgb[0] / 255, + g = rgb[1] / 255, + b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y *100, z * 100]; +} + +function rgb2lab(rgb) { + var xyz = rgb2xyz(rgb), + x = xyz[0], + y = xyz[1], + z = xyz[2], + l, a, b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +} + +function rgb2lch(args) { + return lab2lch(rgb2lab(args)); +} + +function hsl2rgb(hsl) { + var h = hsl[0] / 360, + s = hsl[1] / 100, + l = hsl[2] / 100, + t1, t2, t3, rgb, val; + + if (s == 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) + t2 = l * (1 + s); + else + t2 = l + s - l * s; + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * - (i - 1); + t3 < 0 && t3++; + t3 > 1 && t3--; + + if (6 * t3 < 1) + val = t1 + (t2 - t1) * 6 * t3; + else if (2 * t3 < 1) + val = t2; + else if (3 * t3 < 2) + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + else + val = t1; + + rgb[i] = val * 255; + } + + return rgb; +} + +function hsl2hsv(hsl) { + var h = hsl[0], + s = hsl[1] / 100, + l = hsl[2] / 100, + sv, v; + + if(l === 0) { + // no need to do calc on black + // also avoids divide by 0 error + return [0, 0, 0]; + } + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + v = (l + s) / 2; + sv = (2 * s) / (l + s); + return [h, sv * 100, v * 100]; +} + +function hsl2hwb(args) { + return rgb2hwb(hsl2rgb(args)); +} + +function hsl2cmyk(args) { + return rgb2cmyk(hsl2rgb(args)); +} + +function hsl2keyword(args) { + return rgb2keyword(hsl2rgb(args)); +} + + +function hsv2rgb(hsv) { + var h = hsv[0] / 60, + s = hsv[1] / 100, + v = hsv[2] / 100, + hi = Math.floor(h) % 6; + + var f = h - Math.floor(h), + p = 255 * v * (1 - s), + q = 255 * v * (1 - (s * f)), + t = 255 * v * (1 - (s * (1 - f))), + v = 255 * v; + + switch(hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +} + +function hsv2hsl(hsv) { + var h = hsv[0], + s = hsv[1] / 100, + v = hsv[2] / 100, + sl, l; + + l = (2 - s) * v; + sl = s * v; + sl /= (l <= 1) ? l : 2 - l; + sl = sl || 0; + l /= 2; + return [h, sl * 100, l * 100]; +} + +function hsv2hwb(args) { + return rgb2hwb(hsv2rgb(args)) +} + +function hsv2cmyk(args) { + return rgb2cmyk(hsv2rgb(args)); +} + +function hsv2keyword(args) { + return rgb2keyword(hsv2rgb(args)); +} + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +function hwb2rgb(hwb) { + var h = hwb[0] / 360, + wh = hwb[1] / 100, + bl = hwb[2] / 100, + ratio = wh + bl, + i, v, f, n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + if ((i & 0x01) != 0) { + f = 1 - f; + } + n = wh + f * (v - wh); // linear interpolation + + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; +} + +function hwb2hsl(args) { + return rgb2hsl(hwb2rgb(args)); +} + +function hwb2hsv(args) { + return rgb2hsv(hwb2rgb(args)); +} + +function hwb2cmyk(args) { + return rgb2cmyk(hwb2rgb(args)); +} + +function hwb2keyword(args) { + return rgb2keyword(hwb2rgb(args)); +} + +function cmyk2rgb(cmyk) { + var c = cmyk[0] / 100, + m = cmyk[1] / 100, + y = cmyk[2] / 100, + k = cmyk[3] / 100, + r, g, b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + return [r * 255, g * 255, b * 255]; +} + +function cmyk2hsl(args) { + return rgb2hsl(cmyk2rgb(args)); +} + +function cmyk2hsv(args) { + return rgb2hsv(cmyk2rgb(args)); +} + +function cmyk2hwb(args) { + return rgb2hwb(cmyk2rgb(args)); +} + +function cmyk2keyword(args) { + return rgb2keyword(cmyk2rgb(args)); +} + + +function xyz2rgb(xyz) { + var x = xyz[0] / 100, + y = xyz[1] / 100, + z = xyz[2] / 100, + r, g, b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r = (r * 12.92); + + g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g = (g * 12.92); + + b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b = (b * 12.92); + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +} + +function xyz2lab(xyz) { + var x = xyz[0], + y = xyz[1], + z = xyz[2], + l, a, b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +} + +function xyz2lch(args) { + return lab2lch(xyz2lab(args)); +} + +function lab2xyz(lab) { + var l = lab[0], + a = lab[1], + b = lab[2], + x, y, z, y2; + + if (l <= 8) { + y = (l * 100) / 903.3; + y2 = (7.787 * (y / 100)) + (16 / 116); + } else { + y = 100 * Math.pow((l + 16) / 116, 3); + y2 = Math.pow(y / 100, 1/3); + } + + x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3); + + z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3); + + return [x, y, z]; +} + +function lab2lch(lab) { + var l = lab[0], + a = lab[1], + b = lab[2], + hr, h, c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + if (h < 0) { + h += 360; + } + c = Math.sqrt(a * a + b * b); + return [l, c, h]; +} + +function lab2rgb(args) { + return xyz2rgb(lab2xyz(args)); +} + +function lch2lab(lch) { + var l = lch[0], + c = lch[1], + h = lch[2], + a, b, hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + return [l, a, b]; +} + +function lch2xyz(args) { + return lab2xyz(lch2lab(args)); +} + +function lch2rgb(args) { + return lab2rgb(lch2lab(args)); +} + +function keyword2rgb(keyword) { + return cssKeywords[keyword]; +} + +function keyword2hsl(args) { + return rgb2hsl(keyword2rgb(args)); +} + +function keyword2hsv(args) { + return rgb2hsv(keyword2rgb(args)); +} + +function keyword2hwb(args) { + return rgb2hwb(keyword2rgb(args)); +} + +function keyword2cmyk(args) { + return rgb2cmyk(keyword2rgb(args)); +} + +function keyword2lab(args) { + return rgb2lab(keyword2rgb(args)); +} + +function keyword2xyz(args) { + return rgb2xyz(keyword2rgb(args)); +} + +var cssKeywords = { + aliceblue: [240,248,255], + antiquewhite: [250,235,215], + aqua: [0,255,255], + aquamarine: [127,255,212], + azure: [240,255,255], + beige: [245,245,220], + bisque: [255,228,196], + black: [0,0,0], + blanchedalmond: [255,235,205], + blue: [0,0,255], + blueviolet: [138,43,226], + brown: [165,42,42], + burlywood: [222,184,135], + cadetblue: [95,158,160], + chartreuse: [127,255,0], + chocolate: [210,105,30], + coral: [255,127,80], + cornflowerblue: [100,149,237], + cornsilk: [255,248,220], + crimson: [220,20,60], + cyan: [0,255,255], + darkblue: [0,0,139], + darkcyan: [0,139,139], + darkgoldenrod: [184,134,11], + darkgray: [169,169,169], + darkgreen: [0,100,0], + darkgrey: [169,169,169], + darkkhaki: [189,183,107], + darkmagenta: [139,0,139], + darkolivegreen: [85,107,47], + darkorange: [255,140,0], + darkorchid: [153,50,204], + darkred: [139,0,0], + darksalmon: [233,150,122], + darkseagreen: [143,188,143], + darkslateblue: [72,61,139], + darkslategray: [47,79,79], + darkslategrey: [47,79,79], + darkturquoise: [0,206,209], + darkviolet: [148,0,211], + deeppink: [255,20,147], + deepskyblue: [0,191,255], + dimgray: [105,105,105], + dimgrey: [105,105,105], + dodgerblue: [30,144,255], + firebrick: [178,34,34], + floralwhite: [255,250,240], + forestgreen: [34,139,34], + fuchsia: [255,0,255], + gainsboro: [220,220,220], + ghostwhite: [248,248,255], + gold: [255,215,0], + goldenrod: [218,165,32], + gray: [128,128,128], + green: [0,128,0], + greenyellow: [173,255,47], + grey: [128,128,128], + honeydew: [240,255,240], + hotpink: [255,105,180], + indianred: [205,92,92], + indigo: [75,0,130], + ivory: [255,255,240], + khaki: [240,230,140], + lavender: [230,230,250], + lavenderblush: [255,240,245], + lawngreen: [124,252,0], + lemonchiffon: [255,250,205], + lightblue: [173,216,230], + lightcoral: [240,128,128], + lightcyan: [224,255,255], + lightgoldenrodyellow: [250,250,210], + lightgray: [211,211,211], + lightgreen: [144,238,144], + lightgrey: [211,211,211], + lightpink: [255,182,193], + lightsalmon: [255,160,122], + lightseagreen: [32,178,170], + lightskyblue: [135,206,250], + lightslategray: [119,136,153], + lightslategrey: [119,136,153], + lightsteelblue: [176,196,222], + lightyellow: [255,255,224], + lime: [0,255,0], + limegreen: [50,205,50], + linen: [250,240,230], + magenta: [255,0,255], + maroon: [128,0,0], + mediumaquamarine: [102,205,170], + mediumblue: [0,0,205], + mediumorchid: [186,85,211], + mediumpurple: [147,112,219], + mediumseagreen: [60,179,113], + mediumslateblue: [123,104,238], + mediumspringgreen: [0,250,154], + mediumturquoise: [72,209,204], + mediumvioletred: [199,21,133], + midnightblue: [25,25,112], + mintcream: [245,255,250], + mistyrose: [255,228,225], + moccasin: [255,228,181], + navajowhite: [255,222,173], + navy: [0,0,128], + oldlace: [253,245,230], + olive: [128,128,0], + olivedrab: [107,142,35], + orange: [255,165,0], + orangered: [255,69,0], + orchid: [218,112,214], + palegoldenrod: [238,232,170], + palegreen: [152,251,152], + paleturquoise: [175,238,238], + palevioletred: [219,112,147], + papayawhip: [255,239,213], + peachpuff: [255,218,185], + peru: [205,133,63], + pink: [255,192,203], + plum: [221,160,221], + powderblue: [176,224,230], + purple: [128,0,128], + rebeccapurple: [102, 51, 153], + red: [255,0,0], + rosybrown: [188,143,143], + royalblue: [65,105,225], + saddlebrown: [139,69,19], + salmon: [250,128,114], + sandybrown: [244,164,96], + seagreen: [46,139,87], + seashell: [255,245,238], + sienna: [160,82,45], + silver: [192,192,192], + skyblue: [135,206,235], + slateblue: [106,90,205], + slategray: [112,128,144], + slategrey: [112,128,144], + snow: [255,250,250], + springgreen: [0,255,127], + steelblue: [70,130,180], + tan: [210,180,140], + teal: [0,128,128], + thistle: [216,191,216], + tomato: [255,99,71], + turquoise: [64,224,208], + violet: [238,130,238], + wheat: [245,222,179], + white: [255,255,255], + whitesmoke: [245,245,245], + yellow: [255,255,0], + yellowgreen: [154,205,50] +}; + +var reverseKeywords = {}; +for (var key in cssKeywords) { + reverseKeywords[JSON.stringify(cssKeywords[key])] = key; +} + +var convert = function() { + return new Converter(); +}; + +for (var func in conversions) { + // export Raw versions + convert[func + "Raw"] = (function(func) { + // accept array or plain args + return function(arg) { + if (typeof arg == "number") + arg = Array.prototype.slice.call(arguments); + return conversions[func](arg); + } + })(func); + + var pair = /(\w+)2(\w+)/.exec(func), + from = pair[1], + to = pair[2]; + + // export rgb2hsl and ["rgb"]["hsl"] + convert[from] = convert[from] || {}; + + convert[from][to] = convert[func] = (function(func) { + return function(arg) { + if (typeof arg == "number") + arg = Array.prototype.slice.call(arguments); + + var val = conversions[func](arg); + if (typeof val == "string" || val === undefined) + return val; // keyword + + for (var i = 0; i < val.length; i++) + val[i] = Math.round(val[i]); + return val; + } + })(func); +} + + +/* Converter does lazy conversion and caching */ +var Converter = function() { + this.convs = {}; +}; + +/* Either get the values for a space or + set the values for a space, depending on args */ +Converter.prototype.routeSpace = function(space, args) { + var values = args[0]; + if (values === undefined) { + // color.rgb() + return this.getValues(space); + } + // color.rgb(10, 10, 10) + if (typeof values == "number") { + values = Array.prototype.slice.call(args); + } + + return this.setValues(space, values); +}; + +/* Set the values for a space, invalidating cache */ +Converter.prototype.setValues = function(space, values) { + this.space = space; + this.convs = {}; + this.convs[space] = values; + return this; +}; + +/* Get the values for a space. If there's already + a conversion for the space, fetch it, otherwise + compute it */ +Converter.prototype.getValues = function(space) { + var vals = this.convs[space]; + if (!vals) { + var fspace = this.space, + from = this.convs[fspace]; + vals = convert[fspace][space](from); + + this.convs[space] = vals; + } + return vals; +}; + +["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) { + Converter.prototype[space] = function(vals) { + return this.routeSpace(space, arguments); + }; +}); + +var colorConvert = convert; + +var colorName = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; + +/* MIT license */ + + +var colorString = { + getRgba: getRgba, + getHsla: getHsla, + getRgb: getRgb, + getHsl: getHsl, + getHwb: getHwb, + getAlpha: getAlpha, + + hexString: hexString, + rgbString: rgbString, + rgbaString: rgbaString, + percentString: percentString, + percentaString: percentaString, + hslString: hslString, + hslaString: hslaString, + hwbString: hwbString, + keyword: keyword +}; + +function getRgba(string) { + if (!string) { + return; + } + var abbr = /^#([a-fA-F0-9]{3,4})$/i, + hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i, + rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i, + per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i, + keyword = /(\w+)/; + + var rgb = [0, 0, 0], + a = 1, + match = string.match(abbr), + hexAlpha = ""; + if (match) { + match = match[1]; + hexAlpha = match[3]; + for (var i = 0; i < rgb.length; i++) { + rgb[i] = parseInt(match[i] + match[i], 16); + } + if (hexAlpha) { + a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100; + } + } + else if (match = string.match(hex)) { + hexAlpha = match[2]; + match = match[1]; + for (var i = 0; i < rgb.length; i++) { + rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16); + } + if (hexAlpha) { + a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100; + } + } + else if (match = string.match(rgba)) { + for (var i = 0; i < rgb.length; i++) { + rgb[i] = parseInt(match[i + 1]); + } + a = parseFloat(match[4]); + } + else if (match = string.match(per)) { + for (var i = 0; i < rgb.length; i++) { + rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55); + } + a = parseFloat(match[4]); + } + else if (match = string.match(keyword)) { + if (match[1] == "transparent") { + return [0, 0, 0, 0]; + } + rgb = colorName[match[1]]; + if (!rgb) { + return; + } + } + + for (var i = 0; i < rgb.length; i++) { + rgb[i] = scale(rgb[i], 0, 255); + } + if (!a && a != 0) { + a = 1; + } + else { + a = scale(a, 0, 1); + } + rgb[3] = a; + return rgb; +} + +function getHsla(string) { + if (!string) { + return; + } + var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/; + var match = string.match(hsl); + if (match) { + var alpha = parseFloat(match[4]); + var h = scale(parseInt(match[1]), 0, 360), + s = scale(parseFloat(match[2]), 0, 100), + l = scale(parseFloat(match[3]), 0, 100), + a = scale(isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, s, l, a]; + } +} + +function getHwb(string) { + if (!string) { + return; + } + var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/; + var match = string.match(hwb); + if (match) { + var alpha = parseFloat(match[4]); + var h = scale(parseInt(match[1]), 0, 360), + w = scale(parseFloat(match[2]), 0, 100), + b = scale(parseFloat(match[3]), 0, 100), + a = scale(isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, w, b, a]; + } +} + +function getRgb(string) { + var rgba = getRgba(string); + return rgba && rgba.slice(0, 3); +} + +function getHsl(string) { + var hsla = getHsla(string); + return hsla && hsla.slice(0, 3); +} + +function getAlpha(string) { + var vals = getRgba(string); + if (vals) { + return vals[3]; + } + else if (vals = getHsla(string)) { + return vals[3]; + } + else if (vals = getHwb(string)) { + return vals[3]; + } +} + +// generators +function hexString(rgba, a) { + var a = (a !== undefined && rgba.length === 3) ? a : rgba[3]; + return "#" + hexDouble(rgba[0]) + + hexDouble(rgba[1]) + + hexDouble(rgba[2]) + + ( + (a >= 0 && a < 1) + ? hexDouble(Math.round(a * 255)) + : "" + ); +} + +function rgbString(rgba, alpha) { + if (alpha < 1 || (rgba[3] && rgba[3] < 1)) { + return rgbaString(rgba, alpha); + } + return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")"; +} + +function rgbaString(rgba, alpha) { + if (alpha === undefined) { + alpha = (rgba[3] !== undefined ? rgba[3] : 1); + } + return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + + ", " + alpha + ")"; +} + +function percentString(rgba, alpha) { + if (alpha < 1 || (rgba[3] && rgba[3] < 1)) { + return percentaString(rgba, alpha); + } + var r = Math.round(rgba[0]/255 * 100), + g = Math.round(rgba[1]/255 * 100), + b = Math.round(rgba[2]/255 * 100); + + return "rgb(" + r + "%, " + g + "%, " + b + "%)"; +} + +function percentaString(rgba, alpha) { + var r = Math.round(rgba[0]/255 * 100), + g = Math.round(rgba[1]/255 * 100), + b = Math.round(rgba[2]/255 * 100); + return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")"; +} + +function hslString(hsla, alpha) { + if (alpha < 1 || (hsla[3] && hsla[3] < 1)) { + return hslaString(hsla, alpha); + } + return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)"; +} + +function hslaString(hsla, alpha) { + if (alpha === undefined) { + alpha = (hsla[3] !== undefined ? hsla[3] : 1); + } + return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, " + + alpha + ")"; +} + +// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax +// (hwb have alpha optional & 1 is default value) +function hwbString(hwb, alpha) { + if (alpha === undefined) { + alpha = (hwb[3] !== undefined ? hwb[3] : 1); + } + return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%" + + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")"; +} + +function keyword(rgb) { + return reverseNames[rgb.slice(0, 3)]; +} + +// helpers +function scale(num, min, max) { + return Math.min(Math.max(min, num), max); +} + +function hexDouble(num) { + var str = num.toString(16).toUpperCase(); + return (str.length < 2) ? "0" + str : str; +} + + +//create a list of reverse color names +var reverseNames = {}; +for (var name in colorName) { + reverseNames[colorName[name]] = name; +} + +/* MIT license */ + + + +var Color = function (obj) { + if (obj instanceof Color) { + return obj; + } + if (!(this instanceof Color)) { + return new Color(obj); + } + + this.valid = false; + this.values = { + rgb: [0, 0, 0], + hsl: [0, 0, 0], + hsv: [0, 0, 0], + hwb: [0, 0, 0], + cmyk: [0, 0, 0, 0], + alpha: 1 + }; + + // parse Color() argument + var vals; + if (typeof obj === 'string') { + vals = colorString.getRgba(obj); + if (vals) { + this.setValues('rgb', vals); + } else if (vals = colorString.getHsla(obj)) { + this.setValues('hsl', vals); + } else if (vals = colorString.getHwb(obj)) { + this.setValues('hwb', vals); + } + } else if (typeof obj === 'object') { + vals = obj; + if (vals.r !== undefined || vals.red !== undefined) { + this.setValues('rgb', vals); + } else if (vals.l !== undefined || vals.lightness !== undefined) { + this.setValues('hsl', vals); + } else if (vals.v !== undefined || vals.value !== undefined) { + this.setValues('hsv', vals); + } else if (vals.w !== undefined || vals.whiteness !== undefined) { + this.setValues('hwb', vals); + } else if (vals.c !== undefined || vals.cyan !== undefined) { + this.setValues('cmyk', vals); + } + } +}; + +Color.prototype = { + isValid: function () { + return this.valid; + }, + rgb: function () { + return this.setSpace('rgb', arguments); + }, + hsl: function () { + return this.setSpace('hsl', arguments); + }, + hsv: function () { + return this.setSpace('hsv', arguments); + }, + hwb: function () { + return this.setSpace('hwb', arguments); + }, + cmyk: function () { + return this.setSpace('cmyk', arguments); + }, + + rgbArray: function () { + return this.values.rgb; + }, + hslArray: function () { + return this.values.hsl; + }, + hsvArray: function () { + return this.values.hsv; + }, + hwbArray: function () { + var values = this.values; + if (values.alpha !== 1) { + return values.hwb.concat([values.alpha]); + } + return values.hwb; + }, + cmykArray: function () { + return this.values.cmyk; + }, + rgbaArray: function () { + var values = this.values; + return values.rgb.concat([values.alpha]); + }, + hslaArray: function () { + var values = this.values; + return values.hsl.concat([values.alpha]); + }, + alpha: function (val) { + if (val === undefined) { + return this.values.alpha; + } + this.setValues('alpha', val); + return this; + }, + + red: function (val) { + return this.setChannel('rgb', 0, val); + }, + green: function (val) { + return this.setChannel('rgb', 1, val); + }, + blue: function (val) { + return this.setChannel('rgb', 2, val); + }, + hue: function (val) { + if (val) { + val %= 360; + val = val < 0 ? 360 + val : val; + } + return this.setChannel('hsl', 0, val); + }, + saturation: function (val) { + return this.setChannel('hsl', 1, val); + }, + lightness: function (val) { + return this.setChannel('hsl', 2, val); + }, + saturationv: function (val) { + return this.setChannel('hsv', 1, val); + }, + whiteness: function (val) { + return this.setChannel('hwb', 1, val); + }, + blackness: function (val) { + return this.setChannel('hwb', 2, val); + }, + value: function (val) { + return this.setChannel('hsv', 2, val); + }, + cyan: function (val) { + return this.setChannel('cmyk', 0, val); + }, + magenta: function (val) { + return this.setChannel('cmyk', 1, val); + }, + yellow: function (val) { + return this.setChannel('cmyk', 2, val); + }, + black: function (val) { + return this.setChannel('cmyk', 3, val); + }, + + hexString: function () { + return colorString.hexString(this.values.rgb); + }, + rgbString: function () { + return colorString.rgbString(this.values.rgb, this.values.alpha); + }, + rgbaString: function () { + return colorString.rgbaString(this.values.rgb, this.values.alpha); + }, + percentString: function () { + return colorString.percentString(this.values.rgb, this.values.alpha); + }, + hslString: function () { + return colorString.hslString(this.values.hsl, this.values.alpha); + }, + hslaString: function () { + return colorString.hslaString(this.values.hsl, this.values.alpha); + }, + hwbString: function () { + return colorString.hwbString(this.values.hwb, this.values.alpha); + }, + keyword: function () { + return colorString.keyword(this.values.rgb, this.values.alpha); + }, + + rgbNumber: function () { + var rgb = this.values.rgb; + return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]; + }, + + luminosity: function () { + // http://www.w3.org/TR/WCAG20/#relativeluminancedef + var rgb = this.values.rgb; + var lum = []; + for (var i = 0; i < rgb.length; i++) { + var chan = rgb[i] / 255; + lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4); + } + return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; + }, + + contrast: function (color2) { + // http://www.w3.org/TR/WCAG20/#contrast-ratiodef + var lum1 = this.luminosity(); + var lum2 = color2.luminosity(); + if (lum1 > lum2) { + return (lum1 + 0.05) / (lum2 + 0.05); + } + return (lum2 + 0.05) / (lum1 + 0.05); + }, + + level: function (color2) { + var contrastRatio = this.contrast(color2); + if (contrastRatio >= 7.1) { + return 'AAA'; + } + + return (contrastRatio >= 4.5) ? 'AA' : ''; + }, + + dark: function () { + // YIQ equation from http://24ways.org/2010/calculating-color-contrast + var rgb = this.values.rgb; + var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000; + return yiq < 128; + }, + + light: function () { + return !this.dark(); + }, + + negate: function () { + var rgb = []; + for (var i = 0; i < 3; i++) { + rgb[i] = 255 - this.values.rgb[i]; + } + this.setValues('rgb', rgb); + return this; + }, + + lighten: function (ratio) { + var hsl = this.values.hsl; + hsl[2] += hsl[2] * ratio; + this.setValues('hsl', hsl); + return this; + }, + + darken: function (ratio) { + var hsl = this.values.hsl; + hsl[2] -= hsl[2] * ratio; + this.setValues('hsl', hsl); + return this; + }, + + saturate: function (ratio) { + var hsl = this.values.hsl; + hsl[1] += hsl[1] * ratio; + this.setValues('hsl', hsl); + return this; + }, + + desaturate: function (ratio) { + var hsl = this.values.hsl; + hsl[1] -= hsl[1] * ratio; + this.setValues('hsl', hsl); + return this; + }, + + whiten: function (ratio) { + var hwb = this.values.hwb; + hwb[1] += hwb[1] * ratio; + this.setValues('hwb', hwb); + return this; + }, + + blacken: function (ratio) { + var hwb = this.values.hwb; + hwb[2] += hwb[2] * ratio; + this.setValues('hwb', hwb); + return this; + }, + + greyscale: function () { + var rgb = this.values.rgb; + // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale + var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; + this.setValues('rgb', [val, val, val]); + return this; + }, + + clearer: function (ratio) { + var alpha = this.values.alpha; + this.setValues('alpha', alpha - (alpha * ratio)); + return this; + }, + + opaquer: function (ratio) { + var alpha = this.values.alpha; + this.setValues('alpha', alpha + (alpha * ratio)); + return this; + }, + + rotate: function (degrees) { + var hsl = this.values.hsl; + var hue = (hsl[0] + degrees) % 360; + hsl[0] = hue < 0 ? 360 + hue : hue; + this.setValues('hsl', hsl); + return this; + }, + + /** + * Ported from sass implementation in C + * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209 + */ + mix: function (mixinColor, weight) { + var color1 = this; + var color2 = mixinColor; + var p = weight === undefined ? 0.5 : weight; + + var w = 2 * p - 1; + var a = color1.alpha() - color2.alpha(); + + var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; + var w2 = 1 - w1; + + return this + .rgb( + w1 * color1.red() + w2 * color2.red(), + w1 * color1.green() + w2 * color2.green(), + w1 * color1.blue() + w2 * color2.blue() + ) + .alpha(color1.alpha() * p + color2.alpha() * (1 - p)); + }, + + toJSON: function () { + return this.rgb(); + }, + + clone: function () { + // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify, + // making the final build way to big to embed in Chart.js. So let's do it manually, + // assuming that values to clone are 1 dimension arrays containing only numbers, + // except 'alpha' which is a number. + var result = new Color(); + var source = this.values; + var target = result.values; + var value, type; + + for (var prop in source) { + if (source.hasOwnProperty(prop)) { + value = source[prop]; + type = ({}).toString.call(value); + if (type === '[object Array]') { + target[prop] = value.slice(0); + } else if (type === '[object Number]') { + target[prop] = value; + } else { + console.error('unexpected color value:', value); + } + } + } + + return result; + } +}; + +Color.prototype.spaces = { + rgb: ['red', 'green', 'blue'], + hsl: ['hue', 'saturation', 'lightness'], + hsv: ['hue', 'saturation', 'value'], + hwb: ['hue', 'whiteness', 'blackness'], + cmyk: ['cyan', 'magenta', 'yellow', 'black'] +}; + +Color.prototype.maxes = { + rgb: [255, 255, 255], + hsl: [360, 100, 100], + hsv: [360, 100, 100], + hwb: [360, 100, 100], + cmyk: [100, 100, 100, 100] +}; + +Color.prototype.getValues = function (space) { + var values = this.values; + var vals = {}; + + for (var i = 0; i < space.length; i++) { + vals[space.charAt(i)] = values[space][i]; + } + + if (values.alpha !== 1) { + vals.a = values.alpha; + } + + // {r: 255, g: 255, b: 255, a: 0.4} + return vals; +}; + +Color.prototype.setValues = function (space, vals) { + var values = this.values; + var spaces = this.spaces; + var maxes = this.maxes; + var alpha = 1; + var i; + + this.valid = true; + + if (space === 'alpha') { + alpha = vals; + } else if (vals.length) { + // [10, 10, 10] + values[space] = vals.slice(0, space.length); + alpha = vals[space.length]; + } else if (vals[space.charAt(0)] !== undefined) { + // {r: 10, g: 10, b: 10} + for (i = 0; i < space.length; i++) { + values[space][i] = vals[space.charAt(i)]; + } + + alpha = vals.a; + } else if (vals[spaces[space][0]] !== undefined) { + // {red: 10, green: 10, blue: 10} + var chans = spaces[space]; + + for (i = 0; i < space.length; i++) { + values[space][i] = vals[chans[i]]; + } + + alpha = vals.alpha; + } + + values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha))); + + if (space === 'alpha') { + return false; + } + + var capped; + + // cap values of the space prior converting all values + for (i = 0; i < space.length; i++) { + capped = Math.max(0, Math.min(maxes[space][i], values[space][i])); + values[space][i] = Math.round(capped); + } + + // convert to all the other color spaces + for (var sname in spaces) { + if (sname !== space) { + values[sname] = colorConvert[space][sname](values[space]); + } + } + + return true; +}; + +Color.prototype.setSpace = function (space, args) { + var vals = args[0]; + + if (vals === undefined) { + // color.rgb() + return this.getValues(space); + } + + // color.rgb(10, 10, 10) + if (typeof vals === 'number') { + vals = Array.prototype.slice.call(args); + } + + this.setValues(space, vals); + return this; +}; + +Color.prototype.setChannel = function (space, index, val) { + var svalues = this.values[space]; + if (val === undefined) { + // color.red() + return svalues[index]; + } else if (val === svalues[index]) { + // color.red(color.red()) + return this; + } + + // color.red(100) + svalues[index] = val; + this.setValues(space, svalues); + + return this; +}; + +if (typeof window !== 'undefined') { + window.Color = Color; +} + +var chartjsColor = Color; + +/** + * @namespace Chart.helpers + */ +var helpers = { + /** + * An empty function that can be used, for example, for optional callback. + */ + noop: function() {}, + + /** + * Returns a unique id, sequentially generated from a global variable. + * @returns {number} + * @function + */ + uid: (function() { + var id = 0; + return function() { + return id++; + }; + }()), + + /** + * Returns true if `value` is neither null nor undefined, else returns false. + * @param {*} value - The value to test. + * @returns {boolean} + * @since 2.7.0 + */ + isNullOrUndef: function(value) { + return value === null || typeof value === 'undefined'; + }, + + /** + * Returns true if `value` is an array (including typed arrays), else returns false. + * @param {*} value - The value to test. + * @returns {boolean} + * @function + */ + isArray: function(value) { + if (Array.isArray && Array.isArray(value)) { + return true; + } + var type = Object.prototype.toString.call(value); + if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') { + return true; + } + return false; + }, + + /** + * Returns true if `value` is an object (excluding null), else returns false. + * @param {*} value - The value to test. + * @returns {boolean} + * @since 2.7.0 + */ + isObject: function(value) { + return value !== null && Object.prototype.toString.call(value) === '[object Object]'; + }, + + /** + * Returns true if `value` is a finite number, else returns false + * @param {*} value - The value to test. + * @returns {boolean} + */ + isFinite: function(value) { + return (typeof value === 'number' || value instanceof Number) && isFinite(value); + }, + + /** + * Returns `value` if defined, else returns `defaultValue`. + * @param {*} value - The value to return if defined. + * @param {*} defaultValue - The value to return if `value` is undefined. + * @returns {*} + */ + valueOrDefault: function(value, defaultValue) { + return typeof value === 'undefined' ? defaultValue : value; + }, + + /** + * Returns value at the given `index` in array if defined, else returns `defaultValue`. + * @param {Array} value - The array to lookup for value at `index`. + * @param {number} index - The index in `value` to lookup for value. + * @param {*} defaultValue - The value to return if `value[index]` is undefined. + * @returns {*} + */ + valueAtIndexOrDefault: function(value, index, defaultValue) { + return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue); + }, + + /** + * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the + * value returned by `fn`. If `fn` is not a function, this method returns undefined. + * @param {function} fn - The function to call. + * @param {Array|undefined|null} args - The arguments with which `fn` should be called. + * @param {object} [thisArg] - The value of `this` provided for the call to `fn`. + * @returns {*} + */ + callback: function(fn, args, thisArg) { + if (fn && typeof fn.call === 'function') { + return fn.apply(thisArg, args); + } + }, + + /** + * Note(SB) for performance sake, this method should only be used when loopable type + * is unknown or in none intensive code (not called often and small loopable). Else + * it's preferable to use a regular for() loop and save extra function calls. + * @param {object|Array} loopable - The object or array to be iterated. + * @param {function} fn - The function to call for each item. + * @param {object} [thisArg] - The value of `this` provided for the call to `fn`. + * @param {boolean} [reverse] - If true, iterates backward on the loopable. + */ + each: function(loopable, fn, thisArg, reverse) { + var i, len, keys; + if (helpers.isArray(loopable)) { + len = loopable.length; + if (reverse) { + for (i = len - 1; i >= 0; i--) { + fn.call(thisArg, loopable[i], i); + } + } else { + for (i = 0; i < len; i++) { + fn.call(thisArg, loopable[i], i); + } + } + } else if (helpers.isObject(loopable)) { + keys = Object.keys(loopable); + len = keys.length; + for (i = 0; i < len; i++) { + fn.call(thisArg, loopable[keys[i]], keys[i]); + } + } + }, + + /** + * Returns true if the `a0` and `a1` arrays have the same content, else returns false. + * @see https://stackoverflow.com/a/14853974 + * @param {Array} a0 - The array to compare + * @param {Array} a1 - The array to compare + * @returns {boolean} + */ + arrayEquals: function(a0, a1) { + var i, ilen, v0, v1; + + if (!a0 || !a1 || a0.length !== a1.length) { + return false; + } + + for (i = 0, ilen = a0.length; i < ilen; ++i) { + v0 = a0[i]; + v1 = a1[i]; + + if (v0 instanceof Array && v1 instanceof Array) { + if (!helpers.arrayEquals(v0, v1)) { + return false; + } + } else if (v0 !== v1) { + // NOTE: two different object instances will never be equal: {x:20} != {x:20} + return false; + } + } + + return true; + }, + + /** + * Returns a deep copy of `source` without keeping references on objects and arrays. + * @param {*} source - The value to clone. + * @returns {*} + */ + clone: function(source) { + if (helpers.isArray(source)) { + return source.map(helpers.clone); + } + + if (helpers.isObject(source)) { + var target = {}; + var keys = Object.keys(source); + var klen = keys.length; + var k = 0; + + for (; k < klen; ++k) { + target[keys[k]] = helpers.clone(source[keys[k]]); + } + + return target; + } + + return source; + }, + + /** + * The default merger when Chart.helpers.merge is called without merger option. + * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback. + * @private + */ + _merger: function(key, target, source, options) { + var tval = target[key]; + var sval = source[key]; + + if (helpers.isObject(tval) && helpers.isObject(sval)) { + helpers.merge(tval, sval, options); + } else { + target[key] = helpers.clone(sval); + } + }, + + /** + * Merges source[key] in target[key] only if target[key] is undefined. + * @private + */ + _mergerIf: function(key, target, source) { + var tval = target[key]; + var sval = source[key]; + + if (helpers.isObject(tval) && helpers.isObject(sval)) { + helpers.mergeIf(tval, sval); + } else if (!target.hasOwnProperty(key)) { + target[key] = helpers.clone(sval); + } + }, + + /** + * Recursively deep copies `source` properties into `target` with the given `options`. + * IMPORTANT: `target` is not cloned and will be updated with `source` properties. + * @param {object} target - The target object in which all sources are merged into. + * @param {object|object[]} source - Object(s) to merge into `target`. + * @param {object} [options] - Merging options: + * @param {function} [options.merger] - The merge method (key, target, source, options) + * @returns {object} The `target` object. + */ + merge: function(target, source, options) { + var sources = helpers.isArray(source) ? source : [source]; + var ilen = sources.length; + var merge, i, keys, klen, k; + + if (!helpers.isObject(target)) { + return target; + } + + options = options || {}; + merge = options.merger || helpers._merger; + + for (i = 0; i < ilen; ++i) { + source = sources[i]; + if (!helpers.isObject(source)) { + continue; + } + + keys = Object.keys(source); + for (k = 0, klen = keys.length; k < klen; ++k) { + merge(keys[k], target, source, options); + } + } + + return target; + }, + + /** + * Recursively deep copies `source` properties into `target` *only* if not defined in target. + * IMPORTANT: `target` is not cloned and will be updated with `source` properties. + * @param {object} target - The target object in which all sources are merged into. + * @param {object|object[]} source - Object(s) to merge into `target`. + * @returns {object} The `target` object. + */ + mergeIf: function(target, source) { + return helpers.merge(target, source, {merger: helpers._mergerIf}); + }, + + /** + * Applies the contents of two or more objects together into the first object. + * @param {object} target - The target object in which all objects are merged into. + * @param {object} arg1 - Object containing additional properties to merge in target. + * @param {object} argN - Additional objects containing properties to merge in target. + * @returns {object} The `target` object. + */ + extend: function(target) { + var setFn = function(value, key) { + target[key] = value; + }; + for (var i = 1, ilen = arguments.length; i < ilen; ++i) { + helpers.each(arguments[i], setFn); + } + return target; + }, + + /** + * Basic javascript inheritance based on the model created in Backbone.js + */ + inherits: function(extensions) { + var me = this; + var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() { + return me.apply(this, arguments); + }; + + var Surrogate = function() { + this.constructor = ChartElement; + }; + + Surrogate.prototype = me.prototype; + ChartElement.prototype = new Surrogate(); + ChartElement.extend = helpers.inherits; + + if (extensions) { + helpers.extend(ChartElement.prototype, extensions); + } + + ChartElement.__super__ = me.prototype; + return ChartElement; + } +}; + +var helpers_core = helpers; + +// DEPRECATIONS + +/** + * Provided for backward compatibility, use Chart.helpers.callback instead. + * @function Chart.helpers.callCallback + * @deprecated since version 2.6.0 + * @todo remove at version 3 + * @private + */ +helpers.callCallback = helpers.callback; + +/** + * Provided for backward compatibility, use Array.prototype.indexOf instead. + * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+ + * @function Chart.helpers.indexOf + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers.indexOf = function(array, item, fromIndex) { + return Array.prototype.indexOf.call(array, item, fromIndex); +}; + +/** + * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead. + * @function Chart.helpers.getValueOrDefault + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers.getValueOrDefault = helpers.valueOrDefault; + +/** + * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead. + * @function Chart.helpers.getValueAtIndexOrDefault + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault; + +/** + * Easing functions adapted from Robert Penner's easing equations. + * @namespace Chart.helpers.easingEffects + * @see http://www.robertpenner.com/easing/ + */ +var effects = { + linear: function(t) { + return t; + }, + + easeInQuad: function(t) { + return t * t; + }, + + easeOutQuad: function(t) { + return -t * (t - 2); + }, + + easeInOutQuad: function(t) { + if ((t /= 0.5) < 1) { + return 0.5 * t * t; + } + return -0.5 * ((--t) * (t - 2) - 1); + }, + + easeInCubic: function(t) { + return t * t * t; + }, + + easeOutCubic: function(t) { + return (t = t - 1) * t * t + 1; + }, + + easeInOutCubic: function(t) { + if ((t /= 0.5) < 1) { + return 0.5 * t * t * t; + } + return 0.5 * ((t -= 2) * t * t + 2); + }, + + easeInQuart: function(t) { + return t * t * t * t; + }, + + easeOutQuart: function(t) { + return -((t = t - 1) * t * t * t - 1); + }, + + easeInOutQuart: function(t) { + if ((t /= 0.5) < 1) { + return 0.5 * t * t * t * t; + } + return -0.5 * ((t -= 2) * t * t * t - 2); + }, + + easeInQuint: function(t) { + return t * t * t * t * t; + }, + + easeOutQuint: function(t) { + return (t = t - 1) * t * t * t * t + 1; + }, + + easeInOutQuint: function(t) { + if ((t /= 0.5) < 1) { + return 0.5 * t * t * t * t * t; + } + return 0.5 * ((t -= 2) * t * t * t * t + 2); + }, + + easeInSine: function(t) { + return -Math.cos(t * (Math.PI / 2)) + 1; + }, + + easeOutSine: function(t) { + return Math.sin(t * (Math.PI / 2)); + }, + + easeInOutSine: function(t) { + return -0.5 * (Math.cos(Math.PI * t) - 1); + }, + + easeInExpo: function(t) { + return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)); + }, + + easeOutExpo: function(t) { + return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1; + }, + + easeInOutExpo: function(t) { + if (t === 0) { + return 0; + } + if (t === 1) { + return 1; + } + if ((t /= 0.5) < 1) { + return 0.5 * Math.pow(2, 10 * (t - 1)); + } + return 0.5 * (-Math.pow(2, -10 * --t) + 2); + }, + + easeInCirc: function(t) { + if (t >= 1) { + return t; + } + return -(Math.sqrt(1 - t * t) - 1); + }, + + easeOutCirc: function(t) { + return Math.sqrt(1 - (t = t - 1) * t); + }, + + easeInOutCirc: function(t) { + if ((t /= 0.5) < 1) { + return -0.5 * (Math.sqrt(1 - t * t) - 1); + } + return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1); + }, + + easeInElastic: function(t) { + var s = 1.70158; + var p = 0; + var a = 1; + if (t === 0) { + return 0; + } + if (t === 1) { + return 1; + } + if (!p) { + p = 0.3; + } + if (a < 1) { + a = 1; + s = p / 4; + } else { + s = p / (2 * Math.PI) * Math.asin(1 / a); + } + return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p)); + }, + + easeOutElastic: function(t) { + var s = 1.70158; + var p = 0; + var a = 1; + if (t === 0) { + return 0; + } + if (t === 1) { + return 1; + } + if (!p) { + p = 0.3; + } + if (a < 1) { + a = 1; + s = p / 4; + } else { + s = p / (2 * Math.PI) * Math.asin(1 / a); + } + return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1; + }, + + easeInOutElastic: function(t) { + var s = 1.70158; + var p = 0; + var a = 1; + if (t === 0) { + return 0; + } + if ((t /= 0.5) === 2) { + return 1; + } + if (!p) { + p = 0.45; + } + if (a < 1) { + a = 1; + s = p / 4; + } else { + s = p / (2 * Math.PI) * Math.asin(1 / a); + } + if (t < 1) { + return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p)); + } + return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1; + }, + easeInBack: function(t) { + var s = 1.70158; + return t * t * ((s + 1) * t - s); + }, + + easeOutBack: function(t) { + var s = 1.70158; + return (t = t - 1) * t * ((s + 1) * t + s) + 1; + }, + + easeInOutBack: function(t) { + var s = 1.70158; + if ((t /= 0.5) < 1) { + return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s)); + } + return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2); + }, + + easeInBounce: function(t) { + return 1 - effects.easeOutBounce(1 - t); + }, + + easeOutBounce: function(t) { + if (t < (1 / 2.75)) { + return 7.5625 * t * t; + } + if (t < (2 / 2.75)) { + return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75; + } + if (t < (2.5 / 2.75)) { + return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375; + } + return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375; + }, + + easeInOutBounce: function(t) { + if (t < 0.5) { + return effects.easeInBounce(t * 2) * 0.5; + } + return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5; + } +}; + +var helpers_easing = { + effects: effects +}; + +// DEPRECATIONS + +/** + * Provided for backward compatibility, use Chart.helpers.easing.effects instead. + * @function Chart.helpers.easingEffects + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers_core.easingEffects = effects; + +var PI = Math.PI; +var RAD_PER_DEG = PI / 180; +var DOUBLE_PI = PI * 2; +var HALF_PI = PI / 2; +var QUARTER_PI = PI / 4; +var TWO_THIRDS_PI = PI * 2 / 3; + +/** + * @namespace Chart.helpers.canvas + */ +var exports$1 = { + /** + * Clears the entire canvas associated to the given `chart`. + * @param {Chart} chart - The chart for which to clear the canvas. + */ + clear: function(chart) { + chart.ctx.clearRect(0, 0, chart.width, chart.height); + }, + + /** + * Creates a "path" for a rectangle with rounded corners at position (x, y) with a + * given size (width, height) and the same `radius` for all corners. + * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context. + * @param {number} x - The x axis of the coordinate for the rectangle starting point. + * @param {number} y - The y axis of the coordinate for the rectangle starting point. + * @param {number} width - The rectangle's width. + * @param {number} height - The rectangle's height. + * @param {number} radius - The rounded amount (in pixels) for the four corners. + * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object? + */ + roundedRect: function(ctx, x, y, width, height, radius) { + if (radius) { + var r = Math.min(radius, height / 2, width / 2); + var left = x + r; + var top = y + r; + var right = x + width - r; + var bottom = y + height - r; + + ctx.moveTo(x, top); + if (left < right && top < bottom) { + ctx.arc(left, top, r, -PI, -HALF_PI); + ctx.arc(right, top, r, -HALF_PI, 0); + ctx.arc(right, bottom, r, 0, HALF_PI); + ctx.arc(left, bottom, r, HALF_PI, PI); + } else if (left < right) { + ctx.moveTo(left, y); + ctx.arc(right, top, r, -HALF_PI, HALF_PI); + ctx.arc(left, top, r, HALF_PI, PI + HALF_PI); + } else if (top < bottom) { + ctx.arc(left, top, r, -PI, 0); + ctx.arc(left, bottom, r, 0, PI); + } else { + ctx.arc(left, top, r, -PI, PI); + } + ctx.closePath(); + ctx.moveTo(x, y); + } else { + ctx.rect(x, y, width, height); + } + }, + + drawPoint: function(ctx, style, radius, x, y, rotation) { + var type, xOffset, yOffset, size, cornerRadius; + var rad = (rotation || 0) * RAD_PER_DEG; + + if (style && typeof style === 'object') { + type = style.toString(); + if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') { + ctx.drawImage(style, x - style.width / 2, y - style.height / 2, style.width, style.height); + return; + } + } + + if (isNaN(radius) || radius <= 0) { + return; + } + + ctx.beginPath(); + + switch (style) { + // Default includes circle + default: + ctx.arc(x, y, radius, 0, DOUBLE_PI); + ctx.closePath(); + break; + case 'triangle': + ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); + rad += TWO_THIRDS_PI; + ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); + rad += TWO_THIRDS_PI; + ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); + ctx.closePath(); + break; + case 'rectRounded': + // NOTE: the rounded rect implementation changed to use `arc` instead of + // `quadraticCurveTo` since it generates better results when rect is + // almost a circle. 0.516 (instead of 0.5) produces results with visually + // closer proportion to the previous impl and it is inscribed in the + // circle with `radius`. For more details, see the following PRs: + // https://github.com/chartjs/Chart.js/issues/5597 + // https://github.com/chartjs/Chart.js/issues/5858 + cornerRadius = radius * 0.516; + size = radius - cornerRadius; + xOffset = Math.cos(rad + QUARTER_PI) * size; + yOffset = Math.sin(rad + QUARTER_PI) * size; + ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI); + ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad); + ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI); + ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI); + ctx.closePath(); + break; + case 'rect': + if (!rotation) { + size = Math.SQRT1_2 * radius; + ctx.rect(x - size, y - size, 2 * size, 2 * size); + break; + } + rad += QUARTER_PI; + /* falls through */ + case 'rectRot': + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + yOffset, y - xOffset); + ctx.lineTo(x + xOffset, y + yOffset); + ctx.lineTo(x - yOffset, y + xOffset); + ctx.closePath(); + break; + case 'crossRot': + rad += QUARTER_PI; + /* falls through */ + case 'cross': + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + xOffset, y + yOffset); + ctx.moveTo(x + yOffset, y - xOffset); + ctx.lineTo(x - yOffset, y + xOffset); + break; + case 'star': + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + xOffset, y + yOffset); + ctx.moveTo(x + yOffset, y - xOffset); + ctx.lineTo(x - yOffset, y + xOffset); + rad += QUARTER_PI; + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + xOffset, y + yOffset); + ctx.moveTo(x + yOffset, y - xOffset); + ctx.lineTo(x - yOffset, y + xOffset); + break; + case 'line': + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + xOffset, y + yOffset); + break; + case 'dash': + ctx.moveTo(x, y); + ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius); + break; + } + + ctx.fill(); + ctx.stroke(); + }, + + /** + * Returns true if the point is inside the rectangle + * @param {object} point - The point to test + * @param {object} area - The rectangle + * @returns {boolean} + * @private + */ + _isPointInArea: function(point, area) { + var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error. + + return point.x > area.left - epsilon && point.x < area.right + epsilon && + point.y > area.top - epsilon && point.y < area.bottom + epsilon; + }, + + clipArea: function(ctx, area) { + ctx.save(); + ctx.beginPath(); + ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); + ctx.clip(); + }, + + unclipArea: function(ctx) { + ctx.restore(); + }, + + lineTo: function(ctx, previous, target, flip) { + var stepped = target.steppedLine; + if (stepped) { + if (stepped === 'middle') { + var midpoint = (previous.x + target.x) / 2.0; + ctx.lineTo(midpoint, flip ? target.y : previous.y); + ctx.lineTo(midpoint, flip ? previous.y : target.y); + } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) { + ctx.lineTo(previous.x, target.y); + } else { + ctx.lineTo(target.x, previous.y); + } + ctx.lineTo(target.x, target.y); + return; + } + + if (!target.tension) { + ctx.lineTo(target.x, target.y); + return; + } + + ctx.bezierCurveTo( + flip ? previous.controlPointPreviousX : previous.controlPointNextX, + flip ? previous.controlPointPreviousY : previous.controlPointNextY, + flip ? target.controlPointNextX : target.controlPointPreviousX, + flip ? target.controlPointNextY : target.controlPointPreviousY, + target.x, + target.y); + } +}; + +var helpers_canvas = exports$1; + +// DEPRECATIONS + +/** + * Provided for backward compatibility, use Chart.helpers.canvas.clear instead. + * @namespace Chart.helpers.clear + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers_core.clear = exports$1.clear; + +/** + * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead. + * @namespace Chart.helpers.drawRoundedRectangle + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers_core.drawRoundedRectangle = function(ctx) { + ctx.beginPath(); + exports$1.roundedRect.apply(exports$1, arguments); +}; + +var defaults = { + /** + * @private + */ + _set: function(scope, values) { + return helpers_core.merge(this[scope] || (this[scope] = {}), values); + } +}; + +defaults._set('global', { + defaultColor: 'rgba(0,0,0,0.1)', + defaultFontColor: '#666', + defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", + defaultFontSize: 12, + defaultFontStyle: 'normal', + defaultLineHeight: 1.2, + showLines: true +}); + +var core_defaults = defaults; + +var valueOrDefault = helpers_core.valueOrDefault; + +/** + * Converts the given font object into a CSS font string. + * @param {object} font - A font object. + * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font + * @private + */ +function toFontString(font) { + if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) { + return null; + } + + return (font.style ? font.style + ' ' : '') + + (font.weight ? font.weight + ' ' : '') + + font.size + 'px ' + + font.family; +} + +/** + * @alias Chart.helpers.options + * @namespace + */ +var helpers_options = { + /** + * Converts the given line height `value` in pixels for a specific font `size`. + * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em'). + * @param {number} size - The font size (in pixels) used to resolve relative `value`. + * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid). + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height + * @since 2.7.0 + */ + toLineHeight: function(value, size) { + var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/); + if (!matches || matches[1] === 'normal') { + return size * 1.2; + } + + value = +matches[2]; + + switch (matches[3]) { + case 'px': + return value; + case '%': + value /= 100; + break; + default: + break; + } + + return size * value; + }, + + /** + * Converts the given value into a padding object with pre-computed width/height. + * @param {number|object} value - If a number, set the value to all TRBL component, + * else, if and object, use defined properties and sets undefined ones to 0. + * @returns {object} The padding values (top, right, bottom, left, width, height) + * @since 2.7.0 + */ + toPadding: function(value) { + var t, r, b, l; + + if (helpers_core.isObject(value)) { + t = +value.top || 0; + r = +value.right || 0; + b = +value.bottom || 0; + l = +value.left || 0; + } else { + t = r = b = l = +value || 0; + } + + return { + top: t, + right: r, + bottom: b, + left: l, + height: t + b, + width: l + r + }; + }, + + /** + * Parses font options and returns the font object. + * @param {object} options - A object that contains font options to be parsed. + * @return {object} The font object. + * @todo Support font.* options and renamed to toFont(). + * @private + */ + _parseFont: function(options) { + var globalDefaults = core_defaults.global; + var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize); + var font = { + family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily), + lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size), + size: size, + style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle), + weight: null, + string: '' + }; + + font.string = toFontString(font); + return font; + }, + + /** + * Evaluates the given `inputs` sequentially and returns the first defined value. + * @param {Array} inputs - An array of values, falling back to the last value. + * @param {object} [context] - If defined and the current value is a function, the value + * is called with `context` as first argument and the result becomes the new input. + * @param {number} [index] - If defined and the current value is an array, the value + * at `index` become the new input. + * @since 2.7.0 + */ + resolve: function(inputs, context, index) { + var i, ilen, value; + + for (i = 0, ilen = inputs.length; i < ilen; ++i) { + value = inputs[i]; + if (value === undefined) { + continue; + } + if (context !== undefined && typeof value === 'function') { + value = value(context); + } + if (index !== undefined && helpers_core.isArray(value)) { + value = value[index]; + } + if (value !== undefined) { + return value; + } + } + } +}; + +var helpers$1 = helpers_core; +var easing = helpers_easing; +var canvas = helpers_canvas; +var options = helpers_options; +helpers$1.easing = easing; +helpers$1.canvas = canvas; +helpers$1.options = options; + +function interpolate(start, view, model, ease) { + var keys = Object.keys(model); + var i, ilen, key, actual, origin, target, type, c0, c1; + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + + target = model[key]; + + // if a value is added to the model after pivot() has been called, the view + // doesn't contain it, so let's initialize the view to the target value. + if (!view.hasOwnProperty(key)) { + view[key] = target; + } + + actual = view[key]; + + if (actual === target || key[0] === '_') { + continue; + } + + if (!start.hasOwnProperty(key)) { + start[key] = actual; + } + + origin = start[key]; + + type = typeof target; + + if (type === typeof origin) { + if (type === 'string') { + c0 = chartjsColor(origin); + if (c0.valid) { + c1 = chartjsColor(target); + if (c1.valid) { + view[key] = c1.mix(c0, ease).rgbString(); + continue; + } + } + } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) { + view[key] = origin + (target - origin) * ease; + continue; + } + } + + view[key] = target; + } +} + +var Element = function(configuration) { + helpers$1.extend(this, configuration); + this.initialize.apply(this, arguments); +}; + +helpers$1.extend(Element.prototype, { + + initialize: function() { + this.hidden = false; + }, + + pivot: function() { + var me = this; + if (!me._view) { + me._view = helpers$1.clone(me._model); + } + me._start = {}; + return me; + }, + + transition: function(ease) { + var me = this; + var model = me._model; + var start = me._start; + var view = me._view; + + // No animation -> No Transition + if (!model || ease === 1) { + me._view = model; + me._start = null; + return me; + } + + if (!view) { + view = me._view = {}; + } + + if (!start) { + start = me._start = {}; + } + + interpolate(start, view, model, ease); + + return me; + }, + + tooltipPosition: function() { + return { + x: this._model.x, + y: this._model.y + }; + }, + + hasValue: function() { + return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y); + } +}); + +Element.extend = helpers$1.inherits; + +var core_element = Element; + +var exports$2 = core_element.extend({ + chart: null, // the animation associated chart instance + currentStep: 0, // the current animation step + numSteps: 60, // default number of steps + easing: '', // the easing to use for this animation + render: null, // render function used by the animation service + + onAnimationProgress: null, // user specified callback to fire on each step of the animation + onAnimationComplete: null, // user specified callback to fire when the animation finishes +}); + +var core_animation = exports$2; + +// DEPRECATIONS + +/** + * Provided for backward compatibility, use Chart.Animation instead + * @prop Chart.Animation#animationObject + * @deprecated since version 2.6.0 + * @todo remove at version 3 + */ +Object.defineProperty(exports$2.prototype, 'animationObject', { + get: function() { + return this; + } +}); + +/** + * Provided for backward compatibility, use Chart.Animation#chart instead + * @prop Chart.Animation#chartInstance + * @deprecated since version 2.6.0 + * @todo remove at version 3 + */ +Object.defineProperty(exports$2.prototype, 'chartInstance', { + get: function() { + return this.chart; + }, + set: function(value) { + this.chart = value; + } +}); + +core_defaults._set('global', { + animation: { + duration: 1000, + easing: 'easeOutQuart', + onProgress: helpers$1.noop, + onComplete: helpers$1.noop + } +}); + +var core_animations = { + animations: [], + request: null, + + /** + * @param {Chart} chart - The chart to animate. + * @param {Chart.Animation} animation - The animation that we will animate. + * @param {number} duration - The animation duration in ms. + * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions + */ + addAnimation: function(chart, animation, duration, lazy) { + var animations = this.animations; + var i, ilen; + + animation.chart = chart; + animation.startTime = Date.now(); + animation.duration = duration; + + if (!lazy) { + chart.animating = true; + } + + for (i = 0, ilen = animations.length; i < ilen; ++i) { + if (animations[i].chart === chart) { + animations[i] = animation; + return; + } + } + + animations.push(animation); + + // If there are no animations queued, manually kickstart a digest, for lack of a better word + if (animations.length === 1) { + this.requestAnimationFrame(); + } + }, + + cancelAnimation: function(chart) { + var index = helpers$1.findIndex(this.animations, function(animation) { + return animation.chart === chart; + }); + + if (index !== -1) { + this.animations.splice(index, 1); + chart.animating = false; + } + }, + + requestAnimationFrame: function() { + var me = this; + if (me.request === null) { + // Skip animation frame requests until the active one is executed. + // This can happen when processing mouse events, e.g. 'mousemove' + // and 'mouseout' events will trigger multiple renders. + me.request = helpers$1.requestAnimFrame.call(window, function() { + me.request = null; + me.startDigest(); + }); + } + }, + + /** + * @private + */ + startDigest: function() { + var me = this; + + me.advance(); + + // Do we have more stuff to animate? + if (me.animations.length > 0) { + me.requestAnimationFrame(); + } + }, + + /** + * @private + */ + advance: function() { + var animations = this.animations; + var animation, chart, numSteps, nextStep; + var i = 0; + + // 1 animation per chart, so we are looping charts here + while (i < animations.length) { + animation = animations[i]; + chart = animation.chart; + numSteps = animation.numSteps; + + // Make sure that currentStep starts at 1 + // https://github.com/chartjs/Chart.js/issues/6104 + nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1; + animation.currentStep = Math.min(nextStep, numSteps); + + helpers$1.callback(animation.render, [chart, animation], chart); + helpers$1.callback(animation.onAnimationProgress, [animation], chart); + + if (animation.currentStep >= numSteps) { + helpers$1.callback(animation.onAnimationComplete, [animation], chart); + chart.animating = false; + animations.splice(i, 1); + } else { + ++i; + } + } + } +}; + +var resolve = helpers$1.options.resolve; + +var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift']; + +/** + * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice', + * 'unshift') and notify the listener AFTER the array has been altered. Listeners are + * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments. + */ +function listenArrayEvents(array, listener) { + if (array._chartjs) { + array._chartjs.listeners.push(listener); + return; + } + + Object.defineProperty(array, '_chartjs', { + configurable: true, + enumerable: false, + value: { + listeners: [listener] + } + }); + + arrayEvents.forEach(function(key) { + var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1); + var base = array[key]; + + Object.defineProperty(array, key, { + configurable: true, + enumerable: false, + value: function() { + var args = Array.prototype.slice.call(arguments); + var res = base.apply(this, args); + + helpers$1.each(array._chartjs.listeners, function(object) { + if (typeof object[method] === 'function') { + object[method].apply(object, args); + } + }); + + return res; + } + }); + }); +} + +/** + * Removes the given array event listener and cleanup extra attached properties (such as + * the _chartjs stub and overridden methods) if array doesn't have any more listeners. + */ +function unlistenArrayEvents(array, listener) { + var stub = array._chartjs; + if (!stub) { + return; + } + + var listeners = stub.listeners; + var index = listeners.indexOf(listener); + if (index !== -1) { + listeners.splice(index, 1); + } + + if (listeners.length > 0) { + return; + } + + arrayEvents.forEach(function(key) { + delete array[key]; + }); + + delete array._chartjs; +} + +// Base class for all dataset controllers (line, bar, etc) +var DatasetController = function(chart, datasetIndex) { + this.initialize(chart, datasetIndex); +}; + +helpers$1.extend(DatasetController.prototype, { + + /** + * Element type used to generate a meta dataset (e.g. Chart.element.Line). + * @type {Chart.core.element} + */ + datasetElementType: null, + + /** + * Element type used to generate a meta data (e.g. Chart.element.Point). + * @type {Chart.core.element} + */ + dataElementType: null, + + initialize: function(chart, datasetIndex) { + var me = this; + me.chart = chart; + me.index = datasetIndex; + me.linkScales(); + me.addElements(); + }, + + updateIndex: function(datasetIndex) { + this.index = datasetIndex; + }, + + linkScales: function() { + var me = this; + var meta = me.getMeta(); + var dataset = me.getDataset(); + + if (meta.xAxisID === null || !(meta.xAxisID in me.chart.scales)) { + meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id; + } + if (meta.yAxisID === null || !(meta.yAxisID in me.chart.scales)) { + meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id; + } + }, + + getDataset: function() { + return this.chart.data.datasets[this.index]; + }, + + getMeta: function() { + return this.chart.getDatasetMeta(this.index); + }, + + getScaleForId: function(scaleID) { + return this.chart.scales[scaleID]; + }, + + /** + * @private + */ + _getValueScaleId: function() { + return this.getMeta().yAxisID; + }, + + /** + * @private + */ + _getIndexScaleId: function() { + return this.getMeta().xAxisID; + }, + + /** + * @private + */ + _getValueScale: function() { + return this.getScaleForId(this._getValueScaleId()); + }, + + /** + * @private + */ + _getIndexScale: function() { + return this.getScaleForId(this._getIndexScaleId()); + }, + + reset: function() { + this.update(true); + }, + + /** + * @private + */ + destroy: function() { + if (this._data) { + unlistenArrayEvents(this._data, this); + } + }, + + createMetaDataset: function() { + var me = this; + var type = me.datasetElementType; + return type && new type({ + _chart: me.chart, + _datasetIndex: me.index + }); + }, + + createMetaData: function(index) { + var me = this; + var type = me.dataElementType; + return type && new type({ + _chart: me.chart, + _datasetIndex: me.index, + _index: index + }); + }, + + addElements: function() { + var me = this; + var meta = me.getMeta(); + var data = me.getDataset().data || []; + var metaData = meta.data; + var i, ilen; + + for (i = 0, ilen = data.length; i < ilen; ++i) { + metaData[i] = metaData[i] || me.createMetaData(i); + } + + meta.dataset = meta.dataset || me.createMetaDataset(); + }, + + addElementAndReset: function(index) { + var element = this.createMetaData(index); + this.getMeta().data.splice(index, 0, element); + this.updateElement(element, index, true); + }, + + buildOrUpdateElements: function() { + var me = this; + var dataset = me.getDataset(); + var data = dataset.data || (dataset.data = []); + + // In order to correctly handle data addition/deletion animation (an thus simulate + // real-time charts), we need to monitor these data modifications and synchronize + // the internal meta data accordingly. + if (me._data !== data) { + if (me._data) { + // This case happens when the user replaced the data array instance. + unlistenArrayEvents(me._data, me); + } + + if (data && Object.isExtensible(data)) { + listenArrayEvents(data, me); + } + me._data = data; + } + + // Re-sync meta data in case the user replaced the data array or if we missed + // any updates and so make sure that we handle number of datapoints changing. + me.resyncElements(); + }, + + update: helpers$1.noop, + + transition: function(easingValue) { + var meta = this.getMeta(); + var elements = meta.data || []; + var ilen = elements.length; + var i = 0; + + for (; i < ilen; ++i) { + elements[i].transition(easingValue); + } + + if (meta.dataset) { + meta.dataset.transition(easingValue); + } + }, + + draw: function() { + var meta = this.getMeta(); + var elements = meta.data || []; + var ilen = elements.length; + var i = 0; + + if (meta.dataset) { + meta.dataset.draw(); + } + + for (; i < ilen; ++i) { + elements[i].draw(); + } + }, + + removeHoverStyle: function(element) { + helpers$1.merge(element._model, element.$previousStyle || {}); + delete element.$previousStyle; + }, + + setHoverStyle: function(element) { + var dataset = this.chart.data.datasets[element._datasetIndex]; + var index = element._index; + var custom = element.custom || {}; + var model = element._model; + var getHoverColor = helpers$1.getHoverColor; + + element.$previousStyle = { + backgroundColor: model.backgroundColor, + borderColor: model.borderColor, + borderWidth: model.borderWidth + }; + + model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index); + model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index); + model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index); + }, + + /** + * @private + */ + resyncElements: function() { + var me = this; + var meta = me.getMeta(); + var data = me.getDataset().data; + var numMeta = meta.data.length; + var numData = data.length; + + if (numData < numMeta) { + meta.data.splice(numData, numMeta - numData); + } else if (numData > numMeta) { + me.insertElements(numMeta, numData - numMeta); + } + }, + + /** + * @private + */ + insertElements: function(start, count) { + for (var i = 0; i < count; ++i) { + this.addElementAndReset(start + i); + } + }, + + /** + * @private + */ + onDataPush: function() { + var count = arguments.length; + this.insertElements(this.getDataset().data.length - count, count); + }, + + /** + * @private + */ + onDataPop: function() { + this.getMeta().data.pop(); + }, + + /** + * @private + */ + onDataShift: function() { + this.getMeta().data.shift(); + }, + + /** + * @private + */ + onDataSplice: function(start, count) { + this.getMeta().data.splice(start, count); + this.insertElements(start, arguments.length - 2); + }, + + /** + * @private + */ + onDataUnshift: function() { + this.insertElements(0, arguments.length); + } +}); + +DatasetController.extend = helpers$1.inherits; + +var core_datasetController = DatasetController; + +core_defaults._set('global', { + elements: { + arc: { + backgroundColor: core_defaults.global.defaultColor, + borderColor: '#fff', + borderWidth: 2, + borderAlign: 'center' + } + } +}); + +var element_arc = core_element.extend({ + inLabelRange: function(mouseX) { + var vm = this._view; + + if (vm) { + return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2)); + } + return false; + }, + + inRange: function(chartX, chartY) { + var vm = this._view; + + if (vm) { + var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY}); + var angle = pointRelativePosition.angle; + var distance = pointRelativePosition.distance; + + // Sanitise angle range + var startAngle = vm.startAngle; + var endAngle = vm.endAngle; + while (endAngle < startAngle) { + endAngle += 2.0 * Math.PI; + } + while (angle > endAngle) { + angle -= 2.0 * Math.PI; + } + while (angle < startAngle) { + angle += 2.0 * Math.PI; + } + + // Check if within the range of the open/close angle + var betweenAngles = (angle >= startAngle && angle <= endAngle); + var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius); + + return (betweenAngles && withinRadius); + } + return false; + }, + + getCenterPoint: function() { + var vm = this._view; + var halfAngle = (vm.startAngle + vm.endAngle) / 2; + var halfRadius = (vm.innerRadius + vm.outerRadius) / 2; + return { + x: vm.x + Math.cos(halfAngle) * halfRadius, + y: vm.y + Math.sin(halfAngle) * halfRadius + }; + }, + + getArea: function() { + var vm = this._view; + return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2)); + }, + + tooltipPosition: function() { + var vm = this._view; + var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2); + var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius; + + return { + x: vm.x + (Math.cos(centreAngle) * rangeFromCentre), + y: vm.y + (Math.sin(centreAngle) * rangeFromCentre) + }; + }, + + draw: function() { + var ctx = this._chart.ctx; + var vm = this._view; + var sA = vm.startAngle; + var eA = vm.endAngle; + var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0; + var angleMargin; + + ctx.save(); + + ctx.beginPath(); + ctx.arc(vm.x, vm.y, Math.max(vm.outerRadius - pixelMargin, 0), sA, eA); + ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true); + ctx.closePath(); + + ctx.fillStyle = vm.backgroundColor; + ctx.fill(); + + if (vm.borderWidth) { + if (vm.borderAlign === 'inner') { + // Draw an inner border by cliping the arc and drawing a double-width border + // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders + ctx.beginPath(); + angleMargin = pixelMargin / vm.outerRadius; + ctx.arc(vm.x, vm.y, vm.outerRadius, sA - angleMargin, eA + angleMargin); + if (vm.innerRadius > pixelMargin) { + angleMargin = pixelMargin / vm.innerRadius; + ctx.arc(vm.x, vm.y, vm.innerRadius - pixelMargin, eA + angleMargin, sA - angleMargin, true); + } else { + ctx.arc(vm.x, vm.y, pixelMargin, eA + Math.PI / 2, sA - Math.PI / 2); + } + ctx.closePath(); + ctx.clip(); + + ctx.beginPath(); + ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA); + ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true); + ctx.closePath(); + + ctx.lineWidth = vm.borderWidth * 2; + ctx.lineJoin = 'round'; + } else { + ctx.lineWidth = vm.borderWidth; + ctx.lineJoin = 'bevel'; + } + + ctx.strokeStyle = vm.borderColor; + ctx.stroke(); + } + + ctx.restore(); + } +}); + +var valueOrDefault$1 = helpers$1.valueOrDefault; + +var defaultColor = core_defaults.global.defaultColor; + +core_defaults._set('global', { + elements: { + line: { + tension: 0.4, + backgroundColor: defaultColor, + borderWidth: 3, + borderColor: defaultColor, + borderCapStyle: 'butt', + borderDash: [], + borderDashOffset: 0.0, + borderJoinStyle: 'miter', + capBezierPoints: true, + fill: true, // do we fill in the area between the line and its base axis + } + } +}); + +var element_line = core_element.extend({ + draw: function() { + var me = this; + var vm = me._view; + var ctx = me._chart.ctx; + var spanGaps = vm.spanGaps; + var points = me._children.slice(); // clone array + var globalDefaults = core_defaults.global; + var globalOptionLineElements = globalDefaults.elements.line; + var lastDrawnIndex = -1; + var index, current, previous, currentVM; + + // If we are looping, adding the first point again + if (me._loop && points.length) { + points.push(points[0]); + } + + ctx.save(); + + // Stroke Line Options + ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle; + + // IE 9 and 10 do not support line dash + if (ctx.setLineDash) { + ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash); + } + + ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset); + ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle; + ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth); + ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor; + + // Stroke Line + ctx.beginPath(); + lastDrawnIndex = -1; + + for (index = 0; index < points.length; ++index) { + current = points[index]; + previous = helpers$1.previousItem(points, index); + currentVM = current._view; + + // First point moves to it's starting position no matter what + if (index === 0) { + if (!currentVM.skip) { + ctx.moveTo(currentVM.x, currentVM.y); + lastDrawnIndex = index; + } + } else { + previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex]; + + if (!currentVM.skip) { + if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) { + // There was a gap and this is the first point after the gap + ctx.moveTo(currentVM.x, currentVM.y); + } else { + // Line to next point + helpers$1.canvas.lineTo(ctx, previous._view, current._view); + } + lastDrawnIndex = index; + } + } + } + + ctx.stroke(); + ctx.restore(); + } +}); + +var valueOrDefault$2 = helpers$1.valueOrDefault; + +var defaultColor$1 = core_defaults.global.defaultColor; + +core_defaults._set('global', { + elements: { + point: { + radius: 3, + pointStyle: 'circle', + backgroundColor: defaultColor$1, + borderColor: defaultColor$1, + borderWidth: 1, + // Hover + hitRadius: 1, + hoverRadius: 4, + hoverBorderWidth: 1 + } + } +}); + +function xRange(mouseX) { + var vm = this._view; + return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false; +} + +function yRange(mouseY) { + var vm = this._view; + return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false; +} + +var element_point = core_element.extend({ + inRange: function(mouseX, mouseY) { + var vm = this._view; + return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false; + }, + + inLabelRange: xRange, + inXRange: xRange, + inYRange: yRange, + + getCenterPoint: function() { + var vm = this._view; + return { + x: vm.x, + y: vm.y + }; + }, + + getArea: function() { + return Math.PI * Math.pow(this._view.radius, 2); + }, + + tooltipPosition: function() { + var vm = this._view; + return { + x: vm.x, + y: vm.y, + padding: vm.radius + vm.borderWidth + }; + }, + + draw: function(chartArea) { + var vm = this._view; + var ctx = this._chart.ctx; + var pointStyle = vm.pointStyle; + var rotation = vm.rotation; + var radius = vm.radius; + var x = vm.x; + var y = vm.y; + var globalDefaults = core_defaults.global; + var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow + + if (vm.skip) { + return; + } + + // Clipping for Points. + if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) { + ctx.strokeStyle = vm.borderColor || defaultColor; + ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth); + ctx.fillStyle = vm.backgroundColor || defaultColor; + helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation); + } + } +}); + +var defaultColor$2 = core_defaults.global.defaultColor; + +core_defaults._set('global', { + elements: { + rectangle: { + backgroundColor: defaultColor$2, + borderColor: defaultColor$2, + borderSkipped: 'bottom', + borderWidth: 0 + } + } +}); + +function isVertical(vm) { + return vm && vm.width !== undefined; +} + +/** + * Helper function to get the bounds of the bar regardless of the orientation + * @param bar {Chart.Element.Rectangle} the bar + * @return {Bounds} bounds of the bar + * @private + */ +function getBarBounds(vm) { + var x1, x2, y1, y2, half; + + if (isVertical(vm)) { + half = vm.width / 2; + x1 = vm.x - half; + x2 = vm.x + half; + y1 = Math.min(vm.y, vm.base); + y2 = Math.max(vm.y, vm.base); + } else { + half = vm.height / 2; + x1 = Math.min(vm.x, vm.base); + x2 = Math.max(vm.x, vm.base); + y1 = vm.y - half; + y2 = vm.y + half; + } + + return { + left: x1, + top: y1, + right: x2, + bottom: y2 + }; +} + +function swap(orig, v1, v2) { + return orig === v1 ? v2 : orig === v2 ? v1 : orig; +} + +function parseBorderSkipped(vm) { + var edge = vm.borderSkipped; + var res = {}; + + if (!edge) { + return res; + } + + if (vm.horizontal) { + if (vm.base > vm.x) { + edge = swap(edge, 'left', 'right'); + } + } else if (vm.base < vm.y) { + edge = swap(edge, 'bottom', 'top'); + } + + res[edge] = true; + return res; +} + +function parseBorderWidth(vm, maxW, maxH) { + var value = vm.borderWidth; + var skip = parseBorderSkipped(vm); + var t, r, b, l; + + if (helpers$1.isObject(value)) { + t = +value.top || 0; + r = +value.right || 0; + b = +value.bottom || 0; + l = +value.left || 0; + } else { + t = r = b = l = +value || 0; + } + + return { + t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t, + r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r, + b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b, + l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l + }; +} + +function boundingRects(vm) { + var bounds = getBarBounds(vm); + var width = bounds.right - bounds.left; + var height = bounds.bottom - bounds.top; + var border = parseBorderWidth(vm, width / 2, height / 2); + + return { + outer: { + x: bounds.left, + y: bounds.top, + w: width, + h: height + }, + inner: { + x: bounds.left + border.l, + y: bounds.top + border.t, + w: width - border.l - border.r, + h: height - border.t - border.b + } + }; +} + +function inRange(vm, x, y) { + var skipX = x === null; + var skipY = y === null; + var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm); + + return bounds + && (skipX || x >= bounds.left && x <= bounds.right) + && (skipY || y >= bounds.top && y <= bounds.bottom); +} + +var element_rectangle = core_element.extend({ + draw: function() { + var ctx = this._chart.ctx; + var vm = this._view; + var rects = boundingRects(vm); + var outer = rects.outer; + var inner = rects.inner; + + ctx.fillStyle = vm.backgroundColor; + ctx.fillRect(outer.x, outer.y, outer.w, outer.h); + + if (outer.w === inner.w && outer.h === inner.h) { + return; + } + + ctx.save(); + ctx.beginPath(); + ctx.rect(outer.x, outer.y, outer.w, outer.h); + ctx.clip(); + ctx.fillStyle = vm.borderColor; + ctx.rect(inner.x, inner.y, inner.w, inner.h); + ctx.fill('evenodd'); + ctx.restore(); + }, + + height: function() { + var vm = this._view; + return vm.base - vm.y; + }, + + inRange: function(mouseX, mouseY) { + return inRange(this._view, mouseX, mouseY); + }, + + inLabelRange: function(mouseX, mouseY) { + var vm = this._view; + return isVertical(vm) + ? inRange(vm, mouseX, null) + : inRange(vm, null, mouseY); + }, + + inXRange: function(mouseX) { + return inRange(this._view, mouseX, null); + }, + + inYRange: function(mouseY) { + return inRange(this._view, null, mouseY); + }, + + getCenterPoint: function() { + var vm = this._view; + var x, y; + if (isVertical(vm)) { + x = vm.x; + y = (vm.y + vm.base) / 2; + } else { + x = (vm.x + vm.base) / 2; + y = vm.y; + } + + return {x: x, y: y}; + }, + + getArea: function() { + var vm = this._view; + + return isVertical(vm) + ? vm.width * Math.abs(vm.y - vm.base) + : vm.height * Math.abs(vm.x - vm.base); + }, + + tooltipPosition: function() { + var vm = this._view; + return { + x: vm.x, + y: vm.y + }; + } +}); + +var elements = {}; +var Arc = element_arc; +var Line = element_line; +var Point = element_point; +var Rectangle = element_rectangle; +elements.Arc = Arc; +elements.Line = Line; +elements.Point = Point; +elements.Rectangle = Rectangle; + +var resolve$1 = helpers$1.options.resolve; + +core_defaults._set('bar', { + hover: { + mode: 'label' + }, + + scales: { + xAxes: [{ + type: 'category', + categoryPercentage: 0.8, + barPercentage: 0.9, + offset: true, + gridLines: { + offsetGridLines: true + } + }], + + yAxes: [{ + type: 'linear' + }] + } +}); + +/** + * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap. + * @private + */ +function computeMinSampleSize(scale, pixels) { + var min = scale.isHorizontal() ? scale.width : scale.height; + var ticks = scale.getTicks(); + var prev, curr, i, ilen; + + for (i = 1, ilen = pixels.length; i < ilen; ++i) { + min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1])); + } + + for (i = 0, ilen = ticks.length; i < ilen; ++i) { + curr = scale.getPixelForTick(i); + min = i > 0 ? Math.min(min, curr - prev) : min; + prev = curr; + } + + return min; +} + +/** + * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null, + * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This + * mode currently always generates bars equally sized (until we introduce scriptable options?). + * @private + */ +function computeFitCategoryTraits(index, ruler, options) { + var thickness = options.barThickness; + var count = ruler.stackCount; + var curr = ruler.pixels[index]; + var size, ratio; + + if (helpers$1.isNullOrUndef(thickness)) { + size = ruler.min * options.categoryPercentage; + ratio = options.barPercentage; + } else { + // When bar thickness is enforced, category and bar percentages are ignored. + // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%') + // and deprecate barPercentage since this value is ignored when thickness is absolute. + size = thickness * count; + ratio = 1; + } + + return { + chunk: size / count, + ratio: ratio, + start: curr - (size / 2) + }; +} + +/** + * Computes an "optimal" category that globally arranges bars side by side (no gap when + * percentage options are 1), based on the previous and following categories. This mode + * generates bars with different widths when data are not evenly spaced. + * @private + */ +function computeFlexCategoryTraits(index, ruler, options) { + var pixels = ruler.pixels; + var curr = pixels[index]; + var prev = index > 0 ? pixels[index - 1] : null; + var next = index < pixels.length - 1 ? pixels[index + 1] : null; + var percent = options.categoryPercentage; + var start, size; + + if (prev === null) { + // first data: its size is double based on the next point or, + // if it's also the last data, we use the scale size. + prev = curr - (next === null ? ruler.end - ruler.start : next - curr); + } + + if (next === null) { + // last data: its size is also double based on the previous point. + next = curr + curr - prev; + } + + start = curr - (curr - Math.min(prev, next)) / 2 * percent; + size = Math.abs(next - prev) / 2 * percent; + + return { + chunk: size / ruler.stackCount, + ratio: options.barPercentage, + start: start + }; +} + +var controller_bar = core_datasetController.extend({ + + dataElementType: elements.Rectangle, + + initialize: function() { + var me = this; + var meta; + + core_datasetController.prototype.initialize.apply(me, arguments); + + meta = me.getMeta(); + meta.stack = me.getDataset().stack; + meta.bar = true; + }, + + update: function(reset) { + var me = this; + var rects = me.getMeta().data; + var i, ilen; + + me._ruler = me.getRuler(); + + for (i = 0, ilen = rects.length; i < ilen; ++i) { + me.updateElement(rects[i], i, reset); + } + }, + + updateElement: function(rectangle, index, reset) { + var me = this; + var meta = me.getMeta(); + var dataset = me.getDataset(); + var options = me._resolveElementOptions(rectangle, index); + + rectangle._xScale = me.getScaleForId(meta.xAxisID); + rectangle._yScale = me.getScaleForId(meta.yAxisID); + rectangle._datasetIndex = me.index; + rectangle._index = index; + rectangle._model = { + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderSkipped: options.borderSkipped, + borderWidth: options.borderWidth, + datasetLabel: dataset.label, + label: me.chart.data.labels[index] + }; + + me._updateElementGeometry(rectangle, index, reset); + + rectangle.pivot(); + }, + + /** + * @private + */ + _updateElementGeometry: function(rectangle, index, reset) { + var me = this; + var model = rectangle._model; + var vscale = me._getValueScale(); + var base = vscale.getBasePixel(); + var horizontal = vscale.isHorizontal(); + var ruler = me._ruler || me.getRuler(); + var vpixels = me.calculateBarValuePixels(me.index, index); + var ipixels = me.calculateBarIndexPixels(me.index, index, ruler); + + model.horizontal = horizontal; + model.base = reset ? base : vpixels.base; + model.x = horizontal ? reset ? base : vpixels.head : ipixels.center; + model.y = horizontal ? ipixels.center : reset ? base : vpixels.head; + model.height = horizontal ? ipixels.size : undefined; + model.width = horizontal ? undefined : ipixels.size; + }, + + /** + * Returns the stacks based on groups and bar visibility. + * @param {number} [last] - The dataset index + * @returns {string[]} The list of stack IDs + * @private + */ + _getStacks: function(last) { + var me = this; + var chart = me.chart; + var scale = me._getIndexScale(); + var stacked = scale.options.stacked; + var ilen = last === undefined ? chart.data.datasets.length : last + 1; + var stacks = []; + var i, meta; + + for (i = 0; i < ilen; ++i) { + meta = chart.getDatasetMeta(i); + if (meta.bar && chart.isDatasetVisible(i) && + (stacked === false || + (stacked === true && stacks.indexOf(meta.stack) === -1) || + (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) { + stacks.push(meta.stack); + } + } + + return stacks; + }, + + /** + * Returns the effective number of stacks based on groups and bar visibility. + * @private + */ + getStackCount: function() { + return this._getStacks().length; + }, + + /** + * Returns the stack index for the given dataset based on groups and bar visibility. + * @param {number} [datasetIndex] - The dataset index + * @param {string} [name] - The stack name to find + * @returns {number} The stack index + * @private + */ + getStackIndex: function(datasetIndex, name) { + var stacks = this._getStacks(datasetIndex); + var index = (name !== undefined) + ? stacks.indexOf(name) + : -1; // indexOf returns -1 if element is not present + + return (index === -1) + ? stacks.length - 1 + : index; + }, + + /** + * @private + */ + getRuler: function() { + var me = this; + var scale = me._getIndexScale(); + var stackCount = me.getStackCount(); + var datasetIndex = me.index; + var isHorizontal = scale.isHorizontal(); + var start = isHorizontal ? scale.left : scale.top; + var end = start + (isHorizontal ? scale.width : scale.height); + var pixels = []; + var i, ilen, min; + + for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) { + pixels.push(scale.getPixelForValue(null, i, datasetIndex)); + } + + min = helpers$1.isNullOrUndef(scale.options.barThickness) + ? computeMinSampleSize(scale, pixels) + : -1; + + return { + min: min, + pixels: pixels, + start: start, + end: end, + stackCount: stackCount, + scale: scale + }; + }, + + /** + * Note: pixel values are not clamped to the scale area. + * @private + */ + calculateBarValuePixels: function(datasetIndex, index) { + var me = this; + var chart = me.chart; + var meta = me.getMeta(); + var scale = me._getValueScale(); + var isHorizontal = scale.isHorizontal(); + var datasets = chart.data.datasets; + var value = +scale.getRightValue(datasets[datasetIndex].data[index]); + var minBarLength = scale.options.minBarLength; + var stacked = scale.options.stacked; + var stack = meta.stack; + var start = 0; + var i, imeta, ivalue, base, head, size; + + if (stacked || (stacked === undefined && stack !== undefined)) { + for (i = 0; i < datasetIndex; ++i) { + imeta = chart.getDatasetMeta(i); + + if (imeta.bar && + imeta.stack === stack && + imeta.controller._getValueScaleId() === scale.id && + chart.isDatasetVisible(i)) { + + ivalue = +scale.getRightValue(datasets[i].data[index]); + if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) { + start += ivalue; + } + } + } + } + + base = scale.getPixelForValue(start); + head = scale.getPixelForValue(start + value); + size = head - base; + + if (minBarLength !== undefined && Math.abs(size) < minBarLength) { + size = minBarLength; + if (value >= 0 && !isHorizontal || value < 0 && isHorizontal) { + head = base - minBarLength; + } else { + head = base + minBarLength; + } + } + + return { + size: size, + base: base, + head: head, + center: head + size / 2 + }; + }, + + /** + * @private + */ + calculateBarIndexPixels: function(datasetIndex, index, ruler) { + var me = this; + var options = ruler.scale.options; + var range = options.barThickness === 'flex' + ? computeFlexCategoryTraits(index, ruler, options) + : computeFitCategoryTraits(index, ruler, options); + + var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack); + var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2); + var size = Math.min( + helpers$1.valueOrDefault(options.maxBarThickness, Infinity), + range.chunk * range.ratio); + + return { + base: center - size / 2, + head: center + size / 2, + center: center, + size: size + }; + }, + + draw: function() { + var me = this; + var chart = me.chart; + var scale = me._getValueScale(); + var rects = me.getMeta().data; + var dataset = me.getDataset(); + var ilen = rects.length; + var i = 0; + + helpers$1.canvas.clipArea(chart.ctx, chart.chartArea); + + for (; i < ilen; ++i) { + if (!isNaN(scale.getRightValue(dataset.data[i]))) { + rects[i].draw(); + } + } + + helpers$1.canvas.unclipArea(chart.ctx); + }, + + /** + * @private + */ + _resolveElementOptions: function(rectangle, index) { + var me = this; + var chart = me.chart; + var datasets = chart.data.datasets; + var dataset = datasets[me.index]; + var custom = rectangle.custom || {}; + var options = chart.options.elements.rectangle; + var values = {}; + var i, ilen, key; + + // Scriptable options + var context = { + chart: chart, + dataIndex: index, + dataset: dataset, + datasetIndex: me.index + }; + + var keys = [ + 'backgroundColor', + 'borderColor', + 'borderSkipped', + 'borderWidth' + ]; + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + values[key] = resolve$1([ + custom[key], + dataset[key], + options[key] + ], context, index); + } + + return values; + } +}); + +var valueOrDefault$3 = helpers$1.valueOrDefault; +var resolve$2 = helpers$1.options.resolve; + +core_defaults._set('bubble', { + hover: { + mode: 'single' + }, + + scales: { + xAxes: [{ + type: 'linear', // bubble should probably use a linear scale by default + position: 'bottom', + id: 'x-axis-0' // need an ID so datasets can reference the scale + }], + yAxes: [{ + type: 'linear', + position: 'left', + id: 'y-axis-0' + }] + }, + + tooltips: { + callbacks: { + title: function() { + // Title doesn't make sense for scatter since we format the data as a point + return ''; + }, + label: function(item, data) { + var datasetLabel = data.datasets[item.datasetIndex].label || ''; + var dataPoint = data.datasets[item.datasetIndex].data[item.index]; + return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')'; + } + } + } +}); + +var controller_bubble = core_datasetController.extend({ + /** + * @protected + */ + dataElementType: elements.Point, + + /** + * @protected + */ + update: function(reset) { + var me = this; + var meta = me.getMeta(); + var points = meta.data; + + // Update Points + helpers$1.each(points, function(point, index) { + me.updateElement(point, index, reset); + }); + }, + + /** + * @protected + */ + updateElement: function(point, index, reset) { + var me = this; + var meta = me.getMeta(); + var custom = point.custom || {}; + var xScale = me.getScaleForId(meta.xAxisID); + var yScale = me.getScaleForId(meta.yAxisID); + var options = me._resolveElementOptions(point, index); + var data = me.getDataset().data[index]; + var dsIndex = me.index; + + var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex); + var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex); + + point._xScale = xScale; + point._yScale = yScale; + point._options = options; + point._datasetIndex = dsIndex; + point._index = index; + point._model = { + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderWidth: options.borderWidth, + hitRadius: options.hitRadius, + pointStyle: options.pointStyle, + rotation: options.rotation, + radius: reset ? 0 : options.radius, + skip: custom.skip || isNaN(x) || isNaN(y), + x: x, + y: y, + }; + + point.pivot(); + }, + + /** + * @protected + */ + setHoverStyle: function(point) { + var model = point._model; + var options = point._options; + var getHoverColor = helpers$1.getHoverColor; + + point.$previousStyle = { + backgroundColor: model.backgroundColor, + borderColor: model.borderColor, + borderWidth: model.borderWidth, + radius: model.radius + }; + + model.backgroundColor = valueOrDefault$3(options.hoverBackgroundColor, getHoverColor(options.backgroundColor)); + model.borderColor = valueOrDefault$3(options.hoverBorderColor, getHoverColor(options.borderColor)); + model.borderWidth = valueOrDefault$3(options.hoverBorderWidth, options.borderWidth); + model.radius = options.radius + options.hoverRadius; + }, + + /** + * @private + */ + _resolveElementOptions: function(point, index) { + var me = this; + var chart = me.chart; + var datasets = chart.data.datasets; + var dataset = datasets[me.index]; + var custom = point.custom || {}; + var options = chart.options.elements.point; + var data = dataset.data[index]; + var values = {}; + var i, ilen, key; + + // Scriptable options + var context = { + chart: chart, + dataIndex: index, + dataset: dataset, + datasetIndex: me.index + }; + + var keys = [ + 'backgroundColor', + 'borderColor', + 'borderWidth', + 'hoverBackgroundColor', + 'hoverBorderColor', + 'hoverBorderWidth', + 'hoverRadius', + 'hitRadius', + 'pointStyle', + 'rotation' + ]; + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + values[key] = resolve$2([ + custom[key], + dataset[key], + options[key] + ], context, index); + } + + // Custom radius resolution + values.radius = resolve$2([ + custom.radius, + data ? data.r : undefined, + dataset.radius, + options.radius + ], context, index); + + return values; + } +}); + +var resolve$3 = helpers$1.options.resolve; +var valueOrDefault$4 = helpers$1.valueOrDefault; + +core_defaults._set('doughnut', { + animation: { + // Boolean - Whether we animate the rotation of the Doughnut + animateRotate: true, + // Boolean - Whether we animate scaling the Doughnut from the centre + animateScale: false + }, + hover: { + mode: 'single' + }, + legendCallback: function(chart) { + var text = []; + text.push('
      '); + + var data = chart.data; + var datasets = data.datasets; + var labels = data.labels; + + if (datasets.length) { + for (var i = 0; i < datasets[0].data.length; ++i) { + text.push('
    • '); + if (labels[i]) { + text.push(labels[i]); + } + text.push('
    • '); + } + } + + text.push('
    '); + return text.join(''); + }, + legend: { + labels: { + generateLabels: function(chart) { + var data = chart.data; + if (data.labels.length && data.datasets.length) { + return data.labels.map(function(label, i) { + var meta = chart.getDatasetMeta(0); + var ds = data.datasets[0]; + var arc = meta.data[i]; + var custom = arc && arc.custom || {}; + var arcOpts = chart.options.elements.arc; + var fill = resolve$3([custom.backgroundColor, ds.backgroundColor, arcOpts.backgroundColor], undefined, i); + var stroke = resolve$3([custom.borderColor, ds.borderColor, arcOpts.borderColor], undefined, i); + var bw = resolve$3([custom.borderWidth, ds.borderWidth, arcOpts.borderWidth], undefined, i); + + return { + text: label, + fillStyle: fill, + strokeStyle: stroke, + lineWidth: bw, + hidden: isNaN(ds.data[i]) || meta.data[i].hidden, + + // Extra data used for toggling the correct item + index: i + }; + }); + } + return []; + } + }, + + onClick: function(e, legendItem) { + var index = legendItem.index; + var chart = this.chart; + var i, ilen, meta; + + for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { + meta = chart.getDatasetMeta(i); + // toggle visibility of index if exists + if (meta.data[index]) { + meta.data[index].hidden = !meta.data[index].hidden; + } + } + + chart.update(); + } + }, + + // The percentage of the chart that we cut out of the middle. + cutoutPercentage: 50, + + // The rotation of the chart, where the first data arc begins. + rotation: Math.PI * -0.5, + + // The total circumference of the chart. + circumference: Math.PI * 2.0, + + // Need to override these to give a nice default + tooltips: { + callbacks: { + title: function() { + return ''; + }, + label: function(tooltipItem, data) { + var dataLabel = data.labels[tooltipItem.index]; + var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]; + + if (helpers$1.isArray(dataLabel)) { + // show value on first line of multiline label + // need to clone because we are changing the value + dataLabel = dataLabel.slice(); + dataLabel[0] += value; + } else { + dataLabel += value; + } + + return dataLabel; + } + } + } +}); + +var controller_doughnut = core_datasetController.extend({ + + dataElementType: elements.Arc, + + linkScales: helpers$1.noop, + + // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly + getRingIndex: function(datasetIndex) { + var ringIndex = 0; + + for (var j = 0; j < datasetIndex; ++j) { + if (this.chart.isDatasetVisible(j)) { + ++ringIndex; + } + } + + return ringIndex; + }, + + update: function(reset) { + var me = this; + var chart = me.chart; + var chartArea = chart.chartArea; + var opts = chart.options; + var availableWidth = chartArea.right - chartArea.left; + var availableHeight = chartArea.bottom - chartArea.top; + var minSize = Math.min(availableWidth, availableHeight); + var offset = {x: 0, y: 0}; + var meta = me.getMeta(); + var arcs = meta.data; + var cutoutPercentage = opts.cutoutPercentage; + var circumference = opts.circumference; + var chartWeight = me._getRingWeight(me.index); + var i, ilen; + + // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc + if (circumference < Math.PI * 2.0) { + var startAngle = opts.rotation % (Math.PI * 2.0); + startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0); + var endAngle = startAngle + circumference; + var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)}; + var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)}; + var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle); + var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle); + var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle); + var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle); + var cutout = cutoutPercentage / 100.0; + var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))}; + var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))}; + var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5}; + minSize = Math.min(availableWidth / size.width, availableHeight / size.height); + offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5}; + } + + for (i = 0, ilen = arcs.length; i < ilen; ++i) { + arcs[i]._options = me._resolveElementOptions(arcs[i], i); + } + + chart.borderWidth = me.getMaxBorderWidth(); + chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0); + chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0); + chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1); + chart.offsetX = offset.x * chart.outerRadius; + chart.offsetY = offset.y * chart.outerRadius; + + meta.total = me.calculateTotal(); + + me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index); + me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0); + + for (i = 0, ilen = arcs.length; i < ilen; ++i) { + me.updateElement(arcs[i], i, reset); + } + }, + + updateElement: function(arc, index, reset) { + var me = this; + var chart = me.chart; + var chartArea = chart.chartArea; + var opts = chart.options; + var animationOpts = opts.animation; + var centerX = (chartArea.left + chartArea.right) / 2; + var centerY = (chartArea.top + chartArea.bottom) / 2; + var startAngle = opts.rotation; // non reset case handled later + var endAngle = opts.rotation; // non reset case handled later + var dataset = me.getDataset(); + var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI)); + var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius; + var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius; + var options = arc._options || {}; + + helpers$1.extend(arc, { + // Utility + _datasetIndex: me.index, + _index: index, + + // Desired view properties + _model: { + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderWidth: options.borderWidth, + borderAlign: options.borderAlign, + x: centerX + chart.offsetX, + y: centerY + chart.offsetY, + startAngle: startAngle, + endAngle: endAngle, + circumference: circumference, + outerRadius: outerRadius, + innerRadius: innerRadius, + label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index]) + } + }); + + var model = arc._model; + + // Set correct angles if not resetting + if (!reset || !animationOpts.animateRotate) { + if (index === 0) { + model.startAngle = opts.rotation; + } else { + model.startAngle = me.getMeta().data[index - 1]._model.endAngle; + } + + model.endAngle = model.startAngle + model.circumference; + } + + arc.pivot(); + }, + + calculateTotal: function() { + var dataset = this.getDataset(); + var meta = this.getMeta(); + var total = 0; + var value; + + helpers$1.each(meta.data, function(element, index) { + value = dataset.data[index]; + if (!isNaN(value) && !element.hidden) { + total += Math.abs(value); + } + }); + + /* if (total === 0) { + total = NaN; + }*/ + + return total; + }, + + calculateCircumference: function(value) { + var total = this.getMeta().total; + if (total > 0 && !isNaN(value)) { + return (Math.PI * 2.0) * (Math.abs(value) / total); + } + return 0; + }, + + // gets the max border or hover width to properly scale pie charts + getMaxBorderWidth: function(arcs) { + var me = this; + var max = 0; + var chart = me.chart; + var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth; + + if (!arcs) { + // Find the outmost visible dataset + for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) { + if (chart.isDatasetVisible(i)) { + meta = chart.getDatasetMeta(i); + arcs = meta.data; + if (i !== me.index) { + controller = meta.controller; + } + break; + } + } + } + + if (!arcs) { + return 0; + } + + for (i = 0, ilen = arcs.length; i < ilen; ++i) { + arc = arcs[i]; + options = controller ? controller._resolveElementOptions(arc, i) : arc._options; + if (options.borderAlign !== 'inner') { + borderWidth = options.borderWidth; + hoverWidth = options.hoverBorderWidth; + + max = borderWidth > max ? borderWidth : max; + max = hoverWidth > max ? hoverWidth : max; + } + } + return max; + }, + + /** + * @protected + */ + setHoverStyle: function(arc) { + var model = arc._model; + var options = arc._options; + var getHoverColor = helpers$1.getHoverColor; + + arc.$previousStyle = { + backgroundColor: model.backgroundColor, + borderColor: model.borderColor, + borderWidth: model.borderWidth, + }; + + model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor)); + model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor)); + model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth); + }, + + /** + * @private + */ + _resolveElementOptions: function(arc, index) { + var me = this; + var chart = me.chart; + var dataset = me.getDataset(); + var custom = arc.custom || {}; + var options = chart.options.elements.arc; + var values = {}; + var i, ilen, key; + + // Scriptable options + var context = { + chart: chart, + dataIndex: index, + dataset: dataset, + datasetIndex: me.index + }; + + var keys = [ + 'backgroundColor', + 'borderColor', + 'borderWidth', + 'borderAlign', + 'hoverBackgroundColor', + 'hoverBorderColor', + 'hoverBorderWidth', + ]; + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + values[key] = resolve$3([ + custom[key], + dataset[key], + options[key] + ], context, index); + } + + return values; + }, + + /** + * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly + * @private + */ + _getRingWeightOffset: function(datasetIndex) { + var ringWeightOffset = 0; + + for (var i = 0; i < datasetIndex; ++i) { + if (this.chart.isDatasetVisible(i)) { + ringWeightOffset += this._getRingWeight(i); + } + } + + return ringWeightOffset; + }, + + /** + * @private + */ + _getRingWeight: function(dataSetIndex) { + return Math.max(valueOrDefault$4(this.chart.data.datasets[dataSetIndex].weight, 1), 0); + }, + + /** + * Returns the sum of all visibile data set weights. This value can be 0. + * @private + */ + _getVisibleDatasetWeightTotal: function() { + return this._getRingWeightOffset(this.chart.data.datasets.length); + } +}); + +core_defaults._set('horizontalBar', { + hover: { + mode: 'index', + axis: 'y' + }, + + scales: { + xAxes: [{ + type: 'linear', + position: 'bottom' + }], + + yAxes: [{ + type: 'category', + position: 'left', + categoryPercentage: 0.8, + barPercentage: 0.9, + offset: true, + gridLines: { + offsetGridLines: true + } + }] + }, + + elements: { + rectangle: { + borderSkipped: 'left' + } + }, + + tooltips: { + mode: 'index', + axis: 'y' + } +}); + +var controller_horizontalBar = controller_bar.extend({ + /** + * @private + */ + _getValueScaleId: function() { + return this.getMeta().xAxisID; + }, + + /** + * @private + */ + _getIndexScaleId: function() { + return this.getMeta().yAxisID; + } +}); + +var valueOrDefault$5 = helpers$1.valueOrDefault; +var resolve$4 = helpers$1.options.resolve; +var isPointInArea = helpers$1.canvas._isPointInArea; + +core_defaults._set('line', { + showLines: true, + spanGaps: false, + + hover: { + mode: 'label' + }, + + scales: { + xAxes: [{ + type: 'category', + id: 'x-axis-0' + }], + yAxes: [{ + type: 'linear', + id: 'y-axis-0' + }] + } +}); + +function lineEnabled(dataset, options) { + return valueOrDefault$5(dataset.showLine, options.showLines); +} + +var controller_line = core_datasetController.extend({ + + datasetElementType: elements.Line, + + dataElementType: elements.Point, + + update: function(reset) { + var me = this; + var meta = me.getMeta(); + var line = meta.dataset; + var points = meta.data || []; + var scale = me.getScaleForId(meta.yAxisID); + var dataset = me.getDataset(); + var showLine = lineEnabled(dataset, me.chart.options); + var i, ilen; + + // Update Line + if (showLine) { + // Compatibility: If the properties are defined with only the old name, use those values + if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) { + dataset.lineTension = dataset.tension; + } + + // Utility + line._scale = scale; + line._datasetIndex = me.index; + // Data + line._children = points; + // Model + line._model = me._resolveLineOptions(line); + + line.pivot(); + } + + // Update Points + for (i = 0, ilen = points.length; i < ilen; ++i) { + me.updateElement(points[i], i, reset); + } + + if (showLine && line._model.tension !== 0) { + me.updateBezierControlPoints(); + } + + // Now pivot the point for animation + for (i = 0, ilen = points.length; i < ilen; ++i) { + points[i].pivot(); + } + }, + + updateElement: function(point, index, reset) { + var me = this; + var meta = me.getMeta(); + var custom = point.custom || {}; + var dataset = me.getDataset(); + var datasetIndex = me.index; + var value = dataset.data[index]; + var yScale = me.getScaleForId(meta.yAxisID); + var xScale = me.getScaleForId(meta.xAxisID); + var lineModel = meta.dataset._model; + var x, y; + + var options = me._resolvePointOptions(point, index); + + x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex); + y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex); + + // Utility + point._xScale = xScale; + point._yScale = yScale; + point._options = options; + point._datasetIndex = datasetIndex; + point._index = index; + + // Desired view properties + point._model = { + x: x, + y: y, + skip: custom.skip || isNaN(x) || isNaN(y), + // Appearance + radius: options.radius, + pointStyle: options.pointStyle, + rotation: options.rotation, + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderWidth: options.borderWidth, + tension: valueOrDefault$5(custom.tension, lineModel ? lineModel.tension : 0), + steppedLine: lineModel ? lineModel.steppedLine : false, + // Tooltip + hitRadius: options.hitRadius + }; + }, + + /** + * @private + */ + _resolvePointOptions: function(element, index) { + var me = this; + var chart = me.chart; + var dataset = chart.data.datasets[me.index]; + var custom = element.custom || {}; + var options = chart.options.elements.point; + var values = {}; + var i, ilen, key; + + // Scriptable options + var context = { + chart: chart, + dataIndex: index, + dataset: dataset, + datasetIndex: me.index + }; + + var ELEMENT_OPTIONS = { + backgroundColor: 'pointBackgroundColor', + borderColor: 'pointBorderColor', + borderWidth: 'pointBorderWidth', + hitRadius: 'pointHitRadius', + hoverBackgroundColor: 'pointHoverBackgroundColor', + hoverBorderColor: 'pointHoverBorderColor', + hoverBorderWidth: 'pointHoverBorderWidth', + hoverRadius: 'pointHoverRadius', + pointStyle: 'pointStyle', + radius: 'pointRadius', + rotation: 'pointRotation' + }; + var keys = Object.keys(ELEMENT_OPTIONS); + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + values[key] = resolve$4([ + custom[key], + dataset[ELEMENT_OPTIONS[key]], + dataset[key], + options[key] + ], context, index); + } + + return values; + }, + + /** + * @private + */ + _resolveLineOptions: function(element) { + var me = this; + var chart = me.chart; + var dataset = chart.data.datasets[me.index]; + var custom = element.custom || {}; + var options = chart.options; + var elementOptions = options.elements.line; + var values = {}; + var i, ilen, key; + + var keys = [ + 'backgroundColor', + 'borderWidth', + 'borderColor', + 'borderCapStyle', + 'borderDash', + 'borderDashOffset', + 'borderJoinStyle', + 'fill', + 'cubicInterpolationMode' + ]; + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + values[key] = resolve$4([ + custom[key], + dataset[key], + elementOptions[key] + ]); + } + + // The default behavior of lines is to break at null values, according + // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158 + // This option gives lines the ability to span gaps + values.spanGaps = valueOrDefault$5(dataset.spanGaps, options.spanGaps); + values.tension = valueOrDefault$5(dataset.lineTension, elementOptions.tension); + values.steppedLine = resolve$4([custom.steppedLine, dataset.steppedLine, elementOptions.stepped]); + + return values; + }, + + calculatePointY: function(value, index, datasetIndex) { + var me = this; + var chart = me.chart; + var meta = me.getMeta(); + var yScale = me.getScaleForId(meta.yAxisID); + var sumPos = 0; + var sumNeg = 0; + var i, ds, dsMeta; + + if (yScale.options.stacked) { + for (i = 0; i < datasetIndex; i++) { + ds = chart.data.datasets[i]; + dsMeta = chart.getDatasetMeta(i); + if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) { + var stackedRightValue = Number(yScale.getRightValue(ds.data[index])); + if (stackedRightValue < 0) { + sumNeg += stackedRightValue || 0; + } else { + sumPos += stackedRightValue || 0; + } + } + } + + var rightValue = Number(yScale.getRightValue(value)); + if (rightValue < 0) { + return yScale.getPixelForValue(sumNeg + rightValue); + } + return yScale.getPixelForValue(sumPos + rightValue); + } + + return yScale.getPixelForValue(value); + }, + + updateBezierControlPoints: function() { + var me = this; + var chart = me.chart; + var meta = me.getMeta(); + var lineModel = meta.dataset._model; + var area = chart.chartArea; + var points = meta.data || []; + var i, ilen, model, controlPoints; + + // Only consider points that are drawn in case the spanGaps option is used + if (lineModel.spanGaps) { + points = points.filter(function(pt) { + return !pt._model.skip; + }); + } + + function capControlPoint(pt, min, max) { + return Math.max(Math.min(pt, max), min); + } + + if (lineModel.cubicInterpolationMode === 'monotone') { + helpers$1.splineCurveMonotone(points); + } else { + for (i = 0, ilen = points.length; i < ilen; ++i) { + model = points[i]._model; + controlPoints = helpers$1.splineCurve( + helpers$1.previousItem(points, i)._model, + model, + helpers$1.nextItem(points, i)._model, + lineModel.tension + ); + model.controlPointPreviousX = controlPoints.previous.x; + model.controlPointPreviousY = controlPoints.previous.y; + model.controlPointNextX = controlPoints.next.x; + model.controlPointNextY = controlPoints.next.y; + } + } + + if (chart.options.elements.line.capBezierPoints) { + for (i = 0, ilen = points.length; i < ilen; ++i) { + model = points[i]._model; + if (isPointInArea(model, area)) { + if (i > 0 && isPointInArea(points[i - 1]._model, area)) { + model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right); + model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom); + } + if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) { + model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right); + model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom); + } + } + } + } + }, + + draw: function() { + var me = this; + var chart = me.chart; + var meta = me.getMeta(); + var points = meta.data || []; + var area = chart.chartArea; + var ilen = points.length; + var halfBorderWidth; + var i = 0; + + if (lineEnabled(me.getDataset(), chart.options)) { + halfBorderWidth = (meta.dataset._model.borderWidth || 0) / 2; + + helpers$1.canvas.clipArea(chart.ctx, { + left: area.left, + right: area.right, + top: area.top - halfBorderWidth, + bottom: area.bottom + halfBorderWidth + }); + + meta.dataset.draw(); + + helpers$1.canvas.unclipArea(chart.ctx); + } + + // Draw the points + for (; i < ilen; ++i) { + points[i].draw(area); + } + }, + + /** + * @protected + */ + setHoverStyle: function(point) { + var model = point._model; + var options = point._options; + var getHoverColor = helpers$1.getHoverColor; + + point.$previousStyle = { + backgroundColor: model.backgroundColor, + borderColor: model.borderColor, + borderWidth: model.borderWidth, + radius: model.radius + }; + + model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor)); + model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor)); + model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth); + model.radius = valueOrDefault$5(options.hoverRadius, options.radius); + }, +}); + +var resolve$5 = helpers$1.options.resolve; + +core_defaults._set('polarArea', { + scale: { + type: 'radialLinear', + angleLines: { + display: false + }, + gridLines: { + circular: true + }, + pointLabels: { + display: false + }, + ticks: { + beginAtZero: true + } + }, + + // Boolean - Whether to animate the rotation of the chart + animation: { + animateRotate: true, + animateScale: true + }, + + startAngle: -0.5 * Math.PI, + legendCallback: function(chart) { + var text = []; + text.push('
      '); + + var data = chart.data; + var datasets = data.datasets; + var labels = data.labels; + + if (datasets.length) { + for (var i = 0; i < datasets[0].data.length; ++i) { + text.push('
    • '); + if (labels[i]) { + text.push(labels[i]); + } + text.push('
    • '); + } + } + + text.push('
    '); + return text.join(''); + }, + legend: { + labels: { + generateLabels: function(chart) { + var data = chart.data; + if (data.labels.length && data.datasets.length) { + return data.labels.map(function(label, i) { + var meta = chart.getDatasetMeta(0); + var ds = data.datasets[0]; + var arc = meta.data[i]; + var custom = arc.custom || {}; + var arcOpts = chart.options.elements.arc; + var fill = resolve$5([custom.backgroundColor, ds.backgroundColor, arcOpts.backgroundColor], undefined, i); + var stroke = resolve$5([custom.borderColor, ds.borderColor, arcOpts.borderColor], undefined, i); + var bw = resolve$5([custom.borderWidth, ds.borderWidth, arcOpts.borderWidth], undefined, i); + + return { + text: label, + fillStyle: fill, + strokeStyle: stroke, + lineWidth: bw, + hidden: isNaN(ds.data[i]) || meta.data[i].hidden, + + // Extra data used for toggling the correct item + index: i + }; + }); + } + return []; + } + }, + + onClick: function(e, legendItem) { + var index = legendItem.index; + var chart = this.chart; + var i, ilen, meta; + + for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { + meta = chart.getDatasetMeta(i); + meta.data[index].hidden = !meta.data[index].hidden; + } + + chart.update(); + } + }, + + // Need to override these to give a nice default + tooltips: { + callbacks: { + title: function() { + return ''; + }, + label: function(item, data) { + return data.labels[item.index] + ': ' + item.yLabel; + } + } + } +}); + +var controller_polarArea = core_datasetController.extend({ + + dataElementType: elements.Arc, + + linkScales: helpers$1.noop, + + update: function(reset) { + var me = this; + var dataset = me.getDataset(); + var meta = me.getMeta(); + var start = me.chart.options.startAngle || 0; + var starts = me._starts = []; + var angles = me._angles = []; + var arcs = meta.data; + var i, ilen, angle; + + me._updateRadius(); + + meta.count = me.countVisibleElements(); + + for (i = 0, ilen = dataset.data.length; i < ilen; i++) { + starts[i] = start; + angle = me._computeAngle(i); + angles[i] = angle; + start += angle; + } + + for (i = 0, ilen = arcs.length; i < ilen; ++i) { + arcs[i]._options = me._resolveElementOptions(arcs[i], i); + me.updateElement(arcs[i], i, reset); + } + }, + + /** + * @private + */ + _updateRadius: function() { + var me = this; + var chart = me.chart; + var chartArea = chart.chartArea; + var opts = chart.options; + var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); + + chart.outerRadius = Math.max(minSize / 2, 0); + chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0); + chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount(); + + me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index); + me.innerRadius = me.outerRadius - chart.radiusLength; + }, + + updateElement: function(arc, index, reset) { + var me = this; + var chart = me.chart; + var dataset = me.getDataset(); + var opts = chart.options; + var animationOpts = opts.animation; + var scale = chart.scale; + var labels = chart.data.labels; + + var centerX = scale.xCenter; + var centerY = scale.yCenter; + + // var negHalfPI = -0.5 * Math.PI; + var datasetStartAngle = opts.startAngle; + var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); + var startAngle = me._starts[index]; + var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]); + + var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); + var options = arc._options || {}; + + helpers$1.extend(arc, { + // Utility + _datasetIndex: me.index, + _index: index, + _scale: scale, + + // Desired view properties + _model: { + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderWidth: options.borderWidth, + borderAlign: options.borderAlign, + x: centerX, + y: centerY, + innerRadius: 0, + outerRadius: reset ? resetRadius : distance, + startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle, + endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle, + label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index]) + } + }); + + arc.pivot(); + }, + + countVisibleElements: function() { + var dataset = this.getDataset(); + var meta = this.getMeta(); + var count = 0; + + helpers$1.each(meta.data, function(element, index) { + if (!isNaN(dataset.data[index]) && !element.hidden) { + count++; + } + }); + + return count; + }, + + /** + * @protected + */ + setHoverStyle: function(arc) { + var model = arc._model; + var options = arc._options; + var getHoverColor = helpers$1.getHoverColor; + var valueOrDefault = helpers$1.valueOrDefault; + + arc.$previousStyle = { + backgroundColor: model.backgroundColor, + borderColor: model.borderColor, + borderWidth: model.borderWidth, + }; + + model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor)); + model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor)); + model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth); + }, + + /** + * @private + */ + _resolveElementOptions: function(arc, index) { + var me = this; + var chart = me.chart; + var dataset = me.getDataset(); + var custom = arc.custom || {}; + var options = chart.options.elements.arc; + var values = {}; + var i, ilen, key; + + // Scriptable options + var context = { + chart: chart, + dataIndex: index, + dataset: dataset, + datasetIndex: me.index + }; + + var keys = [ + 'backgroundColor', + 'borderColor', + 'borderWidth', + 'borderAlign', + 'hoverBackgroundColor', + 'hoverBorderColor', + 'hoverBorderWidth', + ]; + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + values[key] = resolve$5([ + custom[key], + dataset[key], + options[key] + ], context, index); + } + + return values; + }, + + /** + * @private + */ + _computeAngle: function(index) { + var me = this; + var count = this.getMeta().count; + var dataset = me.getDataset(); + var meta = me.getMeta(); + + if (isNaN(dataset.data[index]) || meta.data[index].hidden) { + return 0; + } + + // Scriptable options + var context = { + chart: me.chart, + dataIndex: index, + dataset: dataset, + datasetIndex: me.index + }; + + return resolve$5([ + me.chart.options.elements.arc.angle, + (2 * Math.PI) / count + ], context, index); + } +}); + +core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut)); +core_defaults._set('pie', { + cutoutPercentage: 0 +}); + +// Pie charts are Doughnut chart with different defaults +var controller_pie = controller_doughnut; + +var valueOrDefault$6 = helpers$1.valueOrDefault; +var resolve$6 = helpers$1.options.resolve; + +core_defaults._set('radar', { + scale: { + type: 'radialLinear' + }, + elements: { + line: { + tension: 0 // no bezier in radar + } + } +}); + +var controller_radar = core_datasetController.extend({ + + datasetElementType: elements.Line, + + dataElementType: elements.Point, + + linkScales: helpers$1.noop, + + update: function(reset) { + var me = this; + var meta = me.getMeta(); + var line = meta.dataset; + var points = meta.data || []; + var scale = me.chart.scale; + var dataset = me.getDataset(); + var i, ilen; + + // Compatibility: If the properties are defined with only the old name, use those values + if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) { + dataset.lineTension = dataset.tension; + } + + // Utility + line._scale = scale; + line._datasetIndex = me.index; + // Data + line._children = points; + line._loop = true; + // Model + line._model = me._resolveLineOptions(line); + + line.pivot(); + + // Update Points + for (i = 0, ilen = points.length; i < ilen; ++i) { + me.updateElement(points[i], i, reset); + } + + // Update bezier control points + me.updateBezierControlPoints(); + + // Now pivot the point for animation + for (i = 0, ilen = points.length; i < ilen; ++i) { + points[i].pivot(); + } + }, + + updateElement: function(point, index, reset) { + var me = this; + var custom = point.custom || {}; + var dataset = me.getDataset(); + var scale = me.chart.scale; + var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]); + var options = me._resolvePointOptions(point, index); + var lineModel = me.getMeta().dataset._model; + var x = reset ? scale.xCenter : pointPosition.x; + var y = reset ? scale.yCenter : pointPosition.y; + + // Utility + point._scale = scale; + point._options = options; + point._datasetIndex = me.index; + point._index = index; + + // Desired view properties + point._model = { + x: x, // value not used in dataset scale, but we want a consistent API between scales + y: y, + skip: custom.skip || isNaN(x) || isNaN(y), + // Appearance + radius: options.radius, + pointStyle: options.pointStyle, + rotation: options.rotation, + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderWidth: options.borderWidth, + tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0), + + // Tooltip + hitRadius: options.hitRadius + }; + }, + + /** + * @private + */ + _resolvePointOptions: function(element, index) { + var me = this; + var chart = me.chart; + var dataset = chart.data.datasets[me.index]; + var custom = element.custom || {}; + var options = chart.options.elements.point; + var values = {}; + var i, ilen, key; + + // Scriptable options + var context = { + chart: chart, + dataIndex: index, + dataset: dataset, + datasetIndex: me.index + }; + + var ELEMENT_OPTIONS = { + backgroundColor: 'pointBackgroundColor', + borderColor: 'pointBorderColor', + borderWidth: 'pointBorderWidth', + hitRadius: 'pointHitRadius', + hoverBackgroundColor: 'pointHoverBackgroundColor', + hoverBorderColor: 'pointHoverBorderColor', + hoverBorderWidth: 'pointHoverBorderWidth', + hoverRadius: 'pointHoverRadius', + pointStyle: 'pointStyle', + radius: 'pointRadius', + rotation: 'pointRotation' + }; + var keys = Object.keys(ELEMENT_OPTIONS); + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + values[key] = resolve$6([ + custom[key], + dataset[ELEMENT_OPTIONS[key]], + dataset[key], + options[key] + ], context, index); + } + + return values; + }, + + /** + * @private + */ + _resolveLineOptions: function(element) { + var me = this; + var chart = me.chart; + var dataset = chart.data.datasets[me.index]; + var custom = element.custom || {}; + var options = chart.options.elements.line; + var values = {}; + var i, ilen, key; + + var keys = [ + 'backgroundColor', + 'borderWidth', + 'borderColor', + 'borderCapStyle', + 'borderDash', + 'borderDashOffset', + 'borderJoinStyle', + 'fill' + ]; + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + values[key] = resolve$6([ + custom[key], + dataset[key], + options[key] + ]); + } + + values.tension = valueOrDefault$6(dataset.lineTension, options.tension); + + return values; + }, + + updateBezierControlPoints: function() { + var me = this; + var meta = me.getMeta(); + var area = me.chart.chartArea; + var points = meta.data || []; + var i, ilen, model, controlPoints; + + function capControlPoint(pt, min, max) { + return Math.max(Math.min(pt, max), min); + } + + for (i = 0, ilen = points.length; i < ilen; ++i) { + model = points[i]._model; + controlPoints = helpers$1.splineCurve( + helpers$1.previousItem(points, i, true)._model, + model, + helpers$1.nextItem(points, i, true)._model, + model.tension + ); + + // Prevent the bezier going outside of the bounds of the graph + model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right); + model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom); + model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right); + model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom); + } + }, + + setHoverStyle: function(point) { + var model = point._model; + var options = point._options; + var getHoverColor = helpers$1.getHoverColor; + + point.$previousStyle = { + backgroundColor: model.backgroundColor, + borderColor: model.borderColor, + borderWidth: model.borderWidth, + radius: model.radius + }; + + model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor)); + model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor)); + model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth); + model.radius = valueOrDefault$6(options.hoverRadius, options.radius); + } +}); + +core_defaults._set('scatter', { + hover: { + mode: 'single' + }, + + scales: { + xAxes: [{ + id: 'x-axis-1', // need an ID so datasets can reference the scale + type: 'linear', // scatter should not use a category axis + position: 'bottom' + }], + yAxes: [{ + id: 'y-axis-1', + type: 'linear', + position: 'left' + }] + }, + + showLines: false, + + tooltips: { + callbacks: { + title: function() { + return ''; // doesn't make sense for scatter since data are formatted as a point + }, + label: function(item) { + return '(' + item.xLabel + ', ' + item.yLabel + ')'; + } + } + } +}); + +// Scatter charts use line controllers +var controller_scatter = controller_line; + +// NOTE export a map in which the key represents the controller type, not +// the class, and so must be CamelCase in order to be correctly retrieved +// by the controller in core.controller.js (`controllers[meta.type]`). + +var controllers = { + bar: controller_bar, + bubble: controller_bubble, + doughnut: controller_doughnut, + horizontalBar: controller_horizontalBar, + line: controller_line, + polarArea: controller_polarArea, + pie: controller_pie, + radar: controller_radar, + scatter: controller_scatter +}; + +/** + * Helper function to get relative position for an event + * @param {Event|IEvent} event - The event to get the position for + * @param {Chart} chart - The chart + * @returns {object} the event position + */ +function getRelativePosition(e, chart) { + if (e.native) { + return { + x: e.x, + y: e.y + }; + } + + return helpers$1.getRelativePosition(e, chart); +} + +/** + * Helper function to traverse all of the visible elements in the chart + * @param {Chart} chart - the chart + * @param {function} handler - the callback to execute for each visible item + */ +function parseVisibleItems(chart, handler) { + var datasets = chart.data.datasets; + var meta, i, j, ilen, jlen; + + for (i = 0, ilen = datasets.length; i < ilen; ++i) { + if (!chart.isDatasetVisible(i)) { + continue; + } + + meta = chart.getDatasetMeta(i); + for (j = 0, jlen = meta.data.length; j < jlen; ++j) { + var element = meta.data[j]; + if (!element._view.skip) { + handler(element); + } + } + } +} + +/** + * Helper function to get the items that intersect the event position + * @param {ChartElement[]} items - elements to filter + * @param {object} position - the point to be nearest to + * @return {ChartElement[]} the nearest items + */ +function getIntersectItems(chart, position) { + var elements = []; + + parseVisibleItems(chart, function(element) { + if (element.inRange(position.x, position.y)) { + elements.push(element); + } + }); + + return elements; +} + +/** + * Helper function to get the items nearest to the event position considering all visible items in teh chart + * @param {Chart} chart - the chart to look at elements from + * @param {object} position - the point to be nearest to + * @param {boolean} intersect - if true, only consider items that intersect the position + * @param {function} distanceMetric - function to provide the distance between points + * @return {ChartElement[]} the nearest items + */ +function getNearestItems(chart, position, intersect, distanceMetric) { + var minDistance = Number.POSITIVE_INFINITY; + var nearestItems = []; + + parseVisibleItems(chart, function(element) { + if (intersect && !element.inRange(position.x, position.y)) { + return; + } + + var center = element.getCenterPoint(); + var distance = distanceMetric(position, center); + if (distance < minDistance) { + nearestItems = [element]; + minDistance = distance; + } else if (distance === minDistance) { + // Can have multiple items at the same distance in which case we sort by size + nearestItems.push(element); + } + }); + + return nearestItems; +} + +/** + * Get a distance metric function for two points based on the + * axis mode setting + * @param {string} axis - the axis mode. x|y|xy + */ +function getDistanceMetricForAxis(axis) { + var useX = axis.indexOf('x') !== -1; + var useY = axis.indexOf('y') !== -1; + + return function(pt1, pt2) { + var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0; + var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0; + return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); + }; +} + +function indexMode(chart, e, options) { + var position = getRelativePosition(e, chart); + // Default axis for index mode is 'x' to match old behaviour + options.axis = options.axis || 'x'; + var distanceMetric = getDistanceMetricForAxis(options.axis); + var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric); + var elements = []; + + if (!items.length) { + return []; + } + + chart.data.datasets.forEach(function(dataset, datasetIndex) { + if (chart.isDatasetVisible(datasetIndex)) { + var meta = chart.getDatasetMeta(datasetIndex); + var element = meta.data[items[0]._index]; + + // don't count items that are skipped (null data) + if (element && !element._view.skip) { + elements.push(element); + } + } + }); + + return elements; +} + +/** + * @interface IInteractionOptions + */ +/** + * If true, only consider items that intersect the point + * @name IInterfaceOptions#boolean + * @type Boolean + */ + +/** + * Contains interaction related functions + * @namespace Chart.Interaction + */ +var core_interaction = { + // Helper function for different modes + modes: { + single: function(chart, e) { + var position = getRelativePosition(e, chart); + var elements = []; + + parseVisibleItems(chart, function(element) { + if (element.inRange(position.x, position.y)) { + elements.push(element); + return elements; + } + }); + + return elements.slice(0, 1); + }, + + /** + * @function Chart.Interaction.modes.label + * @deprecated since version 2.4.0 + * @todo remove at version 3 + * @private + */ + label: indexMode, + + /** + * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something + * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item + * @function Chart.Interaction.modes.index + * @since v2.4.0 + * @param {Chart} chart - the chart we are returning items from + * @param {Event} e - the event we are find things at + * @param {IInteractionOptions} options - options to use during interaction + * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned + */ + index: indexMode, + + /** + * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something + * If the options.intersect is false, we find the nearest item and return the items in that dataset + * @function Chart.Interaction.modes.dataset + * @param {Chart} chart - the chart we are returning items from + * @param {Event} e - the event we are find things at + * @param {IInteractionOptions} options - options to use during interaction + * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned + */ + dataset: function(chart, e, options) { + var position = getRelativePosition(e, chart); + options.axis = options.axis || 'xy'; + var distanceMetric = getDistanceMetricForAxis(options.axis); + var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric); + + if (items.length > 0) { + items = chart.getDatasetMeta(items[0]._datasetIndex).data; + } + + return items; + }, + + /** + * @function Chart.Interaction.modes.x-axis + * @deprecated since version 2.4.0. Use index mode and intersect == true + * @todo remove at version 3 + * @private + */ + 'x-axis': function(chart, e) { + return indexMode(chart, e, {intersect: false}); + }, + + /** + * Point mode returns all elements that hit test based on the event position + * of the event + * @function Chart.Interaction.modes.intersect + * @param {Chart} chart - the chart we are returning items from + * @param {Event} e - the event we are find things at + * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned + */ + point: function(chart, e) { + var position = getRelativePosition(e, chart); + return getIntersectItems(chart, position); + }, + + /** + * nearest mode returns the element closest to the point + * @function Chart.Interaction.modes.intersect + * @param {Chart} chart - the chart we are returning items from + * @param {Event} e - the event we are find things at + * @param {IInteractionOptions} options - options to use + * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned + */ + nearest: function(chart, e, options) { + var position = getRelativePosition(e, chart); + options.axis = options.axis || 'xy'; + var distanceMetric = getDistanceMetricForAxis(options.axis); + return getNearestItems(chart, position, options.intersect, distanceMetric); + }, + + /** + * x mode returns the elements that hit-test at the current x coordinate + * @function Chart.Interaction.modes.x + * @param {Chart} chart - the chart we are returning items from + * @param {Event} e - the event we are find things at + * @param {IInteractionOptions} options - options to use + * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned + */ + x: function(chart, e, options) { + var position = getRelativePosition(e, chart); + var items = []; + var intersectsItem = false; + + parseVisibleItems(chart, function(element) { + if (element.inXRange(position.x)) { + items.push(element); + } + + if (element.inRange(position.x, position.y)) { + intersectsItem = true; + } + }); + + // If we want to trigger on an intersect and we don't have any items + // that intersect the position, return nothing + if (options.intersect && !intersectsItem) { + items = []; + } + return items; + }, + + /** + * y mode returns the elements that hit-test at the current y coordinate + * @function Chart.Interaction.modes.y + * @param {Chart} chart - the chart we are returning items from + * @param {Event} e - the event we are find things at + * @param {IInteractionOptions} options - options to use + * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned + */ + y: function(chart, e, options) { + var position = getRelativePosition(e, chart); + var items = []; + var intersectsItem = false; + + parseVisibleItems(chart, function(element) { + if (element.inYRange(position.y)) { + items.push(element); + } + + if (element.inRange(position.x, position.y)) { + intersectsItem = true; + } + }); + + // If we want to trigger on an intersect and we don't have any items + // that intersect the position, return nothing + if (options.intersect && !intersectsItem) { + items = []; + } + return items; + } + } +}; + +function filterByPosition(array, position) { + return helpers$1.where(array, function(v) { + return v.position === position; + }); +} + +function sortByWeight(array, reverse) { + array.forEach(function(v, i) { + v._tmpIndex_ = i; + return v; + }); + array.sort(function(a, b) { + var v0 = reverse ? b : a; + var v1 = reverse ? a : b; + return v0.weight === v1.weight ? + v0._tmpIndex_ - v1._tmpIndex_ : + v0.weight - v1.weight; + }); + array.forEach(function(v) { + delete v._tmpIndex_; + }); +} + +function findMaxPadding(boxes) { + var top = 0; + var left = 0; + var bottom = 0; + var right = 0; + helpers$1.each(boxes, function(box) { + if (box.getPadding) { + var boxPadding = box.getPadding(); + top = Math.max(top, boxPadding.top); + left = Math.max(left, boxPadding.left); + bottom = Math.max(bottom, boxPadding.bottom); + right = Math.max(right, boxPadding.right); + } + }); + return { + top: top, + left: left, + bottom: bottom, + right: right + }; +} + +function addSizeByPosition(boxes, size) { + helpers$1.each(boxes, function(box) { + size[box.position] += box.isHorizontal() ? box.height : box.width; + }); +} + +core_defaults._set('global', { + layout: { + padding: { + top: 0, + right: 0, + bottom: 0, + left: 0 + } + } +}); + +/** + * @interface ILayoutItem + * @prop {string} position - The position of the item in the chart layout. Possible values are + * 'left', 'top', 'right', 'bottom', and 'chartArea' + * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area + * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down + * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom) + * @prop {function} update - Takes two parameters: width and height. Returns size of item + * @prop {function} getPadding - Returns an object with padding on the edges + * @prop {number} width - Width of item. Must be valid after update() + * @prop {number} height - Height of item. Must be valid after update() + * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update + * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update + * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update + * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update + */ + +// The layout service is very self explanatory. It's responsible for the layout within a chart. +// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need +// It is this service's responsibility of carrying out that layout. +var core_layouts = { + defaults: {}, + + /** + * Register a box to a chart. + * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title. + * @param {Chart} chart - the chart to use + * @param {ILayoutItem} item - the item to add to be layed out + */ + addBox: function(chart, item) { + if (!chart.boxes) { + chart.boxes = []; + } + + // initialize item with default values + item.fullWidth = item.fullWidth || false; + item.position = item.position || 'top'; + item.weight = item.weight || 0; + + chart.boxes.push(item); + }, + + /** + * Remove a layoutItem from a chart + * @param {Chart} chart - the chart to remove the box from + * @param {ILayoutItem} layoutItem - the item to remove from the layout + */ + removeBox: function(chart, layoutItem) { + var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1; + if (index !== -1) { + chart.boxes.splice(index, 1); + } + }, + + /** + * Sets (or updates) options on the given `item`. + * @param {Chart} chart - the chart in which the item lives (or will be added to) + * @param {ILayoutItem} item - the item to configure with the given options + * @param {object} options - the new item options. + */ + configure: function(chart, item, options) { + var props = ['fullWidth', 'position', 'weight']; + var ilen = props.length; + var i = 0; + var prop; + + for (; i < ilen; ++i) { + prop = props[i]; + if (options.hasOwnProperty(prop)) { + item[prop] = options[prop]; + } + } + }, + + /** + * Fits boxes of the given chart into the given size by having each box measure itself + * then running a fitting algorithm + * @param {Chart} chart - the chart + * @param {number} width - the width to fit into + * @param {number} height - the height to fit into + */ + update: function(chart, width, height) { + if (!chart) { + return; + } + + var layoutOptions = chart.options.layout || {}; + var padding = helpers$1.options.toPadding(layoutOptions.padding); + var leftPadding = padding.left; + var rightPadding = padding.right; + var topPadding = padding.top; + var bottomPadding = padding.bottom; + + var leftBoxes = filterByPosition(chart.boxes, 'left'); + var rightBoxes = filterByPosition(chart.boxes, 'right'); + var topBoxes = filterByPosition(chart.boxes, 'top'); + var bottomBoxes = filterByPosition(chart.boxes, 'bottom'); + var chartAreaBoxes = filterByPosition(chart.boxes, 'chartArea'); + + // Sort boxes by weight. A higher weight is further away from the chart area + sortByWeight(leftBoxes, true); + sortByWeight(rightBoxes, false); + sortByWeight(topBoxes, true); + sortByWeight(bottomBoxes, false); + + var verticalBoxes = leftBoxes.concat(rightBoxes); + var horizontalBoxes = topBoxes.concat(bottomBoxes); + var outerBoxes = verticalBoxes.concat(horizontalBoxes); + + // Essentially we now have any number of boxes on each of the 4 sides. + // Our canvas looks like the following. + // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and + // B1 is the bottom axis + // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays + // These locations are single-box locations only, when trying to register a chartArea location that is already taken, + // an error will be thrown. + // + // |----------------------------------------------------| + // | T1 (Full Width) | + // |----------------------------------------------------| + // | | | T2 | | + // | |----|-------------------------------------|----| + // | | | C1 | | C2 | | + // | | |----| |----| | + // | | | | | + // | L1 | L2 | ChartArea (C0) | R1 | + // | | | | | + // | | |----| |----| | + // | | | C3 | | C4 | | + // | |----|-------------------------------------|----| + // | | | B1 | | + // |----------------------------------------------------| + // | B2 (Full Width) | + // |----------------------------------------------------| + // + // What we do to find the best sizing, we do the following + // 1. Determine the minimum size of the chart area. + // 2. Split the remaining width equally between each vertical axis + // 3. Split the remaining height equally between each horizontal axis + // 4. Give each layout the maximum size it can be. The layout will return it's minimum size + // 5. Adjust the sizes of each axis based on it's minimum reported size. + // 6. Refit each axis + // 7. Position each axis in the final location + // 8. Tell the chart the final location of the chart area + // 9. Tell any axes that overlay the chart area the positions of the chart area + + // Step 1 + var chartWidth = width - leftPadding - rightPadding; + var chartHeight = height - topPadding - bottomPadding; + var chartAreaWidth = chartWidth / 2; // min 50% + + // Step 2 + var verticalBoxWidth = (width - chartAreaWidth) / verticalBoxes.length; + + // Step 3 + // TODO re-limit horizontal axis height (this limit has affected only padding calculation since PR 1837) + // var horizontalBoxHeight = (height - chartAreaHeight) / horizontalBoxes.length; + + // Step 4 + var maxChartAreaWidth = chartWidth; + var maxChartAreaHeight = chartHeight; + var outerBoxSizes = {top: topPadding, left: leftPadding, bottom: bottomPadding, right: rightPadding}; + var minBoxSizes = []; + var maxPadding; + + function getMinimumBoxSize(box) { + var minSize; + var isHorizontal = box.isHorizontal(); + + if (isHorizontal) { + minSize = box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2); + maxChartAreaHeight -= minSize.height; + } else { + minSize = box.update(verticalBoxWidth, maxChartAreaHeight); + maxChartAreaWidth -= minSize.width; + } + + minBoxSizes.push({ + horizontal: isHorizontal, + width: minSize.width, + box: box, + }); + } + + helpers$1.each(outerBoxes, getMinimumBoxSize); + + // If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478) + maxPadding = findMaxPadding(outerBoxes); + + // At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could + // be if the axes are drawn at their minimum sizes. + // Steps 5 & 6 + + // Function to fit a box + function fitBox(box) { + var minBoxSize = helpers$1.findNextWhere(minBoxSizes, function(minBox) { + return minBox.box === box; + }); + + if (minBoxSize) { + if (minBoxSize.horizontal) { + var scaleMargin = { + left: Math.max(outerBoxSizes.left, maxPadding.left), + right: Math.max(outerBoxSizes.right, maxPadding.right), + top: 0, + bottom: 0 + }; + + // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends + // on the margin. Sometimes they need to increase in size slightly + box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin); + } else { + box.update(minBoxSize.width, maxChartAreaHeight); + } + } + } + + // Update, and calculate the left and right margins for the horizontal boxes + helpers$1.each(verticalBoxes, fitBox); + addSizeByPosition(verticalBoxes, outerBoxSizes); + + // Set the Left and Right margins for the horizontal boxes + helpers$1.each(horizontalBoxes, fitBox); + addSizeByPosition(horizontalBoxes, outerBoxSizes); + + function finalFitVerticalBox(box) { + var minBoxSize = helpers$1.findNextWhere(minBoxSizes, function(minSize) { + return minSize.box === box; + }); + + var scaleMargin = { + left: 0, + right: 0, + top: outerBoxSizes.top, + bottom: outerBoxSizes.bottom + }; + + if (minBoxSize) { + box.update(minBoxSize.width, maxChartAreaHeight, scaleMargin); + } + } + + // Let the left layout know the final margin + helpers$1.each(verticalBoxes, finalFitVerticalBox); + + // Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance) + outerBoxSizes = {top: topPadding, left: leftPadding, bottom: bottomPadding, right: rightPadding}; + addSizeByPosition(outerBoxes, outerBoxSizes); + + // We may be adding some padding to account for rotated x axis labels + var leftPaddingAddition = Math.max(maxPadding.left - outerBoxSizes.left, 0); + outerBoxSizes.left += leftPaddingAddition; + outerBoxSizes.right += Math.max(maxPadding.right - outerBoxSizes.right, 0); + + var topPaddingAddition = Math.max(maxPadding.top - outerBoxSizes.top, 0); + outerBoxSizes.top += topPaddingAddition; + outerBoxSizes.bottom += Math.max(maxPadding.bottom - outerBoxSizes.bottom, 0); + + // Figure out if our chart area changed. This would occur if the dataset layout label rotation + // changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do + // without calling `fit` again + var newMaxChartAreaHeight = height - outerBoxSizes.top - outerBoxSizes.bottom; + var newMaxChartAreaWidth = width - outerBoxSizes.left - outerBoxSizes.right; + + if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) { + helpers$1.each(verticalBoxes, function(box) { + box.height = newMaxChartAreaHeight; + }); + + helpers$1.each(horizontalBoxes, function(box) { + if (!box.fullWidth) { + box.width = newMaxChartAreaWidth; + } + }); + + maxChartAreaHeight = newMaxChartAreaHeight; + maxChartAreaWidth = newMaxChartAreaWidth; + } + + // Step 7 - Position the boxes + var left = leftPadding + leftPaddingAddition; + var top = topPadding + topPaddingAddition; + + function placeBox(box) { + if (box.isHorizontal()) { + box.left = box.fullWidth ? leftPadding : outerBoxSizes.left; + box.right = box.fullWidth ? width - rightPadding : outerBoxSizes.left + maxChartAreaWidth; + box.top = top; + box.bottom = top + box.height; + + // Move to next point + top = box.bottom; + + } else { + + box.left = left; + box.right = left + box.width; + box.top = outerBoxSizes.top; + box.bottom = outerBoxSizes.top + maxChartAreaHeight; + + // Move to next point + left = box.right; + } + } + + helpers$1.each(leftBoxes.concat(topBoxes), placeBox); + + // Account for chart width and height + left += maxChartAreaWidth; + top += maxChartAreaHeight; + + helpers$1.each(rightBoxes, placeBox); + helpers$1.each(bottomBoxes, placeBox); + + // Step 8 + chart.chartArea = { + left: outerBoxSizes.left, + top: outerBoxSizes.top, + right: outerBoxSizes.left + maxChartAreaWidth, + bottom: outerBoxSizes.top + maxChartAreaHeight + }; + + // Step 9 + helpers$1.each(chartAreaBoxes, function(box) { + box.left = chart.chartArea.left; + box.top = chart.chartArea.top; + box.right = chart.chartArea.right; + box.bottom = chart.chartArea.bottom; + + box.update(maxChartAreaWidth, maxChartAreaHeight); + }); + } +}; + +/** + * Platform fallback implementation (minimal). + * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939 + */ + +var platform_basic = { + acquireContext: function(item) { + if (item && item.canvas) { + // Support for any object associated to a canvas (including a context2d) + item = item.canvas; + } + + return item && item.getContext('2d') || null; + } +}; + +var platform_dom = "/*\n * DOM element rendering detection\n * https://davidwalsh.name/detect-node-insertion\n */\n@keyframes chartjs-render-animation {\n\tfrom { opacity: 0.99; }\n\tto { opacity: 1; }\n}\n\n.chartjs-render-monitor {\n\tanimation: chartjs-render-animation 0.001s;\n}\n\n/*\n * DOM element resizing detection\n * https://github.com/marcj/css-element-queries\n */\n.chartjs-size-monitor,\n.chartjs-size-monitor-expand,\n.chartjs-size-monitor-shrink {\n\tposition: absolute;\n\tdirection: ltr;\n\tleft: 0;\n\ttop: 0;\n\tright: 0;\n\tbottom: 0;\n\toverflow: hidden;\n\tpointer-events: none;\n\tvisibility: hidden;\n\tz-index: -1;\n}\n\n.chartjs-size-monitor-expand > div {\n\tposition: absolute;\n\twidth: 1000000px;\n\theight: 1000000px;\n\tleft: 0;\n\ttop: 0;\n}\n\n.chartjs-size-monitor-shrink > div {\n\tposition: absolute;\n\twidth: 200%;\n\theight: 200%;\n\tleft: 0;\n\ttop: 0;\n}\n"; + +var platform_dom$1 = /*#__PURE__*/Object.freeze({ +default: platform_dom +}); + +function getCjsExportFromNamespace (n) { + return n && n.default || n; +} + +var stylesheet = getCjsExportFromNamespace(platform_dom$1); + +var EXPANDO_KEY = '$chartjs'; +var CSS_PREFIX = 'chartjs-'; +var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor'; +var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor'; +var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation'; +var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart']; + +/** + * DOM event types -> Chart.js event types. + * Note: only events with different types are mapped. + * @see https://developer.mozilla.org/en-US/docs/Web/Events + */ +var EVENT_TYPES = { + touchstart: 'mousedown', + touchmove: 'mousemove', + touchend: 'mouseup', + pointerenter: 'mouseenter', + pointerdown: 'mousedown', + pointermove: 'mousemove', + pointerup: 'mouseup', + pointerleave: 'mouseout', + pointerout: 'mouseout' +}; + +/** + * The "used" size is the final value of a dimension property after all calculations have + * been performed. This method uses the computed style of `element` but returns undefined + * if the computed style is not expressed in pixels. That can happen in some cases where + * `element` has a size relative to its parent and this last one is not yet displayed, + * for example because of `display: none` on a parent node. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value + * @returns {number} Size in pixels or undefined if unknown. + */ +function readUsedSize(element, property) { + var value = helpers$1.getStyle(element, property); + var matches = value && value.match(/^(\d+)(\.\d+)?px$/); + return matches ? Number(matches[1]) : undefined; +} + +/** + * Initializes the canvas style and render size without modifying the canvas display size, + * since responsiveness is handled by the controller.resize() method. The config is used + * to determine the aspect ratio to apply in case no explicit height has been specified. + */ +function initCanvas(canvas, config) { + var style = canvas.style; + + // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it + // returns null or '' if no explicit value has been set to the canvas attribute. + var renderHeight = canvas.getAttribute('height'); + var renderWidth = canvas.getAttribute('width'); + + // Chart.js modifies some canvas values that we want to restore on destroy + canvas[EXPANDO_KEY] = { + initial: { + height: renderHeight, + width: renderWidth, + style: { + display: style.display, + height: style.height, + width: style.width + } + } + }; + + // Force canvas to display as block to avoid extra space caused by inline + // elements, which would interfere with the responsive resize process. + // https://github.com/chartjs/Chart.js/issues/2538 + style.display = style.display || 'block'; + + if (renderWidth === null || renderWidth === '') { + var displayWidth = readUsedSize(canvas, 'width'); + if (displayWidth !== undefined) { + canvas.width = displayWidth; + } + } + + if (renderHeight === null || renderHeight === '') { + if (canvas.style.height === '') { + // If no explicit render height and style height, let's apply the aspect ratio, + // which one can be specified by the user but also by charts as default option + // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2. + canvas.height = canvas.width / (config.options.aspectRatio || 2); + } else { + var displayHeight = readUsedSize(canvas, 'height'); + if (displayWidth !== undefined) { + canvas.height = displayHeight; + } + } + } + + return canvas; +} + +/** + * Detects support for options object argument in addEventListener. + * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support + * @private + */ +var supportsEventListenerOptions = (function() { + var supports = false; + try { + var options = Object.defineProperty({}, 'passive', { + // eslint-disable-next-line getter-return + get: function() { + supports = true; + } + }); + window.addEventListener('e', null, options); + } catch (e) { + // continue regardless of error + } + return supports; +}()); + +// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events. +// https://github.com/chartjs/Chart.js/issues/4287 +var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false; + +function addListener(node, type, listener) { + node.addEventListener(type, listener, eventListenerOptions); +} + +function removeListener(node, type, listener) { + node.removeEventListener(type, listener, eventListenerOptions); +} + +function createEvent(type, chart, x, y, nativeEvent) { + return { + type: type, + chart: chart, + native: nativeEvent || null, + x: x !== undefined ? x : null, + y: y !== undefined ? y : null, + }; +} + +function fromNativeEvent(event, chart) { + var type = EVENT_TYPES[event.type] || event.type; + var pos = helpers$1.getRelativePosition(event, chart); + return createEvent(type, chart, pos.x, pos.y, event); +} + +function throttled(fn, thisArg) { + var ticking = false; + var args = []; + + return function() { + args = Array.prototype.slice.call(arguments); + thisArg = thisArg || this; + + if (!ticking) { + ticking = true; + helpers$1.requestAnimFrame.call(window, function() { + ticking = false; + fn.apply(thisArg, args); + }); + } + }; +} + +function createDiv(cls) { + var el = document.createElement('div'); + el.className = cls || ''; + return el; +} + +// Implementation based on https://github.com/marcj/css-element-queries +function createResizer(handler) { + var maxSize = 1000000; + + // NOTE(SB) Don't use innerHTML because it could be considered unsafe. + // https://github.com/chartjs/Chart.js/issues/5902 + var resizer = createDiv(CSS_SIZE_MONITOR); + var expand = createDiv(CSS_SIZE_MONITOR + '-expand'); + var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink'); + + expand.appendChild(createDiv()); + shrink.appendChild(createDiv()); + + resizer.appendChild(expand); + resizer.appendChild(shrink); + resizer._reset = function() { + expand.scrollLeft = maxSize; + expand.scrollTop = maxSize; + shrink.scrollLeft = maxSize; + shrink.scrollTop = maxSize; + }; + + var onScroll = function() { + resizer._reset(); + handler(); + }; + + addListener(expand, 'scroll', onScroll.bind(expand, 'expand')); + addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink')); + + return resizer; +} + +// https://davidwalsh.name/detect-node-insertion +function watchForRender(node, handler) { + var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {}); + var proxy = expando.renderProxy = function(e) { + if (e.animationName === CSS_RENDER_ANIMATION) { + handler(); + } + }; + + helpers$1.each(ANIMATION_START_EVENTS, function(type) { + addListener(node, type, proxy); + }); + + // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class + // is removed then added back immediately (same animation frame?). Accessing the + // `offsetParent` property will force a reflow and re-evaluate the CSS animation. + // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics + // https://github.com/chartjs/Chart.js/issues/4737 + expando.reflow = !!node.offsetParent; + + node.classList.add(CSS_RENDER_MONITOR); +} + +function unwatchForRender(node) { + var expando = node[EXPANDO_KEY] || {}; + var proxy = expando.renderProxy; + + if (proxy) { + helpers$1.each(ANIMATION_START_EVENTS, function(type) { + removeListener(node, type, proxy); + }); + + delete expando.renderProxy; + } + + node.classList.remove(CSS_RENDER_MONITOR); +} + +function addResizeListener(node, listener, chart) { + var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {}); + + // Let's keep track of this added resizer and thus avoid DOM query when removing it. + var resizer = expando.resizer = createResizer(throttled(function() { + if (expando.resizer) { + var container = chart.options.maintainAspectRatio && node.parentNode; + var w = container ? container.clientWidth : 0; + listener(createEvent('resize', chart)); + if (container && container.clientWidth < w && chart.canvas) { + // If the container size shrank during chart resize, let's assume + // scrollbar appeared. So we resize again with the scrollbar visible - + // effectively making chart smaller and the scrollbar hidden again. + // Because we are inside `throttled`, and currently `ticking`, scroll + // events are ignored during this whole 2 resize process. + // If we assumed wrong and something else happened, we are resizing + // twice in a frame (potential performance issue) + listener(createEvent('resize', chart)); + } + } + })); + + // The resizer needs to be attached to the node parent, so we first need to be + // sure that `node` is attached to the DOM before injecting the resizer element. + watchForRender(node, function() { + if (expando.resizer) { + var container = node.parentNode; + if (container && container !== resizer.parentNode) { + container.insertBefore(resizer, container.firstChild); + } + + // The container size might have changed, let's reset the resizer state. + resizer._reset(); + } + }); +} + +function removeResizeListener(node) { + var expando = node[EXPANDO_KEY] || {}; + var resizer = expando.resizer; + + delete expando.resizer; + unwatchForRender(node); + + if (resizer && resizer.parentNode) { + resizer.parentNode.removeChild(resizer); + } +} + +function injectCSS(platform, css) { + // https://stackoverflow.com/q/3922139 + var style = platform._style || document.createElement('style'); + if (!platform._style) { + platform._style = style; + css = '/* Chart.js */\n' + css; + style.setAttribute('type', 'text/css'); + document.getElementsByTagName('head')[0].appendChild(style); + } + + style.appendChild(document.createTextNode(css)); +} + +var platform_dom$2 = { + /** + * When `true`, prevents the automatic injection of the stylesheet required to + * correctly detect when the chart is added to the DOM and then resized. This + * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`) + * to be manually imported to make this library compatible with any CSP. + * See https://github.com/chartjs/Chart.js/issues/5208 + */ + disableCSSInjection: false, + + /** + * This property holds whether this platform is enabled for the current environment. + * Currently used by platform.js to select the proper implementation. + * @private + */ + _enabled: typeof window !== 'undefined' && typeof document !== 'undefined', + + /** + * @private + */ + _ensureLoaded: function() { + if (this._loaded) { + return; + } + + this._loaded = true; + + // https://github.com/chartjs/Chart.js/issues/5208 + if (!this.disableCSSInjection) { + injectCSS(this, stylesheet); + } + }, + + acquireContext: function(item, config) { + if (typeof item === 'string') { + item = document.getElementById(item); + } else if (item.length) { + // Support for array based queries (such as jQuery) + item = item[0]; + } + + if (item && item.canvas) { + // Support for any object associated to a canvas (including a context2d) + item = item.canvas; + } + + // To prevent canvas fingerprinting, some add-ons undefine the getContext + // method, for example: https://github.com/kkapsner/CanvasBlocker + // https://github.com/chartjs/Chart.js/issues/2807 + var context = item && item.getContext && item.getContext('2d'); + + // Load platform resources on first chart creation, to make possible to change + // platform options after importing the library (e.g. `disableCSSInjection`). + this._ensureLoaded(); + + // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is + // inside an iframe or when running in a protected environment. We could guess the + // types from their toString() value but let's keep things flexible and assume it's + // a sufficient condition if the item has a context2D which has item as `canvas`. + // https://github.com/chartjs/Chart.js/issues/3887 + // https://github.com/chartjs/Chart.js/issues/4102 + // https://github.com/chartjs/Chart.js/issues/4152 + if (context && context.canvas === item) { + initCanvas(item, config); + return context; + } + + return null; + }, + + releaseContext: function(context) { + var canvas = context.canvas; + if (!canvas[EXPANDO_KEY]) { + return; + } + + var initial = canvas[EXPANDO_KEY].initial; + ['height', 'width'].forEach(function(prop) { + var value = initial[prop]; + if (helpers$1.isNullOrUndef(value)) { + canvas.removeAttribute(prop); + } else { + canvas.setAttribute(prop, value); + } + }); + + helpers$1.each(initial.style || {}, function(value, key) { + canvas.style[key] = value; + }); + + // The canvas render size might have been changed (and thus the state stack discarded), + // we can't use save() and restore() to restore the initial state. So make sure that at + // least the canvas context is reset to the default state by setting the canvas width. + // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html + // eslint-disable-next-line no-self-assign + canvas.width = canvas.width; + + delete canvas[EXPANDO_KEY]; + }, + + addEventListener: function(chart, type, listener) { + var canvas = chart.canvas; + if (type === 'resize') { + // Note: the resize event is not supported on all browsers. + addResizeListener(canvas, listener, chart); + return; + } + + var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {}); + var proxies = expando.proxies || (expando.proxies = {}); + var proxy = proxies[chart.id + '_' + type] = function(event) { + listener(fromNativeEvent(event, chart)); + }; + + addListener(canvas, type, proxy); + }, + + removeEventListener: function(chart, type, listener) { + var canvas = chart.canvas; + if (type === 'resize') { + // Note: the resize event is not supported on all browsers. + removeResizeListener(canvas); + return; + } + + var expando = listener[EXPANDO_KEY] || {}; + var proxies = expando.proxies || {}; + var proxy = proxies[chart.id + '_' + type]; + if (!proxy) { + return; + } + + removeListener(canvas, type, proxy); + } +}; + +// DEPRECATIONS + +/** + * Provided for backward compatibility, use EventTarget.addEventListener instead. + * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+ + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener + * @function Chart.helpers.addEvent + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers$1.addEvent = addListener; + +/** + * Provided for backward compatibility, use EventTarget.removeEventListener instead. + * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+ + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener + * @function Chart.helpers.removeEvent + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers$1.removeEvent = removeListener; + +// @TODO Make possible to select another platform at build time. +var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic; + +/** + * @namespace Chart.platform + * @see https://chartjs.gitbooks.io/proposals/content/Platform.html + * @since 2.4.0 + */ +var platform = helpers$1.extend({ + /** + * @since 2.7.0 + */ + initialize: function() {}, + + /** + * Called at chart construction time, returns a context2d instance implementing + * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}. + * @param {*} item - The native item from which to acquire context (platform specific) + * @param {object} options - The chart options + * @returns {CanvasRenderingContext2D} context2d instance + */ + acquireContext: function() {}, + + /** + * Called at chart destruction time, releases any resources associated to the context + * previously returned by the acquireContext() method. + * @param {CanvasRenderingContext2D} context - The context2d instance + * @returns {boolean} true if the method succeeded, else false + */ + releaseContext: function() {}, + + /** + * Registers the specified listener on the given chart. + * @param {Chart} chart - Chart from which to listen for event + * @param {string} type - The ({@link IEvent}) type to listen for + * @param {function} listener - Receives a notification (an object that implements + * the {@link IEvent} interface) when an event of the specified type occurs. + */ + addEventListener: function() {}, + + /** + * Removes the specified listener previously registered with addEventListener. + * @param {Chart} chart - Chart from which to remove the listener + * @param {string} type - The ({@link IEvent}) type to remove + * @param {function} listener - The listener function to remove from the event target. + */ + removeEventListener: function() {} + +}, implementation); + +core_defaults._set('global', { + plugins: {} +}); + +/** + * The plugin service singleton + * @namespace Chart.plugins + * @since 2.1.0 + */ +var core_plugins = { + /** + * Globally registered plugins. + * @private + */ + _plugins: [], + + /** + * This identifier is used to invalidate the descriptors cache attached to each chart + * when a global plugin is registered or unregistered. In this case, the cache ID is + * incremented and descriptors are regenerated during following API calls. + * @private + */ + _cacheId: 0, + + /** + * Registers the given plugin(s) if not already registered. + * @param {IPlugin[]|IPlugin} plugins plugin instance(s). + */ + register: function(plugins) { + var p = this._plugins; + ([]).concat(plugins).forEach(function(plugin) { + if (p.indexOf(plugin) === -1) { + p.push(plugin); + } + }); + + this._cacheId++; + }, + + /** + * Unregisters the given plugin(s) only if registered. + * @param {IPlugin[]|IPlugin} plugins plugin instance(s). + */ + unregister: function(plugins) { + var p = this._plugins; + ([]).concat(plugins).forEach(function(plugin) { + var idx = p.indexOf(plugin); + if (idx !== -1) { + p.splice(idx, 1); + } + }); + + this._cacheId++; + }, + + /** + * Remove all registered plugins. + * @since 2.1.5 + */ + clear: function() { + this._plugins = []; + this._cacheId++; + }, + + /** + * Returns the number of registered plugins? + * @returns {number} + * @since 2.1.5 + */ + count: function() { + return this._plugins.length; + }, + + /** + * Returns all registered plugin instances. + * @returns {IPlugin[]} array of plugin objects. + * @since 2.1.5 + */ + getAll: function() { + return this._plugins; + }, + + /** + * Calls enabled plugins for `chart` on the specified hook and with the given args. + * This method immediately returns as soon as a plugin explicitly returns false. The + * returned value can be used, for instance, to interrupt the current action. + * @param {Chart} chart - The chart instance for which plugins should be called. + * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate'). + * @param {Array} [args] - Extra arguments to apply to the hook call. + * @returns {boolean} false if any of the plugins return false, else returns true. + */ + notify: function(chart, hook, args) { + var descriptors = this.descriptors(chart); + var ilen = descriptors.length; + var i, descriptor, plugin, params, method; + + for (i = 0; i < ilen; ++i) { + descriptor = descriptors[i]; + plugin = descriptor.plugin; + method = plugin[hook]; + if (typeof method === 'function') { + params = [chart].concat(args || []); + params.push(descriptor.options); + if (method.apply(plugin, params) === false) { + return false; + } + } + } + + return true; + }, + + /** + * Returns descriptors of enabled plugins for the given chart. + * @returns {object[]} [{ plugin, options }] + * @private + */ + descriptors: function(chart) { + var cache = chart.$plugins || (chart.$plugins = {}); + if (cache.id === this._cacheId) { + return cache.descriptors; + } + + var plugins = []; + var descriptors = []; + var config = (chart && chart.config) || {}; + var options = (config.options && config.options.plugins) || {}; + + this._plugins.concat(config.plugins || []).forEach(function(plugin) { + var idx = plugins.indexOf(plugin); + if (idx !== -1) { + return; + } + + var id = plugin.id; + var opts = options[id]; + if (opts === false) { + return; + } + + if (opts === true) { + opts = helpers$1.clone(core_defaults.global.plugins[id]); + } + + plugins.push(plugin); + descriptors.push({ + plugin: plugin, + options: opts || {} + }); + }); + + cache.descriptors = descriptors; + cache.id = this._cacheId; + return descriptors; + }, + + /** + * Invalidates cache for the given chart: descriptors hold a reference on plugin option, + * but in some cases, this reference can be changed by the user when updating options. + * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167 + * @private + */ + _invalidate: function(chart) { + delete chart.$plugins; + } +}; + +var core_scaleService = { + // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then + // use the new chart options to grab the correct scale + constructors: {}, + // Use a registration function so that we can move to an ES6 map when we no longer need to support + // old browsers + + // Scale config defaults + defaults: {}, + registerScaleType: function(type, scaleConstructor, scaleDefaults) { + this.constructors[type] = scaleConstructor; + this.defaults[type] = helpers$1.clone(scaleDefaults); + }, + getScaleConstructor: function(type) { + return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined; + }, + getScaleDefaults: function(type) { + // Return the scale defaults merged with the global settings so that we always use the latest ones + return this.defaults.hasOwnProperty(type) ? helpers$1.merge({}, [core_defaults.scale, this.defaults[type]]) : {}; + }, + updateScaleDefaults: function(type, additions) { + var me = this; + if (me.defaults.hasOwnProperty(type)) { + me.defaults[type] = helpers$1.extend(me.defaults[type], additions); + } + }, + addScalesToLayout: function(chart) { + // Adds each scale to the chart.boxes array to be sized accordingly + helpers$1.each(chart.scales, function(scale) { + // Set ILayoutItem parameters for backwards compatibility + scale.fullWidth = scale.options.fullWidth; + scale.position = scale.options.position; + scale.weight = scale.options.weight; + core_layouts.addBox(chart, scale); + }); + } +}; + +var valueOrDefault$7 = helpers$1.valueOrDefault; + +core_defaults._set('global', { + tooltips: { + enabled: true, + custom: null, + mode: 'nearest', + position: 'average', + intersect: true, + backgroundColor: 'rgba(0,0,0,0.8)', + titleFontStyle: 'bold', + titleSpacing: 2, + titleMarginBottom: 6, + titleFontColor: '#fff', + titleAlign: 'left', + bodySpacing: 2, + bodyFontColor: '#fff', + bodyAlign: 'left', + footerFontStyle: 'bold', + footerSpacing: 2, + footerMarginTop: 6, + footerFontColor: '#fff', + footerAlign: 'left', + yPadding: 6, + xPadding: 6, + caretPadding: 2, + caretSize: 5, + cornerRadius: 6, + multiKeyBackground: '#fff', + displayColors: true, + borderColor: 'rgba(0,0,0,0)', + borderWidth: 0, + callbacks: { + // Args are: (tooltipItems, data) + beforeTitle: helpers$1.noop, + title: function(tooltipItems, data) { + var title = ''; + var labels = data.labels; + var labelCount = labels ? labels.length : 0; + + if (tooltipItems.length > 0) { + var item = tooltipItems[0]; + if (item.label) { + title = item.label; + } else if (item.xLabel) { + title = item.xLabel; + } else if (labelCount > 0 && item.index < labelCount) { + title = labels[item.index]; + } + } + + return title; + }, + afterTitle: helpers$1.noop, + + // Args are: (tooltipItems, data) + beforeBody: helpers$1.noop, + + // Args are: (tooltipItem, data) + beforeLabel: helpers$1.noop, + label: function(tooltipItem, data) { + var label = data.datasets[tooltipItem.datasetIndex].label || ''; + + if (label) { + label += ': '; + } + if (!helpers$1.isNullOrUndef(tooltipItem.value)) { + label += tooltipItem.value; + } else { + label += tooltipItem.yLabel; + } + return label; + }, + labelColor: function(tooltipItem, chart) { + var meta = chart.getDatasetMeta(tooltipItem.datasetIndex); + var activeElement = meta.data[tooltipItem.index]; + var view = activeElement._view; + return { + borderColor: view.borderColor, + backgroundColor: view.backgroundColor + }; + }, + labelTextColor: function() { + return this._options.bodyFontColor; + }, + afterLabel: helpers$1.noop, + + // Args are: (tooltipItems, data) + afterBody: helpers$1.noop, + + // Args are: (tooltipItems, data) + beforeFooter: helpers$1.noop, + footer: helpers$1.noop, + afterFooter: helpers$1.noop + } + } +}); + +var positioners = { + /** + * Average mode places the tooltip at the average position of the elements shown + * @function Chart.Tooltip.positioners.average + * @param elements {ChartElement[]} the elements being displayed in the tooltip + * @returns {object} tooltip position + */ + average: function(elements) { + if (!elements.length) { + return false; + } + + var i, len; + var x = 0; + var y = 0; + var count = 0; + + for (i = 0, len = elements.length; i < len; ++i) { + var el = elements[i]; + if (el && el.hasValue()) { + var pos = el.tooltipPosition(); + x += pos.x; + y += pos.y; + ++count; + } + } + + return { + x: x / count, + y: y / count + }; + }, + + /** + * Gets the tooltip position nearest of the item nearest to the event position + * @function Chart.Tooltip.positioners.nearest + * @param elements {Chart.Element[]} the tooltip elements + * @param eventPosition {object} the position of the event in canvas coordinates + * @returns {object} the tooltip position + */ + nearest: function(elements, eventPosition) { + var x = eventPosition.x; + var y = eventPosition.y; + var minDistance = Number.POSITIVE_INFINITY; + var i, len, nearestElement; + + for (i = 0, len = elements.length; i < len; ++i) { + var el = elements[i]; + if (el && el.hasValue()) { + var center = el.getCenterPoint(); + var d = helpers$1.distanceBetweenPoints(eventPosition, center); + + if (d < minDistance) { + minDistance = d; + nearestElement = el; + } + } + } + + if (nearestElement) { + var tp = nearestElement.tooltipPosition(); + x = tp.x; + y = tp.y; + } + + return { + x: x, + y: y + }; + } +}; + +// Helper to push or concat based on if the 2nd parameter is an array or not +function pushOrConcat(base, toPush) { + if (toPush) { + if (helpers$1.isArray(toPush)) { + // base = base.concat(toPush); + Array.prototype.push.apply(base, toPush); + } else { + base.push(toPush); + } + } + + return base; +} + +/** + * Returns array of strings split by newline + * @param {string} value - The value to split by newline. + * @returns {string[]} value if newline present - Returned from String split() method + * @function + */ +function splitNewlines(str) { + if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) { + return str.split('\n'); + } + return str; +} + + +/** + * Private helper to create a tooltip item model + * @param element - the chart element (point, arc, bar) to create the tooltip item for + * @return new tooltip item + */ +function createTooltipItem(element) { + var xScale = element._xScale; + var yScale = element._yScale || element._scale; // handle radar || polarArea charts + var index = element._index; + var datasetIndex = element._datasetIndex; + var controller = element._chart.getDatasetMeta(datasetIndex).controller; + var indexScale = controller._getIndexScale(); + var valueScale = controller._getValueScale(); + + return { + xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '', + yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '', + label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '', + value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '', + index: index, + datasetIndex: datasetIndex, + x: element._model.x, + y: element._model.y + }; +} + +/** + * Helper to get the reset model for the tooltip + * @param tooltipOpts {object} the tooltip options + */ +function getBaseModel(tooltipOpts) { + var globalDefaults = core_defaults.global; + + return { + // Positioning + xPadding: tooltipOpts.xPadding, + yPadding: tooltipOpts.yPadding, + xAlign: tooltipOpts.xAlign, + yAlign: tooltipOpts.yAlign, + + // Body + bodyFontColor: tooltipOpts.bodyFontColor, + _bodyFontFamily: valueOrDefault$7(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily), + _bodyFontStyle: valueOrDefault$7(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle), + _bodyAlign: tooltipOpts.bodyAlign, + bodyFontSize: valueOrDefault$7(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize), + bodySpacing: tooltipOpts.bodySpacing, + + // Title + titleFontColor: tooltipOpts.titleFontColor, + _titleFontFamily: valueOrDefault$7(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily), + _titleFontStyle: valueOrDefault$7(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle), + titleFontSize: valueOrDefault$7(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize), + _titleAlign: tooltipOpts.titleAlign, + titleSpacing: tooltipOpts.titleSpacing, + titleMarginBottom: tooltipOpts.titleMarginBottom, + + // Footer + footerFontColor: tooltipOpts.footerFontColor, + _footerFontFamily: valueOrDefault$7(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily), + _footerFontStyle: valueOrDefault$7(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle), + footerFontSize: valueOrDefault$7(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize), + _footerAlign: tooltipOpts.footerAlign, + footerSpacing: tooltipOpts.footerSpacing, + footerMarginTop: tooltipOpts.footerMarginTop, + + // Appearance + caretSize: tooltipOpts.caretSize, + cornerRadius: tooltipOpts.cornerRadius, + backgroundColor: tooltipOpts.backgroundColor, + opacity: 0, + legendColorBackground: tooltipOpts.multiKeyBackground, + displayColors: tooltipOpts.displayColors, + borderColor: tooltipOpts.borderColor, + borderWidth: tooltipOpts.borderWidth + }; +} + +/** + * Get the size of the tooltip + */ +function getTooltipSize(tooltip, model) { + var ctx = tooltip._chart.ctx; + + var height = model.yPadding * 2; // Tooltip Padding + var width = 0; + + // Count of all lines in the body + var body = model.body; + var combinedBodyLength = body.reduce(function(count, bodyItem) { + return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length; + }, 0); + combinedBodyLength += model.beforeBody.length + model.afterBody.length; + + var titleLineCount = model.title.length; + var footerLineCount = model.footer.length; + var titleFontSize = model.titleFontSize; + var bodyFontSize = model.bodyFontSize; + var footerFontSize = model.footerFontSize; + + height += titleLineCount * titleFontSize; // Title Lines + height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing + height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin + height += combinedBodyLength * bodyFontSize; // Body Lines + height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing + height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin + height += footerLineCount * (footerFontSize); // Footer Lines + height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing + + // Title width + var widthPadding = 0; + var maxLineWidth = function(line) { + width = Math.max(width, ctx.measureText(line).width + widthPadding); + }; + + ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily); + helpers$1.each(model.title, maxLineWidth); + + // Body width + ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily); + helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth); + + // Body lines may include some extra width due to the color box + widthPadding = model.displayColors ? (bodyFontSize + 2) : 0; + helpers$1.each(body, function(bodyItem) { + helpers$1.each(bodyItem.before, maxLineWidth); + helpers$1.each(bodyItem.lines, maxLineWidth); + helpers$1.each(bodyItem.after, maxLineWidth); + }); + + // Reset back to 0 + widthPadding = 0; + + // Footer width + ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily); + helpers$1.each(model.footer, maxLineWidth); + + // Add padding + width += 2 * model.xPadding; + + return { + width: width, + height: height + }; +} + +/** + * Helper to get the alignment of a tooltip given the size + */ +function determineAlignment(tooltip, size) { + var model = tooltip._model; + var chart = tooltip._chart; + var chartArea = tooltip._chart.chartArea; + var xAlign = 'center'; + var yAlign = 'center'; + + if (model.y < size.height) { + yAlign = 'top'; + } else if (model.y > (chart.height - size.height)) { + yAlign = 'bottom'; + } + + var lf, rf; // functions to determine left, right alignment + var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart + var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges + var midX = (chartArea.left + chartArea.right) / 2; + var midY = (chartArea.top + chartArea.bottom) / 2; + + if (yAlign === 'center') { + lf = function(x) { + return x <= midX; + }; + rf = function(x) { + return x > midX; + }; + } else { + lf = function(x) { + return x <= (size.width / 2); + }; + rf = function(x) { + return x >= (chart.width - (size.width / 2)); + }; + } + + olf = function(x) { + return x + size.width + model.caretSize + model.caretPadding > chart.width; + }; + orf = function(x) { + return x - size.width - model.caretSize - model.caretPadding < 0; + }; + yf = function(y) { + return y <= midY ? 'top' : 'bottom'; + }; + + if (lf(model.x)) { + xAlign = 'left'; + + // Is tooltip too wide and goes over the right side of the chart.? + if (olf(model.x)) { + xAlign = 'center'; + yAlign = yf(model.y); + } + } else if (rf(model.x)) { + xAlign = 'right'; + + // Is tooltip too wide and goes outside left edge of canvas? + if (orf(model.x)) { + xAlign = 'center'; + yAlign = yf(model.y); + } + } + + var opts = tooltip._options; + return { + xAlign: opts.xAlign ? opts.xAlign : xAlign, + yAlign: opts.yAlign ? opts.yAlign : yAlign + }; +} + +/** + * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment + */ +function getBackgroundPoint(vm, size, alignment, chart) { + // Background Position + var x = vm.x; + var y = vm.y; + + var caretSize = vm.caretSize; + var caretPadding = vm.caretPadding; + var cornerRadius = vm.cornerRadius; + var xAlign = alignment.xAlign; + var yAlign = alignment.yAlign; + var paddingAndSize = caretSize + caretPadding; + var radiusAndPadding = cornerRadius + caretPadding; + + if (xAlign === 'right') { + x -= size.width; + } else if (xAlign === 'center') { + x -= (size.width / 2); + if (x + size.width > chart.width) { + x = chart.width - size.width; + } + if (x < 0) { + x = 0; + } + } + + if (yAlign === 'top') { + y += paddingAndSize; + } else if (yAlign === 'bottom') { + y -= size.height + paddingAndSize; + } else { + y -= (size.height / 2); + } + + if (yAlign === 'center') { + if (xAlign === 'left') { + x += paddingAndSize; + } else if (xAlign === 'right') { + x -= paddingAndSize; + } + } else if (xAlign === 'left') { + x -= radiusAndPadding; + } else if (xAlign === 'right') { + x += radiusAndPadding; + } + + return { + x: x, + y: y + }; +} + +function getAlignedX(vm, align) { + return align === 'center' + ? vm.x + vm.width / 2 + : align === 'right' + ? vm.x + vm.width - vm.xPadding + : vm.x + vm.xPadding; +} + +/** + * Helper to build before and after body lines + */ +function getBeforeAfterBodyLines(callback) { + return pushOrConcat([], splitNewlines(callback)); +} + +var exports$3 = core_element.extend({ + initialize: function() { + this._model = getBaseModel(this._options); + this._lastActive = []; + }, + + // Get the title + // Args are: (tooltipItem, data) + getTitle: function() { + var me = this; + var opts = me._options; + var callbacks = opts.callbacks; + + var beforeTitle = callbacks.beforeTitle.apply(me, arguments); + var title = callbacks.title.apply(me, arguments); + var afterTitle = callbacks.afterTitle.apply(me, arguments); + + var lines = []; + lines = pushOrConcat(lines, splitNewlines(beforeTitle)); + lines = pushOrConcat(lines, splitNewlines(title)); + lines = pushOrConcat(lines, splitNewlines(afterTitle)); + + return lines; + }, + + // Args are: (tooltipItem, data) + getBeforeBody: function() { + return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments)); + }, + + // Args are: (tooltipItem, data) + getBody: function(tooltipItems, data) { + var me = this; + var callbacks = me._options.callbacks; + var bodyItems = []; + + helpers$1.each(tooltipItems, function(tooltipItem) { + var bodyItem = { + before: [], + lines: [], + after: [] + }; + pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data))); + pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data)); + pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data))); + + bodyItems.push(bodyItem); + }); + + return bodyItems; + }, + + // Args are: (tooltipItem, data) + getAfterBody: function() { + return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments)); + }, + + // Get the footer and beforeFooter and afterFooter lines + // Args are: (tooltipItem, data) + getFooter: function() { + var me = this; + var callbacks = me._options.callbacks; + + var beforeFooter = callbacks.beforeFooter.apply(me, arguments); + var footer = callbacks.footer.apply(me, arguments); + var afterFooter = callbacks.afterFooter.apply(me, arguments); + + var lines = []; + lines = pushOrConcat(lines, splitNewlines(beforeFooter)); + lines = pushOrConcat(lines, splitNewlines(footer)); + lines = pushOrConcat(lines, splitNewlines(afterFooter)); + + return lines; + }, + + update: function(changed) { + var me = this; + var opts = me._options; + + // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition + // that does _view = _model if ease === 1. This causes the 2nd tooltip update to set properties in both the view and model at the same time + // which breaks any animations. + var existingModel = me._model; + var model = me._model = getBaseModel(opts); + var active = me._active; + + var data = me._data; + + // In the case where active.length === 0 we need to keep these at existing values for good animations + var alignment = { + xAlign: existingModel.xAlign, + yAlign: existingModel.yAlign + }; + var backgroundPoint = { + x: existingModel.x, + y: existingModel.y + }; + var tooltipSize = { + width: existingModel.width, + height: existingModel.height + }; + var tooltipPosition = { + x: existingModel.caretX, + y: existingModel.caretY + }; + + var i, len; + + if (active.length) { + model.opacity = 1; + + var labelColors = []; + var labelTextColors = []; + tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition); + + var tooltipItems = []; + for (i = 0, len = active.length; i < len; ++i) { + tooltipItems.push(createTooltipItem(active[i])); + } + + // If the user provided a filter function, use it to modify the tooltip items + if (opts.filter) { + tooltipItems = tooltipItems.filter(function(a) { + return opts.filter(a, data); + }); + } + + // If the user provided a sorting function, use it to modify the tooltip items + if (opts.itemSort) { + tooltipItems = tooltipItems.sort(function(a, b) { + return opts.itemSort(a, b, data); + }); + } + + // Determine colors for boxes + helpers$1.each(tooltipItems, function(tooltipItem) { + labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart)); + labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart)); + }); + + + // Build the Text Lines + model.title = me.getTitle(tooltipItems, data); + model.beforeBody = me.getBeforeBody(tooltipItems, data); + model.body = me.getBody(tooltipItems, data); + model.afterBody = me.getAfterBody(tooltipItems, data); + model.footer = me.getFooter(tooltipItems, data); + + // Initial positioning and colors + model.x = tooltipPosition.x; + model.y = tooltipPosition.y; + model.caretPadding = opts.caretPadding; + model.labelColors = labelColors; + model.labelTextColors = labelTextColors; + + // data points + model.dataPoints = tooltipItems; + + // We need to determine alignment of the tooltip + tooltipSize = getTooltipSize(this, model); + alignment = determineAlignment(this, tooltipSize); + // Final Size and Position + backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart); + } else { + model.opacity = 0; + } + + model.xAlign = alignment.xAlign; + model.yAlign = alignment.yAlign; + model.x = backgroundPoint.x; + model.y = backgroundPoint.y; + model.width = tooltipSize.width; + model.height = tooltipSize.height; + + // Point where the caret on the tooltip points to + model.caretX = tooltipPosition.x; + model.caretY = tooltipPosition.y; + + me._model = model; + + if (changed && opts.custom) { + opts.custom.call(me, model); + } + + return me; + }, + + drawCaret: function(tooltipPoint, size) { + var ctx = this._chart.ctx; + var vm = this._view; + var caretPosition = this.getCaretPosition(tooltipPoint, size, vm); + + ctx.lineTo(caretPosition.x1, caretPosition.y1); + ctx.lineTo(caretPosition.x2, caretPosition.y2); + ctx.lineTo(caretPosition.x3, caretPosition.y3); + }, + getCaretPosition: function(tooltipPoint, size, vm) { + var x1, x2, x3, y1, y2, y3; + var caretSize = vm.caretSize; + var cornerRadius = vm.cornerRadius; + var xAlign = vm.xAlign; + var yAlign = vm.yAlign; + var ptX = tooltipPoint.x; + var ptY = tooltipPoint.y; + var width = size.width; + var height = size.height; + + if (yAlign === 'center') { + y2 = ptY + (height / 2); + + if (xAlign === 'left') { + x1 = ptX; + x2 = x1 - caretSize; + x3 = x1; + + y1 = y2 + caretSize; + y3 = y2 - caretSize; + } else { + x1 = ptX + width; + x2 = x1 + caretSize; + x3 = x1; + + y1 = y2 - caretSize; + y3 = y2 + caretSize; + } + } else { + if (xAlign === 'left') { + x2 = ptX + cornerRadius + (caretSize); + x1 = x2 - caretSize; + x3 = x2 + caretSize; + } else if (xAlign === 'right') { + x2 = ptX + width - cornerRadius - caretSize; + x1 = x2 - caretSize; + x3 = x2 + caretSize; + } else { + x2 = vm.caretX; + x1 = x2 - caretSize; + x3 = x2 + caretSize; + } + if (yAlign === 'top') { + y1 = ptY; + y2 = y1 - caretSize; + y3 = y1; + } else { + y1 = ptY + height; + y2 = y1 + caretSize; + y3 = y1; + // invert drawing order + var tmp = x3; + x3 = x1; + x1 = tmp; + } + } + return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3}; + }, + + drawTitle: function(pt, vm, ctx) { + var title = vm.title; + + if (title.length) { + pt.x = getAlignedX(vm, vm._titleAlign); + + ctx.textAlign = vm._titleAlign; + ctx.textBaseline = 'top'; + + var titleFontSize = vm.titleFontSize; + var titleSpacing = vm.titleSpacing; + + ctx.fillStyle = vm.titleFontColor; + ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily); + + var i, len; + for (i = 0, len = title.length; i < len; ++i) { + ctx.fillText(title[i], pt.x, pt.y); + pt.y += titleFontSize + titleSpacing; // Line Height and spacing + + if (i + 1 === title.length) { + pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing + } + } + } + }, + + drawBody: function(pt, vm, ctx) { + var bodyFontSize = vm.bodyFontSize; + var bodySpacing = vm.bodySpacing; + var bodyAlign = vm._bodyAlign; + var body = vm.body; + var drawColorBoxes = vm.displayColors; + var labelColors = vm.labelColors; + var xLinePadding = 0; + var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0; + var textColor; + + ctx.textAlign = bodyAlign; + ctx.textBaseline = 'top'; + ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily); + + pt.x = getAlignedX(vm, bodyAlign); + + // Before Body + var fillLineOfText = function(line) { + ctx.fillText(line, pt.x + xLinePadding, pt.y); + pt.y += bodyFontSize + bodySpacing; + }; + + // Before body lines + ctx.fillStyle = vm.bodyFontColor; + helpers$1.each(vm.beforeBody, fillLineOfText); + + xLinePadding = drawColorBoxes && bodyAlign !== 'right' + ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2) + : 0; + + // Draw body lines now + helpers$1.each(body, function(bodyItem, i) { + textColor = vm.labelTextColors[i]; + ctx.fillStyle = textColor; + helpers$1.each(bodyItem.before, fillLineOfText); + + helpers$1.each(bodyItem.lines, function(line) { + // Draw Legend-like boxes if needed + if (drawColorBoxes) { + // Fill a white rect so that colours merge nicely if the opacity is < 1 + ctx.fillStyle = vm.legendColorBackground; + ctx.fillRect(colorX, pt.y, bodyFontSize, bodyFontSize); + + // Border + ctx.lineWidth = 1; + ctx.strokeStyle = labelColors[i].borderColor; + ctx.strokeRect(colorX, pt.y, bodyFontSize, bodyFontSize); + + // Inner square + ctx.fillStyle = labelColors[i].backgroundColor; + ctx.fillRect(colorX + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2); + ctx.fillStyle = textColor; + } + + fillLineOfText(line); + }); + + helpers$1.each(bodyItem.after, fillLineOfText); + }); + + // Reset back to 0 for after body + xLinePadding = 0; + + // After body lines + helpers$1.each(vm.afterBody, fillLineOfText); + pt.y -= bodySpacing; // Remove last body spacing + }, + + drawFooter: function(pt, vm, ctx) { + var footer = vm.footer; + + if (footer.length) { + pt.x = getAlignedX(vm, vm._footerAlign); + pt.y += vm.footerMarginTop; + + ctx.textAlign = vm._footerAlign; + ctx.textBaseline = 'top'; + + ctx.fillStyle = vm.footerFontColor; + ctx.font = helpers$1.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily); + + helpers$1.each(footer, function(line) { + ctx.fillText(line, pt.x, pt.y); + pt.y += vm.footerFontSize + vm.footerSpacing; + }); + } + }, + + drawBackground: function(pt, vm, ctx, tooltipSize) { + ctx.fillStyle = vm.backgroundColor; + ctx.strokeStyle = vm.borderColor; + ctx.lineWidth = vm.borderWidth; + var xAlign = vm.xAlign; + var yAlign = vm.yAlign; + var x = pt.x; + var y = pt.y; + var width = tooltipSize.width; + var height = tooltipSize.height; + var radius = vm.cornerRadius; + + ctx.beginPath(); + ctx.moveTo(x + radius, y); + if (yAlign === 'top') { + this.drawCaret(pt, tooltipSize); + } + ctx.lineTo(x + width - radius, y); + ctx.quadraticCurveTo(x + width, y, x + width, y + radius); + if (yAlign === 'center' && xAlign === 'right') { + this.drawCaret(pt, tooltipSize); + } + ctx.lineTo(x + width, y + height - radius); + ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); + if (yAlign === 'bottom') { + this.drawCaret(pt, tooltipSize); + } + ctx.lineTo(x + radius, y + height); + ctx.quadraticCurveTo(x, y + height, x, y + height - radius); + if (yAlign === 'center' && xAlign === 'left') { + this.drawCaret(pt, tooltipSize); + } + ctx.lineTo(x, y + radius); + ctx.quadraticCurveTo(x, y, x + radius, y); + ctx.closePath(); + + ctx.fill(); + + if (vm.borderWidth > 0) { + ctx.stroke(); + } + }, + + draw: function() { + var ctx = this._chart.ctx; + var vm = this._view; + + if (vm.opacity === 0) { + return; + } + + var tooltipSize = { + width: vm.width, + height: vm.height + }; + var pt = { + x: vm.x, + y: vm.y + }; + + // IE11/Edge does not like very small opacities, so snap to 0 + var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity; + + // Truthy/falsey value for empty tooltip + var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length; + + if (this._options.enabled && hasTooltipContent) { + ctx.save(); + ctx.globalAlpha = opacity; + + // Draw Background + this.drawBackground(pt, vm, ctx, tooltipSize); + + // Draw Title, Body, and Footer + pt.y += vm.yPadding; + + // Titles + this.drawTitle(pt, vm, ctx); + + // Body + this.drawBody(pt, vm, ctx); + + // Footer + this.drawFooter(pt, vm, ctx); + + ctx.restore(); + } + }, + + /** + * Handle an event + * @private + * @param {IEvent} event - The event to handle + * @returns {boolean} true if the tooltip changed + */ + handleEvent: function(e) { + var me = this; + var options = me._options; + var changed = false; + + me._lastActive = me._lastActive || []; + + // Find Active Elements for tooltips + if (e.type === 'mouseout') { + me._active = []; + } else { + me._active = me._chart.getElementsAtEventForMode(e, options.mode, options); + } + + // Remember Last Actives + changed = !helpers$1.arrayEquals(me._active, me._lastActive); + + // Only handle target event on tooltip change + if (changed) { + me._lastActive = me._active; + + if (options.enabled || options.custom) { + me._eventPosition = { + x: e.x, + y: e.y + }; + + me.update(true); + me.pivot(); + } + } + + return changed; + } +}); + +/** + * @namespace Chart.Tooltip.positioners + */ +var positioners_1 = positioners; + +var core_tooltip = exports$3; +core_tooltip.positioners = positioners_1; + +var valueOrDefault$8 = helpers$1.valueOrDefault; + +core_defaults._set('global', { + elements: {}, + events: [ + 'mousemove', + 'mouseout', + 'click', + 'touchstart', + 'touchmove' + ], + hover: { + onHover: null, + mode: 'nearest', + intersect: true, + animationDuration: 400 + }, + onClick: null, + maintainAspectRatio: true, + responsive: true, + responsiveAnimationDuration: 0 +}); + +/** + * Recursively merge the given config objects representing the `scales` option + * by incorporating scale defaults in `xAxes` and `yAxes` array items, then + * returns a deep copy of the result, thus doesn't alter inputs. + */ +function mergeScaleConfig(/* config objects ... */) { + return helpers$1.merge({}, [].slice.call(arguments), { + merger: function(key, target, source, options) { + if (key === 'xAxes' || key === 'yAxes') { + var slen = source[key].length; + var i, type, scale; + + if (!target[key]) { + target[key] = []; + } + + for (i = 0; i < slen; ++i) { + scale = source[key][i]; + type = valueOrDefault$8(scale.type, key === 'xAxes' ? 'category' : 'linear'); + + if (i >= target[key].length) { + target[key].push({}); + } + + if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) { + // new/untyped scale or type changed: let's apply the new defaults + // then merge source scale to correctly overwrite the defaults. + helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]); + } else { + // scales type are the same + helpers$1.merge(target[key][i], scale); + } + } + } else { + helpers$1._merger(key, target, source, options); + } + } + }); +} + +/** + * Recursively merge the given config objects as the root options by handling + * default scale options for the `scales` and `scale` properties, then returns + * a deep copy of the result, thus doesn't alter inputs. + */ +function mergeConfig(/* config objects ... */) { + return helpers$1.merge({}, [].slice.call(arguments), { + merger: function(key, target, source, options) { + var tval = target[key] || {}; + var sval = source[key]; + + if (key === 'scales') { + // scale config merging is complex. Add our own function here for that + target[key] = mergeScaleConfig(tval, sval); + } else if (key === 'scale') { + // used in polar area & radar charts since there is only one scale + target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]); + } else { + helpers$1._merger(key, target, source, options); + } + } + }); +} + +function initConfig(config) { + config = config || {}; + + // Do NOT use mergeConfig for the data object because this method merges arrays + // and so would change references to labels and datasets, preventing data updates. + var data = config.data = config.data || {}; + data.datasets = data.datasets || []; + data.labels = data.labels || []; + + config.options = mergeConfig( + core_defaults.global, + core_defaults[config.type], + config.options || {}); + + return config; +} + +function updateConfig(chart) { + var newOptions = chart.options; + + helpers$1.each(chart.scales, function(scale) { + core_layouts.removeBox(chart, scale); + }); + + newOptions = mergeConfig( + core_defaults.global, + core_defaults[chart.config.type], + newOptions); + + chart.options = chart.config.options = newOptions; + chart.ensureScalesHaveIDs(); + chart.buildOrUpdateScales(); + + // Tooltip + chart.tooltip._options = newOptions.tooltips; + chart.tooltip.initialize(); +} + +function positionIsHorizontal(position) { + return position === 'top' || position === 'bottom'; +} + +var Chart = function(item, config) { + this.construct(item, config); + return this; +}; + +helpers$1.extend(Chart.prototype, /** @lends Chart */ { + /** + * @private + */ + construct: function(item, config) { + var me = this; + + config = initConfig(config); + + var context = platform.acquireContext(item, config); + var canvas = context && context.canvas; + var height = canvas && canvas.height; + var width = canvas && canvas.width; + + me.id = helpers$1.uid(); + me.ctx = context; + me.canvas = canvas; + me.config = config; + me.width = width; + me.height = height; + me.aspectRatio = height ? width / height : null; + me.options = config.options; + me._bufferedRender = false; + + /** + * Provided for backward compatibility, Chart and Chart.Controller have been merged, + * the "instance" still need to be defined since it might be called from plugins. + * @prop Chart#chart + * @deprecated since version 2.6.0 + * @todo remove at version 3 + * @private + */ + me.chart = me; + me.controller = me; // chart.chart.controller #inception + + // Add the chart instance to the global namespace + Chart.instances[me.id] = me; + + // Define alias to the config data: `chart.data === chart.config.data` + Object.defineProperty(me, 'data', { + get: function() { + return me.config.data; + }, + set: function(value) { + me.config.data = value; + } + }); + + if (!context || !canvas) { + // The given item is not a compatible context2d element, let's return before finalizing + // the chart initialization but after setting basic chart / controller properties that + // can help to figure out that the chart is not valid (e.g chart.canvas !== null); + // https://github.com/chartjs/Chart.js/issues/2807 + console.error("Failed to create chart: can't acquire context from the given item"); + return; + } + + me.initialize(); + me.update(); + }, + + /** + * @private + */ + initialize: function() { + var me = this; + + // Before init plugin notification + core_plugins.notify(me, 'beforeInit'); + + helpers$1.retinaScale(me, me.options.devicePixelRatio); + + me.bindEvents(); + + if (me.options.responsive) { + // Initial resize before chart draws (must be silent to preserve initial animations). + me.resize(true); + } + + // Make sure scales have IDs and are built before we build any controllers. + me.ensureScalesHaveIDs(); + me.buildOrUpdateScales(); + me.initToolTip(); + + // After init plugin notification + core_plugins.notify(me, 'afterInit'); + + return me; + }, + + clear: function() { + helpers$1.canvas.clear(this); + return this; + }, + + stop: function() { + // Stops any current animation loop occurring + core_animations.cancelAnimation(this); + return this; + }, + + resize: function(silent) { + var me = this; + var options = me.options; + var canvas = me.canvas; + var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null; + + // the canvas render width and height will be casted to integers so make sure that + // the canvas display style uses the same integer values to avoid blurring effect. + + // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed + var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas))); + var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas))); + + if (me.width === newWidth && me.height === newHeight) { + return; + } + + canvas.width = me.width = newWidth; + canvas.height = me.height = newHeight; + canvas.style.width = newWidth + 'px'; + canvas.style.height = newHeight + 'px'; + + helpers$1.retinaScale(me, options.devicePixelRatio); + + if (!silent) { + // Notify any plugins about the resize + var newSize = {width: newWidth, height: newHeight}; + core_plugins.notify(me, 'resize', [newSize]); + + // Notify of resize + if (options.onResize) { + options.onResize(me, newSize); + } + + me.stop(); + me.update({ + duration: options.responsiveAnimationDuration + }); + } + }, + + ensureScalesHaveIDs: function() { + var options = this.options; + var scalesOptions = options.scales || {}; + var scaleOptions = options.scale; + + helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) { + xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index); + }); + + helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) { + yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index); + }); + + if (scaleOptions) { + scaleOptions.id = scaleOptions.id || 'scale'; + } + }, + + /** + * Builds a map of scale ID to scale object for future lookup. + */ + buildOrUpdateScales: function() { + var me = this; + var options = me.options; + var scales = me.scales || {}; + var items = []; + var updated = Object.keys(scales).reduce(function(obj, id) { + obj[id] = false; + return obj; + }, {}); + + if (options.scales) { + items = items.concat( + (options.scales.xAxes || []).map(function(xAxisOptions) { + return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'}; + }), + (options.scales.yAxes || []).map(function(yAxisOptions) { + return {options: yAxisOptions, dtype: 'linear', dposition: 'left'}; + }) + ); + } + + if (options.scale) { + items.push({ + options: options.scale, + dtype: 'radialLinear', + isDefault: true, + dposition: 'chartArea' + }); + } + + helpers$1.each(items, function(item) { + var scaleOptions = item.options; + var id = scaleOptions.id; + var scaleType = valueOrDefault$8(scaleOptions.type, item.dtype); + + if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) { + scaleOptions.position = item.dposition; + } + + updated[id] = true; + var scale = null; + if (id in scales && scales[id].type === scaleType) { + scale = scales[id]; + scale.options = scaleOptions; + scale.ctx = me.ctx; + scale.chart = me; + } else { + var scaleClass = core_scaleService.getScaleConstructor(scaleType); + if (!scaleClass) { + return; + } + scale = new scaleClass({ + id: id, + type: scaleType, + options: scaleOptions, + ctx: me.ctx, + chart: me + }); + scales[scale.id] = scale; + } + + scale.mergeTicksOptions(); + + // TODO(SB): I think we should be able to remove this custom case (options.scale) + // and consider it as a regular scale part of the "scales"" map only! This would + // make the logic easier and remove some useless? custom code. + if (item.isDefault) { + me.scale = scale; + } + }); + // clear up discarded scales + helpers$1.each(updated, function(hasUpdated, id) { + if (!hasUpdated) { + delete scales[id]; + } + }); + + me.scales = scales; + + core_scaleService.addScalesToLayout(this); + }, + + buildOrUpdateControllers: function() { + var me = this; + var newControllers = []; + + helpers$1.each(me.data.datasets, function(dataset, datasetIndex) { + var meta = me.getDatasetMeta(datasetIndex); + var type = dataset.type || me.config.type; + + if (meta.type && meta.type !== type) { + me.destroyDatasetMeta(datasetIndex); + meta = me.getDatasetMeta(datasetIndex); + } + meta.type = type; + + if (meta.controller) { + meta.controller.updateIndex(datasetIndex); + meta.controller.linkScales(); + } else { + var ControllerClass = controllers[meta.type]; + if (ControllerClass === undefined) { + throw new Error('"' + meta.type + '" is not a chart type.'); + } + + meta.controller = new ControllerClass(me, datasetIndex); + newControllers.push(meta.controller); + } + }, me); + + return newControllers; + }, + + /** + * Reset the elements of all datasets + * @private + */ + resetElements: function() { + var me = this; + helpers$1.each(me.data.datasets, function(dataset, datasetIndex) { + me.getDatasetMeta(datasetIndex).controller.reset(); + }, me); + }, + + /** + * Resets the chart back to it's state before the initial animation + */ + reset: function() { + this.resetElements(); + this.tooltip.initialize(); + }, + + update: function(config) { + var me = this; + + if (!config || typeof config !== 'object') { + // backwards compatibility + config = { + duration: config, + lazy: arguments[1] + }; + } + + updateConfig(me); + + // plugins options references might have change, let's invalidate the cache + // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167 + core_plugins._invalidate(me); + + if (core_plugins.notify(me, 'beforeUpdate') === false) { + return; + } + + // In case the entire data object changed + me.tooltip._data = me.data; + + // Make sure dataset controllers are updated and new controllers are reset + var newControllers = me.buildOrUpdateControllers(); + + // Make sure all dataset controllers have correct meta data counts + helpers$1.each(me.data.datasets, function(dataset, datasetIndex) { + me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements(); + }, me); + + me.updateLayout(); + + // Can only reset the new controllers after the scales have been updated + if (me.options.animation && me.options.animation.duration) { + helpers$1.each(newControllers, function(controller) { + controller.reset(); + }); + } + + me.updateDatasets(); + + // Need to reset tooltip in case it is displayed with elements that are removed + // after update. + me.tooltip.initialize(); + + // Last active contains items that were previously in the tooltip. + // When we reset the tooltip, we need to clear it + me.lastActive = []; + + // Do this before render so that any plugins that need final scale updates can use it + core_plugins.notify(me, 'afterUpdate'); + + if (me._bufferedRender) { + me._bufferedRequest = { + duration: config.duration, + easing: config.easing, + lazy: config.lazy + }; + } else { + me.render(config); + } + }, + + /** + * Updates the chart layout unless a plugin returns `false` to the `beforeLayout` + * hook, in which case, plugins will not be called on `afterLayout`. + * @private + */ + updateLayout: function() { + var me = this; + + if (core_plugins.notify(me, 'beforeLayout') === false) { + return; + } + + core_layouts.update(this, this.width, this.height); + + /** + * Provided for backward compatibility, use `afterLayout` instead. + * @method IPlugin#afterScaleUpdate + * @deprecated since version 2.5.0 + * @todo remove at version 3 + * @private + */ + core_plugins.notify(me, 'afterScaleUpdate'); + core_plugins.notify(me, 'afterLayout'); + }, + + /** + * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate` + * hook, in which case, plugins will not be called on `afterDatasetsUpdate`. + * @private + */ + updateDatasets: function() { + var me = this; + + if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) { + return; + } + + for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) { + me.updateDataset(i); + } + + core_plugins.notify(me, 'afterDatasetsUpdate'); + }, + + /** + * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate` + * hook, in which case, plugins will not be called on `afterDatasetUpdate`. + * @private + */ + updateDataset: function(index) { + var me = this; + var meta = me.getDatasetMeta(index); + var args = { + meta: meta, + index: index + }; + + if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) { + return; + } + + meta.controller.update(); + + core_plugins.notify(me, 'afterDatasetUpdate', [args]); + }, + + render: function(config) { + var me = this; + + if (!config || typeof config !== 'object') { + // backwards compatibility + config = { + duration: config, + lazy: arguments[1] + }; + } + + var animationOptions = me.options.animation; + var duration = valueOrDefault$8(config.duration, animationOptions && animationOptions.duration); + var lazy = config.lazy; + + if (core_plugins.notify(me, 'beforeRender') === false) { + return; + } + + var onComplete = function(animation) { + core_plugins.notify(me, 'afterRender'); + helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me); + }; + + if (animationOptions && duration) { + var animation = new core_animation({ + numSteps: duration / 16.66, // 60 fps + easing: config.easing || animationOptions.easing, + + render: function(chart, animationObject) { + var easingFunction = helpers$1.easing.effects[animationObject.easing]; + var currentStep = animationObject.currentStep; + var stepDecimal = currentStep / animationObject.numSteps; + + chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep); + }, + + onAnimationProgress: animationOptions.onProgress, + onAnimationComplete: onComplete + }); + + core_animations.addAnimation(me, animation, duration, lazy); + } else { + me.draw(); + + // See https://github.com/chartjs/Chart.js/issues/3781 + onComplete(new core_animation({numSteps: 0, chart: me})); + } + + return me; + }, + + draw: function(easingValue) { + var me = this; + + me.clear(); + + if (helpers$1.isNullOrUndef(easingValue)) { + easingValue = 1; + } + + me.transition(easingValue); + + if (me.width <= 0 || me.height <= 0) { + return; + } + + if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) { + return; + } + + // Draw all the scales + helpers$1.each(me.boxes, function(box) { + box.draw(me.chartArea); + }, me); + + me.drawDatasets(easingValue); + me._drawTooltip(easingValue); + + core_plugins.notify(me, 'afterDraw', [easingValue]); + }, + + /** + * @private + */ + transition: function(easingValue) { + var me = this; + + for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) { + if (me.isDatasetVisible(i)) { + me.getDatasetMeta(i).controller.transition(easingValue); + } + } + + me.tooltip.transition(easingValue); + }, + + /** + * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw` + * hook, in which case, plugins will not be called on `afterDatasetsDraw`. + * @private + */ + drawDatasets: function(easingValue) { + var me = this; + + if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) { + return; + } + + // Draw datasets reversed to support proper line stacking + for (var i = (me.data.datasets || []).length - 1; i >= 0; --i) { + if (me.isDatasetVisible(i)) { + me.drawDataset(i, easingValue); + } + } + + core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]); + }, + + /** + * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw` + * hook, in which case, plugins will not be called on `afterDatasetDraw`. + * @private + */ + drawDataset: function(index, easingValue) { + var me = this; + var meta = me.getDatasetMeta(index); + var args = { + meta: meta, + index: index, + easingValue: easingValue + }; + + if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) { + return; + } + + meta.controller.draw(easingValue); + + core_plugins.notify(me, 'afterDatasetDraw', [args]); + }, + + /** + * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw` + * hook, in which case, plugins will not be called on `afterTooltipDraw`. + * @private + */ + _drawTooltip: function(easingValue) { + var me = this; + var tooltip = me.tooltip; + var args = { + tooltip: tooltip, + easingValue: easingValue + }; + + if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) { + return; + } + + tooltip.draw(); + + core_plugins.notify(me, 'afterTooltipDraw', [args]); + }, + + /** + * Get the single element that was clicked on + * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw + */ + getElementAtEvent: function(e) { + return core_interaction.modes.single(this, e); + }, + + getElementsAtEvent: function(e) { + return core_interaction.modes.label(this, e, {intersect: true}); + }, + + getElementsAtXAxis: function(e) { + return core_interaction.modes['x-axis'](this, e, {intersect: true}); + }, + + getElementsAtEventForMode: function(e, mode, options) { + var method = core_interaction.modes[mode]; + if (typeof method === 'function') { + return method(this, e, options); + } + + return []; + }, + + getDatasetAtEvent: function(e) { + return core_interaction.modes.dataset(this, e, {intersect: true}); + }, + + getDatasetMeta: function(datasetIndex) { + var me = this; + var dataset = me.data.datasets[datasetIndex]; + if (!dataset._meta) { + dataset._meta = {}; + } + + var meta = dataset._meta[me.id]; + if (!meta) { + meta = dataset._meta[me.id] = { + type: null, + data: [], + dataset: null, + controller: null, + hidden: null, // See isDatasetVisible() comment + xAxisID: null, + yAxisID: null + }; + } + + return meta; + }, + + getVisibleDatasetCount: function() { + var count = 0; + for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) { + if (this.isDatasetVisible(i)) { + count++; + } + } + return count; + }, + + isDatasetVisible: function(datasetIndex) { + var meta = this.getDatasetMeta(datasetIndex); + + // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false, + // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned. + return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden; + }, + + generateLegend: function() { + return this.options.legendCallback(this); + }, + + /** + * @private + */ + destroyDatasetMeta: function(datasetIndex) { + var id = this.id; + var dataset = this.data.datasets[datasetIndex]; + var meta = dataset._meta && dataset._meta[id]; + + if (meta) { + meta.controller.destroy(); + delete dataset._meta[id]; + } + }, + + destroy: function() { + var me = this; + var canvas = me.canvas; + var i, ilen; + + me.stop(); + + // dataset controllers need to cleanup associated data + for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) { + me.destroyDatasetMeta(i); + } + + if (canvas) { + me.unbindEvents(); + helpers$1.canvas.clear(me); + platform.releaseContext(me.ctx); + me.canvas = null; + me.ctx = null; + } + + core_plugins.notify(me, 'destroy'); + + delete Chart.instances[me.id]; + }, + + toBase64Image: function() { + return this.canvas.toDataURL.apply(this.canvas, arguments); + }, + + initToolTip: function() { + var me = this; + me.tooltip = new core_tooltip({ + _chart: me, + _chartInstance: me, // deprecated, backward compatibility + _data: me.data, + _options: me.options.tooltips + }, me); + }, + + /** + * @private + */ + bindEvents: function() { + var me = this; + var listeners = me._listeners = {}; + var listener = function() { + me.eventHandler.apply(me, arguments); + }; + + helpers$1.each(me.options.events, function(type) { + platform.addEventListener(me, type, listener); + listeners[type] = listener; + }); + + // Elements used to detect size change should not be injected for non responsive charts. + // See https://github.com/chartjs/Chart.js/issues/2210 + if (me.options.responsive) { + listener = function() { + me.resize(); + }; + + platform.addEventListener(me, 'resize', listener); + listeners.resize = listener; + } + }, + + /** + * @private + */ + unbindEvents: function() { + var me = this; + var listeners = me._listeners; + if (!listeners) { + return; + } + + delete me._listeners; + helpers$1.each(listeners, function(listener, type) { + platform.removeEventListener(me, type, listener); + }); + }, + + updateHoverStyle: function(elements, mode, enabled) { + var method = enabled ? 'setHoverStyle' : 'removeHoverStyle'; + var element, i, ilen; + + for (i = 0, ilen = elements.length; i < ilen; ++i) { + element = elements[i]; + if (element) { + this.getDatasetMeta(element._datasetIndex).controller[method](element); + } + } + }, + + /** + * @private + */ + eventHandler: function(e) { + var me = this; + var tooltip = me.tooltip; + + if (core_plugins.notify(me, 'beforeEvent', [e]) === false) { + return; + } + + // Buffer any update calls so that renders do not occur + me._bufferedRender = true; + me._bufferedRequest = null; + + var changed = me.handleEvent(e); + // for smooth tooltip animations issue #4989 + // the tooltip should be the source of change + // Animation check workaround: + // tooltip._start will be null when tooltip isn't animating + if (tooltip) { + changed = tooltip._start + ? tooltip.handleEvent(e) + : changed | tooltip.handleEvent(e); + } + + core_plugins.notify(me, 'afterEvent', [e]); + + var bufferedRequest = me._bufferedRequest; + if (bufferedRequest) { + // If we have an update that was triggered, we need to do a normal render + me.render(bufferedRequest); + } else if (changed && !me.animating) { + // If entering, leaving, or changing elements, animate the change via pivot + me.stop(); + + // We only need to render at this point. Updating will cause scales to be + // recomputed generating flicker & using more memory than necessary. + me.render({ + duration: me.options.hover.animationDuration, + lazy: true + }); + } + + me._bufferedRender = false; + me._bufferedRequest = null; + + return me; + }, + + /** + * Handle an event + * @private + * @param {IEvent} event the event to handle + * @return {boolean} true if the chart needs to re-render + */ + handleEvent: function(e) { + var me = this; + var options = me.options || {}; + var hoverOptions = options.hover; + var changed = false; + + me.lastActive = me.lastActive || []; + + // Find Active Elements for hover and tooltips + if (e.type === 'mouseout') { + me.active = []; + } else { + me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions); + } + + // Invoke onHover hook + // Need to call with native event here to not break backwards compatibility + helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me); + + if (e.type === 'mouseup' || e.type === 'click') { + if (options.onClick) { + // Use e.native here for backwards compatibility + options.onClick.call(me, e.native, me.active); + } + } + + // Remove styling for last active (even if it may still be active) + if (me.lastActive.length) { + me.updateHoverStyle(me.lastActive, hoverOptions.mode, false); + } + + // Built in hover styling + if (me.active.length && hoverOptions.mode) { + me.updateHoverStyle(me.active, hoverOptions.mode, true); + } + + changed = !helpers$1.arrayEquals(me.active, me.lastActive); + + // Remember Last Actives + me.lastActive = me.active; + + return changed; + } +}); + +/** + * NOTE(SB) We actually don't use this container anymore but we need to keep it + * for backward compatibility. Though, it can still be useful for plugins that + * would need to work on multiple charts?! + */ +Chart.instances = {}; + +var core_controller = Chart; + +// DEPRECATIONS + +/** + * Provided for backward compatibility, use Chart instead. + * @class Chart.Controller + * @deprecated since version 2.6 + * @todo remove at version 3 + * @private + */ +Chart.Controller = Chart; + +/** + * Provided for backward compatibility, not available anymore. + * @namespace Chart + * @deprecated since version 2.8 + * @todo remove at version 3 + * @private + */ +Chart.types = {}; + +/** + * Provided for backward compatibility, not available anymore. + * @namespace Chart.helpers.configMerge + * @deprecated since version 2.8.0 + * @todo remove at version 3 + * @private + */ +helpers$1.configMerge = mergeConfig; + +/** + * Provided for backward compatibility, not available anymore. + * @namespace Chart.helpers.scaleMerge + * @deprecated since version 2.8.0 + * @todo remove at version 3 + * @private + */ +helpers$1.scaleMerge = mergeScaleConfig; + +var core_helpers = function() { + + // -- Basic js utility methods + + helpers$1.where = function(collection, filterCallback) { + if (helpers$1.isArray(collection) && Array.prototype.filter) { + return collection.filter(filterCallback); + } + var filtered = []; + + helpers$1.each(collection, function(item) { + if (filterCallback(item)) { + filtered.push(item); + } + }); + + return filtered; + }; + helpers$1.findIndex = Array.prototype.findIndex ? + function(array, callback, scope) { + return array.findIndex(callback, scope); + } : + function(array, callback, scope) { + scope = scope === undefined ? array : scope; + for (var i = 0, ilen = array.length; i < ilen; ++i) { + if (callback.call(scope, array[i], i, array)) { + return i; + } + } + return -1; + }; + helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) { + // Default to start of the array + if (helpers$1.isNullOrUndef(startIndex)) { + startIndex = -1; + } + for (var i = startIndex + 1; i < arrayToSearch.length; i++) { + var currentItem = arrayToSearch[i]; + if (filterCallback(currentItem)) { + return currentItem; + } + } + }; + helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) { + // Default to end of the array + if (helpers$1.isNullOrUndef(startIndex)) { + startIndex = arrayToSearch.length; + } + for (var i = startIndex - 1; i >= 0; i--) { + var currentItem = arrayToSearch[i]; + if (filterCallback(currentItem)) { + return currentItem; + } + } + }; + + // -- Math methods + helpers$1.isNumber = function(n) { + return !isNaN(parseFloat(n)) && isFinite(n); + }; + helpers$1.almostEquals = function(x, y, epsilon) { + return Math.abs(x - y) < epsilon; + }; + helpers$1.almostWhole = function(x, epsilon) { + var rounded = Math.round(x); + return (((rounded - epsilon) < x) && ((rounded + epsilon) > x)); + }; + helpers$1.max = function(array) { + return array.reduce(function(max, value) { + if (!isNaN(value)) { + return Math.max(max, value); + } + return max; + }, Number.NEGATIVE_INFINITY); + }; + helpers$1.min = function(array) { + return array.reduce(function(min, value) { + if (!isNaN(value)) { + return Math.min(min, value); + } + return min; + }, Number.POSITIVE_INFINITY); + }; + helpers$1.sign = Math.sign ? + function(x) { + return Math.sign(x); + } : + function(x) { + x = +x; // convert to a number + if (x === 0 || isNaN(x)) { + return x; + } + return x > 0 ? 1 : -1; + }; + helpers$1.log10 = Math.log10 ? + function(x) { + return Math.log10(x); + } : + function(x) { + var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10. + // Check for whole powers of 10, + // which due to floating point rounding error should be corrected. + var powerOf10 = Math.round(exponent); + var isPowerOf10 = x === Math.pow(10, powerOf10); + + return isPowerOf10 ? powerOf10 : exponent; + }; + helpers$1.toRadians = function(degrees) { + return degrees * (Math.PI / 180); + }; + helpers$1.toDegrees = function(radians) { + return radians * (180 / Math.PI); + }; + + /** + * Returns the number of decimal places + * i.e. the number of digits after the decimal point, of the value of this Number. + * @param {number} x - A number. + * @returns {number} The number of decimal places. + * @private + */ + helpers$1._decimalPlaces = function(x) { + if (!helpers$1.isFinite(x)) { + return; + } + var e = 1; + var p = 0; + while (Math.round(x * e) / e !== x) { + e *= 10; + p++; + } + return p; + }; + + // Gets the angle from vertical upright to the point about a centre. + helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) { + var distanceFromXCenter = anglePoint.x - centrePoint.x; + var distanceFromYCenter = anglePoint.y - centrePoint.y; + var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter); + + var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter); + + if (angle < (-0.5 * Math.PI)) { + angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2] + } + + return { + angle: angle, + distance: radialDistanceFromCenter + }; + }; + helpers$1.distanceBetweenPoints = function(pt1, pt2) { + return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2)); + }; + + /** + * Provided for backward compatibility, not available anymore + * @function Chart.helpers.aliasPixel + * @deprecated since version 2.8.0 + * @todo remove at version 3 + */ + helpers$1.aliasPixel = function(pixelWidth) { + return (pixelWidth % 2 === 0) ? 0 : 0.5; + }; + + /** + * Returns the aligned pixel value to avoid anti-aliasing blur + * @param {Chart} chart - The chart instance. + * @param {number} pixel - A pixel value. + * @param {number} width - The width of the element. + * @returns {number} The aligned pixel value. + * @private + */ + helpers$1._alignPixel = function(chart, pixel, width) { + var devicePixelRatio = chart.currentDevicePixelRatio; + var halfWidth = width / 2; + return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth; + }; + + helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) { + // Props to Rob Spencer at scaled innovation for his post on splining between points + // http://scaledinnovation.com/analytics/splines/aboutSplines.html + + // This function must also respect "skipped" points + + var previous = firstPoint.skip ? middlePoint : firstPoint; + var current = middlePoint; + var next = afterPoint.skip ? middlePoint : afterPoint; + + var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2)); + var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2)); + + var s01 = d01 / (d01 + d12); + var s12 = d12 / (d01 + d12); + + // If all points are the same, s01 & s02 will be inf + s01 = isNaN(s01) ? 0 : s01; + s12 = isNaN(s12) ? 0 : s12; + + var fa = t * s01; // scaling factor for triangle Ta + var fb = t * s12; + + return { + previous: { + x: current.x - fa * (next.x - previous.x), + y: current.y - fa * (next.y - previous.y) + }, + next: { + x: current.x + fb * (next.x - previous.x), + y: current.y + fb * (next.y - previous.y) + } + }; + }; + helpers$1.EPSILON = Number.EPSILON || 1e-14; + helpers$1.splineCurveMonotone = function(points) { + // This function calculates Bézier control points in a similar way than |splineCurve|, + // but preserves monotonicity of the provided data and ensures no local extremums are added + // between the dataset discrete points due to the interpolation. + // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation + + var pointsWithTangents = (points || []).map(function(point) { + return { + model: point._model, + deltaK: 0, + mK: 0 + }; + }); + + // Calculate slopes (deltaK) and initialize tangents (mK) + var pointsLen = pointsWithTangents.length; + var i, pointBefore, pointCurrent, pointAfter; + for (i = 0; i < pointsLen; ++i) { + pointCurrent = pointsWithTangents[i]; + if (pointCurrent.model.skip) { + continue; + } + + pointBefore = i > 0 ? pointsWithTangents[i - 1] : null; + pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null; + if (pointAfter && !pointAfter.model.skip) { + var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x); + + // In the case of two points that appear at the same x pixel, slopeDeltaX is 0 + pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0; + } + + if (!pointBefore || pointBefore.model.skip) { + pointCurrent.mK = pointCurrent.deltaK; + } else if (!pointAfter || pointAfter.model.skip) { + pointCurrent.mK = pointBefore.deltaK; + } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) { + pointCurrent.mK = 0; + } else { + pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2; + } + } + + // Adjust tangents to ensure monotonic properties + var alphaK, betaK, tauK, squaredMagnitude; + for (i = 0; i < pointsLen - 1; ++i) { + pointCurrent = pointsWithTangents[i]; + pointAfter = pointsWithTangents[i + 1]; + if (pointCurrent.model.skip || pointAfter.model.skip) { + continue; + } + + if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) { + pointCurrent.mK = pointAfter.mK = 0; + continue; + } + + alphaK = pointCurrent.mK / pointCurrent.deltaK; + betaK = pointAfter.mK / pointCurrent.deltaK; + squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2); + if (squaredMagnitude <= 9) { + continue; + } + + tauK = 3 / Math.sqrt(squaredMagnitude); + pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK; + pointAfter.mK = betaK * tauK * pointCurrent.deltaK; + } + + // Compute control points + var deltaX; + for (i = 0; i < pointsLen; ++i) { + pointCurrent = pointsWithTangents[i]; + if (pointCurrent.model.skip) { + continue; + } + + pointBefore = i > 0 ? pointsWithTangents[i - 1] : null; + pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null; + if (pointBefore && !pointBefore.model.skip) { + deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3; + pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX; + pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK; + } + if (pointAfter && !pointAfter.model.skip) { + deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3; + pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX; + pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK; + } + } + }; + helpers$1.nextItem = function(collection, index, loop) { + if (loop) { + return index >= collection.length - 1 ? collection[0] : collection[index + 1]; + } + return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1]; + }; + helpers$1.previousItem = function(collection, index, loop) { + if (loop) { + return index <= 0 ? collection[collection.length - 1] : collection[index - 1]; + } + return index <= 0 ? collection[0] : collection[index - 1]; + }; + // Implementation of the nice number algorithm used in determining where axis labels will go + helpers$1.niceNum = function(range, round) { + var exponent = Math.floor(helpers$1.log10(range)); + var fraction = range / Math.pow(10, exponent); + var niceFraction; + + if (round) { + if (fraction < 1.5) { + niceFraction = 1; + } else if (fraction < 3) { + niceFraction = 2; + } else if (fraction < 7) { + niceFraction = 5; + } else { + niceFraction = 10; + } + } else if (fraction <= 1.0) { + niceFraction = 1; + } else if (fraction <= 2) { + niceFraction = 2; + } else if (fraction <= 5) { + niceFraction = 5; + } else { + niceFraction = 10; + } + + return niceFraction * Math.pow(10, exponent); + }; + // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ + helpers$1.requestAnimFrame = (function() { + if (typeof window === 'undefined') { + return function(callback) { + callback(); + }; + } + return window.requestAnimationFrame || + window.webkitRequestAnimationFrame || + window.mozRequestAnimationFrame || + window.oRequestAnimationFrame || + window.msRequestAnimationFrame || + function(callback) { + return window.setTimeout(callback, 1000 / 60); + }; + }()); + // -- DOM methods + helpers$1.getRelativePosition = function(evt, chart) { + var mouseX, mouseY; + var e = evt.originalEvent || evt; + var canvas = evt.target || evt.srcElement; + var boundingRect = canvas.getBoundingClientRect(); + + var touches = e.touches; + if (touches && touches.length > 0) { + mouseX = touches[0].clientX; + mouseY = touches[0].clientY; + + } else { + mouseX = e.clientX; + mouseY = e.clientY; + } + + // Scale mouse coordinates into canvas coordinates + // by following the pattern laid out by 'jerryj' in the comments of + // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/ + var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left')); + var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top')); + var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right')); + var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom')); + var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight; + var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom; + + // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However + // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here + mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio); + mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio); + + return { + x: mouseX, + y: mouseY + }; + + }; + + // Private helper function to convert max-width/max-height values that may be percentages into a number + function parseMaxStyle(styleValue, node, parentProperty) { + var valueInPixels; + if (typeof styleValue === 'string') { + valueInPixels = parseInt(styleValue, 10); + + if (styleValue.indexOf('%') !== -1) { + // percentage * size in dimension + valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty]; + } + } else { + valueInPixels = styleValue; + } + + return valueInPixels; + } + + /** + * Returns if the given value contains an effective constraint. + * @private + */ + function isConstrainedValue(value) { + return value !== undefined && value !== null && value !== 'none'; + } + + /** + * Returns the max width or height of the given DOM node in a cross-browser compatible fashion + * @param {HTMLElement} domNode - the node to check the constraint on + * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height') + * @param {string} percentageProperty - property of parent to use when calculating width as a percentage + * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser} + */ + function getConstraintDimension(domNode, maxStyle, percentageProperty) { + var view = document.defaultView; + var parentNode = helpers$1._getParentNode(domNode); + var constrainedNode = view.getComputedStyle(domNode)[maxStyle]; + var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle]; + var hasCNode = isConstrainedValue(constrainedNode); + var hasCContainer = isConstrainedValue(constrainedContainer); + var infinity = Number.POSITIVE_INFINITY; + + if (hasCNode || hasCContainer) { + return Math.min( + hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity, + hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity); + } + + return 'none'; + } + // returns Number or undefined if no constraint + helpers$1.getConstraintWidth = function(domNode) { + return getConstraintDimension(domNode, 'max-width', 'clientWidth'); + }; + // returns Number or undefined if no constraint + helpers$1.getConstraintHeight = function(domNode) { + return getConstraintDimension(domNode, 'max-height', 'clientHeight'); + }; + /** + * @private + */ + helpers$1._calculatePadding = function(container, padding, parentDimension) { + padding = helpers$1.getStyle(container, padding); + + return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10); + }; + /** + * @private + */ + helpers$1._getParentNode = function(domNode) { + var parent = domNode.parentNode; + if (parent && parent.toString() === '[object ShadowRoot]') { + parent = parent.host; + } + return parent; + }; + helpers$1.getMaximumWidth = function(domNode) { + var container = helpers$1._getParentNode(domNode); + if (!container) { + return domNode.clientWidth; + } + + var clientWidth = container.clientWidth; + var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth); + var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth); + + var w = clientWidth - paddingLeft - paddingRight; + var cw = helpers$1.getConstraintWidth(domNode); + return isNaN(cw) ? w : Math.min(w, cw); + }; + helpers$1.getMaximumHeight = function(domNode) { + var container = helpers$1._getParentNode(domNode); + if (!container) { + return domNode.clientHeight; + } + + var clientHeight = container.clientHeight; + var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight); + var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight); + + var h = clientHeight - paddingTop - paddingBottom; + var ch = helpers$1.getConstraintHeight(domNode); + return isNaN(ch) ? h : Math.min(h, ch); + }; + helpers$1.getStyle = function(el, property) { + return el.currentStyle ? + el.currentStyle[property] : + document.defaultView.getComputedStyle(el, null).getPropertyValue(property); + }; + helpers$1.retinaScale = function(chart, forceRatio) { + var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1; + if (pixelRatio === 1) { + return; + } + + var canvas = chart.canvas; + var height = chart.height; + var width = chart.width; + + canvas.height = height * pixelRatio; + canvas.width = width * pixelRatio; + chart.ctx.scale(pixelRatio, pixelRatio); + + // If no style has been set on the canvas, the render size is used as display size, + // making the chart visually bigger, so let's enforce it to the "correct" values. + // See https://github.com/chartjs/Chart.js/issues/3575 + if (!canvas.style.height && !canvas.style.width) { + canvas.style.height = height + 'px'; + canvas.style.width = width + 'px'; + } + }; + // -- Canvas methods + helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) { + return fontStyle + ' ' + pixelSize + 'px ' + fontFamily; + }; + helpers$1.longestText = function(ctx, font, arrayOfThings, cache) { + cache = cache || {}; + var data = cache.data = cache.data || {}; + var gc = cache.garbageCollect = cache.garbageCollect || []; + + if (cache.font !== font) { + data = cache.data = {}; + gc = cache.garbageCollect = []; + cache.font = font; + } + + ctx.font = font; + var longest = 0; + helpers$1.each(arrayOfThings, function(thing) { + // Undefined strings and arrays should not be measured + if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) { + longest = helpers$1.measureText(ctx, data, gc, longest, thing); + } else if (helpers$1.isArray(thing)) { + // if it is an array lets measure each element + // to do maybe simplify this function a bit so we can do this more recursively? + helpers$1.each(thing, function(nestedThing) { + // Undefined strings and arrays should not be measured + if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) { + longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing); + } + }); + } + }); + + var gcLen = gc.length / 2; + if (gcLen > arrayOfThings.length) { + for (var i = 0; i < gcLen; i++) { + delete data[gc[i]]; + } + gc.splice(0, gcLen); + } + return longest; + }; + helpers$1.measureText = function(ctx, data, gc, longest, string) { + var textWidth = data[string]; + if (!textWidth) { + textWidth = data[string] = ctx.measureText(string).width; + gc.push(string); + } + if (textWidth > longest) { + longest = textWidth; + } + return longest; + }; + helpers$1.numberOfLabelLines = function(arrayOfThings) { + var numberOfLines = 1; + helpers$1.each(arrayOfThings, function(thing) { + if (helpers$1.isArray(thing)) { + if (thing.length > numberOfLines) { + numberOfLines = thing.length; + } + } + }); + return numberOfLines; + }; + + helpers$1.color = !chartjsColor ? + function(value) { + console.error('Color.js not found!'); + return value; + } : + function(value) { + /* global CanvasGradient */ + if (value instanceof CanvasGradient) { + value = core_defaults.global.defaultColor; + } + + return chartjsColor(value); + }; + + helpers$1.getHoverColor = function(colorValue) { + /* global CanvasPattern */ + return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ? + colorValue : + helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString(); + }; +}; + +function abstract() { + throw new Error( + 'This method is not implemented: either no adapter can ' + + 'be found or an incomplete integration was provided.' + ); +} + +/** + * Date adapter (current used by the time scale) + * @namespace Chart._adapters._date + * @memberof Chart._adapters + * @private + */ + +/** + * Currently supported unit string values. + * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')} + * @memberof Chart._adapters._date + * @name Unit + */ + +/** + * @class + */ +function DateAdapter(options) { + this.options = options || {}; +} + +helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ { + /** + * Returns a map of time formats for the supported formatting units defined + * in Unit as well as 'datetime' representing a detailed date/time string. + * @returns {{string: string}} + */ + formats: abstract, + + /** + * Parses the given `value` and return the associated timestamp. + * @param {any} value - the value to parse (usually comes from the data) + * @param {string} [format] - the expected data format + * @returns {(number|null)} + * @function + */ + parse: abstract, + + /** + * Returns the formatted date in the specified `format` for a given `timestamp`. + * @param {number} timestamp - the timestamp to format + * @param {string} format - the date/time token + * @return {string} + * @function + */ + format: abstract, + + /** + * Adds the specified `amount` of `unit` to the given `timestamp`. + * @param {number} timestamp - the input timestamp + * @param {number} amount - the amount to add + * @param {Unit} unit - the unit as string + * @return {number} + * @function + */ + add: abstract, + + /** + * Returns the number of `unit` between the given timestamps. + * @param {number} max - the input timestamp (reference) + * @param {number} min - the timestamp to substract + * @param {Unit} unit - the unit as string + * @return {number} + * @function + */ + diff: abstract, + + /** + * Returns start of `unit` for the given `timestamp`. + * @param {number} timestamp - the input timestamp + * @param {Unit} unit - the unit as string + * @param {number} [weekday] - the ISO day of the week with 1 being Monday + * and 7 being Sunday (only needed if param *unit* is `isoWeek`). + * @function + */ + startOf: abstract, + + /** + * Returns end of `unit` for the given `timestamp`. + * @param {number} timestamp - the input timestamp + * @param {Unit} unit - the unit as string + * @function + */ + endOf: abstract, + + // DEPRECATIONS + + /** + * Provided for backward compatibility for scale.getValueForPixel(), + * this method should be overridden only by the moment adapter. + * @deprecated since version 2.8.0 + * @todo remove at version 3 + * @private + */ + _create: function(value) { + return value; + } +}); + +DateAdapter.override = function(members) { + helpers$1.extend(DateAdapter.prototype, members); +}; + +var _date = DateAdapter; + +var core_adapters = { + _date: _date +}; + +/** + * Namespace to hold static tick generation functions + * @namespace Chart.Ticks + */ +var core_ticks = { + /** + * Namespace to hold formatters for different types of ticks + * @namespace Chart.Ticks.formatters + */ + formatters: { + /** + * Formatter for value labels + * @method Chart.Ticks.formatters.values + * @param value the value to display + * @return {string|string[]} the label to display + */ + values: function(value) { + return helpers$1.isArray(value) ? value : '' + value; + }, + + /** + * Formatter for linear numeric ticks + * @method Chart.Ticks.formatters.linear + * @param tickValue {number} the value to be formatted + * @param index {number} the position of the tickValue parameter in the ticks array + * @param ticks {number[]} the list of ticks being converted + * @return {string} string representation of the tickValue parameter + */ + linear: function(tickValue, index, ticks) { + // If we have lots of ticks, don't use the ones + var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0]; + + // If we have a number like 2.5 as the delta, figure out how many decimal places we need + if (Math.abs(delta) > 1) { + if (tickValue !== Math.floor(tickValue)) { + // not an integer + delta = tickValue - Math.floor(tickValue); + } + } + + var logDelta = helpers$1.log10(Math.abs(delta)); + var tickString = ''; + + if (tickValue !== 0) { + var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1])); + if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation + var logTick = helpers$1.log10(Math.abs(tickValue)); + tickString = tickValue.toExponential(Math.floor(logTick) - Math.floor(logDelta)); + } else { + var numDecimal = -1 * Math.floor(logDelta); + numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places + tickString = tickValue.toFixed(numDecimal); + } + } else { + tickString = '0'; // never show decimal places for 0 + } + + return tickString; + }, + + logarithmic: function(tickValue, index, ticks) { + var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue)))); + + if (tickValue === 0) { + return '0'; + } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) { + return tickValue.toExponential(); + } + return ''; + } + } +}; + +var valueOrDefault$9 = helpers$1.valueOrDefault; +var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault; + +core_defaults._set('scale', { + display: true, + position: 'left', + offset: false, + + // grid line settings + gridLines: { + display: true, + color: 'rgba(0, 0, 0, 0.1)', + lineWidth: 1, + drawBorder: true, + drawOnChartArea: true, + drawTicks: true, + tickMarkLength: 10, + zeroLineWidth: 1, + zeroLineColor: 'rgba(0,0,0,0.25)', + zeroLineBorderDash: [], + zeroLineBorderDashOffset: 0.0, + offsetGridLines: false, + borderDash: [], + borderDashOffset: 0.0 + }, + + // scale label + scaleLabel: { + // display property + display: false, + + // actual label + labelString: '', + + // top/bottom padding + padding: { + top: 4, + bottom: 4 + } + }, + + // label settings + ticks: { + beginAtZero: false, + minRotation: 0, + maxRotation: 50, + mirror: false, + padding: 0, + reverse: false, + display: true, + autoSkip: true, + autoSkipPadding: 0, + labelOffset: 0, + // We pass through arrays to be rendered as multiline labels, we convert Others to strings here. + callback: core_ticks.formatters.values, + minor: {}, + major: {} + } +}); + +function labelsFromTicks(ticks) { + var labels = []; + var i, ilen; + + for (i = 0, ilen = ticks.length; i < ilen; ++i) { + labels.push(ticks[i].label); + } + + return labels; +} + +function getPixelForGridLine(scale, index, offsetGridLines) { + var lineValue = scale.getPixelForTick(index); + + if (offsetGridLines) { + if (scale.getTicks().length === 1) { + lineValue -= scale.isHorizontal() ? + Math.max(lineValue - scale.left, scale.right - lineValue) : + Math.max(lineValue - scale.top, scale.bottom - lineValue); + } else if (index === 0) { + lineValue -= (scale.getPixelForTick(1) - lineValue) / 2; + } else { + lineValue -= (lineValue - scale.getPixelForTick(index - 1)) / 2; + } + } + return lineValue; +} + +function computeTextSize(context, tick, font) { + return helpers$1.isArray(tick) ? + helpers$1.longestText(context, font, tick) : + context.measureText(tick).width; +} + +var core_scale = core_element.extend({ + /** + * Get the padding needed for the scale + * @method getPadding + * @private + * @returns {Padding} the necessary padding + */ + getPadding: function() { + var me = this; + return { + left: me.paddingLeft || 0, + top: me.paddingTop || 0, + right: me.paddingRight || 0, + bottom: me.paddingBottom || 0 + }; + }, + + /** + * Returns the scale tick objects ({label, major}) + * @since 2.7 + */ + getTicks: function() { + return this._ticks; + }, + + // These methods are ordered by lifecyle. Utilities then follow. + // Any function defined here is inherited by all scale types. + // Any function can be extended by the scale type + + mergeTicksOptions: function() { + var ticks = this.options.ticks; + if (ticks.minor === false) { + ticks.minor = { + display: false + }; + } + if (ticks.major === false) { + ticks.major = { + display: false + }; + } + for (var key in ticks) { + if (key !== 'major' && key !== 'minor') { + if (typeof ticks.minor[key] === 'undefined') { + ticks.minor[key] = ticks[key]; + } + if (typeof ticks.major[key] === 'undefined') { + ticks.major[key] = ticks[key]; + } + } + } + }, + beforeUpdate: function() { + helpers$1.callback(this.options.beforeUpdate, [this]); + }, + + update: function(maxWidth, maxHeight, margins) { + var me = this; + var i, ilen, labels, label, ticks, tick; + + // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) + me.beforeUpdate(); + + // Absorb the master measurements + me.maxWidth = maxWidth; + me.maxHeight = maxHeight; + me.margins = helpers$1.extend({ + left: 0, + right: 0, + top: 0, + bottom: 0 + }, margins); + + me._maxLabelLines = 0; + me.longestLabelWidth = 0; + me.longestTextCache = me.longestTextCache || {}; + + // Dimensions + me.beforeSetDimensions(); + me.setDimensions(); + me.afterSetDimensions(); + + // Data min/max + me.beforeDataLimits(); + me.determineDataLimits(); + me.afterDataLimits(); + + // Ticks - `this.ticks` is now DEPRECATED! + // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member + // and must not be accessed directly from outside this class. `this.ticks` being + // around for long time and not marked as private, we can't change its structure + // without unexpected breaking changes. If you need to access the scale ticks, + // use scale.getTicks() instead. + + me.beforeBuildTicks(); + + // New implementations should return an array of objects but for BACKWARD COMPAT, + // we still support no return (`this.ticks` internally set by calling this method). + ticks = me.buildTicks() || []; + + // Allow modification of ticks in callback. + ticks = me.afterBuildTicks(ticks) || ticks; + + me.beforeTickToLabelConversion(); + + // New implementations should return the formatted tick labels but for BACKWARD + // COMPAT, we still support no return (`this.ticks` internally changed by calling + // this method and supposed to contain only string values). + labels = me.convertTicksToLabels(ticks) || me.ticks; + + me.afterTickToLabelConversion(); + + me.ticks = labels; // BACKWARD COMPATIBILITY + + // IMPORTANT: from this point, we consider that `this.ticks` will NEVER change! + + // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`) + for (i = 0, ilen = labels.length; i < ilen; ++i) { + label = labels[i]; + tick = ticks[i]; + if (!tick) { + ticks.push(tick = { + label: label, + major: false + }); + } else { + tick.label = label; + } + } + + me._ticks = ticks; + + // Tick Rotation + me.beforeCalculateTickRotation(); + me.calculateTickRotation(); + me.afterCalculateTickRotation(); + // Fit + me.beforeFit(); + me.fit(); + me.afterFit(); + // + me.afterUpdate(); + + return me.minSize; + + }, + afterUpdate: function() { + helpers$1.callback(this.options.afterUpdate, [this]); + }, + + // + + beforeSetDimensions: function() { + helpers$1.callback(this.options.beforeSetDimensions, [this]); + }, + setDimensions: function() { + var me = this; + // Set the unconstrained dimension before label rotation + if (me.isHorizontal()) { + // Reset position before calculating rotation + me.width = me.maxWidth; + me.left = 0; + me.right = me.width; + } else { + me.height = me.maxHeight; + + // Reset position before calculating rotation + me.top = 0; + me.bottom = me.height; + } + + // Reset padding + me.paddingLeft = 0; + me.paddingTop = 0; + me.paddingRight = 0; + me.paddingBottom = 0; + }, + afterSetDimensions: function() { + helpers$1.callback(this.options.afterSetDimensions, [this]); + }, + + // Data limits + beforeDataLimits: function() { + helpers$1.callback(this.options.beforeDataLimits, [this]); + }, + determineDataLimits: helpers$1.noop, + afterDataLimits: function() { + helpers$1.callback(this.options.afterDataLimits, [this]); + }, + + // + beforeBuildTicks: function() { + helpers$1.callback(this.options.beforeBuildTicks, [this]); + }, + buildTicks: helpers$1.noop, + afterBuildTicks: function(ticks) { + var me = this; + // ticks is empty for old axis implementations here + if (helpers$1.isArray(ticks) && ticks.length) { + return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]); + } + // Support old implementations (that modified `this.ticks` directly in buildTicks) + me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks; + return ticks; + }, + + beforeTickToLabelConversion: function() { + helpers$1.callback(this.options.beforeTickToLabelConversion, [this]); + }, + convertTicksToLabels: function() { + var me = this; + // Convert ticks to strings + var tickOpts = me.options.ticks; + me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this); + }, + afterTickToLabelConversion: function() { + helpers$1.callback(this.options.afterTickToLabelConversion, [this]); + }, + + // + + beforeCalculateTickRotation: function() { + helpers$1.callback(this.options.beforeCalculateTickRotation, [this]); + }, + calculateTickRotation: function() { + var me = this; + var context = me.ctx; + var tickOpts = me.options.ticks; + var labels = labelsFromTicks(me._ticks); + + // Get the width of each grid by calculating the difference + // between x offsets between 0 and 1. + var tickFont = helpers$1.options._parseFont(tickOpts); + context.font = tickFont.string; + + var labelRotation = tickOpts.minRotation || 0; + + if (labels.length && me.options.display && me.isHorizontal()) { + var originalLabelWidth = helpers$1.longestText(context, tickFont.string, labels, me.longestTextCache); + var labelWidth = originalLabelWidth; + var cosRotation, sinRotation; + + // Allow 3 pixels x2 padding either side for label readability + var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6; + + // Max label rotation can be set or default to 90 - also act as a loop counter + while (labelWidth > tickWidth && labelRotation < tickOpts.maxRotation) { + var angleRadians = helpers$1.toRadians(labelRotation); + cosRotation = Math.cos(angleRadians); + sinRotation = Math.sin(angleRadians); + + if (sinRotation * originalLabelWidth > me.maxHeight) { + // go back one step + labelRotation--; + break; + } + + labelRotation++; + labelWidth = cosRotation * originalLabelWidth; + } + } + + me.labelRotation = labelRotation; + }, + afterCalculateTickRotation: function() { + helpers$1.callback(this.options.afterCalculateTickRotation, [this]); + }, + + // + + beforeFit: function() { + helpers$1.callback(this.options.beforeFit, [this]); + }, + fit: function() { + var me = this; + // Reset + var minSize = me.minSize = { + width: 0, + height: 0 + }; + + var labels = labelsFromTicks(me._ticks); + + var opts = me.options; + var tickOpts = opts.ticks; + var scaleLabelOpts = opts.scaleLabel; + var gridLineOpts = opts.gridLines; + var display = me._isVisible(); + var position = opts.position; + var isHorizontal = me.isHorizontal(); + + var parseFont = helpers$1.options._parseFont; + var tickFont = parseFont(tickOpts); + var tickMarkLength = opts.gridLines.tickMarkLength; + + // Width + if (isHorizontal) { + // subtract the margins to line up with the chartArea if we are a full width scale + minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth; + } else { + minSize.width = display && gridLineOpts.drawTicks ? tickMarkLength : 0; + } + + // height + if (isHorizontal) { + minSize.height = display && gridLineOpts.drawTicks ? tickMarkLength : 0; + } else { + minSize.height = me.maxHeight; // fill all the height + } + + // Are we showing a title for the scale? + if (scaleLabelOpts.display && display) { + var scaleLabelFont = parseFont(scaleLabelOpts); + var scaleLabelPadding = helpers$1.options.toPadding(scaleLabelOpts.padding); + var deltaHeight = scaleLabelFont.lineHeight + scaleLabelPadding.height; + + if (isHorizontal) { + minSize.height += deltaHeight; + } else { + minSize.width += deltaHeight; + } + } + + // Don't bother fitting the ticks if we are not showing the labels + if (tickOpts.display && display) { + var largestTextWidth = helpers$1.longestText(me.ctx, tickFont.string, labels, me.longestTextCache); + var tallestLabelHeightInLines = helpers$1.numberOfLabelLines(labels); + var lineSpace = tickFont.size * 0.5; + var tickPadding = me.options.ticks.padding; + + // Store max number of lines and widest label for _autoSkip + me._maxLabelLines = tallestLabelHeightInLines; + me.longestLabelWidth = largestTextWidth; + + if (isHorizontal) { + var angleRadians = helpers$1.toRadians(me.labelRotation); + var cosRotation = Math.cos(angleRadians); + var sinRotation = Math.sin(angleRadians); + + // TODO - improve this calculation + var labelHeight = (sinRotation * largestTextWidth) + + (tickFont.lineHeight * tallestLabelHeightInLines) + + lineSpace; // padding + + minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding); + + me.ctx.font = tickFont.string; + var firstLabelWidth = computeTextSize(me.ctx, labels[0], tickFont.string); + var lastLabelWidth = computeTextSize(me.ctx, labels[labels.length - 1], tickFont.string); + var offsetLeft = me.getPixelForTick(0) - me.left; + var offsetRight = me.right - me.getPixelForTick(labels.length - 1); + var paddingLeft, paddingRight; + + // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned + // which means that the right padding is dominated by the font height + if (me.labelRotation !== 0) { + paddingLeft = position === 'bottom' ? (cosRotation * firstLabelWidth) : (cosRotation * lineSpace); + paddingRight = position === 'bottom' ? (cosRotation * lineSpace) : (cosRotation * lastLabelWidth); + } else { + paddingLeft = firstLabelWidth / 2; + paddingRight = lastLabelWidth / 2; + } + me.paddingLeft = Math.max(paddingLeft - offsetLeft, 0) + 3; // add 3 px to move away from canvas edges + me.paddingRight = Math.max(paddingRight - offsetRight, 0) + 3; + } else { + // A vertical axis is more constrained by the width. Labels are the + // dominant factor here, so get that length first and account for padding + if (tickOpts.mirror) { + largestTextWidth = 0; + } else { + // use lineSpace for consistency with horizontal axis + // tickPadding is not implemented for horizontal + largestTextWidth += tickPadding + lineSpace; + } + + minSize.width = Math.min(me.maxWidth, minSize.width + largestTextWidth); + + me.paddingTop = tickFont.size / 2; + me.paddingBottom = tickFont.size / 2; + } + } + + me.handleMargins(); + + me.width = minSize.width; + me.height = minSize.height; + }, + + /** + * Handle margins and padding interactions + * @private + */ + handleMargins: function() { + var me = this; + if (me.margins) { + me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0); + me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0); + me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0); + me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0); + } + }, + + afterFit: function() { + helpers$1.callback(this.options.afterFit, [this]); + }, + + // Shared Methods + isHorizontal: function() { + return this.options.position === 'top' || this.options.position === 'bottom'; + }, + isFullWidth: function() { + return (this.options.fullWidth); + }, + + // Get the correct value. NaN bad inputs, If the value type is object get the x or y based on whether we are horizontal or not + getRightValue: function(rawValue) { + // Null and undefined values first + if (helpers$1.isNullOrUndef(rawValue)) { + return NaN; + } + // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values + if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) { + return NaN; + } + // If it is in fact an object, dive in one more level + if (rawValue) { + if (this.isHorizontal()) { + if (rawValue.x !== undefined) { + return this.getRightValue(rawValue.x); + } + } else if (rawValue.y !== undefined) { + return this.getRightValue(rawValue.y); + } + } + + // Value is good, return it + return rawValue; + }, + + /** + * Used to get the value to display in the tooltip for the data at the given index + * @param index + * @param datasetIndex + */ + getLabelForIndex: helpers$1.noop, + + /** + * Returns the location of the given data point. Value can either be an index or a numerical value + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param value + * @param index + * @param datasetIndex + */ + getPixelForValue: helpers$1.noop, + + /** + * Used to get the data value from a given pixel. This is the inverse of getPixelForValue + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param pixel + */ + getValueForPixel: helpers$1.noop, + + /** + * Returns the location of the tick at the given index + * The coordinate (0, 0) is at the upper-left corner of the canvas + */ + getPixelForTick: function(index) { + var me = this; + var offset = me.options.offset; + if (me.isHorizontal()) { + var innerWidth = me.width - (me.paddingLeft + me.paddingRight); + var tickWidth = innerWidth / Math.max((me._ticks.length - (offset ? 0 : 1)), 1); + var pixel = (tickWidth * index) + me.paddingLeft; + + if (offset) { + pixel += tickWidth / 2; + } + + var finalVal = me.left + pixel; + finalVal += me.isFullWidth() ? me.margins.left : 0; + return finalVal; + } + var innerHeight = me.height - (me.paddingTop + me.paddingBottom); + return me.top + (index * (innerHeight / (me._ticks.length - 1))); + }, + + /** + * Utility for getting the pixel location of a percentage of scale + * The coordinate (0, 0) is at the upper-left corner of the canvas + */ + getPixelForDecimal: function(decimal) { + var me = this; + if (me.isHorizontal()) { + var innerWidth = me.width - (me.paddingLeft + me.paddingRight); + var valueOffset = (innerWidth * decimal) + me.paddingLeft; + + var finalVal = me.left + valueOffset; + finalVal += me.isFullWidth() ? me.margins.left : 0; + return finalVal; + } + return me.top + (decimal * me.height); + }, + + /** + * Returns the pixel for the minimum chart value + * The coordinate (0, 0) is at the upper-left corner of the canvas + */ + getBasePixel: function() { + return this.getPixelForValue(this.getBaseValue()); + }, + + getBaseValue: function() { + var me = this; + var min = me.min; + var max = me.max; + + return me.beginAtZero ? 0 : + min < 0 && max < 0 ? max : + min > 0 && max > 0 ? min : + 0; + }, + + /** + * Returns a subset of ticks to be plotted to avoid overlapping labels. + * @private + */ + _autoSkip: function(ticks) { + var me = this; + var isHorizontal = me.isHorizontal(); + var optionTicks = me.options.ticks.minor; + var tickCount = ticks.length; + var skipRatio = false; + var maxTicks = optionTicks.maxTicksLimit; + + // Total space needed to display all ticks. First and last ticks are + // drawn as their center at end of axis, so tickCount-1 + var ticksLength = me._tickSize() * (tickCount - 1); + + // Axis length + var axisLength = isHorizontal + ? me.width - (me.paddingLeft + me.paddingRight) + : me.height - (me.paddingTop + me.PaddingBottom); + + var result = []; + var i, tick; + + if (ticksLength > axisLength) { + skipRatio = 1 + Math.floor(ticksLength / axisLength); + } + + // if they defined a max number of optionTicks, + // increase skipRatio until that number is met + if (tickCount > maxTicks) { + skipRatio = Math.max(skipRatio, 1 + Math.floor(tickCount / maxTicks)); + } + + for (i = 0; i < tickCount; i++) { + tick = ticks[i]; + + if (skipRatio > 1 && i % skipRatio > 0) { + // leave tick in place but make sure it's not displayed (#4635) + delete tick.label; + } + result.push(tick); + } + return result; + }, + + /** + * @private + */ + _tickSize: function() { + var me = this; + var isHorizontal = me.isHorizontal(); + var optionTicks = me.options.ticks.minor; + + // Calculate space needed by label in axis direction. + var rot = helpers$1.toRadians(me.labelRotation); + var cos = Math.abs(Math.cos(rot)); + var sin = Math.abs(Math.sin(rot)); + + var padding = optionTicks.autoSkipPadding || 0; + var w = (me.longestLabelWidth + padding) || 0; + + var tickFont = helpers$1.options._parseFont(optionTicks); + var h = (me._maxLabelLines * tickFont.lineHeight + padding) || 0; + + // Calculate space needed for 1 tick in axis direction. + return isHorizontal + ? h * cos > w * sin ? w / cos : h / sin + : h * sin < w * cos ? h / cos : w / sin; + }, + + /** + * @private + */ + _isVisible: function() { + var me = this; + var chart = me.chart; + var display = me.options.display; + var i, ilen, meta; + + if (display !== 'auto') { + return !!display; + } + + // When 'auto', the scale is visible if at least one associated dataset is visible. + for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) { + if (chart.isDatasetVisible(i)) { + meta = chart.getDatasetMeta(i); + if (meta.xAxisID === me.id || meta.yAxisID === me.id) { + return true; + } + } + } + + return false; + }, + + /** + * Actually draw the scale on the canvas + * @param {object} chartArea - the area of the chart to draw full grid lines on + */ + draw: function(chartArea) { + var me = this; + var options = me.options; + + if (!me._isVisible()) { + return; + } + + var chart = me.chart; + var context = me.ctx; + var globalDefaults = core_defaults.global; + var defaultFontColor = globalDefaults.defaultFontColor; + var optionTicks = options.ticks.minor; + var optionMajorTicks = options.ticks.major || optionTicks; + var gridLines = options.gridLines; + var scaleLabel = options.scaleLabel; + var position = options.position; + + var isRotated = me.labelRotation !== 0; + var isMirrored = optionTicks.mirror; + var isHorizontal = me.isHorizontal(); + + var parseFont = helpers$1.options._parseFont; + var ticks = optionTicks.display && optionTicks.autoSkip ? me._autoSkip(me.getTicks()) : me.getTicks(); + var tickFontColor = valueOrDefault$9(optionTicks.fontColor, defaultFontColor); + var tickFont = parseFont(optionTicks); + var lineHeight = tickFont.lineHeight; + var majorTickFontColor = valueOrDefault$9(optionMajorTicks.fontColor, defaultFontColor); + var majorTickFont = parseFont(optionMajorTicks); + var tickPadding = optionTicks.padding; + var labelOffset = optionTicks.labelOffset; + + var tl = gridLines.drawTicks ? gridLines.tickMarkLength : 0; + + var scaleLabelFontColor = valueOrDefault$9(scaleLabel.fontColor, defaultFontColor); + var scaleLabelFont = parseFont(scaleLabel); + var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding); + var labelRotationRadians = helpers$1.toRadians(me.labelRotation); + + var itemsToDraw = []; + + var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0; + var alignPixel = helpers$1._alignPixel; + var borderValue, tickStart, tickEnd; + + if (position === 'top') { + borderValue = alignPixel(chart, me.bottom, axisWidth); + tickStart = me.bottom - tl; + tickEnd = borderValue - axisWidth / 2; + } else if (position === 'bottom') { + borderValue = alignPixel(chart, me.top, axisWidth); + tickStart = borderValue + axisWidth / 2; + tickEnd = me.top + tl; + } else if (position === 'left') { + borderValue = alignPixel(chart, me.right, axisWidth); + tickStart = me.right - tl; + tickEnd = borderValue - axisWidth / 2; + } else { + borderValue = alignPixel(chart, me.left, axisWidth); + tickStart = borderValue + axisWidth / 2; + tickEnd = me.left + tl; + } + + var epsilon = 0.0000001; // 0.0000001 is margin in pixels for Accumulated error. + + helpers$1.each(ticks, function(tick, index) { + // autoskipper skipped this tick (#4635) + if (helpers$1.isNullOrUndef(tick.label)) { + return; + } + + var label = tick.label; + var lineWidth, lineColor, borderDash, borderDashOffset; + if (index === me.zeroLineIndex && options.offset === gridLines.offsetGridLines) { + // Draw the first index specially + lineWidth = gridLines.zeroLineWidth; + lineColor = gridLines.zeroLineColor; + borderDash = gridLines.zeroLineBorderDash || []; + borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0; + } else { + lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, index); + lineColor = valueAtIndexOrDefault(gridLines.color, index); + borderDash = gridLines.borderDash || []; + borderDashOffset = gridLines.borderDashOffset || 0.0; + } + + // Common properties + var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY, textOffset, textAlign; + var labelCount = helpers$1.isArray(label) ? label.length : 1; + var lineValue = getPixelForGridLine(me, index, gridLines.offsetGridLines); + + if (isHorizontal) { + var labelYOffset = tl + tickPadding; + + if (lineValue < me.left - epsilon) { + lineColor = 'rgba(0,0,0,0)'; + } + + tx1 = tx2 = x1 = x2 = alignPixel(chart, lineValue, lineWidth); + ty1 = tickStart; + ty2 = tickEnd; + labelX = me.getPixelForTick(index) + labelOffset; // x values for optionTicks (need to consider offsetLabel option) + + if (position === 'top') { + y1 = alignPixel(chart, chartArea.top, axisWidth) + axisWidth / 2; + y2 = chartArea.bottom; + textOffset = ((!isRotated ? 0.5 : 1) - labelCount) * lineHeight; + textAlign = !isRotated ? 'center' : 'left'; + labelY = me.bottom - labelYOffset; + } else { + y1 = chartArea.top; + y2 = alignPixel(chart, chartArea.bottom, axisWidth) - axisWidth / 2; + textOffset = (!isRotated ? 0.5 : 0) * lineHeight; + textAlign = !isRotated ? 'center' : 'right'; + labelY = me.top + labelYOffset; + } + } else { + var labelXOffset = (isMirrored ? 0 : tl) + tickPadding; + + if (lineValue < me.top - epsilon) { + lineColor = 'rgba(0,0,0,0)'; + } + + tx1 = tickStart; + tx2 = tickEnd; + ty1 = ty2 = y1 = y2 = alignPixel(chart, lineValue, lineWidth); + labelY = me.getPixelForTick(index) + labelOffset; + textOffset = (1 - labelCount) * lineHeight / 2; + + if (position === 'left') { + x1 = alignPixel(chart, chartArea.left, axisWidth) + axisWidth / 2; + x2 = chartArea.right; + textAlign = isMirrored ? 'left' : 'right'; + labelX = me.right - labelXOffset; + } else { + x1 = chartArea.left; + x2 = alignPixel(chart, chartArea.right, axisWidth) - axisWidth / 2; + textAlign = isMirrored ? 'right' : 'left'; + labelX = me.left + labelXOffset; + } + } + + itemsToDraw.push({ + tx1: tx1, + ty1: ty1, + tx2: tx2, + ty2: ty2, + x1: x1, + y1: y1, + x2: x2, + y2: y2, + labelX: labelX, + labelY: labelY, + glWidth: lineWidth, + glColor: lineColor, + glBorderDash: borderDash, + glBorderDashOffset: borderDashOffset, + rotation: -1 * labelRotationRadians, + label: label, + major: tick.major, + textOffset: textOffset, + textAlign: textAlign + }); + }); + + // Draw all of the tick labels, tick marks, and grid lines at the correct places + helpers$1.each(itemsToDraw, function(itemToDraw) { + var glWidth = itemToDraw.glWidth; + var glColor = itemToDraw.glColor; + + if (gridLines.display && glWidth && glColor) { + context.save(); + context.lineWidth = glWidth; + context.strokeStyle = glColor; + if (context.setLineDash) { + context.setLineDash(itemToDraw.glBorderDash); + context.lineDashOffset = itemToDraw.glBorderDashOffset; + } + + context.beginPath(); + + if (gridLines.drawTicks) { + context.moveTo(itemToDraw.tx1, itemToDraw.ty1); + context.lineTo(itemToDraw.tx2, itemToDraw.ty2); + } + + if (gridLines.drawOnChartArea) { + context.moveTo(itemToDraw.x1, itemToDraw.y1); + context.lineTo(itemToDraw.x2, itemToDraw.y2); + } + + context.stroke(); + context.restore(); + } + + if (optionTicks.display) { + // Make sure we draw text in the correct color and font + context.save(); + context.translate(itemToDraw.labelX, itemToDraw.labelY); + context.rotate(itemToDraw.rotation); + context.font = itemToDraw.major ? majorTickFont.string : tickFont.string; + context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor; + context.textBaseline = 'middle'; + context.textAlign = itemToDraw.textAlign; + + var label = itemToDraw.label; + var y = itemToDraw.textOffset; + if (helpers$1.isArray(label)) { + for (var i = 0; i < label.length; ++i) { + // We just make sure the multiline element is a string here.. + context.fillText('' + label[i], 0, y); + y += lineHeight; + } + } else { + context.fillText(label, 0, y); + } + context.restore(); + } + }); + + if (scaleLabel.display) { + // Draw the scale label + var scaleLabelX; + var scaleLabelY; + var rotation = 0; + var halfLineHeight = scaleLabelFont.lineHeight / 2; + + if (isHorizontal) { + scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width + scaleLabelY = position === 'bottom' + ? me.bottom - halfLineHeight - scaleLabelPadding.bottom + : me.top + halfLineHeight + scaleLabelPadding.top; + } else { + var isLeft = position === 'left'; + scaleLabelX = isLeft + ? me.left + halfLineHeight + scaleLabelPadding.top + : me.right - halfLineHeight - scaleLabelPadding.top; + scaleLabelY = me.top + ((me.bottom - me.top) / 2); + rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI; + } + + context.save(); + context.translate(scaleLabelX, scaleLabelY); + context.rotate(rotation); + context.textAlign = 'center'; + context.textBaseline = 'middle'; + context.fillStyle = scaleLabelFontColor; // render in correct colour + context.font = scaleLabelFont.string; + context.fillText(scaleLabel.labelString, 0, 0); + context.restore(); + } + + if (axisWidth) { + // Draw the line at the edge of the axis + var firstLineWidth = axisWidth; + var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, ticks.length - 1, 0); + var x1, x2, y1, y2; + + if (isHorizontal) { + x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2; + x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2; + y1 = y2 = borderValue; + } else { + y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2; + y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2; + x1 = x2 = borderValue; + } + + context.lineWidth = axisWidth; + context.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0); + context.beginPath(); + context.moveTo(x1, y1); + context.lineTo(x2, y2); + context.stroke(); + } + } +}); + +var defaultConfig = { + position: 'bottom' +}; + +var scale_category = core_scale.extend({ + /** + * Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those + * else fall back to data.labels + * @private + */ + getLabels: function() { + var data = this.chart.data; + return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels; + }, + + determineDataLimits: function() { + var me = this; + var labels = me.getLabels(); + me.minIndex = 0; + me.maxIndex = labels.length - 1; + var findIndex; + + if (me.options.ticks.min !== undefined) { + // user specified min value + findIndex = labels.indexOf(me.options.ticks.min); + me.minIndex = findIndex !== -1 ? findIndex : me.minIndex; + } + + if (me.options.ticks.max !== undefined) { + // user specified max value + findIndex = labels.indexOf(me.options.ticks.max); + me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex; + } + + me.min = labels[me.minIndex]; + me.max = labels[me.maxIndex]; + }, + + buildTicks: function() { + var me = this; + var labels = me.getLabels(); + // If we are viewing some subset of labels, slice the original array + me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1); + }, + + getLabelForIndex: function(index, datasetIndex) { + var me = this; + var chart = me.chart; + + if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) { + return me.getRightValue(chart.data.datasets[datasetIndex].data[index]); + } + + return me.ticks[index - me.minIndex]; + }, + + // Used to get data value locations. Value can either be an index or a numerical value + getPixelForValue: function(value, index) { + var me = this; + var offset = me.options.offset; + // 1 is added because we need the length but we have the indexes + var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - (offset ? 0 : 1)), 1); + + // If value is a data object, then index is the index in the data array, + // not the index of the scale. We need to change that. + var valueCategory; + if (value !== undefined && value !== null) { + valueCategory = me.isHorizontal() ? value.x : value.y; + } + if (valueCategory !== undefined || (value !== undefined && isNaN(index))) { + var labels = me.getLabels(); + value = valueCategory || value; + var idx = labels.indexOf(value); + index = idx !== -1 ? idx : index; + } + + if (me.isHorizontal()) { + var valueWidth = me.width / offsetAmt; + var widthOffset = (valueWidth * (index - me.minIndex)); + + if (offset) { + widthOffset += (valueWidth / 2); + } + + return me.left + widthOffset; + } + var valueHeight = me.height / offsetAmt; + var heightOffset = (valueHeight * (index - me.minIndex)); + + if (offset) { + heightOffset += (valueHeight / 2); + } + + return me.top + heightOffset; + }, + + getPixelForTick: function(index) { + return this.getPixelForValue(this.ticks[index], index + this.minIndex, null); + }, + + getValueForPixel: function(pixel) { + var me = this; + var offset = me.options.offset; + var value; + var offsetAmt = Math.max((me._ticks.length - (offset ? 0 : 1)), 1); + var horz = me.isHorizontal(); + var valueDimension = (horz ? me.width : me.height) / offsetAmt; + + pixel -= horz ? me.left : me.top; + + if (offset) { + pixel -= (valueDimension / 2); + } + + if (pixel <= 0) { + value = 0; + } else { + value = Math.round(pixel / valueDimension); + } + + return value + me.minIndex; + }, + + getBasePixel: function() { + return this.bottom; + } +}); + +// INTERNAL: static default options, registered in src/index.js +var _defaults = defaultConfig; +scale_category._defaults = _defaults; + +var noop = helpers$1.noop; +var isNullOrUndef = helpers$1.isNullOrUndef; + +/** + * Generate a set of linear ticks + * @param generationOptions the options used to generate the ticks + * @param dataRange the range of the data + * @returns {number[]} array of tick values + */ +function generateTicks(generationOptions, dataRange) { + var ticks = []; + // To get a "nice" value for the tick spacing, we will use the appropriately named + // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks + // for details. + + var MIN_SPACING = 1e-14; + var stepSize = generationOptions.stepSize; + var unit = stepSize || 1; + var maxNumSpaces = generationOptions.maxTicks - 1; + var min = generationOptions.min; + var max = generationOptions.max; + var precision = generationOptions.precision; + var rmin = dataRange.min; + var rmax = dataRange.max; + var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit; + var factor, niceMin, niceMax, numSpaces; + + // Beyond MIN_SPACING floating point numbers being to lose precision + // such that we can't do the math necessary to generate ticks + if (spacing < MIN_SPACING && isNullOrUndef(min) && isNullOrUndef(max)) { + return [rmin, rmax]; + } + + numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing); + if (numSpaces > maxNumSpaces) { + // If the calculated num of spaces exceeds maxNumSpaces, recalculate it + spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit; + } + + if (stepSize || isNullOrUndef(precision)) { + // If a precision is not specified, calculate factor based on spacing + factor = Math.pow(10, helpers$1._decimalPlaces(spacing)); + } else { + // If the user specified a precision, round to that number of decimal places + factor = Math.pow(10, precision); + spacing = Math.ceil(spacing * factor) / factor; + } + + niceMin = Math.floor(rmin / spacing) * spacing; + niceMax = Math.ceil(rmax / spacing) * spacing; + + // If min, max and stepSize is set and they make an evenly spaced scale use it. + if (stepSize) { + // If very close to our whole number, use it. + if (!isNullOrUndef(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) { + niceMin = min; + } + if (!isNullOrUndef(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) { + niceMax = max; + } + } + + numSpaces = (niceMax - niceMin) / spacing; + // If very close to our rounded value, use it. + if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { + numSpaces = Math.round(numSpaces); + } else { + numSpaces = Math.ceil(numSpaces); + } + + niceMin = Math.round(niceMin * factor) / factor; + niceMax = Math.round(niceMax * factor) / factor; + ticks.push(isNullOrUndef(min) ? niceMin : min); + for (var j = 1; j < numSpaces; ++j) { + ticks.push(Math.round((niceMin + j * spacing) * factor) / factor); + } + ticks.push(isNullOrUndef(max) ? niceMax : max); + + return ticks; +} + +var scale_linearbase = core_scale.extend({ + getRightValue: function(value) { + if (typeof value === 'string') { + return +value; + } + return core_scale.prototype.getRightValue.call(this, value); + }, + + handleTickRangeOptions: function() { + var me = this; + var opts = me.options; + var tickOpts = opts.ticks; + + // If we are forcing it to begin at 0, but 0 will already be rendered on the chart, + // do nothing since that would make the chart weird. If the user really wants a weird chart + // axis, they can manually override it + if (tickOpts.beginAtZero) { + var minSign = helpers$1.sign(me.min); + var maxSign = helpers$1.sign(me.max); + + if (minSign < 0 && maxSign < 0) { + // move the top up to 0 + me.max = 0; + } else if (minSign > 0 && maxSign > 0) { + // move the bottom down to 0 + me.min = 0; + } + } + + var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined; + var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined; + + if (tickOpts.min !== undefined) { + me.min = tickOpts.min; + } else if (tickOpts.suggestedMin !== undefined) { + if (me.min === null) { + me.min = tickOpts.suggestedMin; + } else { + me.min = Math.min(me.min, tickOpts.suggestedMin); + } + } + + if (tickOpts.max !== undefined) { + me.max = tickOpts.max; + } else if (tickOpts.suggestedMax !== undefined) { + if (me.max === null) { + me.max = tickOpts.suggestedMax; + } else { + me.max = Math.max(me.max, tickOpts.suggestedMax); + } + } + + if (setMin !== setMax) { + // We set the min or the max but not both. + // So ensure that our range is good + // Inverted or 0 length range can happen when + // ticks.min is set, and no datasets are visible + if (me.min >= me.max) { + if (setMin) { + me.max = me.min + 1; + } else { + me.min = me.max - 1; + } + } + } + + if (me.min === me.max) { + me.max++; + + if (!tickOpts.beginAtZero) { + me.min--; + } + } + }, + + getTickLimit: function() { + var me = this; + var tickOpts = me.options.ticks; + var stepSize = tickOpts.stepSize; + var maxTicksLimit = tickOpts.maxTicksLimit; + var maxTicks; + + if (stepSize) { + maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1; + } else { + maxTicks = me._computeTickLimit(); + maxTicksLimit = maxTicksLimit || 11; + } + + if (maxTicksLimit) { + maxTicks = Math.min(maxTicksLimit, maxTicks); + } + + return maxTicks; + }, + + _computeTickLimit: function() { + return Number.POSITIVE_INFINITY; + }, + + handleDirectionalChanges: noop, + + buildTicks: function() { + var me = this; + var opts = me.options; + var tickOpts = opts.ticks; + + // Figure out what the max number of ticks we can support it is based on the size of + // the axis area. For now, we say that the minimum tick spacing in pixels must be 40 + // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on + // the graph. Make sure we always have at least 2 ticks + var maxTicks = me.getTickLimit(); + maxTicks = Math.max(2, maxTicks); + + var numericGeneratorOptions = { + maxTicks: maxTicks, + min: tickOpts.min, + max: tickOpts.max, + precision: tickOpts.precision, + stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize) + }; + var ticks = me.ticks = generateTicks(numericGeneratorOptions, me); + + me.handleDirectionalChanges(); + + // At this point, we need to update our max and min given the tick values since we have expanded the + // range of the scale + me.max = helpers$1.max(ticks); + me.min = helpers$1.min(ticks); + + if (tickOpts.reverse) { + ticks.reverse(); + + me.start = me.max; + me.end = me.min; + } else { + me.start = me.min; + me.end = me.max; + } + }, + + convertTicksToLabels: function() { + var me = this; + me.ticksAsNumbers = me.ticks.slice(); + me.zeroLineIndex = me.ticks.indexOf(0); + + core_scale.prototype.convertTicksToLabels.call(me); + } +}); + +var defaultConfig$1 = { + position: 'left', + ticks: { + callback: core_ticks.formatters.linear + } +}; + +var scale_linear = scale_linearbase.extend({ + determineDataLimits: function() { + var me = this; + var opts = me.options; + var chart = me.chart; + var data = chart.data; + var datasets = data.datasets; + var isHorizontal = me.isHorizontal(); + var DEFAULT_MIN = 0; + var DEFAULT_MAX = 1; + + function IDMatches(meta) { + return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id; + } + + // First Calculate the range + me.min = null; + me.max = null; + + var hasStacks = opts.stacked; + if (hasStacks === undefined) { + helpers$1.each(datasets, function(dataset, datasetIndex) { + if (hasStacks) { + return; + } + + var meta = chart.getDatasetMeta(datasetIndex); + if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) && + meta.stack !== undefined) { + hasStacks = true; + } + }); + } + + if (opts.stacked || hasStacks) { + var valuesPerStack = {}; + + helpers$1.each(datasets, function(dataset, datasetIndex) { + var meta = chart.getDatasetMeta(datasetIndex); + var key = [ + meta.type, + // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined + ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''), + meta.stack + ].join('.'); + + if (valuesPerStack[key] === undefined) { + valuesPerStack[key] = { + positiveValues: [], + negativeValues: [] + }; + } + + // Store these per type + var positiveValues = valuesPerStack[key].positiveValues; + var negativeValues = valuesPerStack[key].negativeValues; + + if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { + helpers$1.each(dataset.data, function(rawValue, index) { + var value = +me.getRightValue(rawValue); + if (isNaN(value) || meta.data[index].hidden) { + return; + } + + positiveValues[index] = positiveValues[index] || 0; + negativeValues[index] = negativeValues[index] || 0; + + if (opts.relativePoints) { + positiveValues[index] = 100; + } else if (value < 0) { + negativeValues[index] += value; + } else { + positiveValues[index] += value; + } + }); + } + }); + + helpers$1.each(valuesPerStack, function(valuesForType) { + var values = valuesForType.positiveValues.concat(valuesForType.negativeValues); + var minVal = helpers$1.min(values); + var maxVal = helpers$1.max(values); + me.min = me.min === null ? minVal : Math.min(me.min, minVal); + me.max = me.max === null ? maxVal : Math.max(me.max, maxVal); + }); + + } else { + helpers$1.each(datasets, function(dataset, datasetIndex) { + var meta = chart.getDatasetMeta(datasetIndex); + if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { + helpers$1.each(dataset.data, function(rawValue, index) { + var value = +me.getRightValue(rawValue); + if (isNaN(value) || meta.data[index].hidden) { + return; + } + + if (me.min === null) { + me.min = value; + } else if (value < me.min) { + me.min = value; + } + + if (me.max === null) { + me.max = value; + } else if (value > me.max) { + me.max = value; + } + }); + } + }); + } + + me.min = isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN; + me.max = isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX; + + // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero + this.handleTickRangeOptions(); + }, + + // Returns the maximum number of ticks based on the scale dimension + _computeTickLimit: function() { + var me = this; + var tickFont; + + if (me.isHorizontal()) { + return Math.ceil(me.width / 40); + } + tickFont = helpers$1.options._parseFont(me.options.ticks); + return Math.ceil(me.height / tickFont.lineHeight); + }, + + // Called after the ticks are built. We need + handleDirectionalChanges: function() { + if (!this.isHorizontal()) { + // We are in a vertical orientation. The top value is the highest. So reverse the array + this.ticks.reverse(); + } + }, + + getLabelForIndex: function(index, datasetIndex) { + return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]); + }, + + // Utils + getPixelForValue: function(value) { + // This must be called after fit has been run so that + // this.left, this.top, this.right, and this.bottom have been defined + var me = this; + var start = me.start; + + var rightValue = +me.getRightValue(value); + var pixel; + var range = me.end - start; + + if (me.isHorizontal()) { + pixel = me.left + (me.width / range * (rightValue - start)); + } else { + pixel = me.bottom - (me.height / range * (rightValue - start)); + } + return pixel; + }, + + getValueForPixel: function(pixel) { + var me = this; + var isHorizontal = me.isHorizontal(); + var innerDimension = isHorizontal ? me.width : me.height; + var offset = (isHorizontal ? pixel - me.left : me.bottom - pixel) / innerDimension; + return me.start + ((me.end - me.start) * offset); + }, + + getPixelForTick: function(index) { + return this.getPixelForValue(this.ticksAsNumbers[index]); + } +}); + +// INTERNAL: static default options, registered in src/index.js +var _defaults$1 = defaultConfig$1; +scale_linear._defaults = _defaults$1; + +var valueOrDefault$a = helpers$1.valueOrDefault; + +/** + * Generate a set of logarithmic ticks + * @param generationOptions the options used to generate the ticks + * @param dataRange the range of the data + * @returns {number[]} array of tick values + */ +function generateTicks$1(generationOptions, dataRange) { + var ticks = []; + + var tickVal = valueOrDefault$a(generationOptions.min, Math.pow(10, Math.floor(helpers$1.log10(dataRange.min)))); + + var endExp = Math.floor(helpers$1.log10(dataRange.max)); + var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp)); + var exp, significand; + + if (tickVal === 0) { + exp = Math.floor(helpers$1.log10(dataRange.minNotZero)); + significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp)); + + ticks.push(tickVal); + tickVal = significand * Math.pow(10, exp); + } else { + exp = Math.floor(helpers$1.log10(tickVal)); + significand = Math.floor(tickVal / Math.pow(10, exp)); + } + var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1; + + do { + ticks.push(tickVal); + + ++significand; + if (significand === 10) { + significand = 1; + ++exp; + precision = exp >= 0 ? 1 : precision; + } + + tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision; + } while (exp < endExp || (exp === endExp && significand < endSignificand)); + + var lastTick = valueOrDefault$a(generationOptions.max, tickVal); + ticks.push(lastTick); + + return ticks; +} + +var defaultConfig$2 = { + position: 'left', + + // label settings + ticks: { + callback: core_ticks.formatters.logarithmic + } +}; + +// TODO(v3): change this to positiveOrDefault +function nonNegativeOrDefault(value, defaultValue) { + return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue; +} + +var scale_logarithmic = core_scale.extend({ + determineDataLimits: function() { + var me = this; + var opts = me.options; + var chart = me.chart; + var data = chart.data; + var datasets = data.datasets; + var isHorizontal = me.isHorizontal(); + function IDMatches(meta) { + return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id; + } + + // Calculate Range + me.min = null; + me.max = null; + me.minNotZero = null; + + var hasStacks = opts.stacked; + if (hasStacks === undefined) { + helpers$1.each(datasets, function(dataset, datasetIndex) { + if (hasStacks) { + return; + } + + var meta = chart.getDatasetMeta(datasetIndex); + if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) && + meta.stack !== undefined) { + hasStacks = true; + } + }); + } + + if (opts.stacked || hasStacks) { + var valuesPerStack = {}; + + helpers$1.each(datasets, function(dataset, datasetIndex) { + var meta = chart.getDatasetMeta(datasetIndex); + var key = [ + meta.type, + // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined + ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''), + meta.stack + ].join('.'); + + if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { + if (valuesPerStack[key] === undefined) { + valuesPerStack[key] = []; + } + + helpers$1.each(dataset.data, function(rawValue, index) { + var values = valuesPerStack[key]; + var value = +me.getRightValue(rawValue); + // invalid, hidden and negative values are ignored + if (isNaN(value) || meta.data[index].hidden || value < 0) { + return; + } + values[index] = values[index] || 0; + values[index] += value; + }); + } + }); + + helpers$1.each(valuesPerStack, function(valuesForType) { + if (valuesForType.length > 0) { + var minVal = helpers$1.min(valuesForType); + var maxVal = helpers$1.max(valuesForType); + me.min = me.min === null ? minVal : Math.min(me.min, minVal); + me.max = me.max === null ? maxVal : Math.max(me.max, maxVal); + } + }); + + } else { + helpers$1.each(datasets, function(dataset, datasetIndex) { + var meta = chart.getDatasetMeta(datasetIndex); + if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { + helpers$1.each(dataset.data, function(rawValue, index) { + var value = +me.getRightValue(rawValue); + // invalid, hidden and negative values are ignored + if (isNaN(value) || meta.data[index].hidden || value < 0) { + return; + } + + if (me.min === null) { + me.min = value; + } else if (value < me.min) { + me.min = value; + } + + if (me.max === null) { + me.max = value; + } else if (value > me.max) { + me.max = value; + } + + if (value !== 0 && (me.minNotZero === null || value < me.minNotZero)) { + me.minNotZero = value; + } + }); + } + }); + } + + // Common base implementation to handle ticks.min, ticks.max + this.handleTickRangeOptions(); + }, + + handleTickRangeOptions: function() { + var me = this; + var tickOpts = me.options.ticks; + var DEFAULT_MIN = 1; + var DEFAULT_MAX = 10; + + me.min = nonNegativeOrDefault(tickOpts.min, me.min); + me.max = nonNegativeOrDefault(tickOpts.max, me.max); + + if (me.min === me.max) { + if (me.min !== 0 && me.min !== null) { + me.min = Math.pow(10, Math.floor(helpers$1.log10(me.min)) - 1); + me.max = Math.pow(10, Math.floor(helpers$1.log10(me.max)) + 1); + } else { + me.min = DEFAULT_MIN; + me.max = DEFAULT_MAX; + } + } + if (me.min === null) { + me.min = Math.pow(10, Math.floor(helpers$1.log10(me.max)) - 1); + } + if (me.max === null) { + me.max = me.min !== 0 + ? Math.pow(10, Math.floor(helpers$1.log10(me.min)) + 1) + : DEFAULT_MAX; + } + if (me.minNotZero === null) { + if (me.min > 0) { + me.minNotZero = me.min; + } else if (me.max < 1) { + me.minNotZero = Math.pow(10, Math.floor(helpers$1.log10(me.max))); + } else { + me.minNotZero = DEFAULT_MIN; + } + } + }, + + buildTicks: function() { + var me = this; + var tickOpts = me.options.ticks; + var reverse = !me.isHorizontal(); + + var generationOptions = { + min: nonNegativeOrDefault(tickOpts.min), + max: nonNegativeOrDefault(tickOpts.max) + }; + var ticks = me.ticks = generateTicks$1(generationOptions, me); + + // At this point, we need to update our max and min given the tick values since we have expanded the + // range of the scale + me.max = helpers$1.max(ticks); + me.min = helpers$1.min(ticks); + + if (tickOpts.reverse) { + reverse = !reverse; + me.start = me.max; + me.end = me.min; + } else { + me.start = me.min; + me.end = me.max; + } + if (reverse) { + ticks.reverse(); + } + }, + + convertTicksToLabels: function() { + this.tickValues = this.ticks.slice(); + + core_scale.prototype.convertTicksToLabels.call(this); + }, + + // Get the correct tooltip label + getLabelForIndex: function(index, datasetIndex) { + return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]); + }, + + getPixelForTick: function(index) { + return this.getPixelForValue(this.tickValues[index]); + }, + + /** + * Returns the value of the first tick. + * @param {number} value - The minimum not zero value. + * @return {number} The first tick value. + * @private + */ + _getFirstTickValue: function(value) { + var exp = Math.floor(helpers$1.log10(value)); + var significand = Math.floor(value / Math.pow(10, exp)); + + return significand * Math.pow(10, exp); + }, + + getPixelForValue: function(value) { + var me = this; + var tickOpts = me.options.ticks; + var reverse = tickOpts.reverse; + var log10 = helpers$1.log10; + var firstTickValue = me._getFirstTickValue(me.minNotZero); + var offset = 0; + var innerDimension, pixel, start, end, sign; + + value = +me.getRightValue(value); + if (reverse) { + start = me.end; + end = me.start; + sign = -1; + } else { + start = me.start; + end = me.end; + sign = 1; + } + if (me.isHorizontal()) { + innerDimension = me.width; + pixel = reverse ? me.right : me.left; + } else { + innerDimension = me.height; + sign *= -1; // invert, since the upper-left corner of the canvas is at pixel (0, 0) + pixel = reverse ? me.top : me.bottom; + } + if (value !== start) { + if (start === 0) { // include zero tick + offset = valueOrDefault$a(tickOpts.fontSize, core_defaults.global.defaultFontSize); + innerDimension -= offset; + start = firstTickValue; + } + if (value !== 0) { + offset += innerDimension / (log10(end) - log10(start)) * (log10(value) - log10(start)); + } + pixel += sign * offset; + } + return pixel; + }, + + getValueForPixel: function(pixel) { + var me = this; + var tickOpts = me.options.ticks; + var reverse = tickOpts.reverse; + var log10 = helpers$1.log10; + var firstTickValue = me._getFirstTickValue(me.minNotZero); + var innerDimension, start, end, value; + + if (reverse) { + start = me.end; + end = me.start; + } else { + start = me.start; + end = me.end; + } + if (me.isHorizontal()) { + innerDimension = me.width; + value = reverse ? me.right - pixel : pixel - me.left; + } else { + innerDimension = me.height; + value = reverse ? pixel - me.top : me.bottom - pixel; + } + if (value !== start) { + if (start === 0) { // include zero tick + var offset = valueOrDefault$a(tickOpts.fontSize, core_defaults.global.defaultFontSize); + value -= offset; + innerDimension -= offset; + start = firstTickValue; + } + value *= log10(end) - log10(start); + value /= innerDimension; + value = Math.pow(10, log10(start) + value); + } + return value; + } +}); + +// INTERNAL: static default options, registered in src/index.js +var _defaults$2 = defaultConfig$2; +scale_logarithmic._defaults = _defaults$2; + +var valueOrDefault$b = helpers$1.valueOrDefault; +var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault; +var resolve$7 = helpers$1.options.resolve; + +var defaultConfig$3 = { + display: true, + + // Boolean - Whether to animate scaling the chart from the centre + animate: true, + position: 'chartArea', + + angleLines: { + display: true, + color: 'rgba(0, 0, 0, 0.1)', + lineWidth: 1, + borderDash: [], + borderDashOffset: 0.0 + }, + + gridLines: { + circular: false + }, + + // label settings + ticks: { + // Boolean - Show a backdrop to the scale label + showLabelBackdrop: true, + + // String - The colour of the label backdrop + backdropColor: 'rgba(255,255,255,0.75)', + + // Number - The backdrop padding above & below the label in pixels + backdropPaddingY: 2, + + // Number - The backdrop padding to the side of the label in pixels + backdropPaddingX: 2, + + callback: core_ticks.formatters.linear + }, + + pointLabels: { + // Boolean - if true, show point labels + display: true, + + // Number - Point label font size in pixels + fontSize: 10, + + // Function - Used to convert point labels + callback: function(label) { + return label; + } + } +}; + +function getValueCount(scale) { + var opts = scale.options; + return opts.angleLines.display || opts.pointLabels.display ? scale.chart.data.labels.length : 0; +} + +function getTickBackdropHeight(opts) { + var tickOpts = opts.ticks; + + if (tickOpts.display && opts.display) { + return valueOrDefault$b(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2; + } + return 0; +} + +function measureLabelSize(ctx, lineHeight, label) { + if (helpers$1.isArray(label)) { + return { + w: helpers$1.longestText(ctx, ctx.font, label), + h: label.length * lineHeight + }; + } + + return { + w: ctx.measureText(label).width, + h: lineHeight + }; +} + +function determineLimits(angle, pos, size, min, max) { + if (angle === min || angle === max) { + return { + start: pos - (size / 2), + end: pos + (size / 2) + }; + } else if (angle < min || angle > max) { + return { + start: pos - size, + end: pos + }; + } + + return { + start: pos, + end: pos + size + }; +} + +/** + * Helper function to fit a radial linear scale with point labels + */ +function fitWithPointLabels(scale) { + + // Right, this is really confusing and there is a lot of maths going on here + // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9 + // + // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif + // + // Solution: + // + // We assume the radius of the polygon is half the size of the canvas at first + // at each index we check if the text overlaps. + // + // Where it does, we store that angle and that index. + // + // After finding the largest index and angle we calculate how much we need to remove + // from the shape radius to move the point inwards by that x. + // + // We average the left and right distances to get the maximum shape radius that can fit in the box + // along with labels. + // + // Once we have that, we can find the centre point for the chart, by taking the x text protrusion + // on each side, removing that from the size, halving it and adding the left x protrusion width. + // + // This will mean we have a shape fitted to the canvas, as large as it can be with the labels + // and position it in the most space efficient manner + // + // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif + + var plFont = helpers$1.options._parseFont(scale.options.pointLabels); + + // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width. + // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points + var furthestLimits = { + l: 0, + r: scale.width, + t: 0, + b: scale.height - scale.paddingTop + }; + var furthestAngles = {}; + var i, textSize, pointPosition; + + scale.ctx.font = plFont.string; + scale._pointLabelSizes = []; + + var valueCount = getValueCount(scale); + for (i = 0; i < valueCount; i++) { + pointPosition = scale.getPointPosition(i, scale.drawingArea + 5); + textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i] || ''); + scale._pointLabelSizes[i] = textSize; + + // Add quarter circle to make degree 0 mean top of circle + var angleRadians = scale.getIndexAngle(i); + var angle = helpers$1.toDegrees(angleRadians) % 360; + var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180); + var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270); + + if (hLimits.start < furthestLimits.l) { + furthestLimits.l = hLimits.start; + furthestAngles.l = angleRadians; + } + + if (hLimits.end > furthestLimits.r) { + furthestLimits.r = hLimits.end; + furthestAngles.r = angleRadians; + } + + if (vLimits.start < furthestLimits.t) { + furthestLimits.t = vLimits.start; + furthestAngles.t = angleRadians; + } + + if (vLimits.end > furthestLimits.b) { + furthestLimits.b = vLimits.end; + furthestAngles.b = angleRadians; + } + } + + scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles); +} + +function getTextAlignForAngle(angle) { + if (angle === 0 || angle === 180) { + return 'center'; + } else if (angle < 180) { + return 'left'; + } + + return 'right'; +} + +function fillText(ctx, text, position, lineHeight) { + var y = position.y + lineHeight / 2; + var i, ilen; + + if (helpers$1.isArray(text)) { + for (i = 0, ilen = text.length; i < ilen; ++i) { + ctx.fillText(text[i], position.x, y); + y += lineHeight; + } + } else { + ctx.fillText(text, position.x, y); + } +} + +function adjustPointPositionForLabelHeight(angle, textSize, position) { + if (angle === 90 || angle === 270) { + position.y -= (textSize.h / 2); + } else if (angle > 270 || angle < 90) { + position.y -= textSize.h; + } +} + +function drawPointLabels(scale) { + var ctx = scale.ctx; + var opts = scale.options; + var angleLineOpts = opts.angleLines; + var gridLineOpts = opts.gridLines; + var pointLabelOpts = opts.pointLabels; + var lineWidth = valueOrDefault$b(angleLineOpts.lineWidth, gridLineOpts.lineWidth); + var lineColor = valueOrDefault$b(angleLineOpts.color, gridLineOpts.color); + var tickBackdropHeight = getTickBackdropHeight(opts); + + ctx.save(); + ctx.lineWidth = lineWidth; + ctx.strokeStyle = lineColor; + if (ctx.setLineDash) { + ctx.setLineDash(resolve$7([angleLineOpts.borderDash, gridLineOpts.borderDash, []])); + ctx.lineDashOffset = resolve$7([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]); + } + + var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max); + + // Point Label Font + var plFont = helpers$1.options._parseFont(pointLabelOpts); + + ctx.font = plFont.string; + ctx.textBaseline = 'middle'; + + for (var i = getValueCount(scale) - 1; i >= 0; i--) { + if (angleLineOpts.display && lineWidth && lineColor) { + var outerPosition = scale.getPointPosition(i, outerDistance); + ctx.beginPath(); + ctx.moveTo(scale.xCenter, scale.yCenter); + ctx.lineTo(outerPosition.x, outerPosition.y); + ctx.stroke(); + } + + if (pointLabelOpts.display) { + // Extra pixels out for some label spacing + var extra = (i === 0 ? tickBackdropHeight / 2 : 0); + var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5); + + // Keep this in loop since we may support array properties here + var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor); + ctx.fillStyle = pointLabelFontColor; + + var angleRadians = scale.getIndexAngle(i); + var angle = helpers$1.toDegrees(angleRadians); + ctx.textAlign = getTextAlignForAngle(angle); + adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition); + fillText(ctx, scale.pointLabels[i] || '', pointLabelPosition, plFont.lineHeight); + } + } + ctx.restore(); +} + +function drawRadiusLine(scale, gridLineOpts, radius, index) { + var ctx = scale.ctx; + var circular = gridLineOpts.circular; + var valueCount = getValueCount(scale); + var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1); + var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1); + var pointPosition; + + if ((!circular && !valueCount) || !lineColor || !lineWidth) { + return; + } + + ctx.save(); + ctx.strokeStyle = lineColor; + ctx.lineWidth = lineWidth; + if (ctx.setLineDash) { + ctx.setLineDash(gridLineOpts.borderDash || []); + ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0; + } + + ctx.beginPath(); + if (circular) { + // Draw circular arcs between the points + ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2); + } else { + // Draw straight lines connecting each index + pointPosition = scale.getPointPosition(0, radius); + ctx.moveTo(pointPosition.x, pointPosition.y); + + for (var i = 1; i < valueCount; i++) { + pointPosition = scale.getPointPosition(i, radius); + ctx.lineTo(pointPosition.x, pointPosition.y); + } + } + ctx.closePath(); + ctx.stroke(); + ctx.restore(); +} + +function numberOrZero(param) { + return helpers$1.isNumber(param) ? param : 0; +} + +var scale_radialLinear = scale_linearbase.extend({ + setDimensions: function() { + var me = this; + + // Set the unconstrained dimension before label rotation + me.width = me.maxWidth; + me.height = me.maxHeight; + me.paddingTop = getTickBackdropHeight(me.options) / 2; + me.xCenter = Math.floor(me.width / 2); + me.yCenter = Math.floor((me.height - me.paddingTop) / 2); + me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2; + }, + + determineDataLimits: function() { + var me = this; + var chart = me.chart; + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + + helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) { + if (chart.isDatasetVisible(datasetIndex)) { + var meta = chart.getDatasetMeta(datasetIndex); + + helpers$1.each(dataset.data, function(rawValue, index) { + var value = +me.getRightValue(rawValue); + if (isNaN(value) || meta.data[index].hidden) { + return; + } + + min = Math.min(value, min); + max = Math.max(value, max); + }); + } + }); + + me.min = (min === Number.POSITIVE_INFINITY ? 0 : min); + me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max); + + // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero + me.handleTickRangeOptions(); + }, + + // Returns the maximum number of ticks based on the scale dimension + _computeTickLimit: function() { + return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options)); + }, + + convertTicksToLabels: function() { + var me = this; + + scale_linearbase.prototype.convertTicksToLabels.call(me); + + // Point labels + me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me); + }, + + getLabelForIndex: function(index, datasetIndex) { + return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]); + }, + + fit: function() { + var me = this; + var opts = me.options; + + if (opts.display && opts.pointLabels.display) { + fitWithPointLabels(me); + } else { + me.setCenterPoint(0, 0, 0, 0); + } + }, + + /** + * Set radius reductions and determine new radius and center point + * @private + */ + setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) { + var me = this; + var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l); + var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r); + var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t); + var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b); + + radiusReductionLeft = numberOrZero(radiusReductionLeft); + radiusReductionRight = numberOrZero(radiusReductionRight); + radiusReductionTop = numberOrZero(radiusReductionTop); + radiusReductionBottom = numberOrZero(radiusReductionBottom); + + me.drawingArea = Math.min( + Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2), + Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2)); + me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom); + }, + + setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) { + var me = this; + var maxRight = me.width - rightMovement - me.drawingArea; + var maxLeft = leftMovement + me.drawingArea; + var maxTop = topMovement + me.drawingArea; + var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea; + + me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left); + me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop); + }, + + getIndexAngle: function(index) { + var angleMultiplier = (Math.PI * 2) / getValueCount(this); + var startAngle = this.chart.options && this.chart.options.startAngle ? + this.chart.options.startAngle : + 0; + + var startAngleRadians = startAngle * Math.PI * 2 / 360; + + // Start from the top instead of right, so remove a quarter of the circle + return index * angleMultiplier + startAngleRadians; + }, + + getDistanceFromCenterForValue: function(value) { + var me = this; + + if (value === null) { + return 0; // null always in center + } + + // Take into account half font size + the yPadding of the top value + var scalingFactor = me.drawingArea / (me.max - me.min); + if (me.options.ticks.reverse) { + return (me.max - value) * scalingFactor; + } + return (value - me.min) * scalingFactor; + }, + + getPointPosition: function(index, distanceFromCenter) { + var me = this; + var thisAngle = me.getIndexAngle(index) - (Math.PI / 2); + return { + x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter, + y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter + }; + }, + + getPointPositionForValue: function(index, value) { + return this.getPointPosition(index, this.getDistanceFromCenterForValue(value)); + }, + + getBasePosition: function() { + var me = this; + var min = me.min; + var max = me.max; + + return me.getPointPositionForValue(0, + me.beginAtZero ? 0 : + min < 0 && max < 0 ? max : + min > 0 && max > 0 ? min : + 0); + }, + + draw: function() { + var me = this; + var opts = me.options; + var gridLineOpts = opts.gridLines; + var tickOpts = opts.ticks; + + if (opts.display) { + var ctx = me.ctx; + var startAngle = this.getIndexAngle(0); + var tickFont = helpers$1.options._parseFont(tickOpts); + + if (opts.angleLines.display || opts.pointLabels.display) { + drawPointLabels(me); + } + + helpers$1.each(me.ticks, function(label, index) { + // Don't draw a centre value (if it is minimum) + if (index > 0 || tickOpts.reverse) { + var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]); + + // Draw circular lines around the scale + if (gridLineOpts.display && index !== 0) { + drawRadiusLine(me, gridLineOpts, yCenterOffset, index); + } + + if (tickOpts.display) { + var tickFontColor = valueOrDefault$b(tickOpts.fontColor, core_defaults.global.defaultFontColor); + ctx.font = tickFont.string; + + ctx.save(); + ctx.translate(me.xCenter, me.yCenter); + ctx.rotate(startAngle); + + if (tickOpts.showLabelBackdrop) { + var labelWidth = ctx.measureText(label).width; + ctx.fillStyle = tickOpts.backdropColor; + ctx.fillRect( + -labelWidth / 2 - tickOpts.backdropPaddingX, + -yCenterOffset - tickFont.size / 2 - tickOpts.backdropPaddingY, + labelWidth + tickOpts.backdropPaddingX * 2, + tickFont.size + tickOpts.backdropPaddingY * 2 + ); + } + + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = tickFontColor; + ctx.fillText(label, 0, -yCenterOffset); + ctx.restore(); + } + } + }); + } + } +}); + +// INTERNAL: static default options, registered in src/index.js +var _defaults$3 = defaultConfig$3; +scale_radialLinear._defaults = _defaults$3; + +var valueOrDefault$c = helpers$1.valueOrDefault; + +// Integer constants are from the ES6 spec. +var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991; +var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + +var INTERVALS = { + millisecond: { + common: true, + size: 1, + steps: [1, 2, 5, 10, 20, 50, 100, 250, 500] + }, + second: { + common: true, + size: 1000, + steps: [1, 2, 5, 10, 15, 30] + }, + minute: { + common: true, + size: 60000, + steps: [1, 2, 5, 10, 15, 30] + }, + hour: { + common: true, + size: 3600000, + steps: [1, 2, 3, 6, 12] + }, + day: { + common: true, + size: 86400000, + steps: [1, 2, 5] + }, + week: { + common: false, + size: 604800000, + steps: [1, 2, 3, 4] + }, + month: { + common: true, + size: 2.628e9, + steps: [1, 2, 3] + }, + quarter: { + common: false, + size: 7.884e9, + steps: [1, 2, 3, 4] + }, + year: { + common: true, + size: 3.154e10 + } +}; + +var UNITS = Object.keys(INTERVALS); + +function sorter(a, b) { + return a - b; +} + +function arrayUnique(items) { + var hash = {}; + var out = []; + var i, ilen, item; + + for (i = 0, ilen = items.length; i < ilen; ++i) { + item = items[i]; + if (!hash[item]) { + hash[item] = true; + out.push(item); + } + } + + return out; +} + +/** + * Returns an array of {time, pos} objects used to interpolate a specific `time` or position + * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is + * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other + * extremity (left + width or top + height). Note that it would be more optimized to directly + * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need + * to create the lookup table. The table ALWAYS contains at least two items: min and max. + * + * @param {number[]} timestamps - timestamps sorted from lowest to highest. + * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min + * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}. + * If 'series', timestamps will be positioned at the same distance from each other. In this + * case, only timestamps that break the time linearity are registered, meaning that in the + * best case, all timestamps are linear, the table contains only min and max. + */ +function buildLookupTable(timestamps, min, max, distribution) { + if (distribution === 'linear' || !timestamps.length) { + return [ + {time: min, pos: 0}, + {time: max, pos: 1} + ]; + } + + var table = []; + var items = [min]; + var i, ilen, prev, curr, next; + + for (i = 0, ilen = timestamps.length; i < ilen; ++i) { + curr = timestamps[i]; + if (curr > min && curr < max) { + items.push(curr); + } + } + + items.push(max); + + for (i = 0, ilen = items.length; i < ilen; ++i) { + next = items[i + 1]; + prev = items[i - 1]; + curr = items[i]; + + // only add points that breaks the scale linearity + if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) { + table.push({time: curr, pos: i / (ilen - 1)}); + } + } + + return table; +} + +// @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/ +function lookup(table, key, value) { + var lo = 0; + var hi = table.length - 1; + var mid, i0, i1; + + while (lo >= 0 && lo <= hi) { + mid = (lo + hi) >> 1; + i0 = table[mid - 1] || null; + i1 = table[mid]; + + if (!i0) { + // given value is outside table (before first item) + return {lo: null, hi: i1}; + } else if (i1[key] < value) { + lo = mid + 1; + } else if (i0[key] > value) { + hi = mid - 1; + } else { + return {lo: i0, hi: i1}; + } + } + + // given value is outside table (after last item) + return {lo: i1, hi: null}; +} + +/** + * Linearly interpolates the given source `value` using the table items `skey` values and + * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos') + * returns the position for a timestamp equal to 42. If value is out of bounds, values at + * index [0, 1] or [n - 1, n] are used for the interpolation. + */ +function interpolate$1(table, skey, sval, tkey) { + var range = lookup(table, skey, sval); + + // Note: the lookup table ALWAYS contains at least 2 items (min and max) + var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo; + var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi; + + var span = next[skey] - prev[skey]; + var ratio = span ? (sval - prev[skey]) / span : 0; + var offset = (next[tkey] - prev[tkey]) * ratio; + + return prev[tkey] + offset; +} + +function toTimestamp(scale, input) { + var adapter = scale._adapter; + var options = scale.options.time; + var parser = options.parser; + var format = parser || options.format; + var value = input; + + if (typeof parser === 'function') { + value = parser(value); + } + + // Only parse if its not a timestamp already + if (!helpers$1.isFinite(value)) { + value = typeof format === 'string' + ? adapter.parse(value, format) + : adapter.parse(value); + } + + if (value !== null) { + return +value; + } + + // Labels are in an incompatible format and no `parser` has been provided. + // The user might still use the deprecated `format` option for parsing. + if (!parser && typeof format === 'function') { + value = format(input); + + // `format` could return something else than a timestamp, if so, parse it + if (!helpers$1.isFinite(value)) { + value = adapter.parse(value); + } + } + + return value; +} + +function parse(scale, input) { + if (helpers$1.isNullOrUndef(input)) { + return null; + } + + var options = scale.options.time; + var value = toTimestamp(scale, scale.getRightValue(input)); + if (value === null) { + return value; + } + + if (options.round) { + value = +scale._adapter.startOf(value, options.round); + } + + return value; +} + +/** + * Returns the number of unit to skip to be able to display up to `capacity` number of ticks + * in `unit` for the given `min` / `max` range and respecting the interval steps constraints. + */ +function determineStepSize(min, max, unit, capacity) { + var range = max - min; + var interval = INTERVALS[unit]; + var milliseconds = interval.size; + var steps = interval.steps; + var i, ilen, factor; + + if (!steps) { + return Math.ceil(range / (capacity * milliseconds)); + } + + for (i = 0, ilen = steps.length; i < ilen; ++i) { + factor = steps[i]; + if (Math.ceil(range / (milliseconds * factor)) <= capacity) { + break; + } + } + + return factor; +} + +/** + * Figures out what unit results in an appropriate number of auto-generated ticks + */ +function determineUnitForAutoTicks(minUnit, min, max, capacity) { + var ilen = UNITS.length; + var i, interval, factor; + + for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) { + interval = INTERVALS[UNITS[i]]; + factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER; + + if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) { + return UNITS[i]; + } + } + + return UNITS[ilen - 1]; +} + +/** + * Figures out what unit to format a set of ticks with + */ +function determineUnitForFormatting(scale, ticks, minUnit, min, max) { + var ilen = UNITS.length; + var i, unit; + + for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) { + unit = UNITS[i]; + if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= ticks.length) { + return unit; + } + } + + return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0]; +} + +function determineMajorUnit(unit) { + for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) { + if (INTERVALS[UNITS[i]].common) { + return UNITS[i]; + } + } +} + +/** + * Generates a maximum of `capacity` timestamps between min and max, rounded to the + * `minor` unit, aligned on the `major` unit and using the given scale time `options`. + * Important: this method can return ticks outside the min and max range, it's the + * responsibility of the calling code to clamp values if needed. + */ +function generate(scale, min, max, capacity) { + var adapter = scale._adapter; + var options = scale.options; + var timeOpts = options.time; + var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity); + var major = determineMajorUnit(minor); + var stepSize = valueOrDefault$c(timeOpts.stepSize, timeOpts.unitStepSize); + var weekday = minor === 'week' ? timeOpts.isoWeekday : false; + var majorTicksEnabled = options.ticks.major.enabled; + var interval = INTERVALS[minor]; + var first = min; + var last = max; + var ticks = []; + var time; + + if (!stepSize) { + stepSize = determineStepSize(min, max, minor, capacity); + } + + // For 'week' unit, handle the first day of week option + if (weekday) { + first = +adapter.startOf(first, 'isoWeek', weekday); + last = +adapter.startOf(last, 'isoWeek', weekday); + } + + // Align first/last ticks on unit + first = +adapter.startOf(first, weekday ? 'day' : minor); + last = +adapter.startOf(last, weekday ? 'day' : minor); + + // Make sure that the last tick include max + if (last < max) { + last = +adapter.add(last, 1, minor); + } + + time = first; + + if (majorTicksEnabled && major && !weekday && !timeOpts.round) { + // Align the first tick on the previous `minor` unit aligned on the `major` unit: + // we first aligned time on the previous `major` unit then add the number of full + // stepSize there is between first and the previous major time. + time = +adapter.startOf(time, major); + time = +adapter.add(time, ~~((first - time) / (interval.size * stepSize)) * stepSize, minor); + } + + for (; time < last; time = +adapter.add(time, stepSize, minor)) { + ticks.push(+time); + } + + ticks.push(+time); + + return ticks; +} + +/** + * Returns the start and end offsets from edges in the form of {start, end} + * where each value is a relative width to the scale and ranges between 0 and 1. + * They add extra margins on the both sides by scaling down the original scale. + * Offsets are added when the `offset` option is true. + */ +function computeOffsets(table, ticks, min, max, options) { + var start = 0; + var end = 0; + var first, last; + + if (options.offset && ticks.length) { + if (!options.time.min) { + first = interpolate$1(table, 'time', ticks[0], 'pos'); + if (ticks.length === 1) { + start = 1 - first; + } else { + start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2; + } + } + if (!options.time.max) { + last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos'); + if (ticks.length === 1) { + end = last; + } else { + end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2; + } + } + } + + return {start: start, end: end}; +} + +function ticksFromTimestamps(scale, values, majorUnit) { + var ticks = []; + var i, ilen, value, major; + + for (i = 0, ilen = values.length; i < ilen; ++i) { + value = values[i]; + major = majorUnit ? value === +scale._adapter.startOf(value, majorUnit) : false; + + ticks.push({ + value: value, + major: major + }); + } + + return ticks; +} + +var defaultConfig$4 = { + position: 'bottom', + + /** + * Data distribution along the scale: + * - 'linear': data are spread according to their time (distances can vary), + * - 'series': data are spread at the same distance from each other. + * @see https://github.com/chartjs/Chart.js/pull/4507 + * @since 2.7.0 + */ + distribution: 'linear', + + /** + * Scale boundary strategy (bypassed by min/max time options) + * - `data`: make sure data are fully visible, ticks outside are removed + * - `ticks`: make sure ticks are fully visible, data outside are truncated + * @see https://github.com/chartjs/Chart.js/pull/4556 + * @since 2.7.0 + */ + bounds: 'data', + + adapters: {}, + time: { + parser: false, // false == a pattern string from https://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment + format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from https://momentjs.com/docs/#/parsing/string-format/ + unit: false, // false == automatic or override with week, month, year, etc. + round: false, // none, or override with week, month, year, etc. + displayFormat: false, // DEPRECATED + isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/ + minUnit: 'millisecond', + displayFormats: {} + }, + ticks: { + autoSkip: false, + + /** + * Ticks generation input values: + * - 'auto': generates "optimal" ticks based on scale size and time options. + * - 'data': generates ticks from data (including labels from data {t|x|y} objects). + * - 'labels': generates ticks from user given `data.labels` values ONLY. + * @see https://github.com/chartjs/Chart.js/pull/4507 + * @since 2.7.0 + */ + source: 'auto', + + major: { + enabled: false + } + } +}; + +var scale_time = core_scale.extend({ + initialize: function() { + this.mergeTicksOptions(); + core_scale.prototype.initialize.call(this); + }, + + update: function() { + var me = this; + var options = me.options; + var time = options.time || (options.time = {}); + var adapter = me._adapter = new core_adapters._date(options.adapters.date); + + // DEPRECATIONS: output a message only one time per update + if (time.format) { + console.warn('options.time.format is deprecated and replaced by options.time.parser.'); + } + + // Backward compatibility: before introducing adapter, `displayFormats` was + // supposed to contain *all* unit/string pairs but this can't be resolved + // when loading the scale (adapters are loaded afterward), so let's populate + // missing formats on update + helpers$1.mergeIf(time.displayFormats, adapter.formats()); + + return core_scale.prototype.update.apply(me, arguments); + }, + + /** + * Allows data to be referenced via 't' attribute + */ + getRightValue: function(rawValue) { + if (rawValue && rawValue.t !== undefined) { + rawValue = rawValue.t; + } + return core_scale.prototype.getRightValue.call(this, rawValue); + }, + + determineDataLimits: function() { + var me = this; + var chart = me.chart; + var adapter = me._adapter; + var timeOpts = me.options.time; + var unit = timeOpts.unit || 'day'; + var min = MAX_INTEGER; + var max = MIN_INTEGER; + var timestamps = []; + var datasets = []; + var labels = []; + var i, j, ilen, jlen, data, timestamp; + var dataLabels = chart.data.labels || []; + + // Convert labels to timestamps + for (i = 0, ilen = dataLabels.length; i < ilen; ++i) { + labels.push(parse(me, dataLabels[i])); + } + + // Convert data to timestamps + for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { + if (chart.isDatasetVisible(i)) { + data = chart.data.datasets[i].data; + + // Let's consider that all data have the same format. + if (helpers$1.isObject(data[0])) { + datasets[i] = []; + + for (j = 0, jlen = data.length; j < jlen; ++j) { + timestamp = parse(me, data[j]); + timestamps.push(timestamp); + datasets[i][j] = timestamp; + } + } else { + for (j = 0, jlen = labels.length; j < jlen; ++j) { + timestamps.push(labels[j]); + } + datasets[i] = labels.slice(0); + } + } else { + datasets[i] = []; + } + } + + if (labels.length) { + // Sort labels **after** data have been converted + labels = arrayUnique(labels).sort(sorter); + min = Math.min(min, labels[0]); + max = Math.max(max, labels[labels.length - 1]); + } + + if (timestamps.length) { + timestamps = arrayUnique(timestamps).sort(sorter); + min = Math.min(min, timestamps[0]); + max = Math.max(max, timestamps[timestamps.length - 1]); + } + + min = parse(me, timeOpts.min) || min; + max = parse(me, timeOpts.max) || max; + + // In case there is no valid min/max, set limits based on unit time option + min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min; + max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max; + + // Make sure that max is strictly higher than min (required by the lookup table) + me.min = Math.min(min, max); + me.max = Math.max(min + 1, max); + + // PRIVATE + me._horizontal = me.isHorizontal(); + me._table = []; + me._timestamps = { + data: timestamps, + datasets: datasets, + labels: labels + }; + }, + + buildTicks: function() { + var me = this; + var min = me.min; + var max = me.max; + var options = me.options; + var timeOpts = options.time; + var timestamps = []; + var ticks = []; + var i, ilen, timestamp; + + switch (options.ticks.source) { + case 'data': + timestamps = me._timestamps.data; + break; + case 'labels': + timestamps = me._timestamps.labels; + break; + case 'auto': + default: + timestamps = generate(me, min, max, me.getLabelCapacity(min), options); + } + + if (options.bounds === 'ticks' && timestamps.length) { + min = timestamps[0]; + max = timestamps[timestamps.length - 1]; + } + + // Enforce limits with user min/max options + min = parse(me, timeOpts.min) || min; + max = parse(me, timeOpts.max) || max; + + // Remove ticks outside the min/max range + for (i = 0, ilen = timestamps.length; i < ilen; ++i) { + timestamp = timestamps[i]; + if (timestamp >= min && timestamp <= max) { + ticks.push(timestamp); + } + } + + me.min = min; + me.max = max; + + // PRIVATE + me._unit = timeOpts.unit || determineUnitForFormatting(me, ticks, timeOpts.minUnit, me.min, me.max); + me._majorUnit = determineMajorUnit(me._unit); + me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution); + me._offsets = computeOffsets(me._table, ticks, min, max, options); + + if (options.ticks.reverse) { + ticks.reverse(); + } + + return ticksFromTimestamps(me, ticks, me._majorUnit); + }, + + getLabelForIndex: function(index, datasetIndex) { + var me = this; + var adapter = me._adapter; + var data = me.chart.data; + var timeOpts = me.options.time; + var label = data.labels && index < data.labels.length ? data.labels[index] : ''; + var value = data.datasets[datasetIndex].data[index]; + + if (helpers$1.isObject(value)) { + label = me.getRightValue(value); + } + if (timeOpts.tooltipFormat) { + return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat); + } + if (typeof label === 'string') { + return label; + } + return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime); + }, + + /** + * Function to format an individual tick mark + * @private + */ + tickFormatFunction: function(time, index, ticks, format) { + var me = this; + var adapter = me._adapter; + var options = me.options; + var formats = options.time.displayFormats; + var minorFormat = formats[me._unit]; + var majorUnit = me._majorUnit; + var majorFormat = formats[majorUnit]; + var majorTime = +adapter.startOf(time, majorUnit); + var majorTickOpts = options.ticks.major; + var major = majorTickOpts.enabled && majorUnit && majorFormat && time === majorTime; + var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat); + var tickOpts = major ? majorTickOpts : options.ticks.minor; + var formatter = valueOrDefault$c(tickOpts.callback, tickOpts.userCallback); + + return formatter ? formatter(label, index, ticks) : label; + }, + + convertTicksToLabels: function(ticks) { + var labels = []; + var i, ilen; + + for (i = 0, ilen = ticks.length; i < ilen; ++i) { + labels.push(this.tickFormatFunction(ticks[i].value, i, ticks)); + } + + return labels; + }, + + /** + * @private + */ + getPixelForOffset: function(time) { + var me = this; + var isReverse = me.options.ticks.reverse; + var size = me._horizontal ? me.width : me.height; + var start = me._horizontal ? isReverse ? me.right : me.left : isReverse ? me.bottom : me.top; + var pos = interpolate$1(me._table, 'time', time, 'pos'); + var offset = size * (me._offsets.start + pos) / (me._offsets.start + 1 + me._offsets.end); + + return isReverse ? start - offset : start + offset; + }, + + getPixelForValue: function(value, index, datasetIndex) { + var me = this; + var time = null; + + if (index !== undefined && datasetIndex !== undefined) { + time = me._timestamps.datasets[datasetIndex][index]; + } + + if (time === null) { + time = parse(me, value); + } + + if (time !== null) { + return me.getPixelForOffset(time); + } + }, + + getPixelForTick: function(index) { + var ticks = this.getTicks(); + return index >= 0 && index < ticks.length ? + this.getPixelForOffset(ticks[index].value) : + null; + }, + + getValueForPixel: function(pixel) { + var me = this; + var size = me._horizontal ? me.width : me.height; + var start = me._horizontal ? me.left : me.top; + var pos = (size ? (pixel - start) / size : 0) * (me._offsets.start + 1 + me._offsets.start) - me._offsets.end; + var time = interpolate$1(me._table, 'pos', pos, 'time'); + + // DEPRECATION, we should return time directly + return me._adapter._create(time); + }, + + /** + * Crude approximation of what the label width might be + * @private + */ + getLabelWidth: function(label) { + var me = this; + var ticksOpts = me.options.ticks; + var tickLabelWidth = me.ctx.measureText(label).width; + var angle = helpers$1.toRadians(ticksOpts.maxRotation); + var cosRotation = Math.cos(angle); + var sinRotation = Math.sin(angle); + var tickFontSize = valueOrDefault$c(ticksOpts.fontSize, core_defaults.global.defaultFontSize); + + return (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation); + }, + + /** + * @private + */ + getLabelCapacity: function(exampleTime) { + var me = this; + + // pick the longest format (milliseconds) for guestimation + var format = me.options.time.displayFormats.millisecond; + var exampleLabel = me.tickFormatFunction(exampleTime, 0, [], format); + var tickLabelWidth = me.getLabelWidth(exampleLabel); + var innerWidth = me.isHorizontal() ? me.width : me.height; + var capacity = Math.floor(innerWidth / tickLabelWidth); + + return capacity > 0 ? capacity : 1; + } +}); + +// INTERNAL: static default options, registered in src/index.js +var _defaults$4 = defaultConfig$4; +scale_time._defaults = _defaults$4; + +var scales = { + category: scale_category, + linear: scale_linear, + logarithmic: scale_logarithmic, + radialLinear: scale_radialLinear, + time: scale_time +}; + +var FORMATS = { + datetime: 'MMM D, YYYY, h:mm:ss a', + millisecond: 'h:mm:ss.SSS a', + second: 'h:mm:ss a', + minute: 'h:mm a', + hour: 'hA', + day: 'MMM D', + week: 'll', + month: 'MMM YYYY', + quarter: '[Q]Q - YYYY', + year: 'YYYY' +}; + +core_adapters._date.override(typeof moment === 'function' ? { + _id: 'moment', // DEBUG ONLY + + formats: function() { + return FORMATS; + }, + + parse: function(value, format) { + if (typeof value === 'string' && typeof format === 'string') { + value = moment(value, format); + } else if (!(value instanceof moment)) { + value = moment(value); + } + return value.isValid() ? value.valueOf() : null; + }, + + format: function(time, format) { + return moment(time).format(format); + }, + + add: function(time, amount, unit) { + return moment(time).add(amount, unit).valueOf(); + }, + + diff: function(max, min, unit) { + return moment.duration(moment(max).diff(moment(min))).as(unit); + }, + + startOf: function(time, unit, weekday) { + time = moment(time); + if (unit === 'isoWeek') { + return time.isoWeekday(weekday).valueOf(); + } + return time.startOf(unit).valueOf(); + }, + + endOf: function(time, unit) { + return moment(time).endOf(unit).valueOf(); + }, + + // DEPRECATIONS + + /** + * Provided for backward compatibility with scale.getValueForPixel(). + * @deprecated since version 2.8.0 + * @todo remove at version 3 + * @private + */ + _create: function(time) { + return moment(time); + }, +} : {}); + +core_defaults._set('global', { + plugins: { + filler: { + propagate: true + } + } +}); + +var mappers = { + dataset: function(source) { + var index = source.fill; + var chart = source.chart; + var meta = chart.getDatasetMeta(index); + var visible = meta && chart.isDatasetVisible(index); + var points = (visible && meta.dataset._children) || []; + var length = points.length || 0; + + return !length ? null : function(point, i) { + return (i < length && points[i]._view) || null; + }; + }, + + boundary: function(source) { + var boundary = source.boundary; + var x = boundary ? boundary.x : null; + var y = boundary ? boundary.y : null; + + return function(point) { + return { + x: x === null ? point.x : x, + y: y === null ? point.y : y, + }; + }; + } +}; + +// @todo if (fill[0] === '#') +function decodeFill(el, index, count) { + var model = el._model || {}; + var fill = model.fill; + var target; + + if (fill === undefined) { + fill = !!model.backgroundColor; + } + + if (fill === false || fill === null) { + return false; + } + + if (fill === true) { + return 'origin'; + } + + target = parseFloat(fill, 10); + if (isFinite(target) && Math.floor(target) === target) { + if (fill[0] === '-' || fill[0] === '+') { + target = index + target; + } + + if (target === index || target < 0 || target >= count) { + return false; + } + + return target; + } + + switch (fill) { + // compatibility + case 'bottom': + return 'start'; + case 'top': + return 'end'; + case 'zero': + return 'origin'; + // supported boundaries + case 'origin': + case 'start': + case 'end': + return fill; + // invalid fill values + default: + return false; + } +} + +function computeBoundary(source) { + var model = source.el._model || {}; + var scale = source.el._scale || {}; + var fill = source.fill; + var target = null; + var horizontal; + + if (isFinite(fill)) { + return null; + } + + // Backward compatibility: until v3, we still need to support boundary values set on + // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and + // controllers might still use it (e.g. the Smith chart). + + if (fill === 'start') { + target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom; + } else if (fill === 'end') { + target = model.scaleTop === undefined ? scale.top : model.scaleTop; + } else if (model.scaleZero !== undefined) { + target = model.scaleZero; + } else if (scale.getBasePosition) { + target = scale.getBasePosition(); + } else if (scale.getBasePixel) { + target = scale.getBasePixel(); + } + + if (target !== undefined && target !== null) { + if (target.x !== undefined && target.y !== undefined) { + return target; + } + + if (helpers$1.isFinite(target)) { + horizontal = scale.isHorizontal(); + return { + x: horizontal ? target : null, + y: horizontal ? null : target + }; + } + } + + return null; +} + +function resolveTarget(sources, index, propagate) { + var source = sources[index]; + var fill = source.fill; + var visited = [index]; + var target; + + if (!propagate) { + return fill; + } + + while (fill !== false && visited.indexOf(fill) === -1) { + if (!isFinite(fill)) { + return fill; + } + + target = sources[fill]; + if (!target) { + return false; + } + + if (target.visible) { + return fill; + } + + visited.push(fill); + fill = target.fill; + } + + return false; +} + +function createMapper(source) { + var fill = source.fill; + var type = 'dataset'; + + if (fill === false) { + return null; + } + + if (!isFinite(fill)) { + type = 'boundary'; + } + + return mappers[type](source); +} + +function isDrawable(point) { + return point && !point.skip; +} + +function drawArea(ctx, curve0, curve1, len0, len1) { + var i; + + if (!len0 || !len1) { + return; + } + + // building first area curve (normal) + ctx.moveTo(curve0[0].x, curve0[0].y); + for (i = 1; i < len0; ++i) { + helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]); + } + + // joining the two area curves + ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y); + + // building opposite area curve (reverse) + for (i = len1 - 1; i > 0; --i) { + helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true); + } +} + +function doFill(ctx, points, mapper, view, color, loop) { + var count = points.length; + var span = view.spanGaps; + var curve0 = []; + var curve1 = []; + var len0 = 0; + var len1 = 0; + var i, ilen, index, p0, p1, d0, d1; + + ctx.beginPath(); + + for (i = 0, ilen = (count + !!loop); i < ilen; ++i) { + index = i % count; + p0 = points[index]._view; + p1 = mapper(p0, index, view); + d0 = isDrawable(p0); + d1 = isDrawable(p1); + + if (d0 && d1) { + len0 = curve0.push(p0); + len1 = curve1.push(p1); + } else if (len0 && len1) { + if (!span) { + drawArea(ctx, curve0, curve1, len0, len1); + len0 = len1 = 0; + curve0 = []; + curve1 = []; + } else { + if (d0) { + curve0.push(p0); + } + if (d1) { + curve1.push(p1); + } + } + } + } + + drawArea(ctx, curve0, curve1, len0, len1); + + ctx.closePath(); + ctx.fillStyle = color; + ctx.fill(); +} + +var plugin_filler = { + id: 'filler', + + afterDatasetsUpdate: function(chart, options) { + var count = (chart.data.datasets || []).length; + var propagate = options.propagate; + var sources = []; + var meta, i, el, source; + + for (i = 0; i < count; ++i) { + meta = chart.getDatasetMeta(i); + el = meta.dataset; + source = null; + + if (el && el._model && el instanceof elements.Line) { + source = { + visible: chart.isDatasetVisible(i), + fill: decodeFill(el, i, count), + chart: chart, + el: el + }; + } + + meta.$filler = source; + sources.push(source); + } + + for (i = 0; i < count; ++i) { + source = sources[i]; + if (!source) { + continue; + } + + source.fill = resolveTarget(sources, i, propagate); + source.boundary = computeBoundary(source); + source.mapper = createMapper(source); + } + }, + + beforeDatasetDraw: function(chart, args) { + var meta = args.meta.$filler; + if (!meta) { + return; + } + + var ctx = chart.ctx; + var el = meta.el; + var view = el._view; + var points = el._children || []; + var mapper = meta.mapper; + var color = view.backgroundColor || core_defaults.global.defaultColor; + + if (mapper && color && points.length) { + helpers$1.canvas.clipArea(ctx, chart.chartArea); + doFill(ctx, points, mapper, view, color, el._loop); + helpers$1.canvas.unclipArea(ctx); + } + } +}; + +var noop$1 = helpers$1.noop; +var valueOrDefault$d = helpers$1.valueOrDefault; + +core_defaults._set('global', { + legend: { + display: true, + position: 'top', + fullWidth: true, + reverse: false, + weight: 1000, + + // a callback that will handle + onClick: function(e, legendItem) { + var index = legendItem.datasetIndex; + var ci = this.chart; + var meta = ci.getDatasetMeta(index); + + // See controller.isDatasetVisible comment + meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null; + + // We hid a dataset ... rerender the chart + ci.update(); + }, + + onHover: null, + onLeave: null, + + labels: { + boxWidth: 40, + padding: 10, + // Generates labels shown in the legend + // Valid properties to return: + // text : text to display + // fillStyle : fill of coloured box + // strokeStyle: stroke of coloured box + // hidden : if this legend item refers to a hidden item + // lineCap : cap style for line + // lineDash + // lineDashOffset : + // lineJoin : + // lineWidth : + generateLabels: function(chart) { + var data = chart.data; + return helpers$1.isArray(data.datasets) ? data.datasets.map(function(dataset, i) { + return { + text: dataset.label, + fillStyle: (!helpers$1.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]), + hidden: !chart.isDatasetVisible(i), + lineCap: dataset.borderCapStyle, + lineDash: dataset.borderDash, + lineDashOffset: dataset.borderDashOffset, + lineJoin: dataset.borderJoinStyle, + lineWidth: dataset.borderWidth, + strokeStyle: dataset.borderColor, + pointStyle: dataset.pointStyle, + + // Below is extra data used for toggling the datasets + datasetIndex: i + }; + }, this) : []; + } + } + }, + + legendCallback: function(chart) { + var text = []; + text.push('
      '); + for (var i = 0; i < chart.data.datasets.length; i++) { + text.push('
    • '); + if (chart.data.datasets[i].label) { + text.push(chart.data.datasets[i].label); + } + text.push('
    • '); + } + text.push('
    '); + return text.join(''); + } +}); + +/** + * Helper function to get the box width based on the usePointStyle option + * @param {object} labelopts - the label options on the legend + * @param {number} fontSize - the label font size + * @return {number} width of the color box area + */ +function getBoxWidth(labelOpts, fontSize) { + return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ? + fontSize : + labelOpts.boxWidth; +} + +/** + * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required! + */ +var Legend = core_element.extend({ + + initialize: function(config) { + helpers$1.extend(this, config); + + // Contains hit boxes for each dataset (in dataset order) + this.legendHitBoxes = []; + + /** + * @private + */ + this._hoveredItem = null; + + // Are we in doughnut mode which has a different data type + this.doughnutMode = false; + }, + + // These methods are ordered by lifecycle. Utilities then follow. + // Any function defined here is inherited by all legend types. + // Any function can be extended by the legend type + + beforeUpdate: noop$1, + update: function(maxWidth, maxHeight, margins) { + var me = this; + + // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) + me.beforeUpdate(); + + // Absorb the master measurements + me.maxWidth = maxWidth; + me.maxHeight = maxHeight; + me.margins = margins; + + // Dimensions + me.beforeSetDimensions(); + me.setDimensions(); + me.afterSetDimensions(); + // Labels + me.beforeBuildLabels(); + me.buildLabels(); + me.afterBuildLabels(); + + // Fit + me.beforeFit(); + me.fit(); + me.afterFit(); + // + me.afterUpdate(); + + return me.minSize; + }, + afterUpdate: noop$1, + + // + + beforeSetDimensions: noop$1, + setDimensions: function() { + var me = this; + // Set the unconstrained dimension before label rotation + if (me.isHorizontal()) { + // Reset position before calculating rotation + me.width = me.maxWidth; + me.left = 0; + me.right = me.width; + } else { + me.height = me.maxHeight; + + // Reset position before calculating rotation + me.top = 0; + me.bottom = me.height; + } + + // Reset padding + me.paddingLeft = 0; + me.paddingTop = 0; + me.paddingRight = 0; + me.paddingBottom = 0; + + // Reset minSize + me.minSize = { + width: 0, + height: 0 + }; + }, + afterSetDimensions: noop$1, + + // + + beforeBuildLabels: noop$1, + buildLabels: function() { + var me = this; + var labelOpts = me.options.labels || {}; + var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || []; + + if (labelOpts.filter) { + legendItems = legendItems.filter(function(item) { + return labelOpts.filter(item, me.chart.data); + }); + } + + if (me.options.reverse) { + legendItems.reverse(); + } + + me.legendItems = legendItems; + }, + afterBuildLabels: noop$1, + + // + + beforeFit: noop$1, + fit: function() { + var me = this; + var opts = me.options; + var labelOpts = opts.labels; + var display = opts.display; + + var ctx = me.ctx; + + var labelFont = helpers$1.options._parseFont(labelOpts); + var fontSize = labelFont.size; + + // Reset hit boxes + var hitboxes = me.legendHitBoxes = []; + + var minSize = me.minSize; + var isHorizontal = me.isHorizontal(); + + if (isHorizontal) { + minSize.width = me.maxWidth; // fill all the width + minSize.height = display ? 10 : 0; + } else { + minSize.width = display ? 10 : 0; + minSize.height = me.maxHeight; // fill all the height + } + + // Increase sizes here + if (display) { + ctx.font = labelFont.string; + + if (isHorizontal) { + // Labels + + // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one + var lineWidths = me.lineWidths = [0]; + var totalHeight = 0; + + ctx.textAlign = 'left'; + ctx.textBaseline = 'top'; + + helpers$1.each(me.legendItems, function(legendItem, i) { + var boxWidth = getBoxWidth(labelOpts, fontSize); + var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; + + if (i === 0 || lineWidths[lineWidths.length - 1] + width + labelOpts.padding > minSize.width) { + totalHeight += fontSize + labelOpts.padding; + lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = labelOpts.padding; + } + + // Store the hitbox width and height here. Final position will be updated in `draw` + hitboxes[i] = { + left: 0, + top: 0, + width: width, + height: fontSize + }; + + lineWidths[lineWidths.length - 1] += width + labelOpts.padding; + }); + + minSize.height += totalHeight; + + } else { + var vPadding = labelOpts.padding; + var columnWidths = me.columnWidths = []; + var totalWidth = labelOpts.padding; + var currentColWidth = 0; + var currentColHeight = 0; + var itemHeight = fontSize + vPadding; + + helpers$1.each(me.legendItems, function(legendItem, i) { + var boxWidth = getBoxWidth(labelOpts, fontSize); + var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; + + // If too tall, go to new column + if (i > 0 && currentColHeight + itemHeight > minSize.height - vPadding) { + totalWidth += currentColWidth + labelOpts.padding; + columnWidths.push(currentColWidth); // previous column width + + currentColWidth = 0; + currentColHeight = 0; + } + + // Get max width + currentColWidth = Math.max(currentColWidth, itemWidth); + currentColHeight += itemHeight; + + // Store the hitbox width and height here. Final position will be updated in `draw` + hitboxes[i] = { + left: 0, + top: 0, + width: itemWidth, + height: fontSize + }; + }); + + totalWidth += currentColWidth; + columnWidths.push(currentColWidth); + minSize.width += totalWidth; + } + } + + me.width = minSize.width; + me.height = minSize.height; + }, + afterFit: noop$1, + + // Shared Methods + isHorizontal: function() { + return this.options.position === 'top' || this.options.position === 'bottom'; + }, + + // Actually draw the legend on the canvas + draw: function() { + var me = this; + var opts = me.options; + var labelOpts = opts.labels; + var globalDefaults = core_defaults.global; + var defaultColor = globalDefaults.defaultColor; + var lineDefault = globalDefaults.elements.line; + var legendWidth = me.width; + var lineWidths = me.lineWidths; + + if (opts.display) { + var ctx = me.ctx; + var fontColor = valueOrDefault$d(labelOpts.fontColor, globalDefaults.defaultFontColor); + var labelFont = helpers$1.options._parseFont(labelOpts); + var fontSize = labelFont.size; + var cursor; + + // Canvas setup + ctx.textAlign = 'left'; + ctx.textBaseline = 'middle'; + ctx.lineWidth = 0.5; + ctx.strokeStyle = fontColor; // for strikethrough effect + ctx.fillStyle = fontColor; // render in correct colour + ctx.font = labelFont.string; + + var boxWidth = getBoxWidth(labelOpts, fontSize); + var hitboxes = me.legendHitBoxes; + + // current position + var drawLegendBox = function(x, y, legendItem) { + if (isNaN(boxWidth) || boxWidth <= 0) { + return; + } + + // Set the ctx for the box + ctx.save(); + + var lineWidth = valueOrDefault$d(legendItem.lineWidth, lineDefault.borderWidth); + ctx.fillStyle = valueOrDefault$d(legendItem.fillStyle, defaultColor); + ctx.lineCap = valueOrDefault$d(legendItem.lineCap, lineDefault.borderCapStyle); + ctx.lineDashOffset = valueOrDefault$d(legendItem.lineDashOffset, lineDefault.borderDashOffset); + ctx.lineJoin = valueOrDefault$d(legendItem.lineJoin, lineDefault.borderJoinStyle); + ctx.lineWidth = lineWidth; + ctx.strokeStyle = valueOrDefault$d(legendItem.strokeStyle, defaultColor); + + if (ctx.setLineDash) { + // IE 9 and 10 do not support line dash + ctx.setLineDash(valueOrDefault$d(legendItem.lineDash, lineDefault.borderDash)); + } + + if (opts.labels && opts.labels.usePointStyle) { + // Recalculate x and y for drawPoint() because its expecting + // x and y to be center of figure (instead of top left) + var radius = boxWidth * Math.SQRT2 / 2; + var centerX = x + boxWidth / 2; + var centerY = y + fontSize / 2; + + // Draw pointStyle as legend symbol + helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY); + } else { + // Draw box as legend symbol + if (lineWidth !== 0) { + ctx.strokeRect(x, y, boxWidth, fontSize); + } + ctx.fillRect(x, y, boxWidth, fontSize); + } + + ctx.restore(); + }; + var fillText = function(x, y, legendItem, textWidth) { + var halfFontSize = fontSize / 2; + var xLeft = boxWidth + halfFontSize + x; + var yMiddle = y + halfFontSize; + + ctx.fillText(legendItem.text, xLeft, yMiddle); + + if (legendItem.hidden) { + // Strikethrough the text if hidden + ctx.beginPath(); + ctx.lineWidth = 2; + ctx.moveTo(xLeft, yMiddle); + ctx.lineTo(xLeft + textWidth, yMiddle); + ctx.stroke(); + } + }; + + // Horizontal + var isHorizontal = me.isHorizontal(); + if (isHorizontal) { + cursor = { + x: me.left + ((legendWidth - lineWidths[0]) / 2) + labelOpts.padding, + y: me.top + labelOpts.padding, + line: 0 + }; + } else { + cursor = { + x: me.left + labelOpts.padding, + y: me.top + labelOpts.padding, + line: 0 + }; + } + + var itemHeight = fontSize + labelOpts.padding; + helpers$1.each(me.legendItems, function(legendItem, i) { + var textWidth = ctx.measureText(legendItem.text).width; + var width = boxWidth + (fontSize / 2) + textWidth; + var x = cursor.x; + var y = cursor.y; + + // Use (me.left + me.minSize.width) and (me.top + me.minSize.height) + // instead of me.right and me.bottom because me.width and me.height + // may have been changed since me.minSize was calculated + if (isHorizontal) { + if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) { + y = cursor.y += itemHeight; + cursor.line++; + x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2) + labelOpts.padding; + } + } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) { + x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding; + y = cursor.y = me.top + labelOpts.padding; + cursor.line++; + } + + drawLegendBox(x, y, legendItem); + + hitboxes[i].left = x; + hitboxes[i].top = y; + + // Fill the actual label + fillText(x, y, legendItem, textWidth); + + if (isHorizontal) { + cursor.x += width + labelOpts.padding; + } else { + cursor.y += itemHeight; + } + + }); + } + }, + + /** + * @private + */ + _getLegendItemAt: function(x, y) { + var me = this; + var i, hitBox, lh; + + if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) { + // See if we are touching one of the dataset boxes + lh = me.legendHitBoxes; + for (i = 0; i < lh.length; ++i) { + hitBox = lh[i]; + + if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) { + // Touching an element + return me.legendItems[i]; + } + } + } + + return null; + }, + + /** + * Handle an event + * @private + * @param {IEvent} event - The event to handle + */ + handleEvent: function(e) { + var me = this; + var opts = me.options; + var type = e.type === 'mouseup' ? 'click' : e.type; + var hoveredItem; + + if (type === 'mousemove') { + if (!opts.onHover && !opts.onLeave) { + return; + } + } else if (type === 'click') { + if (!opts.onClick) { + return; + } + } else { + return; + } + + // Chart event already has relative position in it + hoveredItem = me._getLegendItemAt(e.x, e.y); + + if (type === 'click') { + if (hoveredItem && opts.onClick) { + // use e.native for backwards compatibility + opts.onClick.call(me, e.native, hoveredItem); + } + } else { + if (opts.onLeave && hoveredItem !== me._hoveredItem) { + if (me._hoveredItem) { + opts.onLeave.call(me, e.native, me._hoveredItem); + } + me._hoveredItem = hoveredItem; + } + + if (opts.onHover && hoveredItem) { + // use e.native for backwards compatibility + opts.onHover.call(me, e.native, hoveredItem); + } + } + } +}); + +function createNewLegendAndAttach(chart, legendOpts) { + var legend = new Legend({ + ctx: chart.ctx, + options: legendOpts, + chart: chart + }); + + core_layouts.configure(chart, legend, legendOpts); + core_layouts.addBox(chart, legend); + chart.legend = legend; +} + +var plugin_legend = { + id: 'legend', + + /** + * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making + * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of + * the plugin, which one will be re-exposed in the chart.js file. + * https://github.com/chartjs/Chart.js/pull/2640 + * @private + */ + _element: Legend, + + beforeInit: function(chart) { + var legendOpts = chart.options.legend; + + if (legendOpts) { + createNewLegendAndAttach(chart, legendOpts); + } + }, + + beforeUpdate: function(chart) { + var legendOpts = chart.options.legend; + var legend = chart.legend; + + if (legendOpts) { + helpers$1.mergeIf(legendOpts, core_defaults.global.legend); + + if (legend) { + core_layouts.configure(chart, legend, legendOpts); + legend.options = legendOpts; + } else { + createNewLegendAndAttach(chart, legendOpts); + } + } else if (legend) { + core_layouts.removeBox(chart, legend); + delete chart.legend; + } + }, + + afterEvent: function(chart, e) { + var legend = chart.legend; + if (legend) { + legend.handleEvent(e); + } + } +}; + +var noop$2 = helpers$1.noop; + +core_defaults._set('global', { + title: { + display: false, + fontStyle: 'bold', + fullWidth: true, + padding: 10, + position: 'top', + text: '', + weight: 2000 // by default greater than legend (1000) to be above + } +}); + +/** + * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required! + */ +var Title = core_element.extend({ + initialize: function(config) { + var me = this; + helpers$1.extend(me, config); + + // Contains hit boxes for each dataset (in dataset order) + me.legendHitBoxes = []; + }, + + // These methods are ordered by lifecycle. Utilities then follow. + + beforeUpdate: noop$2, + update: function(maxWidth, maxHeight, margins) { + var me = this; + + // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) + me.beforeUpdate(); + + // Absorb the master measurements + me.maxWidth = maxWidth; + me.maxHeight = maxHeight; + me.margins = margins; + + // Dimensions + me.beforeSetDimensions(); + me.setDimensions(); + me.afterSetDimensions(); + // Labels + me.beforeBuildLabels(); + me.buildLabels(); + me.afterBuildLabels(); + + // Fit + me.beforeFit(); + me.fit(); + me.afterFit(); + // + me.afterUpdate(); + + return me.minSize; + + }, + afterUpdate: noop$2, + + // + + beforeSetDimensions: noop$2, + setDimensions: function() { + var me = this; + // Set the unconstrained dimension before label rotation + if (me.isHorizontal()) { + // Reset position before calculating rotation + me.width = me.maxWidth; + me.left = 0; + me.right = me.width; + } else { + me.height = me.maxHeight; + + // Reset position before calculating rotation + me.top = 0; + me.bottom = me.height; + } + + // Reset padding + me.paddingLeft = 0; + me.paddingTop = 0; + me.paddingRight = 0; + me.paddingBottom = 0; + + // Reset minSize + me.minSize = { + width: 0, + height: 0 + }; + }, + afterSetDimensions: noop$2, + + // + + beforeBuildLabels: noop$2, + buildLabels: noop$2, + afterBuildLabels: noop$2, + + // + + beforeFit: noop$2, + fit: function() { + var me = this; + var opts = me.options; + var display = opts.display; + var minSize = me.minSize; + var lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1; + var fontOpts = helpers$1.options._parseFont(opts); + var textSize = display ? (lineCount * fontOpts.lineHeight) + (opts.padding * 2) : 0; + + if (me.isHorizontal()) { + minSize.width = me.maxWidth; // fill all the width + minSize.height = textSize; + } else { + minSize.width = textSize; + minSize.height = me.maxHeight; // fill all the height + } + + me.width = minSize.width; + me.height = minSize.height; + + }, + afterFit: noop$2, + + // Shared Methods + isHorizontal: function() { + var pos = this.options.position; + return pos === 'top' || pos === 'bottom'; + }, + + // Actually draw the title block on the canvas + draw: function() { + var me = this; + var ctx = me.ctx; + var opts = me.options; + + if (opts.display) { + var fontOpts = helpers$1.options._parseFont(opts); + var lineHeight = fontOpts.lineHeight; + var offset = lineHeight / 2 + opts.padding; + var rotation = 0; + var top = me.top; + var left = me.left; + var bottom = me.bottom; + var right = me.right; + var maxWidth, titleX, titleY; + + ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour + ctx.font = fontOpts.string; + + // Horizontal + if (me.isHorizontal()) { + titleX = left + ((right - left) / 2); // midpoint of the width + titleY = top + offset; + maxWidth = right - left; + } else { + titleX = opts.position === 'left' ? left + offset : right - offset; + titleY = top + ((bottom - top) / 2); + maxWidth = bottom - top; + rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5); + } + + ctx.save(); + ctx.translate(titleX, titleY); + ctx.rotate(rotation); + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + + var text = opts.text; + if (helpers$1.isArray(text)) { + var y = 0; + for (var i = 0; i < text.length; ++i) { + ctx.fillText(text[i], 0, y, maxWidth); + y += lineHeight; + } + } else { + ctx.fillText(text, 0, 0, maxWidth); + } + + ctx.restore(); + } + } +}); + +function createNewTitleBlockAndAttach(chart, titleOpts) { + var title = new Title({ + ctx: chart.ctx, + options: titleOpts, + chart: chart + }); + + core_layouts.configure(chart, title, titleOpts); + core_layouts.addBox(chart, title); + chart.titleBlock = title; +} + +var plugin_title = { + id: 'title', + + /** + * Backward compatibility: since 2.1.5, the title is registered as a plugin, making + * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of + * the plugin, which one will be re-exposed in the chart.js file. + * https://github.com/chartjs/Chart.js/pull/2640 + * @private + */ + _element: Title, + + beforeInit: function(chart) { + var titleOpts = chart.options.title; + + if (titleOpts) { + createNewTitleBlockAndAttach(chart, titleOpts); + } + }, + + beforeUpdate: function(chart) { + var titleOpts = chart.options.title; + var titleBlock = chart.titleBlock; + + if (titleOpts) { + helpers$1.mergeIf(titleOpts, core_defaults.global.title); + + if (titleBlock) { + core_layouts.configure(chart, titleBlock, titleOpts); + titleBlock.options = titleOpts; + } else { + createNewTitleBlockAndAttach(chart, titleOpts); + } + } else if (titleBlock) { + core_layouts.removeBox(chart, titleBlock); + delete chart.titleBlock; + } + } +}; + +var plugins = {}; +var filler = plugin_filler; +var legend = plugin_legend; +var title = plugin_title; +plugins.filler = filler; +plugins.legend = legend; +plugins.title = title; + +/** + * @namespace Chart + */ + + +core_controller.helpers = helpers$1; + +// @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests! +core_helpers(core_controller); + +core_controller._adapters = core_adapters; +core_controller.Animation = core_animation; +core_controller.animationService = core_animations; +core_controller.controllers = controllers; +core_controller.DatasetController = core_datasetController; +core_controller.defaults = core_defaults; +core_controller.Element = core_element; +core_controller.elements = elements; +core_controller.Interaction = core_interaction; +core_controller.layouts = core_layouts; +core_controller.platform = platform; +core_controller.plugins = core_plugins; +core_controller.Scale = core_scale; +core_controller.scaleService = core_scaleService; +core_controller.Ticks = core_ticks; +core_controller.Tooltip = core_tooltip; + +// Register built-in scales + +core_controller.helpers.each(scales, function(scale, type) { + core_controller.scaleService.registerScaleType(type, scale, scale._defaults); +}); + +// Load to register built-in adapters (as side effects) + + +// Loading built-in plugins + +for (var k in plugins) { + if (plugins.hasOwnProperty(k)) { + core_controller.plugins.register(plugins[k]); + } +} + +core_controller.platform.initialize(); + +var src = core_controller; +if (typeof window !== 'undefined') { + window.Chart = core_controller; +} + +// DEPRECATIONS + +/** + * Provided for backward compatibility, not available anymore + * @namespace Chart.Chart + * @deprecated since version 2.8.0 + * @todo remove at version 3 + * @private + */ +core_controller.Chart = core_controller; + +/** + * Provided for backward compatibility, not available anymore + * @namespace Chart.Legend + * @deprecated since version 2.1.5 + * @todo remove at version 3 + * @private + */ +core_controller.Legend = plugins.legend._element; + +/** + * Provided for backward compatibility, not available anymore + * @namespace Chart.Title + * @deprecated since version 2.1.5 + * @todo remove at version 3 + * @private + */ +core_controller.Title = plugins.title._element; + +/** + * Provided for backward compatibility, use Chart.plugins instead + * @namespace Chart.pluginService + * @deprecated since version 2.1.5 + * @todo remove at version 3 + * @private + */ +core_controller.pluginService = core_controller.plugins; + +/** + * Provided for backward compatibility, inheriting from Chart.PlugingBase has no + * effect, instead simply create/register plugins via plain JavaScript objects. + * @interface Chart.PluginBase + * @deprecated since version 2.5.0 + * @todo remove at version 3 + * @private + */ +core_controller.PluginBase = core_controller.Element.extend({}); + +/** + * Provided for backward compatibility, use Chart.helpers.canvas instead. + * @namespace Chart.canvasHelpers + * @deprecated since version 2.6.0 + * @todo remove at version 3 + * @private + */ +core_controller.canvasHelpers = core_controller.helpers.canvas; + +/** + * Provided for backward compatibility, use Chart.layouts instead. + * @namespace Chart.layoutService + * @deprecated since version 2.7.3 + * @todo remove at version 3 + * @private + */ +core_controller.layoutService = core_controller.layouts; + +/** + * Provided for backward compatibility, not available anymore. + * @namespace Chart.LinearScaleBase + * @deprecated since version 2.8 + * @todo remove at version 3 + * @private + */ +core_controller.LinearScaleBase = scale_linearbase; + +/** + * Provided for backward compatibility, instead we should create a new Chart + * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`). + * @deprecated since version 2.8.0 + * @todo remove at version 3 + */ +core_controller.helpers.each( + [ + 'Bar', + 'Bubble', + 'Doughnut', + 'Line', + 'PolarArea', + 'Radar', + 'Scatter' + ], + function(klass) { + core_controller[klass] = function(ctx, cfg) { + return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, { + type: klass.charAt(0).toLowerCase() + klass.slice(1) + })); + }; + } +); + +return src; + +}))); \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/libs/jquery-ui.js b/SplunkAppForWazuh/appserver/static/js/libs/jquery-ui.js new file mode 100644 index 000000000..f1cf0fcc1 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/libs/jquery-ui.js @@ -0,0 +1,6 @@ +/*! jQuery UI - v1.12.1 - 2019-04-23 +* http://jqueryui.com +* Includes: widget.js, position.js, data.js, disable-selection.js, focusable.js, form-reset-mixin.js, jquery-1-7.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js +* Copyright jQuery Foundation and other contributors; Licensed MIT */ + +(function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)})(function(t){function e(t){for(var e=t.css("visibility");"inherit"===e;)t=t.parent(),e=t.css("visibility");return"hidden"!==e}t.ui=t.ui||{},t.ui.version="1.12.1";var i=0,s=Array.prototype.slice;t.cleanData=function(e){return function(i){var s,n,o;for(o=0;null!=(n=i[o]);o++)try{s=t._data(n,"events"),s&&s.remove&&t(n).triggerHandler("remove")}catch(a){}e(i)}}(t.cleanData),t.widget=function(e,i,s){var n,o,a,r={},l=e.split(".")[0];e=e.split(".")[1];var h=l+"-"+e;return s||(s=i,i=t.Widget),t.isArray(s)&&(s=t.extend.apply(null,[{}].concat(s))),t.expr[":"][h.toLowerCase()]=function(e){return!!t.data(e,h)},t[l]=t[l]||{},n=t[l][e],o=t[l][e]=function(t,e){return this._createWidget?(arguments.length&&this._createWidget(t,e),void 0):new o(t,e)},t.extend(o,n,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),a=new i,a.options=t.widget.extend({},a.options),t.each(s,function(e,s){return t.isFunction(s)?(r[e]=function(){function t(){return i.prototype[e].apply(this,arguments)}function n(t){return i.prototype[e].apply(this,t)}return function(){var e,i=this._super,o=this._superApply;return this._super=t,this._superApply=n,e=s.apply(this,arguments),this._super=i,this._superApply=o,e}}(),void 0):(r[e]=s,void 0)}),o.prototype=t.widget.extend(a,{widgetEventPrefix:n?a.widgetEventPrefix||e:e},r,{constructor:o,namespace:l,widgetName:e,widgetFullName:h}),n?(t.each(n._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),t.widget.bridge(e,o),o},t.widget.extend=function(e){for(var i,n,o=s.call(arguments,1),a=0,r=o.length;r>a;a++)for(i in o[a])n=o[a][i],o[a].hasOwnProperty(i)&&void 0!==n&&(e[i]=t.isPlainObject(n)?t.isPlainObject(e[i])?t.widget.extend({},e[i],n):t.widget.extend({},n):n);return e},t.widget.bridge=function(e,i){var n=i.prototype.widgetFullName||e;t.fn[e]=function(o){var a="string"==typeof o,r=s.call(arguments,1),l=this;return a?this.length||"instance"!==o?this.each(function(){var i,s=t.data(this,n);return"instance"===o?(l=s,!1):s?t.isFunction(s[o])&&"_"!==o.charAt(0)?(i=s[o].apply(s,r),i!==s&&void 0!==i?(l=i&&i.jquery?l.pushStack(i.get()):i,!1):void 0):t.error("no such method '"+o+"' for "+e+" widget instance"):t.error("cannot call methods on "+e+" prior to initialization; "+"attempted to call method '"+o+"'")}):l=void 0:(r.length&&(o=t.widget.extend.apply(null,[o].concat(r))),this.each(function(){var e=t.data(this,n);e?(e.option(o||{}),e._init&&e._init()):t.data(this,n,new i(o,this))})),l}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"
    ",options:{classes:{},disabled:!1,create:null},_createWidget:function(e,s){s=t(s||this.defaultElement||this)[0],this.element=t(s),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=t(),this.hoverable=t(),this.focusable=t(),this.classesElementLookup={},s!==this&&(t.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===s&&this.destroy()}}),this.document=t(s.style?s.ownerDocument:s.document||s),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){var e=this;this._destroy(),t.each(this.classesElementLookup,function(t,i){e._removeClass(i,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:t.noop,widget:function(){return this.element},option:function(e,i){var s,n,o,a=e;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof e)if(a={},s=e.split("."),e=s.shift(),s.length){for(n=a[e]=t.widget.extend({},this.options[e]),o=0;s.length-1>o;o++)n[s[o]]=n[s[o]]||{},n=n[s[o]];if(e=s.pop(),1===arguments.length)return void 0===n[e]?null:n[e];n[e]=i}else{if(1===arguments.length)return void 0===this.options[e]?null:this.options[e];a[e]=i}return this._setOptions(a),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(e){var i,s,n;for(i in e)n=this.classesElementLookup[i],e[i]!==this.options.classes[i]&&n&&n.length&&(s=t(n.get()),this._removeClass(n,i),s.addClass(this._classes({element:s,keys:i,classes:e,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(e){function i(i,o){var a,r;for(r=0;i.length>r;r++)a=n.classesElementLookup[i[r]]||t(),a=e.add?t(t.unique(a.get().concat(e.element.get()))):t(a.not(e.element).get()),n.classesElementLookup[i[r]]=a,s.push(i[r]),o&&e.classes[i[r]]&&s.push(e.classes[i[r]])}var s=[],n=this;return e=t.extend({element:this.element,classes:this.options.classes||{}},e),this._on(e.element,{remove:"_untrackClassesElement"}),e.keys&&i(e.keys.match(/\S+/g)||[],!0),e.extra&&i(e.extra.match(/\S+/g)||[]),s.join(" ")},_untrackClassesElement:function(e){var i=this;t.each(i.classesElementLookup,function(s,n){-1!==t.inArray(e.target,n)&&(i.classesElementLookup[s]=t(n.not(e.target).get()))})},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,s){s="boolean"==typeof s?s:i;var n="string"==typeof t||null===t,o={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s};return o.element.toggleClass(this._classes(o),s),this},_on:function(e,i,s){var n,o=this;"boolean"!=typeof e&&(s=i,i=e,e=!1),s?(i=n=t(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),t.each(s,function(s,a){function r(){return e||o.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof a?o[a]:a).apply(o,arguments):void 0}"string"!=typeof a&&(r.guid=a.guid=a.guid||r.guid||t.guid++);var l=s.match(/^([\w:-]*)\s*(.*)$/),h=l[1]+o.eventNamespace,c=l[2];c?n.on(h,c,r):i.on(h,r)})},_off:function(e,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.off(i).off(i),this.bindings=t(this.bindings.not(e).get()),this.focusable=t(this.focusable.not(e).get()),this.hoverable=t(this.hoverable.not(e).get())},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){this._addClass(t(e.currentTarget),null,"ui-state-hover")},mouseleave:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){this._addClass(t(e.currentTarget),null,"ui-state-focus")},focusout:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}}),t.widget,function(){function e(t,e,i){return[parseFloat(t[0])*(u.test(t[0])?e/100:1),parseFloat(t[1])*(u.test(t[1])?i/100:1)]}function i(e,i){return parseInt(t.css(e,i),10)||0}function s(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}var n,o=Math.max,a=Math.abs,r=/left|center|right/,l=/top|center|bottom/,h=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,u=/%$/,d=t.fn.position;t.position={scrollbarWidth:function(){if(void 0!==n)return n;var e,i,s=t("
    "),o=s.children()[0];return t("body").append(s),e=o.offsetWidth,s.css("overflow","scroll"),i=o.offsetWidth,e===i&&(i=s[0].clientWidth),s.remove(),n=e-i},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.widthi?"left":e>0?"right":"center",vertical:0>r?"top":s>0?"bottom":"middle"};h>p&&p>a(e+i)&&(u.horizontal="center"),c>f&&f>a(s+r)&&(u.vertical="middle"),u.important=o(a(e),a(i))>o(a(s),a(r))?"horizontal":"vertical",n.using.call(this,t,u)}),l.offset(t.extend(C,{using:r}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=t.left-e.collisionPosition.marginLeft,l=n-r,h=r+e.collisionWidth-a-n;e.collisionWidth>a?l>0&&0>=h?(i=t.left+l+e.collisionWidth-a-n,t.left+=l-i):t.left=h>0&&0>=l?n:l>h?n+a-e.collisionWidth:n:l>0?t.left+=l:h>0?t.left-=h:t.left=o(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,a=e.within.height,r=t.top-e.collisionPosition.marginTop,l=n-r,h=r+e.collisionHeight-a-n;e.collisionHeight>a?l>0&&0>=h?(i=t.top+l+e.collisionHeight-a-n,t.top+=l-i):t.top=h>0&&0>=l?n:l>h?n+a-e.collisionHeight:n:l>0?t.top+=l:h>0?t.top-=h:t.top=o(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,o=n.offset.left+n.scrollLeft,r=n.width,l=n.isWindow?n.scrollLeft:n.offset.left,h=t.left-e.collisionPosition.marginLeft,c=h-l,u=h+e.collisionWidth-r-l,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-r-o,(0>i||a(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-l,(s>0||u>a(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,o=n.offset.top+n.scrollTop,r=n.height,l=n.isWindow?n.scrollTop:n.offset.top,h=t.top-e.collisionPosition.marginTop,c=h-l,u=h+e.collisionHeight-r-l,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-r-o,(0>s||a(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-l,(i>0||u>a(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}}}(),t.ui.position,t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(i){return!!t.data(i,e)}}):function(e,i,s){return!!t.data(e,s[3])}}),t.fn.extend({disableSelection:function(){var t="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}}(),enableSelection:function(){return this.off(".ui-disableSelection")}}),t.ui.focusable=function(i,s){var n,o,a,r,l,h=i.nodeName.toLowerCase();return"area"===h?(n=i.parentNode,o=n.name,i.href&&o&&"map"===n.nodeName.toLowerCase()?(a=t("img[usemap='#"+o+"']"),a.length>0&&a.is(":visible")):!1):(/^(input|select|textarea|button|object)$/.test(h)?(r=!i.disabled,r&&(l=t(i).closest("fieldset")[0],l&&(r=!l.disabled))):r="a"===h?i.href||s:s,r&&t(i).is(":visible")&&e(t(i)))},t.extend(t.expr[":"],{focusable:function(e){return t.ui.focusable(e,null!=t.attr(e,"tabindex"))}}),t.ui.focusable,t.fn.form=function(){return"string"==typeof this[0].form?this.closest("form"):t(this[0].form)},t.ui.formResetMixin={_formResetHandler:function(){var e=t(this);setTimeout(function(){var i=e.data("ui-form-reset-instances");t.each(i,function(){this.refresh()})})},_bindFormResetHandler:function(){if(this.form=this.element.form(),this.form.length){var t=this.form.data("ui-form-reset-instances")||[];t.length||this.form.on("reset.ui-form-reset",this._formResetHandler),t.push(this),this.form.data("ui-form-reset-instances",t)}},_unbindFormResetHandler:function(){if(this.form.length){var e=this.form.data("ui-form-reset-instances");e.splice(t.inArray(this,e),1),e.length?this.form.data("ui-form-reset-instances",e):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset")}}},"1.7"===t.fn.jquery.substring(0,3)&&(t.each(["Width","Height"],function(e,i){function s(e,i,s,o){return t.each(n,function(){i-=parseFloat(t.css(e,"padding"+this))||0,s&&(i-=parseFloat(t.css(e,"border"+this+"Width"))||0),o&&(i-=parseFloat(t.css(e,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],o=i.toLowerCase(),a={innerWidth:t.fn.innerWidth,innerHeight:t.fn.innerHeight,outerWidth:t.fn.outerWidth,outerHeight:t.fn.outerHeight};t.fn["inner"+i]=function(e){return void 0===e?a["inner"+i].call(this):this.each(function(){t(this).css(o,s(this,e)+"px")})},t.fn["outer"+i]=function(e,n){return"number"!=typeof e?a["outer"+i].call(this,e):this.each(function(){t(this).css(o,s(this,e,!0,n)+"px")})}}),t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38},t.ui.escapeSelector=function(){var t=/([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g;return function(e){return e.replace(t,"\\$1")}}(),t.fn.labels=function(){var e,i,s,n,o;return this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(n=this.eq(0).parents("label"),s=this.attr("id"),s&&(e=this.eq(0).parents().last(),o=e.add(e.length?e.siblings():this.siblings()),i="label[for='"+t.ui.escapeSelector(s)+"']",n=n.add(o.find(i).addBack(i))),this.pushStack(n))},t.fn.scrollParent=function(e){var i=this.css("position"),s="absolute"===i,n=e?/(auto|scroll|hidden)/:/(auto|scroll)/,o=this.parents().filter(function(){var e=t(this);return s&&"static"===e.css("position")?!1:n.test(e.css("overflow")+e.css("overflow-y")+e.css("overflow-x"))}).eq(0);return"fixed"!==i&&o.length?o:t(this[0].ownerDocument||document)},t.extend(t.expr[":"],{tabbable:function(e){var i=t.attr(e,"tabindex"),s=null!=i;return(!s||i>=0)&&t.ui.focusable(e,s)}}),t.fn.extend({uniqueId:function(){var t=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++t)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&t(this).removeAttr("id")})}})}); \ No newline at end of file diff --git a/SplunkAppForWazuh/appserver/static/js/libs/moment.js b/SplunkAppForWazuh/appserver/static/js/libs/moment.js new file mode 100644 index 000000000..1b129716a --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/libs/moment.js @@ -0,0 +1,4602 @@ +//! moment.js + +;(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + global.moment = factory() +}(this, (function () { 'use strict'; + + var hookCallback; + + function hooks () { + return hookCallback.apply(null, arguments); + } + + // This is done to register the method called with moment() + // without creating circular dependencies. + function setHookCallback (callback) { + hookCallback = callback; + } + + function isArray(input) { + return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]'; + } + + function isObject(input) { + // IE8 will treat undefined and null as object if it wasn't for + // input != null + return input != null && Object.prototype.toString.call(input) === '[object Object]'; + } + + function isObjectEmpty(obj) { + if (Object.getOwnPropertyNames) { + return (Object.getOwnPropertyNames(obj).length === 0); + } else { + var k; + for (k in obj) { + if (obj.hasOwnProperty(k)) { + return false; + } + } + return true; + } + } + + function isUndefined(input) { + return input === void 0; + } + + function isNumber(input) { + return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]'; + } + + function isDate(input) { + return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; + } + + function map(arr, fn) { + var res = [], i; + for (i = 0; i < arr.length; ++i) { + res.push(fn(arr[i], i)); + } + return res; + } + + function hasOwnProp(a, b) { + return Object.prototype.hasOwnProperty.call(a, b); + } + + function extend(a, b) { + for (var i in b) { + if (hasOwnProp(b, i)) { + a[i] = b[i]; + } + } + + if (hasOwnProp(b, 'toString')) { + a.toString = b.toString; + } + + if (hasOwnProp(b, 'valueOf')) { + a.valueOf = b.valueOf; + } + + return a; + } + + function createUTC (input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, true).utc(); + } + + function defaultParsingFlags() { + // We need to deep clone this object. + return { + empty : false, + unusedTokens : [], + unusedInput : [], + overflow : -2, + charsLeftOver : 0, + nullInput : false, + invalidMonth : null, + invalidFormat : false, + userInvalidated : false, + iso : false, + parsedDateParts : [], + meridiem : null, + rfc2822 : false, + weekdayMismatch : false + }; + } + + function getParsingFlags(m) { + if (m._pf == null) { + m._pf = defaultParsingFlags(); + } + return m._pf; + } + + var some; + if (Array.prototype.some) { + some = Array.prototype.some; + } else { + some = function (fun) { + var t = Object(this); + var len = t.length >>> 0; + + for (var i = 0; i < len; i++) { + if (i in t && fun.call(this, t[i], i, t)) { + return true; + } + } + + return false; + }; + } + + function isValid(m) { + if (m._isValid == null) { + var flags = getParsingFlags(m); + var parsedParts = some.call(flags.parsedDateParts, function (i) { + return i != null; + }); + var isNowValid = !isNaN(m._d.getTime()) && + flags.overflow < 0 && + !flags.empty && + !flags.invalidMonth && + !flags.invalidWeekday && + !flags.weekdayMismatch && + !flags.nullInput && + !flags.invalidFormat && + !flags.userInvalidated && + (!flags.meridiem || (flags.meridiem && parsedParts)); + + if (m._strict) { + isNowValid = isNowValid && + flags.charsLeftOver === 0 && + flags.unusedTokens.length === 0 && + flags.bigHour === undefined; + } + + if (Object.isFrozen == null || !Object.isFrozen(m)) { + m._isValid = isNowValid; + } + else { + return isNowValid; + } + } + return m._isValid; + } + + function createInvalid (flags) { + var m = createUTC(NaN); + if (flags != null) { + extend(getParsingFlags(m), flags); + } + else { + getParsingFlags(m).userInvalidated = true; + } + + return m; + } + + // Plugins that add properties should also add the key here (null value), + // so we can properly clone ourselves. + var momentProperties = hooks.momentProperties = []; + + function copyConfig(to, from) { + var i, prop, val; + + if (!isUndefined(from._isAMomentObject)) { + to._isAMomentObject = from._isAMomentObject; + } + if (!isUndefined(from._i)) { + to._i = from._i; + } + if (!isUndefined(from._f)) { + to._f = from._f; + } + if (!isUndefined(from._l)) { + to._l = from._l; + } + if (!isUndefined(from._strict)) { + to._strict = from._strict; + } + if (!isUndefined(from._tzm)) { + to._tzm = from._tzm; + } + if (!isUndefined(from._isUTC)) { + to._isUTC = from._isUTC; + } + if (!isUndefined(from._offset)) { + to._offset = from._offset; + } + if (!isUndefined(from._pf)) { + to._pf = getParsingFlags(from); + } + if (!isUndefined(from._locale)) { + to._locale = from._locale; + } + + if (momentProperties.length > 0) { + for (i = 0; i < momentProperties.length; i++) { + prop = momentProperties[i]; + val = from[prop]; + if (!isUndefined(val)) { + to[prop] = val; + } + } + } + + return to; + } + + var updateInProgress = false; + + // Moment prototype object + function Moment(config) { + copyConfig(this, config); + this._d = new Date(config._d != null ? config._d.getTime() : NaN); + if (!this.isValid()) { + this._d = new Date(NaN); + } + // Prevent infinite loop in case updateOffset creates new moment + // objects. + if (updateInProgress === false) { + updateInProgress = true; + hooks.updateOffset(this); + updateInProgress = false; + } + } + + function isMoment (obj) { + return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); + } + + function absFloor (number) { + if (number < 0) { + // -0 -> 0 + return Math.ceil(number) || 0; + } else { + return Math.floor(number); + } + } + + function toInt(argumentForCoercion) { + var coercedNumber = +argumentForCoercion, + value = 0; + + if (coercedNumber !== 0 && isFinite(coercedNumber)) { + value = absFloor(coercedNumber); + } + + return value; + } + + // compare two arrays, return the number of differences + function compareArrays(array1, array2, dontConvert) { + var len = Math.min(array1.length, array2.length), + lengthDiff = Math.abs(array1.length - array2.length), + diffs = 0, + i; + for (i = 0; i < len; i++) { + if ((dontConvert && array1[i] !== array2[i]) || + (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { + diffs++; + } + } + return diffs + lengthDiff; + } + + function warn(msg) { + if (hooks.suppressDeprecationWarnings === false && + (typeof console !== 'undefined') && console.warn) { + console.warn('Deprecation warning: ' + msg); + } + } + + function deprecate(msg, fn) { + var firstTime = true; + + return extend(function () { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(null, msg); + } + if (firstTime) { + var args = []; + var arg; + for (var i = 0; i < arguments.length; i++) { + arg = ''; + if (typeof arguments[i] === 'object') { + arg += '\n[' + i + '] '; + for (var key in arguments[0]) { + arg += key + ': ' + arguments[0][key] + ', '; + } + arg = arg.slice(0, -2); // Remove trailing comma and space + } else { + arg = arguments[i]; + } + args.push(arg); + } + warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack); + firstTime = false; + } + return fn.apply(this, arguments); + }, fn); + } + + var deprecations = {}; + + function deprecateSimple(name, msg) { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(name, msg); + } + if (!deprecations[name]) { + warn(msg); + deprecations[name] = true; + } + } + + hooks.suppressDeprecationWarnings = false; + hooks.deprecationHandler = null; + + function isFunction(input) { + return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; + } + + function set (config) { + var prop, i; + for (i in config) { + prop = config[i]; + if (isFunction(prop)) { + this[i] = prop; + } else { + this['_' + i] = prop; + } + } + this._config = config; + // Lenient ordinal parsing accepts just a number in addition to + // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. + // TODO: Remove "ordinalParse" fallback in next major release. + this._dayOfMonthOrdinalParseLenient = new RegExp( + (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + + '|' + (/\d{1,2}/).source); + } + + function mergeConfigs(parentConfig, childConfig) { + var res = extend({}, parentConfig), prop; + for (prop in childConfig) { + if (hasOwnProp(childConfig, prop)) { + if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { + res[prop] = {}; + extend(res[prop], parentConfig[prop]); + extend(res[prop], childConfig[prop]); + } else if (childConfig[prop] != null) { + res[prop] = childConfig[prop]; + } else { + delete res[prop]; + } + } + } + for (prop in parentConfig) { + if (hasOwnProp(parentConfig, prop) && + !hasOwnProp(childConfig, prop) && + isObject(parentConfig[prop])) { + // make sure changes to properties don't modify parent config + res[prop] = extend({}, res[prop]); + } + } + return res; + } + + function Locale(config) { + if (config != null) { + this.set(config); + } + } + + var keys; + + if (Object.keys) { + keys = Object.keys; + } else { + keys = function (obj) { + var i, res = []; + for (i in obj) { + if (hasOwnProp(obj, i)) { + res.push(i); + } + } + return res; + }; + } + + var defaultCalendar = { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' + }; + + function calendar (key, mom, now) { + var output = this._calendar[key] || this._calendar['sameElse']; + return isFunction(output) ? output.call(mom, now) : output; + } + + var defaultLongDateFormat = { + LTS : 'h:mm:ss A', + LT : 'h:mm A', + L : 'MM/DD/YYYY', + LL : 'MMMM D, YYYY', + LLL : 'MMMM D, YYYY h:mm A', + LLLL : 'dddd, MMMM D, YYYY h:mm A' + }; + + function longDateFormat (key) { + var format = this._longDateFormat[key], + formatUpper = this._longDateFormat[key.toUpperCase()]; + + if (format || !formatUpper) { + return format; + } + + this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) { + return val.slice(1); + }); + + return this._longDateFormat[key]; + } + + var defaultInvalidDate = 'Invalid date'; + + function invalidDate () { + return this._invalidDate; + } + + var defaultOrdinal = '%d'; + var defaultDayOfMonthOrdinalParse = /\d{1,2}/; + + function ordinal (number) { + return this._ordinal.replace('%d', number); + } + + var defaultRelativeTime = { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + ss : '%d seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' + }; + + function relativeTime (number, withoutSuffix, string, isFuture) { + var output = this._relativeTime[string]; + return (isFunction(output)) ? + output(number, withoutSuffix, string, isFuture) : + output.replace(/%d/i, number); + } + + function pastFuture (diff, output) { + var format = this._relativeTime[diff > 0 ? 'future' : 'past']; + return isFunction(format) ? format(output) : format.replace(/%s/i, output); + } + + var aliases = {}; + + function addUnitAlias (unit, shorthand) { + var lowerCase = unit.toLowerCase(); + aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; + } + + function normalizeUnits(units) { + return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; + } + + function normalizeObjectUnits(inputObject) { + var normalizedInput = {}, + normalizedProp, + prop; + + for (prop in inputObject) { + if (hasOwnProp(inputObject, prop)) { + normalizedProp = normalizeUnits(prop); + if (normalizedProp) { + normalizedInput[normalizedProp] = inputObject[prop]; + } + } + } + + return normalizedInput; + } + + var priorities = {}; + + function addUnitPriority(unit, priority) { + priorities[unit] = priority; + } + + function getPrioritizedUnits(unitsObj) { + var units = []; + for (var u in unitsObj) { + units.push({unit: u, priority: priorities[u]}); + } + units.sort(function (a, b) { + return a.priority - b.priority; + }); + return units; + } + + function zeroFill(number, targetLength, forceSign) { + var absNumber = '' + Math.abs(number), + zerosToFill = targetLength - absNumber.length, + sign = number >= 0; + return (sign ? (forceSign ? '+' : '') : '-') + + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; + } + + var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; + + var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; + + var formatFunctions = {}; + + var formatTokenFunctions = {}; + + // token: 'M' + // padded: ['MM', 2] + // ordinal: 'Mo' + // callback: function () { this.month() + 1 } + function addFormatToken (token, padded, ordinal, callback) { + var func = callback; + if (typeof callback === 'string') { + func = function () { + return this[callback](); + }; + } + if (token) { + formatTokenFunctions[token] = func; + } + if (padded) { + formatTokenFunctions[padded[0]] = function () { + return zeroFill(func.apply(this, arguments), padded[1], padded[2]); + }; + } + if (ordinal) { + formatTokenFunctions[ordinal] = function () { + return this.localeData().ordinal(func.apply(this, arguments), token); + }; + } + } + + function removeFormattingTokens(input) { + if (input.match(/\[[\s\S]/)) { + return input.replace(/^\[|\]$/g, ''); + } + return input.replace(/\\/g, ''); + } + + function makeFormatFunction(format) { + var array = format.match(formattingTokens), i, length; + + for (i = 0, length = array.length; i < length; i++) { + if (formatTokenFunctions[array[i]]) { + array[i] = formatTokenFunctions[array[i]]; + } else { + array[i] = removeFormattingTokens(array[i]); + } + } + + return function (mom) { + var output = '', i; + for (i = 0; i < length; i++) { + output += isFunction(array[i]) ? array[i].call(mom, format) : array[i]; + } + return output; + }; + } + + // format date using native date object + function formatMoment(m, format) { + if (!m.isValid()) { + return m.localeData().invalidDate(); + } + + format = expandFormat(format, m.localeData()); + formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); + + return formatFunctions[format](m); + } + + function expandFormat(format, locale) { + var i = 5; + + function replaceLongDateFormatTokens(input) { + return locale.longDateFormat(input) || input; + } + + localFormattingTokens.lastIndex = 0; + while (i >= 0 && localFormattingTokens.test(format)) { + format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); + localFormattingTokens.lastIndex = 0; + i -= 1; + } + + return format; + } + + var match1 = /\d/; // 0 - 9 + var match2 = /\d\d/; // 00 - 99 + var match3 = /\d{3}/; // 000 - 999 + var match4 = /\d{4}/; // 0000 - 9999 + var match6 = /[+-]?\d{6}/; // -999999 - 999999 + var match1to2 = /\d\d?/; // 0 - 99 + var match3to4 = /\d\d\d\d?/; // 999 - 9999 + var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 + var match1to3 = /\d{1,3}/; // 0 - 999 + var match1to4 = /\d{1,4}/; // 0 - 9999 + var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 + + var matchUnsigned = /\d+/; // 0 - inf + var matchSigned = /[+-]?\d+/; // -inf - inf + + var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z + var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z + + var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 + + // any word (or two) characters or numbers including two/three word month in arabic. + // includes scottish gaelic two word and hyphenated months + var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i; + + var regexes = {}; + + function addRegexToken (token, regex, strictRegex) { + regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { + return (isStrict && strictRegex) ? strictRegex : regex; + }; + } + + function getParseRegexForToken (token, config) { + if (!hasOwnProp(regexes, token)) { + return new RegExp(unescapeFormat(token)); + } + + return regexes[token](config._strict, config._locale); + } + + // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript + function unescapeFormat(s) { + return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { + return p1 || p2 || p3 || p4; + })); + } + + function regexEscape(s) { + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); + } + + var tokens = {}; + + function addParseToken (token, callback) { + var i, func = callback; + if (typeof token === 'string') { + token = [token]; + } + if (isNumber(callback)) { + func = function (input, array) { + array[callback] = toInt(input); + }; + } + for (i = 0; i < token.length; i++) { + tokens[token[i]] = func; + } + } + + function addWeekParseToken (token, callback) { + addParseToken(token, function (input, array, config, token) { + config._w = config._w || {}; + callback(input, config._w, config, token); + }); + } + + function addTimeToArrayFromToken(token, input, config) { + if (input != null && hasOwnProp(tokens, token)) { + tokens[token](input, config._a, config, token); + } + } + + var YEAR = 0; + var MONTH = 1; + var DATE = 2; + var HOUR = 3; + var MINUTE = 4; + var SECOND = 5; + var MILLISECOND = 6; + var WEEK = 7; + var WEEKDAY = 8; + + // FORMATTING + + addFormatToken('Y', 0, 0, function () { + var y = this.year(); + return y <= 9999 ? '' + y : '+' + y; + }); + + addFormatToken(0, ['YY', 2], 0, function () { + return this.year() % 100; + }); + + addFormatToken(0, ['YYYY', 4], 0, 'year'); + addFormatToken(0, ['YYYYY', 5], 0, 'year'); + addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); + + // ALIASES + + addUnitAlias('year', 'y'); + + // PRIORITIES + + addUnitPriority('year', 1); + + // PARSING + + addRegexToken('Y', matchSigned); + addRegexToken('YY', match1to2, match2); + addRegexToken('YYYY', match1to4, match4); + addRegexToken('YYYYY', match1to6, match6); + addRegexToken('YYYYYY', match1to6, match6); + + addParseToken(['YYYYY', 'YYYYYY'], YEAR); + addParseToken('YYYY', function (input, array) { + array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); + }); + addParseToken('YY', function (input, array) { + array[YEAR] = hooks.parseTwoDigitYear(input); + }); + addParseToken('Y', function (input, array) { + array[YEAR] = parseInt(input, 10); + }); + + // HELPERS + + function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; + } + + function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + } + + // HOOKS + + hooks.parseTwoDigitYear = function (input) { + return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); + }; + + // MOMENTS + + var getSetYear = makeGetSet('FullYear', true); + + function getIsLeapYear () { + return isLeapYear(this.year()); + } + + function makeGetSet (unit, keepTime) { + return function (value) { + if (value != null) { + set$1(this, unit, value); + hooks.updateOffset(this, keepTime); + return this; + } else { + return get(this, unit); + } + }; + } + + function get (mom, unit) { + return mom.isValid() ? + mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; + } + + function set$1 (mom, unit, value) { + if (mom.isValid() && !isNaN(value)) { + if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) { + mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month())); + } + else { + mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); + } + } + } + + // MOMENTS + + function stringGet (units) { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](); + } + return this; + } + + + function stringSet (units, value) { + if (typeof units === 'object') { + units = normalizeObjectUnits(units); + var prioritized = getPrioritizedUnits(units); + for (var i = 0; i < prioritized.length; i++) { + this[prioritized[i].unit](units[prioritized[i].unit]); + } + } else { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](value); + } + } + return this; + } + + function mod(n, x) { + return ((n % x) + x) % x; + } + + var indexOf; + + if (Array.prototype.indexOf) { + indexOf = Array.prototype.indexOf; + } else { + indexOf = function (o) { + // I know + var i; + for (i = 0; i < this.length; ++i) { + if (this[i] === o) { + return i; + } + } + return -1; + }; + } + + function daysInMonth(year, month) { + if (isNaN(year) || isNaN(month)) { + return NaN; + } + var modMonth = mod(month, 12); + year += (month - modMonth) / 12; + return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2); + } + + // FORMATTING + + addFormatToken('M', ['MM', 2], 'Mo', function () { + return this.month() + 1; + }); + + addFormatToken('MMM', 0, 0, function (format) { + return this.localeData().monthsShort(this, format); + }); + + addFormatToken('MMMM', 0, 0, function (format) { + return this.localeData().months(this, format); + }); + + // ALIASES + + addUnitAlias('month', 'M'); + + // PRIORITY + + addUnitPriority('month', 8); + + // PARSING + + addRegexToken('M', match1to2); + addRegexToken('MM', match1to2, match2); + addRegexToken('MMM', function (isStrict, locale) { + return locale.monthsShortRegex(isStrict); + }); + addRegexToken('MMMM', function (isStrict, locale) { + return locale.monthsRegex(isStrict); + }); + + addParseToken(['M', 'MM'], function (input, array) { + array[MONTH] = toInt(input) - 1; + }); + + addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { + var month = config._locale.monthsParse(input, token, config._strict); + // if we didn't find a month name, mark the date as invalid. + if (month != null) { + array[MONTH] = month; + } else { + getParsingFlags(config).invalidMonth = input; + } + }); + + // LOCALES + + var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/; + var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); + function localeMonths (m, format) { + if (!m) { + return isArray(this._months) ? this._months : + this._months['standalone']; + } + return isArray(this._months) ? this._months[m.month()] : + this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()]; + } + + var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); + function localeMonthsShort (m, format) { + if (!m) { + return isArray(this._monthsShort) ? this._monthsShort : + this._monthsShort['standalone']; + } + return isArray(this._monthsShort) ? this._monthsShort[m.month()] : + this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()]; + } + + function handleStrictParse(monthName, format, strict) { + var i, ii, mom, llc = monthName.toLocaleLowerCase(); + if (!this._monthsParse) { + // this is not used + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + for (i = 0; i < 12; ++i) { + mom = createUTC([2000, i]); + this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase(); + this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); + } + } + + if (strict) { + if (format === 'MMM') { + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'MMM') { + ii = indexOf.call(this._shortMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } + } + + function localeMonthsParse (monthName, format, strict) { + var i, mom, regex; + + if (this._monthsParseExact) { + return handleStrictParse.call(this, monthName, format, strict); + } + + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + } + + // TODO: add sorting + // Sorting makes sure if one month (or abbr) is a prefix of another + // see sorting in computeMonthsParse + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + if (strict && !this._longMonthsParse[i]) { + this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); + this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); + } + if (!strict && !this._monthsParse[i]) { + regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); + this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { + return i; + } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { + return i; + } else if (!strict && this._monthsParse[i].test(monthName)) { + return i; + } + } + } + + // MOMENTS + + function setMonth (mom, value) { + var dayOfMonth; + + if (!mom.isValid()) { + // No op + return mom; + } + + if (typeof value === 'string') { + if (/^\d+$/.test(value)) { + value = toInt(value); + } else { + value = mom.localeData().monthsParse(value); + // TODO: Another silent failure? + if (!isNumber(value)) { + return mom; + } + } + } + + dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); + mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); + return mom; + } + + function getSetMonth (value) { + if (value != null) { + setMonth(this, value); + hooks.updateOffset(this, true); + return this; + } else { + return get(this, 'Month'); + } + } + + function getDaysInMonth () { + return daysInMonth(this.year(), this.month()); + } + + var defaultMonthsShortRegex = matchWord; + function monthsShortRegex (isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsShortStrictRegex; + } else { + return this._monthsShortRegex; + } + } else { + if (!hasOwnProp(this, '_monthsShortRegex')) { + this._monthsShortRegex = defaultMonthsShortRegex; + } + return this._monthsShortStrictRegex && isStrict ? + this._monthsShortStrictRegex : this._monthsShortRegex; + } + } + + var defaultMonthsRegex = matchWord; + function monthsRegex (isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsStrictRegex; + } else { + return this._monthsRegex; + } + } else { + if (!hasOwnProp(this, '_monthsRegex')) { + this._monthsRegex = defaultMonthsRegex; + } + return this._monthsStrictRegex && isStrict ? + this._monthsStrictRegex : this._monthsRegex; + } + } + + function computeMonthsParse () { + function cmpLenRev(a, b) { + return b.length - a.length; + } + + var shortPieces = [], longPieces = [], mixedPieces = [], + i, mom; + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + shortPieces.push(this.monthsShort(mom, '')); + longPieces.push(this.months(mom, '')); + mixedPieces.push(this.months(mom, '')); + mixedPieces.push(this.monthsShort(mom, '')); + } + // Sorting makes sure if one month (or abbr) is a prefix of another it + // will match the longer piece. + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + for (i = 0; i < 12; i++) { + shortPieces[i] = regexEscape(shortPieces[i]); + longPieces[i] = regexEscape(longPieces[i]); + } + for (i = 0; i < 24; i++) { + mixedPieces[i] = regexEscape(mixedPieces[i]); + } + + this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._monthsShortRegex = this._monthsRegex; + this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); + this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); + } + + function createDate (y, m, d, h, M, s, ms) { + // can't just apply() to create a date: + // https://stackoverflow.com/q/181348 + var date; + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + date = new Date(y + 400, m, d, h, M, s, ms); + if (isFinite(date.getFullYear())) { + date.setFullYear(y); + } + } else { + date = new Date(y, m, d, h, M, s, ms); + } + + return date; + } + + function createUTCDate (y) { + var date; + // the Date.UTC function remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + var args = Array.prototype.slice.call(arguments); + // preserve leap years using a full 400 year cycle, then reset + args[0] = y + 400; + date = new Date(Date.UTC.apply(null, args)); + if (isFinite(date.getUTCFullYear())) { + date.setUTCFullYear(y); + } + } else { + date = new Date(Date.UTC.apply(null, arguments)); + } + + return date; + } + + // start-of-first-week - start-of-year + function firstWeekOffset(year, dow, doy) { + var // first-week day -- which january is always in the first week (4 for iso, 1 for other) + fwd = 7 + dow - doy, + // first-week day local weekday -- which local weekday is fwd + fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; + + return -fwdlw + fwd - 1; + } + + // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday + function dayOfYearFromWeeks(year, week, weekday, dow, doy) { + var localWeekday = (7 + weekday - dow) % 7, + weekOffset = firstWeekOffset(year, dow, doy), + dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, + resYear, resDayOfYear; + + if (dayOfYear <= 0) { + resYear = year - 1; + resDayOfYear = daysInYear(resYear) + dayOfYear; + } else if (dayOfYear > daysInYear(year)) { + resYear = year + 1; + resDayOfYear = dayOfYear - daysInYear(year); + } else { + resYear = year; + resDayOfYear = dayOfYear; + } + + return { + year: resYear, + dayOfYear: resDayOfYear + }; + } + + function weekOfYear(mom, dow, doy) { + var weekOffset = firstWeekOffset(mom.year(), dow, doy), + week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, + resWeek, resYear; + + if (week < 1) { + resYear = mom.year() - 1; + resWeek = week + weeksInYear(resYear, dow, doy); + } else if (week > weeksInYear(mom.year(), dow, doy)) { + resWeek = week - weeksInYear(mom.year(), dow, doy); + resYear = mom.year() + 1; + } else { + resYear = mom.year(); + resWeek = week; + } + + return { + week: resWeek, + year: resYear + }; + } + + function weeksInYear(year, dow, doy) { + var weekOffset = firstWeekOffset(year, dow, doy), + weekOffsetNext = firstWeekOffset(year + 1, dow, doy); + return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; + } + + // FORMATTING + + addFormatToken('w', ['ww', 2], 'wo', 'week'); + addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); + + // ALIASES + + addUnitAlias('week', 'w'); + addUnitAlias('isoWeek', 'W'); + + // PRIORITIES + + addUnitPriority('week', 5); + addUnitPriority('isoWeek', 5); + + // PARSING + + addRegexToken('w', match1to2); + addRegexToken('ww', match1to2, match2); + addRegexToken('W', match1to2); + addRegexToken('WW', match1to2, match2); + + addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { + week[token.substr(0, 1)] = toInt(input); + }); + + // HELPERS + + // LOCALES + + function localeWeek (mom) { + return weekOfYear(mom, this._week.dow, this._week.doy).week; + } + + var defaultLocaleWeek = { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 6th is the first week of the year. + }; + + function localeFirstDayOfWeek () { + return this._week.dow; + } + + function localeFirstDayOfYear () { + return this._week.doy; + } + + // MOMENTS + + function getSetWeek (input) { + var week = this.localeData().week(this); + return input == null ? week : this.add((input - week) * 7, 'd'); + } + + function getSetISOWeek (input) { + var week = weekOfYear(this, 1, 4).week; + return input == null ? week : this.add((input - week) * 7, 'd'); + } + + // FORMATTING + + addFormatToken('d', 0, 'do', 'day'); + + addFormatToken('dd', 0, 0, function (format) { + return this.localeData().weekdaysMin(this, format); + }); + + addFormatToken('ddd', 0, 0, function (format) { + return this.localeData().weekdaysShort(this, format); + }); + + addFormatToken('dddd', 0, 0, function (format) { + return this.localeData().weekdays(this, format); + }); + + addFormatToken('e', 0, 0, 'weekday'); + addFormatToken('E', 0, 0, 'isoWeekday'); + + // ALIASES + + addUnitAlias('day', 'd'); + addUnitAlias('weekday', 'e'); + addUnitAlias('isoWeekday', 'E'); + + // PRIORITY + addUnitPriority('day', 11); + addUnitPriority('weekday', 11); + addUnitPriority('isoWeekday', 11); + + // PARSING + + addRegexToken('d', match1to2); + addRegexToken('e', match1to2); + addRegexToken('E', match1to2); + addRegexToken('dd', function (isStrict, locale) { + return locale.weekdaysMinRegex(isStrict); + }); + addRegexToken('ddd', function (isStrict, locale) { + return locale.weekdaysShortRegex(isStrict); + }); + addRegexToken('dddd', function (isStrict, locale) { + return locale.weekdaysRegex(isStrict); + }); + + addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { + var weekday = config._locale.weekdaysParse(input, token, config._strict); + // if we didn't get a weekday name, mark the date as invalid + if (weekday != null) { + week.d = weekday; + } else { + getParsingFlags(config).invalidWeekday = input; + } + }); + + addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { + week[token] = toInt(input); + }); + + // HELPERS + + function parseWeekday(input, locale) { + if (typeof input !== 'string') { + return input; + } + + if (!isNaN(input)) { + return parseInt(input, 10); + } + + input = locale.weekdaysParse(input); + if (typeof input === 'number') { + return input; + } + + return null; + } + + function parseIsoWeekday(input, locale) { + if (typeof input === 'string') { + return locale.weekdaysParse(input) % 7 || 7; + } + return isNaN(input) ? null : input; + } + + // LOCALES + function shiftWeekdays (ws, n) { + return ws.slice(n, 7).concat(ws.slice(0, n)); + } + + var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); + function localeWeekdays (m, format) { + var weekdays = isArray(this._weekdays) ? this._weekdays : + this._weekdays[(m && m !== true && this._weekdays.isFormat.test(format)) ? 'format' : 'standalone']; + return (m === true) ? shiftWeekdays(weekdays, this._week.dow) + : (m) ? weekdays[m.day()] : weekdays; + } + + var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); + function localeWeekdaysShort (m) { + return (m === true) ? shiftWeekdays(this._weekdaysShort, this._week.dow) + : (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort; + } + + var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); + function localeWeekdaysMin (m) { + return (m === true) ? shiftWeekdays(this._weekdaysMin, this._week.dow) + : (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin; + } + + function handleStrictParse$1(weekdayName, format, strict) { + var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._shortWeekdaysParse = []; + this._minWeekdaysParse = []; + + for (i = 0; i < 7; ++i) { + mom = createUTC([2000, 1]).day(i); + this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); + this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); + this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); + } + } + + if (strict) { + if (format === 'dddd') { + ii = indexOf.call(this._weekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'dddd') { + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } + } + + function localeWeekdaysParse (weekdayName, format, strict) { + var i, mom, regex; + + if (this._weekdaysParseExact) { + return handleStrictParse$1.call(this, weekdayName, format, strict); + } + + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._minWeekdaysParse = []; + this._shortWeekdaysParse = []; + this._fullWeekdaysParse = []; + } + + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + + mom = createUTC([2000, 1]).day(i); + if (strict && !this._fullWeekdaysParse[i]) { + this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i'); + this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i'); + this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i'); + } + if (!this._weekdaysParse[i]) { + regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); + this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { + return i; + } + } + } + + // MOMENTS + + function getSetDayOfWeek (input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); + if (input != null) { + input = parseWeekday(input, this.localeData()); + return this.add(input - day, 'd'); + } else { + return day; + } + } + + function getSetLocaleDayOfWeek (input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; + return input == null ? weekday : this.add(input - weekday, 'd'); + } + + function getSetISODayOfWeek (input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + + // behaves the same as moment#day except + // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) + // as a setter, sunday should belong to the previous week. + + if (input != null) { + var weekday = parseIsoWeekday(input, this.localeData()); + return this.day(this.day() % 7 ? weekday : weekday - 7); + } else { + return this.day() || 7; + } + } + + var defaultWeekdaysRegex = matchWord; + function weekdaysRegex (isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysStrictRegex; + } else { + return this._weekdaysRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysRegex')) { + this._weekdaysRegex = defaultWeekdaysRegex; + } + return this._weekdaysStrictRegex && isStrict ? + this._weekdaysStrictRegex : this._weekdaysRegex; + } + } + + var defaultWeekdaysShortRegex = matchWord; + function weekdaysShortRegex (isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysShortStrictRegex; + } else { + return this._weekdaysShortRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysShortRegex')) { + this._weekdaysShortRegex = defaultWeekdaysShortRegex; + } + return this._weekdaysShortStrictRegex && isStrict ? + this._weekdaysShortStrictRegex : this._weekdaysShortRegex; + } + } + + var defaultWeekdaysMinRegex = matchWord; + function weekdaysMinRegex (isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysMinStrictRegex; + } else { + return this._weekdaysMinRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysMinRegex')) { + this._weekdaysMinRegex = defaultWeekdaysMinRegex; + } + return this._weekdaysMinStrictRegex && isStrict ? + this._weekdaysMinStrictRegex : this._weekdaysMinRegex; + } + } + + + function computeWeekdaysParse () { + function cmpLenRev(a, b) { + return b.length - a.length; + } + + var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], + i, mom, minp, shortp, longp; + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, 1]).day(i); + minp = this.weekdaysMin(mom, ''); + shortp = this.weekdaysShort(mom, ''); + longp = this.weekdays(mom, ''); + minPieces.push(minp); + shortPieces.push(shortp); + longPieces.push(longp); + mixedPieces.push(minp); + mixedPieces.push(shortp); + mixedPieces.push(longp); + } + // Sorting makes sure if one weekday (or abbr) is a prefix of another it + // will match the longer piece. + minPieces.sort(cmpLenRev); + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + for (i = 0; i < 7; i++) { + shortPieces[i] = regexEscape(shortPieces[i]); + longPieces[i] = regexEscape(longPieces[i]); + mixedPieces[i] = regexEscape(mixedPieces[i]); + } + + this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._weekdaysShortRegex = this._weekdaysRegex; + this._weekdaysMinRegex = this._weekdaysRegex; + + this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); + this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); + this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); + } + + // FORMATTING + + function hFormat() { + return this.hours() % 12 || 12; + } + + function kFormat() { + return this.hours() || 24; + } + + addFormatToken('H', ['HH', 2], 0, 'hour'); + addFormatToken('h', ['hh', 2], 0, hFormat); + addFormatToken('k', ['kk', 2], 0, kFormat); + + addFormatToken('hmm', 0, 0, function () { + return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); + }); + + addFormatToken('hmmss', 0, 0, function () { + return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2); + }); + + addFormatToken('Hmm', 0, 0, function () { + return '' + this.hours() + zeroFill(this.minutes(), 2); + }); + + addFormatToken('Hmmss', 0, 0, function () { + return '' + this.hours() + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2); + }); + + function meridiem (token, lowercase) { + addFormatToken(token, 0, 0, function () { + return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); + }); + } + + meridiem('a', true); + meridiem('A', false); + + // ALIASES + + addUnitAlias('hour', 'h'); + + // PRIORITY + addUnitPriority('hour', 13); + + // PARSING + + function matchMeridiem (isStrict, locale) { + return locale._meridiemParse; + } + + addRegexToken('a', matchMeridiem); + addRegexToken('A', matchMeridiem); + addRegexToken('H', match1to2); + addRegexToken('h', match1to2); + addRegexToken('k', match1to2); + addRegexToken('HH', match1to2, match2); + addRegexToken('hh', match1to2, match2); + addRegexToken('kk', match1to2, match2); + + addRegexToken('hmm', match3to4); + addRegexToken('hmmss', match5to6); + addRegexToken('Hmm', match3to4); + addRegexToken('Hmmss', match5to6); + + addParseToken(['H', 'HH'], HOUR); + addParseToken(['k', 'kk'], function (input, array, config) { + var kInput = toInt(input); + array[HOUR] = kInput === 24 ? 0 : kInput; + }); + addParseToken(['a', 'A'], function (input, array, config) { + config._isPm = config._locale.isPM(input); + config._meridiem = input; + }); + addParseToken(['h', 'hh'], function (input, array, config) { + array[HOUR] = toInt(input); + getParsingFlags(config).bigHour = true; + }); + addParseToken('hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + getParsingFlags(config).bigHour = true; + }); + addParseToken('hmmss', function (input, array, config) { + var pos1 = input.length - 4; + var pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + getParsingFlags(config).bigHour = true; + }); + addParseToken('Hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + }); + addParseToken('Hmmss', function (input, array, config) { + var pos1 = input.length - 4; + var pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + }); + + // LOCALES + + function localeIsPM (input) { + // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays + // Using charAt should be more compatible. + return ((input + '').toLowerCase().charAt(0) === 'p'); + } + + var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; + function localeMeridiem (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'pm' : 'PM'; + } else { + return isLower ? 'am' : 'AM'; + } + } + + + // MOMENTS + + // Setting the hour should keep the time, because the user explicitly + // specified which hour they want. So trying to maintain the same hour (in + // a new timezone) makes sense. Adding/subtracting hours does not follow + // this rule. + var getSetHour = makeGetSet('Hours', true); + + var baseConfig = { + calendar: defaultCalendar, + longDateFormat: defaultLongDateFormat, + invalidDate: defaultInvalidDate, + ordinal: defaultOrdinal, + dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, + relativeTime: defaultRelativeTime, + + months: defaultLocaleMonths, + monthsShort: defaultLocaleMonthsShort, + + week: defaultLocaleWeek, + + weekdays: defaultLocaleWeekdays, + weekdaysMin: defaultLocaleWeekdaysMin, + weekdaysShort: defaultLocaleWeekdaysShort, + + meridiemParse: defaultLocaleMeridiemParse + }; + + // internal storage for locale config files + var locales = {}; + var localeFamilies = {}; + var globalLocale; + + function normalizeLocale(key) { + return key ? key.toLowerCase().replace('_', '-') : key; + } + + // pick the locale from the array + // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each + // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root + function chooseLocale(names) { + var i = 0, j, next, locale, split; + + while (i < names.length) { + split = normalizeLocale(names[i]).split('-'); + j = split.length; + next = normalizeLocale(names[i + 1]); + next = next ? next.split('-') : null; + while (j > 0) { + locale = loadLocale(split.slice(0, j).join('-')); + if (locale) { + return locale; + } + if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { + //the next array item is better than a shallower substring of this one + break; + } + j--; + } + i++; + } + return globalLocale; + } + + function loadLocale(name) { + var oldLocale = null; + // TODO: Find a better way to register and load all the locales in Node + if (!locales[name] && (typeof module !== 'undefined') && + module && module.exports) { + try { + oldLocale = globalLocale._abbr; + var aliasedRequire = require; + aliasedRequire('./locale/' + name); + getSetGlobalLocale(oldLocale); + } catch (e) {} + } + return locales[name]; + } + + // This function will load locale and then set the global locale. If + // no arguments are passed in, it will simply return the current global + // locale key. + function getSetGlobalLocale (key, values) { + var data; + if (key) { + if (isUndefined(values)) { + data = getLocale(key); + } + else { + data = defineLocale(key, values); + } + + if (data) { + // moment.duration._locale = moment._locale = data; + globalLocale = data; + } + else { + if ((typeof console !== 'undefined') && console.warn) { + //warn user if arguments are passed but the locale could not be set + console.warn('Locale ' + key + ' not found. Did you forget to load it?'); + } + } + } + + return globalLocale._abbr; + } + + function defineLocale (name, config) { + if (config !== null) { + var locale, parentConfig = baseConfig; + config.abbr = name; + if (locales[name] != null) { + deprecateSimple('defineLocaleOverride', + 'use moment.updateLocale(localeName, config) to change ' + + 'an existing locale. moment.defineLocale(localeName, ' + + 'config) should only be used for creating a new locale ' + + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'); + parentConfig = locales[name]._config; + } else if (config.parentLocale != null) { + if (locales[config.parentLocale] != null) { + parentConfig = locales[config.parentLocale]._config; + } else { + locale = loadLocale(config.parentLocale); + if (locale != null) { + parentConfig = locale._config; + } else { + if (!localeFamilies[config.parentLocale]) { + localeFamilies[config.parentLocale] = []; + } + localeFamilies[config.parentLocale].push({ + name: name, + config: config + }); + return null; + } + } + } + locales[name] = new Locale(mergeConfigs(parentConfig, config)); + + if (localeFamilies[name]) { + localeFamilies[name].forEach(function (x) { + defineLocale(x.name, x.config); + }); + } + + // backwards compat for now: also set the locale + // make sure we set the locale AFTER all child locales have been + // created, so we won't end up with the child locale set. + getSetGlobalLocale(name); + + + return locales[name]; + } else { + // useful for testing + delete locales[name]; + return null; + } + } + + function updateLocale(name, config) { + if (config != null) { + var locale, tmpLocale, parentConfig = baseConfig; + // MERGE + tmpLocale = loadLocale(name); + if (tmpLocale != null) { + parentConfig = tmpLocale._config; + } + config = mergeConfigs(parentConfig, config); + locale = new Locale(config); + locale.parentLocale = locales[name]; + locales[name] = locale; + + // backwards compat for now: also set the locale + getSetGlobalLocale(name); + } else { + // pass null for config to unupdate, useful for tests + if (locales[name] != null) { + if (locales[name].parentLocale != null) { + locales[name] = locales[name].parentLocale; + } else if (locales[name] != null) { + delete locales[name]; + } + } + } + return locales[name]; + } + + // returns locale data + function getLocale (key) { + var locale; + + if (key && key._locale && key._locale._abbr) { + key = key._locale._abbr; + } + + if (!key) { + return globalLocale; + } + + if (!isArray(key)) { + //short-circuit everything else + locale = loadLocale(key); + if (locale) { + return locale; + } + key = [key]; + } + + return chooseLocale(key); + } + + function listLocales() { + return keys(locales); + } + + function checkOverflow (m) { + var overflow; + var a = m._a; + + if (a && getParsingFlags(m).overflow === -2) { + overflow = + a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : + a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : + a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : + a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : + a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : + a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : + -1; + + if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { + overflow = DATE; + } + if (getParsingFlags(m)._overflowWeeks && overflow === -1) { + overflow = WEEK; + } + if (getParsingFlags(m)._overflowWeekday && overflow === -1) { + overflow = WEEKDAY; + } + + getParsingFlags(m).overflow = overflow; + } + + return m; + } + + // Pick the first defined of two or three arguments. + function defaults(a, b, c) { + if (a != null) { + return a; + } + if (b != null) { + return b; + } + return c; + } + + function currentDateArray(config) { + // hooks is actually the exported moment object + var nowValue = new Date(hooks.now()); + if (config._useUTC) { + return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()]; + } + return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; + } + + // convert an array to a date. + // the array should mirror the parameters below + // note: all values past the year are optional and will default to the lowest possible value. + // [year, month, day , hour, minute, second, millisecond] + function configFromArray (config) { + var i, date, input = [], currentDate, expectedWeekday, yearToUse; + + if (config._d) { + return; + } + + currentDate = currentDateArray(config); + + //compute day of the year from weeks and weekdays + if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { + dayOfYearFromWeekInfo(config); + } + + //if the day of the year is set, figure out what it is + if (config._dayOfYear != null) { + yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); + + if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) { + getParsingFlags(config)._overflowDayOfYear = true; + } + + date = createUTCDate(yearToUse, 0, config._dayOfYear); + config._a[MONTH] = date.getUTCMonth(); + config._a[DATE] = date.getUTCDate(); + } + + // Default to current date. + // * if no year, month, day of month are given, default to today + // * if day of month is given, default month and year + // * if month is given, default only year + // * if year is given, don't default anything + for (i = 0; i < 3 && config._a[i] == null; ++i) { + config._a[i] = input[i] = currentDate[i]; + } + + // Zero out whatever was not defaulted, including time + for (; i < 7; i++) { + config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; + } + + // Check for 24:00:00.000 + if (config._a[HOUR] === 24 && + config._a[MINUTE] === 0 && + config._a[SECOND] === 0 && + config._a[MILLISECOND] === 0) { + config._nextDay = true; + config._a[HOUR] = 0; + } + + config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); + expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); + + // Apply timezone offset from input. The actual utcOffset can be changed + // with parseZone. + if (config._tzm != null) { + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + } + + if (config._nextDay) { + config._a[HOUR] = 24; + } + + // check for mismatching day of week + if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) { + getParsingFlags(config).weekdayMismatch = true; + } + } + + function dayOfYearFromWeekInfo(config) { + var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow; + + w = config._w; + if (w.GG != null || w.W != null || w.E != null) { + dow = 1; + doy = 4; + + // TODO: We need to take the current isoWeekYear, but that depends on + // how we interpret now (local, utc, fixed offset). So create + // a now version of current config (take local/utc/offset flags, and + // create now). + weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year); + week = defaults(w.W, 1); + weekday = defaults(w.E, 1); + if (weekday < 1 || weekday > 7) { + weekdayOverflow = true; + } + } else { + dow = config._locale._week.dow; + doy = config._locale._week.doy; + + var curWeek = weekOfYear(createLocal(), dow, doy); + + weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); + + // Default to current week. + week = defaults(w.w, curWeek.week); + + if (w.d != null) { + // weekday -- low day numbers are considered next week + weekday = w.d; + if (weekday < 0 || weekday > 6) { + weekdayOverflow = true; + } + } else if (w.e != null) { + // local weekday -- counting starts from beginning of week + weekday = w.e + dow; + if (w.e < 0 || w.e > 6) { + weekdayOverflow = true; + } + } else { + // default to beginning of week + weekday = dow; + } + } + if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { + getParsingFlags(config)._overflowWeeks = true; + } else if (weekdayOverflow != null) { + getParsingFlags(config)._overflowWeekday = true; + } else { + temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); + config._a[YEAR] = temp.year; + config._dayOfYear = temp.dayOfYear; + } + } + + // iso 8601 regex + // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) + var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; + var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; + + var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/; + + var isoDates = [ + ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], + ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], + ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], + ['GGGG-[W]WW', /\d{4}-W\d\d/, false], + ['YYYY-DDD', /\d{4}-\d{3}/], + ['YYYY-MM', /\d{4}-\d\d/, false], + ['YYYYYYMMDD', /[+-]\d{10}/], + ['YYYYMMDD', /\d{8}/], + // YYYYMM is NOT allowed by the standard + ['GGGG[W]WWE', /\d{4}W\d{3}/], + ['GGGG[W]WW', /\d{4}W\d{2}/, false], + ['YYYYDDD', /\d{7}/] + ]; + + // iso time formats and regexes + var isoTimes = [ + ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], + ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], + ['HH:mm:ss', /\d\d:\d\d:\d\d/], + ['HH:mm', /\d\d:\d\d/], + ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], + ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], + ['HHmmss', /\d\d\d\d\d\d/], + ['HHmm', /\d\d\d\d/], + ['HH', /\d\d/] + ]; + + var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; + + // date from iso format + function configFromISO(config) { + var i, l, + string = config._i, + match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), + allowTime, dateFormat, timeFormat, tzFormat; + + if (match) { + getParsingFlags(config).iso = true; + + for (i = 0, l = isoDates.length; i < l; i++) { + if (isoDates[i][1].exec(match[1])) { + dateFormat = isoDates[i][0]; + allowTime = isoDates[i][2] !== false; + break; + } + } + if (dateFormat == null) { + config._isValid = false; + return; + } + if (match[3]) { + for (i = 0, l = isoTimes.length; i < l; i++) { + if (isoTimes[i][1].exec(match[3])) { + // match[2] should be 'T' or space + timeFormat = (match[2] || ' ') + isoTimes[i][0]; + break; + } + } + if (timeFormat == null) { + config._isValid = false; + return; + } + } + if (!allowTime && timeFormat != null) { + config._isValid = false; + return; + } + if (match[4]) { + if (tzRegex.exec(match[4])) { + tzFormat = 'Z'; + } else { + config._isValid = false; + return; + } + } + config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); + configFromStringAndFormat(config); + } else { + config._isValid = false; + } + } + + // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 + var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/; + + function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { + var result = [ + untruncateYear(yearStr), + defaultLocaleMonthsShort.indexOf(monthStr), + parseInt(dayStr, 10), + parseInt(hourStr, 10), + parseInt(minuteStr, 10) + ]; + + if (secondStr) { + result.push(parseInt(secondStr, 10)); + } + + return result; + } + + function untruncateYear(yearStr) { + var year = parseInt(yearStr, 10); + if (year <= 49) { + return 2000 + year; + } else if (year <= 999) { + return 1900 + year; + } + return year; + } + + function preprocessRFC2822(s) { + // Remove comments and folding whitespace and replace multiple-spaces with a single space + return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, ''); + } + + function checkWeekday(weekdayStr, parsedInput, config) { + if (weekdayStr) { + // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check. + var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), + weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay(); + if (weekdayProvided !== weekdayActual) { + getParsingFlags(config).weekdayMismatch = true; + config._isValid = false; + return false; + } + } + return true; + } + + var obsOffsets = { + UT: 0, + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60 + }; + + function calculateOffset(obsOffset, militaryOffset, numOffset) { + if (obsOffset) { + return obsOffsets[obsOffset]; + } else if (militaryOffset) { + // the only allowed military tz is Z + return 0; + } else { + var hm = parseInt(numOffset, 10); + var m = hm % 100, h = (hm - m) / 100; + return h * 60 + m; + } + } + + // date and time from ref 2822 format + function configFromRFC2822(config) { + var match = rfc2822.exec(preprocessRFC2822(config._i)); + if (match) { + var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]); + if (!checkWeekday(match[1], parsedArray, config)) { + return; + } + + config._a = parsedArray; + config._tzm = calculateOffset(match[8], match[9], match[10]); + + config._d = createUTCDate.apply(null, config._a); + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + + getParsingFlags(config).rfc2822 = true; + } else { + config._isValid = false; + } + } + + // date from iso format or fallback + function configFromString(config) { + var matched = aspNetJsonRegex.exec(config._i); + + if (matched !== null) { + config._d = new Date(+matched[1]); + return; + } + + configFromISO(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } + + configFromRFC2822(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } + + // Final attempt, use Input Fallback + hooks.createFromInputFallback(config); + } + + hooks.createFromInputFallback = deprecate( + 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + + 'discouraged and will be removed in an upcoming major release. Please refer to ' + + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', + function (config) { + config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); + } + ); + + // constant that refers to the ISO standard + hooks.ISO_8601 = function () {}; + + // constant that refers to the RFC 2822 form + hooks.RFC_2822 = function () {}; + + // date from string and format string + function configFromStringAndFormat(config) { + // TODO: Move this to another part of the creation flow to prevent circular deps + if (config._f === hooks.ISO_8601) { + configFromISO(config); + return; + } + if (config._f === hooks.RFC_2822) { + configFromRFC2822(config); + return; + } + config._a = []; + getParsingFlags(config).empty = true; + + // This array is used to make a Date, either with `new Date` or `Date.UTC` + var string = '' + config._i, + i, parsedInput, tokens, token, skipped, + stringLength = string.length, + totalParsedInputLength = 0; + + tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; + + for (i = 0; i < tokens.length; i++) { + token = tokens[i]; + parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; + // console.log('token', token, 'parsedInput', parsedInput, + // 'regex', getParseRegexForToken(token, config)); + if (parsedInput) { + skipped = string.substr(0, string.indexOf(parsedInput)); + if (skipped.length > 0) { + getParsingFlags(config).unusedInput.push(skipped); + } + string = string.slice(string.indexOf(parsedInput) + parsedInput.length); + totalParsedInputLength += parsedInput.length; + } + // don't parse if it's not a known token + if (formatTokenFunctions[token]) { + if (parsedInput) { + getParsingFlags(config).empty = false; + } + else { + getParsingFlags(config).unusedTokens.push(token); + } + addTimeToArrayFromToken(token, parsedInput, config); + } + else if (config._strict && !parsedInput) { + getParsingFlags(config).unusedTokens.push(token); + } + } + + // add remaining unparsed input length to the string + getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; + if (string.length > 0) { + getParsingFlags(config).unusedInput.push(string); + } + + // clear _12h flag if hour is <= 12 + if (config._a[HOUR] <= 12 && + getParsingFlags(config).bigHour === true && + config._a[HOUR] > 0) { + getParsingFlags(config).bigHour = undefined; + } + + getParsingFlags(config).parsedDateParts = config._a.slice(0); + getParsingFlags(config).meridiem = config._meridiem; + // handle meridiem + config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); + + configFromArray(config); + checkOverflow(config); + } + + + function meridiemFixWrap (locale, hour, meridiem) { + var isPm; + + if (meridiem == null) { + // nothing to do + return hour; + } + if (locale.meridiemHour != null) { + return locale.meridiemHour(hour, meridiem); + } else if (locale.isPM != null) { + // Fallback + isPm = locale.isPM(meridiem); + if (isPm && hour < 12) { + hour += 12; + } + if (!isPm && hour === 12) { + hour = 0; + } + return hour; + } else { + // this is not supposed to happen + return hour; + } + } + + // date from string and array of format strings + function configFromStringAndArray(config) { + var tempConfig, + bestMoment, + + scoreToBeat, + i, + currentScore; + + if (config._f.length === 0) { + getParsingFlags(config).invalidFormat = true; + config._d = new Date(NaN); + return; + } + + for (i = 0; i < config._f.length; i++) { + currentScore = 0; + tempConfig = copyConfig({}, config); + if (config._useUTC != null) { + tempConfig._useUTC = config._useUTC; + } + tempConfig._f = config._f[i]; + configFromStringAndFormat(tempConfig); + + if (!isValid(tempConfig)) { + continue; + } + + // if there is any input that was not parsed add a penalty for that format + currentScore += getParsingFlags(tempConfig).charsLeftOver; + + //or tokens + currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; + + getParsingFlags(tempConfig).score = currentScore; + + if (scoreToBeat == null || currentScore < scoreToBeat) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + } + } + + extend(config, bestMoment || tempConfig); + } + + function configFromObject(config) { + if (config._d) { + return; + } + + var i = normalizeObjectUnits(config._i); + config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) { + return obj && parseInt(obj, 10); + }); + + configFromArray(config); + } + + function createFromConfig (config) { + var res = new Moment(checkOverflow(prepareConfig(config))); + if (res._nextDay) { + // Adding is smart enough around DST + res.add(1, 'd'); + res._nextDay = undefined; + } + + return res; + } + + function prepareConfig (config) { + var input = config._i, + format = config._f; + + config._locale = config._locale || getLocale(config._l); + + if (input === null || (format === undefined && input === '')) { + return createInvalid({nullInput: true}); + } + + if (typeof input === 'string') { + config._i = input = config._locale.preparse(input); + } + + if (isMoment(input)) { + return new Moment(checkOverflow(input)); + } else if (isDate(input)) { + config._d = input; + } else if (isArray(format)) { + configFromStringAndArray(config); + } else if (format) { + configFromStringAndFormat(config); + } else { + configFromInput(config); + } + + if (!isValid(config)) { + config._d = null; + } + + return config; + } + + function configFromInput(config) { + var input = config._i; + if (isUndefined(input)) { + config._d = new Date(hooks.now()); + } else if (isDate(input)) { + config._d = new Date(input.valueOf()); + } else if (typeof input === 'string') { + configFromString(config); + } else if (isArray(input)) { + config._a = map(input.slice(0), function (obj) { + return parseInt(obj, 10); + }); + configFromArray(config); + } else if (isObject(input)) { + configFromObject(config); + } else if (isNumber(input)) { + // from milliseconds + config._d = new Date(input); + } else { + hooks.createFromInputFallback(config); + } + } + + function createLocalOrUTC (input, format, locale, strict, isUTC) { + var c = {}; + + if (locale === true || locale === false) { + strict = locale; + locale = undefined; + } + + if ((isObject(input) && isObjectEmpty(input)) || + (isArray(input) && input.length === 0)) { + input = undefined; + } + // object construction must be done this way. + // https://github.com/moment/moment/issues/1423 + c._isAMomentObject = true; + c._useUTC = c._isUTC = isUTC; + c._l = locale; + c._i = input; + c._f = format; + c._strict = strict; + + return createFromConfig(c); + } + + function createLocal (input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, false); + } + + var prototypeMin = deprecate( + 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other < this ? this : other; + } else { + return createInvalid(); + } + } + ); + + var prototypeMax = deprecate( + 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other > this ? this : other; + } else { + return createInvalid(); + } + } + ); + + // Pick a moment m from moments so that m[fn](other) is true for all + // other. This relies on the function fn to be transitive. + // + // moments should either be an array of moment objects or an array, whose + // first element is an array of moment objects. + function pickBy(fn, moments) { + var res, i; + if (moments.length === 1 && isArray(moments[0])) { + moments = moments[0]; + } + if (!moments.length) { + return createLocal(); + } + res = moments[0]; + for (i = 1; i < moments.length; ++i) { + if (!moments[i].isValid() || moments[i][fn](res)) { + res = moments[i]; + } + } + return res; + } + + // TODO: Use [].sort instead? + function min () { + var args = [].slice.call(arguments, 0); + + return pickBy('isBefore', args); + } + + function max () { + var args = [].slice.call(arguments, 0); + + return pickBy('isAfter', args); + } + + var now = function () { + return Date.now ? Date.now() : +(new Date()); + }; + + var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond']; + + function isDurationValid(m) { + for (var key in m) { + if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) { + return false; + } + } + + var unitHasDecimal = false; + for (var i = 0; i < ordering.length; ++i) { + if (m[ordering[i]]) { + if (unitHasDecimal) { + return false; // only allow non-integers for smallest unit + } + if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { + unitHasDecimal = true; + } + } + } + + return true; + } + + function isValid$1() { + return this._isValid; + } + + function createInvalid$1() { + return createDuration(NaN); + } + + function Duration (duration) { + var normalizedInput = normalizeObjectUnits(duration), + years = normalizedInput.year || 0, + quarters = normalizedInput.quarter || 0, + months = normalizedInput.month || 0, + weeks = normalizedInput.week || normalizedInput.isoWeek || 0, + days = normalizedInput.day || 0, + hours = normalizedInput.hour || 0, + minutes = normalizedInput.minute || 0, + seconds = normalizedInput.second || 0, + milliseconds = normalizedInput.millisecond || 0; + + this._isValid = isDurationValid(normalizedInput); + + // representation for dateAddRemove + this._milliseconds = +milliseconds + + seconds * 1e3 + // 1000 + minutes * 6e4 + // 1000 * 60 + hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 + // Because of dateAddRemove treats 24 hours as different from a + // day when working around DST, we need to store them separately + this._days = +days + + weeks * 7; + // It is impossible to translate months into days without knowing + // which months you are are talking about, so we have to store + // it separately. + this._months = +months + + quarters * 3 + + years * 12; + + this._data = {}; + + this._locale = getLocale(); + + this._bubble(); + } + + function isDuration (obj) { + return obj instanceof Duration; + } + + function absRound (number) { + if (number < 0) { + return Math.round(-1 * number) * -1; + } else { + return Math.round(number); + } + } + + // FORMATTING + + function offset (token, separator) { + addFormatToken(token, 0, 0, function () { + var offset = this.utcOffset(); + var sign = '+'; + if (offset < 0) { + offset = -offset; + sign = '-'; + } + return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); + }); + } + + offset('Z', ':'); + offset('ZZ', ''); + + // PARSING + + addRegexToken('Z', matchShortOffset); + addRegexToken('ZZ', matchShortOffset); + addParseToken(['Z', 'ZZ'], function (input, array, config) { + config._useUTC = true; + config._tzm = offsetFromString(matchShortOffset, input); + }); + + // HELPERS + + // timezone chunker + // '+10:00' > ['10', '00'] + // '-1530' > ['-15', '30'] + var chunkOffset = /([\+\-]|\d\d)/gi; + + function offsetFromString(matcher, string) { + var matches = (string || '').match(matcher); + + if (matches === null) { + return null; + } + + var chunk = matches[matches.length - 1] || []; + var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; + var minutes = +(parts[1] * 60) + toInt(parts[2]); + + return minutes === 0 ? + 0 : + parts[0] === '+' ? minutes : -minutes; + } + + // Return a moment from input, that is local/utc/zone equivalent to model. + function cloneWithOffset(input, model) { + var res, diff; + if (model._isUTC) { + res = model.clone(); + diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); + // Use low-level api, because this fn is low-level api. + res._d.setTime(res._d.valueOf() + diff); + hooks.updateOffset(res, false); + return res; + } else { + return createLocal(input).local(); + } + } + + function getDateOffset (m) { + // On Firefox.24 Date#getTimezoneOffset returns a floating point. + // https://github.com/moment/moment/pull/1871 + return -Math.round(m._d.getTimezoneOffset() / 15) * 15; + } + + // HOOKS + + // This function will be called whenever a moment is mutated. + // It is intended to keep the offset in sync with the timezone. + hooks.updateOffset = function () {}; + + // MOMENTS + + // keepLocalTime = true means only change the timezone, without + // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> + // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset + // +0200, so we adjust the time as needed, to be valid. + // + // Keeping the time actually adds/subtracts (one hour) + // from the actual represented time. That is why we call updateOffset + // a second time. In case it wants us to change the offset again + // _changeInProgress == true case, then we have to adjust, because + // there is no such time in the given timezone. + function getSetOffset (input, keepLocalTime, keepMinutes) { + var offset = this._offset || 0, + localAdjust; + if (!this.isValid()) { + return input != null ? this : NaN; + } + if (input != null) { + if (typeof input === 'string') { + input = offsetFromString(matchShortOffset, input); + if (input === null) { + return this; + } + } else if (Math.abs(input) < 16 && !keepMinutes) { + input = input * 60; + } + if (!this._isUTC && keepLocalTime) { + localAdjust = getDateOffset(this); + } + this._offset = input; + this._isUTC = true; + if (localAdjust != null) { + this.add(localAdjust, 'm'); + } + if (offset !== input) { + if (!keepLocalTime || this._changeInProgress) { + addSubtract(this, createDuration(input - offset, 'm'), 1, false); + } else if (!this._changeInProgress) { + this._changeInProgress = true; + hooks.updateOffset(this, true); + this._changeInProgress = null; + } + } + return this; + } else { + return this._isUTC ? offset : getDateOffset(this); + } + } + + function getSetZone (input, keepLocalTime) { + if (input != null) { + if (typeof input !== 'string') { + input = -input; + } + + this.utcOffset(input, keepLocalTime); + + return this; + } else { + return -this.utcOffset(); + } + } + + function setOffsetToUTC (keepLocalTime) { + return this.utcOffset(0, keepLocalTime); + } + + function setOffsetToLocal (keepLocalTime) { + if (this._isUTC) { + this.utcOffset(0, keepLocalTime); + this._isUTC = false; + + if (keepLocalTime) { + this.subtract(getDateOffset(this), 'm'); + } + } + return this; + } + + function setOffsetToParsedOffset () { + if (this._tzm != null) { + this.utcOffset(this._tzm, false, true); + } else if (typeof this._i === 'string') { + var tZone = offsetFromString(matchOffset, this._i); + if (tZone != null) { + this.utcOffset(tZone); + } + else { + this.utcOffset(0, true); + } + } + return this; + } + + function hasAlignedHourOffset (input) { + if (!this.isValid()) { + return false; + } + input = input ? createLocal(input).utcOffset() : 0; + + return (this.utcOffset() - input) % 60 === 0; + } + + function isDaylightSavingTime () { + return ( + this.utcOffset() > this.clone().month(0).utcOffset() || + this.utcOffset() > this.clone().month(5).utcOffset() + ); + } + + function isDaylightSavingTimeShifted () { + if (!isUndefined(this._isDSTShifted)) { + return this._isDSTShifted; + } + + var c = {}; + + copyConfig(c, this); + c = prepareConfig(c); + + if (c._a) { + var other = c._isUTC ? createUTC(c._a) : createLocal(c._a); + this._isDSTShifted = this.isValid() && + compareArrays(c._a, other.toArray()) > 0; + } else { + this._isDSTShifted = false; + } + + return this._isDSTShifted; + } + + function isLocal () { + return this.isValid() ? !this._isUTC : false; + } + + function isUtcOffset () { + return this.isValid() ? this._isUTC : false; + } + + function isUtc () { + return this.isValid() ? this._isUTC && this._offset === 0 : false; + } + + // ASP.NET json date format regex + var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; + + // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html + // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere + // and further modified to allow for strings containing both week and day + var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; + + function createDuration (input, key) { + var duration = input, + // matching against regexp is expensive, do it on demand + match = null, + sign, + ret, + diffRes; + + if (isDuration(input)) { + duration = { + ms : input._milliseconds, + d : input._days, + M : input._months + }; + } else if (isNumber(input)) { + duration = {}; + if (key) { + duration[key] = input; + } else { + duration.milliseconds = input; + } + } else if (!!(match = aspNetRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : 0, + d : toInt(match[DATE]) * sign, + h : toInt(match[HOUR]) * sign, + m : toInt(match[MINUTE]) * sign, + s : toInt(match[SECOND]) * sign, + ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match + }; + } else if (!!(match = isoRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : parseIso(match[2], sign), + M : parseIso(match[3], sign), + w : parseIso(match[4], sign), + d : parseIso(match[5], sign), + h : parseIso(match[6], sign), + m : parseIso(match[7], sign), + s : parseIso(match[8], sign) + }; + } else if (duration == null) {// checks for null or undefined + duration = {}; + } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { + diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); + + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } + + ret = new Duration(duration); + + if (isDuration(input) && hasOwnProp(input, '_locale')) { + ret._locale = input._locale; + } + + return ret; + } + + createDuration.fn = Duration.prototype; + createDuration.invalid = createInvalid$1; + + function parseIso (inp, sign) { + // We'd normally use ~~inp for this, but unfortunately it also + // converts floats to ints. + // inp may be undefined, so careful calling replace on it. + var res = inp && parseFloat(inp.replace(',', '.')); + // apply sign while we're at it + return (isNaN(res) ? 0 : res) * sign; + } + + function positiveMomentsDifference(base, other) { + var res = {}; + + res.months = other.month() - base.month() + + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, 'M').isAfter(other)) { + --res.months; + } + + res.milliseconds = +other - +(base.clone().add(res.months, 'M')); + + return res; + } + + function momentsDifference(base, other) { + var res; + if (!(base.isValid() && other.isValid())) { + return {milliseconds: 0, months: 0}; + } + + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; + } + + return res; + } + + // TODO: remove 'name' arg after deprecation is removed + function createAdder(direction, name) { + return function (val, period) { + var dur, tmp; + //invert the arguments, but complain about it + if (period !== null && !isNaN(+period)) { + deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'); + tmp = val; val = period; period = tmp; + } + + val = typeof val === 'string' ? +val : val; + dur = createDuration(val, period); + addSubtract(this, dur, direction); + return this; + }; + } + + function addSubtract (mom, duration, isAdding, updateOffset) { + var milliseconds = duration._milliseconds, + days = absRound(duration._days), + months = absRound(duration._months); + + if (!mom.isValid()) { + // No op + return; + } + + updateOffset = updateOffset == null ? true : updateOffset; + + if (months) { + setMonth(mom, get(mom, 'Month') + months * isAdding); + } + if (days) { + set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); + } + if (milliseconds) { + mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); + } + if (updateOffset) { + hooks.updateOffset(mom, days || months); + } + } + + var add = createAdder(1, 'add'); + var subtract = createAdder(-1, 'subtract'); + + function getCalendarFormat(myMoment, now) { + var diff = myMoment.diff(now, 'days', true); + return diff < -6 ? 'sameElse' : + diff < -1 ? 'lastWeek' : + diff < 0 ? 'lastDay' : + diff < 1 ? 'sameDay' : + diff < 2 ? 'nextDay' : + diff < 7 ? 'nextWeek' : 'sameElse'; + } + + function calendar$1 (time, formats) { + // We want to compare the start of today, vs this. + // Getting start-of-today depends on whether we're local/utc/offset or not. + var now = time || createLocal(), + sod = cloneWithOffset(now, this).startOf('day'), + format = hooks.calendarFormat(this, sod) || 'sameElse'; + + var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); + + return this.format(output || this.localeData().calendar(format, this, createLocal(now))); + } + + function clone () { + return new Moment(this); + } + + function isAfter (input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() > localInput.valueOf(); + } else { + return localInput.valueOf() < this.clone().startOf(units).valueOf(); + } + } + + function isBefore (input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() < localInput.valueOf(); + } else { + return this.clone().endOf(units).valueOf() < localInput.valueOf(); + } + } + + function isBetween (from, to, units, inclusivity) { + var localFrom = isMoment(from) ? from : createLocal(from), + localTo = isMoment(to) ? to : createLocal(to); + if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { + return false; + } + inclusivity = inclusivity || '()'; + return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && + (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units)); + } + + function isSame (input, units) { + var localInput = isMoment(input) ? input : createLocal(input), + inputMs; + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() === localInput.valueOf(); + } else { + inputMs = localInput.valueOf(); + return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); + } + } + + function isSameOrAfter (input, units) { + return this.isSame(input, units) || this.isAfter(input, units); + } + + function isSameOrBefore (input, units) { + return this.isSame(input, units) || this.isBefore(input, units); + } + + function diff (input, units, asFloat) { + var that, + zoneDelta, + output; + + if (!this.isValid()) { + return NaN; + } + + that = cloneWithOffset(input, this); + + if (!that.isValid()) { + return NaN; + } + + zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; + + units = normalizeUnits(units); + + switch (units) { + case 'year': output = monthDiff(this, that) / 12; break; + case 'month': output = monthDiff(this, that); break; + case 'quarter': output = monthDiff(this, that) / 3; break; + case 'second': output = (this - that) / 1e3; break; // 1000 + case 'minute': output = (this - that) / 6e4; break; // 1000 * 60 + case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60 + case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst + case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst + default: output = this - that; + } + + return asFloat ? output : absFloor(output); + } + + function monthDiff (a, b) { + // difference in months + var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), + // b is in (anchor - 1 month, anchor + 1 month) + anchor = a.clone().add(wholeMonthDiff, 'months'), + anchor2, adjust; + + if (b - anchor < 0) { + anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor - anchor2); + } else { + anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor2 - anchor); + } + + //check for negative zero, return zero if negative zero + return -(wholeMonthDiff + adjust) || 0; + } + + hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; + hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; + + function toString () { + return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); + } + + function toISOString(keepOffset) { + if (!this.isValid()) { + return null; + } + var utc = keepOffset !== true; + var m = utc ? this.clone().utc() : this; + if (m.year() < 0 || m.year() > 9999) { + return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'); + } + if (isFunction(Date.prototype.toISOString)) { + // native implementation is ~50x faster, use it when we can + if (utc) { + return this.toDate().toISOString(); + } else { + return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z')); + } + } + return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'); + } + + /** + * Return a human readable representation of a moment that can + * also be evaluated to get a new moment which is the same + * + * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects + */ + function inspect () { + if (!this.isValid()) { + return 'moment.invalid(/* ' + this._i + ' */)'; + } + var func = 'moment'; + var zone = ''; + if (!this.isLocal()) { + func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; + zone = 'Z'; + } + var prefix = '[' + func + '("]'; + var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY'; + var datetime = '-MM-DD[T]HH:mm:ss.SSS'; + var suffix = zone + '[")]'; + + return this.format(prefix + year + datetime + suffix); + } + + function format (inputString) { + if (!inputString) { + inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; + } + var output = formatMoment(this, inputString); + return this.localeData().postformat(output); + } + + function from (time, withoutSuffix) { + if (this.isValid() && + ((isMoment(time) && time.isValid()) || + createLocal(time).isValid())) { + return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } + } + + function fromNow (withoutSuffix) { + return this.from(createLocal(), withoutSuffix); + } + + function to (time, withoutSuffix) { + if (this.isValid() && + ((isMoment(time) && time.isValid()) || + createLocal(time).isValid())) { + return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } + } + + function toNow (withoutSuffix) { + return this.to(createLocal(), withoutSuffix); + } + + // If passed a locale key, it will set the locale for this + // instance. Otherwise, it will return the locale configuration + // variables for this instance. + function locale (key) { + var newLocaleData; + + if (key === undefined) { + return this._locale._abbr; + } else { + newLocaleData = getLocale(key); + if (newLocaleData != null) { + this._locale = newLocaleData; + } + return this; + } + } + + var lang = deprecate( + 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', + function (key) { + if (key === undefined) { + return this.localeData(); + } else { + return this.locale(key); + } + } + ); + + function localeData () { + return this._locale; + } + + var MS_PER_SECOND = 1000; + var MS_PER_MINUTE = 60 * MS_PER_SECOND; + var MS_PER_HOUR = 60 * MS_PER_MINUTE; + var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; + + // actual modulo - handles negative numbers (for dates before 1970): + function mod$1(dividend, divisor) { + return (dividend % divisor + divisor) % divisor; + } + + function localStartOfDate(y, m, d) { + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + return new Date(y + 400, m, d) - MS_PER_400_YEARS; + } else { + return new Date(y, m, d).valueOf(); + } + } + + function utcStartOfDate(y, m, d) { + // Date.UTC remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS; + } else { + return Date.UTC(y, m, d); + } + } + + function startOf (units) { + var time; + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond' || !this.isValid()) { + return this; + } + + var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + + switch (units) { + case 'year': + time = startOfDate(this.year(), 0, 1); + break; + case 'quarter': + time = startOfDate(this.year(), this.month() - this.month() % 3, 1); + break; + case 'month': + time = startOfDate(this.year(), this.month(), 1); + break; + case 'week': + time = startOfDate(this.year(), this.month(), this.date() - this.weekday()); + break; + case 'isoWeek': + time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1)); + break; + case 'day': + case 'date': + time = startOfDate(this.year(), this.month(), this.date()); + break; + case 'hour': + time = this._d.valueOf(); + time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR); + break; + case 'minute': + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_MINUTE); + break; + case 'second': + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_SECOND); + break; + } + + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; + } + + function endOf (units) { + var time; + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond' || !this.isValid()) { + return this; + } + + var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + + switch (units) { + case 'year': + time = startOfDate(this.year() + 1, 0, 1) - 1; + break; + case 'quarter': + time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1; + break; + case 'month': + time = startOfDate(this.year(), this.month() + 1, 1) - 1; + break; + case 'week': + time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1; + break; + case 'isoWeek': + time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1; + break; + case 'day': + case 'date': + time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; + break; + case 'hour': + time = this._d.valueOf(); + time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1; + break; + case 'minute': + time = this._d.valueOf(); + time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; + break; + case 'second': + time = this._d.valueOf(); + time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; + break; + } + + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; + } + + function valueOf () { + return this._d.valueOf() - ((this._offset || 0) * 60000); + } + + function unix () { + return Math.floor(this.valueOf() / 1000); + } + + function toDate () { + return new Date(this.valueOf()); + } + + function toArray () { + var m = this; + return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; + } + + function toObject () { + var m = this; + return { + years: m.year(), + months: m.month(), + date: m.date(), + hours: m.hours(), + minutes: m.minutes(), + seconds: m.seconds(), + milliseconds: m.milliseconds() + }; + } + + function toJSON () { + // new Date(NaN).toJSON() === null + return this.isValid() ? this.toISOString() : null; + } + + function isValid$2 () { + return isValid(this); + } + + function parsingFlags () { + return extend({}, getParsingFlags(this)); + } + + function invalidAt () { + return getParsingFlags(this).overflow; + } + + function creationData() { + return { + input: this._i, + format: this._f, + locale: this._locale, + isUTC: this._isUTC, + strict: this._strict + }; + } + + // FORMATTING + + addFormatToken(0, ['gg', 2], 0, function () { + return this.weekYear() % 100; + }); + + addFormatToken(0, ['GG', 2], 0, function () { + return this.isoWeekYear() % 100; + }); + + function addWeekYearFormatToken (token, getter) { + addFormatToken(0, [token, token.length], 0, getter); + } + + addWeekYearFormatToken('gggg', 'weekYear'); + addWeekYearFormatToken('ggggg', 'weekYear'); + addWeekYearFormatToken('GGGG', 'isoWeekYear'); + addWeekYearFormatToken('GGGGG', 'isoWeekYear'); + + // ALIASES + + addUnitAlias('weekYear', 'gg'); + addUnitAlias('isoWeekYear', 'GG'); + + // PRIORITY + + addUnitPriority('weekYear', 1); + addUnitPriority('isoWeekYear', 1); + + + // PARSING + + addRegexToken('G', matchSigned); + addRegexToken('g', matchSigned); + addRegexToken('GG', match1to2, match2); + addRegexToken('gg', match1to2, match2); + addRegexToken('GGGG', match1to4, match4); + addRegexToken('gggg', match1to4, match4); + addRegexToken('GGGGG', match1to6, match6); + addRegexToken('ggggg', match1to6, match6); + + addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { + week[token.substr(0, 2)] = toInt(input); + }); + + addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { + week[token] = hooks.parseTwoDigitYear(input); + }); + + // MOMENTS + + function getSetWeekYear (input) { + return getSetWeekYearHelper.call(this, + input, + this.week(), + this.weekday(), + this.localeData()._week.dow, + this.localeData()._week.doy); + } + + function getSetISOWeekYear (input) { + return getSetWeekYearHelper.call(this, + input, this.isoWeek(), this.isoWeekday(), 1, 4); + } + + function getISOWeeksInYear () { + return weeksInYear(this.year(), 1, 4); + } + + function getWeeksInYear () { + var weekInfo = this.localeData()._week; + return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); + } + + function getSetWeekYearHelper(input, week, weekday, dow, doy) { + var weeksTarget; + if (input == null) { + return weekOfYear(this, dow, doy).year; + } else { + weeksTarget = weeksInYear(input, dow, doy); + if (week > weeksTarget) { + week = weeksTarget; + } + return setWeekAll.call(this, input, week, weekday, dow, doy); + } + } + + function setWeekAll(weekYear, week, weekday, dow, doy) { + var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), + date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); + + this.year(date.getUTCFullYear()); + this.month(date.getUTCMonth()); + this.date(date.getUTCDate()); + return this; + } + + // FORMATTING + + addFormatToken('Q', 0, 'Qo', 'quarter'); + + // ALIASES + + addUnitAlias('quarter', 'Q'); + + // PRIORITY + + addUnitPriority('quarter', 7); + + // PARSING + + addRegexToken('Q', match1); + addParseToken('Q', function (input, array) { + array[MONTH] = (toInt(input) - 1) * 3; + }); + + // MOMENTS + + function getSetQuarter (input) { + return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); + } + + // FORMATTING + + addFormatToken('D', ['DD', 2], 'Do', 'date'); + + // ALIASES + + addUnitAlias('date', 'D'); + + // PRIORITY + addUnitPriority('date', 9); + + // PARSING + + addRegexToken('D', match1to2); + addRegexToken('DD', match1to2, match2); + addRegexToken('Do', function (isStrict, locale) { + // TODO: Remove "ordinalParse" fallback in next major release. + return isStrict ? + (locale._dayOfMonthOrdinalParse || locale._ordinalParse) : + locale._dayOfMonthOrdinalParseLenient; + }); + + addParseToken(['D', 'DD'], DATE); + addParseToken('Do', function (input, array) { + array[DATE] = toInt(input.match(match1to2)[0]); + }); + + // MOMENTS + + var getSetDayOfMonth = makeGetSet('Date', true); + + // FORMATTING + + addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); + + // ALIASES + + addUnitAlias('dayOfYear', 'DDD'); + + // PRIORITY + addUnitPriority('dayOfYear', 4); + + // PARSING + + addRegexToken('DDD', match1to3); + addRegexToken('DDDD', match3); + addParseToken(['DDD', 'DDDD'], function (input, array, config) { + config._dayOfYear = toInt(input); + }); + + // HELPERS + + // MOMENTS + + function getSetDayOfYear (input) { + var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; + return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); + } + + // FORMATTING + + addFormatToken('m', ['mm', 2], 0, 'minute'); + + // ALIASES + + addUnitAlias('minute', 'm'); + + // PRIORITY + + addUnitPriority('minute', 14); + + // PARSING + + addRegexToken('m', match1to2); + addRegexToken('mm', match1to2, match2); + addParseToken(['m', 'mm'], MINUTE); + + // MOMENTS + + var getSetMinute = makeGetSet('Minutes', false); + + // FORMATTING + + addFormatToken('s', ['ss', 2], 0, 'second'); + + // ALIASES + + addUnitAlias('second', 's'); + + // PRIORITY + + addUnitPriority('second', 15); + + // PARSING + + addRegexToken('s', match1to2); + addRegexToken('ss', match1to2, match2); + addParseToken(['s', 'ss'], SECOND); + + // MOMENTS + + var getSetSecond = makeGetSet('Seconds', false); + + // FORMATTING + + addFormatToken('S', 0, 0, function () { + return ~~(this.millisecond() / 100); + }); + + addFormatToken(0, ['SS', 2], 0, function () { + return ~~(this.millisecond() / 10); + }); + + addFormatToken(0, ['SSS', 3], 0, 'millisecond'); + addFormatToken(0, ['SSSS', 4], 0, function () { + return this.millisecond() * 10; + }); + addFormatToken(0, ['SSSSS', 5], 0, function () { + return this.millisecond() * 100; + }); + addFormatToken(0, ['SSSSSS', 6], 0, function () { + return this.millisecond() * 1000; + }); + addFormatToken(0, ['SSSSSSS', 7], 0, function () { + return this.millisecond() * 10000; + }); + addFormatToken(0, ['SSSSSSSS', 8], 0, function () { + return this.millisecond() * 100000; + }); + addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { + return this.millisecond() * 1000000; + }); + + + // ALIASES + + addUnitAlias('millisecond', 'ms'); + + // PRIORITY + + addUnitPriority('millisecond', 16); + + // PARSING + + addRegexToken('S', match1to3, match1); + addRegexToken('SS', match1to3, match2); + addRegexToken('SSS', match1to3, match3); + + var token; + for (token = 'SSSS'; token.length <= 9; token += 'S') { + addRegexToken(token, matchUnsigned); + } + + function parseMs(input, array) { + array[MILLISECOND] = toInt(('0.' + input) * 1000); + } + + for (token = 'S'; token.length <= 9; token += 'S') { + addParseToken(token, parseMs); + } + // MOMENTS + + var getSetMillisecond = makeGetSet('Milliseconds', false); + + // FORMATTING + + addFormatToken('z', 0, 0, 'zoneAbbr'); + addFormatToken('zz', 0, 0, 'zoneName'); + + // MOMENTS + + function getZoneAbbr () { + return this._isUTC ? 'UTC' : ''; + } + + function getZoneName () { + return this._isUTC ? 'Coordinated Universal Time' : ''; + } + + var proto = Moment.prototype; + + proto.add = add; + proto.calendar = calendar$1; + proto.clone = clone; + proto.diff = diff; + proto.endOf = endOf; + proto.format = format; + proto.from = from; + proto.fromNow = fromNow; + proto.to = to; + proto.toNow = toNow; + proto.get = stringGet; + proto.invalidAt = invalidAt; + proto.isAfter = isAfter; + proto.isBefore = isBefore; + proto.isBetween = isBetween; + proto.isSame = isSame; + proto.isSameOrAfter = isSameOrAfter; + proto.isSameOrBefore = isSameOrBefore; + proto.isValid = isValid$2; + proto.lang = lang; + proto.locale = locale; + proto.localeData = localeData; + proto.max = prototypeMax; + proto.min = prototypeMin; + proto.parsingFlags = parsingFlags; + proto.set = stringSet; + proto.startOf = startOf; + proto.subtract = subtract; + proto.toArray = toArray; + proto.toObject = toObject; + proto.toDate = toDate; + proto.toISOString = toISOString; + proto.inspect = inspect; + proto.toJSON = toJSON; + proto.toString = toString; + proto.unix = unix; + proto.valueOf = valueOf; + proto.creationData = creationData; + proto.year = getSetYear; + proto.isLeapYear = getIsLeapYear; + proto.weekYear = getSetWeekYear; + proto.isoWeekYear = getSetISOWeekYear; + proto.quarter = proto.quarters = getSetQuarter; + proto.month = getSetMonth; + proto.daysInMonth = getDaysInMonth; + proto.week = proto.weeks = getSetWeek; + proto.isoWeek = proto.isoWeeks = getSetISOWeek; + proto.weeksInYear = getWeeksInYear; + proto.isoWeeksInYear = getISOWeeksInYear; + proto.date = getSetDayOfMonth; + proto.day = proto.days = getSetDayOfWeek; + proto.weekday = getSetLocaleDayOfWeek; + proto.isoWeekday = getSetISODayOfWeek; + proto.dayOfYear = getSetDayOfYear; + proto.hour = proto.hours = getSetHour; + proto.minute = proto.minutes = getSetMinute; + proto.second = proto.seconds = getSetSecond; + proto.millisecond = proto.milliseconds = getSetMillisecond; + proto.utcOffset = getSetOffset; + proto.utc = setOffsetToUTC; + proto.local = setOffsetToLocal; + proto.parseZone = setOffsetToParsedOffset; + proto.hasAlignedHourOffset = hasAlignedHourOffset; + proto.isDST = isDaylightSavingTime; + proto.isLocal = isLocal; + proto.isUtcOffset = isUtcOffset; + proto.isUtc = isUtc; + proto.isUTC = isUtc; + proto.zoneAbbr = getZoneAbbr; + proto.zoneName = getZoneName; + proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); + proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); + proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); + proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone); + proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted); + + function createUnix (input) { + return createLocal(input * 1000); + } + + function createInZone () { + return createLocal.apply(null, arguments).parseZone(); + } + + function preParsePostFormat (string) { + return string; + } + + var proto$1 = Locale.prototype; + + proto$1.calendar = calendar; + proto$1.longDateFormat = longDateFormat; + proto$1.invalidDate = invalidDate; + proto$1.ordinal = ordinal; + proto$1.preparse = preParsePostFormat; + proto$1.postformat = preParsePostFormat; + proto$1.relativeTime = relativeTime; + proto$1.pastFuture = pastFuture; + proto$1.set = set; + + proto$1.months = localeMonths; + proto$1.monthsShort = localeMonthsShort; + proto$1.monthsParse = localeMonthsParse; + proto$1.monthsRegex = monthsRegex; + proto$1.monthsShortRegex = monthsShortRegex; + proto$1.week = localeWeek; + proto$1.firstDayOfYear = localeFirstDayOfYear; + proto$1.firstDayOfWeek = localeFirstDayOfWeek; + + proto$1.weekdays = localeWeekdays; + proto$1.weekdaysMin = localeWeekdaysMin; + proto$1.weekdaysShort = localeWeekdaysShort; + proto$1.weekdaysParse = localeWeekdaysParse; + + proto$1.weekdaysRegex = weekdaysRegex; + proto$1.weekdaysShortRegex = weekdaysShortRegex; + proto$1.weekdaysMinRegex = weekdaysMinRegex; + + proto$1.isPM = localeIsPM; + proto$1.meridiem = localeMeridiem; + + function get$1 (format, index, field, setter) { + var locale = getLocale(); + var utc = createUTC().set(setter, index); + return locale[field](utc, format); + } + + function listMonthsImpl (format, index, field) { + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + + if (index != null) { + return get$1(format, index, field, 'month'); + } + + var i; + var out = []; + for (i = 0; i < 12; i++) { + out[i] = get$1(format, i, field, 'month'); + } + return out; + } + + // () + // (5) + // (fmt, 5) + // (fmt) + // (true) + // (true, 5) + // (true, fmt, 5) + // (true, fmt) + function listWeekdaysImpl (localeSorted, format, index, field) { + if (typeof localeSorted === 'boolean') { + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + } else { + format = localeSorted; + index = format; + localeSorted = false; + + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + } + + var locale = getLocale(), + shift = localeSorted ? locale._week.dow : 0; + + if (index != null) { + return get$1(format, (index + shift) % 7, field, 'day'); + } + + var i; + var out = []; + for (i = 0; i < 7; i++) { + out[i] = get$1(format, (i + shift) % 7, field, 'day'); + } + return out; + } + + function listMonths (format, index) { + return listMonthsImpl(format, index, 'months'); + } + + function listMonthsShort (format, index) { + return listMonthsImpl(format, index, 'monthsShort'); + } + + function listWeekdays (localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); + } + + function listWeekdaysShort (localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); + } + + function listWeekdaysMin (localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); + } + + getSetGlobalLocale('en', { + dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal : function (number) { + var b = number % 10, + output = (toInt(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; + } + }); + + // Side effect imports + + hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale); + hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale); + + var mathAbs = Math.abs; + + function abs () { + var data = this._data; + + this._milliseconds = mathAbs(this._milliseconds); + this._days = mathAbs(this._days); + this._months = mathAbs(this._months); + + data.milliseconds = mathAbs(data.milliseconds); + data.seconds = mathAbs(data.seconds); + data.minutes = mathAbs(data.minutes); + data.hours = mathAbs(data.hours); + data.months = mathAbs(data.months); + data.years = mathAbs(data.years); + + return this; + } + + function addSubtract$1 (duration, input, value, direction) { + var other = createDuration(input, value); + + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; + + return duration._bubble(); + } + + // supports only 2.0-style add(1, 's') or add(duration) + function add$1 (input, value) { + return addSubtract$1(this, input, value, 1); + } + + // supports only 2.0-style subtract(1, 's') or subtract(duration) + function subtract$1 (input, value) { + return addSubtract$1(this, input, value, -1); + } + + function absCeil (number) { + if (number < 0) { + return Math.floor(number); + } else { + return Math.ceil(number); + } + } + + function bubble () { + var milliseconds = this._milliseconds; + var days = this._days; + var months = this._months; + var data = this._data; + var seconds, minutes, hours, years, monthsFromDays; + + // if we have a mix of positive and negative values, bubble down first + // check: https://github.com/moment/moment/issues/2166 + if (!((milliseconds >= 0 && days >= 0 && months >= 0) || + (milliseconds <= 0 && days <= 0 && months <= 0))) { + milliseconds += absCeil(monthsToDays(months) + days) * 864e5; + days = 0; + months = 0; + } + + // The following code bubbles up values, see the tests for + // examples of what that means. + data.milliseconds = milliseconds % 1000; + + seconds = absFloor(milliseconds / 1000); + data.seconds = seconds % 60; + + minutes = absFloor(seconds / 60); + data.minutes = minutes % 60; + + hours = absFloor(minutes / 60); + data.hours = hours % 24; + + days += absFloor(hours / 24); + + // convert days to months + monthsFromDays = absFloor(daysToMonths(days)); + months += monthsFromDays; + days -= absCeil(monthsToDays(monthsFromDays)); + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + data.days = days; + data.months = months; + data.years = years; + + return this; + } + + function daysToMonths (days) { + // 400 years have 146097 days (taking into account leap year rules) + // 400 years have 12 months === 4800 + return days * 4800 / 146097; + } + + function monthsToDays (months) { + // the reverse of daysToMonths + return months * 146097 / 4800; + } + + function as (units) { + if (!this.isValid()) { + return NaN; + } + var days; + var months; + var milliseconds = this._milliseconds; + + units = normalizeUnits(units); + + if (units === 'month' || units === 'quarter' || units === 'year') { + days = this._days + milliseconds / 864e5; + months = this._months + daysToMonths(days); + switch (units) { + case 'month': return months; + case 'quarter': return months / 3; + case 'year': return months / 12; + } + } else { + // handle milliseconds separately because of floating point math errors (issue #1867) + days = this._days + Math.round(monthsToDays(this._months)); + switch (units) { + case 'week' : return days / 7 + milliseconds / 6048e5; + case 'day' : return days + milliseconds / 864e5; + case 'hour' : return days * 24 + milliseconds / 36e5; + case 'minute' : return days * 1440 + milliseconds / 6e4; + case 'second' : return days * 86400 + milliseconds / 1000; + // Math.floor prevents floating point math errors here + case 'millisecond': return Math.floor(days * 864e5) + milliseconds; + default: throw new Error('Unknown unit ' + units); + } + } + } + + // TODO: Use this.as('ms')? + function valueOf$1 () { + if (!this.isValid()) { + return NaN; + } + return ( + this._milliseconds + + this._days * 864e5 + + (this._months % 12) * 2592e6 + + toInt(this._months / 12) * 31536e6 + ); + } + + function makeAs (alias) { + return function () { + return this.as(alias); + }; + } + + var asMilliseconds = makeAs('ms'); + var asSeconds = makeAs('s'); + var asMinutes = makeAs('m'); + var asHours = makeAs('h'); + var asDays = makeAs('d'); + var asWeeks = makeAs('w'); + var asMonths = makeAs('M'); + var asQuarters = makeAs('Q'); + var asYears = makeAs('y'); + + function clone$1 () { + return createDuration(this); + } + + function get$2 (units) { + units = normalizeUnits(units); + return this.isValid() ? this[units + 's']() : NaN; + } + + function makeGetter(name) { + return function () { + return this.isValid() ? this._data[name] : NaN; + }; + } + + var milliseconds = makeGetter('milliseconds'); + var seconds = makeGetter('seconds'); + var minutes = makeGetter('minutes'); + var hours = makeGetter('hours'); + var days = makeGetter('days'); + var months = makeGetter('months'); + var years = makeGetter('years'); + + function weeks () { + return absFloor(this.days() / 7); + } + + var round = Math.round; + var thresholds = { + ss: 44, // a few seconds to seconds + s : 45, // seconds to minute + m : 45, // minutes to hour + h : 22, // hours to day + d : 26, // days to month + M : 11 // months to year + }; + + // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize + function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { + return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); + } + + function relativeTime$1 (posNegDuration, withoutSuffix, locale) { + var duration = createDuration(posNegDuration).abs(); + var seconds = round(duration.as('s')); + var minutes = round(duration.as('m')); + var hours = round(duration.as('h')); + var days = round(duration.as('d')); + var months = round(duration.as('M')); + var years = round(duration.as('y')); + + var a = seconds <= thresholds.ss && ['s', seconds] || + seconds < thresholds.s && ['ss', seconds] || + minutes <= 1 && ['m'] || + minutes < thresholds.m && ['mm', minutes] || + hours <= 1 && ['h'] || + hours < thresholds.h && ['hh', hours] || + days <= 1 && ['d'] || + days < thresholds.d && ['dd', days] || + months <= 1 && ['M'] || + months < thresholds.M && ['MM', months] || + years <= 1 && ['y'] || ['yy', years]; + + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale; + return substituteTimeAgo.apply(null, a); + } + + // This function allows you to set the rounding function for relative time strings + function getSetRelativeTimeRounding (roundingFunction) { + if (roundingFunction === undefined) { + return round; + } + if (typeof(roundingFunction) === 'function') { + round = roundingFunction; + return true; + } + return false; + } + + // This function allows you to set a threshold for relative time strings + function getSetRelativeTimeThreshold (threshold, limit) { + if (thresholds[threshold] === undefined) { + return false; + } + if (limit === undefined) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + if (threshold === 's') { + thresholds.ss = limit - 1; + } + return true; + } + + function humanize (withSuffix) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + + var locale = this.localeData(); + var output = relativeTime$1(this, !withSuffix, locale); + + if (withSuffix) { + output = locale.pastFuture(+this, output); + } + + return locale.postformat(output); + } + + var abs$1 = Math.abs; + + function sign(x) { + return ((x > 0) - (x < 0)) || +x; + } + + function toISOString$1() { + // for ISO strings we do not use the normal bubbling rules: + // * milliseconds bubble up until they become hours + // * days do not bubble at all + // * months bubble up until they become years + // This is because there is no context-free conversion between hours and days + // (think of clock changes) + // and also not between days and months (28-31 days per month) + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + + var seconds = abs$1(this._milliseconds) / 1000; + var days = abs$1(this._days); + var months = abs$1(this._months); + var minutes, hours, years; + + // 3600 seconds -> 60 minutes -> 1 hour + minutes = absFloor(seconds / 60); + hours = absFloor(minutes / 60); + seconds %= 60; + minutes %= 60; + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + + // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js + var Y = years; + var M = months; + var D = days; + var h = hours; + var m = minutes; + var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; + var total = this.asSeconds(); + + if (!total) { + // this is the same as C#'s (Noda) and python (isodate)... + // but not other JS (goog.date) + return 'P0D'; + } + + var totalSign = total < 0 ? '-' : ''; + var ymSign = sign(this._months) !== sign(total) ? '-' : ''; + var daysSign = sign(this._days) !== sign(total) ? '-' : ''; + var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; + + return totalSign + 'P' + + (Y ? ymSign + Y + 'Y' : '') + + (M ? ymSign + M + 'M' : '') + + (D ? daysSign + D + 'D' : '') + + ((h || m || s) ? 'T' : '') + + (h ? hmsSign + h + 'H' : '') + + (m ? hmsSign + m + 'M' : '') + + (s ? hmsSign + s + 'S' : ''); + } + + var proto$2 = Duration.prototype; + + proto$2.isValid = isValid$1; + proto$2.abs = abs; + proto$2.add = add$1; + proto$2.subtract = subtract$1; + proto$2.as = as; + proto$2.asMilliseconds = asMilliseconds; + proto$2.asSeconds = asSeconds; + proto$2.asMinutes = asMinutes; + proto$2.asHours = asHours; + proto$2.asDays = asDays; + proto$2.asWeeks = asWeeks; + proto$2.asMonths = asMonths; + proto$2.asQuarters = asQuarters; + proto$2.asYears = asYears; + proto$2.valueOf = valueOf$1; + proto$2._bubble = bubble; + proto$2.clone = clone$1; + proto$2.get = get$2; + proto$2.milliseconds = milliseconds; + proto$2.seconds = seconds; + proto$2.minutes = minutes; + proto$2.hours = hours; + proto$2.days = days; + proto$2.weeks = weeks; + proto$2.months = months; + proto$2.years = years; + proto$2.humanize = humanize; + proto$2.toISOString = toISOString$1; + proto$2.toString = toISOString$1; + proto$2.toJSON = toISOString$1; + proto$2.locale = locale; + proto$2.localeData = localeData; + + proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1); + proto$2.lang = lang; + + // Side effect imports + + // FORMATTING + + addFormatToken('X', 0, 0, 'unix'); + addFormatToken('x', 0, 0, 'valueOf'); + + // PARSING + + addRegexToken('x', matchSigned); + addRegexToken('X', matchTimestamp); + addParseToken('X', function (input, array, config) { + config._d = new Date(parseFloat(input, 10) * 1000); + }); + addParseToken('x', function (input, array, config) { + config._d = new Date(toInt(input)); + }); + + // Side effect imports + + + hooks.version = '2.24.0'; + + setHookCallback(createLocal); + + hooks.fn = proto; + hooks.min = min; + hooks.max = max; + hooks.now = now; + hooks.utc = createUTC; + hooks.unix = createUnix; + hooks.months = listMonths; + hooks.isDate = isDate; + hooks.locale = getSetGlobalLocale; + hooks.invalid = createInvalid; + hooks.duration = createDuration; + hooks.isMoment = isMoment; + hooks.weekdays = listWeekdays; + hooks.parseZone = createInZone; + hooks.localeData = getLocale; + hooks.isDuration = isDuration; + hooks.monthsShort = listMonthsShort; + hooks.weekdaysMin = listWeekdaysMin; + hooks.defineLocale = defineLocale; + hooks.updateLocale = updateLocale; + hooks.locales = listLocales; + hooks.weekdaysShort = listWeekdaysShort; + hooks.normalizeUnits = normalizeUnits; + hooks.relativeTimeRounding = getSetRelativeTimeRounding; + hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; + hooks.calendarFormat = getCalendarFormat; + hooks.prototype = proto; + + // currently HTML5 input type only supports 24-hour formats + hooks.HTML5_FMT = { + DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // + DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // + DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // + DATE: 'YYYY-MM-DD', // + TIME: 'HH:mm', // + TIME_SECONDS: 'HH:mm:ss', // + TIME_MS: 'HH:mm:ss.SSS', // + WEEK: 'GGGG-[W]WW', // + MONTH: 'YYYY-MM' // + }; + + return hooks; + +}))); diff --git a/SplunkAppForWazuh/appserver/static/js/main.js b/SplunkAppForWazuh/appserver/static/js/main.js index c85754f12..87c8d4372 100644 --- a/SplunkAppForWazuh/appserver/static/js/main.js +++ b/SplunkAppForWazuh/appserver/static/js/main.js @@ -13,6 +13,11 @@ require.config({ ngMaterial: 'js/libs/material', ngRoute: 'js/libs/router', + // Angular Chart + moment: 'js/libs/moment', + chart: 'js/libs/chart', + angularChart: 'js/libs/angular-chart', + // JSON2XML js2xmlparser: 'js/libs/json2xml/jsontoxml', @@ -20,7 +25,10 @@ require.config({ FileSaver: 'js/libs/file-saver/file-saver', // dom-to-image - domToImg: 'js/libs/required-dom-to-image/src/dom-to-image' + domToImg: 'js/libs/required-dom-to-image/src/dom-to-image', + + // JqueryUI + JqueryUI: 'js/libs/jquery-ui' }, // Add angular modules that does not support AMD out of the box, put it in a shim @@ -43,6 +51,14 @@ require.config({ ngRoute: { exports: 'ngRoute', deps: ['angular'] + }, + chart: { + exports: 'chart', + deps: ['angular'] + }, + angularChart: { + exports: 'angularChart', + deps: ['angular', 'chart'] } }, diff --git a/SplunkAppForWazuh/appserver/static/js/run/run.js b/SplunkAppForWazuh/appserver/static/js/run/run.js index 0b329d634..2b3f718b2 100644 --- a/SplunkAppForWazuh/appserver/static/js/run/run.js +++ b/SplunkAppForWazuh/appserver/static/js/run/run.js @@ -13,8 +13,8 @@ define(['./module'], function(module) { $navigationService, $currentDataService ) { - //Go to last state at login - $navigationService.goToLastState() + //Go to last state or to a specified tab if "currentTab" param is specified in the url + $navigationService.manageState() async function checkBeforeTransition(state) { try { @@ -30,17 +30,53 @@ define(['./module'], function(module) { $currentDataService.getIndex().index }", "implicit":true}` ) + // If change the primary state and do not receive an error the two below code lines clear the warning message + window.localStorage.setItem('wazuhIsReady', 'true') + $rootScope.wazuhNotReadyYet = false + $rootScope.wazuhCouldNotBeRecovered = false } catch (err) { - $rootScope.$broadcast('loading', { status: false }) - if (state != 'settings.api') - $rootScope.$broadcast('stateChanged', 'settings') - $state.go('settings.api') + if ( + err instanceof Object && + err.message && + err.message.includes('ERROR3099') + ) { + $rootScope.$broadcast('wazuhNotReadyYet', {}) + toPrimaryState(state) + } else { + $rootScope.$broadcast('loading', { status: false }) + if (state != 'settings.api') + $rootScope.$broadcast('stateChanged', 'settings') + $state.go('settings.api') + } } } + // Check secondary states when Wazuh is not ready to prevent change the state + $transitions.onBefore({}, async trans => { + const to = trans.to().name + if ( + to !== 'overview' && + to !== 'manager' && + to !== 'agents' && + to !== 'dev-tools' && + to !== 'discover' && + !to.startsWith('settings') + ) { + const wazuhIsReady = + window.localStorage.getItem('wazuhIsReady') === 'true' + if (!wazuhIsReady) { + return false + } + } + }) + $transitions.onStart({}, async trans => { $rootScope.$broadcast('loading', { status: true }) const to = trans.to().name + const from = trans.from().name + if (to !== from && from !== 'discover') { + $currentDataService.cleanFilters() + } if ( to != 'settings.about' && to != 'settings.extensions' && @@ -54,23 +90,36 @@ define(['./module'], function(module) { $transitions.onSuccess({}, async trans => { $rootScope.$broadcast('loading', { status: false }) const to = trans.to().name + const from = trans.from().name //Select primary states - $rootScope.$broadcast('stateChanged', to) - //Select secondary states if ( - to === 'overview' || - to === 'agents' || - to === 'agent-overview' || - to === 'manager' - ) - $currentDataService.cleanFilters() - if ((to !== 'agents' && to.includes('agent')) || to.includes('ag-')) { + (to === 'discover' && from === 'overview') || + from === 'manager' || + from === 'settings' || + from === 'agents' || + from === 'dev-tools' + ) { + $rootScope.$broadcast('stateChanged', to) + } else if (to !== 'discover') { + $rootScope.$broadcast('stateChanged', to) + } + //Select secondary states + + if (to.startsWith('agent') || to.startsWith('ag-')) { + if ( + from !== 'agents' && + !from.startsWith('agent') && + !from.startsWith('ag-') && + from !== 'discover' + ) { + $currentDataService.cleanAgentsPinedFilters() + } $rootScope.$broadcast('stateChanged', 'agents') - } else if (to.includes('ow-')) { + } else if (to.startsWith('ow-')) { $rootScope.$broadcast('stateChanged', 'overview') - } else if (to.includes('mg-')) { + } else if (to.startsWith('mg-')) { $rootScope.$broadcast('stateChanged', 'manager') - } else if (to.includes('settings')) { + } else if (to.startsWith('settings')) { $rootScope.$broadcast('stateChanged', 'settings') } }) @@ -84,6 +133,20 @@ define(['./module'], function(module) { $state.reload() } }) + + // When access to a state and Wazuh is not ready is detected, this funcion checks if is a secondary state, if it is, go to primary state + const toPrimaryState = to => { + if (to.startsWith('ag-') || to.startsWith('agent-')) { + $state.go('agents') + $rootScope.$broadcast('stateChanged', 'agents') + } else if (to.startsWith('ow-')) { + $state.go('overview') + $rootScope.$broadcast('stateChanged', 'overview') + } else if (to.startsWith('mg-')) { + $state.go('manager') + $rootScope.$broadcast('stateChanged', 'manager') + } + } } ]) }) diff --git a/SplunkAppForWazuh/appserver/static/js/services/api-manager/apiMgrService.js b/SplunkAppForWazuh/appserver/static/js/services/api-manager/apiMgrService.js index 800ab1c61..32fed88b3 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/api-manager/apiMgrService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/api-manager/apiMgrService.js @@ -26,13 +26,7 @@ define(['../module'], function(module) { */ const remove = async api => { try { - if ( - $apiIndexStorageService.getApi() && - $apiIndexStorageService.getApi().url === api.url - ) { - $apiIndexStorageService.removeAPI() - } - await $splunkStoreService.delete({ id: api.id }) + await $splunkStoreService.delete(api._key) return } catch (err) { return Promise.reject(err) @@ -52,6 +46,30 @@ define(['../module'], function(module) { } } + /** + * Adds a new API entry with all fields + * @param {Object} record + */ + const addApi = async record => { + try { + // if the API is not connecting, then throw error + const resultRawConnection = await checkRawConnection(record) + record.managerName = resultRawConnection.data.managerName.name + if (resultRawConnection.data.clusterMode.enabled === 'yes') { + record.filterType = 'cluster.name' + record.filterName = resultRawConnection.data.clusterName.cluster + } else { + record.filterType = 'manager.name' + record.filterName = resultRawConnection.data.managerName.name + } + const key = await $splunkStoreService.insert(record) + record['_key'] = key.result + return record + } catch (err) { + return Promise.reject(err) + } + } + /** * Updates an API * @param {Object} api @@ -76,19 +94,6 @@ define(['../module'], function(module) { const getApiList = async () => { try { const apiList = await $splunkStoreService.getAllApis() - const selectedApi = $apiIndexStorageService.getApi() - for (let i = 0; i < apiList.length; i++) { - if ( - selectedApi && - typeof selectedApi === 'string' && - selectedApi !== 'undefined' && - typeof JSON.parse(selectedApi) === 'object' && - JSON.parse(selectedApi).url && - apiList[i].url === JSON.parse(selectedApi).url - ) { - apiList[i].selected = true - } - } return apiList } catch (err) { return Promise.reject(err) @@ -153,10 +158,9 @@ define(['../module'], function(module) { const chose = async id => { try { const apiList = await getApiList() - for (const api of apiList) { - if (api.id === id) { - $apiIndexStorageService.setApi(api) - } + const api = apiList.filter(api => api['_key'] === id)[0] + if (api && typeof api === 'object') { + $apiIndexStorageService.setApi(api) } return } catch (err) { @@ -174,7 +178,7 @@ define(['../module'], function(module) { if (!currentApi) { throw new Error('No selected API in sessionStorage.') } - const api = await checkApiConnection(currentApi.id) + const api = await checkApiConnection(currentApi['_key']) let selectedIndex = $apiIndexStorageService.getIndex() return { api, selectedIndex } } catch (err) { @@ -212,15 +216,25 @@ define(['../module'], function(module) { api.userapi && api.passapi ) { + // Encode user and password, this prevent fails with special charsets + const user = encodeURIComponent(api.userapi) + const pass = encodeURIComponent(api.passapi) + const clusterEnabled = api.filterType === 'cluster.name' const checkConnectionEndpoint = `/manager/check_connection?ip=${ api.url - }&port=${api.portapi}&user=${api.userapi}&pass=${api.passapi}` + }&port=${ + api.portapi + }&user=${user}&pass=${pass}&cluster=${clusterEnabled}` const result = await $requestService.httpReq( 'GET', checkConnectionEndpoint ) if (result.data.status === 400 || result.data.error) { - throw new Error('Cannot connect to API.') + if (result.data.error === 3099) { + throw new Error('ERROR3099 - Wazuh not ready yet.') + } else { + throw new Error('Unreachable API.') + } } return result } @@ -232,45 +246,68 @@ define(['../module'], function(module) { } /** - * Check if connection with API was successful, also returns the full needed information about it - * @param {String} id + * Checks if the API has to change its filters + * @param {Object} api */ - const checkApiConnection = async id => { + const updateApiFilter = async api => { try { - const api = await select(id) - const clusterData = await $requestService.apiReq(`/cluster/status`, { - id: id - }) - if (clusterData.data.error) { - throw new Error(clusterData.data.error) - } - // Get manager name. Necessary for both cases - const managerName = await $requestService.apiReq(`/agents/000`, { - id: id, - select: 'name' - }) - if ( - managerName && - managerName.data && - managerName.data.data && - managerName.data.data.name - ) { - api.managerName = managerName.data.data.name + const results = await Promise.all([ + $requestService.apiReq(`/cluster/status`, { + id: api['_key'] + }), + $requestService.apiReq(`/agents/000`, { + id: api['_key'], + select: 'name' + }) + ]) + + const parsedResult = results.map(item => + item && item.data && item.data.data ? item.data.data : false + ) + const [clusterData, managerName] = parsedResult + + if (managerName.name) { + api.managerName = managerName.name } // If cluster is disabled, then filter by manager.name - if (clusterData.data.data.enabled === 'yes') { + if (clusterData.enabled === 'yes') { api.filterType = 'cluster.name' const clusterName = await $requestService.apiReq(`/cluster/node`, { - id: id + id: api['_key'] }) api.filterName = clusterName.data.data.cluster } else { api.filterType = 'manager.name' api.filterName = api.managerName } - await $splunkStoreService.update(api) - delete api['passapi'] return api + } catch (error) { + return Promise.reject(error) + } + } + + /** + * Check if connection with API was successful, also returns the full needed information about it + * @param {String} id + */ + const checkApiConnection = async id => { + try { + const api = await select(id) //Before update cluster or not cluster + await checkRawConnection(api) + const apiSaved = { ...api } //eslint-disable-line + const updatedApi = await updateApiFilter(api) + let equal = true + Object.keys(updatedApi).forEach(key => { + if (updatedApi[key] !== apiSaved[key]) { + equal = false + } + }) + if (!equal) { + await $splunkStoreService.update(updatedApi) + } else { + } + delete updatedApi['passapi'] + return updatedApi } catch (err) { return Promise.reject(err) } @@ -292,7 +329,8 @@ define(['../module'], function(module) { getIndex: getIndex, setIndex: setIndex, getApi: getApi, - setApi: setApi + setApi: setApi, + addApi: addApi } }) }) diff --git a/SplunkAppForWazuh/appserver/static/js/services/apiIndexStorageService/apiIndexStorageService.js b/SplunkAppForWazuh/appserver/static/js/services/apiIndexStorageService/apiIndexStorageService.js index 0c712a40b..3b46f5ff6 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/apiIndexStorageService/apiIndexStorageService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/apiIndexStorageService/apiIndexStorageService.js @@ -43,14 +43,14 @@ define(['../module'], function(app) { } /** - * Select an API - * @param {String} API + * Select an Api + * @param {String} Api */ - setApi(API) { + setApi(Api) { try { delete this.sessionStorage.selectedAPI - if (typeof API === 'object') { - this.sessionStorage.selectedAPI = JSON.stringify(API) + if (typeof Api === 'object') { + this.sessionStorage.selectedAPI = JSON.stringify(Api) } } catch (error) { return @@ -58,8 +58,8 @@ define(['../module'], function(app) { } /** - * Returns currently selected API - * @param {String} API + * Returns currently selected Api + * @param {String} Api */ getApi() { try { @@ -67,6 +67,7 @@ define(['../module'], function(app) { return JSON.parse(this.sessionStorage.selectedAPI) } } catch (err) { + console.error('err getApi() ', err) return null } } @@ -95,7 +96,7 @@ define(['../module'], function(app) { let existentApi = false for (let i = 0; i < parsedExtensions.length; i++) { if (parsedExtensions[i].id === id) { - parsedExtensions[i] = { id: id, ...extensions } + parsedExtensions[i] = { id: id, ...extensions } //eslint-disable-line existentApi = true break } diff --git a/SplunkAppForWazuh/appserver/static/js/services/cdb-editor/cdb-editor.js b/SplunkAppForWazuh/appserver/static/js/services/cdb-editor/cdb-editor.js new file mode 100644 index 000000000..1c43f9b50 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/services/cdb-editor/cdb-editor.js @@ -0,0 +1,70 @@ +/* + * Wazuh app - Group handler service + * Copyright (C) 2015-2019 Wazuh, Inc. + * + * This program is free software you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation either version 2 of the License, or + * (at your option) any later version. + * + * Find more information about this on the LICENSE file. + */ + +define(['../module'], function(module) { + 'use strict' + + class CDBEditor { + constructor($requestService) { + this.getConfig = $requestService.getConfiguration + this.apiReq = $requestService.apiReq + } + + async sendConfiguration(file, path, content, overwrite = false) { + try { + const url = overwrite + ? `/manager/files?path=${path}/${file}&overwrite=true` + : `/manager/files?path=${path}/${file}` + const result = await this.apiReq( + `${url}`, + { content, origin: 'raw' }, + 'POST' + ) + if ( + !result || + !result.data || + !result.data.data || + result.data.error !== 0 || + (result.data.data.error && result.data.data.error !== 0) + ) { + if (result.data.error === 1905) { + return result + } else { + throw new Error(result.data.message || 'Cannot send this file.') + } + } + return result + } catch (error) { + return Promise.reject(error) + } + } + + async getConfiguration(file, path) { + try { + const url = `/manager/files?path=${path}/${file}` + const result = await this.getConfig(url) + if ( + !result || + !result.data || + !result.data.data || + result.data.error != 0 + ) { + throw new Error('Error fetching cdb list content') + } + return result.data.data + } catch (error) { + return Promise.reject(error) + } + } + } + module.service('$cdbEditor', CDBEditor) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/services/checkDaemons/checkDaemonsService.js b/SplunkAppForWazuh/appserver/static/js/services/checkDaemons/checkDaemonsService.js new file mode 100644 index 000000000..a367d9168 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/services/checkDaemons/checkDaemonsService.js @@ -0,0 +1,54 @@ +define(['../module'], function(module) { + 'use strict' + + class checkDaemonsService { + constructor($rootScope, $requestService, $timeout) { + this.rootScope = $rootScope + this.wazuhIsReady = $requestService.wazuhIsReady + this.tries = 10 + this.timeout = $timeout + this.busy = false + } + + async makePing(msg = false) { + try { + if (this.busy) return + this.busy = true + window.localStorage.setItem('wazuhIsReady', 'false') + this.rootScope.notReadyMsg = msg + this.rootScope.wazuhCouldNotBeRecovered = false + this.rootScope.wazuhNotReadyYet = true + let wazuhReady = false + while (this.tries--) { + await this.timeout(1200) + try { + const result = await this.wazuhIsReady() + wazuhReady = result.data.ready + } catch (error) { + wazuhReady = false + } + if (wazuhReady) { + this.tries = 10 + this.rootScope.wazuhNotReadyYet = false + this.rootScope.wazuhCouldNotBeRecovered = false + this.rootScope.$applyAsync() + window.localStorage.setItem('wazuhIsReady', 'true') + break + } + } + + if (!wazuhReady) { + throw new Error('Not recovered') + } + } catch (error) { + this.tries = 10 + this.rootScope.wazuhCouldNotBeRecovered = true + this.rootScope.$applyAsync() + } + + this.busy = false + } + } + + module.service('$checkDaemonsService', checkDaemonsService) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/services/currentDataService/currentDataService.js b/SplunkAppForWazuh/appserver/static/js/services/currentDataService/currentDataService.js index 6ac24a54d..6aea99c93 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/currentDataService/currentDataService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/currentDataService/currentDataService.js @@ -12,6 +12,10 @@ define(['../module'], function(module) { return $apiMgrService.getPollintState } + const addApi = record => { + return $apiMgrService.addApi(record) + } + const getBaseUrl = () => { return $requestService.getBaseUrl() } @@ -56,18 +60,26 @@ define(['../module'], function(module) { return $filterService.addFilter(filter) } - const getSerializedFilters = () => { - return $filterService.getSerializedFilters() + const getSerializedFilters = hideOnlyShowFilters => { + return $filterService.getSerializedFilters(hideOnlyShowFilters) } const removeFilter = filter => { return $filterService.removeFilter(filter) } + const pinFilter = filter => { + return $filterService.pinFilter(filter) + } + const cleanFilters = () => { return $filterService.cleanFilters() } + const cleanAgentsPinedFilters = () => { + return $filterService.cleanAgentsPinedFilters() + } + const update = register => { return $apiMgrService.update(register) } @@ -133,6 +145,74 @@ define(['../module'], function(module) { } } + /** + * Gets admin extensions by ID + * @param {String} id + */ + const getAdminExtensions = async () => { + try { + const result = {} + const ext = await $requestService.httpReq( + `GET`, + `/manager/admin_extensions` + ) + Object.assign(result, ext.data) + return result + } catch (error) { + return Promise.reject(false) + } + } + + /** + * Checks if is admin + */ + const isAdmin = async () => { + try { + const id = getApi().id + const extensions = await getExtensionsById(id) + return extensions['admin'] === 'true' + } catch (error) { + return Promise.reject(error) + } + } + + /** + * Checks if an extension is enabled + */ + const extensionIsEnabled = async ext => { + try { + const extensions = await getCurrentExtensions() + return extensions[ext] === 'true' + } catch (error) { + return Promise.reject(error) + } + } + + /** + * Get extension by for the current API id + */ + const getCurrentExtensions = async () => { + try { + const id = getApi()['_key'] + return await getExtensionsById(id) + } catch (error) { + return Promise.reject(error) + } + } + + /* + * Gets reporting status + */ + const getReportingStatus = async () => { + try { + const result = await getAdminExtensions() + const status = result.reporting === 'true' + return status + } catch (error) { + return true + } + } + return { getPollintState: getPollintState, getBaseUrl: getBaseUrl, @@ -146,7 +226,9 @@ define(['../module'], function(module) { addFilter: addFilter, getSerializedFilters: getSerializedFilters, removeFilter: removeFilter, + pinFilter: pinFilter, cleanFilters: cleanFilters, + cleanAgentsPinedFilters: cleanAgentsPinedFilters, getFilters: getFilters, update: update, getIndex: getIndex, @@ -159,8 +241,14 @@ define(['../module'], function(module) { getCurrentAgent: getCurrentAgent, setCurrentAgent: setCurrentAgent, getExtensions: getExtensions, + getAdminExtensions: getAdminExtensions, + getCurrentExtensions: getCurrentExtensions, + getExtensionsById: getExtensionsById, + extensionIsEnabled: extensionIsEnabled, setExtensions: setExtensions, - getExtensionsById: getExtensionsById + addApi: addApi, + isAdmin: isAdmin, + getReportingStatus: getReportingStatus } }) }) diff --git a/SplunkAppForWazuh/appserver/static/js/services/dataService/dataService.js b/SplunkAppForWazuh/appserver/static/js/services/dataService/dataService.js index e28f982c7..11f005cd8 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/dataService/dataService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/dataService/dataService.js @@ -22,8 +22,9 @@ define(['../module', 'splunkjs/mvc'], function(module) { * @param {String} path * @param {Object} implicitFilter */ - constructor(path, implicitFilter) { + constructor(path, implicitFilter, implicitSort) { this.implicitFilter = implicitFilter || false + this.implicitSort = implicitSort || false this.items = [] this.path = path this.filters = [] @@ -32,6 +33,9 @@ define(['../module', 'splunkjs/mvc'], function(module) { this.sortValue = false this.busy = false if (this.implicitFilter) this.filters.push(...this.implicitFilter) + if (this.implicitSort) { + this.addSorting(this.implicitSort) + } } /** @@ -95,31 +99,36 @@ define(['../module', 'splunkjs/mvc'], function(module) { const offset = options.offset || 0 const limit = options.limit || 500 const parameters = { limit, offset } - this.serializeFilters(parameters) // Fetch next items const firstPage = await $requestService.apiReq(this.path, parameters) - this.items = this.items.filter(item => !!item) - this.items.push(...firstPage.data.data.items) - const totalItems = firstPage.data.data.totalItems + if (firstPage.data.error) { + this.busy = false + return Promise.reject(firstPage.data.message) + } else { + this.items = this.items.filter(item => !!item) + this.items.push(...firstPage.data.data.items) - const remaining = - this.items.length === totalItems - ? 0 - : totalItems - this.items.length + const totalItems = firstPage.data.data.totalItems - // Ignore manager as an agent, once the team solves this issue, review this line - if (this.path === '/agents') - this.items = this.items.filter(item => item.id !== '000') + const remaining = + this.items.length === totalItems + ? 0 + : totalItems - this.items.length - if (remaining > 0) this.items.push(...Array(remaining).fill(null)) + // Ignore manager as an agent, once the team solves this issue, review this line + if (this.path === '/agents') + this.items = this.items.filter(item => item.id !== '000') - const end = new Date() - const elapsed = (end - start) / 1000 - this.busy = false - return { items: this.items, time: elapsed } + if (remaining > 0) this.items.push(...Array(remaining).fill(null)) + + const end = new Date() + const elapsed = (end - start) / 1000 + this.busy = false + return { items: this.items, time: elapsed } + } } catch (error) { this.busy = false return Promise.reject(error) diff --git a/SplunkAppForWazuh/appserver/static/js/services/date-diff/dateDiffService.js b/SplunkAppForWazuh/appserver/static/js/services/date-diff/dateDiffService.js index 9b7247e1f..c8cd02b2b 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/date-diff/dateDiffService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/date-diff/dateDiffService.js @@ -1,4 +1,4 @@ -define(['../module'], function(module) { +define(['../module'], function (module) { 'use strict' class DateDiffService { @@ -28,6 +28,18 @@ define(['../module'], function(module) { } return result } + + setBrowserOffset(d) { + try { + const date = new Date(d) + const offset = new Date().getTimezoneOffset() + const offsetTime = new Date(date.getTime() - offset * 60000) + const result = offsetTime.toLocaleString('en-ZA').replace(',', '') + return result + } catch (error) { + return Promise.reject(error) + } + } } module.service('$dateDiffService', DateDiffService) diff --git a/SplunkAppForWazuh/appserver/static/js/services/file-editor/file-editor.js b/SplunkAppForWazuh/appserver/static/js/services/file-editor/file-editor.js new file mode 100644 index 000000000..695be63b8 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/services/file-editor/file-editor.js @@ -0,0 +1,118 @@ +/* + * Wazuh app - Group handler service + * Copyright (C) 2015-2019 Wazuh, Inc. + * + * This program is free software you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation either version 2 of the License, or + * (at your option) any later version. + * + * Find more information about this on the LICENSE file. + */ + +define(['../module'], function(module) { + 'use strict' + + class FileEditor { + constructor($requestService) { + this.sendConfig = $requestService.sendConfiguration + this.getConfig = $requestService.getConfiguration + this.apiReq = $requestService.apiReq + } + + async sendConfiguration(file, dir, node, content, overwrite = false) { + try { + let path = dir ? `${dir}/${file}` : file + path = path.startsWith('etc/') ? path : `etc/${path}` + node = node ? `cluster/${node}` : 'manager' + const url = overwrite + ? `/${node}/files?path=${path}&overwrite=true` + : `/${node}/files?path=${path}` + const result = await this.sendConfig(url, content) + if ( + !result || + !result.data || + !result.data.data || + result.data.error !== 0 + ) { + if (result.data.error === 1905) { + return 'fileAlreadyExists' + } else { + throw new Error( + result.data.message || `Error updating ${file} content.` + ) + } + } + return await this.checkConfiguration(node, path) + } catch (error) { + return Promise.reject(error) + } + } + + async getConfiguration(file, dir, node, readOnly = false) { + try { + let path = dir ? `${dir}/${file}` : file + if (!readOnly) { + path = path.startsWith('etc/') ? path : `etc/${path}` + } + node = node ? `cluster/${node}` : 'manager' + const url = `/${node}/files?path=${path}` + const result = await this.getConfig(url) + if ( + !result || + !result.data || + !result.data.data || + result.data.error != 0 + ) { + throw new Error(`Error fetching ${file} content.`) + } + return result.data.data + } catch (error) { + return Promise.reject(error) + } + } + + async checkConfiguration(node, path) { + try { + const check = await this.apiReq(`/${node}/configuration/validation`) + if (check && check.data && !check.data.error) { + if ( + check.data.data.status !== 'OK' && + check.data.data.details[1].includes(path) + ) { + const errObj = {} + errObj['badConfig'] = true + errObj['errMsg'] = [...new Set(check.data.data.details)] + return Promise.reject(errObj) + } else { + return 'Configuration saved.' + } + } else { + return Promise.reject( + check.data.message || 'Cannot check configuration.' + ) + } + } catch (error) { + return Promise.reject(error) + } + } + + async removeFile(item) { + try { + const file = item.file || item.name + const filePath = `${item.path}/${file}` + const url = `/manager/files?path=${filePath}` + const result = await this.apiReq(url, {}, 'DELETE') + if (result && result.data && !result.data.error) { + return `File ${file} deleted.` + } else { + throw new Error(result.data.message || `Cannot remove ${file}`) + } + } catch (error) { + return Promise.reject(error) + } + } + } + + module.service('$fileEditor', FileEditor) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/services/filterService/filterService.js b/SplunkAppForWazuh/appserver/static/js/services/filterService/filterService.js index ebe2a5406..ba833e0b7 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/filterService/filterService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/filterService/filterService.js @@ -3,7 +3,7 @@ define(['../module'], function(module) { class FilterService { constructor($notificationService) { - this.$notificationService = $notificationService + this.notification = $notificationService } /** @@ -48,7 +48,7 @@ define(['../module'], function(module) { window.localStorage.setItem('filters', `[${filter}]`) } } catch (err) { - this.$notificationService.showSimpleToast( + this.notification.showErrorToast( 'Incorrent format. Please use key:value syntax' ) } @@ -58,24 +58,30 @@ define(['../module'], function(module) { * Returns the filters in a way that visualizations can handle * @returns {String} The serialized filters */ - getSerializedFilters() { + getSerializedFilters(hideOnlyShowFilters = true) { try { let filterStr = ' ' - if (window.localStorage.filters) - for (const filter of JSON.parse(window.localStorage.filters)) { - if (typeof filter === 'object') { - const key = Object.keys(filter)[0] - filterStr += key - filterStr += '=' - filterStr += filter[key] - filterStr += ' ' - } else { - filterStr += filter + ' ' - } + let filters = [] + if (window.localStorage.filters) { + filters = JSON.parse(window.localStorage.filters) + filters = hideOnlyShowFilters + ? filters.filter(fil => !fil.onlyShow) + : filters + } + for (const filter of filters) { + if (typeof filter === 'object') { + const key = Object.keys(filter)[0] + filterStr += key + filterStr += '=' + filterStr += filter[key] + filterStr += ' ' + } else { + filterStr += filter + ' ' } + } return filterStr } catch (err) { - this.$notificationService.showSimpleToast('Error when getting filters.') + this.notification.showErrorToast('Error when getting filters.') } } @@ -100,7 +106,31 @@ define(['../module'], function(module) { }) window.localStorage.setItem('filters', JSON.stringify(filters)) } catch (err) { - this.$notificationService.showSimpleToast('Error removing filter.') + this.notification.showErrorToast('Error removing filter.') + } + } + + /** + * Pins a filter + * @param {Object}: The filter to be pined + */ + pinFilter(filter) { + try { + filter = JSON.parse(filter) + const key = Object.keys(filter)[0] + const value = filter[key] + const pined = filter.pined + let filters = JSON.parse(window.localStorage.filters) + filters = filters.filter(fil => Object.keys(fil)[0] != key) + if (pined) { + filter = JSON.parse(`{"${key}":"${value}"}`) + } else { + filter = JSON.parse(`{"${key}":"${value}", "pined":"true"}`) + } + filters.push(filter) + window.localStorage.setItem('filters', JSON.stringify(filters)) + } catch (err) { + this.notification.showErrorToast('Error pinning filter.') } } @@ -108,7 +138,38 @@ define(['../module'], function(module) { * Sets the filters empty */ cleanFilters() { - delete window.localStorage.filters + let filters = [] + try { + if (window.localStorage.filters) { + filters = JSON.parse(window.localStorage.filters) + filters = filters.filter(fil => fil.pined) + filters = JSON.stringify(filters) + window.localStorage.setItem('filters', filters) + } + } catch (err) { + delete window.localStorage.filters // In case of error, delete all filters + } + } + + /** + * Sets the filters empty + */ + cleanAgentsPinedFilters() { + try { + let filters = [] + let pined = [] + if (window.localStorage.filters) { + filters = JSON.parse(window.localStorage.filters) + pined = filters.filter(fil => fil.pined) + filters = filters.filter(fil => !fil.pined) + pined = pined.filter(pin => !Object.keys(pin)[0].startsWith('agent.')) + filters.push(...pined) + } + filters = JSON.stringify(filters) + window.localStorage.setItem('filters', filters) + } catch (err) { + delete window.localStorage.filters // In case of error, delete all filters + } } } module.service('$filterService', FilterService) diff --git a/SplunkAppForWazuh/appserver/static/js/services/group-handler/group-handler.js b/SplunkAppForWazuh/appserver/static/js/services/group-handler/group-handler.js index 95bcd9495..c61d78918 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/group-handler/group-handler.js +++ b/SplunkAppForWazuh/appserver/static/js/services/group-handler/group-handler.js @@ -15,17 +15,21 @@ define(['../module'], function(module) { class GroupHandler { constructor($requestService) { - this.apiReq = $requestService.apiReq + this.req = $requestService } async removeAgentFromGroup(group, agentId) { try { - const result = await this.apiReq( + const result = await this.req.apiReq( `/agents/${agentId}/group/${group}`, {}, 'DELETE' ) - return result + if (result && result.data && result.data.data && !result.data.error) { + return result.data.data + } else { + throw new Error(result.data.message) + } } catch (error) { return Promise.reject(error) } @@ -33,7 +37,7 @@ define(['../module'], function(module) { async addAgentToGroup(group, agentId) { try { - const result = await this.apiReq( + const result = await this.req.apiReq( `/agents/${agentId}/group/${group}`, {}, 'PUT' @@ -54,7 +58,7 @@ define(['../module'], function(module) { async removeGroup(group) { try { - const result = await this.apiReq( + const result = await this.req.apiReq( `/agents/groups/${group}`, {}, 'DELETE' @@ -70,7 +74,11 @@ define(['../module'], function(module) { async createGroup(name) { try { - const result = await this.apiReq(`/agents/groups/${name}`, {}, 'PUT') + const result = await this.req.apiReq( + `/agents/groups/${name}`, + {}, + 'PUT' + ) if (result.data.error != 0) { throw new Error(result.data.message) } @@ -82,20 +90,10 @@ define(['../module'], function(module) { async sendConfiguration(group, content) { try { - const result = await this.apiReq( + const result = this.req.sendConfiguration( `/agents/groups/${group}/files/agent.conf`, - { content, origin: 'xmleditor' }, - 'POST' + content ) - if ( - !result || - !result.data || - !result.data.data || - result.data.error !== 0 || - (result.data.data.error && result.data.data.error !== 0) - ) { - throw new Error('Cannot send file.') - } return result } catch (error) { return Promise.reject(error) diff --git a/SplunkAppForWazuh/appserver/static/js/services/index.js b/SplunkAppForWazuh/appserver/static/js/services/index.js index feb880d53..08c771247 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/index.js +++ b/SplunkAppForWazuh/appserver/static/js/services/index.js @@ -19,5 +19,9 @@ define([ './get-ids/getIdService', './token-model/urlTokenModelService', './group-handler/group-handler', - './date-diff/dateDiffService' + './date-diff/dateDiffService', + './file-editor/file-editor', + './cdb-editor/cdb-editor', + './restartService/restartService', + './checkDaemons/checkDaemonsService' ], function() {}) diff --git a/SplunkAppForWazuh/appserver/static/js/services/key-equivalence/keyEquivalenceService.js b/SplunkAppForWazuh/appserver/static/js/services/key-equivalence/keyEquivalenceService.js index 9b06e0907..bc3244463 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/key-equivalence/keyEquivalenceService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/key-equivalence/keyEquivalenceService.js @@ -19,7 +19,7 @@ define(['../module'], function(module) { level: 'Level', conf_sum: 'Group MD5 sum', merged_sum: 'Group sum', - hash: 'MD5 sum', + hash: 'Checksum', filename: 'File', file: 'File', gdpr: 'GDPR', @@ -42,7 +42,7 @@ define(['../module'], function(module) { details: 'Details', position: 'Position', configSum: 'Group MD5 sum', - mergedSum: 'Group sum', + mergedSum: 'Configuration checksum', key: 'Key', scan_id: 'Scan ID', format: 'Format', @@ -64,7 +64,21 @@ define(['../module'], function(module) { uname: 'User', gname: 'Group', perm: 'Permissions', - process: 'Process' + process: 'Process', + md5: 'MD5', + sha1: 'SHA1', + sha256: 'SHA256', + cis: 'CIS', + event: 'Event', + size: 'Size', + uid: 'User ID', + gid: 'Group ID', + mtime: 'Last modified', + date: 'Date', + expanded: 'Expanded', + title: 'Title', + result: 'Result', + agents: 'Agents' } } } diff --git a/SplunkAppForWazuh/appserver/static/js/services/navigation/navigationService.js b/SplunkAppForWazuh/appserver/static/js/services/navigation/navigationService.js index 141930786..5c436f318 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/navigation/navigationService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/navigation/navigationService.js @@ -2,23 +2,122 @@ define(['../module'], function(module) { 'use strict' class navigationService { - constructor($state, $window) { + constructor($state, $window, $location) { this.$state = $state this.$window = $window + this.$location = $location + + this.$window.onpopstate = () => { + try { + let lastState = sessionStorage.history.split(',') + + let newHistory = lastState[0] + if (lastState.length > 1) { + // if there are previous states + for (var i = 1; i < lastState.length - 2; i++) { + newHistory += ',' + lastState[i] + } + sessionStorage.history = newHistory + lastState = lastState[lastState.length - 2] + $state.go( + lastState, + {}, //routeParams + { reload: true, notify: false } + ) + } + } catch (error) { + sessionStorage.params + ? $state.go(sessionStorage.params) + : $state.go('settings.api') + } + } } storeRoute(params) { sessionStorage.params = params + this.addToHistory(params) + + this.$location.search('currentTab', params) //set currentTab to the new state + } + + addToHistory(url) { + try { + if (!sessionStorage.history) { + sessionStorage.history = url + } else { + const history = sessionStorage.history.split(',') + history.push(url) + let newHistory = history[0] + const len = history.length + if (history.length < 20) { + for (let i = 1; i < len; i++) { + if (history[i - 1] !== history[i]) newHistory += ',' + history[i] + } + } else { + for (let i = 11; i < len; i++) { + if (history[i - 11] !== history[i]) newHistory += ',' + history[i] + } + } + sessionStorage.history = newHistory + } + } catch (error) { + this.goToLastState() + } } goToLastState() { sessionStorage.params ? this.$state.go(sessionStorage.params) - : this.$state.go('settings.api') + : this.$state.go('settings.api') // redirects to settings.api if no previous states were visited + } + + /** + * Returns the current url with updated parameter + * @param {*} url + * @param {*} param - paramater to be updated + * @param {*} paramVal - new value of param + */ + updateURLParameter(url, param, paramVal) { + try { + var newAdditionalURL = '' + var tempArray = url.split('?') + var baseURL = tempArray[0] + var additionalURL = tempArray[1] + var temp = '' + if (additionalURL) { + tempArray = additionalURL.split('&') + for (var i = 0; i < tempArray.length; i++) { + if (tempArray[i].split('=')[0] != param) { + newAdditionalURL += temp + tempArray[i] + temp = '&' + } + } + } + var rows_txt = temp + '' + param + '=' + paramVal + return baseURL + '?' + newAdditionalURL + rows_txt + } catch (error) { + return url + } + } + /* * + * Redirects the user to the tab specified in the url (index?currentTab=) + * if no tab is specified it redirects to the last state visited + * */ + manageState() { + try { + const url_params = this.$location.search() + if (url_params.currentTab) { + this.$state.go(url_params.currentTab) + } else { + this.goToLastState() + } + } catch (error) { + this.$state.go('settings.api') + } } getLastState() { - if (sessionStorage.params) return sessionStorage.params + return sessionStorage.params || undefined } setCurrentAgent(currentAgentId) { @@ -26,7 +125,7 @@ define(['../module'], function(module) { } getCurrentAgent() { - if (sessionStorage.currentAgent) return sessionStorage.currentAgent + return sessionStorage.currentAgent || undefined } setCurrentDevTools(current) { diff --git a/SplunkAppForWazuh/appserver/static/js/services/notificationService/notificationService.js b/SplunkAppForWazuh/appserver/static/js/services/notificationService/notificationService.js index 86d57073f..dc29a292e 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/notificationService/notificationService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/notificationService/notificationService.js @@ -1,6 +1,6 @@ define(['../module'], function(module) { 'use strict' - module.service('$notificationService', function($mdToast) { + module.service('$notificationService', function($mdToast, $rootScope) { let last = { bottom: true, top: false, @@ -31,19 +31,95 @@ define(['../module'], function(module) { last = angular.extend({}, current) // eslint-disable-line } - let showSimpleToast = text => { - let pinTo = getToastPosition() + let showSuccessToast = text => showSimpleToast(text, 1) + let showErrorToast = text => showSimpleToast(text, 2) + let showWarningToast = text => showSimpleToast(text, 3) - $mdToast.show( - $mdToast - .simple() - .textContent(text) - .position(pinTo) - .hideDelay(2000) - ) + let showSimpleToast = (text, type) => { + if (!wazuhIsNotReady(text)) { + let pinTo = getToastPosition() + if (type === 1) { + $mdToast.show({ + //Success + hideDelay: 3000, + position: pinTo, + template: + '' + + '
    ' + + '

     ' + + text + + '

    ' + + '
    ' + }) + } else if (type === 2) { + //Error + $mdToast.show({ + hideDelay: 3000, + position: pinTo, + template: + '' + + '
    ' + + '

     ' + + text + + '

    ' + + '
    ' + }) + } else if (type === 3) { + //Warning + $mdToast.show({ + hideDelay: 3000, + position: pinTo, + template: + '' + + '
    ' + + '

     ' + + text + + '

    ' + + '
    ' + }) + } else { + $mdToast.show({ + //Info + hideDelay: 3000, + position: pinTo, + template: + '' + + '
    ' + + '

     ' + + text + + '

    ' + + '
    ' + }) + } + } } + + const showHeadToaster = (type, msg, delay = false) => { + $rootScope.$broadcast('showHeadToaster', { type, msg, delay }) + } + + const wazuhIsNotReady = text => { + try { + if (text instanceof Object && text.message.includes('ERROR3099')) { + $rootScope.$broadcast('wazuhNotReadyYet', {}) + return true + } else { + if (text.includes('ERROR3099')) { + $rootScope.$broadcast('wazuhNotReadyYet', {}) + return true + } + } + } catch (error) { + return false + } + } + return { - showSimpleToast: showSimpleToast + showSimpleToast: showSimpleToast, + showErrorToast: showErrorToast, + showSuccessToast: showSuccessToast, + showWarningToast: showWarningToast, + showHeadToaster: showHeadToaster } }) }) diff --git a/SplunkAppForWazuh/appserver/static/js/services/rawTableData/rawTableDataService.js b/SplunkAppForWazuh/appserver/static/js/services/rawTableData/rawTableDataService.js index ba96533c1..61c1cfdbc 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/rawTableData/rawTableDataService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/rawTableData/rawTableDataService.js @@ -13,8 +13,9 @@ define([ * @param {String} token * @param {String} value * @param {scope} scope + * @param {string} name */ - constructor(id, search, token, value, scope) { + constructor(id, search, token, value, scope, name) { super( new SearchEventHandler({ id: id, @@ -34,23 +35,26 @@ define([ ) mvc.Components.revokeInstance(this.id) this.token = token + this.name = name this.results = {} this.getSearch().on('search:failed', () => { + this.results = {} console.error('Failed search') }) this.getSearch().on('search:cancelled', () => { + this.results = {} console.error('Cancelled search') }) this.getSearch().on('search:error', error => { + this.results = {} console.error(error) }) this.getSearch().on('search:start', () => { this.results = {} - this.getSearch().trigger('result', this.results) }) this.getSearch().on('search:progress', () => {}) @@ -65,12 +69,10 @@ define([ tableData.on('data', data => { try { if (data._data) { - this.results = { - fields: tableData._data.fields, - rows: tableData._data.rows - } - this.getSearch().trigger('result', this.results) + this.results.fields = tableData._data.fields + this.results.rows = tableData._data.rows this.getSearch().finish = true + this.checkVizzStatus() } else { this.getSearch().finish = false } diff --git a/SplunkAppForWazuh/appserver/static/js/services/reporting/reportingService.js b/SplunkAppForWazuh/appserver/static/js/services/reporting/reportingService.js index 9270f466f..cadfbd7b2 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/reporting/reportingService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/reporting/reportingService.js @@ -4,18 +4,93 @@ define(['../module', 'jquery'], function(module, $) { constructor( $rootScope, vis2png, - // rawVisualizations, $currentDataService, $requestService, - $notificationService + $notificationService, + $navigationService ) { this.$rootScope = $rootScope this.vis2png = vis2png - // this.rawVisualizations = rawVisualizations - this.visHandlers = $currentDataService + this.currentDataService = $currentDataService this.genericReq = $requestService.httpReq this.apiReq = $requestService.apiReq - this.errorHandler = $notificationService.showSimpleToast + this.notification = $notificationService + this.navigationService = $navigationService + } + + /** + * Checks if is a float + */ + isFloat(n) { + return Number(n) === n && n % 1 !== 0 + } + + /** + * Checks if the search time range is between two dates + */ + betweenDates() { + try { + let { earliest_time, latest_time } = JSON.parse( + localStorage.getItem('searchTimeRange') + ) + earliest_time = parseFloat(earliest_time) + latest_time = parseFloat(latest_time) + if ( + isNaN(earliest_time) || + !earliest_time || + isNaN(latest_time) || + !latest_time + ) { + return false + } + if ( + Number.isInteger(earliest_time) || + (this.isFloat(earliest_time) && Number.isInteger(latest_time)) || + this.isFloat(latest_time) + ) { + return this.formatBetweenDates(earliest_time, latest_time) + } + } catch (error) { + return false + } + } + + /** + * Formats dates in milliseconds to a human readable format + */ + formatBetweenDates(earliest, latest) { + try { + //Remove milliseconds and multiply per 1000 to get a milliseconds date format + earliest = Math.trunc(earliest) * 1000 + latest = Math.trunc(latest) * 1000 + const eDate = this.formatDate(earliest) + const lDate = this.formatDate(latest) + return `${eDate} - ${lDate}` + } catch (error) { + throw new Error(error) + } + } + + /** + * Formats dates in YYYY-MM-DD HH:MM:SS format + */ + formatDate(date) { + try { + const d = new Date(date) + const year = d.getFullYear() + const month = + d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1 + const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate() + const hour = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours() + const minute = + d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes() + const second = + d.getSeconds() < 10 ? `0${d.getSeconds()}` : d.getSeconds() + const dateFormatted = `${year}-${month}-${day} ${hour}:${minute}:${second}` + return dateFormatted + } catch (error) { + return date + } } /** @@ -37,35 +112,39 @@ define(['../module', 'jquery'], function(module, $) { metrics = JSON.stringify(metrics) this.$rootScope.$broadcast('loadingReporting', { status: true }) if (this.vis2png.isWorking()) { - this.errorHandler('Report in progress') + this.notification.showSimpleToast('Report in progress') return } - this.$rootScope.reportBusy = true - this.$rootScope.reportStatus = 'Generating report...0%' if (!this.$rootScope.$$phase) this.$rootScope.$digest() this.vis2png.clear() - // const idArray = this.rawVisualizations.getList().map(item => item.id) - const idArray = vizz - - for (const item of idArray) { + for (const item of vizz) { const tmpHTMLElement = $(`#${item}`) this.vis2png.assignHTMLItem(item, tmpHTMLElement) } - const appliedFilters = this.visHandlers.getSerializedFilters() + const appliedFilters = this.currentDataService.getSerializedFilters() - const images = await this.vis2png.checkArray(idArray) + const images = await this.vis2png.checkArray(vizz) const name = `wazuh-${ isAgents ? 'agents' : 'overview' }-${tab}-${(Date.now() / 1000) | 0}.pdf` + let timeRange + //Search time range - const timeRange = document - .getElementById('timePicker') - .getElementsByTagName('span')[1].innerHTML + try { + timeRange = + this.betweenDates() || + document + .getElementById('timePicker') + .getElementsByTagName('span')[1].innerHTML + } catch (error) { + timeRange = false + } + const timeZone = new Date().getTimezoneOffset() const data = { images, tableResults, @@ -81,36 +160,45 @@ define(['../module', 'jquery'], function(module, $) { tables: appliedFilters.tables, pdfName: tab, section: isAgents ? 'agents' : 'overview', - isAgents + isAgents, + timeZone } - await this.genericReq('POST', '/report/generate', { data: JSON.stringify(data) }) - - this.$rootScope.reportBusy = false - this.$rootScope.reportStatus = false if (!this.$rootScope.$$phase) this.$rootScope.$digest() - this.errorHandler('Success. Go to Management -> Reporting') + try { + const reportingUrl = this.navigationService.updateURLParameter( + window.location.href, + 'currentTab', + 'mg-reporting' + ) + this.notification.showSuccessToast( + `Success. Go to Management -> Reporting ` + ) + } catch (error) { + this.notification.showSuccessToast( + 'Success. Go to Management -> Reporting' + ) + } this.$rootScope.$broadcast('loadingReporting', { status: false }) return } catch (error) { this.$rootScope.reportBusy = false this.$rootScope.reportStatus = false - this.errorHandler('Reporting error') + this.$rootScope.$broadcast('loadingReporting', { status: false }) + if (error === 'Impossible fetch visualizations') { + this.notification.showErrorToast(`Reporting error: ${error}.`) + } else { + this.notification.showErrorToast('Reporting error.') + } } } - async reportInventoryData( - tab, - sectionTitle, - queryFilters = '', - vizz = [], - metrics = {}, - tableResults = {}, - isAgents = 'inventory', - agentId - ) { + + async reportInventoryData(agentId) { try { + let tableResults = {} + let isAgents this.$rootScope.$broadcast('loadingReporting', { status: true }) //Get agent info and formating tables try { @@ -121,18 +209,30 @@ define(['../module', 'jquery'], function(module, $) { this.apiReq(`/syscollector/${agentId}/hardware`), this.apiReq(`/syscollector/${agentId}/os`) ]) + + const agentInfo = agent[0].data.data + const { + name, + id, + ip, + version, + manager, + os, + dateAdd, + lastKeepAlive, + group + } = agentInfo + isAgents = { - ID: agent[0].data.data.id, - Name: agent[0].data.data.name, - IP: agent[0].data.data.ip, - Version: agent[0].data.data.version, - Manager: agent[0].data.data.manager, - OS: `${agent[0].data.data.os.name} ${ - agent[0].data.data.os.codename - } ${agent[0].data.data.os.version}`, - dateAdd: agent[0].data.data.dateAdd, - lastKeepAlive: agent[0].data.data.lastKeepAlive, - group: agent[0].data.data.group.toString() + ID: id, + Name: name, + IP: ip, + Version: version, + Manager: manager, + OS: `${os.name} ${os.codename} ${os.version}`, + dateAdd: dateAdd, + lastKeepAlive: lastKeepAlive, + group: group.toString() } } catch (error) { isAgents = 'inventory' @@ -142,7 +242,8 @@ define(['../module', 'jquery'], function(module, $) { const netiface = await this.apiReq(`/syscollector/${agentId}/netiface`) const networkInterfaceKeys = ['Name', 'Mac', 'State', 'MTU', 'Type'] const networkInterfaceData = netiface.data.data.items.map(i => { - return [i.name, i.mac, i.state, i.mtu.toString(), i.type] + i.mtu = i.mtu ? i.mtu.toString() : 'undefined' + return [i.name, i.mac, i.state, i.mtu, i.type] }) const networkInterfaceTable = { fields: networkInterfaceKeys, @@ -154,7 +255,8 @@ define(['../module', 'jquery'], function(module, $) { const ports = await this.apiReq(`/syscollector/${agentId}/ports`) const networkPortsKeys = ['Local IP', 'Local Port', 'State', 'Protocol'] const networkPortsData = ports.data.data.items.map(p => { - return [p.local.ip, p.local.port.toString(), p.state, p.protocol] + p.local.port = p.local.port ? p.local.port.toString() : 'undefined' + return [p.local.ip, p.local.port, p.state, p.protocol] }) const networkPortsTable = { fields: networkPortsKeys, @@ -186,7 +288,8 @@ define(['../module', 'jquery'], function(module, $) { ) const processesKeys = ['Name', 'Euser', 'Nice', 'State'] const processesData = processes.data.data.items.map(n => { - return [n.name, n.euser, n.nice.toString(), n.state] + n.nice = n.nice ? n.nice.toString() : 'undefined' + return [n.name, n.euser, n.nice, n.state] }) const processesTable = { fields: processesKeys, rows: processesData } tableResults['Processes'] = processesTable @@ -200,32 +303,37 @@ define(['../module', 'jquery'], function(module, $) { const packagesTable = { fields: packagesKeys, rows: packagesData } tableResults['Packages'] = packagesTable - const images = vizz + const timeZone = new Date().getTimezoneOffset() + const data = { - images, + images: [], tableResults, - timeRange: '', - sectionTitle, - queryFilters, - metrics, - pdfName: tab, - isAgents + timeRange: false, + sectionTitle: 'Inventory Data', + queryFilters: '', + metrics: {}, + pdfName: 'agents-inventory', + isAgents, + timeZone } await this.genericReq('POST', '/report/generate', { data: JSON.stringify(data) }) - this.$rootScope.reportBusy = false - this.$rootScope.reportStatus = false if (!this.$rootScope.$$phase) this.$rootScope.$digest() - this.errorHandler('Success. Go to Management -> Reporting') + const reportingUrl = this.navigationService.updateURLParameter( + window.location.href, + 'currentTab', + 'mg-reporting' + ) + this.notification.showSuccessToast( + `Success. Go to Management -> Reporting ` + ) this.$rootScope.$broadcast('loadingReporting', { status: false }) return } catch (error) { - this.$rootScope.reportBusy = false - this.$rootScope.reportStatus = false - this.errorHandler('Reporting error') + this.notification.showErrorToast('Reporting error') } } } diff --git a/SplunkAppForWazuh/appserver/static/js/services/requestService/requestService.js b/SplunkAppForWazuh/appserver/static/js/services/requestService/requestService.js index e0d61e64a..203de1d2a 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/requestService/requestService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/requestService/requestService.js @@ -52,8 +52,9 @@ define(['../module'], function(module) { else if (method === 'POST') Object.assign(data, await $http.post(tmpUrl, $.param(payload))) // DELETE METHOD - else if (method === 'DELETE') + else if (method === 'DELETE') { Object.assign(data, await $http.post(tmpUrl, $.param(payload))) + } if (!data) { throw new Error( `Error doing a request to ${tmpUrl}, method: ${method}.` @@ -64,6 +65,7 @@ define(['../module'], function(module) { } return $q.resolve(data) } catch (error) { + console.error('errore in request ', error) return $q.reject(error) } } @@ -78,23 +80,99 @@ define(['../module'], function(module) { $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' const currentApi = $apiIndexStorageService.getApi() - const id = currentApi && currentApi.id ? currentApi.id : opts.id + const id = + currentApi && currentApi['_key'] ? currentApi['_key'] : opts['_key'] const payload = { id, endpoint, method } if (opts && typeof opts === `object`) { Object.assign(payload, opts) } - const result = await httpReq(`POST`, `/api/request`, payload) + const backPoint = payload.delay ? '/queue/add_job' : '/api/request' + const result = await httpReq('POST', backPoint, payload) + if ( + result && + result.data && + result.data.error && + result.data.error === 3099 + ) { + throw new Error('ERROR3099 - Wazuh not ready yet.') + } return result } catch (err) { return Promise.reject(err) } } + const wazuhIsReady = async (opts = null) => { + try { + $http.defaults.headers.post['Content-Type'] = + 'application/x-www-form-urlencoded' + const currentApi = $apiIndexStorageService.getApi() + const id = + currentApi && currentApi['_key'] ? currentApi['_key'] : opts['_key'] + const endpoint = '/api/wazuh_ready' + const method = 'GET' + const payload = { id, method } + const result = await httpReq('POST', endpoint, payload) + return result + } catch (err) { + return Promise.reject(err) + } + } + + const sendConfiguration = async (url, content) => { + try { + const result = await apiReq( + `${url}`, + { content, origin: 'xmleditor' }, + 'POST' + ) + if ( + !result || + !result.data || + !result.data.data || + result.data.error !== 0 || + (result.data.data.error && result.data.data.error !== 0) + ) { + if (result.data.error === 1905) { + return result + } else { + throw new Error( + result.data.message || result.data.error || 'Cannot send file.' + ) + } + } + return result + } catch (error) { + return Promise.reject(error) + } + } + + const getConfiguration = async url => { + try { + const result = await apiReq(url) + if ( + !result || + !result.data || + !result.data.data || + result.data.error !== 0 || + (result.data.data.error && result.data.data.error !== 0) + ) { + throw new Error('Cannot get file.') + } + return result + } catch (error) { + return Promise.reject(error) + } + } + const service = { getBaseUrl: getBaseUrl, getWellFormedUri: getWellFormedUri, apiReq: apiReq, - httpReq: httpReq + httpReq: httpReq, + sendConfiguration: sendConfiguration, + getConfiguration: getConfiguration, + wazuhIsReady: wazuhIsReady } return service }) diff --git a/SplunkAppForWazuh/appserver/static/js/services/restartService/restartService.js b/SplunkAppForWazuh/appserver/static/js/services/restartService/restartService.js new file mode 100644 index 000000000..313fcb904 --- /dev/null +++ b/SplunkAppForWazuh/appserver/static/js/services/restartService/restartService.js @@ -0,0 +1,120 @@ +define(['../module'], function(module) { + 'use strict' + module.service('$restartService', function($requestService) { + const restart = async () => { + try { + const clusterEnabled = await clusterIsEnabled() + if (clusterEnabled) { + return await restartCluster() + } else { + return await restartManager() + } + } catch (error) { + return Promise.reject(error) + } + } + + const restartManager = async () => { + try { + await checkConfig('/manager') + const result = await $requestService.apiReq( + '/manager/restart', + {}, + 'PUT' + ) + if (result && result.data && !result.data.error) { + return 'Restarting manager.' + } else { + throw 'Cannot send restart signal to the manager.' + } + } catch (error) { + return Promise.reject(error) + } + } + + const restartCluster = async () => { + try { + await checkConfig('/cluster') + const result = await $requestService.apiReq( + '/cluster/restart', + { delay: 15 }, + 'PUT' + ) + if (result && result.data && result.data.error !== 0) { + throw result.data.message || + result.data.error || + 'Cannot restart the cluster.' + } + return 'Restarting cluster, it will take up to 30 seconds.' + } catch (error) { + return Promise.reject('Cannot restart the cluster.: ' + error) + } + } + + const restartNode = async node => { + try { + const enabled = await clusterIsEnabled() + if (enabled) { + await checkConfig(`/cluster/${node}`) + const result = await $requestService.apiReq( + `/cluster/${node}/restart`, + {}, + 'PUT' + ) + if (result && result.data && !result.data.error) { + return `Restarting node ${node}, please wait.` + } else { + throw `Cannot send restart signal to the node: ${node}.` + } + } else { + await restartManager() + return `Restarting manager because cluster is disabled and cannot send the restart signal to ${node}.` + } + } catch (error) { + return Promise.reject(error || `Cannot restart the node: ${node}`) + } + } + + const clusterIsEnabled = async () => { + try { + const response = await $requestService.apiReq('/cluster/status') + const result = ((response || {}).data || {}).data || {} + const status = result.enabled === 'yes' && result.running === 'yes' + return status + } catch (error) { + return Promise.reject(error || 'Cannot send restart signal') + } + } + + const checkConfig = async node => { + try { + const check = await $requestService.apiReq( + `${node}/configuration/validation` + ) + if (check && check.data && !check.data.error) { + if (check.data.data.status === 'OK') { + return 'OK' + } else { + if (Array.isArray(check.data.data.details)) { + const msgErr = check.data.data.details.join() + return Promise.reject(msgErr) + } else { + return Promise.reject('Bad configuration, restart aborted.') + } + } + } else { + return Promise.reject( + check.data.message || 'Cannot check configuration.' + ) + } + } catch (error) { + return Promise.reject(error || 'Bad configuration, restart aborted.') + } + } + + return { + restart: restart, + restartNode: restartNode + } + }) +}) diff --git a/SplunkAppForWazuh/appserver/static/js/services/splunkStoreService/splunkStoreService.js b/SplunkAppForWazuh/appserver/static/js/services/splunkStoreService/splunkStoreService.js index eca5449db..54d5e6ecf 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/splunkStoreService/splunkStoreService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/splunkStoreService/splunkStoreService.js @@ -2,7 +2,7 @@ define(['../module'], function(module) { 'use strict' module.service('$splunkStoreService', function($requestService) { /** - * Select an API by ID + * Obtains all APIs * @param {Object} id */ const getAllApis = async () => { @@ -28,7 +28,11 @@ define(['../module'], function(module) { `/manager/get_api`, { id: id } ) - return data[0] + const parsed = JSON.parse(data) + const parsedJson = JSON.parse(parsed) + + const parsedData = parsedJson.data + return parsedData } catch (err) { return Promise.reject(err) } @@ -55,12 +59,12 @@ define(['../module'], function(module) { * DELETE method * @param {String} url */ - const deletes = async id => { + const deletes = async key => { try { const { data } = await $requestService.httpReq( `DELETE`, `manager/remove_api`, - id + { _key: key } ) if (data.error || data.status === 400) throw new Error(data.error) return data diff --git a/SplunkAppForWazuh/appserver/static/js/services/token-model/urlTokenModelService.js b/SplunkAppForWazuh/appserver/static/js/services/token-model/urlTokenModelService.js index 8f3566037..40cb17bc2 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/token-model/urlTokenModelService.js +++ b/SplunkAppForWazuh/appserver/static/js/services/token-model/urlTokenModelService.js @@ -23,13 +23,16 @@ define([ this.urlTokenModel.on('url:navigate', () => { this.defaultTokenModel.set(this.urlTokenModel.toJSON()) - if ( - !_.isEmpty(this.urlTokenModel.toJSON()) && // eslint-disable-line - !_.all(this.urlTokenModel.toJSON(), _.isUndefined) // eslint-disable-line - ) { - this.submitTokens() - } else { - this.submittedTokenModel.clear() + if (typeof _.isEmpty !== 'undefined') { + //eslint-disable-line + if ( + !_.isEmpty(this.urlTokenModel.toJSON()) && // eslint-disable-line + !_.all(this.urlTokenModel.toJSON(), _.isUndefined) // eslint-disable-line + ) { + this.submitTokens() + } else { + this.submittedTokenModel.clear() + } } }) } diff --git a/SplunkAppForWazuh/appserver/static/js/services/vis2png/vis2png.js b/SplunkAppForWazuh/appserver/static/js/services/vis2png/vis2png.js index 94076561f..fb59116fd 100644 --- a/SplunkAppForWazuh/appserver/static/js/services/vis2png/vis2png.js +++ b/SplunkAppForWazuh/appserver/static/js/services/vis2png/vis2png.js @@ -29,27 +29,51 @@ define(['../module', 'domToImg'], function(app, domToImg) { let currentCompleted = 0 await Promise.all( visArray.map(async currentValue => { - const tmpNode = this.htmlObject[currentValue] - const title = document - .getElementById(currentValue) - .parentElement.getElementsByTagName('span')[0].innerHTML - const classes = document - .getElementById(currentValue) - .className.split(' ') + const tmpNode = $('#' + currentValue + ' .panel-body') + const noResults = $('#' + currentValue + ' .panel-body .alert') + let error = false + if (noResults.length > 0) { + error = true + } + + let classes = '' + let title = '' + try { + //Try to fetch the title of the visualization + title = document + .getElementById(currentValue) + .parentElement.getElementsByTagName('span')[0].innerHTML + + if (title.search(' { + try { + localStorage.setItem('searchTimeRange', JSON.stringify(newValue)) + } catch (error) {} //eslint-disable-line if (newValue && this.input) this.handleValueChange(this.input) }) } diff --git a/SplunkAppForWazuh/appserver/static/js/utils/config-handler.js b/SplunkAppForWazuh/appserver/static/js/utils/config-handler.js index e53bd0f70..03daf677b 100644 --- a/SplunkAppForWazuh/appserver/static/js/utils/config-handler.js +++ b/SplunkAppForWazuh/appserver/static/js/utils/config-handler.js @@ -39,7 +39,13 @@ define([ * @param {string} configurationTab The configuration tab to open * @param {Array} sections Array that includes sections to be fetched */ - async switchConfigTab(configurationTab, sections, $scope, agentId = false) { + async switchConfigTab( + configurationTab, + sections, + $scope, + agentId = false, + node = false + ) { try { $scope.load = true $scope.currentConfig = null @@ -48,9 +54,10 @@ define([ $scope.configurationSubTab = false $scope.configurationTab = configurationTab const currentConfigReq = await queryConfig( - agentId || '000', sections, - this.apiReq + this.apiReq, + agentId, + node ) $scope.currentConfig = currentConfigReq if (sections[0].component === 'integrator') { @@ -59,8 +66,11 @@ define([ $scope ) } else if (sections[0].component === 'logcollector') { - const logcollector = - currentConfigReq['logcollector-localfile'].localfile + const logcollector = currentConfigReq['logcollector-localfile'].localfile + $scope.currentConfig['logcollector-localfile']['localfile-logs'] = + logcollector.filter(log => log.logformat !== 'command' && log.logformat !== 'full_command') + $scope.currentConfig['logcollector-localfile']['localfile-commands'] = + logcollector.filter(log => log.logformat === 'command' || log.logformat === 'full_command') logcollector.map(log => { const keys = Object.keys(log) if ( @@ -76,9 +86,8 @@ define([ $scope.integrations = {} } $scope.load = false - if (!$scope.$$phase) $scope.$digest() + $scope.$applyAsync() } catch (error) { - this.errorHandler.showSimpleToast(error, 'Manager') $scope.load = false } return @@ -88,7 +97,7 @@ define([ * Switchs to a wodle section * @param {string} wodleName The wodle to open */ - async switchWodle(wodleName, $scope, agentId = false) { + async switchWodle(wodleName, $scope, agentId = false, node = false) { try { $scope.load = true $scope.currentConfig = null @@ -98,9 +107,10 @@ define([ $scope.configurationTab = wodleName $scope.currentConfig = await queryConfig( - agentId || '000', [{ component: 'wmodules', configuration: 'wmodules' }], - this.apiReq + this.apiReq, + agentId, + node ) // Filter by provided wodleName @@ -124,7 +134,7 @@ define([ } $scope.load = false - if (!$scope.$$phase) $scope.$digest() + $scope.$applyAsync() } catch (error) { this.errorHandler.showSimpleToast(error, 'Manager') $scope.load = false @@ -143,7 +153,7 @@ define([ $scope.JSONContent = false $scope.configurationSubTab = false $scope.configurationTab = configurationTab - if (!$scope.$$phase) $scope.$digest() + $scope.$applyAsync() } /** @@ -155,7 +165,7 @@ define([ $scope.XMLContent = false $scope.JSONContent = false $scope.configurationSubTab = configurationSubTab - if (!$scope.$$phase) $scope.$digest() + $scope.$applyAsync() } /** @@ -172,11 +182,12 @@ define([ try { const cleaned = objectWithoutProperties(config) $scope.XMLContent = XMLBeautifier(js2xmlparser(cleaned)) + $scope.$broadcast('XMLContentReady', { data: $scope.XMLContent }) } catch (error) { $scope.XMLContent = false } } - if (!$scope.$$phase) $scope.$digest() + $scope.$applyAsync() } /** @@ -192,12 +203,13 @@ define([ } else { try { const cleaned = objectWithoutProperties(config) - $scope.JSONContent = this.beautifier.prettyPrint(cleaned) + $scope.JSONContent = JSON.stringify(cleaned, null, 2) + $scope.$broadcast('JSONContentReady', { data: $scope.JSONContent }) } catch (error) { $scope.JSONContent = false } } - if (!$scope.$$phase) $scope.$digest() + $scope.$applyAsync() } reset($scope) { diff --git a/SplunkAppForWazuh/appserver/static/js/utils/query-config.js b/SplunkAppForWazuh/appserver/static/js/utils/query-config.js index 3d6257782..e9c97647e 100644 --- a/SplunkAppForWazuh/appserver/static/js/utils/query-config.js +++ b/SplunkAppForWazuh/appserver/static/js/utils/query-config.js @@ -6,11 +6,16 @@ */ define([], function() { 'use strict' - return async function queryConfig(agentId, sections, apiReq) { + return async function queryConfig( + sections, + apiReq, + agentId = false, + node = false + ) { try { if ( - !agentId || - typeof agentId !== 'string' || + (agentId && typeof agentId !== 'string') || + (node && typeof node !== 'string') || !sections || !sections.length || typeof sections !== 'object' || @@ -30,9 +35,25 @@ define([], function() { ) { throw new Error('Invalid section') } - const partialResult = await apiReq.apiReq( - `/agents/${agentId}/config/${component}/${configuration}` - ) + + // Gets manager, node or agent config + let partialResult = {} + if (agentId && !node) { + partialResult = await apiReq.apiReq( + `/agents/${agentId}/config/${component}/${configuration}` + ) + } else if (!agentId && node) { + partialResult = await apiReq.apiReq( + `/cluster/${node}/config/${component}/${configuration}` + ) + } else if (!agentId && !node) { + partialResult = await apiReq.apiReq( + `/manager/config/${component}/${configuration}` + ) + } else { + throw new Error('Invalid host instance.') + } + result[`${component}-${configuration}`] = partialResult.data.data if (partialResult.data.error) { result[`${component}-${configuration}`] = partialResult.data.message diff --git a/SplunkAppForWazuh/bin/check_queue.py b/SplunkAppForWazuh/bin/check_queue.py new file mode 100644 index 000000000..66e75d179 --- /dev/null +++ b/SplunkAppForWazuh/bin/check_queue.py @@ -0,0 +1,196 @@ +# -*- coding: utf-8 -*- +""" +Wazuh app - Report generation backend. + +Copyright (C) 2015-2019 Wazuh, Inc. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +Find more information about this on the LICENSE file. +""" + +from log import log +import time +import datetime +import jsonbak +import requestsbak +import sys +from jobs_queue import JobsQueue +from db import database + + +class CheckQueue(): + + def __init__(self): + """Constructor.""" + self.logger = log() + self.now = time.time() # Get the date in seconds + self.session = requestsbak.Session() + self.auth_key = sys.stdin.readline().strip() + self.q = JobsQueue() + self.db = database() + + def init(self): + """Inits the jobs + """ + try: + jobs = self.q.get_jobs(self.auth_key) + #undone_jobs = self.get_undone_jobs(jobs) + # self.check_undone_jobs(undone_jobs) + jobs = jsonbak.loads(jobs) + self.check_undone_jobs(jobs) + except Exception as e: + self.logger.error( + 'Error at init in the CheckQueue module: {}'.format(e)) + + def get_undone_jobs(self, jobs): + """Gets the undone jobs + + Parameters + ---------- + str: jobs + A dictionary in string format with the jobs + """ + + try: + jobs = jsonbak.loads(jobs) + undone_jobs = filter(lambda j: j['done'] == False, jobs) + except TypeError as e: + undone_jobs = [] + self.logger.error( + 'Error filtering the fields in the CheckQueue module: {}'.format(e)) + return undone_jobs + + def check_undone_jobs(self, jobs): + """Check the undone jobs + + Parameters + ---------- + dic: jobs + A dictionary with the undone jobs + """ + try: + for job in jobs: + if job['exec_time'] < self.now: + self.exec_job(job) + except Exception as e: + self.logger.error( + 'Error checking undone jobs the fields in the CheckQueue module: {}'.format(e)) + + def exec_job(self, job): + """Exec the passed job + + Parameters + ---------- + dic: job + A dictionary with the job + """ + try: + req = job['job'] + method = 'GET' + + # Checks if are missing params + if 'id' not in req or 'endpoint' not in req: + raise Exception('Missing ID or endpoint') + if 'method' in req.keys() and req['method'] != 'GET': + method = req['method'] + del req['method'] + + api_id = req['id'] + url, auth, verify = self.get_api_credentials(api_id) + endpoint = req['endpoint'] + + # Checks methods + if method == 'GET': + request = self.session.get( + url + endpoint, params=req, auth=auth, + verify=verify).json() + if method == 'POST': + request = self.session.post( + url + endpoint, data=req, auth=auth, + verify=verify).json() + if method == 'PUT': + request = self.session.put( + url + endpoint, data=req, auth=auth, + verify=verify).json() + if method == 'DELETE': + request = self.session.delete( + url + endpoint, data=req, auth=auth, + verify=verify).json() + + if request['error'] == 0: + # self.mark_as_done(job) + self.remove_job(job['_key']) + else: + raise Exception('Job cannot be executed properly.') + return request + except Exception as e: + self.logger.error( + 'Error executing the job in CheckQueue module: {}'.format(e)) + + def mark_as_done(self, job): + """Update the job and mark as done. + + Parameters + ---------- + str: job_key + The job key in the kvStore + """ + try: + job['done'] = True + self.q.update_job(job, self.auth_key) + except Exception as e: + self.logger.error( + 'Error updating the job in CheckQueue module: {}'.format(e)) + + def remove_job(self, job_key): + """Remove the job of the queue. + + Parameters + ---------- + str: job_key + The job key in the kvStore + """ + try: + self.q.remove_job(job_key, self.auth_key) + except Exception as e: + self.logger.error( + 'Error removing the job in CheckQueue module: {}'.format(e)) + + def get_api_credentials(self, api_id): + """Get API credentials. + + Parameters + ---------- + str: api_id + The API id + """ + try: + api = self.db.get(api_id, self.auth_key) + api = jsonbak.loads(api) + if api: + opt_username = api['data']["userapi"] + opt_password = api['data']["passapi"] + opt_base_url = api['data']["url"] + opt_base_port = api['data']["portapi"] + url = str(opt_base_url) + ":" + str(opt_base_port) + auth = requestsbak.auth.HTTPBasicAuth( + opt_username, opt_password) + verify = False + return url, auth, verify + else: + raise Exception('API not found') + except Exception as e: + raise e + + +if __name__ == '__main__': + try: + cq = CheckQueue() + cq.init() + except Exception as e: + log().error( + 'Error at main function in CheckQueue module: {}'.format(e)) diff --git a/SplunkAppForWazuh/bin/db.py b/SplunkAppForWazuh/bin/db.py index 9728ef47b..31f479f1e 100644 --- a/SplunkAppForWazuh/bin/db.py +++ b/SplunkAppForWazuh/bin/db.py @@ -1,37 +1,35 @@ -# -*- coding: utf-8 -*- -""" -Wazuh app - Database backend. - -Copyright (C) 2015-2019 Wazuh, Inc. - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. - -Find more information about this on the LICENSE file. -""" - +# +# Wazuh app - Database backend +# Copyright (C) 2018 Wazuh, Inc. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# Find more information about this on the LICENSE file. +# import jsonbak +import requestsbak import os -# from splunk import AuthorizationFailed as AuthorizationFailed -from tinydb import TinyDB, Query -# sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".")) +from splunk.appserver.mrsparkle.lib.util import make_splunkhome_path from log import log -import threading - +import splunk +from splunk import entity, rest class database(): - """Handle CRUD methods for DB.""" - def __init__(self): - """Constructor.""" self.logger = log() - self.origin = TinyDB(os.path.dirname( - os.path.abspath(__file__))+'/apilist.json') - self.db = self.origin.table('apis', cache_size=0) - self.Api = Query() - self.mutex = threading.Lock() + self.session = requestsbak.Session() + self.session.trust_env = False + self.kvstoreUri = entity.buildEndpoint( + entityClass=["storage", "collections", "data"], + entityName="credentials", + owner="nobody", + namespace="SplunkAppForWazuh", + hostPath=rest.makeSplunkdUri().strip("/") + ) + self.sessionKey = splunk.getSessionKey() def insert(self, obj): """Insert a new API. @@ -42,14 +40,16 @@ def insert(self, obj): The new API """ - with self.mutex: - try: - result = self.db.insert(obj) - parsed_result = jsonbak.dumps({'data': result}) - except Exception as e: - self.logger.error("Error inserting in DB module: %s" % (e)) - raise e - return parsed_result + try: + kvstoreUri = self.kvstoreUri+'?output_mode=json' + result = self.session.post(kvstoreUri, data=obj, headers={"Authorization": "Splunk %s" % splunk.getSessionKey(), "Content-Type": "application/json"}, verify=False).json() + if not '_key' in result: + raise Exception('Format error when inserting object.') + key = result['_key'] + return key + except Exception as e: + self.logger.error("Error inserting in DB module: %s" % (e)) + raise e def update(self, obj): """Update an already inserted API. @@ -60,16 +60,21 @@ def update(self, obj): The API to edit. """ - with self.mutex: - try: - self.db.update(obj, self.Api.id == obj['id']) - parsed_result = jsonbak.dumps({'data': 'success'}) - except Exception as e: - self.logger.error("Error updating in DB module: %s" % (e)) - raise e + try: + if not '_key' in obj: + raise Exception('Missing Key') + id = obj['_key'] + del obj['_key'] + obj = jsonbak.dumps(obj) + kvstoreUri = self.kvstoreUri+'/'+id+'?output_mode=json' + result = self.session.post(kvstoreUri, data=obj, headers={"Authorization": "Splunk %s" % splunk.getSessionKey(), "Content-Type": "application/json"}, verify=False).json() + parsed_result = jsonbak.dumps({'data': result}) return parsed_result + except Exception as e: + self.logger.error("Error updating in DB module: %s" % (e)) + raise e - def remove(self, id): + def remove(self, _key): """Remove an API. Parameters @@ -78,38 +83,41 @@ def remove(self, id): The API to be removed. """ - with self.mutex: - try: - self.db.remove(self.Api.id == id) - parsed_result = jsonbak.dumps({'data': 'success'}) - except Exception as e: - self.logger.error("Error removing in DB module: %s" % (e)) - raise e + try: + if not _key: + raise Exception('Missing ID in remove DB module') + kvstoreUri = self.kvstoreUri+'/'+str(_key)+'?output_mode=json' + result = self.session.delete(kvstoreUri,headers={"Authorization": "Splunk %s" % splunk.getSessionKey(), "Content-Type": "application/json"}, verify=False) + if result.status_code == 200: + parsed_result = jsonbak.dumps({'data': 'API removed.'}) + else: + msg = jsonbak.loads(result.text) + text = msg['messages'][0]['text'] + raise Exception(text) return parsed_result - - def all(self): - """Obtain the full API list.""" - with self.mutex: - try: - all = self.db.all() - except Exception as e: - self.logger.error("Error at get all documents DB module: %s" % (e)) - raise e - return all - - def get(self, id): - """Get API by ID. - - Parameters - ---------- - id : unicode - The API ID - - """ - with self.mutex: - try: - data = self.db.search(self.Api.id == id) - except Exception as e: - self.logger.error("Error at get document DB: %s" % (e)) - raise e - return data + except Exception as e: + self.logger.error("Error removing an API in DB module: %s" % (e)) + raise e + + def all(self, session_key=False): + try: + kvstoreUri = self.kvstoreUri+'?output_mode=json' + auth_key = session_key if session_key else splunk.getSessionKey() + result = self.session.get(kvstoreUri, headers={"Authorization": "Splunk %s" % auth_key, "Content-Type": "application/json"}, verify=False).json() + return jsonbak.dumps(result) + except Exception as e: + self.logger.error('Error returning all API rows in DB module: %s ' % (e)) + return jsonbak.dumps({"error": str(e)}) + + def get(self, id, session_key=False): + try: + if not id: + raise Exception('Missing ID') + kvstoreUri = self.kvstoreUri+'/'+id+'?output_mode=json' + auth_key = session_key if session_key else splunk.getSessionKey() + result = self.session.get(kvstoreUri,headers={"Authorization": "Splunk %s" % auth_key, "Content-Type": "application/json"}, verify=False).json() + parsed_result = jsonbak.dumps({'data': result}) + except Exception as e: + self.logger.error("Error getting an API in DB module : %s" % (e)) + raise e + return parsed_result \ No newline at end of file diff --git a/SplunkAppForWazuh/bin/get_agents_status.py b/SplunkAppForWazuh/bin/get_agents_status.py index 34ded3006..9440556cb 100644 --- a/SplunkAppForWazuh/bin/get_agents_status.py +++ b/SplunkAppForWazuh/bin/get_agents_status.py @@ -20,6 +20,7 @@ import datetime from db import database from log import log +import sys db = database() logger = log() @@ -28,7 +29,8 @@ def get_apis(): """Obtain the list of APIs.""" try: - data_temp = db.all() + session_key = getSplunkSessionKey() + data_temp = db.all(session_key) except Exception as e: return jsonbak.dumps({'error': str(e)}) return data_temp @@ -38,6 +40,7 @@ def check_status(): """Check status of agents.""" try: apis = get_apis() + apis = jsonbak.loads(apis) #get_apis() returns a JSON string, it needs to be converted as a dictionary date = str(datetime.datetime.utcnow())[:-7] # obtains for api in apis: @@ -46,7 +49,7 @@ def check_status(): opt_base_url = api["url"] opt_base_port = api["portapi"] agent_list = {} - url = opt_base_url + ":" + opt_base_port + url = str(opt_base_url) + ":" + str(opt_base_port) auth = requestsbak.auth.HTTPBasicAuth(opt_username, opt_password) verify = False agents_url_total_items = url + '/agents?limit=1&q=id!=000' @@ -100,4 +103,9 @@ def check_status(): pass -check_status() +def getSplunkSessionKey(): + """Get the session key, it needs to configure in the inputs.conf that executes this script the following parameter: passAuth = splunk-system-user""" + session_key = sys.stdin.readline().strip() + return session_key + +check_status() \ No newline at end of file diff --git a/SplunkAppForWazuh/bin/jobs_queue.py b/SplunkAppForWazuh/bin/jobs_queue.py new file mode 100644 index 000000000..8a1cc7a4f --- /dev/null +++ b/SplunkAppForWazuh/bin/jobs_queue.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +""" +Wazuh app - Report generation backend. + +Copyright (C) 2015-2019 Wazuh, Inc. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +Find more information about this on the LICENSE file. +""" + +import jsonbak +import requestsbak +from log import log +# from splunk import AuthorizationFailed as AuthorizationFailed +import splunk +from splunk import entity, rest + + +class JobsQueue(): + """Handle queue endpoints""" + + def __init__(self): + """Constructor.""" + try: + self.logger = log() + self.session = requestsbak.Session() + self.session.trust_env = False + self.kvstoreUri = entity.buildEndpoint( + entityClass=["storage", "collections", "data"], + entityName="jobs", + owner="nobody", + namespace="SplunkAppForWazuh", + hostPath=rest.makeSplunkdUri().strip("/") + ) + self.sessionKey = splunk.getSessionKey() + except Exception as e: + self.logger.error("Error in queue module constructor: %s" % (e)) + + def insert_job(self, job, session_key=False): + """Insert a job. + + Parameters + ---------- + dic : job + The job information + str : session_key + The authorized session key + + """ + try: + kvstoreUri = self.kvstoreUri+'?output_mode=json' + auth_key = session_key if session_key else splunk.getSessionKey() + job = jsonbak.dumps(job) + result = self.session.post(kvstoreUri, data=job, headers={ + "Authorization": "Splunk %s" % auth_key, "Content-Type": "application/json"}, verify=False).json() + return jsonbak.dumps(result) + except Exception as e: + self.logger.error( + 'Error inserting a job in JobsQueue module: %s ' % (e)) + return jsonbak.dumps({"error": str(e)}) + + def update_job(self, job, session_key=False): + """Update an already inserted API. + + Parameters + ---------- + obj : dict + The API to edit. + + """ + try: + if not '_key' in job: + raise Exception('Missing Key') + id = job['_key'] + del job['_key'] + job = jsonbak.dumps(job) + kvstoreUri = self.kvstoreUri+'/'+id+'?output_mode=json' + auth_key = session_key if session_key else splunk.getSessionKey() + result = self.session.post(kvstoreUri, data=job, headers={ + "Authorization": "Splunk %s" % auth_key, "Content-Type": "application/json"}, verify=False).json() + if '_key' in result.keys() and result['_key'] == id: + return 'Job updated.' + else: + raise Exception('Job cannot be updated.') + except Exception as e: + self.logger.error("Error updating in JobsQueue module: %s" % (e)) + raise e + + def remove_job(self, _key, session_key=False): + """Remove an API. + + Parameters + ---------- + obj : dict + The API to be removed. + + """ + try: + if not _key: + raise Exception('Missing ID in remove JobQueue module') + kvstoreUri = self.kvstoreUri+'/'+str(_key)+'?output_mode=json' + auth_key = session_key if session_key else splunk.getSessionKey() + result = self.session.delete(kvstoreUri, headers={ + "Authorization": "Splunk %s" % auth_key, "Content-Type": "application/json"}, verify=False) + if result.status_code == 200: + return 'Job removed.' + else: + msg = jsonbak.loads(result.text) + text = msg['messages'][0]['text'] + raise Exception(text) + except Exception as e: + self.logger.error( + "Error removing a Job in JobsQueue module: %s" % (e)) + raise e + + def get_jobs(self, session_key=False): + """Get all jobs. + + Parameters + ---------- + str : session_key + The authorized session key + + """ + try: + kvstoreUri = self.kvstoreUri+'?output_mode=json' + auth_key = session_key if session_key else splunk.getSessionKey() + result = self.session.get(kvstoreUri, headers={ + "Authorization": "Splunk %s" % auth_key, "Content-Type": "application/json"}, verify=False).json() + return jsonbak.dumps(result) + except Exception as e: + self.logger.error( + 'Error getting the jobs queue in JobsQueue module: %s ' % (e)) + raise e diff --git a/SplunkAppForWazuh/bin/requirements/__init__.py b/SplunkAppForWazuh/bin/requirements/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/SplunkAppForWazuh/bin/requirements/gdpr_requirements.py b/SplunkAppForWazuh/bin/requirements/gdpr_requirements.py new file mode 100644 index 000000000..79ef24d31 --- /dev/null +++ b/SplunkAppForWazuh/bin/requirements/gdpr_requirements.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +""" +Wazuh app - GDPR requirements module. + +Copyright (C) 2015-2019 Wazuh, Inc. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +Find more information about this on the LICENSE file. +""" + +gdpr = { + 'II_5.1.f': + 'Ensure the ongoing confidentiality, integrity, availability and resilience of processing systems and services, verifying its modifications, accesses, locations and guarantee the safety of them.
    File sharing protection and file sharing technologies that meet the requirements of data protection.', + 'III_14.2.c': ' Restrict the processing of personal data temporarily.', + 'III_17': ' Permanently erase personal information of a subject.', + 'IV_24.2': + 'Be able to demonstrate compliance with the GDPR by complying with data protection policies.', + 'IV_28': + ' Ensure data protection during processing, through technical and organizational measures.', + 'IV_30.1.g': + 'It is necessary to keep all processing activities documented, to carry out an inventory of data from beginning to end and an audit, in order to know all the places where personal and sensitive data are located, processed, stored or transmitted.', + 'IV_32.1.c': + 'Data Loss Prevention (DLP) capabilities to examine data flows and identify personal data that is not subject to adequate safeguards or authorizations. DLP tools can block or quarantine such data flows. Classify current data appropriately to determine specific categories of data that will be subject to the GDPR.', + 'IV_32.2': + 'Account management tools that closely monitor actions taken by standard administrators and users who use standard or privileged account credentials are required to control access to data. ', + 'IV_33': + ' Notify the supervisory authority of a violation of the data in 72 hours and in certain cases, the injured parties.', + 'IV_35.1': + 'Perform a data protection impact evaluation for high risk processes. Implement appropriate technical measures to safeguard the rights and freedoms of data subjects, informed by an assessment of the risks to these rights and freedoms.', + 'IV_35.7.d': + 'Capabilities for identification, blocking and forensic investigation of data breaches by malicious actors, through compromised credentials, unauthorized network access, persistent threats and verification of the correct operation of all components.
    Network perimeter and endpoint security tools to prevent unauthorized access to the network, prevent the entry of unwanted data types and malicious threats. Anti-malware and anti-ransomware to prevent malware and ransomware threats from entering your devices.
    A behavioral analysis that uses machine intelligence to identify people who do anomalous things on the network, in order to give early visibility and alert employees who start to become corrupt.' +} diff --git a/SplunkAppForWazuh/bin/requirements/pci_requirements.py b/SplunkAppForWazuh/bin/requirements/pci_requirements.py new file mode 100644 index 000000000..a72a03fdb --- /dev/null +++ b/SplunkAppForWazuh/bin/requirements/pci_requirements.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- +""" +Wazuh app - GDPR requirements module. + +Copyright (C) 2015-2019 Wazuh, Inc. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +Find more information about this on the LICENSE file. +""" + +pci = { + '1.1.1': + 'A formal process for approving and testing all network connections and changes to the firewall and router configurations', + '1.3.4': + 'Do not allow unauthorized outbound traffic from the cardholder data environment to the Internet.', + '1.4': + 'Install personal firewall software or equivalent functionality on any portable computing devices (including company and/or employee-owned) that connect to the Internet when outside the network (for example, laptops used by employees), and which are also used to access the CDE. Firewall (or equivalent) configurations include:
    • Specific configuration settings are defined.
    • Personal firewall (or equivalent functionality) is actively running.
    • Personal firewall (or equivalent functionality) is not alterable by users of the portable computing devices.
    ', + '2.2': + 'Develop configuration standards for all system components. Assure that these standards address all known security vulnerabilities and are consistent with industry accepted system hardening standards (CIS, ISO, SANS, NIST).', + '2.2.2': + 'Enable only necessary services, protocols, daemons, etc., as required for the function of the system. ', + '2.2.3': + 'Implement additional security features for any required services, protocols, or daemons that are considered to be insecure', + '2.2.4': 'Configure system security parameters to prevent misuse.', + '4.1': + 'Use strong cryptography and security protocols (for example, SSL/TLS, IPSEC, SSH, etc.) to safeguard sensitive cardholder data during transmission over open, public networks, including the following:
    • Only trusted keys and certificates are accepted.
    • The protocol in use only supports secure versions or configurations.
    • The encryption strength is appropriate for the encryption methodology in use
    ', + '5.1': + 'Deploy anti-virus software on all systems commonly affected by malicious software (particularly personal computers and servers).', + '5.2': + 'Ensure that all anti-virus mechanisms are maintained as follows:
    • Are kept current
    • Perform periodic scans
    • Generate audit logs which are retained per PCI DSS Requirement 10.7.
    ', + '6.2': + 'Ensure that all system components and software are protected from known vulnerabilities by installing applicable vendor-supplied security patches. Install critical security patches within one month of release.', + '6.5': + 'Address common coding vulnerabilities in software development processes as follows:
    • Train developers in secure coding techniques, including how to avoid common coding vulnerabilities, and understanding how sensitive data is handled in memory.
    • Develop applications based on secure coding guidelines
    ', + '6.5.1': + 'Injection flaws, particularly SQL injection. Also consider OS Command Injection, LDAP and XPath injection flaws as well as other injection flaws.', + '6.5.2': 'Buffer overflows', + '6.5.5': 'Improper error handling', + '6.5.7': 'Cross-site scripting (XSS)', + '6.5.8': + 'Improper access control (such an insecure direct object references, failure to restrict URL access, directory traversal, and failure to restrict user access to functions).', + '6.5.10': 'Broken authentication and session management.', + '6.6': + 'For public-facing web applications, address new threats and vulnerabilities on an ongoing basis and ensure these applications are protected against known attacks by either of the following methods:
    • Reviewing public-facing web applications via manual or automated application vulnerability security assessment tools or methods, at least annually and after any changes
    • Installing an automated technical solution that detects and prevents web-based attacks (for example, a web-application firewall) in front of public-facing web applications, to continually check all traffic.
    ', + '8.1.2': + 'Control addition, deletion, and modification of user IDs, credentials, and other identifier objects.', + '8.1.4': 'Remove/disable inactive user accounts within 90 days.', + '8.1.5': + 'Manage IDs used by third parties to access, support, or maintain system components via remote access as follows:
    • Enabled only during the time period needed and disabled when not in use.
    • Monitored when in use.
    ', + '8.1.6': + 'Limit repeated access attempts by locking out the user ID after not more than six attempts.', + '8.1.8': + 'If a session has been idle for more than 15 minutes, require the user to reauthenticate to re-activate the terminal or session.', + '8.2.4': 'Change user passwords/passphrases at least once every 90 days.', + '8.5.1': + 'Additional requirement for service providers: Service providers with remote access to customer premises (for example, for support of POS systems or servers) must use a unique authentication credential (such as a password/phrase) for each customer.', + '8.7': + 'All access to any database containing cardholder data (including access by applications, administrators, and all other users) is restricted as follows:
    • All user access to, user queries of, and user actions on databases are through programmatic methods.
    • Only database administrators have the ability to directly access or query databases.
    • Application IDs for database applications can only be used by the applications (and not by individual users or other non-application processes).
    ', + '10.1': + 'Implement audit trails to link all access to system components to each individual user.', + '10.2.1': 'All individual user accesses to cardholder data', + '10.2.2': + 'All actions taken by any individual with root or administrative privileges.', + '10.2.4': 'Invalid logical access attempts', + '10.2.5': + 'Use of and changes to identification and authentication mechanisms including but not limited to creation of new accounts and elevation of privileges and all changes, additions, or deletions to accounts with root or administrative privileges.', + '10.2.6': 'Initialization, stopping, or pausing of the audit logs', + '10.2.7': 'Creation and deletion of system level objects', + '10.5.2': 'Protect audit trail files from unauthorized modifications', + '10.5.5': + 'Use file integrity monitoring or change detection software on logs to ensure that existing log data cannot be changed without generating alerts (although new data being added should not cause an alert).', + '10.4': + 'Using time-synchronization technology, synchronize all critical system clocks and times and ensure that the following is implemented for acquiring, distributing, and storing time.', + '10.6': + 'Review logs and security events for all system components to identify anomalies or suspicious activity', + '10.6.1': + 'Review the following at least daily:
    • All security events
    • Logs of all system components that store, process, or transmit CHD and/or SAD, or that could
    • impact the security of CHD and/or SAD
    • Logs of all critical system components
    • Logs of all servers and system components that perform security functions (for example, firewalls, intrusion detection systems/intrusion prevention systems (IDS/IPS), authentication servers, ecommerce redirection servers, etc.)
    ', + '11.4': + 'Use intrusion detection and/or intrusion prevention techniques to detect and/or prevent intrusions into the network.
    Monitor all traffic at the perimeter of the cardholder data environment as well as at critical points in the cardholder data environment, and alert personnel to suspected compromises. Keep all intrusion detection and prevention engines, baselines, and signatures up to date.', + '11.5': + 'Deploy a change detection mechanism (for example, file integrity monitoring tools) to alert personnel to unauthorizeumodification of critical system files, configuration files, or content files; and configure the software to perform critical file comparisons at least weekly.' +} \ No newline at end of file diff --git a/SplunkAppForWazuh/bin/tinydb/__init__.py b/SplunkAppForWazuh/bin/tinydb/__init__.py deleted file mode 100644 index f390eac78..000000000 --- a/SplunkAppForWazuh/bin/tinydb/__init__.py +++ /dev/null @@ -1,31 +0,0 @@ -""" -TinyDB is a tiny, document oriented database optimized for your happiness :) - -TinyDB stores differrent types of python data types using a configurable -backend. It has support for handy querying and tables. - -.. codeauthor:: Markus Siemens - -Usage example: - ->>> from tinydb. import TinyDB, where ->>> from tinydb.storages import MemoryStorage ->>> db = TinyDB(storage=MemoryStorage) ->>> db.insert({'data': 5}) # Insert into '_default' table ->>> db.search(where('data') == 5) -[{'data': 5, '_id': 1}] ->>> # Now let's create a new table ->>> tbl = db.table('our_table') ->>> for i in range(10): -... tbl.insert({'data': i}) -... ->>> len(tbl.search(where('data') < 5)) -5 -""" - -from .queries import Query, where -from .storages import Storage, JSONStorage -from .database import TinyDB -from .version import __version__ - -__all__ = ('TinyDB', 'Storage', 'JSONStorage', 'Query', 'where') diff --git a/SplunkAppForWazuh/bin/tinydb/database.py b/SplunkAppForWazuh/bin/tinydb/database.py deleted file mode 100644 index 53150c2bc..000000000 --- a/SplunkAppForWazuh/bin/tinydb/database.py +++ /dev/null @@ -1,639 +0,0 @@ -""" -Contains the :class:`database ` and -:class:`tables ` implementation. -""" -import warnings - -from . import JSONStorage -from .utils import LRUCache, iteritems, itervalues - - -class Document(dict): - """ - Represents a document stored in the database. - - This is a transparent proxy for database records. It exists - to provide a way to access a record's id via ``el.doc_id``. - """ - - def __init__(self, value, doc_id, **kwargs): - super(Document, self).__init__(**kwargs) - - self.update(value) - self.doc_id = doc_id - - @property - def eid(self): - warnings.warn('eid has been renamed to doc_id', DeprecationWarning) - return self.doc_id - - -Element = Document - - -def _get_doc_id(doc_id, eid): - # Backwards-compatibility shim - if eid is not None: - if doc_id is not None: - raise TypeError('cannot pass both eid and doc_id') - - warnings.warn('eid has been renamed to doc_ids', DeprecationWarning) - return eid - else: - return doc_id - - -def _get_doc_ids(doc_ids, eids): - # Backwards-compatibility shim - if eids is not None: - if doc_ids is not None: - raise TypeError('cannot pass both eids and doc_ids') - - warnings.warn('eids has been renamed to doc_ids', DeprecationWarning) - return eids - else: - return doc_ids - - -class DataProxy(dict): - """ - A proxy to a table's data that remembers the storage's - data dictionary. - """ - - def __init__(self, table, raw_data, **kwargs): - super(DataProxy, self).__init__(**kwargs) - self.update(table) - self.raw_data = raw_data - - -class StorageProxy(object): - """ - A proxy that only allows to read a single table from a - storage. - """ - - def __init__(self, storage, table_name): - self._storage = storage - self._table_name = table_name - - def _new_document(self, key, val): - doc_id = int(key) - return Document(val, doc_id) - - def read(self): - raw_data = self._storage.read() or {} - - try: - table = raw_data[self._table_name] - except KeyError: - raw_data.update({self._table_name: {}}) - self._storage.write(raw_data) - - return DataProxy({}, raw_data) - - docs = {} - for key, val in iteritems(table): - doc = self._new_document(key, val) - docs[doc.doc_id] = doc - - return DataProxy(docs, raw_data) - - def write(self, data): - try: - # Try accessing the full data dict from the data proxy - raw_data = data.raw_data - except AttributeError: - # Not a data proxy, fall back to regular reading - raw_data = self._storage.read() - - raw_data[self._table_name] = dict(data) - self._storage.write(raw_data) - - def purge_table(self): - try: - data = self._storage.read() or {} - del data[self._table_name] - self._storage.write(data) - except KeyError: - pass - - -class TinyDB(object): - """ - The main class of TinyDB. - - Gives access to the database, provides methods to insert/search/remove - and getting tables. - """ - - DEFAULT_TABLE = '_default' - DEFAULT_STORAGE = JSONStorage - - def __init__(self, *args, **kwargs): - """ - Create a new instance of TinyDB. - - All arguments and keyword arguments will be passed to the underlying - storage class (default: :class:`~tinydb.storages.JSONStorage`). - - :param storage: The class of the storage to use. Will be initialized - with ``args`` and ``kwargs``. - :param default_table: The name of the default table to populate. - """ - - storage = kwargs.pop('storage', self.DEFAULT_STORAGE) - default_table = kwargs.pop('default_table', self.DEFAULT_TABLE) - self._cls_table = kwargs.pop('table_class', self.table_class) - self._cls_storage_proxy = kwargs.pop('storage_proxy_class', - self.storage_proxy_class) - - # Prepare the storage - #: :type: Storage - self._storage = storage(*args, **kwargs) - - self._opened = True - - # Prepare the default table - - self._table_cache = {} - self._table = self.table(default_table) - - def table(self, name=DEFAULT_TABLE, **options): - """ - Get access to a specific table. - - Creates a new table, if it hasn't been created before, otherwise it - returns the cached :class:`~tinydb.Table` object. - - :param name: The name of the table. - :type name: str - :param cache_size: How many query results to cache. - :param table_class: Which table class to use. - """ - - if name in self._table_cache: - return self._table_cache[name] - - table_class = options.pop('table_class', self._cls_table) - table = table_class(self._cls_storage_proxy(self._storage, name), name, **options) - - self._table_cache[name] = table - - return table - - def tables(self): - """ - Get the names of all tables in the database. - - :returns: a set of table names - :rtype: set[str] - """ - - return set(self._storage.read()) - - def purge_tables(self): - """ - Purge all tables from the database. **CANNOT BE REVERSED!** - """ - - self._storage.write({}) - self._table_cache.clear() - - def purge_table(self, name): - """ - Purge a specific table from the database. **CANNOT BE REVERSED!** - - :param name: The name of the table. - :type name: str - """ - if name in self._table_cache: - del self._table_cache[name] - - proxy = StorageProxy(self._storage, name) - proxy.purge_table() - - def close(self): - """ - Close the database. - """ - self._opened = False - self._storage.close() - - def __enter__(self): - return self - - def __exit__(self, *args): - if self._opened: - self.close() - - def __getattr__(self, name): - """ - Forward all unknown attribute calls to the underlying standard table. - """ - return getattr(self._table, name) - - # Methods that are executed on the default table - # Because magic methods are not handled by __getattr__ we need to forward - # them manually here - - def __len__(self): - """ - Get the total number of documents in the default table. - - >>> db = TinyDB('db.json') - >>> len(db) - 0 - """ - return len(self._table) - - def __iter__(self): - """ - Iter over all documents from default table. - """ - return self._table.__iter__() - - -class Table(object): - """ - Represents a single TinyDB Table. - """ - - def __init__(self, storage, name, cache_size=10): - """ - Get access to a table. - - :param storage: Access to the storage - :type storage: StorageProxy - :param name: The table name - :param cache_size: Maximum size of query cache. - """ - - self._storage = storage - self._name = name - self._query_cache = LRUCache(capacity=cache_size) - - data = self._read() - self._init_last_id(data) - - def _init_last_id(self, data): - if data: - self._last_id = max(i for i in data) - else: - self._last_id = 0 - - @property - def name(self): - """ - Get the table name. - """ - return self._name - - def process_elements(self, func, cond=None, doc_ids=None, eids=None): - """ - Helper function for processing all documents specified by condition - or IDs. - - A repeating pattern in TinyDB is to run some code on all documents - that match a condition or are specified by their ID. This is - implemented in this function. - The function passed as ``func`` has to be a callable. Its first - argument will be the data currently in the database. Its second - argument is the document ID of the currently processed document. - - See: :meth:`~.update`, :meth:`.remove` - - :param func: the function to execute on every included document. - first argument: all data - second argument: the current eid - :param cond: query that matches documents to use, or - :param doc_ids: list of document IDs to use - :param eids: list of document IDs to use (deprecated) - :returns: the document IDs that were affected during processing - """ - - doc_ids = _get_doc_ids(doc_ids, eids) - data = self._read() - - if doc_ids is not None: - # Processed document specified by id - for doc_id in doc_ids: - func(data, doc_id) - - elif cond is not None: - # Collect affected doc_ids - doc_ids = [] - - # Processed documents specified by condition - for doc_id in list(data): - if cond(data[doc_id]): - func(data, doc_id) - doc_ids.append(doc_id) - else: - # Processed documents - doc_ids = list(data) - - for doc_id in doc_ids: - func(data, doc_id) - - self._write(data) - - return doc_ids - - def clear_cache(self): - """ - Clear the query cache. - - A simple helper that clears the internal query cache. - """ - self._query_cache.clear() - - def _get_next_id(self): - """ - Increment the ID used the last time and return it - """ - - current_id = self._last_id + 1 - self._last_id = current_id - - return current_id - - def _get_doc_id(self, document): - if not isinstance(document, dict): - raise ValueError('Document is not a dictionary') - return self._get_next_id() - - def _read(self): - """ - Reading access to the DB. - - :returns: all values - :rtype: DataProxy - """ - - return self._storage.read() - - def _write(self, values): - """ - Writing access to the DB. - - :param values: the new values to write - :type values: DataProxy | dict - """ - - self._query_cache.clear() - self._storage.write(values) - - def __len__(self): - """ - Get the total number of documents in the table. - """ - return len(self._read()) - - def all(self): - """ - Get all documents stored in the table. - - :returns: a list with all documents. - :rtype: list[Element] - """ - - return list(itervalues(self._read())) - - def __iter__(self): - """ - Iter over all documents stored in the table. - - :returns: an iterator over all documents. - :rtype: listiterator[Element] - """ - - for value in itervalues(self._read()): - yield value - - def insert(self, document): - """ - Insert a new document into the table. - - :param document: the document to insert - :returns: the inserted document's ID - """ - - doc_id = self._get_doc_id(document) - data = self._read() - data[doc_id] = document - self._write(data) - - return doc_id - - def insert_multiple(self, documents): - """ - Insert multiple documents into the table. - - :param documents: a list of documents to insert - :returns: a list containing the inserted documents' IDs - """ - - doc_ids = [] - data = self._read() - - for doc in documents: - doc_id = self._get_doc_id(doc) - doc_ids.append(doc_id) - - data[doc_id] = doc - - self._write(data) - - return doc_ids - - def remove(self, cond=None, doc_ids=None, eids=None): - """ - Remove all matching documents. - - :param cond: the condition to check against - :type cond: query - :param doc_ids: a list of document IDs - :type doc_ids: list - :returns: a list containing the removed document's ID - """ - doc_ids = _get_doc_ids(doc_ids, eids) - - if cond is None and doc_ids is None: - raise RuntimeError('Use purge() to remove all documents') - - return self.process_elements( - lambda data, doc_id: data.pop(doc_id), - cond, doc_ids - ) - - def update(self, fields, cond=None, doc_ids=None, eids=None): - """ - Update all matching documents to have a given set of fields. - - :param fields: the fields that the matching documents will have - or a method that will update the documents - :type fields: dict | dict -> None - :param cond: which documents to update - :type cond: query - :param doc_ids: a list of document IDs - :type doc_ids: list - :returns: a list containing the updated document's ID - """ - doc_ids = _get_doc_ids(doc_ids, eids) - - if callable(fields): - return self.process_elements( - lambda data, doc_id: fields(data[doc_id]), - cond, doc_ids - ) - else: - return self.process_elements( - lambda data, doc_id: data[doc_id].update(fields), - cond, doc_ids - ) - - def write_back(self, documents, doc_ids=None, eids=None): - """ - Write back documents by doc_id - - :param documents: a list of document to write back - :param doc_ids: a list of documents' ID which need to be wrote back - :returns: a list of documents' ID that have been written - """ - doc_ids = _get_doc_ids(doc_ids, eids) - - if doc_ids is not None and not len(documents) == len(doc_ids): - raise ValueError( - 'The length of documents and doc_ids is not match.') - - if doc_ids is None: - doc_ids = [doc.doc_id for doc in documents] - - # Since this function will write docs back like inserting, to ensure - # here only process existing or removed instead of inserting new, - # raise error if doc_id exceeded the last. - if len(doc_ids) > 0 and max(doc_ids) > self._last_id: - raise IndexError( - 'ID exceeds table length, use existing or removed doc_id.') - - data = self._read() - - # Document specified by ID - documents.reverse() - for doc_id in doc_ids: - data[doc_id] = documents.pop() - - self._write(data) - - return doc_ids - - def upsert(self, document, cond): - """ - Update a document, if it exist - insert it otherwise. - - Note: this will update *all* documents matching the query. - - :param document: the document to insert or the fields to update - :param cond: which document to look for - :returns: a list containing the updated document's ID - """ - updated_docs = self.update(document, cond) - - if updated_docs: - return updated_docs - else: - return [self.insert(document)] - - def purge(self): - """ - Purge the table by removing all documents. - """ - - self._write({}) - self._last_id = 0 - - def search(self, cond): - """ - Search for all documents matching a 'where' cond. - - :param cond: the condition to check against - :type cond: Query - - :returns: list of matching documents - :rtype: list[Element] - """ - - if cond in self._query_cache: - return self._query_cache[cond][:] - - docs = [doc for doc in self.all() if cond(doc)] - self._query_cache[cond] = docs - - return docs[:] - - def get(self, cond=None, doc_id=None, eid=None): - """ - Get exactly one document specified by a query or and ID. - - Returns ``None`` if the document doesn't exist - - :param cond: the condition to check against - :type cond: Query - - :param doc_id: the document's ID - - :returns: the document or None - :rtype: Element | None - """ - doc_id = _get_doc_id(doc_id, eid) - - # Cannot use process_elements here because we want to return a - # specific document - - if doc_id is not None: - # Document specified by ID - return self._read().get(doc_id, None) - - # Document specified by condition - for doc in self.all(): - if cond(doc): - return doc - - def count(self, cond): - """ - Count the documents matching a condition. - - :param cond: the condition use - :type cond: Query - """ - - return len(self.search(cond)) - - def contains(self, cond=None, doc_ids=None, eids=None): - """ - Check wether the database contains a document matching a condition or - an ID. - - If ``eids`` is set, it checks if the db contains a document with one - of the specified. - - :param cond: the condition use - :type cond: Query - :param doc_ids: the document IDs to look for - """ - doc_ids = _get_doc_ids(doc_ids, eids) - - if doc_ids is not None: - # Documents specified by ID - return any(self.get(doc_id=doc_id) for doc_id in doc_ids) - - # Document specified by condition - return self.get(cond) is not None - - -# Set the default table class -TinyDB.table_class = Table - -# Set the default storage proxy class -TinyDB.storage_proxy_class = StorageProxy diff --git a/SplunkAppForWazuh/bin/tinydb/middlewares.py b/SplunkAppForWazuh/bin/tinydb/middlewares.py deleted file mode 100644 index 269f41059..000000000 --- a/SplunkAppForWazuh/bin/tinydb/middlewares.py +++ /dev/null @@ -1,116 +0,0 @@ -""" -Contains the :class:`base class ` for -middlewares and implementations. -""" -from . import TinyDB - - -class Middleware(object): - """ - The base class for all Middlewares. - - Middlewares hook into the read/write process of TinyDB allowing you to - extend the behaviour by adding caching, logging, ... - - Your middleware's ``__init__`` method has to accept exactly one - argument which is the class of the "real" storage. It has to be stored as - ``_storage_cls`` (see :class:`~tinydb.middlewares.CachingMiddleware` for an - example). - """ - - def __init__(self, storage_cls=TinyDB.DEFAULT_STORAGE): - self._storage_cls = storage_cls - self.storage = None - - def __call__(self, *args, **kwargs): - """ - Create the storage instance and store it as self.storage. - - Usually a user creates a new TinyDB instance like this:: - - TinyDB(storage=StorageClass) - - The storage kwarg is used by TinyDB this way:: - - self.storage = storage(*args, **kwargs) - - As we can see, ``storage(...)`` runs the constructor and returns the - new storage instance. - - - Using Middlewares, the user will call:: - - The 'real' storage class - v - TinyDB(storage=Middleware(StorageClass)) - ^ - Already an instance! - - So, when running ``self.storage = storage(*args, **kwargs)`` Python - now will call ``__call__`` and TinyDB will expect the return value to - be the storage (or Middleware) instance. Returning the instance is - simple, but we also got the underlying (*real*) StorageClass as an - __init__ argument that still is not an instance. - So, we initialize it in __call__ forwarding any arguments we recieve - from TinyDB (``TinyDB(arg1, kwarg1=value, storage=...)``). - - In case of nested Middlewares, calling the instance as if it was an - class results in calling ``__call__`` what initializes the next - nested Middleware that itself will initialize the next Middleware and - so on. - """ - - self.storage = self._storage_cls(*args, **kwargs) - - return self - - def __getattr__(self, name): - """ - Forward all unknown attribute calls to the underlying storage so we - remain as transparent as possible. - """ - - return getattr(self.__dict__['storage'], name) - - -class CachingMiddleware(Middleware): - """ - Add some caching to TinyDB. - - This Middleware aims to improve the performance of TinyDB by writing only - the last DB state every :attr:`WRITE_CACHE_SIZE` time and reading always - from cache. - """ - - #: The number of write operations to cache before writing to disc - WRITE_CACHE_SIZE = 1000 - - def __init__(self, storage_cls=TinyDB.DEFAULT_STORAGE): - super(CachingMiddleware, self).__init__(storage_cls) - - self.cache = None - self._cache_modified_count = 0 - - def read(self): - if self.cache is None: - self.cache = self.storage.read() - return self.cache - - def write(self, data): - self.cache = data - self._cache_modified_count += 1 - - if self._cache_modified_count >= self.WRITE_CACHE_SIZE: - self.flush() - - def flush(self): - """ - Flush all unwritten data to disk. - """ - if self._cache_modified_count > 0: - self.storage.write(self.cache) - self._cache_modified_count = 0 - - def close(self): - self.flush() # Flush potentially unwritten data - self.storage.close() diff --git a/SplunkAppForWazuh/bin/tinydb/operations.py b/SplunkAppForWazuh/bin/tinydb/operations.py deleted file mode 100644 index 77c15553f..000000000 --- a/SplunkAppForWazuh/bin/tinydb/operations.py +++ /dev/null @@ -1,58 +0,0 @@ -def delete(field): - """ - Delete a given field from the document. - """ - def transform(doc): - del doc[field] - - return transform - - -def add(field, n): - """ - Add n to a given field in the document. - """ - def transform(doc): - doc[field] += n - - return transform - - -def subtract(field, n): - """ - Subtract n from a given field in the document. - """ - def transform(doc): - doc[field] -= n - - return transform - - -def set(field, val): - """ - Set a given field to val. - """ - def transform(doc): - doc[field] = val - - return transform - - -def increment(field): - """ - Increment a given field in the document. - """ - def transform(doc): - doc[field] += 1 - - return transform - - -def decrement(field): - """ - Decrement a given field in the document. - """ - def transform(doc): - doc[field] -= 1 - - return transform diff --git a/SplunkAppForWazuh/bin/tinydb/queries.py b/SplunkAppForWazuh/bin/tinydb/queries.py deleted file mode 100644 index b0eca166e..000000000 --- a/SplunkAppForWazuh/bin/tinydb/queries.py +++ /dev/null @@ -1,376 +0,0 @@ -""" -Contains the querying interface. - -Starting with :class:`~tinydb.queries.Query` you can construct complex -queries: - ->>> ((where('f1') == 5) & (where('f2') != 2)) | where('s').matches(r'^\w+$') -(('f1' == 5) and ('f2' != 2)) or ('s' ~= ^\w+$ ) - -Queries are executed by using the ``__call__``: - ->>> q = where('val') == 5 ->>> q({'val': 5}) -True ->>> q({'val': 1}) -False -""" - -import re -import sys - -from .utils import catch_warning, freeze - -__all__ = ('Query', 'where') - - -def is_sequence(obj): - return hasattr(obj, '__iter__') - - -class QueryImpl(object): - """ - A query implementation. - - This query implementation wraps a test function which is run when the - query is evaluated by calling the object. - - Queries can be combined with logical and/or and modified with logical not. - """ - - def __init__(self, test, hashval): - self.test = test - self.hashval = hashval - - def __call__(self, value): - return self.test(value) - - def __hash__(self): - return hash(self.hashval) - - def __repr__(self): - return 'QueryImpl{}'.format(self.hashval) - - def __eq__(self, other): - return self.hashval == other.hashval - - # --- Query modifiers ----------------------------------------------------- - - def __and__(self, other): - # We use a frozenset for the hash as the AND operation is commutative - # (a & b == b & a) - return QueryImpl(lambda value: self(value) and other(value), - ('and', frozenset([self.hashval, other.hashval]))) - - def __or__(self, other): - # We use a frozenset for the hash as the OR operation is commutative - # (a | b == b | a) - return QueryImpl(lambda value: self(value) or other(value), - ('or', frozenset([self.hashval, other.hashval]))) - - def __invert__(self): - return QueryImpl(lambda value: not self(value), - ('not', self.hashval)) - - -class Query(object): - """ - TinyDB Queries. - - Allows to build queries for TinyDB databases. There are two main ways of - using queries: - - 1) ORM-like usage: - - >>> User = Query() - >>> db.search(User.name == 'John Doe') - >>> db.search(User['logged-in'] == True) - - 2) Classical usage: - - >>> db.search(where('value') == True) - - Note that ``where(...)`` is a shorthand for ``Query(...)`` allowing for - a more fluent syntax. - - Besides the methods documented here you can combine queries using the - binary AND and OR operators: - - >>> db.search(where('field1').exists() & where('field2') == 5) # Binary AND - >>> db.search(where('field1').exists() | where('field2') == 5) # Binary OR - - Queries are executed by calling the resulting object. They expect to get - the document to test as the first argument and return ``True`` or - ``False`` depending on whether the documents matches the query or not. - """ - - def __init__(self): - self._path = [] - - def __getattr__(self, item): - query = Query() - query._path = self._path + [item] - - return query - - __getitem__ = __getattr__ - - def _generate_test(self, test, hashval): - """ - Generate a query based on a test function. - - :param test: The test the query executes. - :param hashval: The hash of the query. - :return: A :class:`~tinydb.queries.QueryImpl` object - """ - if not self._path: - raise ValueError('Query has no path') - - def impl(value): - try: - # Resolve the path - for part in self._path: - value = value[part] - except (KeyError, TypeError): - return False - else: - return test(value) - - return QueryImpl(impl, hashval) - - def __eq__(self, rhs): - """ - Test a dict value for equality. - - >>> Query().f1 == 42 - - :param rhs: The value to compare against - """ - if sys.version_info <= (3, 0): # pragma: no cover - # Special UTF-8 handling on Python 2 - def test(value): - with catch_warning(UnicodeWarning): - try: - return value == rhs - except UnicodeWarning: - # Dealing with a case, where 'value' or 'rhs' - # is unicode and the other is a byte string. - if isinstance(value, str): - return value.decode('utf-8') == rhs - elif isinstance(rhs, str): - return value == rhs.decode('utf-8') - - else: # pragma: no cover - def test(value): - return value == rhs - - return self._generate_test( - lambda value: test(value), - ('==', tuple(self._path), freeze(rhs)) - ) - - def __ne__(self, rhs): - """ - Test a dict value for inequality. - - >>> Query().f1 != 42 - - :param rhs: The value to compare against - """ - return self._generate_test( - lambda value: value != rhs, - ('!=', tuple(self._path), freeze(rhs)) - ) - - def __lt__(self, rhs): - """ - Test a dict value for being lower than another value. - - >>> Query().f1 < 42 - - :param rhs: The value to compare against - """ - return self._generate_test( - lambda value: value < rhs, - ('<', tuple(self._path), rhs) - ) - - def __le__(self, rhs): - """ - Test a dict value for being lower than or equal to another value. - - >>> where('f1') <= 42 - - :param rhs: The value to compare against - """ - return self._generate_test( - lambda value: value <= rhs, - ('<=', tuple(self._path), rhs) - ) - - def __gt__(self, rhs): - """ - Test a dict value for being greater than another value. - - >>> Query().f1 > 42 - - :param rhs: The value to compare against - """ - return self._generate_test( - lambda value: value > rhs, - ('>', tuple(self._path), rhs) - ) - - def __ge__(self, rhs): - """ - Test a dict value for being greater than or equal to another value. - - >>> Query().f1 >= 42 - - :param rhs: The value to compare against - """ - return self._generate_test( - lambda value: value >= rhs, - ('>=', tuple(self._path), rhs) - ) - - def exists(self): - """ - Test for a dict where a provided key exists. - - >>> Query().f1.exists() - """ - return self._generate_test( - lambda _: True, - ('exists', tuple(self._path)) - ) - - def matches(self, regex, flags=0): - """ - Run a regex test against a dict value (whole string has to match). - - >>> Query().f1.matches(r'^\w+$') - - :param regex: The regular expression to use for matching - """ - return self._generate_test( - lambda value: re.match(regex, value, flags), - ('matches', tuple(self._path), regex) - ) - - def search(self, regex, flags=0): - """ - Run a regex test against a dict value (only substring string has to - match). - - >>> Query().f1.search(r'^\w+$') - - :param regex: The regular expression to use for matching - """ - return self._generate_test( - lambda value: re.search(regex, value, flags), - ('search', tuple(self._path), regex) - ) - - def test(self, func, *args): - """ - Run a user-defined test function against a dict value. - - >>> def test_func(val): - ... return val == 42 - ... - >>> Query().f1.test(test_func) - - :param func: The function to call, passing the dict as the first - argument - :param args: Additional arguments to pass to the test function - """ - return self._generate_test( - lambda value: func(value, *args), - ('test', tuple(self._path), func, args) - ) - - def any(self, cond): - """ - Check if a condition is met by any document in a list, - where a condition can also be a sequence (e.g. list). - - >>> Query().f1.any(Query().f2 == 1) - - Matches:: - - {'f1': [{'f2': 1}, {'f2': 0}]} - - >>> Query().f1.any([1, 2, 3]) - - Matches:: - - {'f1': [1, 2]} - {'f1': [3, 4, 5]} - - :param cond: Either a query that at least one document has to match or - a list of which at least one document has to be contained - in the tested document. - """ - if callable(cond): - def _cmp(value): - return is_sequence(value) and any(cond(e) for e in value) - - else: - def _cmp(value): - return is_sequence(value) and any(e in cond for e in value) - - return self._generate_test( - lambda value: _cmp(value), - ('any', tuple(self._path), freeze(cond)) - ) - - def all(self, cond): - """ - Check if a condition is met by all documents in a list, - where a condition can also be a sequence (e.g. list). - - >>> Query().f1.all(Query().f2 == 1) - - Matches:: - - {'f1': [{'f2': 1}, {'f2': 1}]} - - >>> Query().f1.all([1, 2, 3]) - - Matches:: - - {'f1': [1, 2, 3, 4, 5]} - - :param cond: Either a query that all documents have to match or a list - which has to be contained in the tested document. - """ - if callable(cond): - def _cmp(value): - return is_sequence(value) and all(cond(e) for e in value) - - else: - def _cmp(value): - return is_sequence(value) and all(e in value for e in cond) - - return self._generate_test( - lambda value: _cmp(value), - ('all', tuple(self._path), freeze(cond)) - ) - - def one_of(self, items): - """ - Check if the value is contained in a list or generator. - - >>> Query().f1.one_of(['value 1', 'value 2']) - - :param items: The list of items to check with - """ - return self._generate_test( - lambda value: value in items, - ('one_of', tuple(self._path), freeze(items)) - ) - - -def where(key): - return Query()[key] diff --git a/SplunkAppForWazuh/bin/tinydb/storages.py b/SplunkAppForWazuh/bin/tinydb/storages.py deleted file mode 100644 index 717fcf1f7..000000000 --- a/SplunkAppForWazuh/bin/tinydb/storages.py +++ /dev/null @@ -1,136 +0,0 @@ -""" -Contains the :class:`base class ` for storages and -implementations. -""" -import codecs -from abc import ABCMeta, abstractmethod -import os - -from .utils import with_metaclass - - -try: - import ujson as json -except ImportError: - import json - - -def touch(fname, create_dirs): - if create_dirs: - base_dir = os.path.dirname(fname) - if not os.path.exists(base_dir): - os.makedirs(base_dir) - - with open(fname, 'a'): - os.utime(fname, None) - - -class Storage(with_metaclass(ABCMeta, object)): - """ - The abstract base class for all Storages. - - A Storage (de)serializes the current state of the database and stores it in - some place (memory, file on disk, ...). - """ - - # Using ABCMeta as metaclass allows instantiating only storages that have - # implemented read and write - - @abstractmethod - def read(self): - """ - Read the last stored state. - - Any kind of deserialization should go here. - Return ``None`` here to indicate that the storage is empty. - - :rtype: dict - """ - - raise NotImplementedError('To be overridden!') - - @abstractmethod - def write(self, data): - """ - Write the current state of the database to the storage. - - Any kind of serialization should go here. - - :param data: The current state of the database. - :type data: dict - """ - - raise NotImplementedError('To be overridden!') - - def close(self): - """ - Optional: Close open file handles, etc. - """ - - pass - - -class JSONStorage(Storage): - """ - Store the data in a JSON file. - """ - - def __init__(self, path, create_dirs=False, encoding='utf8', **kwargs): - """ - Create a new instance. - - Also creates the storage file, if it doesn't exist. - - :param path: Where to store the JSON data. - :type path: str - :param encoding: The encoding for the JSON file. Default: utf8 - :type encoding: str - """ - - super(JSONStorage, self).__init__() - touch(path, create_dirs=create_dirs) # Create file if not exists - self.kwargs = kwargs - self._handle = codecs.open(path, 'r+', encoding=encoding) - - def close(self): - self._handle.close() - - def read(self): - # Get the file size - self._handle.seek(0, os.SEEK_END) - size = self._handle.tell() - - if not size: - # File is empty - return None - else: - self._handle.seek(0) - return json.load(self._handle) - - def write(self, data): - self._handle.seek(0) - serialized = json.dumps(data, **self.kwargs) - self._handle.write(serialized) - self._handle.flush() - os.fsync(self._handle.fileno()) - self._handle.truncate() - - -class MemoryStorage(Storage): - """ - Store the data as JSON in memory. - """ - - def __init__(self): - """ - Create a new instance. - """ - - super(MemoryStorage, self).__init__() - self.memory = None - - def read(self): - return self.memory - - def write(self, data): - self.memory = data diff --git a/SplunkAppForWazuh/bin/tinydb/utils.py b/SplunkAppForWazuh/bin/tinydb/utils.py deleted file mode 100644 index 92388a8a9..000000000 --- a/SplunkAppForWazuh/bin/tinydb/utils.py +++ /dev/null @@ -1,143 +0,0 @@ -""" -Utility functions. -""" - -from contextlib import contextmanager -import warnings - -# Python 2/3 independant dict iteration -iteritems = getattr(dict, 'iteritems', dict.items) -itervalues = getattr(dict, 'itervalues', dict.values) - - -class LRUCache(dict): - """ - A simple LRU cache. - """ - - def __init__(self, *args, **kwargs): - """ - :param capacity: How many items to store before cleaning up old items - or ``None`` for an unlimited cache size - """ - - self.capacity = kwargs.pop('capacity', None) - if self.capacity is None: - self.capacity = float('nan') - - self.lru = [] - - super(LRUCache, self).__init__(*args, **kwargs) - - def refresh(self, key): - """ - Push a key to the tail of the LRU queue - """ - if key in self.lru: - self.lru.remove(key) - self.lru.append(key) - - def get(self, key, default=None): - item = super(LRUCache, self).get(key, default) - self.refresh(key) - - return item - - def __getitem__(self, key): - item = super(LRUCache, self).__getitem__(key) - self.refresh(key) - - return item - - def __setitem__(self, key, value): - super(LRUCache, self).__setitem__(key, value) - - self.refresh(key) - - # Check, if the cache is full and we have to remove old items - # If the queue is of unlimited size, self.capacity is NaN and - # x > NaN is always False in Python and the cache won't be cleared. - if len(self) > self.capacity: - self.pop(self.lru.pop(0)) - - def __delitem__(self, key): - super(LRUCache, self).__delitem__(key) - self.lru.remove(key) - - def clear(self): - super(LRUCache, self).clear() - del self.lru[:] - - -# Source: https://github.com/PythonCharmers/python-future/blob/466bfb2dfa36d865285dc31fe2b0c0a53ff0f181/future/utils/__init__.py#L102-L134 -def with_metaclass(meta, *bases): - """ - Function from jinja2/_compat.py. License: BSD. - - Use it like this:: - - class BaseForm(object): - pass - - class FormType(type): - pass - - class Form(with_metaclass(FormType, BaseForm)): - pass - - This requires a bit of explanation: the basic idea is to make a - dummy metaclass for one level of class instantiation that replaces - itself with the actual metaclass. Because of internal type checks - we also need to make sure that we downgrade the custom metaclass - for one level to something closer to type (that's why __call__ and - __init__ comes back from type etc.). - - This has the advantage over six.with_metaclass of not introducing - dummy classes into the final MRO. - """ - - class Metaclass(meta): - __call__ = type.__call__ - __init__ = type.__init__ - - def __new__(cls, name, this_bases, d): - if this_bases is None: - return type.__new__(cls, name, (), d) - return meta(name, bases, d) - - return Metaclass('temporary_class', None, {}) - - -@contextmanager -def catch_warning(warning_cls): - with warnings.catch_warnings(): - warnings.filterwarnings('error', category=warning_cls) - - yield - - -class FrozenDict(dict): - def __hash__(self): - return hash(tuple(sorted(self.items()))) - - def _immutable(self, *args, **kws): - raise TypeError('object is immutable') - - __setitem__ = _immutable - __delitem__ = _immutable - clear = _immutable - update = _immutable - setdefault = _immutable - pop = _immutable - popitem = _immutable - - -def freeze(obj): - if isinstance(obj, dict): - return FrozenDict((k, freeze(v)) for k, v in obj.items()) - elif isinstance(obj, list): - return tuple(freeze(el) for el in obj) - elif isinstance(obj, set): - return frozenset(obj) - else: - return obj diff --git a/SplunkAppForWazuh/bin/tinydb/version.py b/SplunkAppForWazuh/bin/tinydb/version.py deleted file mode 100644 index b8b2efb82..000000000 --- a/SplunkAppForWazuh/bin/tinydb/version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = '3.11.0' diff --git a/SplunkAppForWazuh/default/app.conf b/SplunkAppForWazuh/default/app.conf index a6782cf9a..87fd136cd 100644 --- a/SplunkAppForWazuh/default/app.conf +++ b/SplunkAppForWazuh/default/app.conf @@ -3,7 +3,7 @@ is_visible = 1 label = Wazuh [launcher] -version = 3.8.2 +version = 3.9.0 author = info@wazuh.com description = Wazuh helps you to gain deeper security visibility into your infrastructure by monitoring hosts at an operating system and application level. diff --git a/SplunkAppForWazuh/default/collections.conf b/SplunkAppForWazuh/default/collections.conf new file mode 100644 index 000000000..17e005953 --- /dev/null +++ b/SplunkAppForWazuh/default/collections.conf @@ -0,0 +1,25 @@ +# +# Splunk app KV Store collection file +# + +[credentials] +accelerated_fields.id_acceleration = {"id": 1} +replicate = true +local = false +enforceTypes = true +field.portapi = number +field.url = string +field.userapi = string +field.passapi = string +field.managerName = string +field.filterName = string + +[jobs] +accelerated_fields.id_acceleration = {"id": 1} +replicate = false +local = true +enforceTypes = true +field.job = string +field.added = number +field.exec_time = number +field.done = bool \ No newline at end of file diff --git a/SplunkAppForWazuh/default/config.conf b/SplunkAppForWazuh/default/config.conf index 0e859449b..a00f8e1bb 100644 --- a/SplunkAppForWazuh/default/config.conf +++ b/SplunkAppForWazuh/default/config.conf @@ -7,4 +7,8 @@ audit = true osquery = false ciscat = false gdpr = true -admin = true \ No newline at end of file +admin = true +docker = false + +[admin_extensions] +reporting = true \ No newline at end of file diff --git a/SplunkAppForWazuh/default/data/ui/html/index.html b/SplunkAppForWazuh/default/data/ui/html/index.html index 918f09e7f..84753428e 100644 --- a/SplunkAppForWazuh/default/data/ui/html/index.html +++ b/SplunkAppForWazuh/default/data/ui/html/index.html @@ -22,19 +22,15 @@ - +
    -
    -
    -
    + +
    +
    +
    - - -
    diff --git a/SplunkAppForWazuh/default/indexes.conf b/SplunkAppForWazuh/default/indexes.conf deleted file mode 100644 index fd04bd2fe..000000000 --- a/SplunkAppForWazuh/default/indexes.conf +++ /dev/null @@ -1,19 +0,0 @@ -[wazuh] -coldPath = $SPLUNK_DB/wazuh/colddb -enableDataIntegrityControl = 1 -enableTsidxReduction = 1 -homePath = $SPLUNK_DB/wazuh/db -maxTotalDataSizeMB = 512000 -thawedPath = $SPLUNK_DB/wazuh/thaweddb -timePeriodInSecBeforeTsidxReduction = 15552000 -tsidxReductionCheckPeriodInSec = - -[wazuh-monitoring-3x] -coldPath = $SPLUNK_DB/wazuh-monitoring-3x/colddb -enableDataIntegrityControl = 1 -enableTsidxReduction = 1 -homePath = $SPLUNK_DB/wazuh-monitoring-3x/db -maxTotalDataSizeMB = 512000 -thawedPath = $SPLUNK_DB/wazuh-monitoring-3x/thaweddb -timePeriodInSecBeforeTsidxReduction = 15552000 -tsidxReductionCheckPeriodInSec = \ No newline at end of file diff --git a/SplunkAppForWazuh/default/inputs.conf b/SplunkAppForWazuh/default/inputs.conf index 26e4a5d2b..9e808af3a 100644 --- a/SplunkAppForWazuh/default/inputs.conf +++ b/SplunkAppForWazuh/default/inputs.conf @@ -1,8 +1,14 @@ -[splunktcp://9997] -connection_host = ip - -[script:///opt/splunk/etc/apps/SplunkAppForWazuh/bin/get_agents_status.py] -disabled = false -index = wazuh-monitoring-3x -interval = 0 * * * * -sourcetype = _json \ No newline at end of file +[splunktcp://9997] +connection_host = ip + +[script://$SPLUNK_HOME/etc/apps/SplunkAppForWazuh/bin/get_agents_status.py] +disabled = false +index = wazuh-monitoring-3x +interval = */15 * * * * +sourcetype = _json +passAuth = splunk-system-user + +[script://$SPLUNK_HOME/etc/apps/SplunkAppForWazuh/bin/check_queue.py] +disabled = false +interval = 15.0 +passAuth = splunk-system-user \ No newline at end of file diff --git a/SplunkAppForWazuh/default/package.conf b/SplunkAppForWazuh/default/package.conf index 35ed8e15b..6160b0153 100644 --- a/SplunkAppForWazuh/default/package.conf +++ b/SplunkAppForWazuh/default/package.conf @@ -1,9 +1,9 @@ [app] -version = 3.8.2 -revision = 22 +version = 3.9.0 +revision = 25 [wazuh] -version = 3.8.2 +version = 3.9.0 [splunk] -version = 7.2.5 \ No newline at end of file +version = 7.2.6 \ No newline at end of file diff --git a/SplunkAppForWazuh/default/props.conf b/SplunkAppForWazuh/default/props.conf index 9311b009e..bce9b0844 100644 --- a/SplunkAppForWazuh/default/props.conf +++ b/SplunkAppForWazuh/default/props.conf @@ -1,23 +1,4 @@ [wazuh] -DATETIME_CONFIG = -INDEXED_EXTRACTIONS = json +INDEXED_EXTRACTIONS = JSON KV_MODE = none -NO_BINARY_CHECK = true -category = Application -disabled = false -pulldown_type = true -FIELDALIAS-rule.groups = "rule.groups{}" AS "rule.groups" -FIELDALIAS-dstuser = "data.dstuser" AS srcuser -FIELDALIAS-srcip = "data.srcip" AS srcip -FIELDALIAS-data.title = "data.title" AS title -FIELDALIAS-oscap.scan.id = "data.oscap.scan.id" AS "oscap.scan.id" -FIELDALIAS-oscap.scan.content = "data.oscap.scan.content" AS "oscap.scan.content" -FIELDALIAS-oscap.scan.profile.title = "data.oscap.scan.profile.title" AS "oscap.scan.profile.title" -FIELDALIAS-oscap.scan.score = "data.oscap.scan.score" AS "oscap.scan.score" -FIELDALIAS-oscap.check.title = "data.oscap.check.title" AS "oscap.check.title" -FIELDALIAS-oscap.check.result = "data.oscap.check.result" AS "oscap.check.result" -FIELDALIAS-oscap.check.severity = "data.oscap.check.severity" AS "oscap.check.severity" -FIELDALIAS-audit.exe = "data.audit.exe" AS "audit.exe" -FIELDALIAS-audit.file.mode = "data.audit.file.mode" AS "audit.file.mode" -FIELDALIAS-audit.egid = "data.audit.egid" AS "audit.egid" -FIELDALIAS-audit.euid = "data.audit.euid" AS "audit.euid" \ No newline at end of file +AUTO_KV_JSON = false \ No newline at end of file diff --git a/SplunkAppForWazuh/default/transforms.conf b/SplunkAppForWazuh/default/transforms.conf index 879fbec00..69a7cc397 100644 --- a/SplunkAppForWazuh/default/transforms.conf +++ b/SplunkAppForWazuh/default/transforms.conf @@ -1,15 +1,13 @@ -[pci1.csv] -batch_index_query = 0 -case_sensitive_match = 1 -filename = pci1.csv - -[gdpr.csv] -batch_index_query = 0 -case_sensitive_match = 1 -filename = gdpr.csv - +# +# Splunk app KV Store transforms file +# [kvstore_lookup] external_type = kvstore collection = credentials -fields_list = _key, url, portapi, userapi, passapi, managerName, cluster \ No newline at end of file +fields_list = _key, id, url, port, user, password, filter + +[kvstore_lookup] +external_type = kvstore +collection = jobs +fields_list = _key, job, added, exec_time \ No newline at end of file diff --git a/SplunkAppForWazuh/default/web.conf b/SplunkAppForWazuh/default/web.conf index 70db0ef98..dfd07879a 100644 --- a/SplunkAppForWazuh/default/web.conf +++ b/SplunkAppForWazuh/default/web.conf @@ -1,5 +1,3 @@ -simple_error_page = True - # manager endpoints [endpoint:manager] @@ -7,4 +5,7 @@ simple_error_page = True [endpoint:api] # report endpoints -[endpoint:report] \ No newline at end of file +[endpoint:report] + +# queue endpoint +[endpoint:queue] \ No newline at end of file diff --git a/SplunkAppForWazuh/metadata/local.meta b/SplunkAppForWazuh/metadata/local.meta deleted file mode 100644 index 1ecc62acb..000000000 --- a/SplunkAppForWazuh/metadata/local.meta +++ /dev/null @@ -1,23 +0,0 @@ -[app/ui] -version = 7.0.2 -modtime = 1520955322.735444000 - -[app/launcher] -version = 7.0.2 -modtime = 1520955322.736758000 - -[views/index] -owner = admin -version = 7.0.2 -modtime = 1520955616.195560000 - -[views/second] -export = none -owner = admin -version = 7.0.2 -modtime = 1520955809.185500000 - -[html/index_html] -owner = admin -version = 7.0.2 -modtime = 1520957082.712081000 diff --git a/SplunkAppForWazuh/static/appIconAlt.png b/SplunkAppForWazuh/static/appIconAlt.png index 0e78cab85..305cdf548 100644 Binary files a/SplunkAppForWazuh/static/appIconAlt.png and b/SplunkAppForWazuh/static/appIconAlt.png differ diff --git a/SplunkAppForWazuh/static/appLogo.png b/SplunkAppForWazuh/static/appLogo.png index ad2d9bc23..a5b4af2fd 100644 Binary files a/SplunkAppForWazuh/static/appLogo.png and b/SplunkAppForWazuh/static/appLogo.png differ diff --git a/package.json b/package.json index 260607594..389538b19 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { "name": "wazuh-splunk", - "version": "3.8.2", - "revision": "22", - "code": "22-0", + "version": "3.9.0", + "revision": "25", + "code": "25-0", "description": "Splunk app for Wazuh", "main": "index.js", "keywords": [ @@ -12,13 +12,13 @@ ], "dependencies": {}, "devDependencies": { - "babel-eslint": "^9.0.0", "chai": "^4.2.0", "chai-match": "^1.1.1", "eslint": "^5.6.1", - "eslint-plugin-async-await": "^0.0.0", - "eslint-plugin-node": "^7.0.1", + "eslint-plugin-async-await": "0.0.0", + "eslint-plugin-node": "^8.0.1", "eslint-plugin-requirejs": "^3.2.0", + "esprima": "^4.0.1", "mocha": "^5.2.0", "needle": "^2.2.4", "prettier": "^1.14.3" diff --git a/tests/manager.js b/tests/manager.js index 492a39b0c..d52102957 100644 --- a/tests/manager.js +++ b/tests/manager.js @@ -1,8 +1,8 @@ -const chai = require('chai') -const needle = require('needle') +const chai = require('chai')// eslint-disable-line +const needle = require('needle')// eslint-disable-line chai.should() -chai.use(require('chai-match')); +chai.use(require('chai-match'))// eslint-disable-line const s_url = 'http://localhost:8000/en-US/custom/SplunkAppForWazuh/manager' @@ -55,8 +55,8 @@ describe('manager-api', () => { resBodyJson.forEach(api => { api.passapi.should.be.a('string') api.portapi.should.be.a('string') - api.id.should.be.a('string') - chai.expect(api.id).to.match(/^\w+\-\w+\-\w+\-\w+\-\w+$/) // eslint-disable-line + api['_key'].should.be.a('string') + chai.expect(api['_key']).to.match(/^\w+\-\w+\-\w+\-\w+\-\w+$/) // eslint-disable-line api.url.should.be.a('string') api.userapi.should.be.a('string') }) diff --git a/tests/ofuscate.js b/tests/ofuscate.js index 22db0fdab..09e7c479a 100644 --- a/tests/ofuscate.js +++ b/tests/ofuscate.js @@ -1,5 +1,5 @@ -const chai = require('chai') -const needle = require('needle') +const chai = require('chai')// eslint-disable-line +const needle = require('needle')// eslint-disable-line chai.should() const url = process.env.ofuscateurl || '' const s_url = `${url}/custom/SplunkAppForWazuh/api/ofuscate_test`