From a790c2bdc05372d43e53527916497dd20d8d2872 Mon Sep 17 00:00:00 2001 From: andryyy Date: Fri, 5 May 2017 10:34:31 +0200 Subject: [PATCH 01/49] Add phpredis --- data/Dockerfiles/php-fpm/Dockerfile | 3 +++ 1 file changed, 3 insertions(+) diff --git a/data/Dockerfiles/php-fpm/Dockerfile b/data/Dockerfiles/php-fpm/Dockerfile index ad4b105d..9a059a45 100644 --- a/data/Dockerfiles/php-fpm/Dockerfile +++ b/data/Dockerfiles/php-fpm/Dockerfile @@ -9,6 +9,9 @@ RUN apt-get update \ RUN docker-php-ext-configure intl RUN docker-php-ext-install intl pdo pdo_mysql xmlrpc RUN pear install channel://pear.php.net/Net_IDNA2-0.1.1 Auth_SASL Net_IMAP NET_SMTP Net_IDNA2 Mail_mime +RUN pecl install -o -f redis \ + && rm -rf /tmp/pear \ + && docker-php-ext-enable redis COPY ./docker-entrypoint.sh / From 1501df6e42968f7331a2246949efa846e2cf7bb4 Mon Sep 17 00:00:00 2001 From: andryyy Date: Fri, 5 May 2017 10:35:27 +0200 Subject: [PATCH 02/49] Use Redis for DKIM keys, define any selector, auto-merge old keys to Redis and fallback to files --- data/conf/rspamd/local.d/dkim_signing.conf | 6 +- data/web/admin.php | 15 ++++- data/web/inc/functions.inc.php | 68 +++++++++++++++++++--- data/web/inc/prerequisites.inc.php | 4 ++ 4 files changed, 81 insertions(+), 12 deletions(-) diff --git a/data/conf/rspamd/local.d/dkim_signing.conf b/data/conf/rspamd/local.d/dkim_signing.conf index 23eeadb6..9859678e 100644 --- a/data/conf/rspamd/local.d/dkim_signing.conf +++ b/data/conf/rspamd/local.d/dkim_signing.conf @@ -23,6 +23,8 @@ use_domain = "envelope"; # Whether to normalise domains to eSLD use_esld = false; # Whether to get keys from Redis -use_redis = false; +use_redis = true; # Hash for DKIM keys in Redis -hash_key = "DKIM_KEYS"; +key_prefix = "DKIM_PRIV_KEYS"; +# Selector map +selector_map = "redis://DKIM_SELECTORS"; diff --git a/data/web/admin.php b/data/web/admin.php index 6da0f396..6235b682 100644 --- a/data/web/admin.php +++ b/data/web/admin.php @@ -190,7 +190,6 @@ $tfa_data = get_tfa();
-

Domain:
+ Selector '' bit

@@ -233,6 +233,7 @@ $tfa_data = get_tfa();

↳ Alias-Domain:
+ Selector '' bit

@@ -267,8 +268,12 @@ $tfa_data = get_tfa(); ?>
-

Domain:

-
+

Domain:
+ + Selector '' + bit +

+
@@ -290,6 +295,10 @@ $tfa_data = get_tfa();
+
+ + +
+ + + + +
public static $cookieExpiryTime
expiry time for cookie @var int
private static $isSameOrigin
flag for cross origin/same origin request @var bool
private static $isValidHTML
flag to check if output file is a valid HTML or not @var bool
protected static $requestType
Varaible to store weather request type is post or get @var string
public static $config
config file for CSRFProtector @var int Array, length = 6 Property: #1: failedAuthAction (int) => action to be taken in case autherisation fails Property: #2: logDirectory (string) => directory in which log will be saved Property: #3: customErrorMessage (string) => custom error message to be sent in case of failed authentication Property: #4: jsFile (string) => location of the CSRFProtector js file Property: #5: tokenLength (int) => default length of hash Property: #6: disabledJavascriptMessage (string) => error message if client’s js is disabled
public static function init($length =  null,
$action =  null)
function to initialise the csrfProtector work flow
public static function useCachedVersion()
function to check weather to use cached version of js file or not
public static function createNewJsCache()
Function to create new cache version of js
public static function authorisePost()
function to authorise incoming post requests
private static function failedValidationAction()
function to be called in case of failed validation performs logging and take appropriate action
public static function refreshToken()
Function to set auth cookie
public static function generateAuthToken()
function to generate random hash of length as given in parameter max length = 128
public static function ob_handler($buffer,
$flags)
Rewrites form on the fly to add CSRF tokens to them.
private static function logCSRFattack()
Functio to log CSRF Attack
private static function getCurrentUrl()
Function to return current url of executing page
public static function isURLallowed()
Function to check if a url mataches for any urls Listed in config file
+ + + + + + + + \ No newline at end of file diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index.html new file mode 100644 index 00000000..c42fb024 --- /dev/null +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index/Files.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index/Files.html new file mode 100644 index 00000000..a984415a --- /dev/null +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index/Files.html @@ -0,0 +1,33 @@ + + +File Index + + + + + + + + + +
File Index
$#! · 0-9 · A · B · C · D · E · F · G · H · I · J · K · L · M · N · O · P · Q · R · S · T · U · V · W · X · Y · Z
C
 csrfprotector.php
+ + + +
+ + + + + + + + + + + + \ No newline at end of file diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index/Functions.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index/Functions.html new file mode 100644 index 00000000..7a5a0f31 --- /dev/null +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index/Functions.html @@ -0,0 +1,65 @@ + + +Function Index + + + + + + + + + +
Function Index
$#! · 0-9 · A · B · C · D · E · F · G · H · I · J · K · L · M · N · O · P · Q · R · S · T · U · V · W · X · Y · Z
A
 authorisePost
C
 createNewJsCache
F
 failedValidationAction
G
 generateAuthToken
 getCurrentUrl
I
 init
 isURLallowed
L
 logCSRFattack
O
 ob_handler
R
 refreshToken
U
 useCachedVersion
+ +
public static function authorisePost()
function to authorise incoming post requests
+ + + +
public static function createNewJsCache()
Function to create new cache version of js
+ + + +
private static function failedValidationAction()
function to be called in case of failed validation performs logging and take appropriate action
+ + + +
public static function generateAuthToken()
function to generate random hash of length as given in parameter max length = 128
private static function getCurrentUrl()
Function to return current url of executing page
+ + + +
public static function init($length =  null,
$action =  null)
function to initialise the csrfProtector work flow
public static function isURLallowed()
Function to check if a url mataches for any urls Listed in config file
+ + + +
private static function logCSRFattack()
Functio to log CSRF Attack
+ + + +
public static function ob_handler($buffer,
$flags)
Rewrites form on the fly to add CSRF tokens to them.
+ + + +
public static function refreshToken()
Function to set auth cookie
+ + + +
public static function useCachedVersion()
function to check weather to use cached version of js file or not
+ +
+ + + + + + + + + + + + \ No newline at end of file diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index/General.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index/General.html new file mode 100644 index 00000000..adc327a6 --- /dev/null +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index/General.html @@ -0,0 +1,69 @@ + + +Index + + + + + + + + + +
Index
$#! · 0-9 · A · B · C · D · E · F · G · H · I · J · K · L · M · N · O · P · Q · R · S · T · U · V · W · X · Y · Z
A
 authorisePost
C
$config
$cookieExpiryTime
 createNewJsCache
 csrfprotector.php
F
 failedValidationAction
 Functions
G
 generateAuthToken
 getCurrentUrl
I
 init
$isSameOrigin
 isURLallowed
$isValidHTML
L
 logCSRFattack
O
 ob_handler
R
 refreshToken
$requestType
U
 useCachedVersion
V
 Variables
+ +
public static function authorisePost()
function to authorise incoming post requests
+ + + +
public static $config
config file for CSRFProtector @var int Array, length = 6 Property: #1: failedAuthAction (int) => action to be taken in case autherisation fails Property: #2: logDirectory (string) => directory in which log will be saved Property: #3: customErrorMessage (string) => custom error message to be sent in case of failed authentication Property: #4: jsFile (string) => location of the CSRFProtector js file Property: #5: tokenLength (int) => default length of hash Property: #6: disabledJavascriptMessage (string) => error message if client’s js is disabled
public static $cookieExpiryTime
expiry time for cookie @var int
public static function createNewJsCache()
Function to create new cache version of js
+ + + +
private static function failedValidationAction()
function to be called in case of failed validation performs logging and take appropriate action
+ + + +
public static function generateAuthToken()
function to generate random hash of length as given in parameter max length = 128
private static function getCurrentUrl()
Function to return current url of executing page
+ + + +
public static function init($length =  null,
$action =  null)
function to initialise the csrfProtector work flow
private static $isSameOrigin
flag for cross origin/same origin request @var bool
public static function isURLallowed()
Function to check if a url mataches for any urls Listed in config file
private static $isValidHTML
flag to check if output file is a valid HTML or not @var bool
+ + + +
private static function logCSRFattack()
Functio to log CSRF Attack
+ + + +
public static function ob_handler($buffer,
$flags)
Rewrites form on the fly to add CSRF tokens to them.
+ + + +
public static function refreshToken()
Function to set auth cookie
protected static $requestType
Varaible to store weather request type is post or get @var string
+ + + +
public static function useCachedVersion()
function to check weather to use cached version of js file or not
+ + + + + +
+ + + + + + + + + + + + \ No newline at end of file diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index/Variables.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index/Variables.html new file mode 100644 index 00000000..14fccdfb --- /dev/null +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/index/Variables.html @@ -0,0 +1,41 @@ + + +Variable Index + + + + + + + + + +
Variable Index
$#! · 0-9 · A · B · C · D · E · F · G · H · I · J · K · L · M · N · O · P · Q · R · S · T · U · V · W · X · Y · Z
C
$config
$cookieExpiryTime
I
$isSameOrigin
$isValidHTML
R
$requestType
+ +
public static $config
config file for CSRFProtector @var int Array, length = 6 Property: #1: failedAuthAction (int) => action to be taken in case autherisation fails Property: #2: logDirectory (string) => directory in which log will be saved Property: #3: customErrorMessage (string) => custom error message to be sent in case of failed authentication Property: #4: jsFile (string) => location of the CSRFProtector js file Property: #5: tokenLength (int) => default length of hash Property: #6: disabledJavascriptMessage (string) => error message if client’s js is disabled
public static $cookieExpiryTime
expiry time for cookie @var int
+ + + +
private static $isSameOrigin
flag for cross origin/same origin request @var bool
private static $isValidHTML
flag to check if output file is a valid HTML or not @var bool
+ + + +
protected static $requestType
Varaible to store weather request type is post or get @var string
+ +
+ + + + + + + + + + + + \ No newline at end of file diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/javascript/main.js b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/javascript/main.js new file mode 100644 index 00000000..3f42acde --- /dev/null +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/javascript/main.js @@ -0,0 +1,841 @@ +// This file is part of Natural Docs, which is Copyright 2003-2010 Greg Valure +// Natural Docs is licensed under version 3 of the GNU Affero General Public License (AGPL) +// Refer to License.txt for the complete details + +// This file may be distributed with documentation files generated by Natural Docs. +// Such documentation is not covered by Natural Docs' copyright and licensing, +// and may have its own copyright and distribution terms as decided by its author. + + +// +// Browser Styles +// ____________________________________________________________________________ + +var agt=navigator.userAgent.toLowerCase(); +var browserType; +var browserVer; + +if (agt.indexOf("opera") != -1) + { + browserType = "Opera"; + + if (agt.indexOf("opera 7") != -1 || agt.indexOf("opera/7") != -1) + { browserVer = "Opera7"; } + else if (agt.indexOf("opera 8") != -1 || agt.indexOf("opera/8") != -1) + { browserVer = "Opera8"; } + else if (agt.indexOf("opera 9") != -1 || agt.indexOf("opera/9") != -1) + { browserVer = "Opera9"; } + } + +else if (agt.indexOf("applewebkit") != -1) + { + browserType = "Safari"; + + if (agt.indexOf("version/3") != -1) + { browserVer = "Safari3"; } + else if (agt.indexOf("safari/4") != -1) + { browserVer = "Safari2"; } + } + +else if (agt.indexOf("khtml") != -1) + { + browserType = "Konqueror"; + } + +else if (agt.indexOf("msie") != -1) + { + browserType = "IE"; + + if (agt.indexOf("msie 6") != -1) + { browserVer = "IE6"; } + else if (agt.indexOf("msie 7") != -1) + { browserVer = "IE7"; } + } + +else if (agt.indexOf("gecko") != -1) + { + browserType = "Firefox"; + + if (agt.indexOf("rv:1.7") != -1) + { browserVer = "Firefox1"; } + else if (agt.indexOf("rv:1.8)") != -1 || agt.indexOf("rv:1.8.0") != -1) + { browserVer = "Firefox15"; } + else if (agt.indexOf("rv:1.8.1") != -1) + { browserVer = "Firefox2"; } + } + + +// +// Support Functions +// ____________________________________________________________________________ + + +function GetXPosition(item) + { + var position = 0; + + if (item.offsetWidth != null) + { + while (item != document.body && item != null) + { + position += item.offsetLeft; + item = item.offsetParent; + }; + }; + + return position; + }; + + +function GetYPosition(item) + { + var position = 0; + + if (item.offsetWidth != null) + { + while (item != document.body && item != null) + { + position += item.offsetTop; + item = item.offsetParent; + }; + }; + + return position; + }; + + +function MoveToPosition(item, x, y) + { + // Opera 5 chokes on the px extension, so it can use the Microsoft one instead. + + if (item.style.left != null) + { + item.style.left = x + "px"; + item.style.top = y + "px"; + } + else if (item.style.pixelLeft != null) + { + item.style.pixelLeft = x; + item.style.pixelTop = y; + }; + }; + + +// +// Menu +// ____________________________________________________________________________ + + +function ToggleMenu(id) + { + if (!window.document.getElementById) + { return; }; + + var display = window.document.getElementById(id).style.display; + + if (display == "none") + { display = "block"; } + else + { display = "none"; } + + window.document.getElementById(id).style.display = display; + } + +function HideAllBut(ids, max) + { + if (document.getElementById) + { + ids.sort( function(a,b) { return a - b; } ); + var number = 1; + + while (number < max) + { + if (ids.length > 0 && number == ids[0]) + { ids.shift(); } + else + { + document.getElementById("MGroupContent" + number).style.display = "none"; + }; + + number++; + }; + }; + } + + +// +// Tooltips +// ____________________________________________________________________________ + + +var tooltipTimer = 0; + +function ShowTip(event, tooltipID, linkID) + { + if (tooltipTimer) + { clearTimeout(tooltipTimer); }; + + var docX = event.clientX + window.pageXOffset; + var docY = event.clientY + window.pageYOffset; + + var showCommand = "ReallyShowTip('" + tooltipID + "', '" + linkID + "', " + docX + ", " + docY + ")"; + + tooltipTimer = setTimeout(showCommand, 1000); + } + +function ReallyShowTip(tooltipID, linkID, docX, docY) + { + tooltipTimer = 0; + + var tooltip; + var link; + + if (document.getElementById) + { + tooltip = document.getElementById(tooltipID); + link = document.getElementById(linkID); + } +/* else if (document.all) + { + tooltip = eval("document.all['" + tooltipID + "']"); + link = eval("document.all['" + linkID + "']"); + } +*/ + if (tooltip) + { + var left = GetXPosition(link); + var top = GetYPosition(link); + top += link.offsetHeight; + + + // The fallback method is to use the mouse X and Y relative to the document. We use a separate if and test if its a number + // in case some browser snuck through the above if statement but didn't support everything. + + if (!isFinite(top) || top == 0) + { + left = docX; + top = docY; + } + + // Some spacing to get it out from under the cursor. + + top += 10; + + // Make sure the tooltip doesnt get smushed by being too close to the edge, or in some browsers, go off the edge of the + // page. We do it here because Konqueror does get offsetWidth right even if it doesnt get the positioning right. + + if (tooltip.offsetWidth != null) + { + var width = tooltip.offsetWidth; + var docWidth = document.body.clientWidth; + + if (left + width > docWidth) + { left = docWidth - width - 1; } + + // If there's a horizontal scroll bar we could go past zero because it's using the page width, not the window width. + if (left < 0) + { left = 0; }; + } + + MoveToPosition(tooltip, left, top); + tooltip.style.visibility = "visible"; + } + } + +function HideTip(tooltipID) + { + if (tooltipTimer) + { + clearTimeout(tooltipTimer); + tooltipTimer = 0; + } + + var tooltip; + + if (document.getElementById) + { tooltip = document.getElementById(tooltipID); } + else if (document.all) + { tooltip = eval("document.all['" + tooltipID + "']"); } + + if (tooltip) + { tooltip.style.visibility = "hidden"; } + } + + +// +// Blockquote fix for IE +// ____________________________________________________________________________ + + +function NDOnLoad() + { + if (browserVer == "IE6") + { + var scrollboxes = document.getElementsByTagName('blockquote'); + + if (scrollboxes.item(0)) + { + NDDoResize(); + window.onresize=NDOnResize; + }; + }; + }; + + +var resizeTimer = 0; + +function NDOnResize() + { + if (resizeTimer != 0) + { clearTimeout(resizeTimer); }; + + resizeTimer = setTimeout(NDDoResize, 250); + }; + + +function NDDoResize() + { + var scrollboxes = document.getElementsByTagName('blockquote'); + + var i; + var item; + + i = 0; + while (item = scrollboxes.item(i)) + { + item.style.width = 100; + i++; + }; + + i = 0; + while (item = scrollboxes.item(i)) + { + item.style.width = item.parentNode.offsetWidth; + i++; + }; + + clearTimeout(resizeTimer); + resizeTimer = 0; + } + + + +/* ________________________________________________________________________________________________________ + + Class: SearchPanel + ________________________________________________________________________________________________________ + + A class handling everything associated with the search panel. + + Parameters: + + name - The name of the global variable that will be storing this instance. Is needed to be able to set timeouts. + mode - The mode the search is going to work in. Pass CommandLineOption()>, so the + value will be something like "HTML" or "FramedHTML". + + ________________________________________________________________________________________________________ +*/ + + +function SearchPanel(name, mode, resultsPath) + { + if (!name || !mode || !resultsPath) + { alert("Incorrect parameters to SearchPanel."); }; + + + // Group: Variables + // ________________________________________________________________________ + + /* + var: name + The name of the global variable that will be storing this instance of the class. + */ + this.name = name; + + /* + var: mode + The mode the search is going to work in, such as "HTML" or "FramedHTML". + */ + this.mode = mode; + + /* + var: resultsPath + The relative path from the current HTML page to the results page directory. + */ + this.resultsPath = resultsPath; + + /* + var: keyTimeout + The timeout used between a keystroke and when a search is performed. + */ + this.keyTimeout = 0; + + /* + var: keyTimeoutLength + The length of in thousandths of a second. + */ + this.keyTimeoutLength = 500; + + /* + var: lastSearchValue + The last search string executed, or an empty string if none. + */ + this.lastSearchValue = ""; + + /* + var: lastResultsPage + The last results page. The value is only relevant if is set. + */ + this.lastResultsPage = ""; + + /* + var: deactivateTimeout + + The timeout used between when a control is deactivated and when the entire panel is deactivated. Is necessary + because a control may be deactivated in favor of another control in the same panel, in which case it should stay + active. + */ + this.deactivateTimout = 0; + + /* + var: deactivateTimeoutLength + The length of in thousandths of a second. + */ + this.deactivateTimeoutLength = 200; + + + + + // Group: DOM Elements + // ________________________________________________________________________ + + + // Function: DOMSearchField + this.DOMSearchField = function() + { return document.getElementById("MSearchField"); }; + + // Function: DOMSearchType + this.DOMSearchType = function() + { return document.getElementById("MSearchType"); }; + + // Function: DOMPopupSearchResults + this.DOMPopupSearchResults = function() + { return document.getElementById("MSearchResults"); }; + + // Function: DOMPopupSearchResultsWindow + this.DOMPopupSearchResultsWindow = function() + { return document.getElementById("MSearchResultsWindow"); }; + + // Function: DOMSearchPanel + this.DOMSearchPanel = function() + { return document.getElementById("MSearchPanel"); }; + + + + + // Group: Event Handlers + // ________________________________________________________________________ + + + /* + Function: OnSearchFieldFocus + Called when focus is added or removed from the search field. + */ + this.OnSearchFieldFocus = function(isActive) + { + this.Activate(isActive); + }; + + + /* + Function: OnSearchFieldChange + Called when the content of the search field is changed. + */ + this.OnSearchFieldChange = function() + { + if (this.keyTimeout) + { + clearTimeout(this.keyTimeout); + this.keyTimeout = 0; + }; + + var searchValue = this.DOMSearchField().value.replace(/ +/g, ""); + + if (searchValue != this.lastSearchValue) + { + if (searchValue != "") + { + this.keyTimeout = setTimeout(this.name + ".Search()", this.keyTimeoutLength); + } + else + { + if (this.mode == "HTML") + { this.DOMPopupSearchResultsWindow().style.display = "none"; }; + this.lastSearchValue = ""; + }; + }; + }; + + + /* + Function: OnSearchTypeFocus + Called when focus is added or removed from the search type. + */ + this.OnSearchTypeFocus = function(isActive) + { + this.Activate(isActive); + }; + + + /* + Function: OnSearchTypeChange + Called when the search type is changed. + */ + this.OnSearchTypeChange = function() + { + var searchValue = this.DOMSearchField().value.replace(/ +/g, ""); + + if (searchValue != "") + { + this.Search(); + }; + }; + + + + // Group: Action Functions + // ________________________________________________________________________ + + + /* + Function: CloseResultsWindow + Closes the results window. + */ + this.CloseResultsWindow = function() + { + this.DOMPopupSearchResultsWindow().style.display = "none"; + this.Activate(false, true); + }; + + + /* + Function: Search + Performs a search. + */ + this.Search = function() + { + this.keyTimeout = 0; + + var searchValue = this.DOMSearchField().value.replace(/^ +/, ""); + var searchTopic = this.DOMSearchType().value; + + var pageExtension = searchValue.substr(0,1); + + if (pageExtension.match(/^[a-z]/i)) + { pageExtension = pageExtension.toUpperCase(); } + else if (pageExtension.match(/^[0-9]/)) + { pageExtension = 'Numbers'; } + else + { pageExtension = "Symbols"; }; + + var resultsPage; + var resultsPageWithSearch; + var hasResultsPage; + + // indexSectionsWithContent is defined in searchdata.js + if (indexSectionsWithContent[searchTopic][pageExtension] == true) + { + resultsPage = this.resultsPath + '/' + searchTopic + pageExtension + '.html'; + resultsPageWithSearch = resultsPage+'?'+escape(searchValue); + hasResultsPage = true; + } + else + { + resultsPage = this.resultsPath + '/NoResults.html'; + resultsPageWithSearch = resultsPage; + hasResultsPage = false; + }; + + var resultsFrame; + if (this.mode == "HTML") + { resultsFrame = window.frames.MSearchResults; } + else if (this.mode == "FramedHTML") + { resultsFrame = window.top.frames['Content']; }; + + + if (resultsPage != this.lastResultsPage || + + // Bug in IE. If everything becomes hidden in a run, none of them will be able to be reshown in the next for some + // reason. It counts the right number of results, and you can even read the display as "block" after setting it, but it + // just doesn't work in IE 6 or IE 7. So if we're on the right page but the previous search had no results, reload the + // page anyway to get around the bug. + (browserType == "IE" && hasResultsPage && + (!resultsFrame.searchResults || resultsFrame.searchResults.lastMatchCount == 0)) ) + + { + resultsFrame.location.href = resultsPageWithSearch; + } + + // So if the results page is right and there's no IE bug, reperform the search on the existing page. We have to check if there + // are results because NoResults.html doesn't have any JavaScript, and it would be useless to do anything on that page even + // if it did. + else if (hasResultsPage) + { + // We need to check if this exists in case the frame is present but didn't finish loading. + if (resultsFrame.searchResults) + { resultsFrame.searchResults.Search(searchValue); } + + // Otherwise just reload instead of waiting. + else + { resultsFrame.location.href = resultsPageWithSearch; }; + }; + + + var domPopupSearchResultsWindow = this.DOMPopupSearchResultsWindow(); + + if (this.mode == "HTML" && domPopupSearchResultsWindow.style.display != "block") + { + var domSearchType = this.DOMSearchType(); + + var left = GetXPosition(domSearchType); + var top = GetYPosition(domSearchType) + domSearchType.offsetHeight; + + MoveToPosition(domPopupSearchResultsWindow, left, top); + domPopupSearchResultsWindow.style.display = 'block'; + }; + + + this.lastSearchValue = searchValue; + this.lastResultsPage = resultsPage; + }; + + + + // Group: Activation Functions + // Functions that handle whether the entire panel is active or not. + // ________________________________________________________________________ + + + /* + Function: Activate + + Activates or deactivates the search panel, resetting things to their default values if necessary. You can call this on every + control's OnBlur() and it will handle not deactivating the entire panel when focus is just switching between them transparently. + + Parameters: + + isActive - Whether you're activating or deactivating the panel. + ignoreDeactivateDelay - Set if you're positive the action will deactivate the panel and thus want to skip the delay. + */ + this.Activate = function(isActive, ignoreDeactivateDelay) + { + // We want to ignore isActive being false while the results window is open. + if (isActive || (this.mode == "HTML" && this.DOMPopupSearchResultsWindow().style.display == "block")) + { + if (this.inactivateTimeout) + { + clearTimeout(this.inactivateTimeout); + this.inactivateTimeout = 0; + }; + + this.DOMSearchPanel().className = 'MSearchPanelActive'; + + var searchField = this.DOMSearchField(); + + if (searchField.value == 'Search') + { searchField.value = ""; } + } + else if (!ignoreDeactivateDelay) + { + this.inactivateTimeout = setTimeout(this.name + ".InactivateAfterTimeout()", this.inactivateTimeoutLength); + } + else + { + this.InactivateAfterTimeout(); + }; + }; + + + /* + Function: InactivateAfterTimeout + + Called by , which is set by . Inactivation occurs on a timeout because a control may + receive OnBlur() when focus is really transferring to another control in the search panel. In this case we don't want to + actually deactivate the panel because not only would that cause a visible flicker but it could also reset the search value. + So by doing it on a timeout instead, there's a short period where the second control's OnFocus() can cancel the deactivation. + */ + this.InactivateAfterTimeout = function() + { + this.inactivateTimeout = 0; + + this.DOMSearchPanel().className = 'MSearchPanelInactive'; + this.DOMSearchField().value = "Search"; + + this.lastSearchValue = ""; + this.lastResultsPage = ""; + }; + }; + + + + +/* ________________________________________________________________________________________________________ + + Class: SearchResults + _________________________________________________________________________________________________________ + + The class that handles everything on the search results page. + _________________________________________________________________________________________________________ +*/ + + +function SearchResults(name, mode) + { + /* + var: mode + The mode the search is going to work in, such as "HTML" or "FramedHTML". + */ + this.mode = mode; + + /* + var: lastMatchCount + The number of matches from the last run of . + */ + this.lastMatchCount = 0; + + + /* + Function: Toggle + Toggles the visibility of the passed element ID. + */ + this.Toggle = function(id) + { + if (this.mode == "FramedHTML") + { return; }; + + var parentElement = document.getElementById(id); + + var element = parentElement.firstChild; + + while (element && element != parentElement) + { + if (element.nodeName == 'DIV' && element.className == 'ISubIndex') + { + if (element.style.display == 'block') + { element.style.display = "none"; } + else + { element.style.display = 'block'; } + }; + + if (element.nodeName == 'DIV' && element.hasChildNodes()) + { element = element.firstChild; } + else if (element.nextSibling) + { element = element.nextSibling; } + else + { + do + { + element = element.parentNode; + } + while (element && element != parentElement && !element.nextSibling); + + if (element && element != parentElement) + { element = element.nextSibling; }; + }; + }; + }; + + + /* + Function: Search + + Searches for the passed string. If there is no parameter, it takes it from the URL query. + + Always returns true, since other documents may try to call it and that may or may not be possible. + */ + this.Search = function(search) + { + if (!search) + { + search = window.location.search; + search = search.substring(1); // Remove the leading ? + search = unescape(search); + }; + + search = search.replace(/^ +/, ""); + search = search.replace(/ +$/, ""); + search = search.toLowerCase(); + + if (search.match(/[^a-z0-9]/)) // Just a little speedup so it doesn't have to go through the below unnecessarily. + { + search = search.replace(/\_/g, "_und"); + search = search.replace(/\ +/gi, "_spc"); + search = search.replace(/\~/g, "_til"); + search = search.replace(/\!/g, "_exc"); + search = search.replace(/\@/g, "_att"); + search = search.replace(/\#/g, "_num"); + search = search.replace(/\$/g, "_dol"); + search = search.replace(/\%/g, "_pct"); + search = search.replace(/\^/g, "_car"); + search = search.replace(/\&/g, "_amp"); + search = search.replace(/\*/g, "_ast"); + search = search.replace(/\(/g, "_lpa"); + search = search.replace(/\)/g, "_rpa"); + search = search.replace(/\-/g, "_min"); + search = search.replace(/\+/g, "_plu"); + search = search.replace(/\=/g, "_equ"); + search = search.replace(/\{/g, "_lbc"); + search = search.replace(/\}/g, "_rbc"); + search = search.replace(/\[/g, "_lbk"); + search = search.replace(/\]/g, "_rbk"); + search = search.replace(/\:/g, "_col"); + search = search.replace(/\;/g, "_sco"); + search = search.replace(/\"/g, "_quo"); + search = search.replace(/\'/g, "_apo"); + search = search.replace(/\/g, "_ran"); + search = search.replace(/\,/g, "_com"); + search = search.replace(/\./g, "_per"); + search = search.replace(/\?/g, "_que"); + search = search.replace(/\//g, "_sla"); + search = search.replace(/[^a-z0-9\_]i/gi, "_zzz"); + }; + + var resultRows = document.getElementsByTagName("div"); + var matches = 0; + + var i = 0; + while (i < resultRows.length) + { + var row = resultRows.item(i); + + if (row.className == "SRResult") + { + var rowMatchName = row.id.toLowerCase(); + rowMatchName = rowMatchName.replace(/^sr\d*_/, ''); + + if (search.length <= rowMatchName.length && rowMatchName.substr(0, search.length) == search) + { + row.style.display = "block"; + matches++; + } + else + { row.style.display = "none"; }; + }; + + i++; + }; + + document.getElementById("Searching").style.display="none"; + + if (matches == 0) + { document.getElementById("NoMatches").style.display="block"; } + else + { document.getElementById("NoMatches").style.display="none"; } + + this.lastMatchCount = matches; + + return true; + }; + }; + diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/javascript/prettify.js b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/javascript/prettify.js new file mode 100644 index 00000000..fda4bf1e --- /dev/null +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/javascript/prettify.js @@ -0,0 +1,1526 @@ + +// This code comes from the December 2009 release of Google Prettify, which is Copyright 2006 Google Inc. +// Minor modifications are marked with "ND Change" comments. +// As part of Natural Docs, this code is licensed under version 3 of the GNU Affero General Public License (AGPL.) +// However, it may also be obtained separately under version 2.0 of the Apache License. +// Refer to License.txt for the complete details + + +// Main code +// ____________________________________________________________________________ + +// Copyright (C) 2006 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +/** + * @fileoverview + * some functions for browser-side pretty printing of code contained in html. + *

+ * + * For a fairly comprehensive set of languages see the + * README + * file that came with this source. At a minimum, the lexer should work on a + * number of languages including C and friends, Java, Python, Bash, SQL, HTML, + * XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk + * and a subset of Perl, but, because of commenting conventions, doesn't work on + * Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class. + *

+ * Usage:

    + *
  1. include this source file in an html page via + * {@code } + *
  2. define style rules. See the example page for examples. + *
  3. mark the {@code
    } and {@code } tags in your source with
    + *    {@code class=prettyprint.}
    + *    You can also use the (html deprecated) {@code } tag, but the pretty
    + *    printer needs to do more substantial DOM manipulations to support that, so
    + *    some css styles may not be preserved.
    + * </ol>
    + * That's it.  I wanted to keep the API as simple as possible, so there's no
    + * need to specify which language the code is in, but if you wish, you can add
    + * another class to the {@code <pre>} or {@code <code>} element to specify the
    + * language, as in {@code <pre class="prettyprint lang-java">}.  Any class that
    + * starts with "lang-" followed by a file extension, specifies the file type.
    + * See the "lang-*.js" files in this directory for code that implements
    + * per-language file handlers.
    + * <p>
    + * Change log:<br>
    + * cbeust, 2006/08/22
    + * <blockquote>
    + *   Java annotations (start with "@") are now captured as literals ("lit")
    + * </blockquote>
    + * @requires console
    + * @overrides window
    + */
    +
    +// JSLint declarations
    +/*global console, document, navigator, setTimeout, window */
    +
    +/**
    + * Split {@code prettyPrint} into multiple timeouts so as not to interfere with
    + * UI events.
    + * If set to {@code false}, {@code prettyPrint()} is synchronous.
    + */
    +window['PR_SHOULD_USE_CONTINUATION'] = true;
    +
    +/** the number of characters between tab columns */
    +window['PR_TAB_WIDTH'] = 8;
    +
    +/** Walks the DOM returning a properly escaped version of innerHTML.
    +  * @param {Node} node
    +  * @param {Array.<string>} out output buffer that receives chunks of HTML.
    +  */
    +window['PR_normalizedHtml']
    +
    +/** Contains functions for creating and registering new language handlers.
    +  * @type {Object}
    +  */
    +  = window['PR']
    +
    +/** Pretty print a chunk of code.
    +  *
    +  * @param {string} sourceCodeHtml code as html
    +  * @return {string} code as html, but prettier
    +  */
    +  = window['prettyPrintOne']
    +/** Find all the {@code <pre>} and {@code <code>} tags in the DOM with
    +  * {@code class=prettyprint} and prettify them.
    +  * @param {Function?} opt_whenDone if specified, called when the last entry
    +  *     has been finished.
    +  */
    +  = window['prettyPrint'] = void 0;
    +
    +/** browser detection. @extern @returns false if not IE, otherwise the major version. */
    +window['_pr_isIE6'] = function () {
    +  var ieVersion = navigator && navigator.userAgent &&
    +      navigator.userAgent.match(/\bMSIE ([678])\./);
    +  ieVersion = ieVersion ? +ieVersion[1] : false;
    +  window['_pr_isIE6'] = function () { return ieVersion; };
    +  return ieVersion;
    +};
    +
    +
    +(function () {
    +  // Keyword lists for various languages.
    +  var FLOW_CONTROL_KEYWORDS =
    +      "break continue do else for if return while ";
    +  var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default " +
    +      "double enum extern float goto int long register short signed sizeof " +
    +      "static struct switch typedef union unsigned void volatile ";
    +  var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import " +
    +      "new operator private protected public this throw true try typeof ";
    +  var CPP_KEYWORDS = COMMON_KEYWORDS + "alignof align_union asm axiom bool " +
    +      "concept concept_map const_cast constexpr decltype " +
    +      "dynamic_cast explicit export friend inline late_check " +
    +      "mutable namespace nullptr reinterpret_cast static_assert static_cast " +
    +      "template typeid typename using virtual wchar_t where ";
    +  var JAVA_KEYWORDS = COMMON_KEYWORDS +
    +      "abstract boolean byte extends final finally implements import " +
    +      "instanceof null native package strictfp super synchronized throws " +
    +      "transient ";
    +  var CSHARP_KEYWORDS = JAVA_KEYWORDS +
    +      "as base by checked decimal delegate descending event " +
    +      "fixed foreach from group implicit in interface internal into is lock " +
    +      "object out override orderby params partial readonly ref sbyte sealed " +
    +      "stackalloc string select uint ulong unchecked unsafe ushort var ";
    +  var JSCRIPT_KEYWORDS = COMMON_KEYWORDS +
    +      "debugger eval export function get null set undefined var with " +
    +      "Infinity NaN ";
    +  var PERL_KEYWORDS = "caller delete die do dump elsif eval exit foreach for " +
    +      "goto if import last local my next no our print package redo require " +
    +      "sub undef unless until use wantarray while BEGIN END ";
    +  var PYTHON_KEYWORDS = FLOW_CONTROL_KEYWORDS + "and as assert class def del " +
    +      "elif except exec finally from global import in is lambda " +
    +      "nonlocal not or pass print raise try with yield " +
    +      "False True None ";
    +  var RUBY_KEYWORDS = FLOW_CONTROL_KEYWORDS + "alias and begin case class def" +
    +      " defined elsif end ensure false in module next nil not or redo rescue " +
    +      "retry self super then true undef unless until when yield BEGIN END ";
    +  var SH_KEYWORDS = FLOW_CONTROL_KEYWORDS + "case done elif esac eval fi " +
    +      "function in local set then until ";
    +  var ALL_KEYWORDS = (
    +      CPP_KEYWORDS + CSHARP_KEYWORDS + JSCRIPT_KEYWORDS + PERL_KEYWORDS +
    +      PYTHON_KEYWORDS + RUBY_KEYWORDS + SH_KEYWORDS);
    +
    +  // token style names.  correspond to css classes
    +  /** token style for a string literal */
    +  var PR_STRING = 'str';
    +  /** token style for a keyword */
    +  var PR_KEYWORD = 'kwd';
    +  /** token style for a comment */
    +  var PR_COMMENT = 'com';
    +  /** token style for a type */
    +  var PR_TYPE = 'typ';
    +  /** token style for a literal value.  e.g. 1, null, true. */
    +  var PR_LITERAL = 'lit';
    +  /** token style for a punctuation string. */
    +  var PR_PUNCTUATION = 'pun';
    +  /** token style for a punctuation string. */
    +  var PR_PLAIN = 'pln';
    +
    +  /** token style for an sgml tag. */
    +  var PR_TAG = 'tag';
    +  /** token style for a markup declaration such as a DOCTYPE. */
    +  var PR_DECLARATION = 'dec';
    +  /** token style for embedded source. */
    +  var PR_SOURCE = 'src';
    +  /** token style for an sgml attribute name. */
    +  var PR_ATTRIB_NAME = 'atn';
    +  /** token style for an sgml attribute value. */
    +  var PR_ATTRIB_VALUE = 'atv';
    +
    +  /**
    +   * A class that indicates a section of markup that is not code, e.g. to allow
    +   * embedding of line numbers within code listings.
    +   */
    +  var PR_NOCODE = 'nocode';
    +
    +  /** A set of tokens that can precede a regular expression literal in
    +    * javascript.
    +    * http://www.mozilla.org/js/language/js20/rationale/syntax.html has the full
    +    * list, but I've removed ones that might be problematic when seen in
    +    * languages that don't support regular expression literals.
    +    *
    +    * <p>Specifically, I've removed any keywords that can't precede a regexp
    +    * literal in a syntactically legal javascript program, and I've removed the
    +    * "in" keyword since it's not a keyword in many languages, and might be used
    +    * as a count of inches.
    +    *
    +    * <p>The link a above does not accurately describe EcmaScript rules since
    +    * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
    +    * very well in practice.
    +    *
    +    * @private
    +    */
    +  var REGEXP_PRECEDER_PATTERN = function () {
    +      var preceders = [
    +          "!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=",
    +          "&=", "(", "*", "*=", /* "+", */ "+=", ",", /* "-", */ "-=",
    +          "->", /*".", "..", "...", handled below */ "/", "/=", ":", "::", ";",
    +          "<", "<<", "<<=", "<=", "=", "==", "===", ">",
    +          ">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[",
    +          "^", "^=", "^^", "^^=", "{", "|", "|=", "||",
    +          "||=", "~" /* handles =~ and !~ */,
    +          "break", "case", "continue", "delete",
    +          "do", "else", "finally", "instanceof",
    +          "return", "throw", "try", "typeof"
    +          ];
    +      var pattern = '(?:^^|[+-]';
    +      for (var i = 0; i < preceders.length; ++i) {
    +        pattern += '|' + preceders[i].replace(/([^=<>:&a-z])/g, '\\$1');
    +      }
    +      pattern += ')\\s*';  // matches at end, and matches empty string
    +      return pattern;
    +      // CAVEAT: this does not properly handle the case where a regular
    +      // expression immediately follows another since a regular expression may
    +      // have flags for case-sensitivity and the like.  Having regexp tokens
    +      // adjacent is not valid in any language I'm aware of, so I'm punting.
    +      // TODO: maybe style special characters inside a regexp as punctuation.
    +    }();
    +
    +  // Define regexps here so that the interpreter doesn't have to create an
    +  // object each time the function containing them is called.
    +  // The language spec requires a new object created even if you don't access
    +  // the $1 members.
    +  var pr_amp = /&/g;
    +  var pr_lt = /</g;
    +  var pr_gt = />/g;
    +  var pr_quot = /\"/g;
    +  /** like textToHtml but escapes double quotes to be attribute safe. */
    +  function attribToHtml(str) {
    +    return str.replace(pr_amp, '&amp;')
    +        .replace(pr_lt, '&lt;')
    +        .replace(pr_gt, '&gt;')
    +        .replace(pr_quot, '&quot;');
    +  }
    +
    +  /** escapest html special characters to html. */
    +  function textToHtml(str) {
    +    return str.replace(pr_amp, '&amp;')
    +        .replace(pr_lt, '&lt;')
    +        .replace(pr_gt, '&gt;');
    +  }
    +
    +
    +  var pr_ltEnt = /&lt;/g;
    +  var pr_gtEnt = /&gt;/g;
    +  var pr_aposEnt = /&apos;/g;
    +  var pr_quotEnt = /&quot;/g;
    +  var pr_ampEnt = /&amp;/g;
    +  var pr_nbspEnt = /&nbsp;/g;
    +  /** unescapes html to plain text. */
    +  function htmlToText(html) {
    +    var pos = html.indexOf('&');
    +    if (pos < 0) { return html; }
    +    // Handle numeric entities specially.  We can't use functional substitution
    +    // since that doesn't work in older versions of Safari.
    +    // These should be rare since most browsers convert them to normal chars.
    +    for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) {
    +      var end = html.indexOf(';', pos);
    +      if (end >= 0) {
    +        var num = html.substring(pos + 3, end);
    +        var radix = 10;
    +        if (num && num.charAt(0) === 'x') {
    +          num = num.substring(1);
    +          radix = 16;
    +        }
    +        var codePoint = parseInt(num, radix);
    +        if (!isNaN(codePoint)) {
    +          html = (html.substring(0, pos) + String.fromCharCode(codePoint) +
    +                  html.substring(end + 1));
    +        }
    +      }
    +    }
    +
    +    return html.replace(pr_ltEnt, '<')
    +        .replace(pr_gtEnt, '>')
    +        .replace(pr_aposEnt, "'")
    +        .replace(pr_quotEnt, '"')
    +        .replace(pr_nbspEnt, ' ')
    +        .replace(pr_ampEnt, '&');
    +  }
    +
    +  /** is the given node's innerHTML normally unescaped? */
    +  function isRawContent(node) {
    +    return 'XMP' === node.tagName;
    +  }
    +
    +  var newlineRe = /[\r\n]/g;
    +  /**
    +   * Are newlines and adjacent spaces significant in the given node's innerHTML?
    +   */
    +  function isPreformatted(node, content) {
    +    // PRE means preformatted, and is a very common case, so don't create
    +    // unnecessary computed style objects.
    +    if ('PRE' === node.tagName) { return true; }
    +    if (!newlineRe.test(content)) { return true; }  // Don't care
    +    var whitespace = '';
    +    // For disconnected nodes, IE has no currentStyle.
    +    if (node.currentStyle) {
    +      whitespace = node.currentStyle.whiteSpace;
    +    } else if (window.getComputedStyle) {
    +      // Firefox makes a best guess if node is disconnected whereas Safari
    +      // returns the empty string.
    +      whitespace = window.getComputedStyle(node, null).whiteSpace;
    +    }
    +    return !whitespace || whitespace === 'pre';
    +  }
    +
    +  function normalizedHtml(node, out) {
    +    switch (node.nodeType) {
    +      case 1:  // an element
    +        var name = node.tagName.toLowerCase();
    +        out.push('<', name);
    +        for (var i = 0; i < node.attributes.length; ++i) {
    +          var attr = node.attributes[i];
    +          if (!attr.specified) { continue; }
    +          out.push(' ');
    +          normalizedHtml(attr, out);
    +        }
    +        out.push('>');
    +        for (var child = node.firstChild; child; child = child.nextSibling) {
    +          normalizedHtml(child, out);
    +        }
    +        if (node.firstChild || !/^(?:br|link|img)$/.test(name)) {
    +          out.push('<\/', name, '>');
    +        }
    +        break;
    +      case 2: // an attribute
    +        out.push(node.name.toLowerCase(), '="', attribToHtml(node.value), '"');
    +        break;
    +      case 3: case 4: // text
    +        out.push(textToHtml(node.nodeValue));
    +        break;
    +    }
    +  }
    +
    +  /**
    +   * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
    +   * matches the union o the sets o strings matched d by the input RegExp.
    +   * Since it matches globally, if the input strings have a start-of-input
    +   * anchor (/^.../), it is ignored for the purposes of unioning.
    +   * @param {Array.<RegExp>} regexs non multiline, non-global regexs.
    +   * @return {RegExp} a global regex.
    +   */
    +  function combinePrefixPatterns(regexs) {
    +    var capturedGroupIndex = 0;
    +
    +    var needToFoldCase = false;
    +    var ignoreCase = false;
    +    for (var i = 0, n = regexs.length; i < n; ++i) {
    +      var regex = regexs[i];
    +      if (regex.ignoreCase) {
    +        ignoreCase = true;
    +      } else if (/[a-z]/i.test(regex.source.replace(
    +                     /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
    +        needToFoldCase = true;
    +        ignoreCase = false;
    +        break;
    +      }
    +    }
    +
    +    function decodeEscape(charsetPart) {
    +      if (charsetPart.charAt(0) !== '\\') { return charsetPart.charCodeAt(0); }
    +      switch (charsetPart.charAt(1)) {
    +        case 'b': return 8;
    +        case 't': return 9;
    +        case 'n': return 0xa;
    +        case 'v': return 0xb;
    +        case 'f': return 0xc;
    +        case 'r': return 0xd;
    +        case 'u': case 'x':
    +          return parseInt(charsetPart.substring(2), 16)
    +              || charsetPart.charCodeAt(1);
    +        case '0': case '1': case '2': case '3': case '4':
    +        case '5': case '6': case '7':
    +          return parseInt(charsetPart.substring(1), 8);
    +        default: return charsetPart.charCodeAt(1);
    +      }
    +    }
    +
    +    function encodeEscape(charCode) {
    +      if (charCode < 0x20) {
    +        return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
    +      }
    +      var ch = String.fromCharCode(charCode);
    +      if (ch === '\\' || ch === '-' || ch === '[' || ch === ']') {
    +        ch = '\\' + ch;
    +      }
    +      return ch;
    +    }
    +
    +    function caseFoldCharset(charSet) {
    +      var charsetParts = charSet.substring(1, charSet.length - 1).match(
    +          new RegExp(
    +              '\\\\u[0-9A-Fa-f]{4}'
    +              + '|\\\\x[0-9A-Fa-f]{2}'
    +              + '|\\\\[0-3][0-7]{0,2}'
    +              + '|\\\\[0-7]{1,2}'
    +              + '|\\\\[\\s\\S]'
    +              + '|-'
    +              + '|[^-\\\\]',
    +              'g'));
    +      var groups = [];
    +      var ranges = [];
    +      var inverse = charsetParts[0] === '^';
    +      for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
    +        var p = charsetParts[i];
    +        switch (p) {
    +          case '\\B': case '\\b':
    +          case '\\D': case '\\d':
    +          case '\\S': case '\\s':
    +          case '\\W': case '\\w':
    +            groups.push(p);
    +            continue;
    +        }
    +        var start = decodeEscape(p);
    +        var end;
    +        if (i + 2 < n && '-' === charsetParts[i + 1]) {
    +          end = decodeEscape(charsetParts[i + 2]);
    +          i += 2;
    +        } else {
    +          end = start;
    +        }
    +        ranges.push([start, end]);
    +        // If the range might intersect letters, then expand it.
    +        if (!(end < 65 || start > 122)) {
    +          if (!(end < 65 || start > 90)) {
    +            ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
    +          }
    +          if (!(end < 97 || start > 122)) {
    +            ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
    +          }
    +        }
    +      }
    +
    +      // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
    +      // -> [[1, 12], [14, 14], [16, 17]]
    +      ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1]  - a[1]); });
    +      var consolidatedRanges = [];
    +      var lastRange = [NaN, NaN];
    +      for (var i = 0; i < ranges.length; ++i) {
    +        var range = ranges[i];
    +        if (range[0] <= lastRange[1] + 1) {
    +          lastRange[1] = Math.max(lastRange[1], range[1]);
    +        } else {
    +          consolidatedRanges.push(lastRange = range);
    +        }
    +      }
    +
    +      var out = ['['];
    +      if (inverse) { out.push('^'); }
    +      out.push.apply(out, groups);
    +      for (var i = 0; i < consolidatedRanges.length; ++i) {
    +        var range = consolidatedRanges[i];
    +        out.push(encodeEscape(range[0]));
    +        if (range[1] > range[0]) {
    +          if (range[1] + 1 > range[0]) { out.push('-'); }
    +          out.push(encodeEscape(range[1]));
    +        }
    +      }
    +      out.push(']');
    +      return out.join('');
    +    }
    +
    +    function allowAnywhereFoldCaseAndRenumberGroups(regex) {
    +      // Split into character sets, escape sequences, punctuation strings
    +      // like ('(', '(?:', ')', '^'), and runs of characters that do not
    +      // include any of the above.
    +      var parts = regex.source.match(
    +          new RegExp(
    +              '(?:'
    +              + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]'  // a character set
    +              + '|\\\\u[A-Fa-f0-9]{4}'  // a unicode escape
    +              + '|\\\\x[A-Fa-f0-9]{2}'  // a hex escape
    +              + '|\\\\[0-9]+'  // a back-reference or octal escape
    +              + '|\\\\[^ux0-9]'  // other escape sequence
    +              + '|\\(\\?[:!=]'  // start of a non-capturing group
    +              + '|[\\(\\)\\^]'  // start/emd of a group, or line start
    +              + '|[^\\x5B\\x5C\\(\\)\\^]+'  // run of other characters
    +              + ')',
    +              'g'));
    +      var n = parts.length;
    +
    +      // Maps captured group numbers to the number they will occupy in
    +      // the output or to -1 if that has not been determined, or to
    +      // undefined if they need not be capturing in the output.
    +      var capturedGroups = [];
    +
    +      // Walk over and identify back references to build the capturedGroups
    +      // mapping.
    +      for (var i = 0, groupIndex = 0; i < n; ++i) {
    +        var p = parts[i];
    +        if (p === '(') {
    +          // groups are 1-indexed, so max group index is count of '('
    +          ++groupIndex;
    +        } else if ('\\' === p.charAt(0)) {
    +          var decimalValue = +p.substring(1);
    +          if (decimalValue && decimalValue <= groupIndex) {
    +            capturedGroups[decimalValue] = -1;
    +          }
    +        }
    +      }
    +
    +      // Renumber groups and reduce capturing groups to non-capturing groups
    +      // where possible.
    +      for (var i = 1; i < capturedGroups.length; ++i) {
    +        if (-1 === capturedGroups[i]) {
    +          capturedGroups[i] = ++capturedGroupIndex;
    +        }
    +      }
    +      for (var i = 0, groupIndex = 0; i < n; ++i) {
    +        var p = parts[i];
    +        if (p === '(') {
    +          ++groupIndex;
    +          if (capturedGroups[groupIndex] === undefined) {
    +            parts[i] = '(?:';
    +          }
    +        } else if ('\\' === p.charAt(0)) {
    +          var decimalValue = +p.substring(1);
    +          if (decimalValue && decimalValue <= groupIndex) {
    +            parts[i] = '\\' + capturedGroups[groupIndex];
    +          }
    +        }
    +      }
    +
    +      // Remove any prefix anchors so that the output will match anywhere.
    +      // ^^ really does mean an anchored match though.
    +      for (var i = 0, groupIndex = 0; i < n; ++i) {
    +        if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
    +      }
    +
    +      // Expand letters to groupts to handle mixing of case-sensitive and
    +      // case-insensitive patterns if necessary.
    +      if (regex.ignoreCase && needToFoldCase) {
    +        for (var i = 0; i < n; ++i) {
    +          var p = parts[i];
    +          var ch0 = p.charAt(0);
    +          if (p.length >= 2 && ch0 === '[') {
    +            parts[i] = caseFoldCharset(p);
    +          } else if (ch0 !== '\\') {
    +            // TODO: handle letters in numeric escapes.
    +            parts[i] = p.replace(
    +                /[a-zA-Z]/g,
    +                function (ch) {
    +                  var cc = ch.charCodeAt(0);
    +                  return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
    +                });
    +          }
    +        }
    +      }
    +
    +      return parts.join('');
    +    }
    +
    +    var rewritten = [];
    +    for (var i = 0, n = regexs.length; i < n; ++i) {
    +      var regex = regexs[i];
    +      if (regex.global || regex.multiline) { throw new Error('' + regex); }
    +      rewritten.push(
    +          '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
    +    }
    +
    +    return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
    +  }
    +
    +  var PR_innerHtmlWorks = null;
    +  function getInnerHtml(node) {
    +    // inner html is hopelessly broken in Safari 2.0.4 when the content is
    +    // an html description of well formed XML and the containing tag is a PRE
    +    // tag, so we detect that case and emulate innerHTML.
    +    if (null === PR_innerHtmlWorks) {
    +      var testNode = document.createElement('PRE');
    +      testNode.appendChild(
    +          document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));
    +      PR_innerHtmlWorks = !/</.test(testNode.innerHTML);
    +    }
    +
    +    if (PR_innerHtmlWorks) {
    +      var content = node.innerHTML;
    +      // XMP tags contain unescaped entities so require special handling.
    +      if (isRawContent(node)) {
    +        content = textToHtml(content);
    +      } else if (!isPreformatted(node, content)) {
    +        content = content.replace(/(<br\s*\/?>)[\r\n]+/g, '$1')
    +            .replace(/(?:[\r\n]+[ \t]*)+/g, ' ');
    +      }
    +      return content;
    +    }
    +
    +    var out = [];
    +    for (var child = node.firstChild; child; child = child.nextSibling) {
    +      normalizedHtml(child, out);
    +    }
    +    return out.join('');
    +  }
    +
    +  /** returns a function that expand tabs to spaces.  This function can be fed
    +    * successive chunks of text, and will maintain its own internal state to
    +    * keep track of how tabs are expanded.
    +    * @return {function (string) : string} a function that takes
    +    *   plain text and return the text with tabs expanded.
    +    * @private
    +    */
    +  function makeTabExpander(tabWidth) {
    +    var SPACES = '                ';
    +    var charInLine = 0;
    +
    +    return function (plainText) {
    +      // walk over each character looking for tabs and newlines.
    +      // On tabs, expand them.  On newlines, reset charInLine.
    +      // Otherwise increment charInLine
    +      var out = null;
    +      var pos = 0;
    +      for (var i = 0, n = plainText.length; i < n; ++i) {
    +        var ch = plainText.charAt(i);
    +
    +        switch (ch) {
    +          case '\t':
    +            if (!out) { out = []; }
    +            out.push(plainText.substring(pos, i));
    +            // calculate how much space we need in front of this part
    +            // nSpaces is the amount of padding -- the number of spaces needed
    +            // to move us to the next column, where columns occur at factors of
    +            // tabWidth.
    +            var nSpaces = tabWidth - (charInLine % tabWidth);
    +            charInLine += nSpaces;
    +            for (; nSpaces >= 0; nSpaces -= SPACES.length) {
    +              out.push(SPACES.substring(0, nSpaces));
    +            }
    +            pos = i + 1;
    +            break;
    +          case '\n':
    +            charInLine = 0;
    +            break;
    +          default:
    +            ++charInLine;
    +        }
    +      }
    +      if (!out) { return plainText; }
    +      out.push(plainText.substring(pos));
    +      return out.join('');
    +    };
    +  }
    +
    +  var pr_chunkPattern = new RegExp(
    +      '[^<]+'  // A run of characters other than '<'
    +      + '|<\!--[\\s\\S]*?--\>'  // an HTML comment
    +      + '|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>'  // a CDATA section
    +      // a probable tag that should not be highlighted
    +      + '|<\/?[a-zA-Z](?:[^>\"\']|\'[^\']*\'|\"[^\"]*\")*>'
    +      + '|<',  // A '<' that does not begin a larger chunk
    +      'g');
    +  var pr_commentPrefix = /^<\!--/;
    +  var pr_cdataPrefix = /^<!\[CDATA\[/;
    +  var pr_brPrefix = /^<br\b/i;
    +  var pr_tagNameRe = /^<(\/?)([a-zA-Z][a-zA-Z0-9]*)/;
    +
    +  /** split markup into chunks of html tags (style null) and
    +    * plain text (style {@link #PR_PLAIN}), converting tags which are
    +    * significant for tokenization (<br>) into their textual equivalent.
    +    *
    +    * @param {string} s html where whitespace is considered significant.
    +    * @return {Object} source code and extracted tags.
    +    * @private
    +    */
    +  function extractTags(s) {
    +    // since the pattern has the 'g' modifier and defines no capturing groups,
    +    // this will return a list of all chunks which we then classify and wrap as
    +    // PR_Tokens
    +    var matches = s.match(pr_chunkPattern);
    +    var sourceBuf = [];
    +    var sourceBufLen = 0;
    +    var extractedTags = [];
    +    if (matches) {
    +      for (var i = 0, n = matches.length; i < n; ++i) {
    +        var match = matches[i];
    +        if (match.length > 1 && match.charAt(0) === '<') {
    +          if (pr_commentPrefix.test(match)) { continue; }
    +          if (pr_cdataPrefix.test(match)) {
    +            // strip CDATA prefix and suffix.  Don't unescape since it's CDATA
    +            sourceBuf.push(match.substring(9, match.length - 3));
    +            sourceBufLen += match.length - 12;
    +          } else if (pr_brPrefix.test(match)) {
    +            // <br> tags are lexically significant so convert them to text.
    +            // This is undone later.
    +            sourceBuf.push('\n');
    +            ++sourceBufLen;
    +          } else {
    +            if (match.indexOf(PR_NOCODE) >= 0 && isNoCodeTag(match)) {
    +              // A <span class="nocode"> will start a section that should be
    +              // ignored.  Continue walking the list until we see a matching end
    +              // tag.
    +              var name = match.match(pr_tagNameRe)[2];
    +              var depth = 1;
    +              var j;
    +              end_tag_loop:
    +              for (j = i + 1; j < n; ++j) {
    +                var name2 = matches[j].match(pr_tagNameRe);
    +                if (name2 && name2[2] === name) {
    +                  if (name2[1] === '/') {
    +                    if (--depth === 0) { break end_tag_loop; }
    +                  } else {
    +                    ++depth;
    +                  }
    +                }
    +              }
    +              if (j < n) {
    +                extractedTags.push(
    +                    sourceBufLen, matches.slice(i, j + 1).join(''));
    +                i = j;
    +              } else {  // Ignore unclosed sections.
    +                extractedTags.push(sourceBufLen, match);
    +              }
    +            } else {
    +              extractedTags.push(sourceBufLen, match);
    +            }
    +          }
    +        } else {
    +          var literalText = htmlToText(match);
    +          sourceBuf.push(literalText);
    +          sourceBufLen += literalText.length;
    +        }
    +      }
    +    }
    +    return { source: sourceBuf.join(''), tags: extractedTags };
    +  }
    +
    +  /** True if the given tag contains a class attribute with the nocode class. */
    +  function isNoCodeTag(tag) {
    +    return !!tag
    +        // First canonicalize the representation of attributes
    +        .replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g,
    +                 ' $1="$2$3$4"')
    +        // Then look for the attribute we want.
    +        .match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/);
    +  }
    +
    +  /**
    +   * Apply the given language handler to sourceCode and add the resulting
    +   * decorations to out.
    +   * @param {number} basePos the index of sourceCode within the chunk of source
    +   *    whose decorations are already present on out.
    +   */
    +  function appendDecorations(basePos, sourceCode, langHandler, out) {
    +    if (!sourceCode) { return; }
    +    var job = {
    +      source: sourceCode,
    +      basePos: basePos
    +    };
    +    langHandler(job);
    +    out.push.apply(out, job.decorations);
    +  }
    +
    +  /** Given triples of [style, pattern, context] returns a lexing function,
    +    * The lexing function interprets the patterns to find token boundaries and
    +    * returns a decoration list of the form
    +    * [index_0, style_0, index_1, style_1, ..., index_n, style_n]
    +    * where index_n is an index into the sourceCode, and style_n is a style
    +    * constant like PR_PLAIN.  index_n-1 <= index_n, and style_n-1 applies to
    +    * all characters in sourceCode[index_n-1:index_n].
    +    *
    +    * The stylePatterns is a list whose elements have the form
    +    * [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
    +    *
    +    * Style is a style constant like PR_PLAIN, or can be a string of the
    +    * form 'lang-FOO', where FOO is a language extension describing the
    +    * language of the portion of the token in $1 after pattern executes.
    +    * E.g., if style is 'lang-lisp', and group 1 contains the text
    +    * '(hello (world))', then that portion of the token will be passed to the
    +    * registered lisp handler for formatting.
    +    * The text before and after group 1 will be restyled using this decorator
    +    * so decorators should take care that this doesn't result in infinite
    +    * recursion.  For example, the HTML lexer rule for SCRIPT elements looks
    +    * something like ['lang-js', /<[s]cript>(.+?)<\/script>/].  This may match
    +    * '<script>foo()<\/script>', which would cause the current decorator to
    +    * be called with '<script>' which would not match the same rule since
    +    * group 1 must not be empty, so it would be instead styled as PR_TAG by
    +    * the generic tag rule.  The handler registered for the 'js' extension would
    +    * then be called with 'foo()', and finally, the current decorator would
    +    * be called with '<\/script>' which would not match the original rule and
    +    * so the generic tag rule would identify it as a tag.
    +    *
    +    * Pattern must only match prefixes, and if it matches a prefix, then that
    +    * match is considered a token with the same style.
    +    *
    +    * Context is applied to the last non-whitespace, non-comment token
    +    * recognized.
    +    *
    +    * Shortcut is an optional string of characters, any of which, if the first
    +    * character, gurantee that this pattern and only this pattern matches.
    +    *
    +    * @param {Array} shortcutStylePatterns patterns that always start with
    +    *   a known character.  Must have a shortcut string.
    +    * @param {Array} fallthroughStylePatterns patterns that will be tried in
    +    *   order if the shortcut ones fail.  May have shortcuts.
    +    *
    +    * @return {function (Object)} a
    +    *   function that takes source code and returns a list of decorations.
    +    */
    +  function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
    +    var shortcuts = {};
    +    var tokenizer;
    +    (function () {
    +      var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
    +      var allRegexs = [];
    +      var regexKeys = {};
    +      for (var i = 0, n = allPatterns.length; i < n; ++i) {
    +        var patternParts = allPatterns[i];
    +        var shortcutChars = patternParts[3];
    +        if (shortcutChars) {
    +          for (var c = shortcutChars.length; --c >= 0;) {
    +            shortcuts[shortcutChars.charAt(c)] = patternParts;
    +          }
    +        }
    +        var regex = patternParts[1];
    +        var k = '' + regex;
    +        if (!regexKeys.hasOwnProperty(k)) {
    +          allRegexs.push(regex);
    +          regexKeys[k] = null;
    +        }
    +      }
    +      allRegexs.push(/[\0-\uffff]/);
    +      tokenizer = combinePrefixPatterns(allRegexs);
    +    })();
    +
    +    var nPatterns = fallthroughStylePatterns.length;
    +    var notWs = /\S/;
    +
    +    /**
    +     * Lexes job.source and produces an output array job.decorations of style
    +     * classes preceded by the position at which they start in job.source in
    +     * order.
    +     *
    +     * @param {Object} job an object like {@code
    +     *    source: {string} sourceText plain text,
    +     *    basePos: {int} position of job.source in the larger chunk of
    +     *        sourceCode.
    +     * }
    +     */
    +    var decorate = function (job) {
    +      var sourceCode = job.source, basePos = job.basePos;
    +      /** Even entries are positions in source in ascending order.  Odd enties
    +        * are style markers (e.g., PR_COMMENT) that run from that position until
    +        * the end.
    +        * @type {Array.<number|string>}
    +        */
    +      var decorations = [basePos, PR_PLAIN];
    +      var pos = 0;  // index into sourceCode
    +      var tokens = sourceCode.match(tokenizer) || [];
    +      var styleCache = {};
    +
    +      for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
    +        var token = tokens[ti];
    +        var style = styleCache[token];
    +        var match = void 0;
    +
    +        var isEmbedded;
    +        if (typeof style === 'string') {
    +          isEmbedded = false;
    +        } else {
    +          var patternParts = shortcuts[token.charAt(0)];
    +          if (patternParts) {
    +            match = token.match(patternParts[1]);
    +            style = patternParts[0];
    +          } else {
    +            for (var i = 0; i < nPatterns; ++i) {
    +              patternParts = fallthroughStylePatterns[i];
    +              match = token.match(patternParts[1]);
    +              if (match) {
    +                style = patternParts[0];
    +                break;
    +              }
    +            }
    +
    +            if (!match) {  // make sure that we make progress
    +              style = PR_PLAIN;
    +            }
    +          }
    +
    +          isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
    +          if (isEmbedded && !(match && typeof match[1] === 'string')) {
    +            isEmbedded = false;
    +            style = PR_SOURCE;
    +          }
    +
    +          if (!isEmbedded) { styleCache[token] = style; }
    +        }
    +
    +        var tokenStart = pos;
    +        pos += token.length;
    +
    +        if (!isEmbedded) {
    +          decorations.push(basePos + tokenStart, style);
    +        } else {  // Treat group 1 as an embedded block of source code.
    +          var embeddedSource = match[1];
    +          var embeddedSourceStart = token.indexOf(embeddedSource);
    +          var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
    +          if (match[2]) {
    +            // If embeddedSource can be blank, then it would match at the
    +            // beginning which would cause us to infinitely recurse on the
    +            // entire token, so we catch the right context in match[2].
    +            embeddedSourceEnd = token.length - match[2].length;
    +            embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
    +          }
    +          var lang = style.substring(5);
    +          // Decorate the left of the embedded source
    +          appendDecorations(
    +              basePos + tokenStart,
    +              token.substring(0, embeddedSourceStart),
    +              decorate, decorations);
    +          // Decorate the embedded source
    +          appendDecorations(
    +              basePos + tokenStart + embeddedSourceStart,
    +              embeddedSource,
    +              langHandlerForExtension(lang, embeddedSource),
    +              decorations);
    +          // Decorate the right of the embedded section
    +          appendDecorations(
    +              basePos + tokenStart + embeddedSourceEnd,
    +              token.substring(embeddedSourceEnd),
    +              decorate, decorations);
    +        }
    +      }
    +      job.decorations = decorations;
    +    };
    +    return decorate;
    +  }
    +
    +  /** returns a function that produces a list of decorations from source text.
    +    *
    +    * This code treats ", ', and ` as string delimiters, and \ as a string
    +    * escape.  It does not recognize perl's qq() style strings.
    +    * It has no special handling for double delimiter escapes as in basic, or
    +    * the tripled delimiters used in python, but should work on those regardless
    +    * although in those cases a single string literal may be broken up into
    +    * multiple adjacent string literals.
    +    *
    +    * It recognizes C, C++, and shell style comments.
    +    *
    +    * @param {Object} options a set of optional parameters.
    +    * @return {function (Object)} a function that examines the source code
    +    *     in the input job and builds the decoration list.
    +    */
    +  function sourceDecorator(options) {
    +    var shortcutStylePatterns = [], fallthroughStylePatterns = [];
    +    if (options['tripleQuotedStrings']) {
    +      // '''multi-line-string''', 'single-line-string', and double-quoted
    +      shortcutStylePatterns.push(
    +          [PR_STRING,  /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
    +           null, '\'"']);
    +    } else if (options['multiLineStrings']) {
    +      // 'multi-line-string', "multi-line-string"
    +      shortcutStylePatterns.push(
    +          [PR_STRING,  /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
    +           null, '\'"`']);
    +    } else {
    +      // 'single-line-string', "single-line-string"
    +      shortcutStylePatterns.push(
    +          [PR_STRING,
    +           /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
    +           null, '"\'']);
    +    }
    +    if (options['verbatimStrings']) {
    +      // verbatim-string-literal production from the C# grammar.  See issue 93.
    +      fallthroughStylePatterns.push(
    +          [PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
    +    }
    +    if (options['hashComments']) {
    +      if (options['cStyleComments']) {
    +        // Stop C preprocessor declarations at an unclosed open comment
    +        shortcutStylePatterns.push(
    +            [PR_COMMENT, /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,
    +             null, '#']);
    +        fallthroughStylePatterns.push(
    +            [PR_STRING,
    +             /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,
    +             null]);
    +      } else {
    +        shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
    +      }
    +    }
    +    if (options['cStyleComments']) {
    +      fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
    +      fallthroughStylePatterns.push(
    +          [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
    +    }
    +    if (options['regexLiterals']) {
    +      var REGEX_LITERAL = (
    +          // A regular expression literal starts with a slash that is
    +          // not followed by * or / so that it is not confused with
    +          // comments.
    +          '/(?=[^/*])'
    +          // and then contains any number of raw characters,
    +          + '(?:[^/\\x5B\\x5C]'
    +          // escape sequences (\x5C),
    +          +    '|\\x5C[\\s\\S]'
    +          // or non-nesting character sets (\x5B\x5D);
    +          +    '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+'
    +          // finally closed by a /.
    +          + '/');
    +      fallthroughStylePatterns.push(
    +          ['lang-regex',
    +           new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
    +           ]);
    +    }
    +
    +    var keywords = options['keywords'].replace(/^\s+|\s+$/g, '');
    +    if (keywords.length) {
    +      fallthroughStylePatterns.push(
    +          [PR_KEYWORD,
    +           new RegExp('^(?:' + keywords.replace(/\s+/g, '|') + ')\\b'), null]);
    +    }
    +
    +    shortcutStylePatterns.push([PR_PLAIN,       /^\s+/, null, ' \r\n\t\xA0']);
    +    fallthroughStylePatterns.push(
    +        // TODO(mikesamuel): recognize non-latin letters and numerals in idents
    +        [PR_LITERAL,     /^@[a-z_$][a-z_$@0-9]*/i, null],
    +        [PR_TYPE,        /^@?[A-Z]+[a-z][A-Za-z_$@0-9]*/, null],
    +        [PR_PLAIN,       /^[a-z_$][a-z_$@0-9]*/i, null],
    +        [PR_LITERAL,
    +         new RegExp(
    +             '^(?:'
    +             // A hex number
    +             + '0x[a-f0-9]+'
    +             // or an octal or decimal number,
    +             + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
    +             // possibly in scientific notation
    +             + '(?:e[+\\-]?\\d+)?'
    +             + ')'
    +             // with an optional modifier like UL for unsigned long
    +             + '[a-z]*', 'i'),
    +         null, '0123456789'],
    +        [PR_PUNCTUATION, /^.[^\s\w\.$@\'\"\`\/\#]*/, null]);
    +
    +    return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
    +  }
    +
    +  var decorateSource = sourceDecorator({
    +        'keywords': ALL_KEYWORDS,
    +        'hashComments': true,
    +        'cStyleComments': true,
    +        'multiLineStrings': true,
    +        'regexLiterals': true
    +      });
    +
    +  /** Breaks {@code job.source} around style boundaries in
    +    * {@code job.decorations} while re-interleaving {@code job.extractedTags},
    +    * and leaves the result in {@code job.prettyPrintedHtml}.
    +    * @param {Object} job like {
    +    *    source: {string} source as plain text,
    +    *    extractedTags: {Array.<number|string>} extractedTags chunks of raw
    +    *                   html preceded by their position in {@code job.source}
    +    *                   in order
    +    *    decorations: {Array.<number|string} an array of style classes preceded
    +    *                 by the position at which they start in job.source in order
    +    * }
    +    * @private
    +    */
    +  function recombineTagsAndDecorations(job) {
    +    var sourceText = job.source;
    +    var extractedTags = job.extractedTags;
    +    var decorations = job.decorations;
    +
    +    var html = [];
    +    // index past the last char in sourceText written to html
    +    var outputIdx = 0;
    +
    +    var openDecoration = null;
    +    var currentDecoration = null;
    +    var tagPos = 0;  // index into extractedTags
    +    var decPos = 0;  // index into decorations
    +    var tabExpander = makeTabExpander(window['PR_TAB_WIDTH']);
    +
    +    var adjacentSpaceRe = /([\r\n ]) /g;
    +    var startOrSpaceRe = /(^| ) /gm;
    +    var newlineRe = /\r\n?|\n/g;
    +    var trailingSpaceRe = /[ \r\n]$/;
    +    var lastWasSpace = true;  // the last text chunk emitted ended with a space.
    +
    +    // A helper function that is responsible for opening sections of decoration
    +    // and outputing properly escaped chunks of source
    +    function emitTextUpTo(sourceIdx) {
    +      if (sourceIdx > outputIdx) {
    +        if (openDecoration && openDecoration !== currentDecoration) {
    +          // Close the current decoration
    +          html.push('</span>');
    +          openDecoration = null;
    +        }
    +        if (!openDecoration && currentDecoration) {
    +          openDecoration = currentDecoration;
    +          html.push('<span class="', openDecoration, '">');
    +        }
    +        // This interacts badly with some wikis which introduces paragraph tags
    +        // into pre blocks for some strange reason.
    +        // It's necessary for IE though which seems to lose the preformattedness
    +        // of <pre> tags when their innerHTML is assigned.
    +        // http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html
    +        // and it serves to undo the conversion of <br>s to newlines done in
    +        // chunkify.
    +        var htmlChunk = textToHtml(
    +            tabExpander(sourceText.substring(outputIdx, sourceIdx)))
    +            .replace(lastWasSpace
    +                     ? startOrSpaceRe
    +                     : adjacentSpaceRe, '$1&nbsp;');
    +        // Keep track of whether we need to escape space at the beginning of the
    +        // next chunk.
    +        lastWasSpace = trailingSpaceRe.test(htmlChunk);
    +        // IE collapses multiple adjacient <br>s into 1 line break.
    +        // Prefix every <br> with '&nbsp;' can prevent such IE's behavior.
    +        var lineBreakHtml = window['_pr_isIE6']() ? '&nbsp;<br />' : '<br />';
    +        html.push(htmlChunk.replace(newlineRe, lineBreakHtml));
    +        outputIdx = sourceIdx;
    +      }
    +    }
    +
    +    while (true) {
    +      // Determine if we're going to consume a tag this time around.  Otherwise
    +      // we consume a decoration or exit.
    +      var outputTag;
    +      if (tagPos < extractedTags.length) {
    +        if (decPos < decorations.length) {
    +          // Pick one giving preference to extractedTags since we shouldn't open
    +          // a new style that we're going to have to immediately close in order
    +          // to output a tag.
    +          outputTag = extractedTags[tagPos] <= decorations[decPos];
    +        } else {
    +          outputTag = true;
    +        }
    +      } else {
    +        outputTag = false;
    +      }
    +      // Consume either a decoration or a tag or exit.
    +      if (outputTag) {
    +        emitTextUpTo(extractedTags[tagPos]);
    +        if (openDecoration) {
    +          // Close the current decoration
    +          html.push('</span>');
    +          openDecoration = null;
    +        }
    +        html.push(extractedTags[tagPos + 1]);
    +        tagPos += 2;
    +      } else if (decPos < decorations.length) {
    +        emitTextUpTo(decorations[decPos]);
    +        currentDecoration = decorations[decPos + 1];
    +        decPos += 2;
    +      } else {
    +        break;
    +      }
    +    }
    +    emitTextUpTo(sourceText.length);
    +    if (openDecoration) {
    +      html.push('</span>');
    +    }
    +    job.prettyPrintedHtml = html.join('');
    +  }
    +
    +  /** Maps language-specific file extensions to handlers. */
    +  var langHandlerRegistry = {};
    +  /** Register a language handler for the given file extensions.
    +    * @param {function (Object)} handler a function from source code to a list
    +    *      of decorations.  Takes a single argument job which describes the
    +    *      state of the computation.   The single parameter has the form
    +    *      {@code {
    +    *        source: {string} as plain text.
    +    *        decorations: {Array.<number|string>} an array of style classes
    +    *                     preceded by the position at which they start in
    +    *                     job.source in order.
    +    *                     The language handler should assigned this field.
    +    *        basePos: {int} the position of source in the larger source chunk.
    +    *                 All positions in the output decorations array are relative
    +    *                 to the larger source chunk.
    +    *      } }
    +    * @param {Array.<string>} fileExtensions
    +    */
    +  function registerLangHandler(handler, fileExtensions) {
    +    for (var i = fileExtensions.length; --i >= 0;) {
    +      var ext = fileExtensions[i];
    +      if (!langHandlerRegistry.hasOwnProperty(ext)) {
    +        langHandlerRegistry[ext] = handler;
    +      } else if ('console' in window) {
    +        console.warn('cannot override language handler %s', ext);
    +      }
    +    }
    +  }
    +  function langHandlerForExtension(extension, source) {
    +    if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
    +      // Treat it as markup if the first non whitespace character is a < and
    +      // the last non-whitespace character is a >.
    +      extension = /^\s*</.test(source)
    +          ? 'default-markup'
    +          : 'default-code';
    +    }
    +    return langHandlerRegistry[extension];
    +  }
    +  registerLangHandler(decorateSource, ['default-code']);
    +  registerLangHandler(
    +      createSimpleLexer(
    +          [],
    +          [
    +           [PR_PLAIN,       /^[^<?]+/],
    +           [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
    +           [PR_COMMENT,     /^<\!--[\s\S]*?(?:-\->|$)/],
    +           // Unescaped content in an unknown language
    +           ['lang-',        /^<\?([\s\S]+?)(?:\?>|$)/],
    +           ['lang-',        /^<%([\s\S]+?)(?:%>|$)/],
    +           [PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
    +           ['lang-',        /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
    +           // Unescaped content in javascript.  (Or possibly vbscript).
    +           ['lang-js',      /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
    +           // Contains unescaped stylesheet content
    +           ['lang-css',     /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
    +           ['lang-in.tag',  /^(<\/?[a-z][^<>]*>)/i]
    +          ]),
    +      ['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
    +  registerLangHandler(
    +      createSimpleLexer(
    +          [
    +           [PR_PLAIN,        /^[\s]+/, null, ' \t\r\n'],
    +           [PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
    +           ],
    +          [
    +           [PR_TAG,          /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
    +           [PR_ATTRIB_NAME,  /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
    +           ['lang-uq.val',   /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
    +           [PR_PUNCTUATION,  /^[=<>\/]+/],
    +           ['lang-js',       /^on\w+\s*=\s*\"([^\"]+)\"/i],
    +           ['lang-js',       /^on\w+\s*=\s*\'([^\']+)\'/i],
    +           ['lang-js',       /^on\w+\s*=\s*([^\"\'>\s]+)/i],
    +           ['lang-css',      /^style\s*=\s*\"([^\"]+)\"/i],
    +           ['lang-css',      /^style\s*=\s*\'([^\']+)\'/i],
    +           ['lang-css',      /^style\s*=\s*([^\"\'>\s]+)/i]
    +           ]),
    +      ['in.tag']);
    +  registerLangHandler(
    +      createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
    +  registerLangHandler(sourceDecorator({
    +          'keywords': CPP_KEYWORDS,
    +          'hashComments': true,
    +          'cStyleComments': true
    +        }), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
    +  registerLangHandler(sourceDecorator({
    +          'keywords': 'null true false'
    +        }), ['json']);
    +  registerLangHandler(sourceDecorator({
    +          'keywords': CSHARP_KEYWORDS,
    +          'hashComments': true,
    +          'cStyleComments': true,
    +          'verbatimStrings': true
    +        }), ['cs']);
    +  registerLangHandler(sourceDecorator({
    +          'keywords': JAVA_KEYWORDS,
    +          'cStyleComments': true
    +        }), ['java']);
    +  registerLangHandler(sourceDecorator({
    +          'keywords': SH_KEYWORDS,
    +          'hashComments': true,
    +          'multiLineStrings': true
    +        }), ['bsh', 'csh', 'sh']);
    +  registerLangHandler(sourceDecorator({
    +          'keywords': PYTHON_KEYWORDS,
    +          'hashComments': true,
    +          'multiLineStrings': true,
    +          'tripleQuotedStrings': true
    +        }), ['cv', 'py']);
    +  registerLangHandler(sourceDecorator({
    +          'keywords': PERL_KEYWORDS,
    +          'hashComments': true,
    +          'multiLineStrings': true,
    +          'regexLiterals': true
    +        }), ['perl', 'pl', 'pm']);
    +  registerLangHandler(sourceDecorator({
    +          'keywords': RUBY_KEYWORDS,
    +          'hashComments': true,
    +          'multiLineStrings': true,
    +          'regexLiterals': true
    +        }), ['rb']);
    +  registerLangHandler(sourceDecorator({
    +          'keywords': JSCRIPT_KEYWORDS,
    +          'cStyleComments': true,
    +          'regexLiterals': true
    +        }), ['js']);
    +  registerLangHandler(
    +      createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
    +
    +  function applyDecorator(job) {
    +    var sourceCodeHtml = job.sourceCodeHtml;
    +    var opt_langExtension = job.langExtension;
    +
    +    // Prepopulate output in case processing fails with an exception.
    +    job.prettyPrintedHtml = sourceCodeHtml;
    +
    +    try {
    +      // Extract tags, and convert the source code to plain text.
    +      var sourceAndExtractedTags = extractTags(sourceCodeHtml);
    +      /** Plain text. @type {string} */
    +      var source = sourceAndExtractedTags.source;
    +      job.source = source;
    +      job.basePos = 0;
    +
    +      /** Even entries are positions in source in ascending order.  Odd entries
    +        * are tags that were extracted at that position.
    +        * @type {Array.<number|string>}
    +        */
    +      job.extractedTags = sourceAndExtractedTags.tags;
    +
    +      // Apply the appropriate language handler
    +      langHandlerForExtension(opt_langExtension, source)(job);
    +      // Integrate the decorations and tags back into the source code to produce
    +      // a decorated html string which is left in job.prettyPrintedHtml.
    +      recombineTagsAndDecorations(job);
    +    } catch (e) {
    +      if ('console' in window) {
    +        console.log(e);
    +        console.trace();
    +      }
    +    }
    +  }
    +
    +  function prettyPrintOne(sourceCodeHtml, opt_langExtension) {
    +    var job = {
    +      sourceCodeHtml: sourceCodeHtml,
    +      langExtension: opt_langExtension
    +    };
    +    applyDecorator(job);
    +    return job.prettyPrintedHtml;
    +  }
    +
    +  function prettyPrint(opt_whenDone) {
    +    var isIE678 = window['_pr_isIE6']();
    +    var ieNewline = isIE678 === 6 ? '\r\n' : '\r';
    +    // See bug 71 and http://stackoverflow.com/questions/136443/why-doesnt-ie7-
    +
    +    // fetch a list of nodes to rewrite
    +    var codeSegments = [
    +        document.getElementsByTagName('pre'),
    +        document.getElementsByTagName('code'),
    +        document.getElementsByTagName('td'),  /* ND Change: Add tables to support prototypes. */
    +        document.getElementsByTagName('xmp') ];
    +    var elements = [];
    +    for (var i = 0; i < codeSegments.length; ++i) {
    +      for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
    +        elements.push(codeSegments[i][j]);
    +      }
    +    }
    +    codeSegments = null;
    +
    +    var clock = Date;
    +    if (!clock['now']) {
    +      clock = { 'now': function () { return (new Date).getTime(); } };
    +    }
    +
    +    // The loop is broken into a series of continuations to make sure that we
    +    // don't make the browser unresponsive when rewriting a large page.
    +    var k = 0;
    +    var prettyPrintingJob;
    +
    +    function doWork() {
    +      var endTime = (window['PR_SHOULD_USE_CONTINUATION'] ?
    +                     clock.now() + 250 /* ms */ :
    +                     Infinity);
    +      for (; k < elements.length && clock.now() < endTime; k++) {
    +        var cs = elements[k];
    +        if (cs.className && cs.className.indexOf('prettyprint') >= 0) {
    +          // If the classes includes a language extensions, use it.
    +          // Language extensions can be specified like
    +          //     <pre class="prettyprint lang-cpp">
    +          // the language extension "cpp" is used to find a language handler as
    +          // passed to PR_registerLangHandler.
    +          var langExtension = cs.className.match(/\blang-(\w+)\b/);
    +          if (langExtension) { langExtension = langExtension[1]; }
    +
    +          // make sure this is not nested in an already prettified element
    +          var nested = false;
    +          for (var p = cs.parentNode; p; p = p.parentNode) {
    +            if ((p.tagName === 'pre' || p.tagName === 'code' ||
    +                 p.tagName === 'xmp' || p.tagName === 'td') &&  /* ND Change: Add tables to support prototypes */
    +                p.className && p.className.indexOf('prettyprint') >= 0) {
    +              nested = true;
    +              break;
    +            }
    +          }
    +          if (!nested) {
    +            // fetch the content as a snippet of properly escaped HTML.
    +            // Firefox adds newlines at the end.
    +            var content = getInnerHtml(cs);
    +            content = content.replace(/(?:\r\n?|\n)$/, '');
    +
    +	  		/* ND Change: we need to preserve &nbsp;s so change them to a special character instead of a space. */
    +			content = content.replace(/&nbsp;/g, '\x11');
    +
    +            // do the pretty printing
    +            prettyPrintingJob = {
    +              sourceCodeHtml: content,
    +              langExtension: langExtension,
    +              sourceNode: cs
    +            };
    +            applyDecorator(prettyPrintingJob);
    +            replaceWithPrettyPrintedHtml();
    +          }
    +        }
    +      }
    +      if (k < elements.length) {
    +        // finish up in a continuation
    +        setTimeout(doWork, 250);
    +      } else if (opt_whenDone) {
    +        opt_whenDone();
    +      }
    +    }
    +
    +    function replaceWithPrettyPrintedHtml() {
    +      var newContent = prettyPrintingJob.prettyPrintedHtml;
    +      if (!newContent) { return; }
    +
    +      /* ND Change: Restore the preserved &nbsp;s.  */
    +	  newContent = newContent.replace(/\x11/g, '&nbsp;');
    +
    +      var cs = prettyPrintingJob.sourceNode;
    +
    +      // push the prettified html back into the tag.
    +      if (!isRawContent(cs)) {
    +        // just replace the old html with the new
    +        cs.innerHTML = newContent;
    +      } else {
    +        // we need to change the tag to a <pre> since <xmp>s do not allow
    +        // embedded tags such as the span tags used to attach styles to
    +        // sections of source code.
    +        var pre = document.createElement('PRE');
    +        for (var i = 0; i < cs.attributes.length; ++i) {
    +          var a = cs.attributes[i];
    +          if (a.specified) {
    +            var aname = a.name.toLowerCase();
    +            if (aname === 'class') {
    +              pre.className = a.value;  // For IE 6
    +            } else {
    +              pre.setAttribute(a.name, a.value);
    +            }
    +          }
    +        }
    +        pre.innerHTML = newContent;
    +
    +        // remove the old
    +        cs.parentNode.replaceChild(pre, cs);
    +        cs = pre;
    +      }
    +
    +      // Replace <br>s with line-feeds so that copying and pasting works
    +      // on IE 6.
    +      // Doing this on other browsers breaks lots of stuff since \r\n is
    +      // treated as two newlines on Firefox, and doing this also slows
    +      // down rendering.
    +      if (isIE678 && cs.tagName === 'PRE') {
    +        var lineBreaks = cs.getElementsByTagName('br');
    +        for (var j = lineBreaks.length; --j >= 0;) {
    +          var lineBreak = lineBreaks[j];
    +          lineBreak.parentNode.replaceChild(
    +              document.createTextNode(ieNewline), lineBreak);
    +        }
    +      }
    +    }
    +
    +    doWork();
    +  }
    +
    +  window['PR_normalizedHtml'] = normalizedHtml;
    +  window['prettyPrintOne'] = prettyPrintOne;
    +  window['prettyPrint'] = prettyPrint;
    +  window['PR'] = {
    +        'combinePrefixPatterns': combinePrefixPatterns,
    +        'createSimpleLexer': createSimpleLexer,
    +        'registerLangHandler': registerLangHandler,
    +        'sourceDecorator': sourceDecorator,
    +        'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
    +        'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
    +        'PR_COMMENT': PR_COMMENT,
    +        'PR_DECLARATION': PR_DECLARATION,
    +        'PR_KEYWORD': PR_KEYWORD,
    +        'PR_LITERAL': PR_LITERAL,
    +        'PR_NOCODE': PR_NOCODE,
    +        'PR_PLAIN': PR_PLAIN,
    +        'PR_PUNCTUATION': PR_PUNCTUATION,
    +        'PR_SOURCE': PR_SOURCE,
    +        'PR_STRING': PR_STRING,
    +        'PR_TAG': PR_TAG,
    +        'PR_TYPE': PR_TYPE
    +      };
    +})();
    +
    +
    +// ____________________________________________________________________________
    +
    +
    +
    +// Lua extension
    +
    +PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[\t\n\r \xA0]+/,null,'	\n\r \xa0'],[PR.PR_STRING,/^(?:\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)|\'(?:[^\'\\]|\\[\s\S])*(?:\'|$))/,null,'\"\'']],[[PR.PR_COMMENT,/^--(?:\[(=*)\[[\s\S]*?(?:\]\1\]|$)|[^\r\n]*)/],[PR.PR_STRING,/^\[(=*)\[[\s\S]*?(?:\]\1\]|$)/],[PR.PR_KEYWORD,/^(?:and|break|do|else|elseif|end|false|for|function|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/,null],[PR.PR_LITERAL,/^[+-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i],[PR.PR_PLAIN,/^[a-z_]\w*/i],[PR.PR_PUNCTUATION,/^[^\w\t\n\r \xA0][^\w\t\n\r \xA0\"\'\-\+=]*/]]),['lua'])
    +
    +
    +// Haskell extension
    +
    +PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[\t\n\x0B\x0C\r ]+/,null,'	\n\r '],[PR.PR_STRING,/^\"(?:[^\"\\\n\x0C\r]|\\[\s\S])*(?:\"|$)/,null,'\"'],[PR.PR_STRING,/^\'(?:[^\'\\\n\x0C\r]|\\[^&])\'?/,null,'\''],[PR.PR_LITERAL,/^(?:0o[0-7]+|0x[\da-f]+|\d+(?:\.\d+)?(?:e[+\-]?\d+)?)/i,null,'0123456789']],[[PR.PR_COMMENT,/^(?:(?:--+(?:[^\r\n\x0C]*)?)|(?:\{-(?:[^-]|-+[^-\}])*-\}))/],[PR.PR_KEYWORD,/^(?:case|class|data|default|deriving|do|else|if|import|in|infix|infixl|infixr|instance|let|module|newtype|of|then|type|where|_)(?=[^a-zA-Z0-9\']|$)/,null],[PR.PR_PLAIN,/^(?:[A-Z][\w\']*\.)*[a-zA-Z][\w\']*/],[PR.PR_PUNCTUATION,/^[^\t\n\x0B\x0C\r a-zA-Z0-9\'\"]+/]]),['hs'])
    +
    +
    +// ML extension
    +
    +PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[\t\n\r \xA0]+/,null,'	\n\r \xa0'],[PR.PR_COMMENT,/^#(?:if[\t\n\r \xA0]+(?:[a-z_$][\w\']*|``[^\r\n\t`]*(?:``|$))|else|endif|light)/i,null,'#'],[PR.PR_STRING,/^(?:\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)|\'(?:[^\'\\]|\\[\s\S])*(?:\'|$))/,null,'\"\'']],[[PR.PR_COMMENT,/^(?:\/\/[^\r\n]*|\(\*[\s\S]*?\*\))/],[PR.PR_KEYWORD,/^(?:abstract|and|as|assert|begin|class|default|delegate|do|done|downcast|downto|elif|else|end|exception|extern|false|finally|for|fun|function|if|in|inherit|inline|interface|internal|lazy|let|match|member|module|mutable|namespace|new|null|of|open|or|override|private|public|rec|return|static|struct|then|to|true|try|type|upcast|use|val|void|when|while|with|yield|asr|land|lor|lsl|lsr|lxor|mod|sig|atomic|break|checked|component|const|constraint|constructor|continue|eager|event|external|fixed|functor|global|include|method|mixin|object|parallel|process|protected|pure|sealed|trait|virtual|volatile)\b/],[PR.PR_LITERAL,/^[+\-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i],[PR.PR_PLAIN,/^(?:[a-z_]\w*[!?#]?|``[^\r\n\t`]*(?:``|$))/i],[PR.PR_PUNCTUATION,/^[^\t\n\r \xA0\"\'\w]+/]]),['fs','ml'])
    +
    +
    +// SQL extension
    +
    +PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[\t\n\r \xA0]+/,null,'	\n\r \xa0'],[PR.PR_STRING,/^(?:"(?:[^\"\\]|\\.)*"|'(?:[^\'\\]|\\.)*')/,null,'\"\'']],[[PR.PR_COMMENT,/^(?:--[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$))/],[PR.PR_KEYWORD,/^(?:ADD|ALL|ALTER|AND|ANY|AS|ASC|AUTHORIZATION|BACKUP|BEGIN|BETWEEN|BREAK|BROWSE|BULK|BY|CASCADE|CASE|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COMMIT|COMPUTE|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATABASE|DBCC|DEALLOCATE|DECLARE|DEFAULT|DELETE|DENY|DESC|DISK|DISTINCT|DISTRIBUTED|DOUBLE|DROP|DUMMY|DUMP|ELSE|END|ERRLVL|ESCAPE|EXCEPT|EXEC|EXECUTE|EXISTS|EXIT|FETCH|FILE|FILLFACTOR|FOR|FOREIGN|FREETEXT|FREETEXTTABLE|FROM|FULL|FUNCTION|GOTO|GRANT|GROUP|HAVING|HOLDLOCK|IDENTITY|IDENTITYCOL|IDENTITY_INSERT|IF|IN|INDEX|INNER|INSERT|INTERSECT|INTO|IS|JOIN|KEY|KILL|LEFT|LIKE|LINENO|LOAD|NATIONAL|NOCHECK|NONCLUSTERED|NOT|NULL|NULLIF|OF|OFF|OFFSETS|ON|OPEN|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPENXML|OPTION|OR|ORDER|OUTER|OVER|PERCENT|PLAN|PRECISION|PRIMARY|PRINT|PROC|PROCEDURE|PUBLIC|RAISERROR|READ|READTEXT|RECONFIGURE|REFERENCES|REPLICATION|RESTORE|RESTRICT|RETURN|REVOKE|RIGHT|ROLLBACK|ROWCOUNT|ROWGUIDCOL|RULE|SAVE|SCHEMA|SELECT|SESSION_USER|SET|SETUSER|SHUTDOWN|SOME|STATISTICS|SYSTEM_USER|TABLE|TEXTSIZE|THEN|TO|TOP|TRAN|TRANSACTION|TRIGGER|TRUNCATE|TSEQUAL|UNION|UNIQUE|UPDATE|UPDATETEXT|USE|USER|VALUES|VARYING|VIEW|WAITFOR|WHEN|WHERE|WHILE|WITH|WRITETEXT)(?=[^\w-]|$)/i,null],[PR.PR_LITERAL,/^[+-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i],[PR.PR_PLAIN,/^[a-z_][\w-]*/i],[PR.PR_PUNCTUATION,/^[^\w\t\n\r \xA0\"\'][^\w\t\n\r \xA0+\-\"\']*/]]),['sql'])
    +
    +
    +// VB extension
    +
    +PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[\t\n\r \xA0\u2028\u2029]+/,null,'	\n\r \xa0\u2028\u2029'],[PR.PR_STRING,/^(?:[\"\u201C\u201D](?:[^\"\u201C\u201D]|[\"\u201C\u201D]{2})(?:[\"\u201C\u201D]c|$)|[\"\u201C\u201D](?:[^\"\u201C\u201D]|[\"\u201C\u201D]{2})*(?:[\"\u201C\u201D]|$))/i,null,'\"\u201c\u201d'],[PR.PR_COMMENT,/^[\'\u2018\u2019][^\r\n\u2028\u2029]*/,null,'\'\u2018\u2019']],[[PR.PR_KEYWORD,/^(?:AddHandler|AddressOf|Alias|And|AndAlso|Ansi|As|Assembly|Auto|Boolean|ByRef|Byte|ByVal|Call|Case|Catch|CBool|CByte|CChar|CDate|CDbl|CDec|Char|CInt|Class|CLng|CObj|Const|CShort|CSng|CStr|CType|Date|Decimal|Declare|Default|Delegate|Dim|DirectCast|Do|Double|Each|Else|ElseIf|End|EndIf|Enum|Erase|Error|Event|Exit|Finally|For|Friend|Function|Get|GetType|GoSub|GoTo|Handles|If|Implements|Imports|In|Inherits|Integer|Interface|Is|Let|Lib|Like|Long|Loop|Me|Mod|Module|MustInherit|MustOverride|MyBase|MyClass|Namespace|New|Next|Not|NotInheritable|NotOverridable|Object|On|Option|Optional|Or|OrElse|Overloads|Overridable|Overrides|ParamArray|Preserve|Private|Property|Protected|Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler|Resume|Return|Select|Set|Shadows|Shared|Short|Single|Static|Step|Stop|String|Structure|Sub|SyncLock|Then|Throw|To|Try|TypeOf|Unicode|Until|Variant|Wend|When|While|With|WithEvents|WriteOnly|Xor|EndIf|GoSub|Let|Variant|Wend)\b/i,null],[PR.PR_COMMENT,/^REM[^\r\n\u2028\u2029]*/i],[PR.PR_LITERAL,/^(?:True\b|False\b|Nothing\b|\d+(?:E[+\-]?\d+[FRD]?|[FRDSIL])?|(?:&H[0-9A-F]+|&O[0-7]+)[SIL]?|\d*\.\d+(?:E[+\-]?\d+)?[FRD]?|#\s+(?:\d+[\-\/]\d+[\-\/]\d+(?:\s+\d+:\d+(?::\d+)?(\s*(?:AM|PM))?)?|\d+:\d+(?::\d+)?(\s*(?:AM|PM))?)\s+#)/i],[PR.PR_PLAIN,/^(?:(?:[a-z]|_\w)\w*|\[(?:[a-z]|_\w)\w*\])/i],[PR.PR_PUNCTUATION,/^[^\w\t\n\r \"\'\[\]\xA0\u2018\u2019\u201C\u201D\u2028\u2029]+/],[PR.PR_PUNCTUATION,/^(?:\[|\])/]]),['vb','vbs'])
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/javascript/searchdata.js b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/javascript/searchdata.js
    new file mode 100644
    index 00000000..229a815f
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/javascript/searchdata.js
    @@ -0,0 +1,122 @@
    +var indexSectionsWithContent = {
    +   "General": {
    +      "Symbols": false,
    +      "Numbers": false,
    +      "A": true,
    +      "B": false,
    +      "C": true,
    +      "D": false,
    +      "E": false,
    +      "F": true,
    +      "G": true,
    +      "H": false,
    +      "I": true,
    +      "J": false,
    +      "K": false,
    +      "L": true,
    +      "M": false,
    +      "N": false,
    +      "O": true,
    +      "P": false,
    +      "Q": false,
    +      "R": true,
    +      "S": false,
    +      "T": false,
    +      "U": true,
    +      "V": true,
    +      "W": false,
    +      "X": false,
    +      "Y": false,
    +      "Z": false
    +      },
    +   "Variables": {
    +      "Symbols": false,
    +      "Numbers": false,
    +      "A": false,
    +      "B": false,
    +      "C": true,
    +      "D": false,
    +      "E": false,
    +      "F": false,
    +      "G": false,
    +      "H": false,
    +      "I": true,
    +      "J": false,
    +      "K": false,
    +      "L": false,
    +      "M": false,
    +      "N": false,
    +      "O": false,
    +      "P": false,
    +      "Q": false,
    +      "R": true,
    +      "S": false,
    +      "T": false,
    +      "U": false,
    +      "V": false,
    +      "W": false,
    +      "X": false,
    +      "Y": false,
    +      "Z": false
    +      },
    +   "Functions": {
    +      "Symbols": false,
    +      "Numbers": false,
    +      "A": true,
    +      "B": false,
    +      "C": true,
    +      "D": false,
    +      "E": false,
    +      "F": true,
    +      "G": true,
    +      "H": false,
    +      "I": true,
    +      "J": false,
    +      "K": false,
    +      "L": true,
    +      "M": false,
    +      "N": false,
    +      "O": true,
    +      "P": false,
    +      "Q": false,
    +      "R": true,
    +      "S": false,
    +      "T": false,
    +      "U": true,
    +      "V": false,
    +      "W": false,
    +      "X": false,
    +      "Y": false,
    +      "Z": false
    +      },
    +   "Files": {
    +      "Symbols": false,
    +      "Numbers": false,
    +      "A": false,
    +      "B": false,
    +      "C": true,
    +      "D": false,
    +      "E": false,
    +      "F": false,
    +      "G": false,
    +      "H": false,
    +      "I": false,
    +      "J": false,
    +      "K": false,
    +      "L": false,
    +      "M": false,
    +      "N": false,
    +      "O": false,
    +      "P": false,
    +      "Q": false,
    +      "R": false,
    +      "S": false,
    +      "T": false,
    +      "U": false,
    +      "V": false,
    +      "W": false,
    +      "X": false,
    +      "Y": false,
    +      "Z": false
    +      }
    +   }
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FilesC.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FilesC.html
    new file mode 100644
    index 00000000..9b13d7ea
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FilesC.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_csrfprotector_perphp><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#csrfprotector.php" target=_parent class=ISymbol>csrfprotector.php</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsA.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsA.html
    new file mode 100644
    index 00000000..2a3a150e
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsA.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_authorisePost><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#authorisePost" target=_parent class=ISymbol>authorisePost</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsC.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsC.html
    new file mode 100644
    index 00000000..c02adb84
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsC.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_createNewJsCache><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#createNewJsCache" target=_parent class=ISymbol>createNewJsCache</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsF.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsF.html
    new file mode 100644
    index 00000000..88d09287
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsF.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_failedValidationAction><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#failedValidationAction" target=_parent class=ISymbol>failedValidationAction</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsG.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsG.html
    new file mode 100644
    index 00000000..4c9b125a
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsG.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_generateAuthToken><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#generateAuthToken" target=_parent class=ISymbol>generateAuthToken</a></div></div><div class=SRResult id=SR_getCurrentUrl><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#getCurrentUrl" target=_parent class=ISymbol>getCurrentUrl</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsI.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsI.html
    new file mode 100644
    index 00000000..9dc7a592
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsI.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_init><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#init" target=_parent class=ISymbol>init</a></div></div><div class=SRResult id=SR_isURLallowed><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#isURLallowed" target=_parent class=ISymbol>isURLallowed</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsL.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsL.html
    new file mode 100644
    index 00000000..c2cbb504
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsL.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_logCSRFattack><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#logCSRFattack" target=_parent class=ISymbol>logCSRFattack</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsO.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsO.html
    new file mode 100644
    index 00000000..0c67005f
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsO.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_ob_undhandler><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#ob_handler" target=_parent class=ISymbol>ob_handler</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsR.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsR.html
    new file mode 100644
    index 00000000..c25cffe0
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsR.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_refreshToken><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#refreshToken" target=_parent class=ISymbol>refreshToken</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsU.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsU.html
    new file mode 100644
    index 00000000..a43aa753
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/FunctionsU.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_useCachedVersion><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#useCachedVersion" target=_parent class=ISymbol>useCachedVersion</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralA.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralA.html
    new file mode 100644
    index 00000000..2a3a150e
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralA.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_authorisePost><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#authorisePost" target=_parent class=ISymbol>authorisePost</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralC.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralC.html
    new file mode 100644
    index 00000000..edb09c50
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralC.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_config><div class=IEntry><span class=ISymbolPrefix>$</span><a href="../files/libs/csrf/csrfprotector-php.html#$config" target=_parent class=ISymbol>config</a></div></div><div class=SRResult id=SR_cookieExpiryTime><div class=IEntry><span class=ISymbolPrefix>$</span><a href="../files/libs/csrf/csrfprotector-php.html#$cookieExpiryTime" target=_parent class=ISymbol>cookieExpiryTime</a></div></div><div class=SRResult id=SR_createNewJsCache><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#createNewJsCache" target=_parent class=ISymbol>createNewJsCache</a></div></div><div class=SRResult id=SR_csrfprotector_perphp><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#csrfprotector.php" target=_parent class=ISymbol>csrfprotector.php</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralF.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralF.html
    new file mode 100644
    index 00000000..b624d11b
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralF.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_failedValidationAction><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#failedValidationAction" target=_parent class=ISymbol>failedValidationAction</a></div></div><div class=SRResult id=SR_Functions><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#Functions" target=_parent class=ISymbol>Functions</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralG.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralG.html
    new file mode 100644
    index 00000000..4c9b125a
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralG.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_generateAuthToken><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#generateAuthToken" target=_parent class=ISymbol>generateAuthToken</a></div></div><div class=SRResult id=SR_getCurrentUrl><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#getCurrentUrl" target=_parent class=ISymbol>getCurrentUrl</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralI.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralI.html
    new file mode 100644
    index 00000000..0bdb7a47
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralI.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_init><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#init" target=_parent class=ISymbol>init</a></div></div><div class=SRResult id=SR_isSameOrigin><div class=IEntry><span class=ISymbolPrefix>$</span><a href="../files/libs/csrf/csrfprotector-php.html#$isSameOrigin" target=_parent class=ISymbol>isSameOrigin</a></div></div><div class=SRResult id=SR_isURLallowed><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#isURLallowed" target=_parent class=ISymbol>isURLallowed</a></div></div><div class=SRResult id=SR_isValidHTML><div class=IEntry><span class=ISymbolPrefix>$</span><a href="../files/libs/csrf/csrfprotector-php.html#$isValidHTML" target=_parent class=ISymbol>isValidHTML</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralL.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralL.html
    new file mode 100644
    index 00000000..c2cbb504
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralL.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_logCSRFattack><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#logCSRFattack" target=_parent class=ISymbol>logCSRFattack</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralO.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralO.html
    new file mode 100644
    index 00000000..0c67005f
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralO.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_ob_undhandler><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#ob_handler" target=_parent class=ISymbol>ob_handler</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralR.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralR.html
    new file mode 100644
    index 00000000..e6d917c1
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralR.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_refreshToken><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#refreshToken" target=_parent class=ISymbol>refreshToken</a></div></div><div class=SRResult id=SR_requestType><div class=IEntry><span class=ISymbolPrefix>$</span><a href="../files/libs/csrf/csrfprotector-php.html#$requestType" target=_parent class=ISymbol>requestType</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralU.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralU.html
    new file mode 100644
    index 00000000..a43aa753
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralU.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_useCachedVersion><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#useCachedVersion" target=_parent class=ISymbol>useCachedVersion</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralV.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralV.html
    new file mode 100644
    index 00000000..ce09ee7c
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/GeneralV.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_Variables><div class=IEntry><a href="../files/libs/csrf/csrfprotector-php.html#Variables" target=_parent class=ISymbol>Variables</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/NoResults.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/NoResults.html
    new file mode 100644
    index 00000000..8c724966
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/NoResults.html
    @@ -0,0 +1,15 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=NoMatches>No Matches</div></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/VariablesC.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/VariablesC.html
    new file mode 100644
    index 00000000..8b8dc9dc
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/VariablesC.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_config><div class=IEntry><span class=ISymbolPrefix>$</span><a href="../files/libs/csrf/csrfprotector-php.html#$config" target=_parent class=ISymbol>config</a></div></div><div class=SRResult id=SR_cookieExpiryTime><div class=IEntry><span class=ISymbolPrefix>$</span><a href="../files/libs/csrf/csrfprotector-php.html#$cookieExpiryTime" target=_parent class=ISymbol>cookieExpiryTime</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/VariablesI.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/VariablesI.html
    new file mode 100644
    index 00000000..a32aac1d
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/VariablesI.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_isSameOrigin><div class=IEntry><span class=ISymbolPrefix>$</span><a href="../files/libs/csrf/csrfprotector-php.html#$isSameOrigin" target=_parent class=ISymbol>isSameOrigin</a></div></div><div class=SRResult id=SR_isValidHTML><div class=IEntry><span class=ISymbolPrefix>$</span><a href="../files/libs/csrf/csrfprotector-php.html#$isValidHTML" target=_parent class=ISymbol>isValidHTML</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/VariablesR.html b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/VariablesR.html
    new file mode 100644
    index 00000000..3a06b30e
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/search/VariablesR.html
    @@ -0,0 +1,20 @@
    +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
    +
    +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!--
    +if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
    +
    +<!--  Generated by Natural Docs, version 1.52 -->
    +<!--  http://www.naturaldocs.org  -->
    +
    +<!-- saved from url=(0026)http://www.naturaldocs.org -->
    +
    +
    +
    +
    +<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_requestType><div class=IEntry><span class=ISymbolPrefix>$</span><a href="../files/libs/csrf/csrfprotector-php.html#$requestType" target=_parent class=ISymbol>requestType</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
    +document.getElementById("Loading").style.display="none";
    +document.getElementById("NoMatches").style.display="none";
    +var searchResults = new SearchResults("searchResults", "HTML");
    +searchResults.Search();
    +--></script></div><script language=JavaScript><!--
    +if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/styles/main.css b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/styles/main.css
    new file mode 100644
    index 00000000..1832d8f3
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/docs/styles/main.css
    @@ -0,0 +1,824 @@
    +/*
    +   IMPORTANT: If you're editing this file in the output directory of one of
    +   your projects, your changes will be overwritten the next time you run
    +   Natural Docs.  Instead, copy this file to your project directory, make your
    +   changes, and you can use it with -s.  Even better would be to make a CSS
    +   file in your project directory with only your changes, which you can then
    +   use with -s [original style] [your changes].
    +
    +   On the other hand, if you're editing this file in the Natural Docs styles
    +   directory, the changes will automatically be applied to all your projects
    +   that use this style the next time Natural Docs is run on them.
    +
    +   This file is part of Natural Docs, which is Copyright  2003-2010 Greg Valure.
    +   Natural Docs is licensed under version 3 of the GNU Affero General Public
    +   License (AGPL).  Refer to License.txt for the complete details.
    +
    +   This file may be distributed with documentation files generated by Natural Docs.
    +   Such documentation is not covered by Natural Docs' copyright and licensing,
    +   and may have its own copyright and distribution terms as decided by its author.
    +*/
    +
    +body {
    +    font: 8pt Verdana, Arial, sans-serif;
    +    color: #000000;
    +    margin: 0; padding: 0;
    +    }
    +
    +.ContentPage,
    +.IndexPage,
    +.FramedMenuPage {
    +    background-color: #E8E8E8;
    +    }
    +.FramedContentPage,
    +.FramedIndexPage,
    +.FramedSearchResultsPage,
    +.PopupSearchResultsPage {
    +    background-color: #FFFFFF;
    +    }
    +
    +
    +a:link,
    +a:visited { color: #900000; text-decoration: none }
    +a:hover { color: #900000; text-decoration: underline }
    +a:active { color: #FF0000; text-decoration: underline }
    +
    +td {
    +    vertical-align: top }
    +
    +img { border: 0;  }
    +
    +
    +/*
    +    Comment out this line to use web-style paragraphs (blank line between
    +    paragraphs, no indent) instead of print-style paragraphs (no blank line,
    +    indented.)
    +*/
    +p {
    +    text-indent: 5ex; margin: 0 }
    +
    +
    +/*  Opera doesn't break with just wbr, but will if you add this.  */
    +.Opera wbr:after {
    +	content: "\00200B";
    +	}
    +
    +/*  Blockquotes are used as containers for things that may need to scroll.  */
    +blockquote {
    +    padding: 0;
    +    margin: 0;
    +    overflow: auto;
    +    }
    +
    +
    +.Firefox1 blockquote {
    +    padding-bottom: .5em;
    +    }
    +
    +/*  Turn off scrolling when printing.  */
    +@media print {
    +    blockquote {
    +        overflow: visible;
    +        }
    +    .IE blockquote {
    +        width: auto;
    +        }
    +    }
    +
    +
    +
    +#Menu {
    +    font-size: 8pt;
    +    padding: 10px 0 0 0;
    +    }
    +.ContentPage #Menu,
    +.IndexPage #Menu {
    +    position: absolute;
    +    top: 0;
    +    left: 0;
    +    width: 31ex;
    +    overflow: hidden;
    +    }
    +.ContentPage .Firefox #Menu,
    +.IndexPage .Firefox #Menu {
    +    width: 27ex;
    +    }
    +
    +
    +    .MTitle {
    +        font-size: 16pt; font-weight: bold; font-variant: small-caps;
    +        text-align: center;
    +        padding: 5px 10px 15px 10px;
    +        border-bottom: 1px dotted #000000;
    +        margin-bottom: 15px }
    +
    +    .MSubTitle {
    +        font-size: 9pt; font-weight: normal; font-variant: normal;
    +        margin-top: 1ex; margin-bottom: 5px }
    +
    +
    +    .MEntry a:link,
    +    .MEntry a:hover,
    +    .MEntry a:visited { color: #606060; margin-right: 0 }
    +    .MEntry a:active { color: #A00000; margin-right: 0 }
    +
    +
    +    .MGroup {
    +        font-variant: small-caps; font-weight: bold;
    +        margin: 1em 0 1em 10px;
    +        }
    +
    +    .MGroupContent {
    +        font-variant: normal; font-weight: normal }
    +
    +    .MGroup a:link,
    +    .MGroup a:hover,
    +    .MGroup a:visited { color: #545454; margin-right: 10px }
    +    .MGroup a:active { color: #A00000; margin-right: 10px }
    +
    +
    +    .MFile,
    +    .MText,
    +    .MLink,
    +    .MIndex {
    +        padding: 1px 17px 2px 10px;
    +        margin: .25em 0 .25em 0;
    +        }
    +
    +    .MText {
    +        font-size: 8pt; font-style: italic }
    +
    +    .MLink {
    +        font-style: italic }
    +
    +    #MSelected {
    +        color: #000000; background-color: #FFFFFF;
    +        /*  Replace padding with border.  */
    +        padding: 0 10px 0 10px;
    +        border-width: 1px 2px 2px 0; border-style: solid; border-color: #000000;
    +        margin-right: 5px;
    +        }
    +
    +    /*  Close off the left side when its in a group.  */
    +    .MGroup #MSelected {
    +        padding-left: 9px; border-left-width: 1px }
    +
    +    /*  A treat for Mozilla users.  Blatantly non-standard.  Will be replaced with CSS 3 attributes when finalized/supported.  */
    +    .Firefox #MSelected {
    +        -moz-border-radius-topright: 10px;
    +        -moz-border-radius-bottomright: 10px }
    +    .Firefox .MGroup #MSelected {
    +        -moz-border-radius-topleft: 10px;
    +        -moz-border-radius-bottomleft: 10px }
    +
    +
    +    #MSearchPanel {
    +        padding: 0px 6px;
    +        margin: .25em 0;
    +        }
    +
    +
    +    #MSearchField {
    +        font: italic 8pt Verdana, sans-serif;
    +        color: #606060;
    +        background-color: #E8E8E8;
    +        border: none;
    +        padding: 2px 4px;
    +        width: 100%;
    +        }
    +    /* Only Opera gets it right. */
    +    .Firefox #MSearchField,
    +    .IE #MSearchField,
    +    .Safari #MSearchField {
    +        width: 94%;
    +        }
    +    .Opera9 #MSearchField,
    +    .Konqueror #MSearchField {
    +        width: 97%;
    +        }
    +    .FramedMenuPage .Firefox #MSearchField,
    +    .FramedMenuPage .Safari #MSearchField,
    +    .FramedMenuPage .Konqueror #MSearchField {
    +        width: 98%;
    +        }
    +
    +    /* Firefox doesn't do this right in frames without #MSearchPanel added on.
    +        It's presence doesn't hurt anything other browsers. */
    +    #MSearchPanel.MSearchPanelInactive:hover #MSearchField {
    +        background-color: #FFFFFF;
    +        border: 1px solid #C0C0C0;
    +        padding: 1px 3px;
    +        }
    +    .MSearchPanelActive #MSearchField {
    +        background-color: #FFFFFF;
    +        border: 1px solid #C0C0C0;
    +        font-style: normal;
    +        padding: 1px 3px;
    +        }
    +
    +    #MSearchType {
    +        visibility: hidden;
    +        font: 8pt Verdana, sans-serif;
    +        width: 98%;
    +        padding: 0;
    +        border: 1px solid #C0C0C0;
    +        }
    +    .MSearchPanelActive #MSearchType,
    +    /*  As mentioned above, Firefox doesn't do this right in frames without #MSearchPanel added on. */
    +    #MSearchPanel.MSearchPanelInactive:hover #MSearchType,
    +    #MSearchType:focus {
    +        visibility: visible;
    +        color: #606060;
    +        }
    +    #MSearchType option#MSearchEverything {
    +        font-weight: bold;
    +        }
    +
    +    .Opera8 .MSearchPanelInactive:hover,
    +    .Opera8 .MSearchPanelActive {
    +        margin-left: -1px;
    +        }
    +
    +
    +    iframe#MSearchResults {
    +        width: 60ex;
    +        height: 15em;
    +        }
    +    #MSearchResultsWindow {
    +        display: none;
    +        position: absolute;
    +        left: 0; top: 0;
    +        border: 1px solid #000000;
    +        background-color: #E8E8E8;
    +        }
    +    #MSearchResultsWindowClose {
    +        font-weight: bold;
    +        font-size: 8pt;
    +        display: block;
    +        padding: 2px 5px;
    +        }
    +    #MSearchResultsWindowClose:link,
    +    #MSearchResultsWindowClose:visited {
    +        color: #000000;
    +        text-decoration: none;
    +        }
    +    #MSearchResultsWindowClose:active,
    +    #MSearchResultsWindowClose:hover {
    +        color: #800000;
    +        text-decoration: none;
    +        background-color: #F4F4F4;
    +        }
    +
    +
    +
    +
    +#Content {
    +    padding-bottom: 15px;
    +    }
    +
    +.ContentPage #Content {
    +    border-width: 0 0 1px 1px;
    +    border-style: solid;
    +    border-color: #000000;
    +    background-color: #FFFFFF;
    +    font-size: 8pt;  /* To make 31ex match the menu's 31ex. */
    +    margin-left: 31ex;
    +    }
    +.ContentPage .Firefox #Content {
    +    margin-left: 27ex;
    +    }
    +
    +
    +
    +    .CTopic {
    +        font-size: 8pt;
    +        margin-bottom: 3em;
    +        }
    +
    +
    +    .CTitle {
    +        font-size: 11pt; font-weight: bold;
    +        border-width: 0 0 1px 0; border-style: solid; border-color: #A0A0A0;
    +        margin: 0 15px .5em 15px }
    +
    +    .CGroup .CTitle {
    +        font-size: 16pt; font-variant: small-caps;
    +        padding-left: 15px; padding-right: 15px;
    +        border-width: 0 0 2px 0; border-color: #000000;
    +        margin-left: 0; margin-right: 0 }
    +
    +    .CClass .CTitle,
    +    .CInterface .CTitle,
    +    .CDatabase .CTitle,
    +    .CDatabaseTable .CTitle,
    +    .CSection .CTitle {
    +        font-size: 18pt;
    +        color: #FFFFFF; background-color: #A0A0A0;
    +        padding: 10px 15px 10px 15px;
    +        border-width: 2px 0; border-color: #000000;
    +        margin-left: 0; margin-right: 0 }
    +
    +    #MainTopic .CTitle {
    +        font-size: 20pt;
    +        color: #FFFFFF; background-color: #7070C0;
    +        padding: 10px 15px 10px 15px;
    +        border-width: 0 0 3px 0; border-color: #000000;
    +        margin-left: 0; margin-right: 0 }
    +
    +    .CBody {
    +        margin-left: 15px; margin-right: 15px }
    +
    +
    +    .CToolTip {
    +        position: absolute; visibility: hidden;
    +        left: 0; top: 0;
    +        background-color: #FFFFE0;
    +        padding: 5px;
    +        border-width: 1px 2px 2px 1px; border-style: solid; border-color: #000000;
    +        font-size: 8pt;
    +        }
    +
    +    .Opera .CToolTip {
    +        max-width: 98%;
    +        }
    +
    +    /*  Scrollbars would be useless.  */
    +    .CToolTip blockquote {
    +        overflow: hidden;
    +        }
    +    .IE6 .CToolTip blockquote {
    +        overflow: visible;
    +        }
    +
    +    .CHeading {
    +        font-weight: bold; font-size: 9pt;
    +        margin: 1.5em 0 .5em 0;
    +        }
    +
    +    .CBody pre {
    +        font: 8pt "Courier New", Courier, monospace;
    +	    background-color: #FCFCFC;
    +	    margin: 1em 35px;
    +	    padding: 10px 15px 10px 10px;
    +	    border-color: #E0E0E0 #E0E0E0 #E0E0E0 #E4E4E4;
    +	    border-width: 1px 1px 1px 6px;
    +	    border-style: dashed dashed dashed solid;
    +        }
    +
    +    .CBody ul {
    +        /*  I don't know why CBody's margin doesn't apply, but it's consistent across browsers so whatever.
    +             Reapply it here as padding.  */
    +        padding-left: 15px; padding-right: 15px;
    +        margin: .5em 5ex .5em 5ex;
    +        }
    +
    +    .CDescriptionList {
    +        margin: .5em 5ex 0 5ex }
    +
    +        .CDLEntry {
    +            font: 8pt "Courier New", Courier, monospace; color: #808080;
    +            padding-bottom: .25em;
    +            white-space: nowrap }
    +
    +        .CDLDescription {
    +            font-size: 8pt;  /*  For browsers that don't inherit correctly, like Opera 5.  */
    +            padding-bottom: .5em; padding-left: 5ex }
    +
    +
    +    .CTopic img {
    +        text-align: center;
    +        display: block;
    +        margin: 1em auto;
    +        }
    +    .CImageCaption {
    +        font-variant: small-caps;
    +        font-size: 8pt;
    +        color: #808080;
    +        text-align: center;
    +        position: relative;
    +        top: 1em;
    +        }
    +
    +    .CImageLink {
    +        color: #808080;
    +        font-style: italic;
    +        }
    +    a.CImageLink:link,
    +    a.CImageLink:visited,
    +    a.CImageLink:hover { color: #808080 }
    +
    +
    +
    +
    +
    +.Prototype {
    +    font: 8pt "Courier New", Courier, monospace;
    +    padding: 5px 3ex;
    +    border-width: 1px; border-style: solid;
    +    margin: 0 5ex 1.5em 5ex;
    +    }
    +
    +    .Prototype td {
    +        font-size: 8pt;
    +        }
    +
    +    .PDefaultValue,
    +    .PDefaultValuePrefix,
    +    .PTypePrefix {
    +        color: #8F8F8F;
    +        }
    +    .PTypePrefix {
    +        text-align: right;
    +        }
    +    .PAfterParameters {
    +        vertical-align: bottom;
    +        }
    +
    +    .IE .Prototype table {
    +        padding: 0;
    +        }
    +
    +    .CFunction .Prototype {
    +        background-color: #F4F4F4; border-color: #D0D0D0 }
    +    .CProperty .Prototype {
    +        background-color: #F4F4FF; border-color: #C0C0E8 }
    +    .CVariable .Prototype {
    +        background-color: #FFFFF0; border-color: #E0E0A0 }
    +
    +    .CClass .Prototype {
    +        border-width: 1px 2px 2px 1px; border-style: solid; border-color: #A0A0A0;
    +        background-color: #F4F4F4;
    +        }
    +    .CInterface .Prototype {
    +        border-width: 1px 2px 2px 1px; border-style: solid; border-color: #A0A0D0;
    +        background-color: #F4F4FF;
    +        }
    +
    +    .CDatabaseIndex .Prototype,
    +    .CConstant .Prototype {
    +        background-color: #D0D0D0; border-color: #000000 }
    +    .CType .Prototype,
    +    .CEnumeration .Prototype {
    +        background-color: #FAF0F0; border-color: #E0B0B0;
    +        }
    +    .CDatabaseTrigger .Prototype,
    +    .CEvent .Prototype,
    +    .CDelegate .Prototype {
    +        background-color: #F0FCF0; border-color: #B8E4B8 }
    +
    +    .CToolTip .Prototype {
    +        margin: 0 0 .5em 0;
    +        white-space: nowrap;
    +        }
    +
    +
    +
    +
    +
    +.Summary {
    +    margin: 1.5em 5ex 0 5ex }
    +
    +    .STitle {
    +        font-size: 11pt; font-weight: bold;
    +        margin-bottom: .5em }
    +
    +
    +    .SBorder {
    +        background-color: #FFFFF0;
    +        padding: 15px;
    +        border: 1px solid #C0C060 }
    +
    +    /* In a frame IE 6 will make them too long unless you set the width to 100%.  Without frames it will be correct without a width
    +        or slightly too long (but not enough to scroll) with a width.  This arbitrary weirdness simply astounds me.  IE 7 has the same
    +        problem with frames, haven't tested it without.  */
    +    .FramedContentPage .IE .SBorder {
    +        width: 100% }
    +
    +    /*  A treat for Mozilla users.  Blatantly non-standard.  Will be replaced with CSS 3 attributes when finalized/supported.  */
    +    .Firefox .SBorder {
    +        -moz-border-radius: 20px }
    +
    +
    +    .STable {
    +        font-size: 8pt; width: 100% }
    +
    +    .SEntry {
    +        width: 30% }
    +    .SDescription {
    +        width: 70% }
    +
    +
    +    .SMarked {
    +        background-color: #F8F8D8 }
    +
    +    .SDescription { padding-left: 2ex }
    +    .SIndent1 .SEntry { padding-left: 1.5ex }   .SIndent1 .SDescription { padding-left: 3.5ex }
    +    .SIndent2 .SEntry { padding-left: 3.0ex }   .SIndent2 .SDescription { padding-left: 5.0ex }
    +    .SIndent3 .SEntry { padding-left: 4.5ex }   .SIndent3 .SDescription { padding-left: 6.5ex }
    +    .SIndent4 .SEntry { padding-left: 6.0ex }   .SIndent4 .SDescription { padding-left: 8.0ex }
    +    .SIndent5 .SEntry { padding-left: 7.5ex }   .SIndent5 .SDescription { padding-left: 9.5ex }
    +
    +    .SDescription a { color: #800000}
    +    .SDescription a:active { color: #A00000 }
    +
    +    .SGroup td {
    +        padding-top: .5em; padding-bottom: .25em }
    +
    +    .SGroup .SEntry {
    +        font-weight: bold; font-variant: small-caps }
    +
    +    .SGroup .SEntry a { color: #800000 }
    +    .SGroup .SEntry a:active { color: #F00000 }
    +
    +
    +    .SMain td,
    +    .SClass td,
    +    .SDatabase td,
    +    .SDatabaseTable td,
    +    .SSection td {
    +        font-size: 10pt;
    +        padding-bottom: .25em }
    +
    +    .SClass td,
    +    .SDatabase td,
    +    .SDatabaseTable td,
    +    .SSection td {
    +        padding-top: 1em }
    +
    +    .SMain .SEntry,
    +    .SClass .SEntry,
    +    .SDatabase .SEntry,
    +    .SDatabaseTable .SEntry,
    +    .SSection .SEntry {
    +        font-weight: bold;
    +        }
    +
    +    .SMain .SEntry a,
    +    .SClass .SEntry a,
    +    .SDatabase .SEntry a,
    +    .SDatabaseTable .SEntry a,
    +    .SSection .SEntry a { color: #000000 }
    +
    +    .SMain .SEntry a:active,
    +    .SClass .SEntry a:active,
    +    .SDatabase .SEntry a:active,
    +    .SDatabaseTable .SEntry a:active,
    +    .SSection .SEntry a:active { color: #A00000 }
    +
    +
    +
    +
    +
    +.ClassHierarchy {
    +    margin: 0 15px 1em 15px }
    +
    +    .CHEntry {
    +        border-width: 1px 2px 2px 1px; border-style: solid; border-color: #A0A0A0;
    +        margin-bottom: 3px;
    +        padding: 2px 2ex;
    +        font-size: 8pt;
    +        background-color: #F4F4F4; color: #606060;
    +        }
    +
    +    .Firefox .CHEntry {
    +        -moz-border-radius: 4px;
    +        }
    +
    +    .CHCurrent .CHEntry {
    +        font-weight: bold;
    +        border-color: #000000;
    +        color: #000000;
    +        }
    +
    +    .CHChildNote .CHEntry {
    +        font-style: italic;
    +        font-size: 8pt;
    +        }
    +
    +    .CHIndent {
    +        margin-left: 3ex;
    +        }
    +
    +    .CHEntry a:link,
    +    .CHEntry a:visited,
    +    .CHEntry a:hover {
    +        color: #606060;
    +        }
    +    .CHEntry a:active {
    +        color: #800000;
    +        }
    +
    +
    +
    +
    +
    +#Index {
    +    background-color: #FFFFFF;
    +    }
    +
    +/*  As opposed to .PopupSearchResultsPage #Index  */
    +.IndexPage #Index,
    +.FramedIndexPage #Index,
    +.FramedSearchResultsPage #Index {
    +    padding: 15px;
    +    }
    +
    +.IndexPage #Index {
    +    border-width: 0 0 1px 1px;
    +    border-style: solid;
    +    border-color: #000000;
    +    font-size: 8pt;  /* To make 27ex match the menu's 27ex. */
    +    margin-left: 27ex;
    +    }
    +
    +
    +    .IPageTitle {
    +        font-size: 20pt; font-weight: bold;
    +        color: #FFFFFF; background-color: #7070C0;
    +        padding: 10px 15px 10px 15px;
    +        border-width: 0 0 3px 0; border-color: #000000; border-style: solid;
    +        margin: -15px -15px 0 -15px }
    +
    +    .FramedSearchResultsPage .IPageTitle {
    +        margin-bottom: 15px;
    +        }
    +
    +    .INavigationBar {
    +        text-align: center;
    +        background-color: #FFFFF0;
    +        padding: 5px;
    +        border-bottom: solid 1px black;
    +        margin: 0 -15px 15px -15px;
    +        }
    +
    +    .INavigationBar a {
    +        font-weight: bold }
    +
    +    .IHeading {
    +        font-size: 14pt; font-weight: bold;
    +        padding: 2.5em 0 .5em 0;
    +        text-align: center;
    +        width: 3.5ex;
    +        }
    +    #IFirstHeading {
    +        padding-top: 0;
    +        }
    +
    +    .IEntry {
    +        padding-left: 1ex;
    +        }
    +    .PopupSearchResultsPage .IEntry {
    +        font-size: 8pt;
    +        padding: 1px 5px;
    +        }
    +    .PopupSearchResultsPage .Opera9 .IEntry,
    +    .FramedSearchResultsPage .Opera9 .IEntry {
    +        text-align: left;
    +        }
    +    .FramedSearchResultsPage .IEntry {
    +        padding: 0;
    +        }
    +
    +    .ISubIndex {
    +        padding-left: 3ex; padding-bottom: .5em }
    +    .PopupSearchResultsPage .ISubIndex {
    +        display: none;
    +        }
    +
    +    /*  While it may cause some entries to look like links when they aren't, I found it's much easier to read the
    +         index if everything's the same color.  */
    +    .ISymbol {
    +        font-weight: bold; color: #900000  }
    +
    +    .IndexPage .ISymbolPrefix,
    +    .FramedIndexPage .ISymbolPrefix {
    +        text-align: right;
    +        color: #C47C7C;
    +        background-color: #F8F8F8;
    +        border-right: 3px solid #E0E0E0;
    +        border-left: 1px solid #E0E0E0;
    +        padding: 0 1px 0 2px;
    +        }
    +    .PopupSearchResultsPage .ISymbolPrefix,
    +    .FramedSearchResultsPage .ISymbolPrefix {
    +        color: #900000;
    +        }
    +    .PopupSearchResultsPage .ISymbolPrefix {
    +        font-size: 8pt;
    +        }
    +
    +    .IndexPage #IFirstSymbolPrefix,
    +    .FramedIndexPage #IFirstSymbolPrefix {
    +        border-top: 1px solid #E0E0E0;
    +        }
    +    .IndexPage #ILastSymbolPrefix,
    +    .FramedIndexPage #ILastSymbolPrefix {
    +        border-bottom: 1px solid #E0E0E0;
    +        }
    +    .IndexPage #IOnlySymbolPrefix,
    +    .FramedIndexPage #IOnlySymbolPrefix {
    +        border-top: 1px solid #E0E0E0;
    +        border-bottom: 1px solid #E0E0E0;
    +        }
    +
    +    a.IParent,
    +    a.IFile {
    +        display: block;
    +        }
    +
    +    .PopupSearchResultsPage .SRStatus {
    +        padding: 2px 5px;
    +        font-size: 8pt;
    +        font-style: italic;
    +        }
    +    .FramedSearchResultsPage .SRStatus {
    +        font-size: 8pt;
    +        font-style: italic;
    +        }
    +
    +    .SRResult {
    +        display: none;
    +        }
    +
    +
    +
    +#Footer {
    +    font-size: 8pt;
    +    color: #989898;
    +    text-align: right;
    +    }
    +
    +#Footer p {
    +    text-indent: 0;
    +    margin-bottom: .5em;
    +    }
    +
    +.ContentPage #Footer,
    +.IndexPage #Footer {
    +    text-align: right;
    +    margin: 2px;
    +    }
    +
    +.FramedMenuPage #Footer {
    +    text-align: center;
    +    margin: 5em 10px 10px 10px;
    +    padding-top: 1em;
    +    border-top: 1px solid #C8C8C8;
    +    }
    +
    +    #Footer a:link,
    +    #Footer a:hover,
    +    #Footer a:visited { color: #989898 }
    +    #Footer a:active { color: #A00000 }
    +
    +
    +
    +.prettyprint .kwd { color: #800000; }  /* keywords */
    +
    +    .prettyprint.PDefaultValue .kwd,
    +    .prettyprint.PDefaultValuePrefix .kwd,
    +    .prettyprint.PTypePrefix .kwd {
    +        color: #C88F8F;
    +        }
    +
    +.prettyprint .com { color: #008000; }  /* comments */
    +
    +    .prettyprint.PDefaultValue .com,
    +    .prettyprint.PDefaultValuePrefix .com,
    +    .prettyprint.PTypePrefix .com {
    +        color: #8FC88F;
    +        }
    +
    +.prettyprint .str { color: #0000B0; }  /* strings */
    +.prettyprint .lit { color: #0000B0; }  /* literals */
    +
    +    .prettyprint.PDefaultValue .str,
    +    .prettyprint.PDefaultValuePrefix .str,
    +    .prettyprint.PTypePrefix .str,
    +    .prettyprint.PDefaultValue .lit,
    +    .prettyprint.PDefaultValuePrefix .lit,
    +    .prettyprint.PTypePrefix .lit {
    +        color: #8F8FC0;
    +        }
    +
    +.prettyprint .typ { color: #000000; }  /* types */
    +.prettyprint .pun { color: #000000; }  /* punctuation */
    +.prettyprint .pln { color: #000000; }  /* punctuation */
    +
    +    .prettyprint.PDefaultValue .typ,
    +    .prettyprint.PDefaultValuePrefix .typ,
    +    .prettyprint.PTypePrefix .typ,
    +    .prettyprint.PDefaultValue .pun,
    +    .prettyprint.PDefaultValuePrefix .pun,
    +    .prettyprint.PTypePrefix .pun,
    +    .prettyprint.PDefaultValue .pln,
    +    .prettyprint.PDefaultValuePrefix .pln,
    +    .prettyprint.PTypePrefix .pln {
    +        color: #8F8F8F;
    +        }
    +
    +.prettyprint .tag { color: #008; }
    +.prettyprint .atn { color: #606; }
    +.prettyprint .atv { color: #080; }
    +.prettyprint .dec { color: #606; }
    +
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/js/README.md b/data/web/inc/lib/vendor/owasp/csrf-protector-php/js/README.md
    new file mode 100644
    index 00000000..9b9dbbc0
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/js/README.md
    @@ -0,0 +1,15 @@
    +Compatiblity with different browsers
    +===================================
    +**OS: `windows`**<br>
    +
    +
    + Cases               | IE (Win)   | Opera | Chrome | Mozilla | Safari 
    + ------------------  | ------- | ----- | ------ | ------- | ------ 
    + XHR wrapping        | ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)     | ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)      |     ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)   |    ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)     | ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)
    + HTML dom-0 wrapping |   ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)   |    ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)   |    ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)    |     ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)    | ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)
    + HTML dom-2 wrapping |   ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)    |    ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)   |   ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)     |      ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)   | ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png) 
    + URL rewriting       |   ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)   |   ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)    |     ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)   |    ![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)     |![yes](https://cdn3.iconfinder.com/data/icons/fatcow/32/accept.png)
    +
    +<pre>Note: Missing tick means, this has not yet been implemented or tested</pre>
    +
    +
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/js/csrfprotector.js b/data/web/inc/lib/vendor/owasp/csrf-protector-php/js/csrfprotector.js
    new file mode 100644
    index 00000000..aa548cb3
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/js/csrfprotector.js
    @@ -0,0 +1,366 @@
    +/** 
    + * =================================================================
    + * Javascript code for OWASP CSRF Protector
    + * Task it does: Fetch csrftoken from cookie, and attach it to every
    + * 		POST request
    + *		Allowed GET url
    + *			-- XHR
    + *			-- Static Forms
    + *			-- URLS (GET only)
    + *			-- dynamic forms
    + * =================================================================
    + */
    +
    +var CSRFP_FIELD_TOKEN_NAME = 'csrfp_hidden_data_token';
    +var CSRFP_FIELD_URLS = 'csrfp_hidden_data_urls';
    +
    +var CSRFP = {
    +	CSRFP_TOKEN: 'csrfp_token',
    +	/**
    +	 * Array of patterns of url, for which csrftoken need to be added
    +	 * In case of GET request also, provided from server
    +	 *
    +	 * @var string array
    +	 */
    +	checkForUrls: [],
    +	/**
    +	 * Function to check if a certain url is allowed to perform the request
    +	 * With or without csrf token
    +	 *
    +	 * @param: string, url
    +	 *
    +	 * @return: boolean, 	true if csrftoken is not needed
    +	 * 						false if csrftoken is needed
    +	 */
    +	_isValidGetRequest: function(url) {
    +		for (var i = 0; i < CSRFP.checkForUrls.length; i++) {
    +			var match = CSRFP.checkForUrls[i].exec(url);
    +			if (match !== null && match.length > 0) {
    +				return false;
    +			}
    +		}
    +		return true;
    +	},
    +	/** 
    +	 * function to get Auth key from cookie Andreturn it to requesting function
    +	 *
    +	 * @param: void
    +	 *
    +	 * @return: string, csrftoken retrieved from cookie
    +	 */
    +	_getAuthKey: function() {
    +		var re = new RegExp(CSRFP.CSRFP_TOKEN +"=([^;]+)(;|$)");
    +		var RegExpArray = re.exec(document.cookie);
    +		
    +		if (RegExpArray === null) {
    +			return false;
    +		}
    +		return RegExpArray[1];
    +	},
    +	/** 
    +	 * Function to get domain of any url
    +	 *
    +	 * @param: string, url
    +	 *
    +	 * @return: string, domain of url
    +	 */
    +	_getDomain: function(url) {
    +		if (url.indexOf("http://") !== 0 
    +			&& url.indexOf("https://") !== 0)
    +			return document.domain;
    +		return /http(s)?:\/\/([^\/]+)/.exec(url)[2];
    +	},
    +	/**
    +	 * Function to create and return a hidden input element
    +	 * For stroing the CSRFP_TOKEN
    +	 *
    +	 * @param void
    +	 *
    +	 * @return input element
    +	 */
    +	_getInputElt: function() {
    +		var hiddenObj = document.createElement("input");
    +		hiddenObj.setAttribute('name', CSRFP.CSRFP_TOKEN);
    +		hiddenObj.setAttribute('class', CSRFP.CSRFP_TOKEN);
    +		hiddenObj.type = 'hidden';
    +		hiddenObj.value = CSRFP._getAuthKey();
    +		return hiddenObj;
    +	},
    +	/**
    +	 * Returns absolute path for relative path
    +	 * 
    +	 * @param base, base url
    +	 * @param relative, relative url
    +	 *
    +	 * @return absolute path (string)
    +	 */
    +	_getAbsolutePath: function(base, relative) {
    +		var stack = base.split("/");
    +		var parts = relative.split("/");
    +		// remove current file name (or empty string)
    +		// (omit if "base" is the current folder without trailing slash)
    +		stack.pop(); 
    +			 
    +		for (var i = 0; i < parts.length; i++) {
    +			if (parts[i] == ".")
    +				continue;
    +			if (parts[i] == "..")
    +				stack.pop();
    +			else
    +				stack.push(parts[i]);
    +		}
    +		return stack.join("/");
    +	},
    +	/** 
    +	 * Remove jcsrfp-token run fun and then put them back 
    +	 *
    +	 * @param function
    +	 * @param reference form obj
    +	 *
    +	 * @retrun function
    +	 */
    +	_csrfpWrap: function(fun, obj) {
    +		return function(event) {
    +			// Remove CSRf token if exists
    +			if (typeof obj[CSRFP.CSRFP_TOKEN] !== 'undefined') {
    +				var target = obj[CSRFP.CSRFP_TOKEN];
    +				target.parentNode.removeChild(target);
    +			}
    +			
    +			// Trigger the functions
    +			var result = fun.apply(this, [event]);
    +			
    +			// Now append the csrfp_token back
    +			obj.appendChild(CSRFP._getInputElt());
    +			
    +			return result;
    +		};
    +	},
    +	/**
    +	 * Initialises the CSRFProtector js script
    +	 *
    +	 * @param void
    +	 *
    +	 * @return void
    +	 */
    +	_init: function() {
    +		CSRFP.CSRFP_TOKEN = document.getElementById(CSRFP_FIELD_TOKEN_NAME).value;
    +		try {
    +			CSRFP.checkForUrls = JSON.parse(document.getElementById(CSRFP_FIELD_URLS).value);
    +		} catch (err) {
    +			console.error(err);
    +			console.error('[ERROR] [CSRF Protector] unable to parse blacklisted url fields.');
    +		}
    +
    +		//convert these rules received from php lib to regex objects
    +		for (var i = 0; i < CSRFP.checkForUrls.length; i++) {
    +			CSRFP.checkForUrls[i] = CSRFP.checkForUrls[i].replace(/\*/g, '(.*)')
    +								.replace(/\//g, "\\/");
    +			CSRFP.checkForUrls[i] = new RegExp(CSRFP.checkForUrls[i]);
    +		}
    +	
    +	}
    +	
    +}; 
    +
    +//==========================================================
    +// Adding tokens, wrappers on window onload
    +//==========================================================
    +
    +function csrfprotector_init() {
    +	
    +	// Call the init funcion
    +	CSRFP._init();
    +
    +	// definition of basic FORM submit event handler to intercept the form request
    +	// and attach a CSRFP TOKEN if it's not already available
    +	var BasicSubmitInterceptor = function(event) {
    +		if (typeof event.target[CSRFP.CSRFP_TOKEN] === 'undefined') {
    +			event.target.appendChild(CSRFP._getInputElt());
    +		} else {
    +			//modify token to latest value
    +			event.target[CSRFP.CSRFP_TOKEN].value = CSRFP._getAuthKey();
    +		}
    +	}
    +
    +	//==================================================================
    +	// Adding csrftoken to request resulting from <form> submissions
    +	// Add for each POST, while for mentioned GET request
    +	// TODO - check for method
    +	//==================================================================
    +	// run time binding
    +	document.querySelector('body').addEventListener('submit', function(event) {
    +		if (event.target.tagName.toLowerCase() === 'form') {
    +			BasicSubmitInterceptor(event);
    +		};
    +	});
    +
    +	// intial binding
    +	// for(var i = 0; i < document.forms.length; i++) {
    +	// 	document.forms[i].addEventListener("submit", BasicSubmitInterceptor);
    +	// }
    +
    +	//==================================================================
    +	// Adding csrftoken to request resulting from direct form.submit() call
    +	// Add for each POST, while for mentioned GET request
    +	// TODO - check for form method
    +	//==================================================================
    +	HTMLFormElement.prototype.submit_ = HTMLFormElement.prototype.submit;
    +	HTMLFormElement.prototype.submit = function() {
    +		// check if the FORM already contains the token element
    +		if (!this.getElementsByClassName(CSRFP.CSRFP_TOKEN).length)
    +			this.appendChild(CSRFP._getInputElt());
    +		this.submit_();
    +	}
    +
    +
    +	/**
    +	 * Add wrapper for HTMLFormElements addEventListener so that any further 
    +	 * addEventListens won't have trouble with CSRF token
    +	 * todo - check for method
    +	 */
    +	HTMLFormElement.prototype.addEventListener_ = HTMLFormElement.prototype.addEventListener;
    +	HTMLFormElement.prototype.addEventListener = function(eventType, fun, bubble) {
    +		if (eventType === 'submit') {
    +			var wrapped = CSRFP._csrfpWrap(fun, this);
    +			this.addEventListener_(eventType, wrapped, bubble);
    +		} else {
    +			this.addEventListener_(eventType, fun, bubble);
    +		}	
    +	}
    +
    +	/**
    +	 * Add wrapper for IE's attachEvent
    +	 * todo - check for method
    +	 * todo - typeof is now obselete for IE 11, use some other method.
    +	 */
    +	if (typeof HTMLFormElement.prototype.attachEvent !== 'undefined') {
    +		HTMLFormElement.prototype.attachEvent_ = HTMLFormElement.prototype.attachEvent;
    +		HTMLFormElement.prototype.attachEvent = function(eventType, fun) {
    +			if (eventType === 'onsubmit') {
    +				var wrapped = CSRFP._csrfpWrap(fun, this);
    +				this.attachEvent_(eventType, wrapped);
    +			} else {
    +				this.attachEvent_(eventType, fun);
    +			}
    +		}
    +	}
    +
    +
    +	//==================================================================
    +	// Wrapper for XMLHttpRequest & ActiveXObject (for IE 6 & below)
    +	// Set X-No-CSRF to true before sending if request method is 
    +	//==================================================================
    +
    +	/** 
    +	 * Wrapper to XHR open method
    +	 * Add a property method to XMLHttpRequst class
    +	 * @param: all parameters to XHR open method
    +	 * @return: object returned by default, XHR open method
    +	 */
    +	function new_open(method, url, async, username, password) {
    +		this.method = method;
    +		var isAbsolute = (url.indexOf("./") === -1) ? true : false;
    +		if (!isAbsolute) {
    +			var base = location.protocol +'//' +location.host 
    +							+ location.pathname;
    +			url = CSRFP._getAbsolutePath(base, url);
    +		}
    +		if (method.toLowerCase() === 'get' 
    +			&& !CSRFP._isValidGetRequest(url)) {
    +			//modify the url
    +			if (url.indexOf('?') === -1) {
    +				url += "?" +CSRFP.CSRFP_TOKEN +"=" +CSRFP._getAuthKey();
    +			} else {
    +				url += "&" +CSRFP.CSRFP_TOKEN +"=" +CSRFP._getAuthKey();
    +			}
    +		}
    +
    +		return this.old_open(method, url, async, username, password);
    +	}
    +
    +	/** 
    +	 * Wrapper to XHR send method
    +	 * Add query paramter to XHR object
    +	 *
    +	 * @param: all parameters to XHR send method
    +	 *
    +	 * @return: object returned by default, XHR send method
    +	 */
    +	function new_send(data) {
    +		if (this.method.toLowerCase() === 'post') {
    +			if (data !== null && typeof data === 'object') {
    +				data.append(CSRFP.CSRFP_TOKEN, CSRFP._getAuthKey());
    +			} else {
    +				if (typeof data != "undefined") {
    +					data += "&";
    +				} else {
    +					data = "";
    +				}
    +				data += CSRFP.CSRFP_TOKEN +"=" +CSRFP._getAuthKey();
    +			}
    +		}
    +		return this.old_send(data);
    +	}
    +
    +	if (window.XMLHttpRequest) {
    +		// Wrapping
    +		XMLHttpRequest.prototype.old_send = XMLHttpRequest.prototype.send;
    +		XMLHttpRequest.prototype.old_open = XMLHttpRequest.prototype.open;
    +		XMLHttpRequest.prototype.open = new_open;
    +		XMLHttpRequest.prototype.send = new_send;
    +	}
    +	if (typeof ActiveXObject !== 'undefined') {
    +		ActiveXObject.prototype.old_send = ActiveXObject.prototype.send;
    +		ActiveXObject.prototype.old_open = ActiveXObject.prototype.open;
    +		ActiveXObject.prototype.open = new_open;
    +		ActiveXObject.prototype.send = new_send;	
    +	}
    +	//==================================================================
    +	// Rewrite existing urls ( Attach CSRF token )
    +	// Rules:
    +	// Rewrite those urls which matches the regex sent by Server
    +	// Ignore cross origin urls & internal links (one with hashtags)
    +	// Append the token to those url already containig GET query parameter(s)
    +	// Add the token to those which does not contain GET query parameter(s)
    +	//==================================================================
    +
    +	for (var i = 0; i < document.links.length; i++) {
    +		document.links[i].addEventListener("mousedown", function(event) {
    +			var href = event.target.href;
    +			if(typeof href === "string")
    +			{
    +				var urlDisect = href.split('#');
    +				var url = urlDisect[0];
    +				var hash = urlDisect[1];
    +
    +				if(CSRFP._getDomain(url).indexOf(document.domain) === -1
    +					|| CSRFP._isValidGetRequest(url)) {
    +					//cross origin or not to be protected by rules -- ignore
    +					return;
    +				}
    +
    +				if (url.indexOf('?') !== -1) {
    +					if(url.indexOf(CSRFP.CSRFP_TOKEN) === -1) {
    +						url += "&" +CSRFP.CSRFP_TOKEN +"=" +CSRFP._getAuthKey();
    +					} else {
    +						url = url.replace(new RegExp(CSRFP.CSRFP_TOKEN +"=.*?(&|$)", 'g'),
    +							CSRFP.CSRFP_TOKEN +"=" +CSRFP._getAuthKey() + "$1");
    +					}
    +				} else {
    +					url += "?" +CSRFP.CSRFP_TOKEN +"=" +CSRFP._getAuthKey();
    +				}
    +
    +				event.target.href = url;
    +				if (typeof hash !== 'undefined') {
    +					event.target.href += '#' +hash;
    +				}
    +			}
    +		});
    +	}
    +
    +}
    +
    +window.addEventListener("DOMContentLoaded", function() {
    +	csrfprotector_init();
    +}, false);
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/js/index.php b/data/web/inc/lib/vendor/owasp/csrf-protector-php/js/index.php
    new file mode 100644
    index 00000000..03e25a69
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/js/index.php
    @@ -0,0 +1,7 @@
    +<?php
    +/**
    + * OWASP CSRF Protector Project
    + * Code to redirect the user to previosus directory
    + * In case a user try to access this directory directly
    + */
    +header('location: ../index.php');
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/README.md b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/README.md
    new file mode 100644
    index 00000000..6562a9d9
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/README.md
    @@ -0,0 +1,21 @@
    +CSRFProtector configuration
    +==========================================
    +
    + - `CSRFP_TOKEN`: name of the csrf nonce, used for cookie or posting as argument. default: `csrfp_token` (if left blank)
    + - `logDirectory`: location of the directory at which log files will be saved **relative** to `config.php` file. This is required for file based logging (default), Not needed, in case you override logging function to implement your logging logic. (View [Overriding logging function](https://github.com/mebjas/CSRF-Protector-PHP/wiki/Overriding-logging-function))
    + <br>**Default value:** `../log/`
    + - `failedAuthAction`: Action code (integer) for action to be taken in case of failed validation. Has two different values for bot `GET` and `POST`. Different action codes are specified as follows, (<br>**Default:** `0` for both `GET` & `POST`):
    +*  `0` Send **403, Forbidden** Header
    +*  `1` **Strip the POST/GET query** and forward the request! unset($_POST)
    +*  `2` **Redirect to custom error page** mentioned in `errorRedirectionPage` 
    +*  `3` **Show custom error message** to user, mentioned in `customErrorMessage` 
    +*  `4` Send **500, Internal Server Error** header
    +
    + - `errorRedirectionPage`: **Absolute url** of the file to which user should be redirected. <br>**Default: null**
    + - `customErrorMessage`: **Error Message** to be shown to user. Only this text will be shown!<br>**Default: null**
    + - `jsPath`: location of the js file **relative** to `config.php`. <br>**Default:** `../js/csrfprotector.js`
    + - `jsUrl`: **Absolute url** of the js file. (See [Setting up](https://github.com/mebjas/CSRF-Protector-PHP/wiki/Setting-up-CSRF-Protector-PHP-in-your-web-application) for more information)
    + - `tokenLength`: length of csrfp token, Default `10`
    + - `secureCookie`: sets the "secure" HTTPS flag on the cookie. <br>**Default: `false`**
    + - `disabledJavascriptMessage`: messaged to be shown if js is disabled (string)
    + - `verifyGetFor`: regex rules for those urls for which csrfp validation should be enabled for `GET` requests also. (View [verifyGetFor rules](https://github.com/mebjas/CSRF-Protector-PHP/wiki/verifyGetFor-rules) for more information)
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/config.php b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/config.php
    new file mode 100755
    index 00000000..a12394e0
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/config.php
    @@ -0,0 +1,29 @@
    +<?php
    +/**
    + * Configuration file for CSRF Protector
    + * Necessary configurations are (library would throw exception otherwise)
    + * ---- logDirectory
    + * ---- failedAuthAction
    + * ---- jsPath
    + * ---- jsUrl
    + * ---- tokenLength
    + */
    +
    +return array(
    +	"CSRFP_TOKEN" => "MAILCOW_CSRF",
    +	"logDirectory" => "../log",
    +	"failedAuthAction" => array(
    +		"GET" => 1,
    +		"POST" => 1),
    +	"errorRedirectionPage" => "",
    +	"customErrorMessage" => "",
    +	"jsPath" => "../js/csrfprotector.js",
    +  // Fetching IS_HTTPS from sessions handler
    +	"jsUrl" => (($GLOBALS['IS_HTTPS'] === true) ? 'https://' : 'http://') . $GLOBALS['mailcow_hostname'] . ':' . intval(explode(':', $_SERVER['HTTP_HOST'])[1]) . "/inc/lib/vendor/owasp/csrf-protector-php/js/csrfprotector.js",
    +	"tokenLength" => 10,
    +	"secureCookie" => false,
    +	"disabledJavascriptMessage" => "This site attempts to protect users against <a href=\"https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29\">
    +	Cross-Site Request Forgeries </a> attacks. In order to do so, you must have JavaScript enabled in your web browser otherwise this site will fail to work correctly for you.
    +	 See details of your web browser for how to enable JavaScript.",
    +	 "verifyGetFor" => array()
    +);
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/csrf/README.md b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/csrf/README.md
    new file mode 100644
    index 00000000..286bcbad
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/csrf/README.md
    @@ -0,0 +1,6 @@
    +Placeholder for **CSRF Protector - php library**
    +=====================================================
    +
    +**Dependency:** `None`<br>
    +**Configuration-File:** `../config.php`<br>
    +**Configuration-Format:** `PHP ARRAY`<br>
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/csrf/csrfprotector.php b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/csrf/csrfprotector.php
    new file mode 100755
    index 00000000..c09a5b03
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/csrf/csrfprotector.php
    @@ -0,0 +1,536 @@
    +<?php
    +
    +if (!defined('__CSRF_PROTECTOR__')) {
    +	define('__CSRF_PROTECTOR__', true); 	// to avoid multiple declaration errors
    +
    +	// name of HTTP POST variable for authentication
    +	define("CSRFP_TOKEN","csrfp_token");
    +
    +	// We insert token name and list of url patterns for which
    +	// GET requests are validated against CSRF as hidden input fields
    +	// these are the names of the input fields
    +	define("CSRFP_FIELD_TOKEN_NAME", "csrfp_hidden_data_token");
    +	define("CSRFP_FIELD_URLS", "csrfp_hidden_data_urls");
    +
    +	/**
    +	 * child exception classes
    +	 */
    +	class configFileNotFoundException extends \exception {};
    +	class logDirectoryNotFoundException extends \exception {};
    +	class jsFileNotFoundException extends \exception {};
    +	class logFileWriteError extends \exception {};
    +	class baseJSFileNotFoundExceptio extends \exception {};
    +	class incompleteConfigurationException extends \exception {};
    +	class alreadyInitializedException extends \exception {};
    +
    +	class csrfProtector
    +	{
    +		/*
    +		 * Variable: $cookieExpiryTime
    +		 * expiry time for cookie
    +		 * @var int
    +		 */
    +		public static $cookieExpiryTime = 1800;	//30 minutes
    +
    +		/*
    +		 * Variable: $isSameOrigin
    +		 * flag for cross origin/same origin request
    +		 * @var bool
    +		 */
    +		private static $isSameOrigin = true;
    +
    +		/*
    +		 * Variable: $isValidHTML
    +		 * flag to check if output file is a valid HTML or not
    +		 * @var bool
    +		 */
    +		private static $isValidHTML = false;
    +
    +		/*
    +		 * Variable: $requestType
    +		 * Varaible to store weather request type is post or get
    +		 * @var string
    +		 */
    +		protected static $requestType = "GET";
    +
    +		/*
    +		 * Variable: $config
    +		 * config file for CSRFProtector
    +		 * @var int Array, length = 6
    +		 * Property: #1: failedAuthAction (int) => action to be taken in case autherisation fails
    +		 * Property: #2: logDirectory (string) => directory in which log will be saved
    +		 * Property: #3: customErrorMessage (string) => custom error message to be sent in case
    +		 *						of failed authentication
    +		 * Property: #4: jsFile (string) => location of the CSRFProtector js file
    +		 * Property: #5: tokenLength (int) => default length of hash
    +		 * Property: #6: disabledJavascriptMessage (string) => error message if client's js is disabled
    +		 */
    +		public static $config = array();
    +
    +		/*
    +		 * Variable: $requiredConfigurations
    +		 * Contains list of those parameters that are required to be there
    +		 * 	in config file for csrfp to work
    +		 */
    +		public static $requiredConfigurations  = array('logDirectory', 'failedAuthAction', 'jsPath', 'jsUrl', 'tokenLength');
    +		
    +		/*
    +		 *	Function: init
    +	 	 *
    +		 *	function to initialise the csrfProtector work flow
    +		 *
    +		 *	Parameters:
    +		 *	$length - length of CSRF_AUTH_TOKEN to be generated
    +		 *	$action - int array, for different actions to be taken in case of failed validation
    +		 *
    +		 *	Returns:
    +		 *		void
    +		 *
    +		 *	Throws:
    +		 *		configFileNotFoundException - when configuration file is not found
    +		 * 		incompleteConfigurationException - when all required fields in config
    +		 *											file are not available
    +		 *
    +		 */
    +		public static function init($length = null, $action = null)
    +		{
    +			/*
    +			 * Check if init has already been called.
    +			 */
    +			 if (count(self::$config) > 0) {
    +				 throw new alreadyInitializedException("OWASP CSRFProtector: library was already initialized.");
    +			 }
    +
    +			/*
    +			 * if mod_csrfp already enabled, no verification, no filtering
    +			 * Already done by mod_csrfp
    +			 */
    +			if (getenv('mod_csrfp_enabled'))
    +				return;
    +
    +			//start session in case its not
    +			if (session_id() == '')
    +			    session_start();
    +
    +			/*
    +			 * load configuration file and properties
    +			 * Check locally for a config.php then check for 
    +			 * a config/csrf_config.php file in the root folder
    +			 * for composer installations
    +			 */
    +			$standard_config_location = __DIR__ ."/../config.php";
    +			$composer_config_location = __DIR__ ."/../../../../../config/csrf_config.php";
    +
    +			if (file_exists($standard_config_location)) {
    +				self::$config = include($standard_config_location);
    +			} elseif(file_exists($composer_config_location)) {
    +				self::$config = include($composer_config_location);
    +			} else {
    +				throw new configFileNotFoundException("OWASP CSRFProtector: configuration file not found for CSRFProtector!");
    +			}
    +
    +			//overriding length property if passed in parameters
    +			if ($length != null)
    +				self::$config['tokenLength'] = intval($length);
    +			
    +			//action that is needed to be taken in case of failed authorisation
    +			if ($action != null)
    +				self::$config['failedAuthAction'] = $action;
    +
    +			if (self::$config['CSRFP_TOKEN'] == '')
    +				self::$config['CSRFP_TOKEN'] = CSRFP_TOKEN;
    +
    +			// Validate the config if everythings filled out
    +			// TODO: collect all missing values and throw exception together
    +			foreach (self::$requiredConfigurations as $value) {
    +				if (!isset(self::$config[$value]) || self::$config[$value] == '') {
    +					throw new incompleteConfigurationException(
    +						sprintf(
    +							"OWASP CSRFProtector: Incomplete configuration file, Value: %s missing ",
    +							$value
    +						)
    +					);
    +					exit;
    +				}
    +			}
    +
    +			// Authorise the incoming request
    +			self::authorizePost();
    +
    +			// Initialize output buffering handler
    +			if (!defined('__TESTING_CSRFP__'))
    +				ob_start('csrfProtector::ob_handler');
    +
    +			if (!isset($_COOKIE[self::$config['CSRFP_TOKEN']])
    +				|| !isset($_SESSION[self::$config['CSRFP_TOKEN']])
    +				|| !is_array($_SESSION[self::$config['CSRFP_TOKEN']])
    +				|| !in_array($_COOKIE[self::$config['CSRFP_TOKEN']],
    +					$_SESSION[self::$config['CSRFP_TOKEN']]))
    +				self::refreshToken();
    +
    +			// Set protected by CSRF Protector header
    +			header('X-CSRF-Protection: OWASP CSRFP 1.0.0');
    +		}
    +
    +		/*
    +		 * Function: authorizePost
    +		 * function to authorise incoming post requests
    +		 *
    +		 * Parameters: 
    +		 * void
    +		 *
    +		 * Returns: 
    +		 * void
    +		 *
    +		 * Throws: 
    +		 * logDirectoryNotFoundException - if log directory is not found
    +		 */
    +		public static function authorizePost()
    +		{
    +			//#todo this method is valid for same origin request only, 
    +			//enable it for cross origin also sometime
    +			//for cross origin the functionality is different
    +			if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    +
    +				//set request type to POST
    +				self::$requestType = "POST";
    +
    +				//currently for same origin only
    +				if (!(isset($_POST[self::$config['CSRFP_TOKEN']]) 
    +					&& isset($_SESSION[self::$config['CSRFP_TOKEN']])
    +					&& (self::isValidToken($_POST[self::$config['CSRFP_TOKEN']]))
    +					)) {
    +
    +					//action in case of failed validation
    +					self::failedValidationAction();			
    +				} else {
    +					self::refreshToken();	//refresh token for successfull validation
    +				}
    +			} else if (!static::isURLallowed()) {
    +				
    +				//currently for same origin only
    +				if (!(isset($_GET[self::$config['CSRFP_TOKEN']]) 
    +					&& isset($_SESSION[self::$config['CSRFP_TOKEN']])
    +					&& (self::isValidToken($_GET[self::$config['CSRFP_TOKEN']]))
    +					)) {
    +
    +					//action in case of failed validation
    +					self::failedValidationAction();			
    +				} else {
    +					self::refreshToken();	//refresh token for successfull validation
    +				}
    +			}	
    +		}
    +
    +		/*
    +		 * Function: isValidToken
    +		 * function to check the validity of token in session array
    +		 * Function also clears all tokens older than latest one
    +		 *
    +		 * Parameters: 
    +		 * $token - the token sent with GET or POST payload
    +		 *
    +		 * Returns: 
    +		 * bool - true if its valid else false
    +		 */
    +		private static function isValidToken($token) {
    +			if (!isset($_SESSION[self::$config['CSRFP_TOKEN']])) return false;
    +			if (!is_array($_SESSION[self::$config['CSRFP_TOKEN']])) return false;
    +			foreach ($_SESSION[self::$config['CSRFP_TOKEN']] as $key => $value) {
    +				if ($value == $token) {
    +
    +					// Clear all older tokens assuming they have been consumed
    +					foreach ($_SESSION[self::$config['CSRFP_TOKEN']] as $_key => $_value) {
    +						if ($_value == $token) break;
    +						array_shift($_SESSION[self::$config['CSRFP_TOKEN']]);
    +					}
    +					return true;
    +				}
    +			}
    +
    +			return false;
    +		}
    +
    +		/*
    +		 * Function: failedValidationAction
    +		 * function to be called in case of failed validation
    +		 * performs logging and take appropriate action
    +		 *
    +		 * Parameters: 
    +		 * void
    +		 *
    +		 * Returns: 
    +		 * void
    +		 */
    +		private static function failedValidationAction()
    +		{
    +			if (!file_exists(__DIR__ ."/../" .self::$config['logDirectory']))
    +				throw new logDirectoryNotFoundException("OWASP CSRFProtector: Log Directory Not Found!");
    +		
    +			//call the logging function
    +			static::logCSRFattack();
    +
    +			//#todo: ask mentors if $failedAuthAction is better as an int or string
    +			//default case is case 0
    +			switch (self::$config['failedAuthAction'][self::$requestType]) {
    +				case 0:
    +					//send 403 header
    +					header('HTTP/1.0 403 Forbidden');
    +					exit("<h2>403 Access Forbidden by CSRFProtector!</h2>");
    +					break;
    +				case 1:
    +					//unset the query parameters and forward
    +					if (self::$requestType === 'GET') {
    +						$_GET = array();
    +					} else {
    +						$_POST = array();
    +					}
    +					break;
    +				case 2:
    +					//redirect to custom error page
    +					$location  = self::$config['errorRedirectionPage'];
    +					header("location: $location");
    +				case 3:
    +					//send custom error message
    +					exit(self::$config['customErrorMessage']);
    +					break;
    +				case 4:
    +					//send 500 header -- internal server error
    +					header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
    +					exit("<h2>500 Internal Server Error!</h2>");
    +					break;
    +				default:
    +					//unset the query parameters and forward
    +					if (self::$requestType === 'GET') {
    +						$_GET = array();
    +					} else {
    +						$_POST = array();
    +					}
    +					break;
    +			}		
    +		}
    +
    +		/*
    +		 * Function: refreshToken
    +		 * Function to set auth cookie
    +		 *
    +		 * Parameters: 
    +		 * void
    +		 *
    +		 * Returns: 
    +		 * void
    +		 */
    +		public static function refreshToken()
    +		{
    +			$token = self::generateAuthToken();
    +
    +			if (!isset($_SESSION[self::$config['CSRFP_TOKEN']])
    +				|| !is_array($_SESSION[self::$config['CSRFP_TOKEN']]))
    +				$_SESSION[self::$config['CSRFP_TOKEN']] = array();
    +
    +			//set token to session for server side validation
    +			array_push($_SESSION[self::$config['CSRFP_TOKEN']], $token);
    +
    +			//set token to cookie for client side processing
    +			setcookie(self::$config['CSRFP_TOKEN'], 
    +				$token, 
    +				time() + self::$cookieExpiryTime,
    +				'',
    +				'',
    +				(array_key_exists('secureCookie', self::$config) ? (bool)self::$config['secureCookie'] : false));
    +		}
    +
    +		/*
    +		 * Function: generateAuthToken
    +		 * function to generate random hash of length as given in parameter
    +		 * max length = 128
    +		 *
    +		 * Parameters: 
    +		 * length to hash required, int
    +		 *
    +		 * Returns:
    +		 * string, token
    +		 */
    +		public static function generateAuthToken()
    +		{
    +			// todo - make this a member method / configurable
    +			$randLength = 64;
    +			
    +			//if config tokenLength value is 0 or some non int
    +			if (intval(self::$config['tokenLength']) == 0) {
    +				self::$config['tokenLength'] = 32;	//set as default
    +			}
    +
    +			//#todo - if $length > 128 throw exception 
    +
    +			if (function_exists("random_bytes")) {
    +				$token = bin2hex(random_bytes($randLength));
    +			} elseif (function_exists("openssl_random_pseudo_bytes")) {
    +				$token = bin2hex(openssl_random_pseudo_bytes($randLength));
    +			} else {
    +				$token = '';
    +				for ($i = 0; $i < 128; ++$i) {
    +					$r = mt_rand (0, 35);
    +					if ($r < 26) {
    +						$c = chr(ord('a') + $r);
    +					} else { 
    +						$c = chr(ord('0') + $r - 26);
    +					}
    +					$token .= $c;
    +				}
    +			}
    +			return substr($token, 0, self::$config['tokenLength']);
    +		}
    +
    +		/*
    +		 * Function: ob_handler
    +		 * Rewrites <form> on the fly to add CSRF tokens to them. This can also
    +		 * inject our JavaScript library.
    +		 *
    +		 * Parameters: 
    +		 * $buffer - output buffer to which all output are stored
    +		 * $flag - INT
    +		 *
    +		 * Return:
    +		 * string, complete output buffer
    +		 */
    +		public static function ob_handler($buffer, $flags)
    +		{
    +			// Even though the user told us to rewrite, we should do a quick heuristic
    +		    // to check if the page is *actually* HTML. We don't begin rewriting until
    +		    // we hit the first <html tag.
    +		    if (!self::$isValidHTML) {
    +		        // not HTML until proven otherwise
    +		        if (stripos($buffer, '<html') !== false) {
    +		            self::$isValidHTML = true; 
    +		        } else {
    +		            return $buffer;
    +		        }
    +		    }
    +		    
    +		    // TODO: statically rewrite all forms as well so that if a form is submitted
    +		    // before the js has worked on, it will still have token to send
    +		    // @priority: medium @labels: important @assign: mebjas
    +		    // @deadline: 1 week
    +
    +		    //add a <noscript> message to outgoing HTML output,
    +		    //informing the user to enable js for CSRFProtector to work
    +		    //best section to add, after <body> tag
    +		    $buffer = preg_replace("/<body[^>]*>/", "$0 <noscript>" .self::$config['disabledJavascriptMessage'] .
    +		    	"</noscript>", $buffer);
    +
    +		    $hiddenInput = '<input type="hidden" id="' . CSRFP_FIELD_TOKEN_NAME.'" value="' 
    +		    				.self::$config['CSRFP_TOKEN'] .'">' .PHP_EOL;
    +
    +		    $hiddenInput .= '<input type="hidden" id="' .CSRFP_FIELD_URLS .'" value=\''
    +		    				.json_encode(self::$config['verifyGetFor']) .'\'>';
    +
    +		    //implant hidden fields with check url information for reading in javascript
    +	        $buffer = str_ireplace('</body>', $hiddenInput . '</body>', $buffer);
    +
    +		    //implant the CSRFGuard js file to outgoing script
    +		    $script = '<script type="text/javascript" src="' . self::$config['jsUrl'] . '"></script>' . PHP_EOL;
    +		    $buffer = str_ireplace('</body>', $script . '</body>', $buffer, $count);
    +
    +		    if (!$count)
    +		        $buffer .= $script;
    +
    +		    return $buffer;
    +		}
    +
    +		/*
    +		 * Function: logCSRFattack
    +		 * Function to log CSRF Attack
    +		 * 
    +		 * Parameters: 
    +		 * void
    +		 *
    +		 * Retruns: 
    +		 * void
    +		 *
    +		 * Throws: 
    +		 * logFileWriteError - if unable to log an attack
    +		 */
    +		protected static function logCSRFattack()
    +		{
    +			//if file doesnot exist for, create it
    +			$logFile = fopen(__DIR__ ."/../" .self::$config['logDirectory']
    +			."/" .date("m-20y") .".log", "a+");
    +			
    +			//throw exception if above fopen fails
    +			if (!$logFile)
    +				throw new logFileWriteError("OWASP CSRFProtector: Unable to write to the log file");	
    +
    +			//miniature version of the log
    +			$log = array();
    +			$log['timestamp'] = time();
    +			$log['HOST'] = $_SERVER['HTTP_HOST'];
    +			$log['REQUEST_URI'] = $_SERVER['REQUEST_URI'];
    +			$log['requestType'] = self::$requestType;
    +
    +			if (self::$requestType === "GET")
    +				$log['query'] = $_GET;
    +			else
    +				$log['query'] = $_POST;
    +
    +			$log['cookie'] = $_COOKIE;
    +
    +			//convert log array to JSON format to be logged
    +			$log = json_encode($log) .PHP_EOL;
    +
    +			//append log to the file
    +			fwrite($logFile, $log);
    +
    +			//close the file handler
    +			fclose($logFile);
    +		}
    +
    +		/*
    +		 * Function: getCurrentUrl
    +		 * Function to return current url of executing page
    +		 * 
    +		 * Parameters: 
    +		 * void
    +		 *
    +		 * Returns: 
    +		 * string - current url
    +		 */
    +		private static function getCurrentUrl()
    +		{
    +			$request_scheme = 'https';
    +
    +			if (isset($_SERVER['REQUEST_SCHEME'])) {
    +				$request_scheme = $_SERVER['REQUEST_SCHEME'];
    +			} else {
    +				if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
    +					$request_scheme = 'https';
    +				} else {
    +					$request_scheme = 'http';
    +				}
    +			}
    +
    +			return $request_scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    +		}
    +
    +		/*
    +		 * Function: isURLallowed
    +		 * Function to check if a url mataches for any urls
    +		 * Listed in config file
    +		 *
    +		 * Parameters: 
    +		 * void
    +		 *
    +		 * Returns: 
    +		 * boolean - true is url need no validation, false if validation needed
    +		 */  
    +		public static function isURLallowed() {
    +			foreach (self::$config['verifyGetFor'] as $key => $value) {
    +				$value = str_replace(array('/','*'), array('\/','(.*)'), $value);
    +				preg_match('/' .$value .'/', self::getCurrentUrl(), $output);
    +				if (count($output) > 0)
    +					return false;
    +			}
    +			return true;
    +		}
    +	};
    +}
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/csrf/index.php b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/csrf/index.php
    new file mode 100644
    index 00000000..03e25a69
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/csrf/index.php
    @@ -0,0 +1,7 @@
    +<?php
    +/**
    + * OWASP CSRF Protector Project
    + * Code to redirect the user to previosus directory
    + * In case a user try to access this directory directly
    + */
    +header('location: ../index.php');
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/index.php b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/index.php
    new file mode 100644
    index 00000000..03e25a69
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/index.php
    @@ -0,0 +1,7 @@
    +<?php
    +/**
    + * OWASP CSRF Protector Project
    + * Code to redirect the user to previosus directory
    + * In case a user try to access this directory directly
    + */
    +header('location: ../index.php');
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/licence.md b/data/web/inc/lib/vendor/owasp/csrf-protector-php/licence.md
    new file mode 100644
    index 00000000..eba85e5b
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/licence.md
    @@ -0,0 +1,13 @@
    +Copyright 2014 OWASP Foundation
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/log/.htaccess b/data/web/inc/lib/vendor/owasp/csrf-protector-php/log/.htaccess
    new file mode 100644
    index 00000000..3418e55a
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/log/.htaccess
    @@ -0,0 +1 @@
    +deny from all
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/log/index.php b/data/web/inc/lib/vendor/owasp/csrf-protector-php/log/index.php
    new file mode 100644
    index 00000000..03e25a69
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/log/index.php
    @@ -0,0 +1,7 @@
    +<?php
    +/**
    + * OWASP CSRF Protector Project
    + * Code to redirect the user to previosus directory
    + * In case a user try to access this directory directly
    + */
    +header('location: ../index.php');
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/phpunit.xml.dist b/data/web/inc/lib/vendor/owasp/csrf-protector-php/phpunit.xml.dist
    new file mode 100644
    index 00000000..34814a25
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/phpunit.xml.dist
    @@ -0,0 +1,15 @@
    +<?xml version="1.0" encoding="UTF-8"?>
    +<phpunit verbose="true">
    +    <php>
    +        <ini name="memory_limit" value="1024M" />
    +        <ini name="error_reporting" value="E_ALL"/>
    +    </php>
    +    <testsuite name="OWASP CSRF Protector php">
    +        <directory>./test/csrfprotector_test.php</directory>
    +    </testsuite>
    +    <filter>
    +        <whitelist processUncoveredFilesFromWhitelist="true">
    +        <file>libs/csrf/csrfprotector.php</file>
    +        </whitelist>
    +    </filter>
    +</phpunit>
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/readme.md b/data/web/inc/lib/vendor/owasp/csrf-protector-php/readme.md
    new file mode 100644
    index 00000000..fa427811
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/readme.md
    @@ -0,0 +1,65 @@
    +CSRF Protector
    +==========================
    +[![Todo Status](http://todofy.org/b/mebjas/CSRF-Protector-PHP)](http://todofy.org/r/mebjas/CSRF-Protector-PHP) [![Build Status](https://travis-ci.org/mebjas/CSRF-Protector-PHP.svg?branch=master)](https://travis-ci.org/mebjas/CSRF-Protector-PHP)  [![codecov](https://codecov.io/gh/mebjas/CSRF-Protector-PHP/branch/master/graph/badge.svg)](https://codecov.io/gh/mebjas/CSRF-Protector-PHP)
    +<br>CSRF protector php, a standalone php library for csrf mitigation in web applications. Easy to integrate in any php web app. 
    +
    +Add to your project using packagist
    +==========
    + Add a `composer.json` file to your project directory
    + ```json
    + {
    +    "require": {
    +        "owasp/csrf-protector-php": "dev-master"
    +    }
    +}
    +```
    +Then open terminal (or command prompt), move to project directory and run
    +```shell
    +composer install
    +```
    +OR
    +```
    +php composer.phar install
    +```
    +This will add CSRFP (library will be downloaded at ./vendor/owasp/csrf-protector-php) to your project directory. View [packagist.org](https://packagist.org/) for more help with composer!
    +
    +Configuration
    +==========
    +For composer installations: Copy the config.sample.php file into your root folder at config/csrf_config.php
    +For non-composer installations: Copy the libs/csrf/config.sample.php file into libs/csrc/config.php
    +Edit config accordingly. See Detailed Information link below.
    +
    +How to use
    +==========
    +```php
    +<?php
    +include_once __DIR__ .'/vendor/owasp/csrf-protector-php/libs/csrf/csrfprotector.php';
    +
    +//Initialise CSRFGuard library
    +csrfProtector::init();
    +```
    +simply include the library and call the `init()` function!
    +
    +### Detailed information @[Project wiki on github](https://github.com/mebjas/CSRF-Protector-PHP/wiki)
    +
    +### More information @[OWASP wiki](https://www.owasp.org/index.php/CSRFProtector_Project)
    +
    +### Contribute
    +
    +* Fork the repo
    +* Create your branch
    +* Commit your changes
    +* Create a pull request
    +
    +### Note
    +This version (`master`) requires the clients to have Javascript enabled. However if your application can work without javascript & you require a nojs version of this library, check our [nojs version](https://github.com/mebjas/CSRF-Protector-PHP/tree/nojs-support)
    +
    +## Discussion
    +Join Discussions on the [mailing list](https://lists.owasp.org/mailman/listinfo/owasp-csrfprotector)
    +
    +For any other queries contact me at: **minhaz@owasp.org**
    +
    +### FAQ:
    +1. What happens if token expires? - https://github.com/mebjas/CSRF-Protector-PHP/wiki/what-if-token-expires
    +2. Secure flag in cookie? - https://github.com/mebjas/CSRF-Protector-PHP/issues/54
    +3. NoJS support? - https://github.com/mebjas/CSRF-Protector-PHP/tree/nojs-support
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/test/config.test.php b/data/web/inc/lib/vendor/owasp/csrf-protector-php/test/config.test.php
    new file mode 100644
    index 00000000..14bc1828
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/test/config.test.php
    @@ -0,0 +1,27 @@
    +<?php
    +/**
    + * Configuration file for CSRF Protector
    + * Necessary configurations are (library would throw exception otherwise)
    + * ---- logDirectory
    + * ---- failedAuthAction
    + * ---- jsPath
    + * ---- jsUrl
    + * ---- tokenLength
    + */
    +return array(
    +	"CSRFP_TOKEN" => "csrfp_token",
    +	"logDirectory" => "../log",
    +	"failedAuthAction" => array(
    +		"GET" => 0,
    +		"POST" => 0),
    +	"errorRedirectionPage" => "",
    +	"customErrorMessage" => "",
    +	"jsPath" => "../js/csrfprotector.js",
    +	"jsUrl" => "http://localhost/csrfp/js/csrfprotector.js",
    +	"tokenLength" => 10,
    +	"secureCookie" => false,
    +	"disabledJavascriptMessage" => "This site attempts to protect users against <a href=\"https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29\">
    +	Cross-Site Request Forgeries </a> attacks. In order to do so, you must have JavaScript enabled in your web browser otherwise this site will fail to work correctly for you.
    +	 See details of your web browser for how to enable JavaScript.",
    +	 "verifyGetFor" => array()
    +);
    \ No newline at end of file
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/test/csrfprotector_test.php b/data/web/inc/lib/vendor/owasp/csrf-protector-php/test/csrfprotector_test.php
    new file mode 100644
    index 00000000..ca5404e5
    --- /dev/null
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/test/csrfprotector_test.php
    @@ -0,0 +1,534 @@
    +<?php
    +date_default_timezone_set('UTC');
    +require_once __DIR__ .'/../libs/csrf/csrfprotector.php';
    +
    +if (intval(phpversion('tidy')) >= 7 && !class_exists('\PHPUnit_Framework_TestCase', true)) {
    +    class_alias('\PHPUnit\Framework\TestCase', '\PHPUnit_Framework_TestCase');
    +}
    +
    +/**
    + * Wrapper class for testing purpose
    + */
    +class csrfp_wrapper extends csrfprotector
    +{
    +    /**
    +     * Function to provide wrapper methode to set the protected var, requestType
    +     */
    +    public static function changeRequestType($type)
    +    {
    +        self::$requestType = $type;
    +    }
    +
    +    /**
    +     * Function to check for a string value anywhere within HTTP response headers
    +     * Returns true on first match of $needle in header names or values
    +     */
    +    public static function checkHeader($needle)
    +    {
    +        $haystack = xdebug_get_headers();
    +        foreach ($haystack as $key => $value) {
    +            if (strpos($value, $needle) !== false)
    +                return true;
    +        }
    +        return false;
    +    }
    +
    +    /**
    +     * Function to return the string value of the last response header
    +     * identified by name $needle
    +     */
    +    public static function getHeaderValue($needle)
    +    {
    +        $haystack = xdebug_get_headers();
    +        foreach ($haystack as $key => $value) {
    +            if (strpos($value, $needle) === 0) {
    +                // Deliberately overwrite to accept the last rather than first match
    +                // as xdebug_get_headers() will accumulate all set headers
    +                list(,$hvalue) = explode(':', $value, 2);
    +            }
    +        }
    +        return $hvalue;
    +    } 
    +}
    +
    +/**
    + * helper methods
    + */
    +class Helper {
    +    /**
    +     * Function to recusively delete a dir
    +     */
    +    public static function delTree($dir) { 
    +        $files = array_diff(scandir($dir), array('.','..')); 
    +        foreach ($files as $file) { 
    +            (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); 
    +        } 
    +        return rmdir($dir); 
    +    }
    +}
    +
    +
    +/**
    + * main test class
    + */
    +class csrfp_test extends PHPUnit_Framework_TestCase
    +{
    +    /**
    +     * @var to hold current configurations
    +     */
    +    protected $config = array();
    +
    +    /**
    +     * @var log directory for testing
    +     */
    +    private $logDir;
    +
    +    /**
    +     * Function to be run before every test*() functions.
    +     */
    +    public function setUp()
    +    {
    +        $this->logDir = __DIR__ .'/logs';
    +
    +        csrfprotector::$config['jsPath'] = '../js/csrfprotector.js';
    +        csrfprotector::$config['CSRFP_TOKEN'] = 'csrfp_token';
    +        csrfprotector::$config['secureCookie'] = false;
    +        csrfprotector::$config['logDirectory'] = '../test/logs';
    +
    +        $_SERVER['REQUEST_URI'] = 'temp';       // For logging
    +        $_SERVER['REQUEST_SCHEME'] = 'http';    // For authorizePost
    +        $_SERVER['HTTP_HOST'] = 'test';         // For isUrlAllowed
    +        $_SERVER['PHP_SELF'] = '/index.php';     // For authorizePost
    +        $_POST[csrfprotector::$config['CSRFP_TOKEN']]
    +          = $_GET[csrfprotector::$config['CSRFP_TOKEN']] = '123';
    +
    +        //token mismatch - leading to failed validation
    +        $_SESSION[csrfprotector::$config['CSRFP_TOKEN']] = array('abc');
    +        $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
    +        $_SERVER['HTTPS'] = null;
    +
    +        $this->config = include(__DIR__ .'/config.test.php');
    +
    +        // Create an instance of config file -- for testing
    +        $data = file_get_contents(__DIR__ .'/config.test.php');
    +        file_put_contents(__DIR__ .'/../libs/config.php', $data);
    +
    +        if (!defined('__TESTING_CSRFP__')) define('__TESTING_CSRFP__', true);
    +    }
    +
    +    /**
    +     * tearDown()
    +     */
    +    public function tearDown()
    +    {
    +        unlink(__DIR__ .'/../libs/config.php');
    +        if (is_dir(__DIR__ .'/logs'))
    +            Helper::delTree(__DIR__ .'/logs');
    +    }
    +
    +    /**
    +     * Function to check refreshToken() functionality
    +     */
    +    public function testRefreshToken()
    +    {
    +        $val = $_COOKIE[csrfprotector::$config['CSRFP_TOKEN']] = '123abcd';
    +        $_SESSION[csrfprotector::$config['CSRFP_TOKEN']] = array('123abcd');
    +        csrfProtector::$config['tokenLength'] = 20;
    +        csrfProtector::refreshToken();
    +
    +        $this->assertTrue(strcmp($val, $_SESSION[csrfprotector::$config['CSRFP_TOKEN']][1]) != 0);
    +
    +        $this->assertTrue(csrfP_wrapper::checkHeader('Set-Cookie'));
    +        $this->assertTrue(csrfP_wrapper::checkHeader('csrfp_token'));
    +        $this->assertTrue(csrfp_wrapper::checkHeader($_SESSION[csrfprotector::$config['CSRFP_TOKEN']][1]));
    +    }
    +
    +    /**
    +     * test secure flag is set in the token cookie when requested
    +     */
    +    public function testSecureCookie()
    +    {
    +        $_SERVER['REQUEST_METHOD'] = 'POST';
    +        $_SESSION[csrfprotector::$config['CSRFP_TOKEN']] = array('123abcd');
    +
    +        csrfprotector::$config['secureCookie'] = false;
    +        csrfprotector::refreshToken();
    +        $this->assertNotRegExp('/; secure/', csrfp_wrapper::getHeaderValue('Set-Cookie'));
    +
    +        csrfprotector::$config['secureCookie'] = true;
    +        csrfprotector::refreshToken();
    +        $this->assertRegExp('/; secure/', csrfp_wrapper::getHeaderValue('Set-Cookie'));
    +    }
    +
    +    /**
    +     * test authorise post -> log directory exception
    +     */
    +    public function testAuthorisePost_logdirException()
    +    {
    +        $_SERVER['REQUEST_METHOD'] = 'POST';
    +        csrfprotector::$config['logDirectory'] = 'unknown_location';
    +
    +        try {
    +            csrfprotector::authorizePost();
    +        } catch (logDirectoryNotFoundException $ex) {
    +            $this->assertTrue(true);
    +            return;;
    +        }
    +        $this->fail('logDirectoryNotFoundException has not been raised.');
    +    }
    +
    +    /**
    +     * test authorise post -> action = 403, forbidden
    +     */
    +    public function testAuthorisePost_failedAction_1()
    +    {
    +        $_SERVER['REQUEST_METHOD'] = 'POST';
    +        csrfprotector::$config['verifyGetFor'] = array('http://test/index*');
    +        csrfprotector::$config['logDirectory'] = '../log';
    +        csrfprotector::$config['failedAuthAction']['POST'] = 0;
    +        csrfprotector::$config['failedAuthAction']['GET'] = 0;
    +
    +        //csrfprotector::authorizePost();
    +        $this->markTestSkipped('Cannot add tests as code exit here');
    +
    +        $_SERVER['REQUEST_METHOD'] = 'GET';
    +        csrfp_wrapper::changeRequestType('GET');
    +        //csrfprotector::authorizePost();
    +
    +        $this->markTestSkipped('Cannot add tests as code exit here');
    +    }
    +
    +    /**
    +     * test authorise post -> strip $_GET, $_POST
    +     */
    +    public function testAuthorisePost_failedAction_2()
    +    {
    +        $_SERVER['REQUEST_METHOD'] = 'POST';
    +
    +        csrfprotector::$config['logDirectory'] = '../log';
    +        csrfprotector::$config['verifyGetFor'] = array('http://test/index*');
    +        csrfprotector::$config['failedAuthAction']['POST'] = 1;
    +        csrfprotector::$config['failedAuthAction']['GET'] = 1;
    +
    +        $_POST = array('param1' => 1, 'param2' => 2);
    +        csrfprotector::authorizePost();
    +        $this->assertEmpty($_POST);
    +
    +        $_SERVER['REQUEST_METHOD'] = 'GET';
    +        csrfp_wrapper::changeRequestType('GET');
    +        $_GET = array('param1' => 1, 'param2' => 2);
    +
    +        csrfprotector::authorizePost();
    +        $this->assertEmpty($_GET);
    +    }
    +
    +    /**
    +     * test authorise post -> redirect
    +     */
    +    public function testAuthorisePost_failedAction_3()
    +    {
    +        $_SERVER['REQUEST_METHOD'] = 'POST';
    +
    +        csrfprotector::$config['logDirectory'] = '../log';
    +        csrfprotector::$config['verifyGetFor'] = array('http://test/index*');
    +        csrfprotector::$config['errorRedirectionPage'] = 'http://test';
    +        csrfprotector::$config['failedAuthAction']['POST'] = 2;
    +        csrfprotector::$config['failedAuthAction']['GET'] = 2;
    +
    +        //csrfprotector::authorizePost();
    +        $this->markTestSkipped('Cannot add tests as code exit here');
    +
    +        $_SERVER['REQUEST_METHOD'] = 'GET';
    +        csrfp_wrapper::changeRequestType('GET');
    +        //csrfprotector::authorizePost();
    +        $this->markTestSkipped('Cannot add tests as code exit here');
    +    }
    +
    +    /**
    +     * test authorise post -> error message & exit
    +     */
    +    public function testAuthorisePost_failedAction_4()
    +    {
    +        $_SERVER['REQUEST_METHOD'] = 'POST';
    +
    +        csrfprotector::$config['logDirectory'] = '../log';
    +        csrfprotector::$config['verifyGetFor'] = array('http://test/index*');
    +        csrfprotector::$config['customErrorMessage'] = 'custom error message';
    +        csrfprotector::$config['failedAuthAction']['POST'] = 3;
    +        csrfprotector::$config['failedAuthAction']['POST'] = 3;
    +
    +        //csrfprotector::authorizePost();
    +        $this->markTestSkipped('Cannot add tests as code exit here');
    +
    +        $_SERVER['REQUEST_METHOD'] = 'GET';
    +        csrfp_wrapper::changeRequestType('GET');
    +        //csrfprotector::authorizePost();
    +        $this->markTestSkipped('Cannot add tests as code exit here');
    +    }
    +
    +    /**
    +     * test authorise post -> 500 internal server error
    +     */
    +    public function testAuthorisePost_failedAction_5()
    +    {
    +        $_SERVER['REQUEST_METHOD'] = 'POST';
    +
    +        csrfprotector::$config['logDirectory'] = '../log';
    +        csrfprotector::$config['verifyGetFor'] = array('http://test/index*');
    +        csrfprotector::$config['failedAuthAction']['POST'] = 4;
    +        csrfprotector::$config['failedAuthAction']['GET'] = 4;
    +
    +        //csrfprotector::authorizePost();
    +        //$this->markTestSkipped('Cannot add tests as code exit here');
    +
    +        $_SERVER['REQUEST_METHOD'] = 'GET';
    +        csrfp_wrapper::changeRequestType('GET');
    +        //csrfprotector::authorizePost();
    +        //csrfp_wrapper::checkHeader('500');
    +        //$this->markTestSkipped('Cannot add tests as code exit here');
    +    }
    +
    +    /**
    +     * test authorise post -> default action: strip $_GET, $_POST
    +     */
    +    public function testAuthorisePost_failedAction_6()
    +    {
    +        $_SERVER['REQUEST_METHOD'] = 'POST';
    +
    +        csrfprotector::$config['logDirectory'] = '../log';
    +        csrfprotector::$config['verifyGetFor'] = array('http://test/index*');
    +        csrfprotector::$config['failedAuthAction']['POST'] = 10;
    +        csrfprotector::$config['failedAuthAction']['GET'] = 10;
    +
    +        $_POST = array('param1' => 1, 'param2' => 2);
    +        csrfprotector::authorizePost();
    +        $this->assertEmpty($_POST);
    +
    +        $_SERVER['REQUEST_METHOD'] = 'GET';
    +        csrfp_wrapper::changeRequestType('GET');
    +        $_GET = array('param1' => 1, 'param2' => 2);
    +
    +        csrfprotector::authorizePost();
    +        $this->assertEmpty($_GET);
    +    }
    +
    +    /**
    +     * test authorise success
    +     */
    +    public function testAuthorisePost_success()
    +    {
    +
    +        $_SERVER['REQUEST_METHOD'] = 'POST';
    +        $_POST[csrfprotector::$config['CSRFP_TOKEN']]
    +            = $_GET[csrfprotector::$config['CSRFP_TOKEN']]
    +            = $_SESSION[csrfprotector::$config['CSRFP_TOKEN']][0];
    +        $temp = $_SESSION[csrfprotector::$config['CSRFP_TOKEN']];
    +
    +        csrfprotector::authorizePost(); //will create new session and cookies
    +        $this->assertFalse($temp == $_SESSION[csrfprotector::$config['CSRFP_TOKEN']][0]);
    +        $this->assertTrue(csrfp_wrapper::checkHeader('Set-Cookie'));
    +        $this->assertTrue(csrfp_wrapper::checkHeader('csrfp_token'));
    +        // $this->assertTrue(csrfp_wrapper::checkHeader($_SESSION[csrfprotector::$config['CSRFP_TOKEN']][0]));  // Combine these 3 later
    +
    +        // For get method
    +        $_SERVER['REQUEST_METHOD'] = 'GET';
    +        csrfp_wrapper::changeRequestType('GET');
    +        $_POST[csrfprotector::$config['CSRFP_TOKEN']]
    +            = $_GET[csrfprotector::$config['CSRFP_TOKEN']]
    +            = $_SESSION[csrfprotector::$config['CSRFP_TOKEN']][0];
    +        $temp = $_SESSION[csrfprotector::$config['CSRFP_TOKEN']];
    +
    +        csrfprotector::authorizePost(); //will create new session and cookies
    +        $this->assertFalse($temp == $_SESSION[csrfprotector::$config['CSRFP_TOKEN']]);
    +        $this->assertTrue(csrfp_wrapper::checkHeader('Set-Cookie'));
    +        $this->assertTrue(csrfp_wrapper::checkHeader('csrfp_token'));
    +        // $this->assertTrue(csrfp_wrapper::checkHeader($_SESSION[csrfprotector::$config['CSRFP_TOKEN']][0]));  // Combine these 3 later
    +    }
    +
    +    /**
    +     * test for generateAuthToken()
    +     */
    +    public function testGenerateAuthToken()
    +    {
    +        csrfprotector::$config['tokenLength'] = 20;
    +        $token1 = csrfprotector::generateAuthToken();
    +        $token2 = csrfprotector::generateAuthToken();
    +
    +        $this->assertFalse($token1 == $token2);
    +        $this->assertEquals(strlen($token1), 20);
    +        $this->assertRegExp('/^[a-z0-9]{20}$/', $token1);
    +
    +        csrfprotector::$config['tokenLength'] = 128;
    +        $token = csrfprotector::generateAuthToken();
    +        $this->assertEquals(strlen($token), 128);
    +        $this->assertRegExp('/^[a-z0-9]{128}$/', $token);
    +    }
    +
    +    /**
    +     * test ob_handler_function
    +     */
    +    public function testob_handler()
    +    {
    +        csrfprotector::$config['disabledJavascriptMessage'] = 'test message';
    +        csrfprotector::$config['jsUrl'] = 'http://localhost/test/csrf/js/csrfprotector.js';
    +
    +        $testHTML = '<html>';
    +        $testHTML .= '<head><title>1</title>';
    +        $testHTML .= '<body onload="test()">';
    +        $testHTML .= '-- some static content --';
    +        $testHTML .= '-- some static content --';
    +        $testHTML .= '</body>';
    +        $testHTML .= '</head></html>';
    +
    +        $modifiedHTML = csrfprotector::ob_handler($testHTML, 0);
    +        $inpLength = strlen($testHTML);
    +        $outLength = strlen($modifiedHTML);
    +
    +        //Check if file has been modified
    +        $this->assertFalse($outLength == $inpLength);
    +        $this->assertTrue(strpos($modifiedHTML, '<noscript>') !== false);
    +        $this->assertTrue(strpos($modifiedHTML, '<script') !== false);
    +
    +    }
    +
    +    /**
    +     * test ob_handler_function for output filter
    +     */
    +    public function testob_handler_positioning()
    +    {
    +        csrfprotector::$config['disabledJavascriptMessage'] = 'test message';
    +        csrfprotector::$config['jsUrl'] = 'http://localhost/test/csrf/js/csrfprotector.js';
    +
    +        $testHTML = '<html>';
    +        $testHTML .= '<head><title>1</title>';
    +        $testHTML .= '<body onload="test()">';
    +        $testHTML .= '-- some static content --';
    +        $testHTML .= '-- some static content --';
    +        $testHTML .= '</body>';
    +        $testHTML .= '</head></html>';
    +
    +        $modifiedHTML = csrfprotector::ob_handler($testHTML, 0);
    +
    +        $this->assertEquals(strpos($modifiedHTML, '<body') + 23, strpos($modifiedHTML, '<noscript'));
    +        // Check if content before </body> is </script> #todo
    +        //$this->markTestSkipped('todo, add appropriate test here');
    +    }
    +
    +    /**
    +     * testing exception in logging function
    +     */
    +    public function testgetCurrentUrl()
    +    {
    +        $stub = new ReflectionClass('csrfprotector');
    +        $method = $stub->getMethod('getCurrentUrl');
    +        $method->setAccessible(true);
    +        $this->assertEquals($method->invoke(null, array()), "http://test/index.php");
    +
    +        $tmp_request_scheme = $_SERVER['REQUEST_SCHEME'];
    +        unset($_SERVER['REQUEST_SCHEME']);
    +
    +        // server-https is not set
    +        $this->assertEquals($method->invoke(null, array()), "http://test/index.php");
    +
    +        $_SERVER['HTTPS'] = 'on';
    +        $this->assertEquals($method->invoke(null, array()), "https://test/index.php");
    +        unset($_SERVER['HTTPS']);
    +
    +        $_SERVER['REQUEST_SCHEME'] = "https";
    +        $this->assertEquals($method->invoke(null, array()), "https://test/index.php");
    +
    +        $_SERVER['REQUEST_SCHEME'] = $tmp_request_scheme;
    +    }
    +
    +    /**
    +     * testing exception in logging function
    +     */
    +    public function testLoggingException()
    +    {
    +        $stub = new ReflectionClass('csrfprotector');
    +        $method = $stub->getMethod('logCSRFattack');
    +        $method->setAccessible(true);
    +
    +        try {
    +            $method->invoke(null, array());
    +            $this->fail("logFileWriteError was not caught");
    +        } catch (Exception $ex) {
    +            // pass
    +            $this->assertTrue(true);
    +        }
    +
    +        if (!is_dir($this->logDir))
    +            mkdir($this->logDir);
    +        $method->invoke(null, array());
    +        $this->assertTrue(file_exists($this->logDir ."/" .date("m-20y") .".log"));
    +    }
    +
    +    /**
    +     * Tests isUrlAllowed() function for various urls and configuration
    +     */
    +    public function testisURLallowed()
    +    {
    +        csrfprotector::$config['verifyGetFor'] = array('http://test/delete*', 'https://test/*');
    +
    +        $_SERVER['PHP_SELF'] = '/nodelete.php';
    +        $this->assertTrue(csrfprotector::isURLallowed());
    +
    +        $_SERVER['PHP_SELF'] = '/index.php';
    +        $this->assertTrue(csrfprotector::isURLallowed('http://test/index.php'));
    +
    +        $_SERVER['PHP_SELF'] = '/delete.php';
    +        $this->assertFalse(csrfprotector::isURLallowed('http://test/delete.php'));
    +
    +        $_SERVER['PHP_SELF'] = '/delete_user.php';
    +        $this->assertFalse(csrfprotector::isURLallowed('http://test/delete_users.php'));
    +
    +        $_SERVER['REQUEST_SCHEME'] = 'https';
    +        $_SERVER['PHP_SELF'] = '/index.php';
    +        $this->assertFalse(csrfprotector::isURLallowed('https://test/index.php'));
    +
    +        $_SERVER['PHP_SELF'] = '/delete_user.php';
    +        $this->assertFalse(csrfprotector::isURLallowed('https://test/delete_users.php'));
    +    }
    +
    +    /**
    +     * Test for exception thrown when env variable is set by mod_csrfprotector
    +     */
    +    public function testModCSRFPEnabledException()
    +    {
    +        putenv('mod_csrfp_enabled=true');
    +        $temp = $_COOKIE[csrfprotector::$config['CSRFP_TOKEN']] = 'abc';
    +        $_SESSION[csrfprotector::$config['CSRFP_TOKEN']] = array('abc');
    +
    +        csrfProtector::$config = array();
    +        csrfProtector::init();
    +
    +        // Assuming no config was added
    +        $this->assertTrue(count(csrfProtector::$config) == 0);
    +        
    +        // unset the env variable
    +        putenv('mod_csrfp_enabled');
    +    }
    +
    +    /**
    +     * Test for exception thrown when init() method is called multiple times
    +     */
    +    public function testMultipleInitializeException()
    +    {
    +        csrfProtector::$config = array();
    +        $this->assertTrue(count(csrfProtector::$config) == 0);
    +
    +        $_SERVER['REQUEST_METHOD'] = 'GET';
    +        csrfProtector::init();
    +
    +        $this->assertTrue(count(csrfProtector::$config) == 11);
    +        try {
    +            csrfProtector::init();
    +            $this->fail("alreadyInitializedException not raised");
    +        }  catch (alreadyInitializedException $ex) {
    +            // pass
    +            $this->assertTrue(true);
    +        } catch (Exception $ex) {
    +            $this->fail("exception other than alreadyInitializedException failed");            
    +        }
    +    }
    +}
    
    From 2dd9e1b14fa682e1fed86948afc08680c32646af Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Sun, 7 May 2017 17:46:10 +0200
    Subject: [PATCH 14/49] Fix hostname detection
    
    ---
     .../owasp/csrf-protector-php/libs/config.php  | 22 ++++++++++++++++++-
     1 file changed, 21 insertions(+), 1 deletion(-)
    
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/config.php b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/config.php
    index a12394e0..cf2512e9 100755
    --- a/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/config.php
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/config.php
    @@ -9,6 +9,26 @@
      * ---- tokenLength
      */
     
    +function get_trusted_hostname() {
    +  $js_path = "/inc/lib/vendor/owasp/csrf-protector-php/js/csrfprotector.js";
    +  if ((isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == "https") || isset($_SERVER['HTTPS'])) {
    +    $is_scheme = "https://";
    +  }
    +  else {
    +    $is_scheme = "http://";
    +  }
    +  if (isset(explode(':', $_SERVER['HTTP_HOST'])[1])) {
    +    $is_port = intval(explode(':', $_SERVER['HTTP_HOST'])[1]);
    +    if (filter_var($is_port, FILTER_VALIDATE_INT, array("options" => array("min_range" =>1, "max_range" => 65535))) === false) {
    +      return false;
    +    }
    +  }
    +  if (!isset($is_port) || $is_port == 0) {
    +    $is_port = ($is_scheme == "https://") ? 443 : 80;
    +  }
    +  return $is_scheme . $GLOBALS['mailcow_hostname'] . ':' . $is_port . $js_path;
    +}
    +
     return array(
     	"CSRFP_TOKEN" => "MAILCOW_CSRF",
     	"logDirectory" => "../log",
    @@ -19,7 +39,7 @@ return array(
     	"customErrorMessage" => "",
     	"jsPath" => "../js/csrfprotector.js",
       // Fetching IS_HTTPS from sessions handler
    -	"jsUrl" => (($GLOBALS['IS_HTTPS'] === true) ? 'https://' : 'http://') . $GLOBALS['mailcow_hostname'] . ':' . intval(explode(':', $_SERVER['HTTP_HOST'])[1]) . "/inc/lib/vendor/owasp/csrf-protector-php/js/csrfprotector.js",
    +	"jsUrl" => get_trusted_hostname(),
     	"tokenLength" => 10,
     	"secureCookie" => false,
     	"disabledJavascriptMessage" => "This site attempts to protect users against <a href=\"https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29\">
    
    From 2444cd1cd24a5480b606f9ead735f474764243ea Mon Sep 17 00:00:00 2001
    From: Michael Kuron <mkuron@users.noreply.github.com>
    Date: Sun, 7 May 2017 20:12:24 +0200
    Subject: [PATCH 15/49] Remove duplicated SQL
    
    ---
     data/web/inc/functions.inc.php | 6 +-----
     1 file changed, 1 insertion(+), 5 deletions(-)
    
    diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php
    index 97a06b8d..1c0504f6 100644
    --- a/data/web/inc/functions.inc.php
    +++ b/data/web/inc/functions.inc.php
    @@ -5134,11 +5134,7 @@ function add_forwarding_host($postarray) {
     		if ($source == $host)
     			$source = '';
     		try {
    -			if ($filter_spam) { // if the host already exists, REPLACE it with the spam filter turned on
    -				$stmt = $pdo->prepare("REPLACE INTO `forwarding_hosts` (`host`, `source`, `filter_spam`) VALUES (:host, :source, :filter_spam)");
    -			} else { // if the host already exists, IGNORE it no matter whether the spam filter is already turned on
    -				$stmt = $pdo->prepare("INSERT IGNORE INTO `forwarding_hosts` (`host`, `source`, `filter_spam`) VALUES (:host, :source, :filter_spam)");
    -			}
    +			$stmt = $pdo->prepare("REPLACE INTO `forwarding_hosts` (`host`, `source`, `filter_spam`) VALUES (:host, :source, :filter_spam)");
     			$stmt->execute(array(
     				':host' => $host,
     				':source' => $source,
    
    From aa98d86febdc0be6987a35667981ad1db201bf45 Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Mon, 8 May 2017 00:27:16 +0200
    Subject: [PATCH 16/49] Sieve rule for tags changed
    
    ---
     data/conf/dovecot/sieve_after | 15 ++++++---------
     1 file changed, 6 insertions(+), 9 deletions(-)
    
    diff --git a/data/conf/dovecot/sieve_after b/data/conf/dovecot/sieve_after
    index 0b43dbcf..2e0cfe08 100644
    --- a/data/conf/dovecot/sieve_after
    +++ b/data/conf/dovecot/sieve_after
    @@ -9,16 +9,13 @@ if header :contains "X-Spam-Flag" "YES" {
     }
     
     if allof (
    -  envelope :detail :matches "to" "*",
    -  header :contains "X-Moo-Tag" "YES",
    -  mailboxexists "INBOX/${s}"
    -  ) {
    -    fileinto "INBOX/${s}";
    -}
    -elsif allof (
       envelope :detail :matches "to" "*",
       header :contains "X-Moo-Tag" "YES"
       ) {
    -    set :lower "s" "${1}";
    -    fileinto :create "INBOX/${s}";
    +  set :lower :upperfirst "tag" "${1}";
    +  if mailboxexists "INBOX/${1}" {
    +    fileinto "INBOX/${1}";
    +  } else {
    +    fileinto :create "INBOX/${tag}";
    +  }
     }
    
    From 3b80a1af371d9b614ffc9a3bd1926a5447d44c5d Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Mon, 8 May 2017 00:27:35 +0200
    Subject: [PATCH 17/49] Change admin layout, add Postfix logs
    
    ---
     data/web/admin.php                 | 409 ++++++++++++++++-------------
     data/web/css/admin.css             |   5 +-
     data/web/inc/functions.inc.php     |   5 +-
     data/web/inc/prerequisites.inc.php |   4 +-
     data/web/js/admin.js               | 139 ++++++++--
     data/web/lang/lang.de.php          |   5 +
     data/web/lang/lang.en.php          |   5 +
     7 files changed, 351 insertions(+), 221 deletions(-)
    
    diff --git a/data/web/admin.php b/data/web/admin.php
    index 6c7033e5..2c27e805 100644
    --- a/data/web/admin.php
    +++ b/data/web/admin.php
    @@ -7,9 +7,21 @@ $_SESSION['return_to'] = $_SERVER['REQUEST_URI'];
     $tfa_data = get_tfa();
     ?>
     <div class="container">
    -  <h4><span class="glyphicon glyphicon-user" aria-hidden="true"></span> <?=$lang['admin']['access'];?></h4>
     
    -  <div class="panel-group">
    +  <ul class="nav nav-tabs" role="tablist">
    +    <li role="presentation" class="active">
    +      <a href="#tab-access" aria-controls="tab-access" role="tab" data-toggle="tab"><?=$lang['admin']['access'];?></a>
    +    </li>
    +    <li role="presentation">
    +      <a href="#tab-config" aria-controls="tab-config" role="tab" data-toggle="tab"><?=$lang['admin']['configuration'];?></a>
    +    </li>
    +    <li role="presentation">
    +      <a href="#tab-logs" aria-controls="tab-logs" role="tab" data-toggle="tab"><?=$lang['admin']['logs'];?></a>
    +    </li>
    +  </ul>
    +
    +  <div class="tab-content" style="padding-top:20px">
    +  <div role="tabpanel" class="tab-pane active" id="tab-access">
         <div class="panel panel-danger">
           <div class="panel-heading"><?=$lang['admin']['admin_details'];?></div>
           <div class="panel-body">
    @@ -138,207 +150,228 @@ $tfa_data = get_tfa();
         </div>
       </div>
     
    -  <h4><span class="glyphicon glyphicon-wrench" aria-hidden="true"></span> <?=$lang['admin']['configuration'];?></h4>
     
    -  <div class="panel-group">
    -
    -  <div class="panel panel-default">
    -  <div class="panel-heading"><?=$lang['admin']['dkim_keys'];?></div>
    -  <div class="panel-body">
    -    <?php
    -    foreach(mailbox_get_domains() as $domain) {
    -        if (!empty($dkim = dkim_get_key_details($domain))) {
    -      ?>
    -        <div class="row">
    -          <div class="col-xs-3">
    -            <p>Domain: <strong><?=htmlspecialchars($domain);?></strong><br />
    -              <span class="label label-success"><?=$lang['admin']['dkim_key_valid'];?></span>
    -              <span class="label label-primary">Selector '<?=$dkim['dkim_selector'];?>'</span>
    -              <span class="label label-info"><?=$dkim['length'];?> bit</span>
    -            </p>
    -          </div>
    -          <div class="col-xs-8">
    -              <pre><?=$dkim['dkim_txt'];?></pre>
    -          </div>
    -          <div class="col-xs-1">
    -            <form class="form-inline" method="post">
    -              <input type="hidden" name="domain" value="<?=$domain;?>">
    -              <input type="hidden" name="dkim_delete_key" value="1">
    -                <a href="#" onclick="$(this).closest('form').submit()" data-toggle="tooltip" data-placement="top" title="<?=$lang['user']['delete_now'];?>"><span class="glyphicon glyphicon-remove"></span></a>
    -            </form>
    -          </div>
    -        </div>
    -      <?php
    -      }
    -      else {
    -      ?>
    -      <div class="row">
    -        <div class="col-xs-3">
    -          <p>Domain: <strong><?=htmlspecialchars($domain);?></strong><br /><span class="label label-danger"><?=$lang['admin']['dkim_key_missing'];?></span></p>
    -        </div>
    -        <div class="col-xs-8"><pre>-</pre></div>
    -        <div class="col-xs-1">&nbsp;</div>
    -      </div>
    -      <?php
    -      }
    -      foreach(mailbox_get_alias_domains($domain) as $alias_domain) {
    -        if (!empty($dkim = dkim_get_key_details($alias_domain))) {
    -        ?>
    +  <div role="tabpanel" class="tab-pane" id="tab-config">
    +    <div class="panel panel-default">
    +      <div class="panel-heading"><?=$lang['admin']['dkim_keys'];?></div>
    +      <div class="panel-body">
    +        <?php
    +        foreach(mailbox_get_domains() as $domain) {
    +            if (!empty($dkim = dkim_get_key_details($domain))) {
    +          ?>
    +            <div class="row">
    +              <div class="col-xs-3">
    +                <p>Domain: <strong><?=htmlspecialchars($domain);?></strong><br />
    +                  <span class="label label-success"><?=$lang['admin']['dkim_key_valid'];?></span>
    +                  <span class="label label-primary">Selector '<?=$dkim['dkim_selector'];?>'</span>
    +                  <span class="label label-info"><?=$dkim['length'];?> bit</span>
    +                </p>
    +              </div>
    +              <div class="col-xs-8">
    +                  <pre><?=$dkim['dkim_txt'];?></pre>
    +              </div>
    +              <div class="col-xs-1">
    +                <form class="form-inline" method="post">
    +                  <input type="hidden" name="domain" value="<?=$domain;?>">
    +                  <input type="hidden" name="dkim_delete_key" value="1">
    +                    <a href="#" onclick="$(this).closest('form').submit()" data-toggle="tooltip" data-placement="top" title="<?=$lang['user']['delete_now'];?>"><span class="glyphicon glyphicon-remove"></span></a>
    +                </form>
    +              </div>
    +            </div>
    +          <?php
    +          }
    +          else {
    +          ?>
               <div class="row">
    -            <div class="col-xs-offset-1 col-xs-2">
    -              <p><small>↳ Alias-Domain: <strong><?=htmlspecialchars($alias_domain);?></strong><br /></small>
    -                <span class="label label-success"><?=$lang['admin']['dkim_key_valid'];?></span>
    -                <span class="label label-primary">Selector '<?=$dkim['dkim_selector'];?>'</span>
    -                <span class="label label-info"><?=$dkim['length'];?> bit</span>
    -            </p>
    -            </div>
    -            <div class="col-xs-8">
    -              <pre><?=$dkim['dkim_txt'];?></pre>
    -            </div>
    -            <div class="col-xs-1">
    -              <form class="form-inline" method="post">
    -                <input type="hidden" name="domain" value="<?=$alias_domain;?>">
    -                <input type="hidden" name="dkim_delete_key" value="1">
    -                <a href="#" onclick="$(this).closest('form').submit()" data-toggle="tooltip" data-placement="top" title="<?=$lang['user']['delete_now'];?>"><span class="glyphicon glyphicon-remove"></span></a>
    -              </form>
    +            <div class="col-xs-3">
    +              <p>Domain: <strong><?=htmlspecialchars($domain);?></strong><br /><span class="label label-danger"><?=$lang['admin']['dkim_key_missing'];?></span></p>
                 </div>
    +            <div class="col-xs-8"><pre>-</pre></div>
    +            <div class="col-xs-1">&nbsp;</div>
               </div>
    -        <?php
    -        }
    -        else {
    -        ?>
    -        <div class="row">
    -          <div class="col-xs-2 col-xs-offset-1">
    -            <p><small>↳ Alias-Domain: <strong><?=htmlspecialchars($alias_domain);?></strong><br /></small><span class="label label-danger"><?=$lang['admin']['dkim_key_missing'];?></span></p>
    -          </div>
    -        <div class="col-xs-8"><pre>-</pre></div>
    -        <div class="col-xs-1">&nbsp;</div>
    -        </div>
    -        <?php
    -        }
    -      }
    -    }
    -    foreach(dkim_get_blind_keys() as $blind) {
    -      if (!empty($dkim = dkim_get_key_details($blind))) {
    -      ?>
    -        <div class="row">
    -          <div class="col-xs-3">
    -            <p>Domain: <strong><?=htmlspecialchars($blind);?></strong><br />
    -              <span class="label label-warning"><?=$lang['admin']['dkim_key_unused'];?></span>
    -              <span class="label label-primary">Selector '<?=$dkim['dkim_selector'];?>'</span>
    -              <span class="label label-info"><?=$dkim['length'];?> bit</span>
    -            </p>
    -            </div>
    -            <div class="col-xs-8">
    -              <pre><?=$dkim['dkim_txt'];?></pre>
    -            </div>
    -            <div class="col-xs-1">
    -              <form class="form-inline" method="post">
    -                <input type="hidden" name="domain" value="<?=$blind;?>">
    -                <input type="hidden" name="dkim_delete_key" value="1">
    -                <a href="#" onclick="$(this).closest('form').submit()" data-toggle="tooltip" data-placement="top" title="<?=$lang['user']['delete_now'];?>"><span class="glyphicon glyphicon-remove"></span></a>
    -              </form>
    -            </div>
    -        </div>
    -      <?php
    -      }
    -    }
    -    ?>
    -    <legend style="margin-top:40px"><?=$lang['admin']['dkim_add_key'];?></legend>
    -    <form class="form-inline" role="form" method="post">
    -      <div class="form-group">
    -        <label for="domain">Domain</label>
    -        <input class="form-control" id="domain" name="domain" placeholder="example.org" required>
    -      </div>
    -      <div class="form-group">
    -        <label for="domain">Selector</label>
    -        <input class="form-control" id="dkim_selector" name="dkim_selector" value="dkim" required>
    -      </div>
    -      <div class="form-group">
    -        <select data-width="200px" class="form-control" id="key_size" name="key_size" title="<?=$lang['admin']['dkim_key_length'];?>" required>
    -          <option data-subtext="bits">1024</option>
    -          <option data-subtext="bits">2048</option>
    -        </select>
    -      </div>
    -      <button type="submit" name="dkim_add_key" class="btn btn-default"><span class="glyphicon glyphicon-plus"></span> <?=$lang['admin']['add'];?></button>
    -    </form>
    -  </div>
    -  </div>
    -  
    -  <div class="panel panel-default">
    -    <div class="panel-heading"><?=$lang['admin']['forwarding_hosts'];?></div>
    -    <div class="panel-body">
    -      <p style="margin-bottom:40px"><?=$lang['admin']['forwarding_hosts_hint'];?></p>
    -      <form method="post">
    -        <div class="table-responsive">
    -        <table class="table table-striped" id="forwardinghoststable">
    -          <thead>
    -          <tr>
    -            <th style="min-width: 100px;"><?=$lang['edit']['host'];?></th>
    -            <th style="min-width: 100px;"><?=$lang['edit']['source'];?></th>
    -            <th style="text-align: right; min-width: 200px;"><?=$lang['admin']['action'];?></th>
    -          </tr>
    -          </thead>
    -          <tbody>
    -            <?php
    -            $forwarding_hosts = get_forwarding_hosts();
    -            if ($forwarding_hosts) {
    -              foreach ($forwarding_hosts as $host) {
    -                $source = $host->source;
    -                $host = $host->host;
    -              ?>
    -              <tr id="data">
    -                <td><?=htmlspecialchars(strtolower($host));?></td>
    -                <td><?=htmlspecialchars(strtolower($source));?></td>
    -                <td style="text-align: right;">
    -                  <div class="btn-group">
    -                    <a href="delete.php?forwardinghost=<?=$host;?>" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> <?=$lang['admin']['remove'];?></a>
    -                  </div>
    -                </td>
    -                </td>
    -              </tr>
    -
    -              <?php
    -              }
    -            } else {
    +          <?php
    +          }
    +          foreach(mailbox_get_alias_domains($domain) as $alias_domain) {
    +            if (!empty($dkim = dkim_get_key_details($alias_domain))) {
                 ?>
    -              <tr id="no-data"><td colspan="4" style="text-align: center; font-style: italic;"><?=$lang['admin']['no_record'];?></td></tr>
    +              <div class="row">
    +                <div class="col-xs-offset-1 col-xs-2">
    +                  <p><small>↳ Alias-Domain: <strong><?=htmlspecialchars($alias_domain);?></strong><br /></small>
    +                    <span class="label label-success"><?=$lang['admin']['dkim_key_valid'];?></span>
    +                    <span class="label label-primary">Selector '<?=$dkim['dkim_selector'];?>'</span>
    +                    <span class="label label-info"><?=$dkim['length'];?> bit</span>
    +                </p>
    +                </div>
    +                <div class="col-xs-8">
    +                  <pre><?=$dkim['dkim_txt'];?></pre>
    +                </div>
    +                <div class="col-xs-1">
    +                  <form class="form-inline" method="post">
    +                    <input type="hidden" name="domain" value="<?=$alias_domain;?>">
    +                    <input type="hidden" name="dkim_delete_key" value="1">
    +                    <a href="#" onclick="$(this).closest('form').submit()" data-toggle="tooltip" data-placement="top" title="<?=$lang['user']['delete_now'];?>"><span class="glyphicon glyphicon-remove"></span></a>
    +                  </form>
    +                </div>
    +              </div>
                 <?php
                 }
    +            else {
                 ?>
    -          </tbody>
    -        </table>
    -        </div>
    -      </form>
    -      <legend><?=$lang['admin']['add_forwarding_host'];?></legend>
    -      <p class="help-block"><?=$lang['admin']['forwarding_hosts_add_hint'];?></p>
    -      <form class="form-horizontal" role="form" method="post">
    -        <div class="form-group">
    -          <label class="control-label col-sm-2" for="hostname"><?=$lang['edit']['host'];?>:</label>
    -          <div class="col-sm-10">
    -            <input type="text" class="form-control" name="hostname" id="hostname" required>
    +            <div class="row">
    +              <div class="col-xs-2 col-xs-offset-1">
    +                <p><small>↳ Alias-Domain: <strong><?=htmlspecialchars($alias_domain);?></strong><br /></small><span class="label label-danger"><?=$lang['admin']['dkim_key_missing'];?></span></p>
    +              </div>
    +            <div class="col-xs-8"><pre>-</pre></div>
    +            <div class="col-xs-1">&nbsp;</div>
    +            </div>
    +            <?php
    +            }
    +          }
    +        }
    +        foreach(dkim_get_blind_keys() as $blind) {
    +          if (!empty($dkim = dkim_get_key_details($blind))) {
    +          ?>
    +            <div class="row">
    +              <div class="col-xs-3">
    +                <p>Domain: <strong><?=htmlspecialchars($blind);?></strong><br />
    +                  <span class="label label-warning"><?=$lang['admin']['dkim_key_unused'];?></span>
    +                  <span class="label label-primary">Selector '<?=$dkim['dkim_selector'];?>'</span>
    +                  <span class="label label-info"><?=$dkim['length'];?> bit</span>
    +                </p>
    +                </div>
    +                <div class="col-xs-8">
    +                  <pre><?=$dkim['dkim_txt'];?></pre>
    +                </div>
    +                <div class="col-xs-1">
    +                  <form class="form-inline" method="post">
    +                    <input type="hidden" name="domain" value="<?=$blind;?>">
    +                    <input type="hidden" name="dkim_delete_key" value="1">
    +                    <a href="#" onclick="$(this).closest('form').submit()" data-toggle="tooltip" data-placement="top" title="<?=$lang['user']['delete_now'];?>"><span class="glyphicon glyphicon-remove"></span></a>
    +                  </form>
    +                </div>
    +            </div>
    +          <?php
    +          }
    +        }
    +        ?>
    +        <legend style="margin-top:40px"><?=$lang['admin']['dkim_add_key'];?></legend>
    +        <form class="form-inline" role="form" method="post">
    +          <div class="form-group">
    +            <label for="domain">Domain</label>
    +            <input class="form-control" id="domain" name="domain" placeholder="example.org" required>
               </div>
    -        </div>
    -        <div class="form-group">
    -          <div class="col-sm-offset-2 col-sm-10">
    -            <button type="submit" name="add_forwarding_host" class="btn btn-default"><?=$lang['admin']['add'];?></button>
    +          <div class="form-group">
    +            <label for="domain">Selector</label>
    +            <input class="form-control" id="dkim_selector" name="dkim_selector" value="dkim" required>
               </div>
    -        </div>
    -      </form>
    +          <div class="form-group">
    +            <select data-width="200px" class="form-control" id="key_size" name="key_size" title="<?=$lang['admin']['dkim_key_length'];?>" required>
    +              <option data-subtext="bits">1024</option>
    +              <option data-subtext="bits">2048</option>
    +            </select>
    +          </div>
    +          <button type="submit" name="dkim_add_key" class="btn btn-default"><span class="glyphicon glyphicon-plus"></span> <?=$lang['admin']['add'];?></button>
    +        </form>
    +      </div>
         </div>
    -  </div>
    -  </div>
    -
    -  <h4><span class="glyphicon glyphicon-book" aria-hidden="true"></span> Mail Logs</h4>
    -  <div class="panel-group">
    +    
         <div class="panel panel-default">
    -    <div class="panel-heading">Logs</div>
    -    <div class="panel-body">
    -      <div class="table-responsive">
    -        <table class="table table-striped" id="dovecot_log"></table>
    +      <div class="panel-heading"><?=$lang['admin']['forwarding_hosts'];?></div>
    +      <div class="panel-body">
    +        <p style="margin-bottom:40px"><?=$lang['admin']['forwarding_hosts_hint'];?></p>
    +        <form method="post">
    +          <div class="table-responsive">
    +          <table class="table table-striped" id="forwardinghoststable">
    +            <thead>
    +            <tr>
    +              <th style="min-width: 100px;"><?=$lang['edit']['host'];?></th>
    +              <th style="min-width: 100px;"><?=$lang['edit']['source'];?></th>
    +              <th style="text-align: right; min-width: 200px;"><?=$lang['admin']['action'];?></th>
    +            </tr>
    +            </thead>
    +            <tbody>
    +              <?php
    +              $forwarding_hosts = get_forwarding_hosts();
    +              if ($forwarding_hosts) {
    +                foreach ($forwarding_hosts as $host) {
    +                  $source = $host->source;
    +                  $host = $host->host;
    +                ?>
    +                <tr id="data">
    +                  <td><?=htmlspecialchars(strtolower($host));?></td>
    +                  <td><?=htmlspecialchars(strtolower($source));?></td>
    +                  <td style="text-align: right;">
    +                    <div class="btn-group">
    +                      <a href="delete.php?forwardinghost=<?=$host;?>" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> <?=$lang['admin']['remove'];?></a>
    +                    </div>
    +                  </td>
    +                  </td>
    +                </tr>
    +
    +                <?php
    +                }
    +              } else {
    +              ?>
    +                <tr id="no-data"><td colspan="4" style="text-align: center; font-style: italic;"><?=$lang['admin']['no_record'];?></td></tr>
    +              <?php
    +              }
    +              ?>
    +            </tbody>
    +          </table>
    +          </div>
    +        </form>
    +        <legend><?=$lang['admin']['add_forwarding_host'];?></legend>
    +        <p class="help-block"><?=$lang['admin']['forwarding_hosts_add_hint'];?></p>
    +        <form class="form-horizontal" role="form" method="post">
    +          <div class="form-group">
    +            <label class="control-label col-sm-2" for="hostname"><?=$lang['edit']['host'];?>:</label>
    +            <div class="col-sm-10">
    +              <input type="text" class="form-control" name="hostname" id="hostname" required>
    +            </div>
    +          </div>
    +          <div class="form-group">
    +            <div class="col-sm-offset-2 col-sm-10">
    +              <button type="submit" name="add_forwarding_host" class="btn btn-default"><?=$lang['admin']['add'];?></button>
    +            </div>
    +          </div>
    +        </form>
           </div>
         </div>
       </div>
    +
    +  <div role="tabpanel" class="tab-pane" id="tab-logs">
    +    <div class="panel panel-default">
    +      <div class="panel-heading">Dovecot
    +        <div class="btn-group pull-right">
    +          <a class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown" href="#"><?=$lang['admin']['action'];?> <span class="caret"></span></a>
    +          <ul class="dropdown-menu">
    +            <li><a href="#" id="refresh_dovecot_log"><?=$lang['admin']['refresh'];?></a></li>
    +          </ul>
    +        </div>
    +      </div>
    +      <div class="panel-body">
    +        <div class="table-responsive">
    +          <table class="table table-striped" id="dovecot_log"></table>
    +        </div>
    +      </div>
    +    </div>
    +    <div class="panel panel-default">
    +      <div class="panel-heading">Postfix
    +        <div class="btn-group pull-right">
    +          <a class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown" href="#"><?=$lang['admin']['action'];?> <span class="caret"></span></a>
    +          <ul class="dropdown-menu">
    +            <li><a href="#" id="refresh_postfix_log"><?=$lang['admin']['refresh'];?></a></li>
    +          </ul>
    +        </div>
    +      </div>
    +      <div class="panel-body">
    +        <div class="table-responsive">
    +          <table class="table table-striped" id="postfix_log"></table>
    +        </div>
    +      </div>
    +    </div>
    +  </div>
    +
       </div>
     </div> <!-- /container -->
     <script type='text/javascript'>
    diff --git a/data/web/css/admin.css b/data/web/css/admin.css
    index 61f23763..81f5a7b4 100644
    --- a/data/web/css/admin.css
    +++ b/data/web/css/admin.css
    @@ -10,4 +10,7 @@ table.footable>tbody>tr.footable-empty>td {
     }
     .table-responsive {
       overflow: visible !important;
    -}
    \ No newline at end of file
    +}
    +body {
    +  overflow-y:scroll;
    +}
    diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php
    index d4f7dcc5..ba970063 100644
    --- a/data/web/inc/functions.inc.php
    +++ b/data/web/inc/functions.inc.php
    @@ -5202,7 +5202,10 @@ function get_logs($container, $lines = 100) {
       }
       if ($container == "postfix-mailcow") {
         if ($data = $redis->lRange('POSTFIX_MAILLOG', 1, $lines)) {
    -      return $data;
    +      foreach ($data as $json_line) {
    +        $data_array[] = json_decode($json_line, true);
    +      }
    +      return $data_array;
         }
       }
       return false;
    diff --git a/data/web/inc/prerequisites.inc.php b/data/web/inc/prerequisites.inc.php
    index 902b46af..6b9126fe 100644
    --- a/data/web/inc/prerequisites.inc.php
    +++ b/data/web/inc/prerequisites.inc.php
    @@ -21,8 +21,8 @@ $csrfProtector = new csrfProtector;
     class mailcowCsrfProtector extends csrfprotector {
       public static function logCSRFattack() {
         $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => 'CSRF violation'
    +      'type' => 'warning',
    +      'msg' => 'CSRF violation, please try again.'
         );
       }
     }
    diff --git a/data/web/js/admin.js b/data/web/js/admin.js
    index 0b9d4e7a..db3b8bae 100644
    --- a/data/web/js/admin.js
    +++ b/data/web/js/admin.js
    @@ -39,37 +39,118 @@ $(document).ready(function() {
           });
         }
       });
    -  $.ajax({
    -    dataType: 'json',
    -    url: '/api/v1/get/logs/dovecot/all',
    -    jsonp: false,
    -    error: function () {
    -      alert('Cannot draw dovecot log table');
    -    },
    -    success: function (data) {
    -      $('#dovecot_log').footable({
    -        "columns": [
    -          {"name":"time","title":"time"},
    -          {"name":"program","title":"program"},
    -          {"name":"priority","title":"priority"},
    -          {"name":"message","title":"message"},
    -        ],
    -        "rows": data,
    -        "empty": lang.empty,
    -        "paging": {
    -          "enabled": true,
    -          "limit": 5,
    -          "size": pagination_size
    +  $("#refresh_dovecot_log").on('click', function(e) {
    +      function unix_time_format(tm) {
    +        var date = new Date(tm ? tm * 1000 : 0);
    +        return date.toLocaleString();
    +      }
    +      e.preventDefault();
    +      if (typeof ft_dovecot_logs != 'undefined') {
    +        ft_dovecot_logs.destroy();
    +      }
    +      $.ajax({
    +        dataType: 'json',
    +        url: '/api/v1/get/logs/dovecot/1000',
    +        jsonp: false,
    +        error: function () {
    +          alert('Cannot draw dovecot log table');
             },
    -        "filtering": {
    -          "enabled": true,
    -          "position": "left",
    -          "placeholder": lang.filter_table
    -        },
    -        "sorting": {
    -          "enabled": true
    +        success: function (data) {
    +          $.each(data, function (i, item) {
    +            var danger_class = ["emerg", "alert", "crit"];
    +            var warning_class = ["warning"];
    +            var info_class = ["notice", "info", "debug"];
    +            if (jQuery.inArray(item.priority, danger_class) !== -1) {
    +              item.priority = '<span class="label label-danger">' + item.priority + '</span>';
    +            } 
    +            else if (jQuery.inArray(item.priority, warning_class) !== -1) {
    +              item.priority = '<span class="label label-warning">' + item.priority + '</span>';
    +            }
    +            else if (jQuery.inArray(item.priority, info_class) !== -1) {
    +              item.priority = '<span class="label label-info">' + item.priority + '</span>';
    +            }
    +          });
    +          ft_dovecot_logs = FooTable.init("#dovecot_log", {
    +            "columns": [
    +              {"name":"time","formatter":function unix_time_format(tm) {var date = new Date(tm ? tm * 1000 : 0); return date.toLocaleString();},"title":lang.time,"style":{"width":"170px"}},
    +              {"name":"priority","title":lang.priority,"style":{"width":"80px"}},
    +              {"name":"message","title":lang.message},
    +            ],
    +            "rows": data,
    +            "empty": lang.empty,
    +            "paging": {
    +              "enabled": true,
    +              "limit": 5,
    +              "size": pagination_size
    +            },
    +            "filtering": {
    +              "enabled": true,
    +              "position": "left",
    +              "placeholder": lang.filter_table
    +            },
    +            "sorting": {
    +              "enabled": true
    +            }
    +          });
             }
           });
    -    }
       });
    +  $("#refresh_postfix_log").on('click', function(e) {
    +      function unix_time_format(tm) {
    +        var date = new Date(tm ? tm * 1000 : 0);
    +        return date.toLocaleString();
    +      }
    +      e.preventDefault();
    +      if (typeof ft_postfix_logs != 'undefined') {
    +        ft_postfix_logs.destroy();
    +      }
    +      $.ajax({
    +        dataType: 'json',
    +        url: '/api/v1/get/logs/postfix/1000',
    +        jsonp: false,
    +        error: function () {
    +          alert('Cannot draw postfix log table');
    +        },
    +        success: function (data) {
    +          $.each(data, function (i, item) {
    +            var danger_class = ["emerg", "alert", "crit"];
    +            var warning_class = ["warning"];
    +            var info_class = ["notice", "info", "debug"];
    +            if (jQuery.inArray(item.priority, danger_class) !== -1) {
    +              item.priority = '<span class="label label-danger">' + item.priority + '</span>';
    +            } 
    +            else if (jQuery.inArray(item.priority, warning_class) !== -1) {
    +              item.priority = '<span class="label label-warning">' + item.priority + '</span>';
    +            }
    +            else if (jQuery.inArray(item.priority, info_class) !== -1) {
    +              item.priority = '<span class="label label-info">' + item.priority + '</span>';
    +            }
    +          });
    +          ft_postfix_logs = FooTable.init("#postfix_log", {
    +            "columns": [
    +              {"name":"time","formatter":function unix_time_format(tm) {var date = new Date(tm ? tm * 1000 : 0); return date.toLocaleString();},"title":lang.time,"style":{"width":"170px"}},
    +              {"name":"priority","title":lang.priority,"style":{"width":"80px"}},
    +              {"name":"message","title":lang.message},
    +            ],
    +            "rows": data,
    +            "empty": lang.empty,
    +            "paging": {
    +              "enabled": true,
    +              "limit": 5,
    +              "size": pagination_size
    +            },
    +            "filtering": {
    +              "enabled": true,
    +              "position": "left",
    +              "placeholder": lang.filter_table
    +            },
    +            "sorting": {
    +              "enabled": true
    +            }
    +          });
    +        }
    +      });
    +  });
    +  $("#refresh_dovecot_log").trigger('click');
    +  $("#refresh_postfix_log").trigger('click');
     });
    \ No newline at end of file
    diff --git a/data/web/lang/lang.de.php b/data/web/lang/lang.de.php
    index 947bb267..0e6f67c4 100644
    --- a/data/web/lang/lang.de.php
    +++ b/data/web/lang/lang.de.php
    @@ -471,6 +471,11 @@ $lang['admin']['set_rr_failed'] = 'Kann Postfix Restriktionen nicht setzen';
     $lang['admin']['no_record'] = 'Kein Eintrag';
     $lang['admin']['filter_table'] = 'Tabelle Filtern';
     $lang['admin']['empty'] = 'Keine Einträge vorhanden';
    +$lang['admin']['time'] = 'Zeit';
    +$lang['admin']['priority'] = 'Gewichtung';
    +$lang['admin']['refresh'] = 'Neu laden';
    +$lang['admin']['logs'] = 'Logs';
    +$lang['admin']['message'] = 'Nachricht';
     $lang['admin']['forwarding_hosts'] = 'Weiterleitungs-Hosts';
     $lang['admin']['forwarding_hosts_hint'] = 'Eingehende Nachrichten werden von den hier gelisteten Hosts bedingungslos akzeptiert. Diese Hosts werden dann nicht mit DNSBLs abgeglichen oder Greylisting unterworfen. Von ihnen empfangener Spam wird nie abgelehnt und immer in den Spam-Ordner einsortiert. Die übliche Verwendung für diese Funktion ist, um Mailserver anzugeben, auf denen eine Weiterleitung zu Ihrem Mailcow-Server eingerichtet wurde.';
     $lang['admin']['forwarding_hosts_add_hint'] = 'Sie können entweder IPv4/IPv6-Adressen, Netzwerke in CIDR-Notation, Hostnamen (die zu IP-Adressen aufgelöst werden), oder Domainnamen (die zu IP-Adressen aufgelöst werden, indem ihr SPF-Record abgefragt wird oder, in dessen Abwesenheit, ihre MX-Records) angeben.';
    diff --git a/data/web/lang/lang.en.php b/data/web/lang/lang.en.php
    index ea573f49..1d658308 100644
    --- a/data/web/lang/lang.en.php
    +++ b/data/web/lang/lang.en.php
    @@ -483,6 +483,11 @@ $lang['admin']['set_rr_failed'] = 'Cannot set Postfix restrictions';
     $lang['admin']['no_record'] = 'No record';
     $lang['admin']['filter_table'] = 'Filter table';
     $lang['admin']['empty'] = 'No results';
    +$lang['admin']['time'] = 'Time';
    +$lang['admin']['priority'] = 'Priority';
    +$lang['admin']['message'] = 'Message';
    +$lang['admin']['refresh'] = 'Refresh';
    +$lang['admin']['logs'] = 'Logs';
     $lang['admin']['forwarding_hosts'] = 'Forwarding Hosts';
     $lang['admin']['forwarding_hosts_hint'] = 'Incoming messages are unconditionally accepted from any hosts listed here. These hosts are then not checked against DNSBLs or subjected to greylisting. Spam received from them is never rejected and always filed into the Junk folder. The most common use for this is to specify mail servers on which you have set up a rule that forwards incoming emails to your Mailcow server.';
     $lang['admin']['forwarding_hosts_add_hint'] = 'You can either specify IPv4/IPv6 addresses, networks in CIDR notation, host names (which will be resolved to IP addresses), or domain names (which will be resolved to IP addresses by querying SPF records or, in their absence, MX records).';
    
    From 7931b00fa0225e707f62a1e478d032f194380e39 Mon Sep 17 00:00:00 2001
    From: Michael Kuron <mkuron@users.noreply.github.com>
    Date: Mon, 8 May 2017 07:46:36 +0200
    Subject: [PATCH 18/49] Fix column width
    
    ---
     data/web/admin.php | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/data/web/admin.php b/data/web/admin.php
    index 15eed2c3..df442b68 100644
    --- a/data/web/admin.php
    +++ b/data/web/admin.php
    @@ -286,7 +286,7 @@ $tfa_data = get_tfa();
                 <tr>
                   <th style="min-width: 100px;"><?=$lang['edit']['host'];?></th>
                   <th style="min-width: 100px;"><?=$lang['edit']['source'];?></th>
    -              <th style="min-width: 100px;"><?=$lang['user']['spamfilter'];?></th>
    +              <th><?=$lang['user']['spamfilter'];?></th>
                   <th style="text-align: right; min-width: 200px;"><?=$lang['admin']['action'];?></th>
                 </tr>
                 </thead>
    
    From a267a4ad71be3c824e3f36c6899a68f6c7fa8796 Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Mon, 8 May 2017 14:11:30 +0200
    Subject: [PATCH 19/49] Use DKIM selector from Redis
    
    ---
     data/Dockerfiles/rspamd/Dockerfile           |   2 +-
     data/Dockerfiles/rspamd/dkim_signing.lua     | 287 +++++++++++++++++++
     data/Dockerfiles/rspamd/docker-entrypoint.sh |  10 +
     3 files changed, 298 insertions(+), 1 deletion(-)
     create mode 100644 data/Dockerfiles/rspamd/dkim_signing.lua
     create mode 100755 data/Dockerfiles/rspamd/docker-entrypoint.sh
    
    diff --git a/data/Dockerfiles/rspamd/Dockerfile b/data/Dockerfiles/rspamd/Dockerfile
    index 46a97748..2a4ff29c 100644
    --- a/data/Dockerfiles/rspamd/Dockerfile
    +++ b/data/Dockerfiles/rspamd/Dockerfile
    @@ -13,7 +13,7 @@ RUN echo '.include $LOCAL_CONFDIR/local.d/rspamd.conf.local' > /etc/rspamd/rspam
     
     COPY settings.conf /etc/rspamd/modules.d/settings.conf
     COPY antivirus.conf /etc/rspamd/modules.d/antivirus.conf
    -
    +COPY dkim_signing.lua /usr/share/rspamd/lua/dkim_signing.lua
     RUN pip install -U oletools
     
     CMD /usr/bin/rspamd -f -u _rspamd -g _rspamd
    diff --git a/data/Dockerfiles/rspamd/dkim_signing.lua b/data/Dockerfiles/rspamd/dkim_signing.lua
    new file mode 100644
    index 00000000..1d713e3e
    --- /dev/null
    +++ b/data/Dockerfiles/rspamd/dkim_signing.lua
    @@ -0,0 +1,287 @@
    +--[[
    +Copyright (c) 2016, Andrew Lewis <nerf@judo.za.org>
    +Copyright (c) 2016, Vsevolod Stakhov <vsevolod@highsecure.ru>
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +]]--
    +
    +local rspamd_logger = require "rspamd_logger"
    +local rspamd_util = require "rspamd_util"
    +
    +if confighelp then
    +  return
    +end
    +
    +local settings = {
    +  allow_envfrom_empty = true,
    +  allow_hdrfrom_mismatch = false,
    +  allow_hdrfrom_mismatch_local = false,
    +  allow_hdrfrom_mismatch_sign_networks = false,
    +  allow_hdrfrom_multiple = false,
    +  allow_username_mismatch = false,
    +  auth_only = true,
    +  domain = {},
    +  path = string.format('%s/%s/%s', rspamd_paths['DBDIR'], 'dkim', '$domain.$selector.key'),
    +  sign_local = true,
    +  selector = 'dkim',
    +  symbol = 'DKIM_SIGNED',
    +  try_fallback = true,
    +  use_domain = 'header',
    +  use_esld = true,
    +  use_redis = false,
    +  key_prefix = 'dkim_keys', -- default hash name
    +}
    +
    +local E = {}
    +local N = 'dkim_signing'
    +local redis_params
    +
    +local function simple_template(tmpl, keys)
    +  local lpeg = require "lpeg"
    +
    +  local var_lit = lpeg.P { lpeg.R("az") + lpeg.R("AZ") + lpeg.R("09") + "_" }
    +  local var = lpeg.P { (lpeg.P("$") / "") * ((var_lit^1) / keys) }
    +  local var_braced = lpeg.P { (lpeg.P("${") / "") * ((var_lit^1) / keys) * (lpeg.P("}") / "") }
    +
    +  local template_grammar = lpeg.Cs((var + var_braced + 1)^0)
    +
    +  return lpeg.match(template_grammar, tmpl)
    +end
    +
    +local function dkim_signing_cb(task)
    +  local is_local, is_sign_networks
    +  local auser = task:get_user()
    +  local ip = task:get_from_ip()
    +  if ip and ip:is_local() then
    +    is_local = true
    +  end
    +  if settings.auth_only and not auser then
    +    if (settings.sign_networks and settings.sign_networks:get_key(ip)) then
    +      is_sign_networks = true
    +      rspamd_logger.debugm(N, task, 'mail is from address in sign_networks')
    +    elseif settings.sign_local and is_local then
    +      rspamd_logger.debugm(N, task, 'mail is from local address')
    +    else
    +      rspamd_logger.debugm(N, task, 'ignoring unauthenticated mail')
    +      return
    +    end
    +  end
    +  local efrom = task:get_from('smtp')
    +  if not settings.allow_envfrom_empty and
    +      #(((efrom or E)[1] or E).addr or '') == 0 then
    +    rspamd_logger.debugm(N, task, 'empty envelope from not allowed')
    +    return false
    +  end
    +  local hfrom = task:get_from('mime')
    +  if not settings.allow_hdrfrom_multiple and (hfrom or E)[2] then
    +    rspamd_logger.debugm(N, task, 'multiple header from not allowed')
    +    return false
    +  end
    +  local dkim_domain
    +  local hdom = ((hfrom or E)[1] or E).domain
    +  local edom = ((efrom or E)[1] or E).domain
    +  if hdom then
    +    hdom = hdom:lower()
    +  end
    +  if edom then
    +    edom = edom:lower()
    +  end
    +  if settings.use_domain_sign_networks and is_sign_networks then
    +    if settings.use_domain_sign_networks == 'header' then
    +      dkim_domain = hdom
    +    else
    +      dkim_domain = edom
    +    end
    +  elseif settings.use_domain_local and is_local then
    +    if settings.use_domain_local == 'header' then
    +      dkim_domain = hdom
    +    else
    +      dkim_domain = edom
    +    end
    +  else
    +    if settings.use_domain == 'header' then
    +      dkim_domain = hdom
    +    else
    +      dkim_domain = edom
    +    end
    +  end
    +  if not dkim_domain then
    +    rspamd_logger.debugm(N, task, 'could not extract dkim domain')
    +    return false
    +  end
    +  if settings.use_esld then
    +    dkim_domain = rspamd_util.get_tld(dkim_domain)
    +    if settings.use_domain == 'envelope' and hdom then
    +      hdom = rspamd_util.get_tld(hdom)
    +    elseif settings.use_domain == 'header' and edom then
    +      edom = rspamd_util.get_tld(edom)
    +    end
    +  end
    +  if edom and hdom and not settings.allow_hdrfrom_mismatch and hdom ~= edom then
    +    if settings.allow_hdrfrom_mismatch_local and is_local then
    +      rspamd_logger.debugm(N, task, 'domain mismatch allowed for local IP: %1 != %2', hdom, edom)
    +    elseif settings.allow_hdrfrom_mismatch_sign_networks and is_sign_networks then
    +      rspamd_logger.debugm(N, task, 'domain mismatch allowed for sign_networks: %1 != %2', hdom, edom)
    +    else
    +      rspamd_logger.debugm(N, task, 'domain mismatch not allowed: %1 != %2', hdom, edom)
    +      return false
    +    end
    +  end
    +  if auser and not settings.allow_username_mismatch then
    +    local udom = string.match(auser, '.*@(.*)')
    +    if not udom then
    +      rspamd_logger.debugm(N, task, 'couldnt find domain in username')
    +      return false
    +    end
    +    if settings.use_esld then
    +      udom = rspamd_util.get_tld(udom)
    +    end
    +    if udom ~= dkim_domain then
    +      rspamd_logger.debugm(N, task, 'user domain mismatch')
    +      return false
    +    end
    +  end
    +  local p = {}
    +  if settings.domain[dkim_domain] then
    +    p.selector = settings.domain[dkim_domain].selector
    +    p.key = settings.domain[dkim_domain].path
    +  end
    +  if not (p.key and p.selector) and not
    +    (settings.try_fallback or settings.use_redis or settings.selector_map or settings.path_map) then
    +    rspamd_logger.debugm(N, task, 'dkim unconfigured and fallback disabled')
    +    return false
    +  end
    +  if not p.key then
    +    if not settings.use_redis then
    +      p.key = settings.path
    +    end
    +  end
    +  if not p.selector then
    +    p.selector = settings.selector
    +  end
    +  p.domain = dkim_domain
    +
    +  if settings.selector_map then
    +    local data = settings.selector_map:get_key(dkim_domain)
    +    if data then
    +      p.selector = data
    +    end
    +  end
    +
    +  if settings.path_map then
    +    local data = settings.path_map:get_key(dkim_domain)
    +    if data then
    +      p.key = data
    +    end
    +  end
    +
    +  if settings.use_redis then
    +    local function try_redis_key(selector)
    +      p.key = nil
    +      p.selector = selector
    +      local rk = string.format('%s.%s', p.selector, p.domain)
    +      local function redis_key_cb(err, data)
    +        if err or type(data) ~= 'string' then
    +          rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM key for %s: %s",
    +            rk, err)
    +        else
    +          p.rawkey = data
    +          if rspamd_plugins.dkim.sign(task, p) then
    +            task:insert_result(settings.symbol, 1.0)
    +          end
    +        end
    +      end
    +      local ret = rspamd_redis_make_request(task,
    +        redis_params, -- connect params
    +        rk, -- hash key
    +        false, -- is write
    +        redis_key_cb, --callback
    +        'HGET', -- command
    +        {settings.key_prefix, rk} -- arguments
    +      )
    +      if not ret then
    +        rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM key for %s", rk)
    +      end
    +    end
    +    if settings.selector_prefix then
    +      rspamd_logger.infox(rspamd_config, "Using selector prefix %s for domain %s", settings.selector_prefix, p.domain);
    +      local function redis_selector_cb(err, data)
    +        if err or type(data) ~= 'string' then
    +          rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM selector for domain %s: %s", p.domain, err)
    +        else
    +          try_redis_key(data)
    +        end
    +      end
    +      local ret = rspamd_redis_make_request(task,
    +        redis_params, -- connect params
    +        p.domain, -- hash key
    +        false, -- is write
    +        redis_selector_cb, --callback
    +        'HGET', -- command
    +        {settings.selector_prefix, p.domain} -- arguments
    +      )
    +      if not ret then
    +        rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM selector for %s", p.domain)
    +      end
    +    else
    +      if not p.selector then
    +        rspamd_logger.errx(task, 'No selector specified')
    +        return false
    +      end
    +      try_redis_key(p.selector)
    +    end
    +  else
    +    if (p.key and p.selector) then
    +      p.key = simple_template(p.key, {domain = p.domain, selector = p.selector})
    +      return rspamd_plugins.dkim.sign(task, p)
    +    else
    +      rspamd_logger.infox(task, 'key path or dkim selector unconfigured; no signing')
    +      return false
    +    end
    +  end
    +end
    +
    +local opts =  rspamd_config:get_all_opt('dkim_signing')
    +if not opts then return end
    +for k,v in pairs(opts) do
    +  if k == 'sign_networks' then
    +    settings[k] = rspamd_map_add(N, k, 'radix', 'DKIM signing networks')
    +  elseif k == 'path_map' then
    +    settings[k] = rspamd_map_add(N, k, 'map', 'Paths to DKIM signing keys')
    +  elseif k == 'selector_map' then
    +    settings[k] = rspamd_map_add(N, k, 'map', 'DKIM selectors')
    +  else
    +    settings[k] = v
    +  end
    +end
    +if not (settings.use_redis or settings.path or settings.domain or settings.path_map or settings.selector_map) then
    +  rspamd_logger.infox(rspamd_config, 'mandatory parameters missing, disable dkim signing')
    +  return
    +end
    +if settings.use_redis then
    +  redis_params = rspamd_parse_redis_server('dkim_signing')
    +
    +  if not redis_params then
    +    rspamd_logger.errx(rspamd_config, 'no servers are specified, but module is configured to load keys from redis, disable dkim signing')
    +    return
    +  end
    +end
    +if settings.use_domain ~= 'header' and settings.use_domain ~= 'envelope' then
    +  rspamd_logger.errx(rspamd_config, "Value for 'use_domain' is invalid")
    +  settings.use_domain = 'header'
    +end
    +
    +rspamd_config:register_symbol({
    +  name = settings['symbol'],
    +  callback = dkim_signing_cb
    +})
    diff --git a/data/Dockerfiles/rspamd/docker-entrypoint.sh b/data/Dockerfiles/rspamd/docker-entrypoint.sh
    new file mode 100755
    index 00000000..c1101d94
    --- /dev/null
    +++ b/data/Dockerfiles/rspamd/docker-entrypoint.sh
    @@ -0,0 +1,10 @@
    +#!/bin/bash
    +set -e
    +
    +if [[ ! -d "/data/dkim/txt" || ! -d "/data/dkim/keys" ]] ; then	mkdir -p /data/dkim/{txt,keys} ; chown -R www-data:www-data /data/dkim; fi
    +if [[ $(stat -c %U /data/dkim/) != "www-data" ]] ; then chown -R www-data:www-data /data/dkim ; fi
    +
    +# Migrate domain table to redis
    +
    +
    +exec "$@"
    
    From 653d23a843cc981bc8847d815a0a46ab5498510b Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Mon, 8 May 2017 15:35:24 +0200
    Subject: [PATCH 20/49] Migrate some settings and DKIM keys to Redis when
     starting
    
    ---
     data/Dockerfiles/php-fpm/Dockerfile           |  8 ++-
     data/Dockerfiles/php-fpm/docker-entrypoint.sh | 53 +++++++++++++++++++
     2 files changed, 60 insertions(+), 1 deletion(-)
    
    diff --git a/data/Dockerfiles/php-fpm/Dockerfile b/data/Dockerfiles/php-fpm/Dockerfile
    index 9a059a45..ad03b8ad 100644
    --- a/data/Dockerfiles/php-fpm/Dockerfile
    +++ b/data/Dockerfiles/php-fpm/Dockerfile
    @@ -4,7 +4,13 @@ MAINTAINER Andre Peters <andre.peters@servercow.de>
     ENV DEBIAN_FRONTEND noninteractive
     
     RUN apt-get update \
    -        && apt-get install -y zlib1g-dev libicu-dev g++ libidn11-dev libxml2-dev
    +	&& apt-get install -y zlib1g-dev \
    +	libicu-dev \
    +	g++ \
    +	libidn11-dev \
    +	libxml2-dev \
    +	redis-tools \
    +	mysql-client
     
     RUN docker-php-ext-configure intl
     RUN docker-php-ext-install intl pdo pdo_mysql xmlrpc
    diff --git a/data/Dockerfiles/php-fpm/docker-entrypoint.sh b/data/Dockerfiles/php-fpm/docker-entrypoint.sh
    index 8f57a6d9..1e4d3fe6 100755
    --- a/data/Dockerfiles/php-fpm/docker-entrypoint.sh
    +++ b/data/Dockerfiles/php-fpm/docker-entrypoint.sh
    @@ -4,4 +4,57 @@ set -e
     if [[ ! -d "/data/dkim/txt" || ! -d "/data/dkim/keys" ]] ; then	mkdir -p /data/dkim/{txt,keys} ; chown -R www-data:www-data /data/dkim; fi
     if [[ $(stat -c %U /data/dkim/) != "www-data" ]] ; then chown -R www-data:www-data /data/dkim ; fi
     
    +# Wait for containers
    +
    +while ! mysqladmin ping --host mysql --silent; do
    +  sleep 2
    +done
    +
    +until [ $(redis-cli -h redis-mailcow PING) == "PONG" ]; do
    +  sleep 2
    +done
    +
    +# Migrate domain map
    +
    +declare -a DOMAIN_ARR
    +redis-cli -h redis-mailcow DEL DOMAIN_MAP
    +while read line
    +do
    +  DOMAIN_ARR+=("$line")
    +done < <(mysql -h mysql-mailcow -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain FROM domain" -Bs)
    +
    +if [[ ! -z ${DOMAIN_ARR} ]]; then
    +for domain in "${DOMAIN_ARR[@]}"; do
    +  redis-cli -h redis-mailcow HSET DOMAIN_MAP ${domain} 1
    +done
    +fi
    +
    +# Migrate tag settings map
    +
    +declare -a SUBJ_TAG_ARR
    +redis-cli -h redis-mailcow DEL SUBJ_TAG_ARR
    +while read line
    +do
    +  SUBJ_TAG_ARR+=("$line")
    +done < <(mysql -h mysql-mailcow -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT username FROM mailbox WHERE wants_tagged_subject='1'" -Bs)
    +
    +if [[ ! -z ${SUBJ_TAG_ARR} ]]; then
    +for user in "${SUBJ_TAG_ARR[@]}"; do
    +  redis-cli -h redis-mailcow HSET RCPT_WANTS_SUBJECT_TAG ${user} 1
    +  mysql -h mysql-mailcow -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "UPDATE mailbox SET wants_tagged_subject='2' WHERE username = '${user}'"
    +done
    +fi
    +
    +# Migrate DKIM keys
    +
    +for file in $(ls /data/dkim/keys/); do
    +  domain=${file%.dkim}
    +  if [[ -f /data/dkim/txt/${file} ]]; then
    +    redis-cli -h redis-mailcow HSET DKIM_PUB_KEYS "${domain}" "$(cat /data/dkim/keys/${domain})"
    +    redis-cli -h redis-mailcow HSET DKIM_PRIV_KEYS "${domain}" "$(cat /data/dkim/keys/${file})"
    +    redis-cli -h redis-mailcow HSET DKIM_SELECTORS "${domain}" "dkim.${domain}"
    +  fi
    +  rm /data/dkim/{keys,txt}/${file}
    +done
    +
     exec "$@"
    
    From a18bcce93d3826e6af145b2bd1eb062c2b7c8e6d Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Mon, 8 May 2017 15:38:03 +0200
    Subject: [PATCH 21/49] Minor style changes
    
    ---
     data/Dockerfiles/rspamd/dkim_signing.lua | 573 +++++++++++------------
     1 file changed, 286 insertions(+), 287 deletions(-)
    
    diff --git a/data/Dockerfiles/rspamd/dkim_signing.lua b/data/Dockerfiles/rspamd/dkim_signing.lua
    index 1d713e3e..b76a73ac 100644
    --- a/data/Dockerfiles/rspamd/dkim_signing.lua
    +++ b/data/Dockerfiles/rspamd/dkim_signing.lua
    @@ -1,287 +1,286 @@
    ---[[
    -Copyright (c) 2016, Andrew Lewis <nerf@judo.za.org>
    -Copyright (c) 2016, Vsevolod Stakhov <vsevolod@highsecure.ru>
    -
    -Licensed under the Apache License, Version 2.0 (the "License");
    -you may not use this file except in compliance with the License.
    -You may obtain a copy of the License at
    -
    -    http://www.apache.org/licenses/LICENSE-2.0
    -
    -Unless required by applicable law or agreed to in writing, software
    -distributed under the License is distributed on an "AS IS" BASIS,
    -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -See the License for the specific language governing permissions and
    -limitations under the License.
    -]]--
    -
    -local rspamd_logger = require "rspamd_logger"
    -local rspamd_util = require "rspamd_util"
    -
    -if confighelp then
    -  return
    -end
    -
    -local settings = {
    -  allow_envfrom_empty = true,
    -  allow_hdrfrom_mismatch = false,
    -  allow_hdrfrom_mismatch_local = false,
    -  allow_hdrfrom_mismatch_sign_networks = false,
    -  allow_hdrfrom_multiple = false,
    -  allow_username_mismatch = false,
    -  auth_only = true,
    -  domain = {},
    -  path = string.format('%s/%s/%s', rspamd_paths['DBDIR'], 'dkim', '$domain.$selector.key'),
    -  sign_local = true,
    -  selector = 'dkim',
    -  symbol = 'DKIM_SIGNED',
    -  try_fallback = true,
    -  use_domain = 'header',
    -  use_esld = true,
    -  use_redis = false,
    -  key_prefix = 'dkim_keys', -- default hash name
    -}
    -
    -local E = {}
    -local N = 'dkim_signing'
    -local redis_params
    -
    -local function simple_template(tmpl, keys)
    -  local lpeg = require "lpeg"
    -
    -  local var_lit = lpeg.P { lpeg.R("az") + lpeg.R("AZ") + lpeg.R("09") + "_" }
    -  local var = lpeg.P { (lpeg.P("$") / "") * ((var_lit^1) / keys) }
    -  local var_braced = lpeg.P { (lpeg.P("${") / "") * ((var_lit^1) / keys) * (lpeg.P("}") / "") }
    -
    -  local template_grammar = lpeg.Cs((var + var_braced + 1)^0)
    -
    -  return lpeg.match(template_grammar, tmpl)
    -end
    -
    -local function dkim_signing_cb(task)
    -  local is_local, is_sign_networks
    -  local auser = task:get_user()
    -  local ip = task:get_from_ip()
    -  if ip and ip:is_local() then
    -    is_local = true
    -  end
    -  if settings.auth_only and not auser then
    -    if (settings.sign_networks and settings.sign_networks:get_key(ip)) then
    -      is_sign_networks = true
    -      rspamd_logger.debugm(N, task, 'mail is from address in sign_networks')
    -    elseif settings.sign_local and is_local then
    -      rspamd_logger.debugm(N, task, 'mail is from local address')
    -    else
    -      rspamd_logger.debugm(N, task, 'ignoring unauthenticated mail')
    -      return
    -    end
    -  end
    -  local efrom = task:get_from('smtp')
    -  if not settings.allow_envfrom_empty and
    -      #(((efrom or E)[1] or E).addr or '') == 0 then
    -    rspamd_logger.debugm(N, task, 'empty envelope from not allowed')
    -    return false
    -  end
    -  local hfrom = task:get_from('mime')
    -  if not settings.allow_hdrfrom_multiple and (hfrom or E)[2] then
    -    rspamd_logger.debugm(N, task, 'multiple header from not allowed')
    -    return false
    -  end
    -  local dkim_domain
    -  local hdom = ((hfrom or E)[1] or E).domain
    -  local edom = ((efrom or E)[1] or E).domain
    -  if hdom then
    -    hdom = hdom:lower()
    -  end
    -  if edom then
    -    edom = edom:lower()
    -  end
    -  if settings.use_domain_sign_networks and is_sign_networks then
    -    if settings.use_domain_sign_networks == 'header' then
    -      dkim_domain = hdom
    -    else
    -      dkim_domain = edom
    -    end
    -  elseif settings.use_domain_local and is_local then
    -    if settings.use_domain_local == 'header' then
    -      dkim_domain = hdom
    -    else
    -      dkim_domain = edom
    -    end
    -  else
    -    if settings.use_domain == 'header' then
    -      dkim_domain = hdom
    -    else
    -      dkim_domain = edom
    -    end
    -  end
    -  if not dkim_domain then
    -    rspamd_logger.debugm(N, task, 'could not extract dkim domain')
    -    return false
    -  end
    -  if settings.use_esld then
    -    dkim_domain = rspamd_util.get_tld(dkim_domain)
    -    if settings.use_domain == 'envelope' and hdom then
    -      hdom = rspamd_util.get_tld(hdom)
    -    elseif settings.use_domain == 'header' and edom then
    -      edom = rspamd_util.get_tld(edom)
    -    end
    -  end
    -  if edom and hdom and not settings.allow_hdrfrom_mismatch and hdom ~= edom then
    -    if settings.allow_hdrfrom_mismatch_local and is_local then
    -      rspamd_logger.debugm(N, task, 'domain mismatch allowed for local IP: %1 != %2', hdom, edom)
    -    elseif settings.allow_hdrfrom_mismatch_sign_networks and is_sign_networks then
    -      rspamd_logger.debugm(N, task, 'domain mismatch allowed for sign_networks: %1 != %2', hdom, edom)
    -    else
    -      rspamd_logger.debugm(N, task, 'domain mismatch not allowed: %1 != %2', hdom, edom)
    -      return false
    -    end
    -  end
    -  if auser and not settings.allow_username_mismatch then
    -    local udom = string.match(auser, '.*@(.*)')
    -    if not udom then
    -      rspamd_logger.debugm(N, task, 'couldnt find domain in username')
    -      return false
    -    end
    -    if settings.use_esld then
    -      udom = rspamd_util.get_tld(udom)
    -    end
    -    if udom ~= dkim_domain then
    -      rspamd_logger.debugm(N, task, 'user domain mismatch')
    -      return false
    -    end
    -  end
    -  local p = {}
    -  if settings.domain[dkim_domain] then
    -    p.selector = settings.domain[dkim_domain].selector
    -    p.key = settings.domain[dkim_domain].path
    -  end
    -  if not (p.key and p.selector) and not
    -    (settings.try_fallback or settings.use_redis or settings.selector_map or settings.path_map) then
    -    rspamd_logger.debugm(N, task, 'dkim unconfigured and fallback disabled')
    -    return false
    -  end
    -  if not p.key then
    -    if not settings.use_redis then
    -      p.key = settings.path
    -    end
    -  end
    -  if not p.selector then
    -    p.selector = settings.selector
    -  end
    -  p.domain = dkim_domain
    -
    -  if settings.selector_map then
    -    local data = settings.selector_map:get_key(dkim_domain)
    -    if data then
    -      p.selector = data
    -    end
    -  end
    -
    -  if settings.path_map then
    -    local data = settings.path_map:get_key(dkim_domain)
    -    if data then
    -      p.key = data
    -    end
    -  end
    -
    -  if settings.use_redis then
    -    local function try_redis_key(selector)
    -      p.key = nil
    -      p.selector = selector
    -      local rk = string.format('%s.%s', p.selector, p.domain)
    -      local function redis_key_cb(err, data)
    -        if err or type(data) ~= 'string' then
    -          rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM key for %s: %s",
    -            rk, err)
    -        else
    -          p.rawkey = data
    -          if rspamd_plugins.dkim.sign(task, p) then
    -            task:insert_result(settings.symbol, 1.0)
    -          end
    -        end
    -      end
    -      local ret = rspamd_redis_make_request(task,
    -        redis_params, -- connect params
    -        rk, -- hash key
    -        false, -- is write
    -        redis_key_cb, --callback
    -        'HGET', -- command
    -        {settings.key_prefix, rk} -- arguments
    -      )
    -      if not ret then
    -        rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM key for %s", rk)
    -      end
    -    end
    -    if settings.selector_prefix then
    -      rspamd_logger.infox(rspamd_config, "Using selector prefix %s for domain %s", settings.selector_prefix, p.domain);
    -      local function redis_selector_cb(err, data)
    -        if err or type(data) ~= 'string' then
    -          rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM selector for domain %s: %s", p.domain, err)
    -        else
    -          try_redis_key(data)
    -        end
    -      end
    -      local ret = rspamd_redis_make_request(task,
    -        redis_params, -- connect params
    -        p.domain, -- hash key
    -        false, -- is write
    -        redis_selector_cb, --callback
    -        'HGET', -- command
    -        {settings.selector_prefix, p.domain} -- arguments
    -      )
    -      if not ret then
    -        rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM selector for %s", p.domain)
    -      end
    -    else
    -      if not p.selector then
    -        rspamd_logger.errx(task, 'No selector specified')
    -        return false
    -      end
    -      try_redis_key(p.selector)
    -    end
    -  else
    -    if (p.key and p.selector) then
    -      p.key = simple_template(p.key, {domain = p.domain, selector = p.selector})
    -      return rspamd_plugins.dkim.sign(task, p)
    -    else
    -      rspamd_logger.infox(task, 'key path or dkim selector unconfigured; no signing')
    -      return false
    -    end
    -  end
    -end
    -
    -local opts =  rspamd_config:get_all_opt('dkim_signing')
    -if not opts then return end
    -for k,v in pairs(opts) do
    -  if k == 'sign_networks' then
    -    settings[k] = rspamd_map_add(N, k, 'radix', 'DKIM signing networks')
    -  elseif k == 'path_map' then
    -    settings[k] = rspamd_map_add(N, k, 'map', 'Paths to DKIM signing keys')
    -  elseif k == 'selector_map' then
    -    settings[k] = rspamd_map_add(N, k, 'map', 'DKIM selectors')
    -  else
    -    settings[k] = v
    -  end
    -end
    -if not (settings.use_redis or settings.path or settings.domain or settings.path_map or settings.selector_map) then
    -  rspamd_logger.infox(rspamd_config, 'mandatory parameters missing, disable dkim signing')
    -  return
    -end
    -if settings.use_redis then
    -  redis_params = rspamd_parse_redis_server('dkim_signing')
    -
    -  if not redis_params then
    -    rspamd_logger.errx(rspamd_config, 'no servers are specified, but module is configured to load keys from redis, disable dkim signing')
    -    return
    -  end
    -end
    -if settings.use_domain ~= 'header' and settings.use_domain ~= 'envelope' then
    -  rspamd_logger.errx(rspamd_config, "Value for 'use_domain' is invalid")
    -  settings.use_domain = 'header'
    -end
    -
    -rspamd_config:register_symbol({
    -  name = settings['symbol'],
    -  callback = dkim_signing_cb
    -})
    +--[[
    +Copyright (c) 2016, Andrew Lewis <nerf@judo.za.org>
    +Copyright (c) 2016, Vsevolod Stakhov <vsevolod@highsecure.ru>
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +]]--
    +
    +local rspamd_logger = require "rspamd_logger"
    +local rspamd_util = require "rspamd_util"
    +
    +if confighelp then
    +  return
    +end
    +
    +local settings = {
    +  allow_envfrom_empty = true,
    +  allow_hdrfrom_mismatch = false,
    +  allow_hdrfrom_mismatch_local = false,
    +  allow_hdrfrom_mismatch_sign_networks = false,
    +  allow_hdrfrom_multiple = false,
    +  allow_username_mismatch = false,
    +  auth_only = true,
    +  domain = {},
    +  path = string.format('%s/%s/%s', rspamd_paths['DBDIR'], 'dkim', '$domain.$selector.key'),
    +  sign_local = true,
    +  selector = 'dkim',
    +  symbol = 'DKIM_SIGNED',
    +  try_fallback = true,
    +  use_domain = 'header',
    +  use_esld = true,
    +  use_redis = false,
    +  key_prefix = 'dkim_keys', -- default hash name
    +}
    +
    +local E = {}
    +local N = 'dkim_signing'
    +local redis_params
    +
    +local function simple_template(tmpl, keys)
    +  local lpeg = require "lpeg"
    +
    +  local var_lit = lpeg.P { lpeg.R("az") + lpeg.R("AZ") + lpeg.R("09") + "_" }
    +  local var = lpeg.P { (lpeg.P("$") / "") * ((var_lit^1) / keys) }
    +  local var_braced = lpeg.P { (lpeg.P("${") / "") * ((var_lit^1) / keys) * (lpeg.P("}") / "") }
    +
    +  local template_grammar = lpeg.Cs((var + var_braced + 1)^0)
    +
    +  return lpeg.match(template_grammar, tmpl)
    +end
    +
    +local function dkim_signing_cb(task)
    +  local is_local, is_sign_networks
    +  local auser = task:get_user()
    +  local ip = task:get_from_ip()
    +  if ip and ip:is_local() then
    +    is_local = true
    +  end
    +  if settings.auth_only and not auser then
    +    if (settings.sign_networks and settings.sign_networks:get_key(ip)) then
    +      is_sign_networks = true
    +      rspamd_logger.debugm(N, task, 'mail is from address in sign_networks')
    +    elseif settings.sign_local and is_local then
    +      rspamd_logger.debugm(N, task, 'mail is from local address')
    +    else
    +      rspamd_logger.debugm(N, task, 'ignoring unauthenticated mail')
    +      return
    +    end
    +  end
    +  local efrom = task:get_from('smtp')
    +  if not settings.allow_envfrom_empty and
    +      #(((efrom or E)[1] or E).addr or '') == 0 then
    +    rspamd_logger.debugm(N, task, 'empty envelope from not allowed')
    +    return false
    +  end
    +  local hfrom = task:get_from('mime')
    +  if not settings.allow_hdrfrom_multiple and (hfrom or E)[2] then
    +    rspamd_logger.debugm(N, task, 'multiple header from not allowed')
    +    return false
    +  end
    +  local dkim_domain
    +  local hdom = ((hfrom or E)[1] or E).domain
    +  local edom = ((efrom or E)[1] or E).domain
    +  if hdom then
    +    hdom = hdom:lower()
    +  end
    +  if edom then
    +    edom = edom:lower()
    +  end
    +  if settings.use_domain_sign_networks and is_sign_networks then
    +    if settings.use_domain_sign_networks == 'header' then
    +      dkim_domain = hdom
    +    else
    +      dkim_domain = edom
    +    end
    +  elseif settings.use_domain_local and is_local then
    +    if settings.use_domain_local == 'header' then
    +      dkim_domain = hdom
    +    else
    +      dkim_domain = edom
    +    end
    +  else
    +    if settings.use_domain == 'header' then
    +      dkim_domain = hdom
    +    else
    +      dkim_domain = edom
    +    end
    +  end
    +  if not dkim_domain then
    +    rspamd_logger.debugm(N, task, 'could not extract dkim domain')
    +    return false
    +  end
    +  if settings.use_esld then
    +    dkim_domain = rspamd_util.get_tld(dkim_domain)
    +    if settings.use_domain == 'envelope' and hdom then
    +      hdom = rspamd_util.get_tld(hdom)
    +    elseif settings.use_domain == 'header' and edom then
    +      edom = rspamd_util.get_tld(edom)
    +    end
    +  end
    +  if edom and hdom and not settings.allow_hdrfrom_mismatch and hdom ~= edom then
    +    if settings.allow_hdrfrom_mismatch_local and is_local then
    +      rspamd_logger.debugm(N, task, 'domain mismatch allowed for local IP: %1 != %2', hdom, edom)
    +    elseif settings.allow_hdrfrom_mismatch_sign_networks and is_sign_networks then
    +      rspamd_logger.debugm(N, task, 'domain mismatch allowed for sign_networks: %1 != %2', hdom, edom)
    +    else
    +      rspamd_logger.debugm(N, task, 'domain mismatch not allowed: %1 != %2', hdom, edom)
    +      return false
    +    end
    +  end
    +  if auser and not settings.allow_username_mismatch then
    +    local udom = string.match(auser, '.*@(.*)')
    +    if not udom then
    +      rspamd_logger.debugm(N, task, 'couldnt find domain in username')
    +      return false
    +    end
    +    if settings.use_esld then
    +      udom = rspamd_util.get_tld(udom)
    +    end
    +    if udom ~= dkim_domain then
    +      rspamd_logger.debugm(N, task, 'user domain mismatch')
    +      return false
    +    end
    +  end
    +  local p = {}
    +  if settings.domain[dkim_domain] then
    +    p.selector = settings.domain[dkim_domain].selector
    +    p.key = settings.domain[dkim_domain].path
    +  end
    +  if not (p.key and p.selector) and not
    +    (settings.try_fallback or settings.use_redis or settings.selector_map or settings.path_map) then
    +    rspamd_logger.debugm(N, task, 'dkim unconfigured and fallback disabled')
    +    return false
    +  end
    +  if not p.key then
    +    if not settings.use_redis then
    +      p.key = settings.path
    +    end
    +  end
    +  if not p.selector then
    +    p.selector = settings.selector
    +  end
    +  p.domain = dkim_domain
    +
    +  if settings.selector_map then
    +    local data = settings.selector_map:get_key(dkim_domain)
    +    if data then
    +      p.selector = data
    +    end
    +  end
    +  if settings.path_map then
    +    local data = settings.path_map:get_key(dkim_domain)
    +    if data then
    +      p.key = data
    +    end
    +  end
    +
    +  if settings.use_redis then
    +    local function try_redis_key(selector)
    +      p.key = nil
    +      p.selector = selector
    +      local rk = string.format('%s.%s', p.selector, p.domain)
    +      local function redis_key_cb(err, data)
    +        if err or type(data) ~= 'string' then
    +          rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM key for %s: %s",
    +            rk, err)
    +        else
    +          p.rawkey = data
    +          if rspamd_plugins.dkim.sign(task, p) then
    +            task:insert_result(settings.symbol, 1.0)
    +          end
    +        end
    +      end
    +      local ret = rspamd_redis_make_request(task,
    +        redis_params, -- connect params
    +        rk, -- hash key
    +        false, -- is write
    +        redis_key_cb, --callback
    +        'HGET', -- command
    +        {settings.key_prefix, rk} -- arguments
    +      )
    +      if not ret then
    +        rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM key for %s", rk)
    +      end
    +    end
    +    if settings.selector_prefix then
    +      rspamd_logger.infox(rspamd_config, "Using selector prefix %s for domain %s", settings.selector_prefix, p.domain);
    +      local function redis_selector_cb(err, data)
    +        if err or type(data) ~= 'string' then
    +          rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM selector for domain %s: %s", p.domain, err)
    +        else
    +          try_redis_key(data)
    +        end
    +      end
    +      local ret = rspamd_redis_make_request(task,
    +        redis_params, -- connect params
    +        p.domain, -- hash key
    +        false, -- is write
    +        redis_selector_cb, --callback
    +        'HGET', -- command
    +        {settings.selector_prefix, p.domain} -- arguments
    +      )
    +      if not ret then
    +        rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM selector for %s", p.domain)
    +      end
    +    else
    +      if not p.selector then
    +        rspamd_logger.errx(task, 'No selector specified')
    +        return false
    +      end
    +      try_redis_key(p.selector)
    +    end
    +  else
    +    if (p.key and p.selector) then
    +      p.key = simple_template(p.key, {domain = p.domain, selector = p.selector})
    +      return rspamd_plugins.dkim.sign(task, p)
    +    else
    +      rspamd_logger.infox(task, 'key path or dkim selector unconfigured; no signing')
    +      return false
    +    end
    +  end
    +end
    +
    +local opts =  rspamd_config:get_all_opt('dkim_signing')
    +if not opts then return end
    +for k,v in pairs(opts) do
    +  if k == 'sign_networks' then
    +    settings[k] = rspamd_map_add(N, k, 'radix', 'DKIM signing networks')
    +  elseif k == 'path_map' then
    +    settings[k] = rspamd_map_add(N, k, 'map', 'Paths to DKIM signing keys')
    +  elseif k == 'selector_map' then
    +    settings[k] = rspamd_map_add(N, k, 'map', 'DKIM selectors')
    +  else
    +    settings[k] = v
    +  end
    +end
    +if not (settings.use_redis or settings.path or settings.domain or settings.path_map or settings.selector_map) then
    +  rspamd_logger.infox(rspamd_config, 'mandatory parameters missing, disable dkim signing')
    +  return
    +end
    +if settings.use_redis then
    +  redis_params = rspamd_parse_redis_server('dkim_signing')
    +
    +  if not redis_params then
    +    rspamd_logger.errx(rspamd_config, 'no servers are specified, but module is configured to load keys from redis, disable dkim signing')
    +    return
    +  end
    +end
    +if settings.use_domain ~= 'header' and settings.use_domain ~= 'envelope' then
    +  rspamd_logger.errx(rspamd_config, "Value for 'use_domain' is invalid")
    +  settings.use_domain = 'header'
    +end
    +
    +rspamd_config:register_symbol({
    +  name = settings['symbol'],
    +  callback = dkim_signing_cb
    +})
    
    From cdf7c87e208a538409163e9b5e09811aa28f1365 Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Mon, 8 May 2017 15:39:33 +0200
    Subject: [PATCH 22/49] Deleted two http maps, replaced by redis multimaps,
     much better tag system
    
    ---
     data/conf/rspamd/dynmaps/authoritative.php | 34 ---------------
     data/conf/rspamd/dynmaps/settings.php      |  2 +-
     data/conf/rspamd/dynmaps/tags.php          | 41 ------------------
     data/conf/rspamd/local.d/dkim_signing.conf |  2 +-
     data/conf/rspamd/local.d/multimap.conf     | 11 +++++
     data/conf/rspamd/lua/rspamd.local.lua      | 48 ++++++++++------------
     6 files changed, 34 insertions(+), 104 deletions(-)
     delete mode 100644 data/conf/rspamd/dynmaps/authoritative.php
     delete mode 100644 data/conf/rspamd/dynmaps/tags.php
     create mode 100644 data/conf/rspamd/local.d/multimap.conf
    
    diff --git a/data/conf/rspamd/dynmaps/authoritative.php b/data/conf/rspamd/dynmaps/authoritative.php
    deleted file mode 100644
    index ffbfacf6..00000000
    --- a/data/conf/rspamd/dynmaps/authoritative.php
    +++ /dev/null
    @@ -1,34 +0,0 @@
    -<?php
    -require_once "vars.inc.php";
    -ini_set('error_reporting', 0);
    -$has_object = 0;
    -header('Content-Type: text/plain');
    -$dsn = $database_type . ':host=' . $database_host . ';dbname=' . $database_name;
    -$opt = [
    -    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    -    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    -    PDO::ATTR_EMULATE_PREPARES   => false,
    -];
    -try {
    -  $pdo = new PDO($dsn, $database_user, $database_pass, $opt);
    -  $stmt = $pdo->query("SELECT `domain` FROM `domain`");
    -  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    -  while ($row = array_shift($rows)) {
    -    $has_object = 1;
    -    echo strtolower(trim($row['domain'])) . PHP_EOL;
    -  }
    -  $stmt = $pdo->query("SELECT `alias_domain` FROM `alias_domain`");
    -  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    -  while ($row = array_shift($rows)) {
    -    $has_object = 1;
    -    echo strtolower(trim($row['alias_domain'])) . PHP_EOL;
    -  }
    -  if ($has_object == 0) {
    -    echo "dummy@domain.local";
    -  }
    -}
    -catch (PDOException $e) {
    -  echo "dummy@domain.local";
    -  exit;
    -}
    -?>
    \ No newline at end of file
    diff --git a/data/conf/rspamd/dynmaps/settings.php b/data/conf/rspamd/dynmaps/settings.php
    index eb68c910..f3bc25f1 100644
    --- a/data/conf/rspamd/dynmaps/settings.php
    +++ b/data/conf/rspamd/dynmaps/settings.php
    @@ -346,4 +346,4 @@ while ($row = array_shift($rows)) {
     <?php
     }
     ?>
    -}
    +}
    \ No newline at end of file
    diff --git a/data/conf/rspamd/dynmaps/tags.php b/data/conf/rspamd/dynmaps/tags.php
    deleted file mode 100644
    index 7552575c..00000000
    --- a/data/conf/rspamd/dynmaps/tags.php
    +++ /dev/null
    @@ -1,41 +0,0 @@
    -<?php
    -require_once "vars.inc.php";
    -ini_set('error_reporting', 0);
    -$has_object = 0;
    -header('Content-Type: text/plain');
    -$dsn = $database_type . ':host=' . $database_host . ';dbname=' . $database_name;
    -$opt = [
    -    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    -    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    -    PDO::ATTR_EMULATE_PREPARES   => false,
    -];
    -try {
    -  $pdo = new PDO($dsn, $database_user, $database_pass, $opt);
    -  $stmt = $pdo->query("SELECT `username` FROM `mailbox` WHERE `wants_tagged_subject` = '1'");
    -  $rows_a = $stmt->fetchAll(PDO::FETCH_ASSOC);
    -  while ($row_a = array_shift($rows_a)) {
    -    $stmt = $pdo->prepare("SELECT `address` FROM `alias` WHERE `goto` REGEXP :username AND goto != `address` AND `address` NOT LIKE '@%'");
    -    $stmt->execute(array(':username' => '(^|,)'.$row_a['username'].'($|,)'));
    -    $rows_a_a = $stmt->fetchAll(PDO::FETCH_ASSOC);
    -    while ($row_a_a = array_shift($rows_a_a)) {
    -      echo strtolower(trim($row_a_a['address'])) . PHP_EOL;
    -    }
    -    $has_object = 1;
    -    echo strtolower(trim($row_a['username'])) . PHP_EOL;
    -  }
    -  $stmt = $pdo->query("SELECT CONCAT(`mailbox`.`local_part`, '@', `alias_domain`.`alias_domain`) AS `tag_ad` FROM `mailbox`
    -    INNER JOIN `alias_domain` ON `mailbox`.`domain` = `alias_domain`.`target_domain` WHERE `mailbox`.`wants_tagged_subject` = '1';");
    -  $rows_b = $stmt->fetchAll(PDO::FETCH_ASSOC);
    -  while ($row_b = array_shift($rows_b)) {
    -    $has_object = 1;
    -    echo strtolower(trim($row_b['tag_ad'])) . PHP_EOL;
    -  }
    -  if ($has_object == 0) {
    -    echo "dummy@domain.local";
    -  }
    -}
    -catch (PDOException $e) {
    -  echo "dummy@domain.local";
    -  exit;
    -}
    -?>
    diff --git a/data/conf/rspamd/local.d/dkim_signing.conf b/data/conf/rspamd/local.d/dkim_signing.conf
    index 9859678e..fe4bc7ae 100644
    --- a/data/conf/rspamd/local.d/dkim_signing.conf
    +++ b/data/conf/rspamd/local.d/dkim_signing.conf
    @@ -27,4 +27,4 @@ use_redis = true;
     # Hash for DKIM keys in Redis
     key_prefix = "DKIM_PRIV_KEYS";
     # Selector map
    -selector_map = "redis://DKIM_SELECTORS";
    +selector_prefix = "DKIM_SELECTORS";
    diff --git a/data/conf/rspamd/local.d/multimap.conf b/data/conf/rspamd/local.d/multimap.conf
    new file mode 100644
    index 00000000..935b0414
    --- /dev/null
    +++ b/data/conf/rspamd/local.d/multimap.conf
    @@ -0,0 +1,11 @@
    +RCPT_MAILCOW_DOMAIN {
    +  type = "rcpt";
    +  filter = "email:domain"
    +  map = "redis://DOMAIN_MAP"
    +}
    +
    +RCPT_WANTS_SUBJECT_TAG {
    +  type = "rcpt";
    +  filter = "email:addr"
    +  map = "redis://RCPT_WANTS_SUBJECT_TAG"
    +}
    diff --git a/data/conf/rspamd/lua/rspamd.local.lua b/data/conf/rspamd/lua/rspamd.local.lua
    index 09cf9d10..43c272d6 100644
    --- a/data/conf/rspamd/lua/rspamd.local.lua
    +++ b/data/conf/rspamd/lua/rspamd.local.lua
    @@ -13,12 +13,9 @@ modify_subject_map = rspamd_config:add_map({
       description = 'Map of users to use subject tags for'
     })
     
    -auth_domain_map = rspamd_config:add_map({
    -  url = 'http://172.22.1.251:8081/authoritative.php',
    -  type = 'map',
    -  description = 'Map of domains we are authoritative for'
    -})
    -
    +local redis_params
    +redis_params = rspamd_parse_redis_server('tag_settings')
    +if redis_params then
     rspamd_config:register_symbol({
       name = 'TAG_MOO',
       type = 'postfilter',
    @@ -27,12 +24,14 @@ rspamd_config:register_symbol({
         local rspamd_logger = require "rspamd_logger"
     
         local tagged_rcpt = task:get_symbol("TAGGED_RCPT")
    +    local mailcow_domain = task:get_symbol("RCPT_MAILCOW_DOMAIN")
    +
         local user = task:get_recipients(0)[1]['user']
         local domain = task:get_recipients(0)[1]['domain']
         local rcpt = user .. '@' .. domain
    -    local authdomain = auth_domain_map:get_key(domain)
     
    -    if tagged_rcpt then
    +
    +    if tagged_rcpt and mailcow_domain then
           local tag = tagged_rcpt[1].options[1]
           rspamd_logger.infox("found tag: %s", tag)
           local action = task:get_metric_action('default')
    @@ -44,32 +43,27 @@ rspamd_config:register_symbol({
             return true
           end
     
    -      if authdomain then
    -        rspamd_logger.infox("found mailcow domain %s", domain)
    -        rspamd_logger.infox("querying tag settings for user %s", rcpt)
    +      local wants_subject_tag = task:get_symbol("RCPT_WANTS_SUBJECT_TAG")
     
    -        if modify_subject_map:get_key(rcpt) then
    -          rspamd_logger.infox("user wants subject modified for tagged mail")
    -          local sbj = task:get_header('Subject')
    -          new_sbj = '=?UTF-8?B?' .. tostring(util.encode_base64('[' .. tag .. '] ' .. sbj)) .. '?='
    -          task:set_rmilter_reply({
    -            remove_headers = {['Subject'] = 1},
    -            add_headers = {['Subject'] = new_sbj}
    -          })
    -        else
    -          rspamd_logger.infox("Add X-Moo-Tag header")
    -          task:set_rmilter_reply({
    -            add_headers = {['X-Moo-Tag'] = 'YES'}
    -          })
    -        end
    +      if wants_subject_tag then
    +        rspamd_logger.infox("user wants subject modified for tagged mail")
    +        local sbj = task:get_header('Subject')
    +        new_sbj = '=?UTF-8?B?' .. tostring(util.encode_base64('[' .. tag .. '] ' .. sbj)) .. '?='
    +        task:set_rmilter_reply({
    +          remove_headers = {['Subject'] = 1},
    +          add_headers = {['Subject'] = new_sbj}
    +        })
           else
    -        rspamd_logger.infox("skip delimiter handling for unknown domain")
    +        rspamd_logger.infox("Add X-Moo-Tag header")
    +        task:set_rmilter_reply({
    +          add_headers = {['X-Moo-Tag'] = 'YES'}
    +        })
           end
    -      return false
         end
       end,
       priority = 10
     })
    +end
     
     rspamd_config.MRAPTOR = {
       callback = function(task)
    
    From 2e6fdba2b63f19ae150b8223ce74dc992acd6024 Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Mon, 8 May 2017 15:40:31 +0200
    Subject: [PATCH 23/49] PHP should depend on Redis
    
    ---
     docker-compose.yml | 1 +
     1 file changed, 1 insertion(+)
    
    diff --git a/docker-compose.yml b/docker-compose.yml
    index f2c80a4d..1deea6d9 100644
    --- a/docker-compose.yml
    +++ b/docker-compose.yml
    @@ -100,6 +100,7 @@ services:
           command: "php-fpm -d date.timezone=${TZ}"
           depends_on:
             - bind9-mailcow
    +        - redis-mailcow
           volumes:
             - ./data/web:/web:ro
             - ./data/conf/rspamd/dynmaps:/dynmaps:ro
    
    From f77c40a179bb89b463318c6dafe4823a5844a43f Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Mon, 8 May 2017 15:41:05 +0200
    Subject: [PATCH 24/49] Better log table, some MySQL to Redis migrations, API
     changes, other minor changes...
    
    ---
     data/web/inc/functions.inc.php                | 169 +++++++++---------
     .../owasp/csrf-protector-php/libs/config.php  |   4 +-
     data/web/inc/prerequisites.inc.php            |  18 +-
     data/web/inc/spf.inc.php                      |  23 ++-
     data/web/js/admin.js                          |   8 +-
     data/web/json_api.php                         |   4 +-
     data/web/user.php                             |   6 +-
     7 files changed, 122 insertions(+), 110 deletions(-)
    
    diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php
    index ba970063..7d916a1e 100644
    --- a/data/web/inc/functions.inc.php
    +++ b/data/web/inc/functions.inc.php
    @@ -1327,7 +1327,7 @@ function edit_delimiter_action($postarray) {
       // Array items
       // 'username' can be set, defaults to mailcow_cc_username
     	global $lang;
    -	global $pdo;
    +	global $redis;
       if (isset($postarray['username']) && filter_var($postarray['username'], FILTER_VALIDATE_EMAIL)) {
         if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $postarray['username'])) {
           $_SESSION['return'] = array(
    @@ -1343,7 +1343,6 @@ function edit_delimiter_action($postarray) {
       else {
         $username = $_SESSION['mailcow_cc_username'];
       }
    -  ($postarray['tagged_mail_handler'] == "subject") ? $wants_tagged_subject = '1' : $wants_tagged_subject = '0';
       if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
         $_SESSION['return'] = array(
           'type' => 'danger',
    @@ -1351,17 +1350,29 @@ function edit_delimiter_action($postarray) {
         );
         return false;
       }
    -  try {
    -    $stmt = $pdo->prepare("UPDATE `mailbox` SET `wants_tagged_subject` = :wants_tagged_subject WHERE `username` = :username");
    -    $stmt->execute(array(':username' => $username, ':wants_tagged_subject' => $wants_tagged_subject));
    -    $SelectData = $stmt->fetch(PDO::FETCH_ASSOC);
    +  if (isset($postarray['tagged_mail_handler']) && $postarray['tagged_mail_handler'] == "subject") {
    +    try {
    +      $redis->hSet('RCPT_WANTS_SUBJECT_TAG', $username, 1);
    +    }
    +    catch (RedisException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'Redis: '.$e
    +      );
    +      return false;
    +    }
       }
    -  catch(PDOException $e) {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => 'MySQL: '.$e
    -    );
    -    return false;
    +  else {
    +    try {
    +      $redis->hDel('RCPT_WANTS_SUBJECT_TAG', $username);
    +    }
    +    catch (RedisException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'Redis: '.$e
    +      );
    +      return false;
    +    }
       }
       $_SESSION['return'] = array(
         'type' => 'success',
    @@ -1372,7 +1383,7 @@ function edit_delimiter_action($postarray) {
     function get_delimiter_action($username = null) {
       // 'username' can be set, defaults to mailcow_cc_username
     	global $lang;
    -	global $pdo;
    +	global $redis;
     	$data = array();
       if (isset($username) && filter_var($username, FILTER_VALIDATE_EMAIL)) {
         if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {
    @@ -1383,18 +1394,20 @@ function get_delimiter_action($username = null) {
         $username = $_SESSION['mailcow_cc_username'];
       }
       try {
    -    $stmt = $pdo->prepare("SELECT `wants_tagged_subject` FROM `mailbox` WHERE `username` = :username");
    -    $stmt->execute(array(':username' => $username));
    -    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    +    if ($redis->hGet('RCPT_WANTS_SUBJECT_TAG', $username)) {
    +      return "subject";
    +    }
    +    else {
    +      return "subfolder";
    +    }
       }
    -  catch(PDOException $e) {
    +  catch (RedisException $e) {
         $_SESSION['return'] = array(
           'type' => 'danger',
    -      'msg' => 'MySQL: '.$e
    +      'msg' => 'Redis: '.$e
         );
         return false;
       }
    -  return $data;
     }
     function user_get_alias_details($username) {
     	global $lang;
    @@ -2413,12 +2426,30 @@ function dkim_add_key($postarray) {
             ), 1, -1)
           );
         // Save public key and selector to redis
    -    $redis->hSet('DKIM_PUB_KEYS', $domain, $pubKey);
    -    $redis->hSet('DKIM_SELECTORS', $domain, $dkim_selector);
    +    try {
    +      $redis->hSet('DKIM_PUB_KEYS', $domain, $pubKey);
    +      $redis->hSet('DKIM_SELECTORS', $domain, $dkim_selector);
    +    }
    +    catch (RedisException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'Redis: '.$e
    +      );
    +      return false;
    +    }
         // Export private key and save private key to redis
         openssl_pkey_export($keypair_ressource, $privKey);
         if (isset($privKey) && !empty($privKey)) {
    -      $redis->hSet('DKIM_PRIV_KEYS', $dkim_selector . '.' . $domain, trim($privKey));
    +      try {
    +        $redis->hSet('DKIM_PRIV_KEYS', $dkim_selector . '.' . $domain, trim($privKey));
    +      }
    +      catch (RedisException $e) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => 'Redis: '.$e
    +        );
    +        return false;
    +      }
         }
         $_SESSION['return'] = array(
           'type' => 'success',
    @@ -2438,18 +2469,7 @@ function dkim_get_key_details($domain) {
       $data = array();
       global $redis;
       if (hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    -    $dkim_pubkey_file = escapeshellarg($GLOBALS["MC_DKIM_TXTS"]. "/" . $domain . "." . "dkim");
    -    if (file_exists(substr($dkim_pubkey_file, 1, -1))) {
    -      $data['pubkey'] = file_get_contents($GLOBALS["MC_DKIM_TXTS"]. "/" . $domain . "." . "dkim");
    -      $data['length'] = (strlen($data['pubkey']) < 391) ? 1024 : 2048;
    -      $data['dkim_txt'] = 'v=DKIM1;k=rsa;t=s;s=email;p=' . file_get_contents($GLOBALS["MC_DKIM_TXTS"]. "/" . $domain . "." . "dkim");
    -      $data['dkim_selector'] = 'dkim';
    -      // Migrate key to redis
    -      $redis->hSet('DKIM_PRIV_KEYS', $data['dkim_selector'] . '.' . $domain, trim(file_get_contents($GLOBALS["MC_DKIM_KEYS"]. "/" . $domain . "." . "dkim")));
    -      $redis->hSet('DKIM_PUB_KEYS', $domain, $data['pubkey']);
    -      $redis->hSet('DKIM_SELECTORS', $domain, 'dkim');
    -    }
    -    elseif ($redis_dkim_key_data = $redis->hGet('DKIM_PUB_KEYS', $domain)) {
    +    if ($redis_dkim_key_data = $redis->hGet('DKIM_PUB_KEYS', $domain)) {
           $data['pubkey'] = $redis_dkim_key_data;
           $data['length'] = (strlen($data['pubkey']) < 391) ? 1024 : 2048;
           $data['dkim_txt'] = 'v=DKIM1;k=rsa;t=s;s=email;p=' . $redis_dkim_key_data;
    @@ -2469,11 +2489,6 @@ function dkim_get_blind_keys() {
         return false;
       }
       $domains = array();
    -  $dnstxt_folder = scandir($GLOBALS["MC_DKIM_TXTS"]);
    -  $dnstxt_files = array_diff($dnstxt_folder, array('.', '..'));
    -  foreach($dnstxt_files as $file) {
    -    $domains[] = substr($file, 0, -5);
    -  }
       foreach ($redis->hKeys('DKIM_PUB_KEYS') as $redis_dkim_domain) {
         $domains[] = $redis_dkim_domain;
       }
    @@ -2491,13 +2506,6 @@ function dkim_delete_key($postarray) {
         );
         return false;
       }
    -  // if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    -    // $_SESSION['return'] = array(
    -      // 'type' => 'danger',
    -      // 'msg' => sprintf($lang['danger']['access_denied'])
    -    // );
    -    // return false;
    -  // }
       if (!is_valid_domain_name($domain)) {
         $_SESSION['return'] = array(
           'type' => 'danger',
    @@ -2505,43 +2513,22 @@ function dkim_delete_key($postarray) {
         );
         return false;
       }
    -  foreach (array('DKIM_PUB_KEYS', 'DKIM_SELECTORS',) as $hash) {
    -    if (!$redis->hDel($hash, $domain)) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['dkim_remove_failed'])
    -      );
    -      return false;
    +  try {
    +    foreach ($redis->hGetAll('DKIM_PRIV_KEYS') as $key => $value) {
    +      if (preg_match('/\.' . $domain . '$/i', $key)) {
    +        $redis->hDel('DKIM_PUB_KEYS', $key);
    +      }
         }
    +    $redis->hDel('DKIM_PUB_KEYS', $domain);
    +    $redis->hDel('DKIM_SELECTORS', $domain);
    +    $redis->hDel('DKIM_PRIV_KEYS', $domain);
       }
    -  if (!empty($key_details = dkim_get_key_details($domain))) {
    -    if (!$redis->hDel($hash . $key_details['dkim_selector'], $domain)) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['dkim_remove_failed'])
    -      );
    -      return false;
    -    }
    -  }
    -  
    -  $redis->hDel('DKIM_PUB_KEYS', $domain);
    -  $redis->hDel('DKIM_PRIV_KEYS', $domain);
    -  $redis->hDel('DKIM_SELECTORS', $domain);
    -  exec('rm -f ' . escapeshellarg($GLOBALS['MC_DKIM_TXTS'] . '/' . $domain . '.dkim'), $out, $return);
    -  if ($return != "0") {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['dkim_remove_failed'])
    -    );
    -    return false;
    -  }
    -  exec('rm -f ' . escapeshellarg($GLOBALS['MC_DKIM_KEYS'] . '/' . $domain . '.dkim'), $out, $return);
    -  if ($return != "0") {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['dkim_remove_failed'])
    -    );
    -    return false;
    +  catch (RedisException $e) {
    +		$_SESSION['return'] = array(
    +			'type' => 'danger',
    +			'msg' => 'Redis: '.$e
    +		);
    +		return false;
       }
       $_SESSION['return'] = array(
         'type' => 'success',
    @@ -2654,6 +2641,16 @@ function mailbox_add_domain($postarray) {
     			':active' => $active,
     			':relay_all_recipients' => $relay_all_recipients
     		));
    +    try {
    +      $redis->hSet('DOMAIN_MAP', $domain, 1);
    +    }
    +    catch (RedisException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'Redis: '.$e
    +      );
    +      return false;
    +    }
     		$_SESSION['return'] = array(
     			'type' => 'success',
     			'msg' => sprintf($lang['success']['domain_added'], htmlspecialchars($domain))
    @@ -4646,6 +4643,16 @@ function mailbox_delete_domain($postarray) {
     		);
     		return false;
     	}
    +  try {
    +    $redis->hDel('DOMAIN_MAP', $domain);
    +  }
    +  catch (RedisException $e) {
    +		$_SESSION['return'] = array(
    +			'type' => 'danger',
    +			'msg' => 'Redis: '.$e
    +		);
    +		return false;
    +  }
     	$_SESSION['return'] = array(
     		'type' => 'success',
     		'msg' => sprintf($lang['success']['domain_removed'], htmlspecialchars($domain))
    diff --git a/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/config.php b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/config.php
    index cf2512e9..b9833d64 100755
    --- a/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/config.php
    +++ b/data/web/inc/lib/vendor/owasp/csrf-protector-php/libs/config.php
    @@ -42,8 +42,6 @@ return array(
     	"jsUrl" => get_trusted_hostname(),
     	"tokenLength" => 10,
     	"secureCookie" => false,
    -	"disabledJavascriptMessage" => "This site attempts to protect users against <a href=\"https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29\">
    -	Cross-Site Request Forgeries </a> attacks. In order to do so, you must have JavaScript enabled in your web browser otherwise this site will fail to work correctly for you.
    -	 See details of your web browser for how to enable JavaScript.",
    +	"disabledJavascriptMessage" => "",
     	 "verifyGetFor" => array()
     );
    \ No newline at end of file
    diff --git a/data/web/inc/prerequisites.inc.php b/data/web/inc/prerequisites.inc.php
    index 6b9126fe..3961aa00 100644
    --- a/data/web/inc/prerequisites.inc.php
    +++ b/data/web/inc/prerequisites.inc.php
    @@ -1,16 +1,16 @@
     <?php
    -require_once 'inc/sessions.inc.php';
    +require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/sessions.inc.php';
     
    -require_once 'inc/vars.inc.php';
    +require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/vars.inc.php';
     if (file_exists('./inc/vars.local.inc.php')) {
     	include_once 'inc/vars.local.inc.php';
     }
     
     // Yubi OTP API
    -require_once 'inc/lib/Yubico.php';
    +require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/lib/Yubico.php';
     
     // Autoload composer
    -require_once 'inc/lib/vendor/autoload.php';
    +require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/lib/vendor/autoload.php';
     
     // U2F API + T/HOTP API
     $u2f = new u2flib_server\U2F('https://' . $_SERVER['HTTP_HOST']);
    @@ -117,9 +117,9 @@ if (isset($_GET['lang'])) {
     		break;
     	}
     }
    -require_once 'lang/lang.en.php';
    -include 'lang/lang.'.$_SESSION['mailcow_locale'].'.php';
    -require_once 'inc/functions.inc.php';
    -require_once 'inc/init_db.inc.php';
    -require_once 'inc/triggers.inc.php';
    +require_once $_SERVER['DOCUMENT_ROOT'] . '/lang/lang.en.php';
    +include $_SERVER['DOCUMENT_ROOT'] . '/lang/lang.'.$_SESSION['mailcow_locale'].'.php';
    +require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/functions.inc.php';
    +require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/init_db.inc.php';
    +require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/triggers.inc.php';
     init_db_schema();
    diff --git a/data/web/inc/spf.inc.php b/data/web/inc/spf.inc.php
    index 0e584b40..09a724f5 100644
    --- a/data/web/inc/spf.inc.php
    +++ b/data/web/inc/spf.inc.php
    @@ -79,17 +79,24 @@ function get_spf_allowed_hosts($domain)
     	return $hosts;
     }
     
    +
     function get_mx_hosts($domain)
     {
     	$hosts = array();
    -	
    -	$mx_records = dns_get_record($domain, DNS_MX);
    -	foreach ($mx_records as $mx_record)
    -	{
    -		$new_hosts = get_a_hosts($mx_record['target']);
    -		$hosts = array_unique(array_merge($hosts,$new_hosts), SORT_REGULAR);
    -	}
    -	
    +  try {
    +    $mx_records = dns_get_record($domain, DNS_MX);
    +    foreach ($mx_records as $mx_record)
    +    {
    +      $new_hosts = get_a_hosts($mx_record['target']);
    +      $hosts = array_unique(array_merge($hosts,$new_hosts), SORT_REGULAR);
    +    }
    +  }
    +  catch (Exception $e) {
    +    if ($e->getMessage() !== 'dns_get_record(): A temporary server error occurred.') {
    +      throw $e;
    +    }
    +    $mx_records = false;
    +  }
     	return $hosts;
     }
     
    diff --git a/data/web/js/admin.js b/data/web/js/admin.js
    index db3b8bae..42cc6e34 100644
    --- a/data/web/js/admin.js
    +++ b/data/web/js/admin.js
    @@ -4,7 +4,7 @@ $(document).ready(function() {
         url: '/api/v1/get/domain-admin/all',
         jsonp: false,
         error: function () {
    -      alert('Cannot draw domain administrator table');
    +      console.log('Cannot draw domain admin table');
         },
         success: function (data) {
           $.each(data, function (i, item) {
    @@ -53,7 +53,7 @@ $(document).ready(function() {
             url: '/api/v1/get/logs/dovecot/1000',
             jsonp: false,
             error: function () {
    -          alert('Cannot draw dovecot log table');
    +          console.log('Cannot draw dovecot log table');
             },
             success: function (data) {
               $.each(data, function (i, item) {
    @@ -109,7 +109,7 @@ $(document).ready(function() {
             url: '/api/v1/get/logs/postfix/1000',
             jsonp: false,
             error: function () {
    -          alert('Cannot draw postfix log table');
    +          console.log('Cannot draw postfix log table');
             },
             success: function (data) {
               $.each(data, function (i, item) {
    @@ -128,7 +128,7 @@ $(document).ready(function() {
               });
               ft_postfix_logs = FooTable.init("#postfix_log", {
                 "columns": [
    -              {"name":"time","formatter":function unix_time_format(tm) {var date = new Date(tm ? tm * 1000 : 0); return date.toLocaleString();},"title":lang.time,"style":{"width":"170px"}},
    +              {"name":"time","formatter":function unix_time_format(tm) { var date = new Date(tm ? tm * 1000 : 0); return date.toLocaleString();},"title":lang.time,"style":{"width":"170px"}},
                   {"name":"priority","title":lang.priority,"style":{"width":"80px"}},
                   {"name":"message","title":lang.message},
                 ],
    diff --git a/data/web/json_api.php b/data/web/json_api.php
    index ba6ff70c..7ac78b53 100644
    --- a/data/web/json_api.php
    +++ b/data/web/json_api.php
    @@ -61,7 +61,7 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
               case "logs":
                 switch ($object) {
                   case "dovecot":
    -                if (isset($extra) && !empty($extra) && is_int($extra)) {
    +                if (isset($extra) && !empty($extra)) {
                       $extra = intval($extra);
                       $logs = get_logs('dovecot-mailcow', $extra);
                     }
    @@ -77,7 +77,7 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                   break;
     
                   case "postfix":
    -                if (isset($extra) && !empty($extra) && is_int($extra)) {
    +                if (isset($extra) && !empty($extra)) {
                       $extra = intval($extra);
                       $logs = get_logs('postfix-mailcow', $extra);
                     }
    diff --git a/data/web/user.php b/data/web/user.php
    index eaf35923..ec25dc94 100644
    --- a/data/web/user.php
    +++ b/data/web/user.php
    @@ -125,14 +125,14 @@ elseif (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == '
       <hr>
       <?php // Show tagging options ?>
       <form class="form-horizontal" role="form" method="post">
    -  <?php $get_tagging_options = get_delimiter_action()['wants_tagged_subject'];?>
    +  <?php $get_tagging_options = get_delimiter_action();?>
       <div class="row">
         <div class="col-md-3 col-xs-5 text-right"><?=$lang['user']['tag_handling'];?>:</div>
         <div class="col-md-9 col-xs-7">
         <input type="hidden" name="edit_delimiter_action" value="1">
         <select name="tagged_mail_handler" class="selectpicker" onchange="this.form.submit()">
    -      <option value="subfolder" <?=($get_tagging_options == "0") ? 'selected' : null; ?>><?=$lang['user']['tag_in_subfolder'];?></option>
    -      <option value="subject" <?=($get_tagging_options == "1") ? 'selected' : null; ?>><?=$lang['user']['tag_in_subject'];?></option>
    +      <option value="subfolder" <?=($get_tagging_options == "subfolder") ? 'selected' : null; ?>><?=$lang['user']['tag_in_subfolder'];?></option>
    +      <option value="subject" <?=($get_tagging_options == "subject") ? 'selected' : null; ?>><?=$lang['user']['tag_in_subject'];?></option>
         </select>
         <p class="help-block"><?=$lang['user']['tag_help_explain'];?></p>
         <p class="help-block"><?=$lang['user']['tag_help_example'];?></p>
    
    From 97dc8d9ff896844d1bcbce8cca8fecb279eb8171 Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Mon, 8 May 2017 15:44:30 +0200
    Subject: [PATCH 25/49] Fix modal in admin
    
    ---
     data/web/css/admin.css | 5 +++++
     1 file changed, 5 insertions(+)
    
    diff --git a/data/web/css/admin.css b/data/web/css/admin.css
    index 81f5a7b4..de6fbfa0 100644
    --- a/data/web/css/admin.css
    +++ b/data/web/css/admin.css
    @@ -14,3 +14,8 @@ table.footable>tbody>tr.footable-empty>td {
     body {
       overflow-y:scroll;
     }
    +/* Fix modal moving content left */
    +body.modal-open {
    +  overflow-y:scroll;
    +  padding-right: inherit !important;
    +}
    \ No newline at end of file
    
    From d64ed65575e3a287a78ba7f976b96dd1006f7a9a Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Mon, 8 May 2017 23:09:21 +0200
    Subject: [PATCH 26/49] Add multimap and forced actions for forwarded_hosts,
     removed from settings
    
    ---
     data/conf/rspamd/dynmaps/forwardinghosts.php | 70 ++++++++------------
     data/conf/rspamd/dynmaps/settings.php        | 60 -----------------
     data/conf/rspamd/local.d/force_actions.conf  | 10 +++
     data/conf/rspamd/local.d/multimap.conf       | 11 +++
     4 files changed, 50 insertions(+), 101 deletions(-)
    
    diff --git a/data/conf/rspamd/dynmaps/forwardinghosts.php b/data/conf/rspamd/dynmaps/forwardinghosts.php
    index 377c5e7e..cbc82ee7 100644
    --- a/data/conf/rspamd/dynmaps/forwardinghosts.php
    +++ b/data/conf/rspamd/dynmaps/forwardinghosts.php
    @@ -1,56 +1,44 @@
     <?php
     header('Content-Type: text/plain');
    -require_once "vars.inc.php";
    -
     ini_set('error_reporting', 0);
     
    -function in_net($addr, $net)
    -{
    -	$net = explode('/', $net);
    -	if (count($net) > 1)
    -		$mask = $net[1];
    -	$net = inet_pton($net[0]);
    -	$addr = inet_pton($addr);
    +$redis = new Redis();
    +$redis->connect('redis-mailcow', 6379);
     
    -	$length = strlen($net); // 4 for IPv4, 16 for IPv6
    -	if (strlen($net) != strlen($addr))
    -		return FALSE;
    -	if (!isset($mask))
    -		$mask = $length * 8;
    -
    -	$addr_bin = '';
    -	$net_bin = '';
    -	for ($i = 0; $i < $length; ++$i)
    -	{
    -		$addr_bin .= str_pad(decbin(ord(substr($addr, $i, $i+1))), 8, '0', STR_PAD_LEFT);
    -		$net_bin .= str_pad(decbin(ord(substr($net, $i, $i+1))), 8, '0', STR_PAD_LEFT);
    -	}
    -
    -	return substr($addr_bin, 0, $mask) == substr($net_bin, 0, $mask);
    +function in_net($addr, $net) {
    +  $net = explode('/', $net);
    +  if (count($net) > 1) {
    +    $mask = $net[1];
    +  }
    +  $net = inet_pton($net[0]);
    +  $addr = inet_pton($addr);
    +  $length = strlen($net); // 4 for IPv4, 16 for IPv6
    +  if (strlen($net) != strlen($addr)) {
    +    return false;
    +  }
    +  if (!isset($mask)) {
    +    $mask = $length * 8;
    +  }
    +  $addr_bin = '';
    +  $net_bin = '';
    +  for ($i = 0; $i < $length; ++$i) {
    +    $addr_bin .= str_pad(decbin(ord(substr($addr, $i, $i+1))), 8, '0', STR_PAD_LEFT);
    +    $net_bin .= str_pad(decbin(ord(substr($net, $i, $i+1))), 8, '0', STR_PAD_LEFT);
    +  }
    +  return substr($addr_bin, 0, $mask) == substr($net_bin, 0, $mask);
     }
     
    -$dsn = $database_type . ':host=' . $database_host . ';dbname=' . $database_name;
    -$opt = [
    -    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    -    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    -    PDO::ATTR_EMULATE_PREPARES   => false,
    -];
     try {
    -  $pdo = new PDO($dsn, $database_user, $database_pass, $opt);
    -  $stmt = $pdo->query("SELECT host FROM `forwarding_hosts`");
    -  $networks = $stmt->fetchAll(PDO::FETCH_COLUMN);
    -  foreach ($networks as $network)
    -  {
    -    if (in_net($_GET['host'], $network))
    -    {
    -      echo '200 permit';
    +  foreach ($redis->hGetAll('WHITELISTED_FWD_HOST') as $host => $source) {
    +    if (in_net($_GET['host'], $host)) {
    +      echo '200 PERMIT';
           exit;
         }
       }
    -  echo '200 dunno';
    +  echo '200 DUNNO';
     }
    -catch (PDOException $e) {
    -  echo '200 dunno';
    +catch (RedisException $e) {
    +  echo '200 DUNNO';
       exit;
     }
     ?>
    diff --git a/data/conf/rspamd/dynmaps/settings.php b/data/conf/rspamd/dynmaps/settings.php
    index 36b28d59..3976954c 100644
    --- a/data/conf/rspamd/dynmaps/settings.php
    +++ b/data/conf/rspamd/dynmaps/settings.php
    @@ -31,67 +31,7 @@ catch (PDOException $e) {
     
     ?>
     settings {
    -
    -/*
    -// Start whitelist for forwarding hosts
    -*/
    -
     <?php
    -try {
    -	$stmt = $pdo->query("SELECT `host` FROM `forwarding_hosts` WHERE `filter_spam` = 1");
    -	$rows = $stmt->fetchAll(PDO::FETCH_COLUMN);
    -}
    -catch (PDOException $e) {
    -	$rows = array();
    -}
    -
    -if (!empty($rows)) {
    -?>
    -	whitelist_forwarding_hosts_with_spam_filter {
    -		priority = high;
    -<?php
    -foreach ($rows as $host):
    -?>
    -		ip = "<?=$host;?>";
    -<?php
    -endforeach;
    -?>
    -		apply "default" {
    -			actions {
    -				reject = 999.9;
    -				greylist = 999.8;
    -			}
    -		}
    -		symbols [
    -			"WHITELIST_FORWARDING_HOST"
    -		]
    -	}
    -<?php
    -}
    -
    -try {
    -	$stmt = $pdo->query("SELECT `host` FROM `forwarding_hosts` WHERE `filter_spam` = 0");
    -	$rows = $stmt->fetchAll(PDO::FETCH_COLUMN);
    -}
    -catch (PDOException $e) {
    -	$rows = array();
    -}
    -
    -if (!empty($rows)) {
    -?>
    -	whitelist_forwarding_hosts {
    -		priority = high;
    -<?php
    -foreach ($rows as $host):
    -?>
    -		ip = "<?=$host;?>";
    -<?php
    -endforeach;
    -?>
    -		want_spam = yes;
    -	}
    -<?php
    -}
     
     /*
     // Start custom scores for users
    diff --git a/data/conf/rspamd/local.d/force_actions.conf b/data/conf/rspamd/local.d/force_actions.conf
    index 1aa10659..df64d41c 100644
    --- a/data/conf/rspamd/local.d/force_actions.conf
    +++ b/data/conf/rspamd/local.d/force_actions.conf
    @@ -9,4 +9,14 @@ rules {
         expression = "CLAM_VIRUS & !MAILCOW_WHITE";
         honor_action = ["reject"];
       }
    +  WHITELIST_FORWARDING_HOST_NO_REJECT {
    +    action = "add header";
    +    expression = "WHITELIST_FORWARDING_HOST";
    +    require_action = ["soft reject", "reject"];
    +  }
    +  WHITELIST_FORWARDING_HOST_NO_GREYLIST {
    +    action = "no action";
    +    expression = "WHITELIST_FORWARDING_HOST";
    +    require_action = ["greylist"];
    +  }
     }
    diff --git a/data/conf/rspamd/local.d/multimap.conf b/data/conf/rspamd/local.d/multimap.conf
    index 935b0414..d524264e 100644
    --- a/data/conf/rspamd/local.d/multimap.conf
    +++ b/data/conf/rspamd/local.d/multimap.conf
    @@ -9,3 +9,14 @@ RCPT_WANTS_SUBJECT_TAG {
       filter = "email:addr"
       map = "redis://RCPT_WANTS_SUBJECT_TAG"
     }
    +
    +WHITELISTED_FWD_HOST {
    +  type = "ip";
    +  map = "redis://WHITELISTED_FWD_HOST"
    +}
    +
    +KEEP_SPAM {
    +  type = "ip";
    +  map = "redis://KEEP_SPAM"
    +  action = "accept";
    +}
    
    From 74359f6df4f2200ed11223ba911e6683cd963b0d Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Mon, 8 May 2017 23:09:40 +0200
    Subject: [PATCH 27/49] Use Redis for forwarded_hosts, some fixes
    
    ---
     data/web/admin.php             |  39 +++++------
     data/web/inc/functions.inc.php | 115 +++++++++++++++++++--------------
     data/web/inc/spf.inc.php       |  11 ++--
     data/web/inc/vars.inc.php      |   2 +-
     data/web/lang/lang.de.php      |   1 +
     data/web/lang/lang.en.php      |   1 +
     6 files changed, 95 insertions(+), 74 deletions(-)
    
    diff --git a/data/web/admin.php b/data/web/admin.php
    index df442b68..b2962079 100644
    --- a/data/web/admin.php
    +++ b/data/web/admin.php
    @@ -292,24 +292,25 @@ $tfa_data = get_tfa();
                 </thead>
                 <tbody>
                   <?php
    -              $forwarding_hosts = get_forwarding_hosts();
    -              if ($forwarding_hosts) {
    -                foreach ($forwarding_hosts as $host) {
    +              $fwd_hosts = get_forwarding_hosts();
    +              if (!empty($fwd_hosts)) {
    +                foreach ($fwd_hosts as $host => $attr) {
                     ?>
                     <tr id="data">
    -                  <td><?=htmlspecialchars(strtolower($host->host));?></td>
    -                  <td><?=htmlspecialchars(strtolower($host->source));?></td>
    +                  <td><?=htmlspecialchars($host);?></td>
    +                  <td><?=htmlspecialchars($attr['source']);?></td>
    +                  <td><?=($attr['keep_spam'] == "no") ? $lang['admin']['yes'] : $lang['admin']['no'];?></td>
                       <td style="text-align: right;">
                         <div class="btn-group">
    -                      <a href="delete.php?forwardinghost=<?=$host->host;?>" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> <?=$lang['admin']['remove'];?></a>
    +                      <a href="delete.php?forwardinghost=<?=htmlspecialchars($host);?>" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> <?=$lang['admin']['remove'];?></a>
                         </div>
                       </td>
                       </td>
                     </tr>
    -
                     <?php
                     }
    -              } else {
    +              }
    +              else {
                   ?>
                     <tr id="no-data"><td colspan="4" style="text-align: center; font-style: italic;"><?=$lang['admin']['no_record'];?></td></tr>
                   <?php
    @@ -321,24 +322,18 @@ $tfa_data = get_tfa();
             </form>
             <legend><?=$lang['admin']['add_forwarding_host'];?></legend>
             <p class="help-block"><?=$lang['admin']['forwarding_hosts_add_hint'];?></p>
    -        <form class="form-horizontal" role="form" method="post">
    +        <form class="form-inline" role="form" method="post">
               <div class="form-group">
    -            <label class="control-label col-sm-2" for="hostname"><?=$lang['edit']['host'];?>:</label>
    -            <div class="col-sm-10">
    -              <input type="text" class="form-control" name="hostname" id="hostname" required>
    -            </div>
    +            <label for="hostname"><?=$lang['edit']['host'];?></label>
    +            <input class="form-control" id="hostname" name="hostname" placeholder="example.org" required>
               </div>
               <div class="form-group">
    -            <label class="control-label col-sm-2" for="filter_spam"><?=$lang['user']['spamfilter'];?>:</label>
    -            <div class="col-sm-10">
    -              <input type="checkbox" class="form-control" name="filter_spam" id="filter_spam">
    -            </div>
    -          </div>
    -          <div class="form-group">
    -            <div class="col-sm-offset-2 col-sm-10">
    -              <button type="submit" name="add_forwarding_host" class="btn btn-default"><?=$lang['admin']['add'];?></button>
    -            </div>
    +            <select data-width="200px" class="form-control" id="filter_spam" name="filter_spam" title="<?=$lang['user']['spamfilter'];?>" required>
    +              <option value="1"><?=$lang['admin']['active'];?></option>
    +              <option value="0"><?=$lang['admin']['inactive'];?></option>
    +            </select>
               </div>
    +          <button type="submit" name="add_forwarding_host" class="btn btn-default"><span class="glyphicon glyphicon-plus"></span> <?=$lang['admin']['add'];?></button>
             </form>
           </div>
         </div>
    diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php
    index 2000aad2..a2b2fba8 100644
    --- a/data/web/inc/functions.inc.php
    +++ b/data/web/inc/functions.inc.php
    @@ -5100,14 +5100,29 @@ function get_u2f_registrations($username) {
       return $sel->fetchAll(PDO::FETCH_OBJ);
     }
     function get_forwarding_hosts() {
    -	global $pdo;
    -  $sel = $pdo->prepare("SELECT * FROM `forwarding_hosts`");
    -  $sel->execute();
    -  return $sel->fetchAll(PDO::FETCH_OBJ);
    +	global $redis;
    +  $data = array();
    +  try {
    +    $wl_hosts = $redis->hGetAll('WHITELISTED_FWD_HOST');
    +    if (!empty($wl_hosts)) {
    +      foreach ($wl_hosts as $host => $source) {
    +        $data[$host]['keep_spam'] = ($redis->hGet('KEEP_SPAM', $host)) ? "yes" : "no";
    +        $data[$host]['source'] = $source;
    +      }
    +    }
    +  }
    +  catch (RedisException $e) {
    +		$_SESSION['return'] = array(
    +			'type' => 'danger',
    +			'msg' => 'Redis: '.$e
    +		);
    +		return false;
    +  }
    +  return $data;
     }
     function add_forwarding_host($postarray) {
     	require_once 'spf.inc.php';
    -	global $pdo;
    +	global $redis;
     	global $lang;
     	if ($_SESSION['mailcow_cc_role'] != "admin") {
     		$_SESSION['return'] = array(
    @@ -5117,20 +5132,21 @@ function add_forwarding_host($postarray) {
     		return false;
     	}
     	$source = $postarray['hostname'];
    -	$host = $postarray['hostname'];
    -	$filter_spam = !empty($postarray['filter_spam']);
    -	$hosts = array();
    -	if (preg_match('/^[0-9a-fA-F:\/]+$/', $host)) { // IPv6 address
    +	$host   = trim($postarray['hostname']);
    +  $filter_spam = $postarray['filter_spam'];
    +  if (isset($postarray['filter_spam']) && $postarray['filter_spam'] == 1) {
    +    $filter_spam = 1;
    +  }
    +  else {
    +    $filter_spam = 0;
    +  }
    +  if (filter_var($host, FILTER_VALIDATE_IP)) {
     		$hosts = array($host);
    -	}
    -	elseif (preg_match('/^[0-9\.\/]+$/', $host)) { // IPv4 address
    -		$hosts = array($host);
    -	}
    +  }
     	else {
     		$hosts = get_outgoing_hosts_best_guess($host);
     	}
    -	if (!$hosts)
    -	{
    +	if (!$hosts) {
     		$_SESSION['return'] = array(
     			'type' => 'danger',
     			'msg' => 'Invalid host specified: '. htmlspecialchars($host)
    @@ -5138,23 +5154,22 @@ function add_forwarding_host($postarray) {
     		return false;
     	}
     	foreach ($hosts as $host) {
    -		if ($source == $host)
    -			$source = '';
    -		try {
    -			$stmt = $pdo->prepare("REPLACE INTO `forwarding_hosts` (`host`, `source`, `filter_spam`) VALUES (:host, :source, :filter_spam)");
    -			$stmt->execute(array(
    -				':host' => $host,
    -				':source' => $source,
    -				':filter_spam' => $filter_spam ? 1 : 0,
    -			));
    -		}
    -		catch (PDOException $e) {
    -			$_SESSION['return'] = array(
    -				'type' => 'danger',
    -				'msg' => 'MySQL: '.$e
    -			);
    -			return false;
    -		}
    +    try {
    +      $redis->hSet('WHITELISTED_FWD_HOST', $host, $source);
    +      if ($filter_spam == 0) {
    +        $redis->hSet('KEEP_SPAM', $host, 1);
    +      }
    +      elseif ($redis->hGet('KEEP_SPAM', $host)) {
    +        $redis->hDel('KEEP_SPAM', $host);
    +      }
    +    }
    +    catch (RedisException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'Redis: '.$e
    +      );
    +      return false;
    +    }
     	}
     	$_SESSION['return'] = array(
     		'type' => 'success',
    @@ -5162,7 +5177,7 @@ function add_forwarding_host($postarray) {
     	);
     }
     function delete_forwarding_host($postarray) {
    -	global $pdo;
    +	global $redis;
     	global $lang;
     	if ($_SESSION['mailcow_cc_role'] != "admin") {
     		$_SESSION['return'] = array(
    @@ -5171,20 +5186,26 @@ function delete_forwarding_host($postarray) {
     		);
     		return false;
     	}
    -	$host = $postarray['forwardinghost'];
    -	try {
    -		$stmt = $pdo->prepare("DELETE FROM `forwarding_hosts` WHERE `host` = :host");
    -		$stmt->execute(array(
    -			':host' => $host,
    -		));
    -	}
    -	catch (PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    -	}
    +  if (!is_array($postarray['forwardinghost'])) {
    +    $hosts = array();
    +    $hosts[] = $postarray['forwardinghost'];
    +  }
    +  else {
    +    $hosts = $postarray['forwardinghost'];
    +  }
    +  foreach ($hosts as $host) {
    +    try {
    +      return $redis->hDel('WHITELISTED_FWD_HOST', $host);
    +      return $redis->hDel('KEEP_SPAM', $host);
    +    }
    +    catch (RedisException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'Redis: '.$e
    +      );
    +      return false;
    +    }
    +  }
     	$_SESSION['return'] = array(
     		'type' => 'success',
     		'msg' => sprintf($lang['success']['forwarding_host_removed'], htmlspecialchars($host))
    diff --git a/data/web/inc/spf.inc.php b/data/web/inc/spf.inc.php
    index 09a724f5..18dd2893 100644
    --- a/data/web/inc/spf.inc.php
    +++ b/data/web/inc/spf.inc.php
    @@ -1,4 +1,6 @@
     <?php
    +error_reporting(0);
    +
     function get_spf_allowed_hosts($domain)
     {
     	$hosts = array();
    @@ -85,10 +87,11 @@ function get_mx_hosts($domain)
     	$hosts = array();
       try {
         $mx_records = dns_get_record($domain, DNS_MX);
    -    foreach ($mx_records as $mx_record)
    -    {
    -      $new_hosts = get_a_hosts($mx_record['target']);
    -      $hosts = array_unique(array_merge($hosts,$new_hosts), SORT_REGULAR);
    +    if ($mx_records) {
    +      foreach ($mx_records as $mx_record) {
    +        $new_hosts = get_a_hosts($mx_record['target']);
    +        $hosts = array_unique(array_merge($hosts,$new_hosts), SORT_REGULAR);
    +      }
         }
       }
       catch (Exception $e) {
    diff --git a/data/web/inc/vars.inc.php b/data/web/inc/vars.inc.php
    index faef565d..67c6c34e 100644
    --- a/data/web/inc/vars.inc.php
    +++ b/data/web/inc/vars.inc.php
    @@ -1,5 +1,5 @@
     <?php
    -error_reporting(E_ERROR | E_WARNING);
    +error_reporting(E_ERROR);
     //error_reporting(E_ALL);
     
     /*
    diff --git a/data/web/lang/lang.de.php b/data/web/lang/lang.de.php
    index b0c86b09..a6a856e6 100644
    --- a/data/web/lang/lang.de.php
    +++ b/data/web/lang/lang.de.php
    @@ -450,6 +450,7 @@ $lang['admin']['configuration'] = 'Konfiguration';
     $lang['admin']['password'] = 'Passwort';
     $lang['admin']['password_repeat'] = 'Passwort (Wiederholung)';
     $lang['admin']['active'] = 'Aktiv';
    +$lang['admin']['inactive'] = 'Inaktiv';
     $lang['admin']['action'] = 'Aktion';
     $lang['admin']['add_domain_admin'] = 'Domain-Administrator hinzufügen';
     $lang['admin']['admin_domains'] = 'Domain-Zuweisungen';
    diff --git a/data/web/lang/lang.en.php b/data/web/lang/lang.en.php
    index e5ebe008..4b361afe 100644
    --- a/data/web/lang/lang.en.php
    +++ b/data/web/lang/lang.en.php
    @@ -462,6 +462,7 @@ $lang['admin']['configuration'] = 'Configuration';
     $lang['admin']['password'] = 'Password';
     $lang['admin']['password_repeat'] = 'Confirmation password (repeat)';
     $lang['admin']['active'] = 'Active';
    +$lang['admin']['inactive'] = 'Inactive';
     $lang['admin']['action'] = 'Action';
     $lang['admin']['add_domain_admin'] = 'Add Domain administrator';
     $lang['admin']['admin_domains'] = 'Domain assignments';
    
    From 759f21ac6b6c872654f5799b39bb6715b8447596 Mon Sep 17 00:00:00 2001
    From: Michael Kuron <mkuron@users.noreply.github.com>
    Date: Tue, 9 May 2017 07:29:43 +0200
    Subject: [PATCH 28/49] Consistent symbol names for forwarding hosts
    
    multimap.conf and force_actions weren't using the same name
    ---
     data/conf/rspamd/local.d/force_actions.conf | 4 ++--
     1 file changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/data/conf/rspamd/local.d/force_actions.conf b/data/conf/rspamd/local.d/force_actions.conf
    index df64d41c..2541f949 100644
    --- a/data/conf/rspamd/local.d/force_actions.conf
    +++ b/data/conf/rspamd/local.d/force_actions.conf
    @@ -11,12 +11,12 @@ rules {
       }
       WHITELIST_FORWARDING_HOST_NO_REJECT {
         action = "add header";
    -    expression = "WHITELIST_FORWARDING_HOST";
    +    expression = "WHITELISTED_FWD_HOST";
         require_action = ["soft reject", "reject"];
       }
       WHITELIST_FORWARDING_HOST_NO_GREYLIST {
         action = "no action";
    -    expression = "WHITELIST_FORWARDING_HOST";
    +    expression = "WHITELISTED_FWD_HOST";
         require_action = ["greylist"];
       }
     }
    
    From bbff045d0434e5c265657da3c5a8735c3911da05 Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Tue, 9 May 2017 13:43:54 +0200
    Subject: [PATCH 29/49] Use API for forwarding hosts
    
    ---
     data/web/admin.php             |  47 +++-----------
     data/web/css/mailcow.css       |  10 ++-
     data/web/inc/footer.inc.php    |  33 +++++-----
     data/web/inc/functions.inc.php |  51 +++++++++++----
     data/web/js/admin.js           | 111 ++++++++++++++++++++++++++++++++
     data/web/js/mailbox.js         |   2 +-
     data/web/json_api.php          | 113 +++++++++++++++++++++++++++++----
     data/web/lang/lang.de.php      |   5 +-
     data/web/lang/lang.en.php      |   5 +-
     9 files changed, 290 insertions(+), 87 deletions(-)
    
    diff --git a/data/web/admin.php b/data/web/admin.php
    index b2962079..39900fac 100644
    --- a/data/web/admin.php
    +++ b/data/web/admin.php
    @@ -279,45 +279,14 @@ $tfa_data = get_tfa();
           <div class="panel-heading"><?=$lang['admin']['forwarding_hosts'];?></div>
           <div class="panel-body">
             <p style="margin-bottom:40px"><?=$lang['admin']['forwarding_hosts_hint'];?></p>
    -        <form method="post">
    -          <div class="table-responsive">
    -          <table class="table table-striped" id="forwardinghoststable">
    -            <thead>
    -            <tr>
    -              <th style="min-width: 100px;"><?=$lang['edit']['host'];?></th>
    -              <th style="min-width: 100px;"><?=$lang['edit']['source'];?></th>
    -              <th><?=$lang['user']['spamfilter'];?></th>
    -              <th style="text-align: right; min-width: 200px;"><?=$lang['admin']['action'];?></th>
    -            </tr>
    -            </thead>
    -            <tbody>
    -              <?php
    -              $fwd_hosts = get_forwarding_hosts();
    -              if (!empty($fwd_hosts)) {
    -                foreach ($fwd_hosts as $host => $attr) {
    -                ?>
    -                <tr id="data">
    -                  <td><?=htmlspecialchars($host);?></td>
    -                  <td><?=htmlspecialchars($attr['source']);?></td>
    -                  <td><?=($attr['keep_spam'] == "no") ? $lang['admin']['yes'] : $lang['admin']['no'];?></td>
    -                  <td style="text-align: right;">
    -                    <div class="btn-group">
    -                      <a href="delete.php?forwardinghost=<?=htmlspecialchars($host);?>" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> <?=$lang['admin']['remove'];?></a>
    -                    </div>
    -                  </td>
    -                  </td>
    -                </tr>
    -                <?php
    -                }
    -              }
    -              else {
    -              ?>
    -                <tr id="no-data"><td colspan="4" style="text-align: center; font-style: italic;"><?=$lang['admin']['no_record'];?></td></tr>
    -              <?php
    -              }
    -              ?>
    -            </tbody>
    -          </table>
    +        <form method="post" data-id="fwdhosts">
    +        <div class="btn-group btn-group-sm">
    +          <button type="button" id="toggle_multi_select_all" data-form-id="fwdhosts" class="btn btn-default">Toggle all</button>
    +          <button type="button" id="delete_fwdhosts" name="delete_fwdhosts" class="btn btn-danger"><?=$lang['admin']['remove'];?></button>
    +        </div>
    +        <hr >
    +        <div class="table-responsive">
    +            <table class="table table-striped" id="forwardinghoststable"></table>
               </div>
             </form>
             <legend><?=$lang['admin']['add_forwarding_host'];?></legend>
    diff --git a/data/web/css/mailcow.css b/data/web/css/mailcow.css
    index 20dfb69a..8ab3d1e9 100644
    --- a/data/web/css/mailcow.css
    +++ b/data/web/css/mailcow.css
    @@ -55,4 +55,12 @@ body.modal-open {
       overflow: inherit;
       padding-right: inherit !important;
     }
    -
    +.mailcow-alert-box {
    +  position: fixed;
    +  bottom: 8px;
    +  right: 25px;
    +  min-width: 300px;
    +  max-width: 350px;
    +  z-index: 2000;
    +  display: none;
    +}
    \ No newline at end of file
    diff --git a/data/web/inc/footer.inc.php b/data/web/inc/footer.inc.php
    index 97b59c0e..6fc6d321 100644
    --- a/data/web/inc/footer.inc.php
    +++ b/data/web/inc/footer.inc.php
    @@ -19,6 +19,9 @@ if (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == "admi
     		</div>
     	</div>
     </div>
    +<?php
    +endif;
    +?>
     <div id="ConfirmDeleteModal" class="modal fade" role="dialog">
     	<div class="modal-dialog">
     		<div class="modal-content">
    @@ -36,9 +39,6 @@ if (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == "admi
     		</div>
     	</div>
     </div>
    -<?php
    -endif;
    -?>
     <div style="margin-bottom:100px"></div>
     <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
     <script src="/js/bootstrap-switch.min.js"></script>
    @@ -53,6 +53,16 @@ function setLang(sel) {
     }
     
     $(document).ready(function() {
    +  function mailcow_alert_box(type, message) {
    +    $('.mailcow-alert-box').show();
    +    $('.mailcow-alert-box').addClass("alert-" + type);
    +    $('#mailcow-alert-text').text(message);
    +  }
    +  // PHP error handler
    +  <?php if (isset($_SESSION['return'])): ?>
    +  mailcow_alert_box("<?=$_SESSION['return']['type'];?>",  "<?=$_SESSION['return']['msg'];?>");
    +  <?php endif; unset($_SESSION['return']); ?>
    +
       // Confirm TFA modal
       <?php if (isset($_SESSION['pending_tfa_method'])):?>
       $('#ConfirmTFAModal').modal({
    @@ -220,21 +230,10 @@ $(document).ready(function() {
     	});
     });
     </script>
    -<?php
    -if (isset($_SESSION['return'])):
    -?>
    -<div class="container">
    -	<div style="position:fixed;bottom:8px;right:25px;min-width:300px;max-width:350px;z-index:2000">
    -		<div <?=($_SESSION['return']['type'] == 'danger') ? null : 'id="alert-fade"'?> class="alert alert-<?=$_SESSION['return']['type'];?>" role="alert">
    -		<a href="#" class="close" data-dismiss="alert"> &times;</a>
    -		<?=htmlspecialchars($_SESSION['return']['msg']);?>
    -		</div>
    -	</div>
    +<div class="mailcow-alert-box alert" role="alert">
    +  <a href="#" class="close" data-dismiss="alert"> &times;</a>
    +  <span id="mailcow-alert-text"></span>
     </div>
    -<?php
    -unset($_SESSION['return']);
    -endif;
    -?>
     </body>
     </html>
     <?php $stmt = null; $pdo = null; ?>
    diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php
    index a2b2fba8..26888b79 100644
    --- a/data/web/inc/functions.inc.php
    +++ b/data/web/inc/functions.inc.php
    @@ -5103,11 +5103,10 @@ function get_forwarding_hosts() {
     	global $redis;
       $data = array();
       try {
    -    $wl_hosts = $redis->hGetAll('WHITELISTED_FWD_HOST');
    -    if (!empty($wl_hosts)) {
    -      foreach ($wl_hosts as $host => $source) {
    -        $data[$host]['keep_spam'] = ($redis->hGet('KEEP_SPAM', $host)) ? "yes" : "no";
    -        $data[$host]['source'] = $source;
    +    $fwd_hosts = $redis->hGetAll('WHITELISTED_FWD_HOST');
    +    if (!empty($fwd_hosts)) {
    +      foreach ($fwd_hosts as $fwd_host => $source) {
    +        $data[] = $fwd_host;
           }
         }
       }
    @@ -5120,6 +5119,31 @@ function get_forwarding_hosts() {
       }
       return $data;
     }
    +function get_forwarding_host_details($host) {
    +	global $redis;
    +  $data = array();
    +  if (!isset($host) || empty($host)) {
    +    return false;
    +  }
    +  if (filter_var($host, FILTER_VALIDATE_IP)) {
    +    return;
    +  }
    +  try {
    +    if ($source = $redis->hGet('WHITELISTED_FWD_HOST', $host)) {
    +      $data['host'] = $host;
    +      $data['source'] = $source;
    +      $data['keep_spam'] = ($redis->hGet('KEEP_SPAM', $host)) ? "yes" : "no";
    +    }
    +  }
    +  catch (RedisException $e) {
    +		$_SESSION['return'] = array(
    +			'type' => 'danger',
    +			'msg' => 'Redis: '.$e
    +		);
    +		return false;
    +  }
    +  return $data;
    +}
     function add_forwarding_host($postarray) {
     	require_once 'spf.inc.php';
     	global $redis;
    @@ -5132,7 +5156,7 @@ function add_forwarding_host($postarray) {
     		return false;
     	}
     	$source = $postarray['hostname'];
    -	$host   = trim($postarray['hostname']);
    +	$host = trim($postarray['hostname']);
       $filter_spam = $postarray['filter_spam'];
       if (isset($postarray['filter_spam']) && $postarray['filter_spam'] == 1) {
         $filter_spam = 1;
    @@ -5140,13 +5164,16 @@ function add_forwarding_host($postarray) {
       else {
         $filter_spam = 0;
       }
    -  if (filter_var($host, FILTER_VALIDATE_IP)) {
    +	if (preg_match('/^[0-9a-fA-F:\/]+$/', $host)) { // IPv6 address
     		$hosts = array($host);
    -  }
    +	}
    +	elseif (preg_match('/^[0-9\.\/]+$/', $host)) { // IPv4 address
    +		$hosts = array($host);
    +	}
     	else {
     		$hosts = get_outgoing_hosts_best_guess($host);
     	}
    -	if (!$hosts) {
    +	if (empty($hosts)) {
     		$_SESSION['return'] = array(
     			'type' => 'danger',
     			'msg' => 'Invalid host specified: '. htmlspecialchars($host)
    @@ -5195,8 +5222,8 @@ function delete_forwarding_host($postarray) {
       }
       foreach ($hosts as $host) {
         try {
    -      return $redis->hDel('WHITELISTED_FWD_HOST', $host);
    -      return $redis->hDel('KEEP_SPAM', $host);
    +      $redis->hDel('WHITELISTED_FWD_HOST', $host);
    +      $redis->hDel('KEEP_SPAM', $host);
         }
         catch (RedisException $e) {
           $_SESSION['return'] = array(
    @@ -5208,7 +5235,7 @@ function delete_forwarding_host($postarray) {
       }
     	$_SESSION['return'] = array(
     		'type' => 'success',
    -		'msg' => sprintf($lang['success']['forwarding_host_removed'], htmlspecialchars($host))
    +		'msg' => sprintf($lang['success']['forwarding_host_removed'], htmlspecialchars(implode(', ', $hosts)))
     	);
     }
     function get_logs($container, $lines = 100) {
    diff --git a/data/web/js/admin.js b/data/web/js/admin.js
    index 42cc6e34..be0fbd11 100644
    --- a/data/web/js/admin.js
    +++ b/data/web/js/admin.js
    @@ -1,4 +1,37 @@
     $(document).ready(function() {
    +  
    +  // Collect values of input fields with name multi_select to js array multi_data[data-id-of-checkbox]
    +  var multi_data = [];
    +  $(document).on('change', 'input[name=multi_select]:checkbox', function() {
    +    if ($(this).is(':checked') && $(this).attr('data-form-id')) {
    +      var id = $(this).data('form-id');
    +      if (typeof multi_data[id] == "undefined") {
    +        multi_data[id] = [];
    +      }
    +      multi_data[id].push($(this).val());
    +    }
    +    else {
    +      var id = $(this).data('form-id');
    +      multi_data[id].splice($.inArray($(this).val(), multi_data[id]),1);
    +    }
    +  });
    +  // Select by click on tr
    +  $(document).on('click', 'tr', function(e) {
    +    if (e.target.type == "checkbox") {
    +      e.stopPropagation();
    +    } else {
    +      var checkbox = $(this).find(':checkbox');
    +      checkbox.trigger('click');
    +    }
    +  });
    +  // Select or deselect all checkboxes with same data-form-id
    +  $(document).on('click', '#toggle_multi_select_all', function(e) {
    +    e.preventDefault();
    +    var closests_checkboxes = $("input[data-form-id=" + $(this).attr("data-form-id") + "]");
    +    closests_checkboxes.prop("checked", !closests_checkboxes.prop("checked")).change();
    +  });
    +
    +  // Draw domain admin table
       $.ajax({
         dataType: 'json',
         url: '/api/v1/get/domain-admin/all',
    @@ -39,6 +72,84 @@ $(document).ready(function() {
           });
         }
       });
    +  
    +  // Draw fwd hosts table
    +  $.ajax({
    +    dataType: 'json',
    +    url: '/api/v1/get/fwdhost/all',
    +    jsonp: false,
    +    error: function () {
    +      console.log('Cannot draw forwarding hosts table');
    +    },
    +    success: function (data) {
    +      $.each(data, function (i, item) {
    +        item.action = '<div class="btn-group">' +
    +          '<a href="/delete.php?forwardinghost=' + encodeURI(item.host) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    +					'</div>';
    +        if (item.keep_spam == "yes") {
    +          item.keep_spam = lang.no;
    +        }
    +        else {
    +          item.keep_spam = lang.yes;
    +        }
    +        item.chkbox = '<input type="checkbox" data-form-id="fwdhosts" name="multi_select" value="' + item.host + '" />';
    +      });
    +      $('#forwardinghoststable').footable({
    +        "columns": [
    +          {"name":"chkbox","title":"","style":{"maxWidth":"40px","width":"40px"},"filterable": false,"sortable": false,"type":"html"},
    +          {"name":"host","type":"text","title":lang.host,"style":{"width":"250px"}},
    +          {"name":"source","title":lang.source,"breakpoints":"xs sm"},
    +          {"name":"keep_spam","title":lang.spamfilter, "type": "text","style":{"maxWidth":"80px","width":"80px"}},
    +          {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
    +        ],
    +        "rows": data,
    +        "empty": lang.empty,
    +        "paging": {
    +          "enabled": true,
    +          "limit": 5,
    +          "size": pagination_size
    +        },
    +        "sorting": {
    +          "enabled": true
    +        }
    +      });
    +    }
    +  });
    +  
    +  $(document).on('click', '#delete_fwdhosts', function(e) {
    +    e.preventDefault();
    +    var id = $(this).closest("form").attr('data-id');
    +    if (typeof multi_data[id] == "undefined") return;
    +    data_array = multi_data[id];
    +    if (Object.keys(data_array).length !== 0) {
    +      $(document).on('show.bs.modal','#ConfirmDeleteModal', function () {
    +        $("#ItemsToDelete").empty();
    +        for (var i in data_array) {
    +          $("#ItemsToDelete").append("<li>" + data_array[i] + "</li>");
    +        }
    +      })
    +      $('#ConfirmDeleteModal').modal({
    +        backdrop: 'static',
    +        keyboard: false
    +      })
    +      .one('click', '#IsConfirmed', function(e) {
    +        $.ajax({
    +          type: "POST",
    +          dataType: "json",
    +          data: { "forwardinghost": JSON.stringify(data_array) },
    +          url: '/api/v1/delete/fwdhost',
    +          jsonp: false,
    +          complete: function (data) {
    +            location.reload();
    +          }
    +        });
    +      })
    +      .one('click', '#isCanceled', function(e) {
    +        $('#ConfirmDeleteModal').modal('hide');
    +      });;
    +    }
    +  });
    +
       $("#refresh_dovecot_log").on('click', function(e) {
           function unix_time_format(tm) {
             var date = new Date(tm ? tm * 1000 : 0);
    diff --git a/data/web/js/mailbox.js b/data/web/js/mailbox.js
    index 6acb22eb..1e168f59 100644
    --- a/data/web/js/mailbox.js
    +++ b/data/web/js/mailbox.js
    @@ -301,7 +301,7 @@ $(document).ready(function() {
     
           $(document).on('click', '#activate_selected_alias', function(e) {
             e.preventDefault();
    -        if (selected_aliases.length !== 0) {
    +        if (Object.keys(selected_aliases).length !== 0) {
               $.ajax({
                 type: "POST",
                 dataType: "json",
    diff --git a/data/web/json_api.php b/data/web/json_api.php
    index 7ac78b53..c48a1293 100644
    --- a/data/web/json_api.php
    +++ b/data/web/json_api.php
    @@ -33,7 +33,12 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                     $domains = mailbox_get_domains();
                     if (!empty($domains)) {
                       foreach ($domains as $domain) {
    -                    $data[] = mailbox_get_domain_details($domain);
    +                    if ($details = mailbox_get_domain_details($domain)) {
    +                      $data[] = $details;
    +                    }
    +                    else {
    +                      continue;
    +                    }
                       }
                       if (!isset($data) || empty($data)) {
                         echo '{}';
    @@ -53,7 +58,7 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                       echo '{}';
                     }
                     else {
    -                  echo json_encode(mailbox_get_domain_details($object), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    +                  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                     }
                   break;
                 }
    @@ -102,7 +107,12 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                         $mailboxes = mailbox_get_mailboxes($domain);
                         if (!empty($mailboxes)) {
                           foreach ($mailboxes as $mailbox) {
    -                        $data[] = mailbox_get_mailbox_details($mailbox);
    +                        if ($details = mailbox_get_mailbox_details($mailbox)) {
    +                          $data[] = $details;
    +                        }
    +                        else {
    +                          continue;
    +                        }
                           }
                         }
                       }
    @@ -124,7 +134,7 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                       echo '{}';
                     }
                     else {
    -                  echo json_encode(mailbox_get_mailbox_details($object), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    +                  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                     }
                   break;
     
    @@ -139,7 +149,12 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                         $resources = mailbox_get_resources($domain);
                         if (!empty($resources)) {
                           foreach ($resources as $resource) {
    -                        $data[] = mailbox_get_resource_details($resource);
    +                        if ($details = mailbox_get_resource_details($resource)) {
    +                          $data[] = $details;
    +                        }
    +                        else {
    +                          continue;
    +                        }
                           }
                         }
                       }
    @@ -161,7 +176,40 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                       echo '{}';
                     }
                     else {
    -                  echo json_encode(mailbox_get_resource_details($object), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    +                  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    +                }
    +              break;
    +
    +            }
    +          break;
    +          case "fwdhost":
    +            switch ($object) {
    +              case "all":
    +                $fwdhosts = get_forwarding_hosts();
    +                if (!empty($fwdhosts)) {
    +                  foreach ($fwdhosts as $fwdhost) {
    +                    if ($details = get_forwarding_host_details($fwdhost)) {
    +                      $data[] = $details;
    +                    }
    +                    else {
    +                      continue;
    +                    }
    +                  }
    +                }
    +                if (!isset($data) || empty($data)) {
    +                  echo '{}';
    +                }
    +                else {
    +                  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    +                }
    +              break;
    +              default:
    +                $data = get_forwarding_host_details($object);
    +                if (!isset($data) || empty($data)) {
    +                  echo '{}';
    +                }
    +                else {
    +                  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                     }
                   break;
     
    @@ -176,7 +224,12 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                         $alias_domains = mailbox_get_alias_domains($domain);
                         if (!empty($alias_domains)) {
                           foreach ($alias_domains as $alias_domain) {
    -                        $data[] = mailbox_get_alias_domain_details($alias_domain);
    +                        if ($details = mailbox_get_alias_domain_details($alias_domain)) {
    +                          $data[] = $details;
    +                        }
    +                        else {
    +                          continue;
    +                        }
                           }
                         }
                       }
    @@ -198,7 +251,7 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                       echo '{}';
                     }
                     else {
    -                  echo json_encode(mailbox_get_alias_domains($object), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    +                  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                     }
                   break;
                 }
    @@ -212,7 +265,12 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                         $aliases = mailbox_get_aliases($domain);
                         if (!empty($aliases)) {
                           foreach ($aliases as $alias) {
    -                        $data[] = mailbox_get_alias_details($alias);
    +                        if ($details = mailbox_get_alias_details($alias)) {
    +                          $data[] = $details;
    +                        }
    +                        else {
    +                          continue;
    +                        }
                           }
                         }
                       }
    @@ -234,7 +292,7 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                       echo '{}';
                     }
                     else {
    -                  echo json_encode(mailbox_get_alias_details($object), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    +                  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                     }
                   break;
                 }
    @@ -245,7 +303,12 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                     $domain_admins = get_domain_admins();
                     if (!empty($domain_admins)) {
                       foreach ($domain_admins as $domain_admin) {
    -                    $data[] = get_domain_admin_details($domain_admin);
    +                    if ($details = get_domain_admin_details($domain_admin)) {
    +                      $data[] = $details;
    +                    }
    +                    else {
    +                      continue;
    +                    }
                       }
                       if (!isset($data) || empty($data)) {
                         echo '{}';
    @@ -265,7 +328,7 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                       echo '{}';
                     }
                     else {
    -                  echo json_encode(get_domain_admin_details($object), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    +                  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                     }
                   break;
                 }
    @@ -307,7 +370,7 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                     if (mailbox_delete_alias(array('address' => $address)) === false) {
                       echo json_encode(array(
                         'type' => 'error',
    -                    'message' => 'Deletion of item failed'
    +                    'message' => 'Deletion of item/s failed'
                       ));
                       exit();
                     }
    @@ -324,6 +387,30 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                   ));
                 }
               break;
    +          case "fwdhost":
    +            if (isset($_POST['forwardinghost'])) {
    +              $forwardinghost = json_decode($_POST['forwardinghost'], true);
    +              if (is_array($forwardinghost)) {
    +                if (delete_forwarding_host(array('forwardinghost' => $forwardinghost)) === false) {
    +                  echo json_encode(array(
    +                    'type' => 'error',
    +                    'message' => 'Deletion of item/s failed'
    +                  ));
    +                  exit();
    +                }
    +                echo json_encode(array(
    +                  'type' => 'success',
    +                  'message' => 'Task completed'
    +                ));
    +              }
    +            }
    +            else {
    +              echo json_encode(array(
    +                'type' => 'error',
    +                'message' => 'Cannot find forwardinghost array in post data'
    +              ));
    +            }
    +          break;
             }
           break;
           case "edit":
    diff --git a/data/web/lang/lang.de.php b/data/web/lang/lang.de.php
    index a6a856e6..bc254ccb 100644
    --- a/data/web/lang/lang.de.php
    +++ b/data/web/lang/lang.de.php
    @@ -135,6 +135,7 @@ $lang['user']['day'] = 'Tag';
     $lang['user']['week'] = 'Woche';
     $lang['user']['weeks'] = 'Wochen';
     $lang['user']['spamfilter'] = 'Spamfilter';
    +$lang['admin']['spamfilter'] = 'Spamfilter';
     $lang['user']['spamfilter_wl'] = 'Whitelist';
     $lang['user']['spamfilter_wl_desc'] = 'Für E-Mail-Adressen, die vom Spamfilter <b>nicht</b> erfasst werden sollen. Die Verwendung von Wildcards ist gestattet.';
     $lang['user']['spamfilter_bl'] = 'Blacklist';
    @@ -480,8 +481,8 @@ $lang['admin']['message'] = 'Nachricht';
     $lang['admin']['forwarding_hosts'] = 'Weiterleitungs-Hosts';
     $lang['admin']['forwarding_hosts_hint'] = 'Eingehende Nachrichten werden von den hier gelisteten Hosts bedingungslos akzeptiert. Diese Hosts werden dann nicht mit DNSBLs abgeglichen oder Greylisting unterworfen. Von ihnen empfangener Spam wird nie abgelehnt, optional kann er aber in den Spam-Ordner einsortiert werden. Die übliche Verwendung für diese Funktion ist, um Mailserver anzugeben, auf denen eine Weiterleitung zu Ihrem Mailcow-Server eingerichtet wurde.';
     $lang['admin']['forwarding_hosts_add_hint'] = 'Sie können entweder IPv4/IPv6-Adressen, Netzwerke in CIDR-Notation, Hostnamen (die zu IP-Adressen aufgelöst werden), oder Domainnamen (die zu IP-Adressen aufgelöst werden, indem ihr SPF-Record abgefragt wird oder, in dessen Abwesenheit, ihre MX-Records) angeben.';
    -$lang['edit']['host'] = 'Host';
    -$lang['edit']['source'] = 'Quelle';
    +$lang['admin']['host'] = 'Host';
    +$lang['admin']['source'] = 'Quelle';
     $lang['admin']['add_forwarding_host'] = 'Weiterleitungs-Host hinzufügen';
     $lang['delete']['remove_forwardinghost_warning'] = '<b>Warnung:</b> Sie entfernen den Weiterleitungs-Host <b>%s</b>!';
     $lang['success']['forwarding_host_removed'] = "Weiterleitungs-Host %s wurde entfernt";
    diff --git a/data/web/lang/lang.en.php b/data/web/lang/lang.en.php
    index 4b361afe..af500355 100644
    --- a/data/web/lang/lang.en.php
    +++ b/data/web/lang/lang.en.php
    @@ -137,6 +137,7 @@ $lang['user']['day'] = 'Day';
     $lang['user']['week'] = 'Week';
     $lang['user']['weeks'] = 'Weeks';
     $lang['user']['spamfilter'] = 'Spam filter';
    +$lang['admin']['spamfilter'] = 'Spam filter';
     $lang['user']['spamfilter_wl'] = 'Whitelist';
     $lang['user']['spamfilter_wl_desc'] = 'Whitelisted email addresses to <b>never</b> classify as spam. Wildcards maybe used.';
     $lang['user']['spamfilter_bl'] = 'Blacklist';
    @@ -492,8 +493,8 @@ $lang['admin']['logs'] = 'Logs';
     $lang['admin']['forwarding_hosts'] = 'Forwarding Hosts';
     $lang['admin']['forwarding_hosts_hint'] = 'Incoming messages are unconditionally accepted from any hosts listed here. These hosts are then not checked against DNSBLs or subjected to greylisting. Spam received from them is never rejected, but optionally it can be filed into the Junk folder. The most common use for this is to specify mail servers on which you have set up a rule that forwards incoming emails to your Mailcow server.';
     $lang['admin']['forwarding_hosts_add_hint'] = 'You can either specify IPv4/IPv6 addresses, networks in CIDR notation, host names (which will be resolved to IP addresses), or domain names (which will be resolved to IP addresses by querying SPF records or, in their absence, MX records).';
    -$lang['edit']['host'] = 'Host';
    -$lang['edit']['source'] = 'Source';
    +$lang['admin']['host'] = 'Host';
    +$lang['admin']['source'] = 'Source';
     $lang['admin']['add_forwarding_host'] = 'Add Forwarding Host';
     $lang['delete']['remove_forwardinghost_warning'] = '<b>Warning:</b> You are about to remove the forwarding host <b>%s</b>!';
     $lang['success']['forwarding_host_removed'] = "Forwarding host %s has been removed";
    
    From 93046dea45c2fd2117e4eb53f753e4fb671bf1f2 Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Tue, 9 May 2017 21:29:51 +0200
    Subject: [PATCH 30/49] Fixes #261
    
    ---
     data/Dockerfiles/dovecot/docker-entrypoint.sh | 2 ++
     1 file changed, 2 insertions(+)
    
    diff --git a/data/Dockerfiles/dovecot/docker-entrypoint.sh b/data/Dockerfiles/dovecot/docker-entrypoint.sh
    index a7191306..a07a3896 100755
    --- a/data/Dockerfiles/dovecot/docker-entrypoint.sh
    +++ b/data/Dockerfiles/dovecot/docker-entrypoint.sh
    @@ -71,5 +71,7 @@ sievec /usr/local/lib/dovecot/sieve/report-ham.sieve
     # Fix permissions
     chown -R vmail:vmail /var/vmail/sieve
     
    +# Fix more than 1 hardlink issue
    +touch /etc/crontab /etc/cron.*/*
     
     exec "$@"
    
    From a8e550244e9afc893161815fbcb11047f7fb211c Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Tue, 9 May 2017 21:30:08 +0200
    Subject: [PATCH 31/49] Remove DKIM keys with api
    
    ---
     data/web/admin.php             |  21 ++----
     data/web/inc/functions.inc.php |  50 +++++++-------
     data/web/js/admin.js           |  39 +++++++++--
     data/web/js/mailbox.js         |   6 +-
     data/web/json_api.php          | 116 +++++++++++++++++++++++++--------
     5 files changed, 158 insertions(+), 74 deletions(-)
    
    diff --git a/data/web/admin.php b/data/web/admin.php
    index 39900fac..9a7f2ba2 100644
    --- a/data/web/admin.php
    +++ b/data/web/admin.php
    @@ -155,6 +155,7 @@ $tfa_data = get_tfa();
         <div class="panel panel-default">
           <div class="panel-heading"><?=$lang['admin']['dkim_keys'];?></div>
           <div class="panel-body">
    +      <form class="form-inline" method="post" data-id="dkimkeys">
             <?php
             foreach(mailbox_get_domains() as $domain) {
                 if (!empty($dkim = dkim_get_key_details($domain))) {
    @@ -171,11 +172,7 @@ $tfa_data = get_tfa();
                       <pre><?=$dkim['dkim_txt'];?></pre>
                   </div>
                   <div class="col-xs-1">
    -                <form class="form-inline" method="post">
    -                  <input type="hidden" name="domain" value="<?=$domain;?>">
    -                  <input type="hidden" name="dkim_delete_key" value="1">
    -                    <a href="#" onclick="$(this).closest('form').submit()" data-toggle="tooltip" data-placement="top" title="<?=$lang['user']['delete_now'];?>"><span class="glyphicon glyphicon-remove"></span></a>
    -                </form>
    +                <span style="cursor:pointer" data-dkim-domain="<?=$domain;?>" data-dkim-selector="<?=$dkim['dkim_selector'];?>" id="delete_dkim_key" class="text-danger glyphicon glyphicon-remove"></span></a>
                   </div>
                 </div>
               <?php
    @@ -206,11 +203,7 @@ $tfa_data = get_tfa();
                       <pre><?=$dkim['dkim_txt'];?></pre>
                     </div>
                     <div class="col-xs-1">
    -                  <form class="form-inline" method="post">
    -                    <input type="hidden" name="domain" value="<?=$alias_domain;?>">
    -                    <input type="hidden" name="dkim_delete_key" value="1">
    -                    <a href="#" onclick="$(this).closest('form').submit()" data-toggle="tooltip" data-placement="top" title="<?=$lang['user']['delete_now'];?>"><span class="glyphicon glyphicon-remove"></span></a>
    -                  </form>
    +                  <span style="cursor:pointer" data-dkim-domain="<?=$domain;?>" data-dkim-selector="<?=$dkim['dkim_selector'];?>" id="delete_dkim_key" class="text-danger glyphicon glyphicon-remove"></span></a>
                     </div>
                   </div>
                 <?php
    @@ -243,17 +236,15 @@ $tfa_data = get_tfa();
                       <pre><?=$dkim['dkim_txt'];?></pre>
                     </div>
                     <div class="col-xs-1">
    -                  <form class="form-inline" method="post">
    -                    <input type="hidden" name="domain" value="<?=$blind;?>">
    -                    <input type="hidden" name="dkim_delete_key" value="1">
    -                    <a href="#" onclick="$(this).closest('form').submit()" data-toggle="tooltip" data-placement="top" title="<?=$lang['user']['delete_now'];?>"><span class="glyphicon glyphicon-remove"></span></a>
    -                  </form>
    +                  <span style="cursor:pointer" data-dkim-domain="<?=$blind;?>" data-dkim-selector="<?=$dkim['dkim_selector'];?>" id="delete_dkim_key" class="text-danger glyphicon glyphicon-remove"></span></a>
                     </div>
                 </div>
               <?php
               }
             }
             ?>
    +        </form>
    +
             <legend style="margin-top:40px"><?=$lang['admin']['dkim_add_key'];?></legend>
             <form class="form-inline" role="form" method="post">
               <div class="form-group">
    diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php
    index 26888b79..50b26660 100644
    --- a/data/web/inc/functions.inc.php
    +++ b/data/web/inc/functions.inc.php
    @@ -2497,8 +2497,13 @@ function dkim_get_blind_keys() {
     function dkim_delete_key($postarray) {
     	global $redis;
     	global $lang;
    -  $domain	= $postarray['domain'];
    -
    +  if (!is_array($postarray['domains'])) {
    +    $domains = array();
    +    $domains[] = $postarray['domains'];
    +  }
    +  else {
    +    $domains = $postarray['domains'];
    +  }
       if ($_SESSION['mailcow_cc_role'] != "admin") {
         $_SESSION['return'] = array(
           'type' => 'danger',
    @@ -2506,29 +2511,28 @@ function dkim_delete_key($postarray) {
         );
         return false;
       }
    -  if (!is_valid_domain_name($domain)) {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['dkim_domain_or_sel_invalid'])
    -    );
    -    return false;
    -  }
    -  try {
    -    foreach ($redis->hGetAll('DKIM_PRIV_KEYS') as $key => $value) {
    -      if (preg_match('/\.' . $domain . '$/i', $key)) {
    -        $redis->hDel('DKIM_PUB_KEYS', $key);
    +  foreach ($domains as $domain) {
    +    if (!is_valid_domain_name($domain)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['dkim_domain_or_sel_invalid'])
    +      );
    +      return false;
    +    }
    +    try {
    +      foreach ($redis->hGetAll('DKIM_SELECTORS') as $domain_name => $selector) {
    +        $redis->hDel('DKIM_PUB_KEYS', $domain_name);
    +        $redis->hDel('DKIM_PRIV_KEYS', $selector . '.' . $domain_name);
    +        $redis->hDel('DKIM_SELECTORS', $domain_name);
           }
         }
    -    $redis->hDel('DKIM_PUB_KEYS', $domain);
    -    $redis->hDel('DKIM_SELECTORS', $domain);
    -    $redis->hDel('DKIM_PRIV_KEYS', $domain);
    -  }
    -  catch (RedisException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'Redis: '.$e
    -		);
    -		return false;
    +    catch (RedisException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'Redis: '.$e
    +      );
    +      return false;
    +    }
       }
       $_SESSION['return'] = array(
         'type' => 'success',
    diff --git a/data/web/js/admin.js b/data/web/js/admin.js
    index be0fbd11..76367b15 100644
    --- a/data/web/js/admin.js
    +++ b/data/web/js/admin.js
    @@ -1,6 +1,6 @@
     $(document).ready(function() {
       
    -  // Collect values of input fields with name multi_select to js array multi_data[data-id-of-checkbox]
    +  // Collect values of input fields with name multi_select with same data-form-id to js array multi_data[data-form-id-of-checkbox]
       var multi_data = [];
       $(document).on('change', 'input[name=multi_select]:checkbox', function() {
         if ($(this).is(':checked') && $(this).attr('data-form-id')) {
    @@ -15,7 +15,7 @@ $(document).ready(function() {
           multi_data[id].splice($.inArray($(this).val(), multi_data[id]),1);
         }
       });
    -  // Select by click on tr
    +  // Select checkbox by click on parent tr
       $(document).on('click', 'tr', function(e) {
         if (e.target.type == "checkbox") {
           e.stopPropagation();
    @@ -27,8 +27,8 @@ $(document).ready(function() {
       // Select or deselect all checkboxes with same data-form-id
       $(document).on('click', '#toggle_multi_select_all', function(e) {
         e.preventDefault();
    -    var closests_checkboxes = $("input[data-form-id=" + $(this).attr("data-form-id") + "]");
    -    closests_checkboxes.prop("checked", !closests_checkboxes.prop("checked")).change();
    +    var all_checkboxes = $("input[data-form-id=" + $(this).attr("data-form-id") + "]");
    +    all_checkboxes.prop("checked", !closests_checkboxes.prop("checked")).change();
       });
     
       // Draw domain admin table
    @@ -140,7 +140,7 @@ $(document).ready(function() {
               url: '/api/v1/delete/fwdhost',
               jsonp: false,
               complete: function (data) {
    -            location.reload();
    +            window.location.href = window.location.href;
               }
             });
           })
    @@ -150,6 +150,35 @@ $(document).ready(function() {
         }
       });
     
    +  $(document).on('click', '#delete_dkim_key', function(e) {
    +    e.preventDefault();
    +    var dkim_domain = $(this).data('dkim-domain');
    +    var dkim_selector = $(this).data('dkim-selector');
    +      $(document).on('show.bs.modal','#ConfirmDeleteModal', function () {
    +        $("#ItemsToDelete").empty();
    +        $("#ItemsToDelete").append("<li>" + dkim_domain + ", " + dkim_selector + "</li>");
    +      })
    +      $('#ConfirmDeleteModal').modal({
    +        backdrop: 'static',
    +        keyboard: false
    +      })
    +      .one('click', '#IsConfirmed', function(e) {
    +        $.ajax({
    +          type: "POST",
    +          dataType: "json",
    +          data: { "domains": JSON.stringify(dkim_domain) },
    +          url: '/api/v1/delete/dkim',
    +          jsonp: false,
    +          complete: function (data) {
    +            window.location.href = window.location.href;
    +          }
    +        });
    +      })
    +      .one('click', '#isCanceled', function(e) {
    +        $('#ConfirmDeleteModal').modal('hide');
    +      });;
    +  });
    +
       $("#refresh_dovecot_log").on('click', function(e) {
           function unix_time_format(tm) {
             var date = new Date(tm ? tm * 1000 : 0);
    diff --git a/data/web/js/mailbox.js b/data/web/js/mailbox.js
    index 1e168f59..39f2d976 100644
    --- a/data/web/js/mailbox.js
    +++ b/data/web/js/mailbox.js
    @@ -309,7 +309,7 @@ $(document).ready(function() {
                 url: '/api/v1/edit/alias',
                 jsonp: false,
                 complete: function (data) {
    -              location.reload();
    +              window.location.href = window.location.href;
                 }
               });
             }
    @@ -325,7 +325,7 @@ $(document).ready(function() {
                 url: '/api/v1/edit/alias',
                 jsonp: false,
                 complete: function (data) {
    -              location.reload();
    +              window.location.href = window.location.href;
                 }
               });
             }
    @@ -352,7 +352,7 @@ $(document).ready(function() {
                   url: '/api/v1/delete/alias',
                   jsonp: false,
                   complete: function (data) {
    -                location.reload();
    +              window.location.href = window.location.href;
                   }
                 });
               })
    diff --git a/data/web/json_api.php b/data/web/json_api.php
    index c48a1293..3d15d3f3 100644
    --- a/data/web/json_api.php
    +++ b/data/web/json_api.php
    @@ -356,6 +356,18 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                   return;
                 }
               break;
    +          case "csrf-cookie":
    +            if (isset($_SESSION['mailcow_cc_username']) && isset($_SESSION['mailcow_cc_role'])) {
    +              csrfprotector::refreshToken();
    +              echo json_encode(array(
    +                'type' => 'success',
    +                'msg' => 'Cookie refreshed'
    +              ));
    +            }
    +            else {
    +              return;
    +            }
    +          break;
               default:
                 echo '{}';
               break;
    @@ -368,46 +380,94 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                   $address = json_decode($_POST['address'], true);
                   if (is_array($address)) {
                     if (mailbox_delete_alias(array('address' => $address)) === false) {
    -                  echo json_encode(array(
    -                    'type' => 'error',
    -                    'message' => 'Deletion of item/s failed'
    -                  ));
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Deletion of items/s failed'
    +                    ));
    +                  }
                       exit();
                     }
    -                echo json_encode(array(
    -                  'type' => 'success',
    -                  'message' => 'Task completed'
    -                ));
    +                if (isset($_SESSION['return'])) {
    +                  echo json_encode($_SESSION['return']);
    +                }
    +                else {
    +                  echo json_encode(array(
    +                    'type' => 'success',
    +                    'msg' => 'Item/s deleted: ' . $domains
    +                  ));
    +                }
                   }
                 }
    -            else {
    -              echo json_encode(array(
    -                'type' => 'error',
    -                'message' => 'Cannot find address array in post data'
    -              ));
    -            }
               break;
               case "fwdhost":
                 if (isset($_POST['forwardinghost'])) {
    -              $forwardinghost = json_decode($_POST['forwardinghost'], true);
    +              $forwardinghost = (array)json_decode($_POST['forwardinghost'], true);
                   if (is_array($forwardinghost)) {
                     if (delete_forwarding_host(array('forwardinghost' => $forwardinghost)) === false) {
    -                  echo json_encode(array(
    -                    'type' => 'error',
    -                    'message' => 'Deletion of item/s failed'
    -                  ));
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Deletion of items/s failed'
    +                    ));
    +                  }
                       exit();
                     }
    -                echo json_encode(array(
    -                  'type' => 'success',
    -                  'message' => 'Task completed'
    -                ));
    +                if (isset($_SESSION['return'])) {
    +                  echo json_encode($_SESSION['return']);
    +                }
    +                else {
    +                  echo json_encode(array(
    +                    'type' => 'success',
    +                    'msg' => 'Item/s deleted: ' . $domains
    +                  ));
    +                }
                   }
                 }
                 else {
                   echo json_encode(array(
                     'type' => 'error',
    -                'message' => 'Cannot find forwardinghost array in post data'
    +                'msg' => 'Cannot find forwardinghost array in post data'
    +              ));
    +            }
    +          break;
    +          case "dkim":
    +            if (isset($_POST['domains'])) {
    +              $domains = (array)json_decode($_POST['domains'], true);
    +              if (is_array($domains)) {
    +                if (dkim_delete_key(array('domains' => $domains)) === false) {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Deletion of items/s failed'
    +                    ));
    +                  }
    +                  exit();
    +                }
    +                if (isset($_SESSION['return'])) {
    +                  echo json_encode($_SESSION['return']);
    +                }
    +                else {
    +                  echo json_encode(array(
    +                    'type' => 'success',
    +                    'msg' => 'Item/s deleted: ' . $domains
    +                  ));
    +                }
    +              }
    +            }
    +            else {
    +              echo json_encode(array(
    +                'type' => 'error',
    +                'msg' => 'Cannot find domains array in post data'
                   ));
                 }
               break;
    @@ -417,25 +477,25 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
             switch ($category) {
               case "alias":
                 if (isset($_POST['address']) && isset($_POST['active'])) {
    -              $address = json_decode($_POST['address'], true);
    +              $address = (array)json_decode($_POST['address'], true);
                   if (is_array($address)) {
                     if (mailbox_edit_alias(array('address' => $address, 'active' => ($_POST['active'] == "1") ? $active = 1 : null)) === false) {
                       echo json_encode(array(
                         'type' => 'error',
    -                    'message' => 'Edit item failed'
    +                    'msg' => 'Edit item failed'
                       ));
                       exit();
                     }
                     echo json_encode(array(
                       'type' => 'success',
    -                  'message' => 'Task completed'
    +                  'msg' => 'Task completed'
                     ));
                   }
                 }
                 else {
                   echo json_encode(array(
                     'type' => 'error',
    -                'message' => 'Cannot find address array in post data'
    +                'msg' => 'Cannot find address array in post data'
                   ));
                 }
               break;
    
    From 4cb8596ff001ada7d0adab56343fc1c7bddf794a Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Tue, 9 May 2017 23:25:13 +0200
    Subject: [PATCH 32/49] Remove unused and unnamed volume
    
    ---
     docker-compose.yml | 1 -
     1 file changed, 1 deletion(-)
    
    diff --git a/docker-compose.yml b/docker-compose.yml
    index 1deea6d9..eb43d8d9 100644
    --- a/docker-compose.yml
    +++ b/docker-compose.yml
    @@ -134,7 +134,6 @@ services:
           dns_search: mailcow-network
           volumes:
             - ./data/conf/sogo/:/etc/sogo/
    -        - /usr/lib/GNUstep/SOGo/WebServerResources/
           restart: always
           networks:
             mailcow-network:
    
    From f582f0f01bd629f2283a53218ecfc1874a291d1d Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Tue, 9 May 2017 23:25:23 +0200
    Subject: [PATCH 33/49] Various fixes, update u2flib
    
    ---
     data/web/css/mailcow.css                      |   7 +-
     data/web/css/noty.css                         | 650 ++++++++++++++++++
     data/web/inc/footer.inc.php                   |  25 +-
     data/web/inc/functions.inc.php                |   2 +
     data/web/inc/lib/composer.lock                |  18 +-
     .../inc/lib/vendor/composer/installed.json    |  70 +-
     .../vendor/yubico/u2flib-server/.travis.yml   |  18 +-
     .../inc/lib/vendor/yubico/u2flib-server/NEWS  |   4 +
     .../vendor/yubico/u2flib-server/apigen.neon   |   3 +-
     .../vendor/yubico/u2flib-server/composer.json |   7 +-
     .../yubico/u2flib-server/do-source-release.sh |   2 +-
     .../cli/{u2f-server.php => u2f-server.phps}   |   0
     .../localstorage/{index.php => index.phps}    |   0
     .../examples/pdo/{index.php => index.phps}    |   0
     .../vendor/yubico/u2flib-server/phpunit.xml   |   2 +-
     .../u2flib-server/src/u2flib_server/U2F.php   |   3 +-
     data/web/inc/prerequisites.inc.php            |  12 -
     data/web/js/admin.js                          |   4 +-
     data/web/js/notify.min.js                     |   1 +
     data/web/js/noty.min.js                       |   9 +
     20 files changed, 759 insertions(+), 78 deletions(-)
     create mode 100644 data/web/css/noty.css
     rename data/web/inc/lib/vendor/yubico/u2flib-server/examples/cli/{u2f-server.php => u2f-server.phps} (100%)
     rename data/web/inc/lib/vendor/yubico/u2flib-server/examples/localstorage/{index.php => index.phps} (100%)
     rename data/web/inc/lib/vendor/yubico/u2flib-server/examples/pdo/{index.php => index.phps} (100%)
     create mode 100644 data/web/js/notify.min.js
     create mode 100644 data/web/js/noty.min.js
    
    diff --git a/data/web/css/mailcow.css b/data/web/css/mailcow.css
    index 8ab3d1e9..90dccf93 100644
    --- a/data/web/css/mailcow.css
    +++ b/data/web/css/mailcow.css
    @@ -55,12 +55,11 @@ body.modal-open {
       overflow: inherit;
       padding-right: inherit !important;
     }
    -.mailcow-alert-box {
    +#mailcow-alert {
       position: fixed;
       bottom: 8px;
       right: 25px;
    -  min-width: 300px;
    -  max-width: 350px;
    +  min-width: 350px;
    +  max-width: 550px;
       z-index: 2000;
    -  display: none;
     }
    \ No newline at end of file
    diff --git a/data/web/css/noty.css b/data/web/css/noty.css
    new file mode 100644
    index 00000000..2df92f1f
    --- /dev/null
    +++ b/data/web/css/noty.css
    @@ -0,0 +1,650 @@
    +.noty_layout_mixin, #noty_layout__top, #noty_layout__topLeft, #noty_layout__topCenter, #noty_layout__topRight, #noty_layout__bottom, #noty_layout__bottomLeft, #noty_layout__bottomCenter, #noty_layout__bottomRight, #noty_layout__center, #noty_layout__centerLeft, #noty_layout__centerRight {
    +  position: fixed;
    +  margin: 0;
    +  padding: 0;
    +  z-index: 9999999;
    +  -webkit-transform: translateZ(0) scale(1, 1);
    +          transform: translateZ(0) scale(1, 1);
    +  -webkit-backface-visibility: hidden;
    +          backface-visibility: hidden;
    +  -webkit-font-smoothing: subpixel-antialiased;
    +  filter: blur(0);
    +  -webkit-filter: blur(0);
    +  max-width: 90%; }
    +
    +#noty_layout__top {
    +  top: 0;
    +  left: 5%;
    +  width: 90%; }
    +
    +#noty_layout__topLeft {
    +  top: 20px;
    +  left: 20px;
    +  width: 325px; }
    +
    +#noty_layout__topCenter {
    +  top: 5%;
    +  left: 50%;
    +  width: 325px;
    +  -webkit-transform: translate(-webkit-calc(-50% - .5px)) translateZ(0) scale(1, 1);
    +          transform: translate(calc(-50% - .5px)) translateZ(0) scale(1, 1); }
    +
    +#noty_layout__topRight {
    +  top: 20px;
    +  right: 20px;
    +  width: 325px; }
    +
    +#noty_layout__bottom {
    +  bottom: 0;
    +  left: 5%;
    +  width: 90%; }
    +
    +#noty_layout__bottomLeft {
    +  bottom: 20px;
    +  left: 20px;
    +  width: 325px; }
    +
    +#noty_layout__bottomCenter {
    +  bottom: 5%;
    +  left: 50%;
    +  width: 325px;
    +  -webkit-transform: translate(-webkit-calc(-50% - .5px)) translateZ(0) scale(1, 1);
    +          transform: translate(calc(-50% - .5px)) translateZ(0) scale(1, 1); }
    +
    +#noty_layout__bottomRight {
    +  bottom: 20px;
    +  right: 20px;
    +  width: 325px; }
    +
    +#noty_layout__center {
    +  top: 50%;
    +  left: 50%;
    +  width: 325px;
    +  -webkit-transform: translate(-webkit-calc(-50% - .5px), -webkit-calc(-50% - .5px)) translateZ(0) scale(1, 1);
    +          transform: translate(calc(-50% - .5px), calc(-50% - .5px)) translateZ(0) scale(1, 1); }
    +
    +#noty_layout__centerLeft {
    +  top: 50%;
    +  left: 20px;
    +  width: 325px;
    +  -webkit-transform: translate(0, -webkit-calc(-50% - .5px)) translateZ(0) scale(1, 1);
    +          transform: translate(0, calc(-50% - .5px)) translateZ(0) scale(1, 1); }
    +
    +#noty_layout__centerRight {
    +  top: 50%;
    +  right: 20px;
    +  width: 325px;
    +  -webkit-transform: translate(0, -webkit-calc(-50% - .5px)) translateZ(0) scale(1, 1);
    +          transform: translate(0, calc(-50% - .5px)) translateZ(0) scale(1, 1); }
    +
    +.noty_progressbar {
    +  display: none; }
    +
    +.noty_has_timeout .noty_progressbar {
    +  display: block;
    +  position: absolute;
    +  left: 0;
    +  bottom: 0;
    +  height: 3px;
    +  width: 100%;
    +  background-color: #646464;
    +  opacity: 0.2;
    +  filter: alpha(opacity=10); }
    +
    +.noty_bar {
    +  -webkit-backface-visibility: hidden;
    +  -webkit-transform: translate(0, 0) translateZ(0) scale(1, 1);
    +  -ms-transform: translate(0, 0) scale(1, 1);
    +      transform: translate(0, 0) scale(1, 1);
    +  -webkit-font-smoothing: subpixel-antialiased;
    +  overflow: hidden; }
    +
    +.noty_effects_open {
    +  opacity: 0;
    +  -webkit-transform: translate(50%);
    +      -ms-transform: translate(50%);
    +          transform: translate(50%);
    +  -webkit-animation: noty_anim_in 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    +          animation: noty_anim_in 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    +  -webkit-animation-fill-mode: forwards;
    +          animation-fill-mode: forwards; }
    +
    +.noty_effects_close {
    +  -webkit-animation: noty_anim_out 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    +          animation: noty_anim_out 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    +  -webkit-animation-fill-mode: forwards;
    +          animation-fill-mode: forwards; }
    +
    +.noty_fix_effects_height {
    +  -webkit-animation: noty_anim_height 75ms ease-out;
    +          animation: noty_anim_height 75ms ease-out; }
    +
    +.noty_close_with_click {
    +  cursor: pointer; }
    +
    +.noty_close_button {
    +  position: absolute;
    +  top: 2px;
    +  right: 2px;
    +  font-weight: bold;
    +  width: 20px;
    +  height: 20px;
    +  text-align: center;
    +  line-height: 20px;
    +  background-color: rgba(0, 0, 0, 0.05);
    +  border-radius: 2px;
    +  cursor: pointer;
    +  -webkit-transition: all .2s ease-out;
    +  transition: all .2s ease-out; }
    +
    +.noty_close_button:hover {
    +  background-color: rgba(0, 0, 0, 0.1); }
    +
    +.noty_modal {
    +  position: fixed;
    +  width: 100%;
    +  height: 100%;
    +  background-color: #000;
    +  z-index: 10000;
    +  opacity: .3;
    +  left: 0;
    +  top: 0; }
    +
    +.noty_modal.noty_modal_open {
    +  opacity: 0;
    +  -webkit-animation: noty_modal_in .3s ease-out;
    +          animation: noty_modal_in .3s ease-out; }
    +
    +.noty_modal.noty_modal_close {
    +  -webkit-animation: noty_modal_out .3s ease-out;
    +          animation: noty_modal_out .3s ease-out;
    +  -webkit-animation-fill-mode: forwards;
    +          animation-fill-mode: forwards; }
    +
    +@-webkit-keyframes noty_modal_in {
    +  100% {
    +    opacity: .3; } }
    +
    +@keyframes noty_modal_in {
    +  100% {
    +    opacity: .3; } }
    +
    +@-webkit-keyframes noty_modal_out {
    +  100% {
    +    opacity: 0; } }
    +
    +@keyframes noty_modal_out {
    +  100% {
    +    opacity: 0; } }
    +
    +@keyframes noty_modal_out {
    +  100% {
    +    opacity: 0; } }
    +
    +@-webkit-keyframes noty_anim_in {
    +  100% {
    +    -webkit-transform: translate(0);
    +            transform: translate(0);
    +    opacity: 1; } }
    +
    +@keyframes noty_anim_in {
    +  100% {
    +    -webkit-transform: translate(0);
    +            transform: translate(0);
    +    opacity: 1; } }
    +
    +@-webkit-keyframes noty_anim_out {
    +  100% {
    +    -webkit-transform: translate(50%);
    +            transform: translate(50%);
    +    opacity: 0; } }
    +
    +@keyframes noty_anim_out {
    +  100% {
    +    -webkit-transform: translate(50%);
    +            transform: translate(50%);
    +    opacity: 0; } }
    +
    +@-webkit-keyframes noty_anim_height {
    +  100% {
    +    height: 0; } }
    +
    +@keyframes noty_anim_height {
    +  100% {
    +    height: 0; } }
    +
    +.noty_theme__relax.noty_bar {
    +  margin: 4px 0;
    +  overflow: hidden;
    +  border-radius: 2px;
    +  position: relative; }
    +  .noty_theme__relax.noty_bar .noty_body {
    +    padding: 10px; }
    +  .noty_theme__relax.noty_bar .noty_buttons {
    +    border-top: 1px solid #e7e7e7;
    +    padding: 5px 10px; }
    +
    +.noty_theme__relax.noty_type__alert,
    +.noty_theme__relax.noty_type__notification {
    +  background-color: #fff;
    +  border: 1px solid #dedede;
    +  color: #444; }
    +
    +.noty_theme__relax.noty_type__warning {
    +  background-color: #FFEAA8;
    +  border: 1px solid #FFC237;
    +  color: #826200; }
    +  .noty_theme__relax.noty_type__warning .noty_buttons {
    +    border-color: #dfaa30; }
    +
    +.noty_theme__relax.noty_type__error {
    +  background-color: #FF8181;
    +  border: 1px solid #e25353;
    +  color: #FFF; }
    +  .noty_theme__relax.noty_type__error .noty_buttons {
    +    border-color: darkred; }
    +
    +.noty_theme__relax.noty_type__info,
    +.noty_theme__relax.noty_type__information {
    +  background-color: #78C5E7;
    +  border: 1px solid #3badd6;
    +  color: #FFF; }
    +  .noty_theme__relax.noty_type__info .noty_buttons,
    +  .noty_theme__relax.noty_type__information .noty_buttons {
    +    border-color: #0B90C4; }
    +
    +.noty_theme__relax.noty_type__success {
    +  background-color: #BCF5BC;
    +  border: 1px solid #7cdd77;
    +  color: darkgreen; }
    +  .noty_theme__relax.noty_type__success .noty_buttons {
    +    border-color: #50C24E; }
    +
    +.noty_theme__metroui.noty_bar {
    +  margin: 4px 0;
    +  overflow: hidden;
    +  position: relative;
    +  box-shadow: rgba(0, 0, 0, 0.298039) 0 0 5px 0; }
    +  .noty_theme__metroui.noty_bar .noty_progressbar {
    +    position: absolute;
    +    left: 0;
    +    bottom: 0;
    +    height: 3px;
    +    width: 100%;
    +    background-color: #000;
    +    opacity: 0.2;
    +    filter: alpha(opacity=20); }
    +  .noty_theme__metroui.noty_bar .noty_body {
    +    padding: 1.25em;
    +    font-size: 14px; }
    +  .noty_theme__metroui.noty_bar .noty_buttons {
    +    padding: 0 10px .5em 10px; }
    +
    +.noty_theme__metroui.noty_type__alert,
    +.noty_theme__metroui.noty_type__notification {
    +  background-color: #fff;
    +  color: #1d1d1d; }
    +
    +.noty_theme__metroui.noty_type__warning {
    +  background-color: #FA6800;
    +  color: #fff; }
    +
    +.noty_theme__metroui.noty_type__error {
    +  background-color: #CE352C;
    +  color: #FFF; }
    +
    +.noty_theme__metroui.noty_type__info,
    +.noty_theme__metroui.noty_type__information {
    +  background-color: #1BA1E2;
    +  color: #FFF; }
    +
    +.noty_theme__metroui.noty_type__success {
    +  background-color: #60A917;
    +  color: #fff; }
    +
    +.noty_theme__mint.noty_bar {
    +  margin: 4px 0;
    +  overflow: hidden;
    +  border-radius: 2px;
    +  position: relative; }
    +  .noty_theme__mint.noty_bar .noty_body {
    +    padding: 10px;
    +    font-size: 14px; }
    +  .noty_theme__mint.noty_bar .noty_buttons {
    +    padding: 10px; }
    +
    +.noty_theme__mint.noty_type__alert,
    +.noty_theme__mint.noty_type__notification {
    +  background-color: #fff;
    +  border-bottom: 1px solid #D1D1D1;
    +  color: #2F2F2F; }
    +
    +.noty_theme__mint.noty_type__warning {
    +  background-color: #FFAE42;
    +  border-bottom: 1px solid #E89F3C;
    +  color: #fff; }
    +
    +.noty_theme__mint.noty_type__error {
    +  background-color: #DE636F;
    +  border-bottom: 1px solid #CA5A65;
    +  color: #fff; }
    +
    +.noty_theme__mint.noty_type__info,
    +.noty_theme__mint.noty_type__information {
    +  background-color: #7F7EFF;
    +  border-bottom: 1px solid #7473E8;
    +  color: #fff; }
    +
    +.noty_theme__mint.noty_type__success {
    +  background-color: #AFC765;
    +  border-bottom: 1px solid #A0B55C;
    +  color: #fff; }
    +
    +.noty_theme__sunset.noty_bar {
    +  margin: 4px 0;
    +  overflow: hidden;
    +  border-radius: 2px;
    +  position: relative; }
    +  .noty_theme__sunset.noty_bar .noty_body {
    +    padding: 10px;
    +    font-size: 14px;
    +    text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1); }
    +  .noty_theme__sunset.noty_bar .noty_buttons {
    +    padding: 10px; }
    +
    +.noty_theme__sunset.noty_type__alert,
    +.noty_theme__sunset.noty_type__notification {
    +  background-color: #073B4C;
    +  color: #fff; }
    +  .noty_theme__sunset.noty_type__alert .noty_progressbar,
    +  .noty_theme__sunset.noty_type__notification .noty_progressbar {
    +    background-color: #fff; }
    +
    +.noty_theme__sunset.noty_type__warning {
    +  background-color: #FFD166;
    +  color: #fff; }
    +
    +.noty_theme__sunset.noty_type__error {
    +  background-color: #EF476F;
    +  color: #fff; }
    +  .noty_theme__sunset.noty_type__error .noty_progressbar {
    +    opacity: .4; }
    +
    +.noty_theme__sunset.noty_type__info,
    +.noty_theme__sunset.noty_type__information {
    +  background-color: #118AB2;
    +  color: #fff; }
    +  .noty_theme__sunset.noty_type__info .noty_progressbar,
    +  .noty_theme__sunset.noty_type__information .noty_progressbar {
    +    opacity: .6; }
    +
    +.noty_theme__sunset.noty_type__success {
    +  background-color: #06D6A0;
    +  color: #fff; }
    +
    +.noty_theme__bootstrap-v3.noty_bar {
    +  margin: 4px 0;
    +  overflow: hidden;
    +  position: relative;
    +  border: 1px solid transparent;
    +  border-radius: 4px; }
    +  .noty_theme__bootstrap-v3.noty_bar .noty_body {
    +    padding: 15px; }
    +  .noty_theme__bootstrap-v3.noty_bar .noty_buttons {
    +    padding: 10px; }
    +  .noty_theme__bootstrap-v3.noty_bar .noty_close_button {
    +    font-size: 21px;
    +    font-weight: 700;
    +    line-height: 1;
    +    color: #000;
    +    text-shadow: 0 1px 0 #fff;
    +    filter: alpha(opacity=20);
    +    opacity: .2;
    +    background: transparent; }
    +  .noty_theme__bootstrap-v3.noty_bar .noty_close_button:hover {
    +    background: transparent;
    +    text-decoration: none;
    +    cursor: pointer;
    +    filter: alpha(opacity=50);
    +    opacity: .5; }
    +
    +.noty_theme__bootstrap-v3.noty_type__alert,
    +.noty_theme__bootstrap-v3.noty_type__notification {
    +  background-color: #fff;
    +  color: inherit; }
    +
    +.noty_theme__bootstrap-v3.noty_type__warning {
    +  background-color: #fcf8e3;
    +  color: #8a6d3b;
    +  border-color: #faebcc; }
    +
    +.noty_theme__bootstrap-v3.noty_type__error {
    +  background-color: #f2dede;
    +  color: #a94442;
    +  border-color: #ebccd1; }
    +
    +.noty_theme__bootstrap-v3.noty_type__info,
    +.noty_theme__bootstrap-v3.noty_type__information {
    +  background-color: #d9edf7;
    +  color: #31708f;
    +  border-color: #bce8f1; }
    +
    +.noty_theme__bootstrap-v3.noty_type__success {
    +  background-color: #dff0d8;
    +  color: #3c763d;
    +  border-color: #d6e9c6; }
    +
    +.noty_theme__bootstrap-v4.noty_bar {
    +  margin: 4px 0;
    +  overflow: hidden;
    +  position: relative;
    +  border: 1px solid transparent;
    +  border-radius: .25rem; }
    +  .noty_theme__bootstrap-v4.noty_bar .noty_body {
    +    padding: .75rem 1.25rem; }
    +  .noty_theme__bootstrap-v4.noty_bar .noty_buttons {
    +    padding: 10px; }
    +  .noty_theme__bootstrap-v4.noty_bar .noty_close_button {
    +    font-size: 1.5rem;
    +    font-weight: 700;
    +    line-height: 1;
    +    color: #000;
    +    text-shadow: 0 1px 0 #fff;
    +    filter: alpha(opacity=20);
    +    opacity: .5;
    +    background: transparent; }
    +  .noty_theme__bootstrap-v4.noty_bar .noty_close_button:hover {
    +    background: transparent;
    +    text-decoration: none;
    +    cursor: pointer;
    +    filter: alpha(opacity=50);
    +    opacity: .75; }
    +
    +.noty_theme__bootstrap-v4.noty_type__alert,
    +.noty_theme__bootstrap-v4.noty_type__notification {
    +  background-color: #fff;
    +  color: inherit; }
    +
    +.noty_theme__bootstrap-v4.noty_type__warning {
    +  background-color: #fcf8e3;
    +  color: #8a6d3b;
    +  border-color: #faebcc; }
    +
    +.noty_theme__bootstrap-v4.noty_type__error {
    +  background-color: #f2dede;
    +  color: #a94442;
    +  border-color: #ebccd1; }
    +
    +.noty_theme__bootstrap-v4.noty_type__info,
    +.noty_theme__bootstrap-v4.noty_type__information {
    +  background-color: #d9edf7;
    +  color: #31708f;
    +  border-color: #bce8f1; }
    +
    +.noty_theme__bootstrap-v4.noty_type__success {
    +  background-color: #dff0d8;
    +  color: #3c763d;
    +  border-color: #d6e9c6; }
    +
    +.noty_theme__semanticui.noty_bar {
    +  margin: 4px 0;
    +  overflow: hidden;
    +  position: relative;
    +  border: 1px solid transparent;
    +  font-size: 1em;
    +  border-radius: .28571429rem;
    +  box-shadow: 0 0 0 1px rgba(34, 36, 38, 0.22) inset, 0 0 0 0 transparent; }
    +  .noty_theme__semanticui.noty_bar .noty_body {
    +    padding: 1em 1.5em;
    +    line-height: 1.4285em; }
    +  .noty_theme__semanticui.noty_bar .noty_buttons {
    +    padding: 10px; }
    +
    +.noty_theme__semanticui.noty_type__alert,
    +.noty_theme__semanticui.noty_type__notification {
    +  background-color: #f8f8f9;
    +  color: rgba(0, 0, 0, 0.87); }
    +
    +.noty_theme__semanticui.noty_type__warning {
    +  background-color: #fffaf3;
    +  color: #573a08;
    +  box-shadow: 0 0 0 1px #c9ba9b inset, 0 0 0 0 transparent; }
    +
    +.noty_theme__semanticui.noty_type__error {
    +  background-color: #fff6f6;
    +  color: #9f3a38;
    +  box-shadow: 0 0 0 1px #e0b4b4 inset, 0 0 0 0 transparent; }
    +
    +.noty_theme__semanticui.noty_type__info,
    +.noty_theme__semanticui.noty_type__information {
    +  background-color: #f8ffff;
    +  color: #276f86;
    +  box-shadow: 0 0 0 1px #a9d5de inset, 0 0 0 0 transparent; }
    +
    +.noty_theme__semanticui.noty_type__success {
    +  background-color: #fcfff5;
    +  color: #2c662d;
    +  box-shadow: 0 0 0 1px #a3c293 inset, 0 0 0 0 transparent; }
    +
    +.noty_theme__nest.noty_bar {
    +  margin: 0 0 15px 0;
    +  overflow: hidden;
    +  border-radius: 2px;
    +  position: relative;
    +  box-shadow: rgba(0, 0, 0, 0.098039) 5px 4px 10px 0; }
    +  .noty_theme__nest.noty_bar .noty_body {
    +    padding: 10px;
    +    font-size: 14px;
    +    text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1); }
    +  .noty_theme__nest.noty_bar .noty_buttons {
    +    padding: 10px; }
    +
    +.noty_layout .noty_theme__nest.noty_bar {
    +  z-index: 5; }
    +
    +.noty_layout .noty_theme__nest.noty_bar:nth-child(2) {
    +  position: absolute;
    +  top: 0;
    +  margin-top: 4px;
    +  margin-right: -4px;
    +  margin-left: 4px;
    +  z-index: 4;
    +  width: 100%; }
    +
    +.noty_layout .noty_theme__nest.noty_bar:nth-child(3) {
    +  position: absolute;
    +  top: 0;
    +  margin-top: 8px;
    +  margin-right: -8px;
    +  margin-left: 8px;
    +  z-index: 3;
    +  width: 100%; }
    +
    +.noty_layout .noty_theme__nest.noty_bar:nth-child(4) {
    +  position: absolute;
    +  top: 0;
    +  margin-top: 12px;
    +  margin-right: -12px;
    +  margin-left: 12px;
    +  z-index: 2;
    +  width: 100%; }
    +
    +.noty_layout .noty_theme__nest.noty_bar:nth-child(5) {
    +  position: absolute;
    +  top: 0;
    +  margin-top: 16px;
    +  margin-right: -16px;
    +  margin-left: 16px;
    +  z-index: 1;
    +  width: 100%; }
    +
    +.noty_layout .noty_theme__nest.noty_bar:nth-child(n+6) {
    +  position: absolute;
    +  top: 0;
    +  margin-top: 20px;
    +  margin-right: -20px;
    +  margin-left: 20px;
    +  z-index: -1;
    +  width: 100%; }
    +
    +#noty_layout__bottomLeft .noty_theme__nest.noty_bar:nth-child(2),
    +#noty_layout__topLeft .noty_theme__nest.noty_bar:nth-child(2) {
    +  margin-top: 4px;
    +  margin-left: -4px;
    +  margin-right: 4px; }
    +
    +#noty_layout__bottomLeft .noty_theme__nest.noty_bar:nth-child(3),
    +#noty_layout__topLeft .noty_theme__nest.noty_bar:nth-child(3) {
    +  margin-top: 8px;
    +  margin-left: -8px;
    +  margin-right: 8px; }
    +
    +#noty_layout__bottomLeft .noty_theme__nest.noty_bar:nth-child(4),
    +#noty_layout__topLeft .noty_theme__nest.noty_bar:nth-child(4) {
    +  margin-top: 12px;
    +  margin-left: -12px;
    +  margin-right: 12px; }
    +
    +#noty_layout__bottomLeft .noty_theme__nest.noty_bar:nth-child(5),
    +#noty_layout__topLeft .noty_theme__nest.noty_bar:nth-child(5) {
    +  margin-top: 16px;
    +  margin-left: -16px;
    +  margin-right: 16px; }
    +
    +#noty_layout__bottomLeft .noty_theme__nest.noty_bar:nth-child(n+6),
    +#noty_layout__topLeft .noty_theme__nest.noty_bar:nth-child(n+6) {
    +  margin-top: 20px;
    +  margin-left: -20px;
    +  margin-right: 20px; }
    +
    +.noty_theme__nest.noty_type__alert,
    +.noty_theme__nest.noty_type__notification {
    +  background-color: #073B4C;
    +  color: #fff; }
    +  .noty_theme__nest.noty_type__alert .noty_progressbar,
    +  .noty_theme__nest.noty_type__notification .noty_progressbar {
    +    background-color: #fff; }
    +
    +.noty_theme__nest.noty_type__warning {
    +  background-color: #FFD166;
    +  color: #fff; }
    +
    +.noty_theme__nest.noty_type__error {
    +  background-color: #EF476F;
    +  color: #fff; }
    +  .noty_theme__nest.noty_type__error .noty_progressbar {
    +    opacity: .4; }
    +
    +.noty_theme__nest.noty_type__info,
    +.noty_theme__nest.noty_type__information {
    +  background-color: #118AB2;
    +  color: #fff; }
    +  .noty_theme__nest.noty_type__info .noty_progressbar,
    +  .noty_theme__nest.noty_type__information .noty_progressbar {
    +    opacity: .6; }
    +
    +.noty_theme__nest.noty_type__success {
    +  background-color: #06D6A0;
    +  color: #fff; }
    +
    +/*# sourceMappingURL=noty.css.map*/
    \ No newline at end of file
    diff --git a/data/web/inc/footer.inc.php b/data/web/inc/footer.inc.php
    index 6fc6d321..08fd6d00 100644
    --- a/data/web/inc/footer.inc.php
    +++ b/data/web/inc/footer.inc.php
    @@ -59,9 +59,7 @@ $(document).ready(function() {
         $('#mailcow-alert-text').text(message);
       }
       // PHP error handler
    -  <?php if (isset($_SESSION['return'])): ?>
    -  mailcow_alert_box("<?=$_SESSION['return']['type'];?>",  "<?=$_SESSION['return']['msg'];?>");
    -  <?php endif; unset($_SESSION['return']); ?>
    +
     
       // Confirm TFA modal
       <?php if (isset($_SESSION['pending_tfa_method'])):?>
    @@ -230,10 +228,25 @@ $(document).ready(function() {
     	});
     });
     </script>
    -<div class="mailcow-alert-box alert" role="alert">
    -  <a href="#" class="close" data-dismiss="alert"> &times;</a>
    -  <span id="mailcow-alert-text"></span>
    +
    +<div class="container">
    +  <div id="mailcow-alert" class="alert" role="alert">
    +    <a href="#" class="close" data-dismiss="alert"> &times;</a>
    +    <span id="mailcow-alert-text"></span>
    +  </div>
     </div>
    +
     </body>
    +<?php // Notifications ?>
    +<script>
    +function mailcow_alert_box(msg, type) {
    +  document.getElementById('mailcow-alert').style.display = 'visible';
    +  document.getElementById('mailcow-alert-text').innerHTML = msg;
    +  document.getElementById("mailcow-alert").className = "alert alert-" + type;
    +}
    +<?php if (isset($_SESSION['return'])): ?>
    +mailcow_alert_box("<?=$_SESSION['return']['msg'];?>",  "<?=$_SESSION['return']['type'];?>");
    +<?php endif; unset($_SESSION['return']); ?>
    +</script>
     </html>
     <?php $stmt = null; $pdo = null; ?>
    diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php
    index 50b26660..ac99a014 100644
    --- a/data/web/inc/functions.inc.php
    +++ b/data/web/inc/functions.inc.php
    @@ -2552,6 +2552,7 @@ function mailbox_add_domain($postarray) {
       // relay_all_recipients   int
       // backupmx               int
     	global $pdo;
    +	global $redis;
     	global $lang;
     	if ($_SESSION['mailcow_cc_role'] != "admin") {
     		$_SESSION['return'] = array(
    @@ -5177,6 +5178,7 @@ function add_forwarding_host($postarray) {
     	else {
     		$hosts = get_outgoing_hosts_best_guess($host);
     	}
    +  print_r($hosts);
     	if (empty($hosts)) {
     		$_SESSION['return'] = array(
     			'type' => 'danger',
    diff --git a/data/web/inc/lib/composer.lock b/data/web/inc/lib/composer.lock
    index d0f94fc4..8e9ac8c2 100644
    --- a/data/web/inc/lib/composer.lock
    +++ b/data/web/inc/lib/composer.lock
    @@ -40,7 +40,7 @@
                     "owasp",
                     "security"
                 ],
    -            "time": "2017-04-12 05:47:07"
    +            "time": "2017-04-12T05:47:07+00:00"
             },
             {
                 "name": "robthree/twofactorauth",
    @@ -95,20 +95,24 @@
             },
             {
                 "name": "yubico/u2flib-server",
    -            "version": "1.0.0",
    +            "version": "1.0.1",
                 "source": {
                     "type": "git",
                     "url": "https://github.com/Yubico/php-u2flib-server.git",
    -                "reference": "407eb21da24150aad30bcd8cc0ee72963eac5e9d"
    +                "reference": "dc318c80b59e62921c210f31b014def26ceebbab"
                 },
                 "dist": {
                     "type": "zip",
    -                "url": "https://api.github.com/repos/Yubico/php-u2flib-server/zipball/407eb21da24150aad30bcd8cc0ee72963eac5e9d",
    -                "reference": "407eb21da24150aad30bcd8cc0ee72963eac5e9d",
    +                "url": "https://api.github.com/repos/Yubico/php-u2flib-server/zipball/dc318c80b59e62921c210f31b014def26ceebbab",
    +                "reference": "dc318c80b59e62921c210f31b014def26ceebbab",
                     "shasum": ""
                 },
                 "require": {
    -                "ext-openssl": "*"
    +                "ext-openssl": "*",
    +                "php": ">=5.6"
    +            },
    +            "require-dev": {
    +                "phpunit/phpunit": "~5.7"
                 },
                 "type": "library",
                 "autoload": {
    @@ -122,7 +126,7 @@
                 ],
                 "description": "Library for U2F implementation",
                 "homepage": "https://developers.yubico.com/php-u2flib-server",
    -            "time": "2016-02-19T09:47:51+00:00"
    +            "time": "2017-05-09T07:33:58+00:00"
             }
         ],
         "packages-dev": [],
    diff --git a/data/web/inc/lib/vendor/composer/installed.json b/data/web/inc/lib/vendor/composer/installed.json
    index fa07bcd4..cd2803e5 100644
    --- a/data/web/inc/lib/vendor/composer/installed.json
    +++ b/data/web/inc/lib/vendor/composer/installed.json
    @@ -52,39 +52,6 @@
                 "tfa"
             ]
         },
    -    {
    -        "name": "yubico/u2flib-server",
    -        "version": "1.0.0",
    -        "version_normalized": "1.0.0.0",
    -        "source": {
    -            "type": "git",
    -            "url": "https://github.com/Yubico/php-u2flib-server.git",
    -            "reference": "407eb21da24150aad30bcd8cc0ee72963eac5e9d"
    -        },
    -        "dist": {
    -            "type": "zip",
    -            "url": "https://api.github.com/repos/Yubico/php-u2flib-server/zipball/407eb21da24150aad30bcd8cc0ee72963eac5e9d",
    -            "reference": "407eb21da24150aad30bcd8cc0ee72963eac5e9d",
    -            "shasum": ""
    -        },
    -        "require": {
    -            "ext-openssl": "*"
    -        },
    -        "time": "2016-02-19T09:47:51+00:00",
    -        "type": "library",
    -        "installation-source": "dist",
    -        "autoload": {
    -            "classmap": [
    -                "src/"
    -            ]
    -        },
    -        "notification-url": "https://packagist.org/downloads/",
    -        "license": [
    -            "BSD-2-Clause"
    -        ],
    -        "description": "Library for U2F implementation",
    -        "homepage": "https://developers.yubico.com/php-u2flib-server"
    -    },
         {
             "name": "owasp/csrf-protector-php",
             "version": "dev-master",
    @@ -122,5 +89,42 @@
                 "owasp",
                 "security"
             ]
    +    },
    +    {
    +        "name": "yubico/u2flib-server",
    +        "version": "1.0.1",
    +        "version_normalized": "1.0.1.0",
    +        "source": {
    +            "type": "git",
    +            "url": "https://github.com/Yubico/php-u2flib-server.git",
    +            "reference": "dc318c80b59e62921c210f31b014def26ceebbab"
    +        },
    +        "dist": {
    +            "type": "zip",
    +            "url": "https://api.github.com/repos/Yubico/php-u2flib-server/zipball/dc318c80b59e62921c210f31b014def26ceebbab",
    +            "reference": "dc318c80b59e62921c210f31b014def26ceebbab",
    +            "shasum": ""
    +        },
    +        "require": {
    +            "ext-openssl": "*",
    +            "php": ">=5.6"
    +        },
    +        "require-dev": {
    +            "phpunit/phpunit": "~5.7"
    +        },
    +        "time": "2017-05-09T07:33:58+00:00",
    +        "type": "library",
    +        "installation-source": "dist",
    +        "autoload": {
    +            "classmap": [
    +                "src/"
    +            ]
    +        },
    +        "notification-url": "https://packagist.org/downloads/",
    +        "license": [
    +            "BSD-2-Clause"
    +        ],
    +        "description": "Library for U2F implementation",
    +        "homepage": "https://developers.yubico.com/php-u2flib-server"
         }
     ]
    diff --git a/data/web/inc/lib/vendor/yubico/u2flib-server/.travis.yml b/data/web/inc/lib/vendor/yubico/u2flib-server/.travis.yml
    index 781f2b84..b4282b2c 100644
    --- a/data/web/inc/lib/vendor/yubico/u2flib-server/.travis.yml
    +++ b/data/web/inc/lib/vendor/yubico/u2flib-server/.travis.yml
    @@ -1,19 +1,21 @@
     language: php
     sudo: false
     php:
    -  - 5.3
    -  - 5.4
    -  - 5.5
    -  - 5.6
       - 7.0
    +  - 7.1
       - hhvm
    -  - hhvm-nightly
    -after_success:
    -  - test -z $COVERALLS || (composer require satooshi/php-coveralls && vendor/bin/coveralls -v)
     matrix:
       include:
         - php: 5.6
           env: COVERALLS=true
       allow_failures:
         - php: hhvm
    -    - php: hhvm-nightly
    +
    +before_script:
    +  - composer install
    +
    +script:
    +  - ./vendor/phpunit/phpunit/phpunit -c phpunit.xml
    +
    +after_success:
    +  - test -z $COVERALLS || (composer require satooshi/php-coveralls && vendor/bin/coveralls -v)
    diff --git a/data/web/inc/lib/vendor/yubico/u2flib-server/NEWS b/data/web/inc/lib/vendor/yubico/u2flib-server/NEWS
    index 0fffd587..a8f97ae7 100644
    --- a/data/web/inc/lib/vendor/yubico/u2flib-server/NEWS
    +++ b/data/web/inc/lib/vendor/yubico/u2flib-server/NEWS
    @@ -1,5 +1,9 @@
     php-u2flib-server NEWS -- History of user-visible changes.
     
    +* Version 1.0.1 (released 2017-05-09)
    + ** Move examples to phps so they don't execute by default
    + ** Use common challenge for multiple registrations
    +
     * Version 1.0.0 (released 2016-02-19)
      ** Give an early error on openssl < 1.0
      ** Support devices with initial counter 0
    diff --git a/data/web/inc/lib/vendor/yubico/u2flib-server/apigen.neon b/data/web/inc/lib/vendor/yubico/u2flib-server/apigen.neon
    index 80d9e744..bbb7071b 100644
    --- a/data/web/inc/lib/vendor/yubico/u2flib-server/apigen.neon
    +++ b/data/web/inc/lib/vendor/yubico/u2flib-server/apigen.neon
    @@ -3,7 +3,8 @@ destination: apidocs
     source:
       - src/u2flib_server
     
    -exclude: "*/tests/*"
    +exclude:
    +  - "*/tests/*"
     
     groups: none
     
    diff --git a/data/web/inc/lib/vendor/yubico/u2flib-server/composer.json b/data/web/inc/lib/vendor/yubico/u2flib-server/composer.json
    index f14a88f6..5b3a970d 100644
    --- a/data/web/inc/lib/vendor/yubico/u2flib-server/composer.json
    +++ b/data/web/inc/lib/vendor/yubico/u2flib-server/composer.json
    @@ -4,10 +4,13 @@
       "homepage":"https://developers.yubico.com/php-u2flib-server",
       "license":"BSD-2-Clause",
       "require": {
    -    "ext-openssl":"*"
    +    "ext-openssl":"*",
    +    "php": ">=5.6"
       },
       "autoload": {
         "classmap": ["src/"]
    +  },
    +  "require-dev": {
    +    "phpunit/phpunit": "~5.7"
       }
     }
    -
    diff --git a/data/web/inc/lib/vendor/yubico/u2flib-server/do-source-release.sh b/data/web/inc/lib/vendor/yubico/u2flib-server/do-source-release.sh
    index 3c592ea3..7e501736 100755
    --- a/data/web/inc/lib/vendor/yubico/u2flib-server/do-source-release.sh
    +++ b/data/web/inc/lib/vendor/yubico/u2flib-server/do-source-release.sh
    @@ -32,7 +32,7 @@ mkdir -p $releasedir
     git archive $VERSION --format=tar | tar -xC $releasedir
     git2cl > $releasedir/ChangeLog
     cd $releasedir
    -apigen
    +apigen generate
     cd -
     tar -cz --directory=$tmpdir --file=${releasename}.tar.gz $releasename
     gpg --detach-sign --default-key $PGP_KEYID ${releasename}.tar.gz
    diff --git a/data/web/inc/lib/vendor/yubico/u2flib-server/examples/cli/u2f-server.php b/data/web/inc/lib/vendor/yubico/u2flib-server/examples/cli/u2f-server.phps
    similarity index 100%
    rename from data/web/inc/lib/vendor/yubico/u2flib-server/examples/cli/u2f-server.php
    rename to data/web/inc/lib/vendor/yubico/u2flib-server/examples/cli/u2f-server.phps
    diff --git a/data/web/inc/lib/vendor/yubico/u2flib-server/examples/localstorage/index.php b/data/web/inc/lib/vendor/yubico/u2flib-server/examples/localstorage/index.phps
    similarity index 100%
    rename from data/web/inc/lib/vendor/yubico/u2flib-server/examples/localstorage/index.php
    rename to data/web/inc/lib/vendor/yubico/u2flib-server/examples/localstorage/index.phps
    diff --git a/data/web/inc/lib/vendor/yubico/u2flib-server/examples/pdo/index.php b/data/web/inc/lib/vendor/yubico/u2flib-server/examples/pdo/index.phps
    similarity index 100%
    rename from data/web/inc/lib/vendor/yubico/u2flib-server/examples/pdo/index.php
    rename to data/web/inc/lib/vendor/yubico/u2flib-server/examples/pdo/index.phps
    diff --git a/data/web/inc/lib/vendor/yubico/u2flib-server/phpunit.xml b/data/web/inc/lib/vendor/yubico/u2flib-server/phpunit.xml
    index 603e6935..fa6f08e8 100644
    --- a/data/web/inc/lib/vendor/yubico/u2flib-server/phpunit.xml
    +++ b/data/web/inc/lib/vendor/yubico/u2flib-server/phpunit.xml
    @@ -1,7 +1,7 @@
     <phpunit
         colors="true">
         <testsuite name="tests">
    -        <directory suffix="test.php">.</directory>
    +        <directory suffix="test.php">tests</directory>
         </testsuite>
         <logging>
             <log type="coverage-clover" target="build/logs/clover.xml"/>
    diff --git a/data/web/inc/lib/vendor/yubico/u2flib-server/src/u2flib_server/U2F.php b/data/web/inc/lib/vendor/yubico/u2flib-server/src/u2flib_server/U2F.php
    index b79d7fac..a11c78fb 100644
    --- a/data/web/inc/lib/vendor/yubico/u2flib-server/src/u2flib_server/U2F.php
    +++ b/data/web/inc/lib/vendor/yubico/u2flib-server/src/u2flib_server/U2F.php
    @@ -222,6 +222,7 @@ class U2F
         public function getAuthenticateData(array $registrations)
         {
             $sigs = array();
    +        $challenge = $this->createChallenge();
             foreach ($registrations as $reg) {
                 if( !is_object( $reg ) ) {
                     throw new \InvalidArgumentException('$registrations of getAuthenticateData() method only accepts array of object.');
    @@ -230,7 +231,7 @@ class U2F
                 $sig = new SignRequest();
                 $sig->appId = $this->appId;
                 $sig->keyHandle = $reg->keyHandle;
    -            $sig->challenge = $this->createChallenge();
    +            $sig->challenge = $challenge;
                 $sigs[] = $sig;
             }
             return $sigs;
    diff --git a/data/web/inc/prerequisites.inc.php b/data/web/inc/prerequisites.inc.php
    index 3961aa00..8a96e66e 100644
    --- a/data/web/inc/prerequisites.inc.php
    +++ b/data/web/inc/prerequisites.inc.php
    @@ -16,18 +16,6 @@ require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/lib/vendor/autoload.php';
     $u2f = new u2flib_server\U2F('https://' . $_SERVER['HTTP_HOST']);
     $tfa = new RobThree\Auth\TwoFactorAuth('mailcow UI');
     
    -// OWASP CSRF Protector
    -$csrfProtector = new csrfProtector;
    -class mailcowCsrfProtector extends csrfprotector {
    -  public static function logCSRFattack() {
    -    $_SESSION['return'] = array(
    -      'type' => 'warning',
    -      'msg' => 'CSRF violation, please try again.'
    -    );
    -  }
    -}
    -mailcowCsrfProtector::init();
    -
     // Redis
     $redis = new Redis();
     $redis->connect('redis-mailcow', 6379);
    diff --git a/data/web/js/admin.js b/data/web/js/admin.js
    index 76367b15..4ad8246b 100644
    --- a/data/web/js/admin.js
    +++ b/data/web/js/admin.js
    @@ -28,7 +28,7 @@ $(document).ready(function() {
       $(document).on('click', '#toggle_multi_select_all', function(e) {
         e.preventDefault();
         var all_checkboxes = $("input[data-form-id=" + $(this).attr("data-form-id") + "]");
    -    all_checkboxes.prop("checked", !closests_checkboxes.prop("checked")).change();
    +    all_checkboxes.prop("checked", !all_checkboxes.prop("checked")).change();
       });
     
       // Draw domain admin table
    @@ -170,7 +170,7 @@ $(document).ready(function() {
               url: '/api/v1/delete/dkim',
               jsonp: false,
               complete: function (data) {
    -            window.location.href = window.location.href;
    +            mailcow_alert_box("warn", "asd");
               }
             });
           })
    diff --git a/data/web/js/notify.min.js b/data/web/js/notify.min.js
    new file mode 100644
    index 00000000..6766fd1d
    --- /dev/null
    +++ b/data/web/js/notify.min.js
    @@ -0,0 +1 @@
    +(function(e){typeof define=="function"&&define.amd?define(["jquery"],e):typeof module=="object"&&module.exports?module.exports=function(t,n){return n===undefined&&(typeof window!="undefined"?n=require("jquery"):n=require("jquery")(t)),e(n),n}:e(jQuery)})(function(e){function A(t,n,i){typeof i=="string"&&(i={className:i}),this.options=E(w,e.isPlainObject(i)?i:{}),this.loadHTML(),this.wrapper=e(h.html),this.options.clickToHide&&this.wrapper.addClass(r+"-hidable"),this.wrapper.data(r,this),this.arrow=this.wrapper.find("."+r+"-arrow"),this.container=this.wrapper.find("."+r+"-container"),this.container.append(this.userContainer),t&&t.length&&(this.elementType=t.attr("type"),this.originalElement=t,this.elem=N(t),this.elem.data(r,this),this.elem.before(this.wrapper)),this.container.hide(),this.run(n)}var t=[].indexOf||function(e){for(var t=0,n=this.length;t<n;t++)if(t in this&&this[t]===e)return t;return-1},n="notify",r=n+"js",i=n+"!blank",s={t:"top",m:"middle",b:"bottom",l:"left",c:"center",r:"right"},o=["l","c","r"],u=["t","m","b"],a=["t","b","l","r"],f={t:"b",m:null,b:"t",l:"r",c:null,r:"l"},l=function(t){var n;return n=[],e.each(t.split(/\W+/),function(e,t){var r;r=t.toLowerCase().charAt(0);if(s[r])return n.push(r)}),n},c={},h={name:"core",html:'<div class="'+r+'-wrapper">\n	<div class="'+r+'-arrow"></div>\n	<div class="'+r+'-container"></div>\n</div>',css:"."+r+"-corner {\n	position: fixed;\n	margin: 5px;\n	z-index: 1050;\n}\n\n."+r+"-corner ."+r+"-wrapper,\n."+r+"-corner ."+r+"-container {\n	position: relative;\n	display: block;\n	height: inherit;\n	width: inherit;\n	margin: 3px;\n}\n\n."+r+"-wrapper {\n	z-index: 1;\n	position: absolute;\n	display: inline-block;\n	height: 0;\n	width: 0;\n}\n\n."+r+"-container {\n	display: none;\n	z-index: 1;\n	position: absolute;\n}\n\n."+r+"-hidable {\n	cursor: pointer;\n}\n\n[data-notify-text],[data-notify-html] {\n	position: relative;\n}\n\n."+r+"-arrow {\n	position: absolute;\n	z-index: 2;\n	width: 0;\n	height: 0;\n}"},p={"border-radius":["-webkit-","-moz-"]},d=function(e){return c[e]},v=function(e){if(!e)throw"Missing Style name";c[e]&&delete c[e]},m=function(t,i){if(!t)throw"Missing Style name";if(!i)throw"Missing Style definition";if(!i.html)throw"Missing Style HTML";var s=c[t];s&&s.cssElem&&(window.console&&console.warn(n+": overwriting style '"+t+"'"),c[t].cssElem.remove()),i.name=t,c[t]=i;var o="";i.classes&&e.each(i.classes,function(t,n){return o+="."+r+"-"+i.name+"-"+t+" {\n",e.each(n,function(t,n){return p[t]&&e.each(p[t],function(e,r){return o+="	"+r+t+": "+n+";\n"}),o+="	"+t+": "+n+";\n"}),o+="}\n"}),i.css&&(o+="/* styles for "+i.name+" */\n"+i.css),o&&(i.cssElem=g(o),i.cssElem.attr("id","notify-"+i.name));var u={},a=e(i.html);y("html",a,u),y("text",a,u),i.fields=u},g=function(t){var n,r,i;r=x("style"),r.attr("type","text/css"),e("head").append(r);try{r.html(t)}catch(s){r[0].styleSheet.cssText=t}return r},y=function(t,n,r){var s;return t!=="html"&&(t="text"),s="data-notify-"+t,b(n,"["+s+"]").each(function(){var n;n=e(this).attr(s),n||(n=i),r[n]=t})},b=function(e,t){return e.is(t)?e:e.find(t)},w={clickToHide:!0,autoHide:!0,autoHideDelay:5e3,arrowShow:!0,arrowSize:5,breakNewLines:!0,elementPosition:"bottom",globalPosition:"top right",style:"bootstrap",className:"error",showAnimation:"slideDown",showDuration:400,hideAnimation:"slideUp",hideDuration:200,gap:5},E=function(t,n){var r;return r=function(){},r.prototype=t,e.extend(!0,new r,n)},S=function(t){return e.extend(w,t)},x=function(t){return e("<"+t+"></"+t+">")},T={},N=function(t){var n;return t.is("[type=radio]")&&(n=t.parents("form:first").find("[type=radio]").filter(function(n,r){return e(r).attr("name")===t.attr("name")}),t=n.first()),t},C=function(e,t,n){var r,i;if(typeof n=="string")n=parseInt(n,10);else if(typeof n!="number")return;if(isNaN(n))return;return r=s[f[t.charAt(0)]],i=t,e[r]!==undefined&&(t=s[r.charAt(0)],n=-n),e[t]===undefined?e[t]=n:e[t]+=n,null},k=function(e,t,n){if(e==="l"||e==="t")return 0;if(e==="c"||e==="m")return n/2-t/2;if(e==="r"||e==="b")return n-t;throw"Invalid alignment"},L=function(e){return L.e=L.e||x("div"),L.e.text(e).html()};A.prototype.loadHTML=function(){var t;t=this.getStyle(),this.userContainer=e(t.html),this.userFields=t.fields},A.prototype.show=function(e,t){var n,r,i,s,o;r=function(n){return function(){!e&&!n.elem&&n.destroy();if(t)return t()}}(this),o=this.container.parent().parents(":hidden").length>0,i=this.container.add(this.arrow),n=[];if(o&&e)s="show";else if(o&&!e)s="hide";else if(!o&&e)s=this.options.showAnimation,n.push(this.options.showDuration);else{if(!!o||!!e)return r();s=this.options.hideAnimation,n.push(this.options.hideDuration)}return n.push(r),i[s].apply(i,n)},A.prototype.setGlobalPosition=function(){var t=this.getPosition(),n=t[0],i=t[1],o=s[n],u=s[i],a=n+"|"+i,f=T[a];if(!f||!document.body.contains(f[0])){f=T[a]=x("div");var l={};l[o]=0,u==="middle"?l.top="45%":u==="center"?l.left="45%":l[u]=0,f.css(l).addClass(r+"-corner"),e("body").append(f)}return f.prepend(this.wrapper)},A.prototype.setElementPosition=function(){var n,r,i,l,c,h,p,d,v,m,g,y,b,w,E,S,x,T,N,L,A,O,M,_,D,P,H,B,j;H=this.getPosition(),_=H[0],O=H[1],M=H[2],g=this.elem.position(),d=this.elem.outerHeight(),y=this.elem.outerWidth(),v=this.elem.innerHeight(),m=this.elem.innerWidth(),j=this.wrapper.position(),c=this.container.height(),h=this.container.width(),T=s[_],L=f[_],A=s[L],p={},p[A]=_==="b"?d:_==="r"?y:0,C(p,"top",g.top-j.top),C(p,"left",g.left-j.left),B=["top","left"];for(w=0,S=B.length;w<S;w++)D=B[w],N=parseInt(this.elem.css("margin-"+D),10),N&&C(p,D,N);b=Math.max(0,this.options.gap-(this.options.arrowShow?i:0)),C(p,A,b);if(!this.options.arrowShow)this.arrow.hide();else{i=this.options.arrowSize,r=e.extend({},p),n=this.userContainer.css("border-color")||this.userContainer.css("border-top-color")||this.userContainer.css("background-color")||"white";for(E=0,x=a.length;E<x;E++){D=a[E],P=s[D];if(D===L)continue;l=P===T?n:"transparent",r["border-"+P]=i+"px solid "+l}C(p,s[L],i),t.call(a,O)>=0&&C(r,s[O],i*2)}t.call(u,_)>=0?(C(p,"left",k(O,h,y)),r&&C(r,"left",k(O,i,m))):t.call(o,_)>=0&&(C(p,"top",k(O,c,d)),r&&C(r,"top",k(O,i,v))),this.container.is(":visible")&&(p.display="block"),this.container.removeAttr("style").css(p);if(r)return this.arrow.removeAttr("style").css(r)},A.prototype.getPosition=function(){var e,n,r,i,s,f,c,h;h=this.options.position||(this.elem?this.options.elementPosition:this.options.globalPosition),e=l(h),e.length===0&&(e[0]="b");if(n=e[0],t.call(a,n)<0)throw"Must be one of ["+a+"]";if(e.length===1||(r=e[0],t.call(u,r)>=0)&&(i=e[1],t.call(o,i)<0)||(s=e[0],t.call(o,s)>=0)&&(f=e[1],t.call(u,f)<0))e[1]=(c=e[0],t.call(o,c)>=0)?"m":"l";return e.length===2&&(e[2]=e[1]),e},A.prototype.getStyle=function(e){var t;e||(e=this.options.style),e||(e="default"),t=c[e];if(!t)throw"Missing style: "+e;return t},A.prototype.updateClasses=function(){var t,n;return t=["base"],e.isArray(this.options.className)?t=t.concat(this.options.className):this.options.className&&t.push(this.options.className),n=this.getStyle(),t=e.map(t,function(e){return r+"-"+n.name+"-"+e}).join(" "),this.userContainer.attr("class",t)},A.prototype.run=function(t,n){var r,s,o,u,a;e.isPlainObject(n)?e.extend(this.options,n):e.type(n)==="string"&&(this.options.className=n);if(this.container&&!t){this.show(!1);return}if(!this.container&&!t)return;s={},e.isPlainObject(t)?s=t:s[i]=t;for(o in s){r=s[o],u=this.userFields[o];if(!u)continue;u==="text"&&(r=L(r),this.options.breakNewLines&&(r=r.replace(/\n/g,"<br/>"))),a=o===i?"":"="+o,b(this.userContainer,"[data-notify-"+u+a+"]").html(r)}this.updateClasses(),this.elem?this.setElementPosition():this.setGlobalPosition(),this.show(!0),this.options.autoHide&&(clearTimeout(this.autohideTimer),this.autohideTimer=setTimeout(this.show.bind(this,!1),this.options.autoHideDelay))},A.prototype.destroy=function(){this.wrapper.data(r,null),this.wrapper.remove()},e[n]=function(t,r,i){return t&&t.nodeName||t.jquery?e(t)[n](r,i):(i=r,r=t,new A(null,r,i)),t},e.fn[n]=function(t,n){return e(this).each(function(){var i=N(e(this)).data(r);i&&i.destroy();var s=new A(e(this),t,n)}),this},e.extend(e[n],{defaults:S,addStyle:m,removeStyle:v,pluginOptions:w,getStyle:d,insertCSS:g}),m("bootstrap",{html:"<div>\n<span data-notify-text></span>\n</div>",classes:{base:{"font-weight":"bold",padding:"8px 15px 8px 14px","text-shadow":"0 1px 0 rgba(255, 255, 255, 0.5)","background-color":"#fcf8e3",border:"1px solid #fbeed5","border-radius":"4px","white-space":"nowrap","padding-left":"25px","background-repeat":"no-repeat","background-position":"3px 7px"},error:{color:"#B94A48","background-color":"#F2DEDE","border-color":"#EED3D7","background-image":"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAtRJREFUeNqkVc1u00AQHq+dOD+0poIQfkIjalW0SEGqRMuRnHos3DjwAH0ArlyQeANOOSMeAA5VjyBxKBQhgSpVUKKQNGloFdw4cWw2jtfMOna6JOUArDTazXi/b3dm55socPqQhFka++aHBsI8GsopRJERNFlY88FCEk9Yiwf8RhgRyaHFQpPHCDmZG5oX2ui2yilkcTT1AcDsbYC1NMAyOi7zTX2Agx7A9luAl88BauiiQ/cJaZQfIpAlngDcvZZMrl8vFPK5+XktrWlx3/ehZ5r9+t6e+WVnp1pxnNIjgBe4/6dAysQc8dsmHwPcW9C0h3fW1hans1ltwJhy0GxK7XZbUlMp5Ww2eyan6+ft/f2FAqXGK4CvQk5HueFz7D6GOZtIrK+srupdx1GRBBqNBtzc2AiMr7nPplRdKhb1q6q6zjFhrklEFOUutoQ50xcX86ZlqaZpQrfbBdu2R6/G19zX6XSgh6RX5ubyHCM8nqSID6ICrGiZjGYYxojEsiw4PDwMSL5VKsC8Yf4VRYFzMzMaxwjlJSlCyAQ9l0CW44PBADzXhe7xMdi9HtTrdYjFYkDQL0cn4Xdq2/EAE+InCnvADTf2eah4Sx9vExQjkqXT6aAERICMewd/UAp/IeYANM2joxt+q5VI+ieq2i0Wg3l6DNzHwTERPgo1ko7XBXj3vdlsT2F+UuhIhYkp7u7CarkcrFOCtR3H5JiwbAIeImjT/YQKKBtGjRFCU5IUgFRe7fF4cCNVIPMYo3VKqxwjyNAXNepuopyqnld602qVsfRpEkkz+GFL1wPj6ySXBpJtWVa5xlhpcyhBNwpZHmtX8AGgfIExo0ZpzkWVTBGiXCSEaHh62/PoR0p/vHaczxXGnj4bSo+G78lELU80h1uogBwWLf5YlsPmgDEd4M236xjm+8nm4IuE/9u+/PH2JXZfbwz4zw1WbO+SQPpXfwG/BBgAhCNZiSb/pOQAAAAASUVORK5CYII=)"},success:{color:"#468847","background-color":"#DFF0D8","border-color":"#D6E9C6","background-image":"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAutJREFUeNq0lctPE0Ecx38zu/RFS1EryqtgJFA08YCiMZIAQQ4eRG8eDGdPJiYeTIwHTfwPiAcvXIwXLwoXPaDxkWgQ6islKlJLSQWLUraPLTv7Gme32zoF9KSTfLO7v53vZ3d/M7/fIth+IO6INt2jjoA7bjHCJoAlzCRw59YwHYjBnfMPqAKWQYKjGkfCJqAF0xwZjipQtA3MxeSG87VhOOYegVrUCy7UZM9S6TLIdAamySTclZdYhFhRHloGYg7mgZv1Zzztvgud7V1tbQ2twYA34LJmF4p5dXF1KTufnE+SxeJtuCZNsLDCQU0+RyKTF27Unw101l8e6hns3u0PBalORVVVkcaEKBJDgV3+cGM4tKKmI+ohlIGnygKX00rSBfszz/n2uXv81wd6+rt1orsZCHRdr1Imk2F2Kob3hutSxW8thsd8AXNaln9D7CTfA6O+0UgkMuwVvEFFUbbAcrkcTA8+AtOk8E6KiQiDmMFSDqZItAzEVQviRkdDdaFgPp8HSZKAEAL5Qh7Sq2lIJBJwv2scUqkUnKoZgNhcDKhKg5aH+1IkcouCAdFGAQsuWZYhOjwFHQ96oagWgRoUov1T9kRBEODAwxM2QtEUl+Wp+Ln9VRo6BcMw4ErHRYjH4/B26AlQoQQTRdHWwcd9AH57+UAXddvDD37DmrBBV34WfqiXPl61g+vr6xA9zsGeM9gOdsNXkgpEtTwVvwOklXLKm6+/p5ezwk4B+j6droBs2CsGa/gNs6RIxazl4Tc25mpTgw/apPR1LYlNRFAzgsOxkyXYLIM1V8NMwyAkJSctD1eGVKiq5wWjSPdjmeTkiKvVW4f2YPHWl3GAVq6ymcyCTgovM3FzyRiDe2TaKcEKsLpJvNHjZgPNqEtyi6mZIm4SRFyLMUsONSSdkPeFtY1n0mczoY3BHTLhwPRy9/lzcziCw9ACI+yql0VLzcGAZbYSM5CCSZg1/9oc/nn7+i8N9p/8An4JMADxhH+xHfuiKwAAAABJRU5ErkJggg==)"},info:{color:"#3A87AD","background-color":"#D9EDF7","border-color":"#BCE8F1","background-image":"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QYFAhkSsdes/QAAA8dJREFUOMvVlGtMW2UYx//POaWHXg6lLaW0ypAtw1UCgbniNOLcVOLmAjHZolOYlxmTGXVZdAnRfXQm+7SoU4mXaOaiZsEpC9FkiQs6Z6bdCnNYruM6KNBw6YWewzl9z+sHImEWv+vz7XmT95f/+3/+7wP814v+efDOV3/SoX3lHAA+6ODeUFfMfjOWMADgdk+eEKz0pF7aQdMAcOKLLjrcVMVX3xdWN29/GhYP7SvnP0cWfS8caSkfHZsPE9Fgnt02JNutQ0QYHB2dDz9/pKX8QjjuO9xUxd/66HdxTeCHZ3rojQObGQBcuNjfplkD3b19Y/6MrimSaKgSMmpGU5WevmE/swa6Oy73tQHA0Rdr2Mmv/6A1n9w9suQ7097Z9lM4FlTgTDrzZTu4StXVfpiI48rVcUDM5cmEksrFnHxfpTtU/3BFQzCQF/2bYVoNbH7zmItbSoMj40JSzmMyX5qDvriA7QdrIIpA+3cdsMpu0nXI8cV0MtKXCPZev+gCEM1S2NHPvWfP/hL+7FSr3+0p5RBEyhEN5JCKYr8XnASMT0xBNyzQGQeI8fjsGD39RMPk7se2bd5ZtTyoFYXftF6y37gx7NeUtJJOTFlAHDZLDuILU3j3+H5oOrD3yWbIztugaAzgnBKJuBLpGfQrS8wO4FZgV+c1IxaLgWVU0tMLEETCos4xMzEIv9cJXQcyagIwigDGwJgOAtHAwAhisQUjy0ORGERiELgG4iakkzo4MYAxcM5hAMi1WWG1yYCJIcMUaBkVRLdGeSU2995TLWzcUAzONJ7J6FBVBYIggMzmFbvdBV44Corg8vjhzC+EJEl8U1kJtgYrhCzgc/vvTwXKSib1paRFVRVORDAJAsw5FuTaJEhWM2SHB3mOAlhkNxwuLzeJsGwqWzf5TFNdKgtY5qHp6ZFf67Y/sAVadCaVY5YACDDb3Oi4NIjLnWMw2QthCBIsVhsUTU9tvXsjeq9+X1d75/KEs4LNOfcdf/+HthMnvwxOD0wmHaXr7ZItn2wuH2SnBzbZAbPJwpPx+VQuzcm7dgRCB57a1uBzUDRL4bfnI0RE0eaXd9W89mpjqHZnUI5Hh2l2dkZZUhOqpi2qSmpOmZ64Tuu9qlz/SEXo6MEHa3wOip46F1n7633eekV8ds8Wxjn37Wl63VVa+ej5oeEZ/82ZBETJjpJ1Rbij2D3Z/1trXUvLsblCK0XfOx0SX2kMsn9dX+d+7Kf6h8o4AIykuffjT8L20LU+w4AZd5VvEPY+XpWqLV327HR7DzXuDnD8r+ovkBehJ8i+y8YAAAAASUVORK5CYII=)"},warn:{color:"#C09853","background-color":"#FCF8E3","border-color":"#FBEED5","background-image":"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAMAAAC6V+0/AAABJlBMVEXr6eb/2oD/wi7/xjr/0mP/ykf/tQD/vBj/3o7/uQ//vyL/twebhgD/4pzX1K3z8e349vK6tHCilCWbiQymn0jGworr6dXQza3HxcKkn1vWvV/5uRfk4dXZ1bD18+/52YebiAmyr5S9mhCzrWq5t6ufjRH54aLs0oS+qD751XqPhAybhwXsujG3sm+Zk0PTwG6Shg+PhhObhwOPgQL4zV2nlyrf27uLfgCPhRHu7OmLgAafkyiWkD3l49ibiAfTs0C+lgCniwD4sgDJxqOilzDWowWFfAH08uebig6qpFHBvH/aw26FfQTQzsvy8OyEfz20r3jAvaKbhgG9q0nc2LbZxXanoUu/u5WSggCtp1anpJKdmFz/zlX/1nGJiYmuq5Dx7+sAAADoPUZSAAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfdBgUBGhh4aah5AAAAlklEQVQY02NgoBIIE8EUcwn1FkIXM1Tj5dDUQhPU502Mi7XXQxGz5uVIjGOJUUUW81HnYEyMi2HVcUOICQZzMMYmxrEyMylJwgUt5BljWRLjmJm4pI1hYp5SQLGYxDgmLnZOVxuooClIDKgXKMbN5ggV1ACLJcaBxNgcoiGCBiZwdWxOETBDrTyEFey0jYJ4eHjMGWgEAIpRFRCUt08qAAAAAElFTkSuQmCC)"}}}),e(function(){g(h.css).attr("id","core-notify"),e(document).on("click","."+r+"-hidable",function(t){e(this).trigger("notify-hide")}),e(document).on("notify-hide","."+r+"-wrapper",function(t){var n=e(this).data(r);n&&n.show(!1)})})})
    \ No newline at end of file
    diff --git a/data/web/js/noty.min.js b/data/web/js/noty.min.js
    new file mode 100644
    index 00000000..2cdeac52
    --- /dev/null
    +++ b/data/web/js/noty.min.js
    @@ -0,0 +1,9 @@
    +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("Noty",[],e):"object"==typeof exports?exports.Noty=e():t.Noty=e()}(this,function(){return function(t){function e(o){if(n[o])return n[o].exports;var i=n[o]={i:o,l:!1,exports:{}};return t[o].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,o){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:o})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=6)}([function(t,e,n){"use strict";function o(t,e,n){var o=void 0;if(!n){for(o in e)if(e.hasOwnProperty(o)&&e[o]===t)return!0}else for(o in e)if(e.hasOwnProperty(o)&&e[o]===t)return!0;return!1}function i(t){t=t||window.event,void 0!==t.stopPropagation?t.stopPropagation():t.cancelBubble=!0}function r(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",e="noty_"+t+"_";return e+="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function s(t){var e=t.offsetHeight,n=window.getComputedStyle(t);return e+=parseInt(n.marginTop)+parseInt(n.marginBottom)}function u(t,e,n){var o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];e=e.split(" ");for(var i=0;i<e.length;i++)document.addEventListener?t.addEventListener(e[i],n,o):document.attachEvent&&t.attachEvent("on"+e[i],n)}function a(t,e){return("string"==typeof t?t:f(t)).indexOf(" "+e+" ")>=0}function c(t,e){var n=f(t),o=n+e;a(n,e)||(t.className=o.substring(1))}function l(t,e){var n=f(t),o=void 0;a(t,e)&&(o=n.replace(" "+e+" "," "),t.className=o.substring(1,o.length-1))}function d(t){t.parentNode&&t.parentNode.removeChild(t)}function f(t){return(" "+(t&&t.className||"")+" ").replace(/\s+/gi," ")}function h(){function t(){b.PageHidden=document[s],o()}function e(){b.PageHidden=!0,o()}function n(){b.PageHidden=!1,o()}function o(){b.PageHidden?i():r()}function i(){setTimeout(function(){Object.keys(b.Store).forEach(function(t){b.Store.hasOwnProperty(t)&&b.Store[t].options.visibilityControl&&b.Store[t].stop()})},100)}function r(){setTimeout(function(){Object.keys(b.Store).forEach(function(t){b.Store.hasOwnProperty(t)&&b.Store[t].options.visibilityControl&&b.Store[t].resume()}),b.queueRenderAll()},100)}var s=void 0,a=void 0;void 0!==document.hidden?(s="hidden",a="visibilitychange"):void 0!==document.msHidden?(s="msHidden",a="msvisibilitychange"):void 0!==document.webkitHidden&&(s="webkitHidden",a="webkitvisibilitychange"),u(document,a,t),u(window,"blur",e),u(window,"focus",n)}function p(t){if(t.hasSound){var e=document.createElement("audio");t.options.sounds.sources.forEach(function(t){var n=document.createElement("source");n.src=t,n.type="audio/"+m(t),e.appendChild(n)}),t.barDom?t.barDom.appendChild(e):document.querySelector("body").appendChild(e),e.volume=t.options.sounds.volume,t.soundPlayed||(e.play(),t.soundPlayed=!0),e.onended=function(){d(e)}}}function m(t){return t.match(/\.([^.]+)$/)[1]}Object.defineProperty(e,"__esModule",{value:!0}),e.css=e.deepExtend=e.animationEndEvents=void 0;var v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};e.inArray=o,e.stopPropagation=i,e.generateID=r,e.outerHeight=s,e.addListener=u,e.hasClass=a,e.addClass=c,e.removeClass=l,e.remove=d,e.classList=f,e.visibilityChangeFlow=h,e.createAudioElements=p;var y=n(1),b=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}(y);e.animationEndEvents="webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend",e.deepExtend=function t(e){e=e||{};for(var n=1;n<arguments.length;n++){var o=arguments[n];if(o)for(var i in o)o.hasOwnProperty(i)&&(Array.isArray(o[i])?e[i]=o[i]:"object"===v(o[i])&&null!==o[i]?e[i]=t(e[i],o[i]):e[i]=o[i])}return e},e.css=function(){function t(t){return t.replace(/^-ms-/,"ms-").replace(/-([\da-z])/gi,function(t,e){return e.toUpperCase()})}function e(t){var e=document.body.style;if(t in e)return t;for(var n=i.length,o=t.charAt(0).toUpperCase()+t.slice(1),r=void 0;n--;)if((r=i[n]+o)in e)return r;return t}function n(n){return n=t(n),r[n]||(r[n]=e(n))}function o(t,e,o){e=n(e),t.style[e]=o}var i=["Webkit","O","Moz","ms"],r={};return function(t,e){var n=arguments,i=void 0,r=void 0;if(2===n.length)for(i in e)e.hasOwnProperty(i)&&void 0!==(r=e[i])&&e.hasOwnProperty(i)&&o(t,i,r);else o(t,n[1],n[2])}}()},function(t,e,n){"use strict";function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"global",e=0,n=x;return E.hasOwnProperty(t)&&(n=E[t].maxVisible,Object.keys(P).forEach(function(n){P[n].options.queue!==t||P[n].closed||e++})),{current:e,maxVisible:n}}function i(t){E.hasOwnProperty(t.options.queue)||(E[t.options.queue]={maxVisible:x,queue:[]}),E[t.options.queue].queue.push(t)}function r(t){if(E.hasOwnProperty(t.options.queue)){var e=[];Object.keys(E[t.options.queue].queue).forEach(function(n){E[t.options.queue].queue[n].id!==t.id&&e.push(E[t.options.queue].queue[n])}),E[t.options.queue].queue=e}}function s(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"global";if(E.hasOwnProperty(t)){var e=E[t].queue.shift();e&&e.show()}}function u(){Object.keys(E).forEach(function(t){s(t)})}function a(t){var e=k.generateID("ghost"),n=document.createElement("div");n.setAttribute("id",e),k.css(n,{height:k.outerHeight(t.barDom)+"px"}),t.barDom.insertAdjacentHTML("afterend",n.outerHTML),k.remove(t.barDom),n=document.getElementById(e),k.addClass(n,"noty_fix_effects_height"),k.addListener(n,k.animationEndEvents,function(){k.remove(n)})}function c(t){m(t);var e='<div class="noty_body">'+t.options.text+"</div>"+d(t)+'<div class="noty_progressbar"></div>';t.barDom=document.createElement("div"),t.barDom.setAttribute("id",t.id),k.addClass(t.barDom,"noty_bar noty_type__"+t.options.type+" noty_theme__"+t.options.theme),t.barDom.innerHTML=e,b(t,"onTemplate")}function l(t){return!(!t.options.buttons||!Object.keys(t.options.buttons).length)}function d(t){if(l(t)){var e=document.createElement("div");return k.addClass(e,"noty_buttons"),Object.keys(t.options.buttons).forEach(function(n){e.appendChild(t.options.buttons[n].dom)}),t.options.buttons.forEach(function(t){e.appendChild(t.dom)}),e.outerHTML}return""}function f(t){t.options.modal&&(0===S&&p(),e.DocModalCount=S+=1)}function h(t){if(t.options.modal&&S>0&&(e.DocModalCount=S-=1,S<=0)){var n=document.querySelector(".noty_modal");n&&(k.removeClass(n,"noty_modal_open"),k.addClass(n,"noty_modal_close"),k.addListener(n,k.animationEndEvents,function(){k.remove(n)}))}}function p(){var t=document.querySelector("body"),e=document.createElement("div");k.addClass(e,"noty_modal"),t.insertBefore(e,t.firstChild),k.addClass(e,"noty_modal_open"),k.addListener(e,k.animationEndEvents,function(){k.removeClass(e,"noty_modal_open")})}function m(t){if(t.options.container)return void(t.layoutDom=document.querySelector(t.options.container));var e="noty_layout__"+t.options.layout;t.layoutDom=document.querySelector("div#"+e),t.layoutDom||(t.layoutDom=document.createElement("div"),t.layoutDom.setAttribute("id",e),k.addClass(t.layoutDom,"noty_layout"),document.querySelector("body").appendChild(t.layoutDom))}function v(t){t.options.timeout&&(t.options.progressBar&&t.progressDom&&k.css(t.progressDom,{transition:"width "+t.options.timeout+"ms linear",width:"0%"}),clearTimeout(t.closeTimer),t.closeTimer=setTimeout(function(){t.close()},t.options.timeout))}function y(t){t.options.timeout&&t.closeTimer&&(clearTimeout(t.closeTimer),t.closeTimer=-1,t.options.progressBar&&t.progressDom&&k.css(t.progressDom,{transition:"width 0ms linear",width:"100%"}))}function b(t,e){t.listeners.hasOwnProperty(e)&&t.listeners[e].forEach(function(e){"function"==typeof e&&e.apply(t)})}function w(t){b(t,"afterShow"),v(t),k.addListener(t.barDom,"mouseenter",function(){y(t)}),k.addListener(t.barDom,"mouseleave",function(){v(t)})}function g(t){delete P[t.id],t.closing=!1,b(t,"afterClose"),k.remove(t.barDom),0!==t.layoutDom.querySelectorAll(".noty_bar").length||t.options.container||k.remove(t.layoutDom),(k.inArray("docVisible",t.options.titleCount.conditions)||k.inArray("docHidden",t.options.titleCount.conditions))&&D.decrement(),s(t.options.queue)}Object.defineProperty(e,"__esModule",{value:!0}),e.Defaults=e.Store=e.Queues=e.DefaultMaxVisible=e.docTitle=e.DocModalCount=e.PageHidden=void 0,e.getQueueCounts=o,e.addToQueue=i,e.removeFromQueue=r,e.queueRender=s,e.queueRenderAll=u,e.ghostFix=a,e.build=c,e.hasButtons=l,e.handleModal=f,e.handleModalClose=h,e.queueClose=v,e.dequeueClose=y,e.fire=b,e.openFlow=w,e.closeFlow=g;var _=n(0),k=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}(_),S=(e.PageHidden=!1,e.DocModalCount=0),C={originalTitle:null,count:0,changed:!1,timer:-1},D=e.docTitle={increment:function(){C.count++,D._update()},decrement:function(){if(--C.count<=0)return void D._clear();D._update()},_update:function(){var t=document.title;C.changed?document.title="("+C.count+") "+C.originalTitle:(C.originalTitle=t,document.title="("+C.count+") "+t,C.changed=!0)},_clear:function(){C.changed&&(C.count=0,document.title=C.originalTitle,C.changed=!1)}},x=e.DefaultMaxVisible=5,E=e.Queues={global:{maxVisible:x,queue:[]}},P=e.Store={};e.Defaults={type:"alert",layout:"topRight",theme:"mint",text:"",timeout:!1,progressBar:!0,closeWith:["click"],animation:{open:"noty_effects_open",close:"noty_effects_close"},id:!1,force:!1,killer:!1,queue:"global",container:!1,buttons:[],callbacks:{beforeShow:null,onShow:null,afterShow:null,onClose:null,afterClose:null,onHover:null,onTemplate:null},sounds:{sources:[],volume:1,conditions:[]},titleCount:{conditions:[]},modal:!1,visibilityControl:!0}},function(t,e,n){"use strict";function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.NotyButton=void 0;var i=n(0),r=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}(i);e.NotyButton=function t(e,n,i){var s=this,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return o(this,t),this.dom=document.createElement("button"),this.dom.innerHTML=e,this.id=u.id=u.id||r.generateID("button"),this.cb=i,Object.keys(u).forEach(function(t){s.dom.setAttribute(t,u[t])}),r.addClass(this.dom,n||"noty_btn"),this}},function(t,e,n){"use strict";function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}return function(e,n,o){return n&&t(e.prototype,n),o&&t(e,o),e}}();e.Push=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/service-worker.js";return o(this,t),this.subData={},this.workerPath=e,this.listeners={onPermissionGranted:[],onPermissionDenied:[],onSubscriptionSuccess:[],onSubscriptionCancel:[],onWorkerError:[],onWorkerSuccess:[],onWorkerNotSupported:[]},this}return i(t,[{key:"on",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){};return"function"==typeof e&&this.listeners.hasOwnProperty(t)&&this.listeners[t].push(e),this}},{key:"fire",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.listeners.hasOwnProperty(t)&&this.listeners[t].forEach(function(t){"function"==typeof t&&t.apply(e,n)})}},{key:"create",value:function(){console.log("NOT IMPLEMENTED YET")}},{key:"isSupported",value:function(){var t=!1;try{t=window.Notification||window.webkitNotifications||navigator.mozNotification||window.external&&void 0!==window.external.msIsSiteMode()}catch(t){}return t}},{key:"getPermissionStatus",value:function(){var t="default";if(window.Notification&&window.Notification.permissionLevel)t=window.Notification.permissionLevel;else if(window.webkitNotifications&&window.webkitNotifications.checkPermission)switch(window.webkitNotifications.checkPermission()){case 1:t="default";break;case 0:t="granted";break;default:t="denied"}else window.Notification&&window.Notification.permission?t=window.Notification.permission:navigator.mozNotification?t="granted":window.external&&void 0!==window.external.msIsSiteMode()&&(t=window.external.msIsSiteMode()?"granted":"default");return t.toString().toLowerCase()}},{key:"getEndpoint",value:function(t){var e=t.endpoint,n=t.subscriptionId;return n&&-1===e.indexOf(n)&&(e+="/"+n),e}},{key:"isSWRegistered",value:function(){try{return"activated"===navigator.serviceWorker.controller.state}catch(t){return!1}}},{key:"unregisterWorker",value:function(){var t=this;"serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(function(e){var n=!0,o=!1,i=void 0;try{for(var r,s=e[Symbol.iterator]();!(n=(r=s.next()).done);n=!0){r.value.unregister(),t.fire("onSubscriptionCancel")}}catch(t){o=!0,i=t}finally{try{!n&&s.return&&s.return()}finally{if(o)throw i}}})}},{key:"requestSubscription",value:function(){var t=this,e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=this,o=this.getPermissionStatus(),i=function(o){"granted"===o?(t.fire("onPermissionGranted"),"serviceWorker"in navigator?navigator.serviceWorker.register(t.workerPath).then(function(){navigator.serviceWorker.ready.then(function(t){n.fire("onWorkerSuccess"),t.pushManager.subscribe({userVisibleOnly:e}).then(function(t){var e=t.getKey("p256dh"),o=t.getKey("auth");n.subData={endpoint:n.getEndpoint(t),p256dh:e?window.btoa(String.fromCharCode.apply(null,new Uint8Array(e))):null,auth:o?window.btoa(String.fromCharCode.apply(null,new Uint8Array(o))):null},n.fire("onSubscriptionSuccess",[n.subData])}).catch(function(t){n.fire("onWorkerError",[t])})})}):n.fire("onWorkerNotSupported")):"denied"===o&&(t.fire("onPermissionDenied"),t.unregisterWorker())};"default"===o?window.Notification&&window.Notification.requestPermission?window.Notification.requestPermission(i):window.webkitNotifications&&window.webkitNotifications.checkPermission&&window.webkitNotifications.requestPermission(i):i(o)}}]),t}()},function(t,e,n){(function(e,o){/*!
    + * @overview es6-promise - a tiny implementation of Promises/A+.
    + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
    + * @license   Licensed under MIT license
    + *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
    + * @version   4.1.0
    + */
    +!function(e,n){t.exports=n()}(0,function(){"use strict";function t(t){return"function"==typeof t||"object"==typeof t&&null!==t}function i(t){return"function"==typeof t}function r(t){z=t}function s(t){U=t}function u(){return void 0!==R?function(){R(c)}:a()}function a(){var t=setTimeout;return function(){return t(c,1)}}function c(){for(var t=0;t<Q;t+=2){(0,X[t])(X[t+1]),X[t]=void 0,X[t+1]=void 0}Q=0}function l(t,e){var n=arguments,o=this,i=new this.constructor(f);void 0===i[tt]&&A(i);var r=o._state;return r?function(){var t=n[r-1];U(function(){return P(r,i,t,o._result)})}():C(o,i,t,e),i}function d(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var n=new e(f);return g(n,t),n}function f(){}function h(){return new TypeError("You cannot resolve a promise with itself")}function p(){return new TypeError("A promises callback cannot return that same promise.")}function m(t){try{return t.then}catch(t){return it.error=t,it}}function v(t,e,n,o){try{t.call(e,n,o)}catch(t){return t}}function y(t,e,n){U(function(t){var o=!1,i=v(n,e,function(n){o||(o=!0,e!==n?g(t,n):k(t,n))},function(e){o||(o=!0,S(t,e))},"Settle: "+(t._label||" unknown promise"));!o&&i&&(o=!0,S(t,i))},t)}function b(t,e){e._state===nt?k(t,e._result):e._state===ot?S(t,e._result):C(e,void 0,function(e){return g(t,e)},function(e){return S(t,e)})}function w(t,e,n){e.constructor===t.constructor&&n===l&&e.constructor.resolve===d?b(t,e):n===it?(S(t,it.error),it.error=null):void 0===n?k(t,e):i(n)?y(t,e,n):k(t,e)}function g(e,n){e===n?S(e,h()):t(n)?w(e,n,m(n)):k(e,n)}function _(t){t._onerror&&t._onerror(t._result),D(t)}function k(t,e){t._state===et&&(t._result=e,t._state=nt,0!==t._subscribers.length&&U(D,t))}function S(t,e){t._state===et&&(t._state=ot,t._result=e,U(_,t))}function C(t,e,n,o){var i=t._subscribers,r=i.length;t._onerror=null,i[r]=e,i[r+nt]=n,i[r+ot]=o,0===r&&t._state&&U(D,t)}function D(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var o=void 0,i=void 0,r=t._result,s=0;s<e.length;s+=3)o=e[s],i=e[s+n],o?P(n,o,i,r):i(r);t._subscribers.length=0}}function x(){this.error=null}function E(t,e){try{return t(e)}catch(t){return rt.error=t,rt}}function P(t,e,n,o){var r=i(n),s=void 0,u=void 0,a=void 0,c=void 0;if(r){if(s=E(n,o),s===rt?(c=!0,u=s.error,s.error=null):a=!0,e===s)return void S(e,p())}else s=o,a=!0;e._state!==et||(r&&a?g(e,s):c?S(e,u):t===nt?k(e,s):t===ot&&S(e,s))}function T(t,e){try{e(function(e){g(t,e)},function(e){S(t,e)})}catch(e){S(t,e)}}function O(){return st++}function A(t){t[tt]=st++,t._state=void 0,t._result=void 0,t._subscribers=[]}function M(t,e){this._instanceConstructor=t,this.promise=new t(f),this.promise[tt]||A(this.promise),I(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?k(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&k(this.promise,this._result))):S(this.promise,q())}function q(){return new Error("Array Methods must be provided an Array")}function j(t){return new M(this,t).promise}function N(t){var e=this;return new e(I(t)?function(n,o){for(var i=t.length,r=0;r<i;r++)e.resolve(t[r]).then(n,o)}:function(t,e){return e(new TypeError("You must pass an array to race."))})}function H(t){var e=this,n=new e(f);return S(n,t),n}function L(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function W(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function V(t){this[tt]=O(),this._result=this._state=void 0,this._subscribers=[],f!==t&&("function"!=typeof t&&L(),this instanceof V?T(this,t):W())}function B(){var t=void 0;if(void 0!==o)t=o;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(t){throw new Error("polyfill failed because global object is unavailable in this environment")}var e=t.Promise;if(e){var n=null;try{n=Object.prototype.toString.call(e.resolve())}catch(t){}if("[object Promise]"===n&&!e.cast)return}t.Promise=V}var F=void 0;F=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var I=F,Q=0,R=void 0,z=void 0,U=function(t,e){X[Q]=t,X[Q+1]=e,2===(Q+=2)&&(z?z(c):Z())},Y="undefined"!=typeof window?window:void 0,K=Y||{},G=K.MutationObserver||K.WebKitMutationObserver,$="undefined"==typeof self&&void 0!==e&&"[object process]"==={}.toString.call(e),J="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,X=new Array(1e3),Z=void 0;Z=$?function(){return function(){return e.nextTick(c)}}():G?function(){var t=0,e=new G(c),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}():J?function(){var t=new MessageChannel;return t.port1.onmessage=c,function(){return t.port2.postMessage(0)}}():void 0===Y?function(){try{var t=n(9);return R=t.runOnLoop||t.runOnContext,u()}catch(t){return a()}}():a();var tt=Math.random().toString(36).substring(16),et=void 0,nt=1,ot=2,it=new x,rt=new x,st=0;return M.prototype._enumerate=function(){for(var t=this.length,e=this._input,n=0;this._state===et&&n<t;n++)this._eachEntry(e[n],n)},M.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,o=n.resolve;if(o===d){var i=m(t);if(i===l&&t._state!==et)this._settledAt(t._state,e,t._result);else if("function"!=typeof i)this._remaining--,this._result[e]=t;else if(n===V){var r=new n(f);w(r,t,i),this._willSettleAt(r,e)}else this._willSettleAt(new n(function(e){return e(t)}),e)}else this._willSettleAt(o(t),e)},M.prototype._settledAt=function(t,e,n){var o=this.promise;o._state===et&&(this._remaining--,t===ot?S(o,n):this._result[e]=n),0===this._remaining&&k(o,this._result)},M.prototype._willSettleAt=function(t,e){var n=this;C(t,void 0,function(t){return n._settledAt(nt,e,t)},function(t){return n._settledAt(ot,e,t)})},V.all=j,V.race=N,V.resolve=d,V.reject=H,V._setScheduler=r,V._setAsap=s,V._asap=U,V.prototype={constructor:V,then:l,catch:function(t){return this.then(null,t)}},V.polyfill=B,V.Promise=V,V})}).call(e,n(7),n(8))},function(t,e){},function(t,e,n){"use strict";function o(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}return function(e,n,o){return n&&t(e.prototype,n),o&&t(e,o),e}}();n(5);var s=n(4),u=function(t){return t&&t.__esModule?t:{default:t}}(s),a=n(0),c=o(a),l=n(1),d=o(l),f=n(2),h=n(3),p=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return i(this,t),this.options=c.deepExtend({},d.Defaults,e),this.id=this.options.id||c.generateID("bar"),this.closeTimer=-1,this.barDom=null,this.layoutDom=null,this.progressDom=null,this.showing=!1,this.shown=!1,this.closed=!1,this.closing=!1,this.killable=this.options.timeout||this.options.closeWith.length>0,this.hasSound=this.options.sounds.sources.length>0,this.soundPlayed=!1,this.listeners={beforeShow:[],onShow:[],afterShow:[],onClose:[],afterClose:[],onHover:[],onTemplate:[]},this.promises={show:null,close:null},this.on("beforeShow",this.options.callbacks.beforeShow),this.on("onShow",this.options.callbacks.onShow),this.on("afterShow",this.options.callbacks.afterShow),this.on("onClose",this.options.callbacks.onClose),this.on("afterClose",this.options.callbacks.afterClose),this.on("onHover",this.options.callbacks.onHover),this.on("onTemplate",this.options.callbacks.onTemplate),this}return r(t,[{key:"on",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){};return"function"==typeof e&&this.listeners.hasOwnProperty(t)&&this.listeners[t].push(e),this}},{key:"show",value:function(){var e=this;if(!0!==this.options.killer||d.PageHidden)if("string"!=typeof this.options.killer||d.PageHidden){var n=d.getQueueCounts(this.options.queue);if(n.current>=n.maxVisible||d.PageHidden)return d.addToQueue(this),d.PageHidden&&this.hasSound&&c.inArray("docHidden",this.options.sounds.conditions)&&c.createAudioElements(this),d.PageHidden&&c.inArray("docHidden",this.options.titleCount.conditions)&&d.docTitle.increment(),this}else t.closeAll(this.options.killer);else t.closeAll();if(d.Store[this.id]=this,d.fire(this,"beforeShow"),this.showing=!0,this.closing)return this.showing=!1,this;if(d.build(this),d.handleModal(this),this.options.force?this.layoutDom.insertBefore(this.barDom,this.layoutDom.firstChild):this.layoutDom.appendChild(this.barDom),this.hasSound&&!this.soundPlayed&&c.inArray("docVisible",this.options.sounds.conditions)&&c.createAudioElements(this),c.inArray("docVisible",this.options.titleCount.conditions)&&d.docTitle.increment(),this.shown=!0,this.closed=!1,d.hasButtons(this)&&Object.keys(this.options.buttons).forEach(function(t){var n=e.barDom.querySelector("#"+e.options.buttons[t].id);c.addListener(n,"click",function(n){c.stopPropagation(n),e.options.buttons[t].cb()})}),this.progressDom=this.barDom.querySelector(".noty_progressbar"),c.inArray("click",this.options.closeWith)&&(c.addClass(this.barDom,"noty_close_with_click"),c.addListener(this.barDom,"click",function(t){c.stopPropagation(t),e.close()},!1)),c.addListener(this.barDom,"mouseenter",function(){d.fire(e,"onHover")},!1),this.options.timeout&&c.addClass(this.barDom,"noty_has_timeout"),c.inArray("button",this.options.closeWith)){c.addClass(this.barDom,"noty_close_with_button");var o=document.createElement("div");c.addClass(o,"noty_close_button"),o.innerHTML="×",this.barDom.appendChild(o),c.addListener(o,"click",function(t){c.stopPropagation(t),e.close()},!1)}return d.fire(this,"onShow"),null===this.options.animation.open?this.promises.show=new u.default(function(t){t()}):"function"==typeof this.options.animation.open?this.promises.show=new u.default(this.options.animation.open.bind(this)):(c.addClass(this.barDom,this.options.animation.open),this.promises.show=new u.default(function(t){c.addListener(e.barDom,c.animationEndEvents,function(){c.removeClass(e.barDom,e.options.animation.open),t()})})),this.promises.show.then(function(){var t=e;setTimeout(function(){d.openFlow(t)},100)}),this}},{key:"stop",value:function(){return d.dequeueClose(this),this}},{key:"resume",value:function(){return d.queueClose(this),this}},{key:"setTimeout",value:function(t){function e(e){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}(function(t){if(this.stop(),this.options.timeout=t,this.barDom){this.options.timeout?c.addClass(this.barDom,"noty_has_timeout"):c.removeClass(this.barDom,"noty_has_timeout");var e=this;setTimeout(function(){e.resume()},100)}return this})},{key:"setText",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.barDom&&(this.barDom.querySelector(".noty_body").innerHTML=t),e&&(this.options.text=t),this}},{key:"setType",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.barDom){c.classList(this.barDom).split(" ").forEach(function(t){"noty_type__"===t.substring(0,11)&&c.removeClass(e.barDom,t)}),c.addClass(this.barDom,"noty_type__"+t)}return n&&(this.options.type=t),this}},{key:"setTheme",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.barDom){c.classList(this.barDom).split(" ").forEach(function(t){"noty_theme__"===t.substring(0,12)&&c.removeClass(e.barDom,t)}),c.addClass(this.barDom,"noty_theme__"+t)}return n&&(this.options.theme=t),this}},{key:"close",value:function(){var t=this;return this.closed?this:this.shown?(d.fire(this,"onClose"),this.closing=!0,null===this.options.animation.close?this.promises.close=new u.default(function(t){t()}):"function"==typeof this.options.animation.close?this.promises.close=new u.default(this.options.animation.close.bind(this)):(c.addClass(this.barDom,this.options.animation.close),this.promises.close=new u.default(function(e){c.addListener(t.barDom,c.animationEndEvents,function(){t.options.force?c.remove(t.barDom):d.ghostFix(t),e()})})),this.promises.close.then(function(){d.closeFlow(t),d.handleModalClose(t)}),this.closed=!0,this):(d.removeFromQueue(this),this)}}],[{key:"closeAll",value:function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Object.keys(d.Store).forEach(function(e){t?d.Store[e].options.queue===t&&d.Store[e].killable&&d.Store[e].close():d.Store[e].killable&&d.Store[e].close()}),this}},{key:"overrideDefaults",value:function(t){return d.Defaults=c.deepExtend({},d.Defaults,t),this}},{key:"setMaxVisible",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:d.DefaultMaxVisible,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"global";return d.Queues.hasOwnProperty(e)||(d.Queues[e]={maxVisible:t,queue:[]}),d.Queues[e].maxVisible=t,this}},{key:"button",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return new f.NotyButton(t,e,n,o)}},{key:"version",value:function(){return"3.1.0"}},{key:"Push",value:function(t){return new h.Push(t)}}]),t}();e.default=p,c.visibilityChangeFlow(),t.exports=e.default},function(t,e){function n(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function i(t){if(l===setTimeout)return setTimeout(t,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(t,0);try{return l(t,0)}catch(e){try{return l.call(null,t,0)}catch(e){return l.call(this,t,0)}}}function r(t){if(d===clearTimeout)return clearTimeout(t);if((d===o||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(t);try{return d(t)}catch(e){try{return d.call(null,t)}catch(e){return d.call(this,t)}}}function s(){m&&h&&(m=!1,h.length?p=h.concat(p):v=-1,p.length&&u())}function u(){if(!m){var t=i(s);m=!0;for(var e=p.length;e;){for(h=p,p=[];++v<e;)h&&h[v].run();v=-1,e=p.length}h=null,m=!1,r(t)}}function a(t,e){this.fun=t,this.array=e}function c(){}var l,d,f=t.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(t){l=n}try{d="function"==typeof clearTimeout?clearTimeout:o}catch(t){d=o}}();var h,p=[],m=!1,v=-1;f.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];p.push(new a(t,e)),1!==p.length||m||i(u)},a.prototype.run=function(){this.fun.apply(null,this.array)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=c,f.addListener=c,f.once=c,f.off=c,f.removeListener=c,f.removeAllListeners=c,f.emit=c,f.binding=function(t){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(t){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e){}])});
    +//# sourceMappingURL=noty.min.js.map
    \ No newline at end of file
    
    From 14a9a1c616ae0a217cb53a3a86c9b84140bb0553 Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Thu, 11 May 2017 23:10:32 +0200
    Subject: [PATCH 34/49] A lot of changes... still not finished, use with
     caution. Edit actions can be done with the internal API, trying to get rid of
     edit and add files
    
    ---
     data/web/add.php               |   35 +-
     data/web/admin.php             |   66 +-
     data/web/css/mailbox.css       |   15 +-
     data/web/css/mailcow.css       |   10 +-
     data/web/css/noty.css          |  650 ------------
     data/web/edit.php              |   45 +-
     data/web/inc/footer.inc.php    |    5 +-
     data/web/inc/functions.inc.php | 1791 ++++++++++++++++----------------
     data/web/inc/vars.inc.php      |    5 +-
     data/web/js/admin.js           |  407 ++++----
     data/web/js/mailbox.js         |  704 +++++++------
     data/web/js/notify.min.js      |    1 -
     data/web/js/noty.min.js        |    9 -
     data/web/json_api.php          |  527 ++++++++--
     data/web/lang/lang.de.php      |    4 +-
     data/web/lang/lang.en.php      |    2 +-
     data/web/mailbox.php           |   75 +-
     data/web/user.php              |    6 +-
     18 files changed, 2095 insertions(+), 2262 deletions(-)
     delete mode 100644 data/web/css/noty.css
     delete mode 100644 data/web/js/notify.min.js
     delete mode 100644 data/web/js/noty.min.js
    
    diff --git a/data/web/add.php b/data/web/add.php
    index 5f1aa0d6..88e60b06 100644
    --- a/data/web/add.php
    +++ b/data/web/add.php
    @@ -21,6 +21,9 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     ?>
     				<h4><?=$lang['add']['domain'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    +          <input type="hidden" value="0" name="active">
    +          <input type="hidden" value="0" name="backupmx">
    +          <input type="hidden" value="0" name="relay_all_recipients">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="domain"><?=$lang['add']['domain'];?>:</label>
     						<div class="col-sm-10">
    @@ -61,9 +64,9 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     						<label class="control-label col-sm-2"><?=$lang['add']['backup_mx_options'];?></label>
     						<div class="col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="backupmx"> <?=$lang['add']['relay_domain'];?></label>
    +							<label><input type="checkbox" value="1" name="backupmx"> <?=$lang['add']['relay_domain'];?></label>
     							<br />
    -							<label><input type="checkbox" name="relay_all_recipients"> <?=$lang['add']['relay_all'];?></label>
    +							<label><input type="checkbox" value="1" name="relay_all_recipients"> <?=$lang['add']['relay_all'];?></label>
     							<p><?=$lang['add']['relay_all_info'];?></p>
     							</div>
     						</div>
    @@ -71,7 +74,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="active" checked> <?=$lang['add']['active'];?></label>
    +							<label><input type="checkbox" value="1" name="active" checked> <?=$lang['add']['active'];?></label>
     							</div>
     						</div>
     					</div>
    @@ -89,6 +92,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     				<h4><?=$lang['add']['alias'];?></h4>
     				<p><?=$lang['add']['alias_spf_fail'];?></p>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    +          <input type="hidden" value="0" name="active">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="address"><?=$lang['add']['alias_address'];?></label>
     						<div class="col-sm-10">
    @@ -106,7 +110,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="active" checked> <?=$lang['add']['active'];?></label>
    +							<label><input type="checkbox" value="1" name="active" checked> <?=$lang['add']['active'];?></label>
     							</div>
     						</div>
     					</div>
    @@ -122,6 +126,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     	?>
     				<h4><?=$lang['add']['alias_domain'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    +          <input type="hidden" value="0" name="active">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="alias_domain"><?=$lang['add']['alias_domain'];?></label>
     						<div class="col-sm-10">
    @@ -144,7 +149,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="active" checked> <?=$lang['add']['active'];?></label>
    +							<label><input type="checkbox" value="1" name="active" checked> <?=$lang['add']['active'];?></label>
     							</div>
     						</div>
     					</div>
    @@ -160,6 +165,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     	?>
     				<h4><?=$lang['add']['mailbox'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    +          <input type="hidden" value="0" name="active">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="local_part"><?=$lang['add']['mailbox_username'];?></label>
     						<div class="col-sm-10">
    @@ -207,7 +213,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="active" checked> <?=$lang['add']['active'];?></label>
    +							<label><input type="checkbox" value="1" name="active" checked> <?=$lang['add']['active'];?></label>
     							</div>
     						</div>
     					</div>
    @@ -223,6 +229,8 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     	?>
     				<h4><?=$lang['add']['resource'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    +          <input type="hidden" value="0" name="active">
    +          <input type="hidden" value="0" name="multiple_bookings">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="description"><?=$lang['add']['description'];?></label>
     						<div class="col-sm-10">
    @@ -254,14 +262,14 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="active" checked> <?=$lang['add']['active'];?></label>
    +							<label><input type="checkbox" value="1" name="active" checked> <?=$lang['add']['active'];?></label>
     							</div>
     						</div>
     					</div>
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="multiple_bookings" checked> <?=$lang['add']['multiple_bookings'];?></label>
    +							<label><input type="checkbox" value="1" name="multiple_bookings" checked> <?=$lang['add']['multiple_bookings'];?></label>
     							</div>
     						</div>
     					</div>
    @@ -285,6 +293,9 @@ elseif (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] ==
     				<h4><?=$lang['add']['syncjob'];?></h4>
     				<p><?=$lang['add']['syncjob_hint'];?></p>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    +          <input type="hidden" value="0" name="active">
    +          <input type="hidden" value="0" name="delete1">
    +          <input type="hidden" value="0" name="delete2duplicates">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="host1"><?=$lang['add']['hostname'];?></label>
     						<div class="col-sm-10">
    @@ -346,27 +357,27 @@ elseif (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] ==
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="delete2duplicates" checked> <?=$lang['add']['delete2duplicates'];?></label>
    +							<label><input type="checkbox" value="1" name="delete2duplicates" checked> <?=$lang['add']['delete2duplicates'];?></label>
     							</div>
     						</div>
     					</div>
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="delete1"> <?=$lang['add']['delete1'];?></label>
    +							<label><input type="checkbox" value="1" name="delete1"> <?=$lang['add']['delete1'];?></label>
     							</div>
     						</div>
     					</div>
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="active" checked> <?=$lang['add']['active'];?></label>
    +							<label><input type="checkbox" value="1" name="active" checked> <?=$lang['add']['active'];?></label>
     							</div>
     						</div>
     					</div>
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
    -							<button type="submit" name="add_syncjob" value="1" class="btn btn-success "><?=$lang['add']['save'];?></button>
    +							<button type="submit" name="add_syncjob" class="btn btn-success "><?=$lang['add']['save'];?></button>
     						</div>
     					</div>
     				</form>
    diff --git a/data/web/admin.php b/data/web/admin.php
    index 9a7f2ba2..2d800622 100644
    --- a/data/web/admin.php
    +++ b/data/web/admin.php
    @@ -100,6 +100,7 @@ $tfa_data = get_tfa();
               <small>
               <legend><?=$lang['admin']['add_domain_admin'];?></legend>
               <form class="form-horizontal" role="form" method="post">
    +            <input type="hidden" value="0" name="active">
                 <div class="form-group">
                   <label class="control-label col-sm-2" for="username"><?=$lang['admin']['username'];?>:</label>
                   <div class="col-sm-10">
    @@ -134,7 +135,7 @@ $tfa_data = get_tfa();
                 <div class="form-group">
                   <div class="col-sm-offset-2 col-sm-10">
                     <div class="checkbox">
    -                <label><input type="checkbox" name="active" checked> <?=$lang['admin']['active'];?></label>
    +                <label><input type="checkbox" value="1" name="active" checked> <?=$lang['admin']['active'];?></label>
                     </div>
                   </div>
                 </div>
    @@ -155,36 +156,39 @@ $tfa_data = get_tfa();
         <div class="panel panel-default">
           <div class="panel-heading"><?=$lang['admin']['dkim_keys'];?></div>
           <div class="panel-body">
    -      <form class="form-inline" method="post" data-id="dkimkeys">
    +        <div class="mass-actions-admin">
    +          <div class="btn-group btn-group-sm">
    +            <button type="button" id="toggle_multi_select_all" data-id="dkim" class="btn btn-default"><?=$lang['mailbox']['toggle_all'];?></button>
    +            <button type="button" id="delete_selected" name="delete_selected" data-id="dkim" data-api-url="delete/dkim" class="btn btn-danger"><?=$lang['admin']['remove'];?></button>
    +          </div>
    +        </div>
             <?php
             foreach(mailbox_get_domains() as $domain) {
                 if (!empty($dkim = dkim_get_key_details($domain))) {
               ?>
                 <div class="row">
    -              <div class="col-xs-3">
    +              <div class="col-xs-1"><input type="checkbox" data-id="dkim" name="multi_select" value="<?=$domain;?>" /></div>
    +              <div class="col-xs-2">
                     <p>Domain: <strong><?=htmlspecialchars($domain);?></strong><br />
                       <span class="label label-success"><?=$lang['admin']['dkim_key_valid'];?></span>
                       <span class="label label-primary">Selector '<?=$dkim['dkim_selector'];?>'</span>
                       <span class="label label-info"><?=$dkim['length'];?> bit</span>
                     </p>
                   </div>
    -              <div class="col-xs-8">
    +              <div class="col-xs-9">
                       <pre><?=$dkim['dkim_txt'];?></pre>
                   </div>
    -              <div class="col-xs-1">
    -                <span style="cursor:pointer" data-dkim-domain="<?=$domain;?>" data-dkim-selector="<?=$dkim['dkim_selector'];?>" id="delete_dkim_key" class="text-danger glyphicon glyphicon-remove"></span></a>
    -              </div>
                 </div>
               <?php
               }
               else {
               ?>
               <div class="row">
    -            <div class="col-xs-3">
    +              <div class="col-xs-1"><input type="checkbox" data-id="dkim" name="multi_select" value="<?=$domain;?>" disabled /></div>
    +            <div class="col-xs-2">
                   <p>Domain: <strong><?=htmlspecialchars($domain);?></strong><br /><span class="label label-danger"><?=$lang['admin']['dkim_key_missing'];?></span></p>
                 </div>
    -            <div class="col-xs-8"><pre>-</pre></div>
    -            <div class="col-xs-1">&nbsp;</div>
    +            <div class="col-xs-9"><pre>-</pre></div>
               </div>
               <?php
               }
    @@ -192,30 +196,28 @@ $tfa_data = get_tfa();
                 if (!empty($dkim = dkim_get_key_details($alias_domain))) {
                 ?>
                   <div class="row">
    -                <div class="col-xs-offset-1 col-xs-2">
    +              <div class="col-xs-1"><input type="checkbox" data-id="dkim" name="multi_select" value="<?=$alias_domain;?>" /></div>
    +                <div class="col-xs-1 col-xs-offset-1">
                       <p><small>↳ Alias-Domain: <strong><?=htmlspecialchars($alias_domain);?></strong><br /></small>
                         <span class="label label-success"><?=$lang['admin']['dkim_key_valid'];?></span>
                         <span class="label label-primary">Selector '<?=$dkim['dkim_selector'];?>'</span>
                         <span class="label label-info"><?=$dkim['length'];?> bit</span>
                     </p>
                     </div>
    -                <div class="col-xs-8">
    +                <div class="col-xs-9">
                       <pre><?=$dkim['dkim_txt'];?></pre>
                     </div>
    -                <div class="col-xs-1">
    -                  <span style="cursor:pointer" data-dkim-domain="<?=$domain;?>" data-dkim-selector="<?=$dkim['dkim_selector'];?>" id="delete_dkim_key" class="text-danger glyphicon glyphicon-remove"></span></a>
    -                </div>
                   </div>
                 <?php
                 }
                 else {
                 ?>
                 <div class="row">
    -              <div class="col-xs-2 col-xs-offset-1">
    +              <div class="col-xs-1"><input type="checkbox" data-id="dkim" name="multi_select" value="<?=$domain;?>" disabled /></div>
    +              <div class="col-xs-1 col-xs-offset-1">
                     <p><small>↳ Alias-Domain: <strong><?=htmlspecialchars($alias_domain);?></strong><br /></small><span class="label label-danger"><?=$lang['admin']['dkim_key_missing'];?></span></p>
                   </div>
    -            <div class="col-xs-8"><pre>-</pre></div>
    -            <div class="col-xs-1">&nbsp;</div>
    +            <div class="col-xs-9"><pre>-</pre></div>
                 </div>
                 <?php
                 }
    @@ -225,25 +227,22 @@ $tfa_data = get_tfa();
               if (!empty($dkim = dkim_get_key_details($blind))) {
               ?>
                 <div class="row">
    -              <div class="col-xs-3">
    +              <div class="col-xs-1"><input type="checkbox" data-id="dkim" name="multi_select" value="<?=$blind;?>" /></div>
    +              <div class="col-xs-2">
                     <p>Domain: <strong><?=htmlspecialchars($blind);?></strong><br />
                       <span class="label label-warning"><?=$lang['admin']['dkim_key_unused'];?></span>
                       <span class="label label-primary">Selector '<?=$dkim['dkim_selector'];?>'</span>
                       <span class="label label-info"><?=$dkim['length'];?> bit</span>
                     </p>
                     </div>
    -                <div class="col-xs-8">
    +                <div class="col-xs-9">
                       <pre><?=$dkim['dkim_txt'];?></pre>
                     </div>
    -                <div class="col-xs-1">
    -                  <span style="cursor:pointer" data-dkim-domain="<?=$blind;?>" data-dkim-selector="<?=$dkim['dkim_selector'];?>" id="delete_dkim_key" class="text-danger glyphicon glyphicon-remove"></span></a>
    -                </div>
                 </div>
               <?php
               }
             }
             ?>
    -        </form>
     
             <legend style="margin-top:40px"><?=$lang['admin']['dkim_add_key'];?></legend>
             <form class="form-inline" role="form" method="post">
    @@ -270,21 +269,20 @@ $tfa_data = get_tfa();
           <div class="panel-heading"><?=$lang['admin']['forwarding_hosts'];?></div>
           <div class="panel-body">
             <p style="margin-bottom:40px"><?=$lang['admin']['forwarding_hosts_hint'];?></p>
    -        <form method="post" data-id="fwdhosts">
    -        <div class="btn-group btn-group-sm">
    -          <button type="button" id="toggle_multi_select_all" data-form-id="fwdhosts" class="btn btn-default">Toggle all</button>
    -          <button type="button" id="delete_fwdhosts" name="delete_fwdhosts" class="btn btn-danger"><?=$lang['admin']['remove'];?></button>
    -        </div>
    -        <hr >
    -        <div class="table-responsive">
    -            <table class="table table-striped" id="forwardinghoststable"></table>
    +        <div class="mass-actions-admin">
    +          <div class="btn-group btn-group-sm">
    +            <button type="button" id="toggle_multi_select_all" data-id="fwdhosts" class="btn btn-default"><?=$lang['mailbox']['toggle_all'];?></button>
    +            <button type="button" id="delete_selected" name="delete_selected" data-id="fwdhosts" data-api-url="delete/fwdhost" class="btn btn-danger"><?=$lang['admin']['remove'];?></button>
               </div>
    -        </form>
    +        </div>
    +        <div class="table-responsive">
    +          <table class="table table-striped" id="forwardinghoststable"></table>
    +        </div>
             <legend><?=$lang['admin']['add_forwarding_host'];?></legend>
             <p class="help-block"><?=$lang['admin']['forwarding_hosts_add_hint'];?></p>
             <form class="form-inline" role="form" method="post">
               <div class="form-group">
    -            <label for="hostname"><?=$lang['edit']['host'];?></label>
    +            <label for="hostname"><?=$lang['admin']['host'];?></label>
                 <input class="form-control" id="hostname" name="hostname" placeholder="example.org" required>
               </div>
               <div class="form-group">
    diff --git a/data/web/css/mailbox.css b/data/web/css/mailbox.css
    index 2e6c1afe..8db97c31 100644
    --- a/data/web/css/mailbox.css
    +++ b/data/web/css/mailbox.css
    @@ -13,21 +13,12 @@ table.footable>tbody>tr.footable-empty>td {
     }
     .footer-add-item {
       display:block;
    +  text-align: center;
    +  font-style: italic;
       padding: 10px;
       background: #F5F5F5;
     }
    -.mass-each-action {
    -  padding: 0 3px 0 3px;
    -  user-select: none;
    -}
    -.mass-actions {
    -  user-select: none;
    -  padding:10px;
    -}
    -.mass-select-all {
    -  cursor:pointer;
    -  color:#555;
    -}
    +
     #alias_table {
       cursor:pointer;
     }
    diff --git a/data/web/css/mailcow.css b/data/web/css/mailcow.css
    index 90dccf93..3978fcd9 100644
    --- a/data/web/css/mailcow.css
    +++ b/data/web/css/mailcow.css
    @@ -62,4 +62,12 @@ body.modal-open {
       min-width: 350px;
       max-width: 550px;
       z-index: 2000;
    -}
    \ No newline at end of file
    +}
    +.mass-actions-mailbox {
    +  user-select: none;
    +  padding:10px 0 10px 10px;
    +}
    +.mass-actions-admin {
    +  user-select: none;
    +  padding:10px 0 10px 0;
    +}
    diff --git a/data/web/css/noty.css b/data/web/css/noty.css
    deleted file mode 100644
    index 2df92f1f..00000000
    --- a/data/web/css/noty.css
    +++ /dev/null
    @@ -1,650 +0,0 @@
    -.noty_layout_mixin, #noty_layout__top, #noty_layout__topLeft, #noty_layout__topCenter, #noty_layout__topRight, #noty_layout__bottom, #noty_layout__bottomLeft, #noty_layout__bottomCenter, #noty_layout__bottomRight, #noty_layout__center, #noty_layout__centerLeft, #noty_layout__centerRight {
    -  position: fixed;
    -  margin: 0;
    -  padding: 0;
    -  z-index: 9999999;
    -  -webkit-transform: translateZ(0) scale(1, 1);
    -          transform: translateZ(0) scale(1, 1);
    -  -webkit-backface-visibility: hidden;
    -          backface-visibility: hidden;
    -  -webkit-font-smoothing: subpixel-antialiased;
    -  filter: blur(0);
    -  -webkit-filter: blur(0);
    -  max-width: 90%; }
    -
    -#noty_layout__top {
    -  top: 0;
    -  left: 5%;
    -  width: 90%; }
    -
    -#noty_layout__topLeft {
    -  top: 20px;
    -  left: 20px;
    -  width: 325px; }
    -
    -#noty_layout__topCenter {
    -  top: 5%;
    -  left: 50%;
    -  width: 325px;
    -  -webkit-transform: translate(-webkit-calc(-50% - .5px)) translateZ(0) scale(1, 1);
    -          transform: translate(calc(-50% - .5px)) translateZ(0) scale(1, 1); }
    -
    -#noty_layout__topRight {
    -  top: 20px;
    -  right: 20px;
    -  width: 325px; }
    -
    -#noty_layout__bottom {
    -  bottom: 0;
    -  left: 5%;
    -  width: 90%; }
    -
    -#noty_layout__bottomLeft {
    -  bottom: 20px;
    -  left: 20px;
    -  width: 325px; }
    -
    -#noty_layout__bottomCenter {
    -  bottom: 5%;
    -  left: 50%;
    -  width: 325px;
    -  -webkit-transform: translate(-webkit-calc(-50% - .5px)) translateZ(0) scale(1, 1);
    -          transform: translate(calc(-50% - .5px)) translateZ(0) scale(1, 1); }
    -
    -#noty_layout__bottomRight {
    -  bottom: 20px;
    -  right: 20px;
    -  width: 325px; }
    -
    -#noty_layout__center {
    -  top: 50%;
    -  left: 50%;
    -  width: 325px;
    -  -webkit-transform: translate(-webkit-calc(-50% - .5px), -webkit-calc(-50% - .5px)) translateZ(0) scale(1, 1);
    -          transform: translate(calc(-50% - .5px), calc(-50% - .5px)) translateZ(0) scale(1, 1); }
    -
    -#noty_layout__centerLeft {
    -  top: 50%;
    -  left: 20px;
    -  width: 325px;
    -  -webkit-transform: translate(0, -webkit-calc(-50% - .5px)) translateZ(0) scale(1, 1);
    -          transform: translate(0, calc(-50% - .5px)) translateZ(0) scale(1, 1); }
    -
    -#noty_layout__centerRight {
    -  top: 50%;
    -  right: 20px;
    -  width: 325px;
    -  -webkit-transform: translate(0, -webkit-calc(-50% - .5px)) translateZ(0) scale(1, 1);
    -          transform: translate(0, calc(-50% - .5px)) translateZ(0) scale(1, 1); }
    -
    -.noty_progressbar {
    -  display: none; }
    -
    -.noty_has_timeout .noty_progressbar {
    -  display: block;
    -  position: absolute;
    -  left: 0;
    -  bottom: 0;
    -  height: 3px;
    -  width: 100%;
    -  background-color: #646464;
    -  opacity: 0.2;
    -  filter: alpha(opacity=10); }
    -
    -.noty_bar {
    -  -webkit-backface-visibility: hidden;
    -  -webkit-transform: translate(0, 0) translateZ(0) scale(1, 1);
    -  -ms-transform: translate(0, 0) scale(1, 1);
    -      transform: translate(0, 0) scale(1, 1);
    -  -webkit-font-smoothing: subpixel-antialiased;
    -  overflow: hidden; }
    -
    -.noty_effects_open {
    -  opacity: 0;
    -  -webkit-transform: translate(50%);
    -      -ms-transform: translate(50%);
    -          transform: translate(50%);
    -  -webkit-animation: noty_anim_in 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    -          animation: noty_anim_in 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    -  -webkit-animation-fill-mode: forwards;
    -          animation-fill-mode: forwards; }
    -
    -.noty_effects_close {
    -  -webkit-animation: noty_anim_out 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    -          animation: noty_anim_out 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    -  -webkit-animation-fill-mode: forwards;
    -          animation-fill-mode: forwards; }
    -
    -.noty_fix_effects_height {
    -  -webkit-animation: noty_anim_height 75ms ease-out;
    -          animation: noty_anim_height 75ms ease-out; }
    -
    -.noty_close_with_click {
    -  cursor: pointer; }
    -
    -.noty_close_button {
    -  position: absolute;
    -  top: 2px;
    -  right: 2px;
    -  font-weight: bold;
    -  width: 20px;
    -  height: 20px;
    -  text-align: center;
    -  line-height: 20px;
    -  background-color: rgba(0, 0, 0, 0.05);
    -  border-radius: 2px;
    -  cursor: pointer;
    -  -webkit-transition: all .2s ease-out;
    -  transition: all .2s ease-out; }
    -
    -.noty_close_button:hover {
    -  background-color: rgba(0, 0, 0, 0.1); }
    -
    -.noty_modal {
    -  position: fixed;
    -  width: 100%;
    -  height: 100%;
    -  background-color: #000;
    -  z-index: 10000;
    -  opacity: .3;
    -  left: 0;
    -  top: 0; }
    -
    -.noty_modal.noty_modal_open {
    -  opacity: 0;
    -  -webkit-animation: noty_modal_in .3s ease-out;
    -          animation: noty_modal_in .3s ease-out; }
    -
    -.noty_modal.noty_modal_close {
    -  -webkit-animation: noty_modal_out .3s ease-out;
    -          animation: noty_modal_out .3s ease-out;
    -  -webkit-animation-fill-mode: forwards;
    -          animation-fill-mode: forwards; }
    -
    -@-webkit-keyframes noty_modal_in {
    -  100% {
    -    opacity: .3; } }
    -
    -@keyframes noty_modal_in {
    -  100% {
    -    opacity: .3; } }
    -
    -@-webkit-keyframes noty_modal_out {
    -  100% {
    -    opacity: 0; } }
    -
    -@keyframes noty_modal_out {
    -  100% {
    -    opacity: 0; } }
    -
    -@keyframes noty_modal_out {
    -  100% {
    -    opacity: 0; } }
    -
    -@-webkit-keyframes noty_anim_in {
    -  100% {
    -    -webkit-transform: translate(0);
    -            transform: translate(0);
    -    opacity: 1; } }
    -
    -@keyframes noty_anim_in {
    -  100% {
    -    -webkit-transform: translate(0);
    -            transform: translate(0);
    -    opacity: 1; } }
    -
    -@-webkit-keyframes noty_anim_out {
    -  100% {
    -    -webkit-transform: translate(50%);
    -            transform: translate(50%);
    -    opacity: 0; } }
    -
    -@keyframes noty_anim_out {
    -  100% {
    -    -webkit-transform: translate(50%);
    -            transform: translate(50%);
    -    opacity: 0; } }
    -
    -@-webkit-keyframes noty_anim_height {
    -  100% {
    -    height: 0; } }
    -
    -@keyframes noty_anim_height {
    -  100% {
    -    height: 0; } }
    -
    -.noty_theme__relax.noty_bar {
    -  margin: 4px 0;
    -  overflow: hidden;
    -  border-radius: 2px;
    -  position: relative; }
    -  .noty_theme__relax.noty_bar .noty_body {
    -    padding: 10px; }
    -  .noty_theme__relax.noty_bar .noty_buttons {
    -    border-top: 1px solid #e7e7e7;
    -    padding: 5px 10px; }
    -
    -.noty_theme__relax.noty_type__alert,
    -.noty_theme__relax.noty_type__notification {
    -  background-color: #fff;
    -  border: 1px solid #dedede;
    -  color: #444; }
    -
    -.noty_theme__relax.noty_type__warning {
    -  background-color: #FFEAA8;
    -  border: 1px solid #FFC237;
    -  color: #826200; }
    -  .noty_theme__relax.noty_type__warning .noty_buttons {
    -    border-color: #dfaa30; }
    -
    -.noty_theme__relax.noty_type__error {
    -  background-color: #FF8181;
    -  border: 1px solid #e25353;
    -  color: #FFF; }
    -  .noty_theme__relax.noty_type__error .noty_buttons {
    -    border-color: darkred; }
    -
    -.noty_theme__relax.noty_type__info,
    -.noty_theme__relax.noty_type__information {
    -  background-color: #78C5E7;
    -  border: 1px solid #3badd6;
    -  color: #FFF; }
    -  .noty_theme__relax.noty_type__info .noty_buttons,
    -  .noty_theme__relax.noty_type__information .noty_buttons {
    -    border-color: #0B90C4; }
    -
    -.noty_theme__relax.noty_type__success {
    -  background-color: #BCF5BC;
    -  border: 1px solid #7cdd77;
    -  color: darkgreen; }
    -  .noty_theme__relax.noty_type__success .noty_buttons {
    -    border-color: #50C24E; }
    -
    -.noty_theme__metroui.noty_bar {
    -  margin: 4px 0;
    -  overflow: hidden;
    -  position: relative;
    -  box-shadow: rgba(0, 0, 0, 0.298039) 0 0 5px 0; }
    -  .noty_theme__metroui.noty_bar .noty_progressbar {
    -    position: absolute;
    -    left: 0;
    -    bottom: 0;
    -    height: 3px;
    -    width: 100%;
    -    background-color: #000;
    -    opacity: 0.2;
    -    filter: alpha(opacity=20); }
    -  .noty_theme__metroui.noty_bar .noty_body {
    -    padding: 1.25em;
    -    font-size: 14px; }
    -  .noty_theme__metroui.noty_bar .noty_buttons {
    -    padding: 0 10px .5em 10px; }
    -
    -.noty_theme__metroui.noty_type__alert,
    -.noty_theme__metroui.noty_type__notification {
    -  background-color: #fff;
    -  color: #1d1d1d; }
    -
    -.noty_theme__metroui.noty_type__warning {
    -  background-color: #FA6800;
    -  color: #fff; }
    -
    -.noty_theme__metroui.noty_type__error {
    -  background-color: #CE352C;
    -  color: #FFF; }
    -
    -.noty_theme__metroui.noty_type__info,
    -.noty_theme__metroui.noty_type__information {
    -  background-color: #1BA1E2;
    -  color: #FFF; }
    -
    -.noty_theme__metroui.noty_type__success {
    -  background-color: #60A917;
    -  color: #fff; }
    -
    -.noty_theme__mint.noty_bar {
    -  margin: 4px 0;
    -  overflow: hidden;
    -  border-radius: 2px;
    -  position: relative; }
    -  .noty_theme__mint.noty_bar .noty_body {
    -    padding: 10px;
    -    font-size: 14px; }
    -  .noty_theme__mint.noty_bar .noty_buttons {
    -    padding: 10px; }
    -
    -.noty_theme__mint.noty_type__alert,
    -.noty_theme__mint.noty_type__notification {
    -  background-color: #fff;
    -  border-bottom: 1px solid #D1D1D1;
    -  color: #2F2F2F; }
    -
    -.noty_theme__mint.noty_type__warning {
    -  background-color: #FFAE42;
    -  border-bottom: 1px solid #E89F3C;
    -  color: #fff; }
    -
    -.noty_theme__mint.noty_type__error {
    -  background-color: #DE636F;
    -  border-bottom: 1px solid #CA5A65;
    -  color: #fff; }
    -
    -.noty_theme__mint.noty_type__info,
    -.noty_theme__mint.noty_type__information {
    -  background-color: #7F7EFF;
    -  border-bottom: 1px solid #7473E8;
    -  color: #fff; }
    -
    -.noty_theme__mint.noty_type__success {
    -  background-color: #AFC765;
    -  border-bottom: 1px solid #A0B55C;
    -  color: #fff; }
    -
    -.noty_theme__sunset.noty_bar {
    -  margin: 4px 0;
    -  overflow: hidden;
    -  border-radius: 2px;
    -  position: relative; }
    -  .noty_theme__sunset.noty_bar .noty_body {
    -    padding: 10px;
    -    font-size: 14px;
    -    text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1); }
    -  .noty_theme__sunset.noty_bar .noty_buttons {
    -    padding: 10px; }
    -
    -.noty_theme__sunset.noty_type__alert,
    -.noty_theme__sunset.noty_type__notification {
    -  background-color: #073B4C;
    -  color: #fff; }
    -  .noty_theme__sunset.noty_type__alert .noty_progressbar,
    -  .noty_theme__sunset.noty_type__notification .noty_progressbar {
    -    background-color: #fff; }
    -
    -.noty_theme__sunset.noty_type__warning {
    -  background-color: #FFD166;
    -  color: #fff; }
    -
    -.noty_theme__sunset.noty_type__error {
    -  background-color: #EF476F;
    -  color: #fff; }
    -  .noty_theme__sunset.noty_type__error .noty_progressbar {
    -    opacity: .4; }
    -
    -.noty_theme__sunset.noty_type__info,
    -.noty_theme__sunset.noty_type__information {
    -  background-color: #118AB2;
    -  color: #fff; }
    -  .noty_theme__sunset.noty_type__info .noty_progressbar,
    -  .noty_theme__sunset.noty_type__information .noty_progressbar {
    -    opacity: .6; }
    -
    -.noty_theme__sunset.noty_type__success {
    -  background-color: #06D6A0;
    -  color: #fff; }
    -
    -.noty_theme__bootstrap-v3.noty_bar {
    -  margin: 4px 0;
    -  overflow: hidden;
    -  position: relative;
    -  border: 1px solid transparent;
    -  border-radius: 4px; }
    -  .noty_theme__bootstrap-v3.noty_bar .noty_body {
    -    padding: 15px; }
    -  .noty_theme__bootstrap-v3.noty_bar .noty_buttons {
    -    padding: 10px; }
    -  .noty_theme__bootstrap-v3.noty_bar .noty_close_button {
    -    font-size: 21px;
    -    font-weight: 700;
    -    line-height: 1;
    -    color: #000;
    -    text-shadow: 0 1px 0 #fff;
    -    filter: alpha(opacity=20);
    -    opacity: .2;
    -    background: transparent; }
    -  .noty_theme__bootstrap-v3.noty_bar .noty_close_button:hover {
    -    background: transparent;
    -    text-decoration: none;
    -    cursor: pointer;
    -    filter: alpha(opacity=50);
    -    opacity: .5; }
    -
    -.noty_theme__bootstrap-v3.noty_type__alert,
    -.noty_theme__bootstrap-v3.noty_type__notification {
    -  background-color: #fff;
    -  color: inherit; }
    -
    -.noty_theme__bootstrap-v3.noty_type__warning {
    -  background-color: #fcf8e3;
    -  color: #8a6d3b;
    -  border-color: #faebcc; }
    -
    -.noty_theme__bootstrap-v3.noty_type__error {
    -  background-color: #f2dede;
    -  color: #a94442;
    -  border-color: #ebccd1; }
    -
    -.noty_theme__bootstrap-v3.noty_type__info,
    -.noty_theme__bootstrap-v3.noty_type__information {
    -  background-color: #d9edf7;
    -  color: #31708f;
    -  border-color: #bce8f1; }
    -
    -.noty_theme__bootstrap-v3.noty_type__success {
    -  background-color: #dff0d8;
    -  color: #3c763d;
    -  border-color: #d6e9c6; }
    -
    -.noty_theme__bootstrap-v4.noty_bar {
    -  margin: 4px 0;
    -  overflow: hidden;
    -  position: relative;
    -  border: 1px solid transparent;
    -  border-radius: .25rem; }
    -  .noty_theme__bootstrap-v4.noty_bar .noty_body {
    -    padding: .75rem 1.25rem; }
    -  .noty_theme__bootstrap-v4.noty_bar .noty_buttons {
    -    padding: 10px; }
    -  .noty_theme__bootstrap-v4.noty_bar .noty_close_button {
    -    font-size: 1.5rem;
    -    font-weight: 700;
    -    line-height: 1;
    -    color: #000;
    -    text-shadow: 0 1px 0 #fff;
    -    filter: alpha(opacity=20);
    -    opacity: .5;
    -    background: transparent; }
    -  .noty_theme__bootstrap-v4.noty_bar .noty_close_button:hover {
    -    background: transparent;
    -    text-decoration: none;
    -    cursor: pointer;
    -    filter: alpha(opacity=50);
    -    opacity: .75; }
    -
    -.noty_theme__bootstrap-v4.noty_type__alert,
    -.noty_theme__bootstrap-v4.noty_type__notification {
    -  background-color: #fff;
    -  color: inherit; }
    -
    -.noty_theme__bootstrap-v4.noty_type__warning {
    -  background-color: #fcf8e3;
    -  color: #8a6d3b;
    -  border-color: #faebcc; }
    -
    -.noty_theme__bootstrap-v4.noty_type__error {
    -  background-color: #f2dede;
    -  color: #a94442;
    -  border-color: #ebccd1; }
    -
    -.noty_theme__bootstrap-v4.noty_type__info,
    -.noty_theme__bootstrap-v4.noty_type__information {
    -  background-color: #d9edf7;
    -  color: #31708f;
    -  border-color: #bce8f1; }
    -
    -.noty_theme__bootstrap-v4.noty_type__success {
    -  background-color: #dff0d8;
    -  color: #3c763d;
    -  border-color: #d6e9c6; }
    -
    -.noty_theme__semanticui.noty_bar {
    -  margin: 4px 0;
    -  overflow: hidden;
    -  position: relative;
    -  border: 1px solid transparent;
    -  font-size: 1em;
    -  border-radius: .28571429rem;
    -  box-shadow: 0 0 0 1px rgba(34, 36, 38, 0.22) inset, 0 0 0 0 transparent; }
    -  .noty_theme__semanticui.noty_bar .noty_body {
    -    padding: 1em 1.5em;
    -    line-height: 1.4285em; }
    -  .noty_theme__semanticui.noty_bar .noty_buttons {
    -    padding: 10px; }
    -
    -.noty_theme__semanticui.noty_type__alert,
    -.noty_theme__semanticui.noty_type__notification {
    -  background-color: #f8f8f9;
    -  color: rgba(0, 0, 0, 0.87); }
    -
    -.noty_theme__semanticui.noty_type__warning {
    -  background-color: #fffaf3;
    -  color: #573a08;
    -  box-shadow: 0 0 0 1px #c9ba9b inset, 0 0 0 0 transparent; }
    -
    -.noty_theme__semanticui.noty_type__error {
    -  background-color: #fff6f6;
    -  color: #9f3a38;
    -  box-shadow: 0 0 0 1px #e0b4b4 inset, 0 0 0 0 transparent; }
    -
    -.noty_theme__semanticui.noty_type__info,
    -.noty_theme__semanticui.noty_type__information {
    -  background-color: #f8ffff;
    -  color: #276f86;
    -  box-shadow: 0 0 0 1px #a9d5de inset, 0 0 0 0 transparent; }
    -
    -.noty_theme__semanticui.noty_type__success {
    -  background-color: #fcfff5;
    -  color: #2c662d;
    -  box-shadow: 0 0 0 1px #a3c293 inset, 0 0 0 0 transparent; }
    -
    -.noty_theme__nest.noty_bar {
    -  margin: 0 0 15px 0;
    -  overflow: hidden;
    -  border-radius: 2px;
    -  position: relative;
    -  box-shadow: rgba(0, 0, 0, 0.098039) 5px 4px 10px 0; }
    -  .noty_theme__nest.noty_bar .noty_body {
    -    padding: 10px;
    -    font-size: 14px;
    -    text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1); }
    -  .noty_theme__nest.noty_bar .noty_buttons {
    -    padding: 10px; }
    -
    -.noty_layout .noty_theme__nest.noty_bar {
    -  z-index: 5; }
    -
    -.noty_layout .noty_theme__nest.noty_bar:nth-child(2) {
    -  position: absolute;
    -  top: 0;
    -  margin-top: 4px;
    -  margin-right: -4px;
    -  margin-left: 4px;
    -  z-index: 4;
    -  width: 100%; }
    -
    -.noty_layout .noty_theme__nest.noty_bar:nth-child(3) {
    -  position: absolute;
    -  top: 0;
    -  margin-top: 8px;
    -  margin-right: -8px;
    -  margin-left: 8px;
    -  z-index: 3;
    -  width: 100%; }
    -
    -.noty_layout .noty_theme__nest.noty_bar:nth-child(4) {
    -  position: absolute;
    -  top: 0;
    -  margin-top: 12px;
    -  margin-right: -12px;
    -  margin-left: 12px;
    -  z-index: 2;
    -  width: 100%; }
    -
    -.noty_layout .noty_theme__nest.noty_bar:nth-child(5) {
    -  position: absolute;
    -  top: 0;
    -  margin-top: 16px;
    -  margin-right: -16px;
    -  margin-left: 16px;
    -  z-index: 1;
    -  width: 100%; }
    -
    -.noty_layout .noty_theme__nest.noty_bar:nth-child(n+6) {
    -  position: absolute;
    -  top: 0;
    -  margin-top: 20px;
    -  margin-right: -20px;
    -  margin-left: 20px;
    -  z-index: -1;
    -  width: 100%; }
    -
    -#noty_layout__bottomLeft .noty_theme__nest.noty_bar:nth-child(2),
    -#noty_layout__topLeft .noty_theme__nest.noty_bar:nth-child(2) {
    -  margin-top: 4px;
    -  margin-left: -4px;
    -  margin-right: 4px; }
    -
    -#noty_layout__bottomLeft .noty_theme__nest.noty_bar:nth-child(3),
    -#noty_layout__topLeft .noty_theme__nest.noty_bar:nth-child(3) {
    -  margin-top: 8px;
    -  margin-left: -8px;
    -  margin-right: 8px; }
    -
    -#noty_layout__bottomLeft .noty_theme__nest.noty_bar:nth-child(4),
    -#noty_layout__topLeft .noty_theme__nest.noty_bar:nth-child(4) {
    -  margin-top: 12px;
    -  margin-left: -12px;
    -  margin-right: 12px; }
    -
    -#noty_layout__bottomLeft .noty_theme__nest.noty_bar:nth-child(5),
    -#noty_layout__topLeft .noty_theme__nest.noty_bar:nth-child(5) {
    -  margin-top: 16px;
    -  margin-left: -16px;
    -  margin-right: 16px; }
    -
    -#noty_layout__bottomLeft .noty_theme__nest.noty_bar:nth-child(n+6),
    -#noty_layout__topLeft .noty_theme__nest.noty_bar:nth-child(n+6) {
    -  margin-top: 20px;
    -  margin-left: -20px;
    -  margin-right: 20px; }
    -
    -.noty_theme__nest.noty_type__alert,
    -.noty_theme__nest.noty_type__notification {
    -  background-color: #073B4C;
    -  color: #fff; }
    -  .noty_theme__nest.noty_type__alert .noty_progressbar,
    -  .noty_theme__nest.noty_type__notification .noty_progressbar {
    -    background-color: #fff; }
    -
    -.noty_theme__nest.noty_type__warning {
    -  background-color: #FFD166;
    -  color: #fff; }
    -
    -.noty_theme__nest.noty_type__error {
    -  background-color: #EF476F;
    -  color: #fff; }
    -  .noty_theme__nest.noty_type__error .noty_progressbar {
    -    opacity: .4; }
    -
    -.noty_theme__nest.noty_type__info,
    -.noty_theme__nest.noty_type__information {
    -  background-color: #118AB2;
    -  color: #fff; }
    -  .noty_theme__nest.noty_type__info .noty_progressbar,
    -  .noty_theme__nest.noty_type__information .noty_progressbar {
    -    opacity: .6; }
    -
    -.noty_theme__nest.noty_type__success {
    -  background-color: #06D6A0;
    -  color: #fff; }
    -
    -/*# sourceMappingURL=noty.css.map*/
    \ No newline at end of file
    diff --git a/data/web/edit.php b/data/web/edit.php
    index 3f3311d0..1532d06b 100644
    --- a/data/web/edit.php
    +++ b/data/web/edit.php
    @@ -26,6 +26,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     					<h4><?=$lang['edit']['alias'];?></h4>
     					<br />
     					<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    +          <input type="hidden" value="0" name="active">
     					<input type="hidden" name="address" value="<?=htmlspecialchars($alias);?>">
     						<div class="form-group">
     							<label class="control-label col-sm-2" for="goto"><?=$lang['edit']['target_address'];?></label>
    @@ -36,7 +37,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     						<div class="form-group">
     							<div class="col-sm-offset-2 col-sm-10">
     								<div class="checkbox">
    -								<label><input type="checkbox" name="active" <?php if (isset($result['active_int']) && $result['active_int']=="1") { echo "checked"; }; ?>> <?=$lang['edit']['active'];?></label>
    +								<label><input type="checkbox" value="1" name="active" <?php if (isset($result['active_int']) && $result['active_int']=="1") { echo "checked"; }; ?>> <?=$lang['edit']['active'];?></label>
     								</div>
     							</div>
     						</div>
    @@ -66,6 +67,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     				<h4><?=$lang['edit']['domain_admin'];?></h4>
     				<br />
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    +        <input type="hidden" value="0" name="active">
     				<input type="hidden" name="username_now" value="<?=htmlspecialchars($domain_admin);?>">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="username"><?=$lang['edit']['username'];?></label>
    @@ -107,14 +109,14 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="active" <?php if (isset($result['active_int']) && $result['active_int']=="1") { echo "checked"; }; ?>> <?=$lang['edit']['active'];?></label>
    +							<label><input type="checkbox" value="1" name="active" <?php if (isset($result['active_int']) && $result['active_int']=="1") { echo "checked"; }; ?>> <?=$lang['edit']['active'];?></label>
     							</div>
     						</div>
     					</div>
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="disable_tfa"> <?=$lang['tfa']['disable_tfa'];?></label>
    +							<label><input type="checkbox" value="1" name="disable_tfa"> <?=$lang['tfa']['disable_tfa'];?></label>
     							</div>
     						</div>
     					</div>
    @@ -141,6 +143,9 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     			?>
     				<h4><?=$lang['edit']['domain'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    +        <input type="hidden" value="0" name="active">
    +        <input type="hidden" value="0" name="backupmx">
    +        <input type="hidden" value="0" name="relay_all_recipients">
     				<input type="hidden" name="domain" value="<?=htmlspecialchars($domain);?>">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="description"><?=$lang['edit']['description'];?></label>
    @@ -179,9 +184,9 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     						<label class="control-label col-sm-2"><?=$lang['edit']['backup_mx_options'];?></label>
     						<div class="col-sm-10">
     							<div class="checkbox">
    -								<label><input type="checkbox" name="backupmx" <?=(isset($result['backupmx_int']) && $result['backupmx_int']=="1") ? "checked" : null;?>> <?=$lang['edit']['relay_domain'];?></label>
    +								<label><input type="checkbox" value="1" name="backupmx" <?=(isset($result['backupmx_int']) && $result['backupmx_int']=="1") ? "checked" : null;?>> <?=$lang['edit']['relay_domain'];?></label>
     								<br />
    -								<label><input type="checkbox" name="relay_all_recipients" <?=(isset($result['relay_all_recipients_int']) && $result['relay_all_recipients_int']=="1") ? "checked" : null;?>> <?=$lang['edit']['relay_all'];?></label>
    +								<label><input type="checkbox" value="1" name="relay_all_recipients" <?=(isset($result['relay_all_recipients_int']) && $result['relay_all_recipients_int']=="1") ? "checked" : null;?>> <?=$lang['edit']['relay_all'];?></label>
     								<p><?=$lang['edit']['relay_all_info'];?></p>
     							</div>
     						</div>
    @@ -192,7 +197,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -								<label><input type="checkbox" name="active" <?=(isset($result['active_int']) && $result['active_int']=="1") ? "checked" : null;?> <?=($_SESSION['mailcow_cc_role'] == "admin") ? null : "disabled";?>> <?=$lang['edit']['active'];?></label>
    +								<label><input type="checkbox" value="1" name="active" <?=(isset($result['active_int']) && $result['active_int']=="1") ? "checked" : null;?> <?=($_SESSION['mailcow_cc_role'] == "admin") ? null : "disabled";?>> <?=$lang['edit']['active'];?></label>
     							</div>
     						</div>
     					</div>
    @@ -350,17 +355,18 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     			?>
     				<h4><?=$lang['edit']['edit_alias_domain'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -					<input type="hidden" name="alias_domain_now" value="<?=htmlspecialchars($alias_domain);?>">
    +          <input type="hidden" value="0" name="active">
    +          <input type="hidden" value="<?=$result['alias_domain'];?>" name="alias_domain">
     					<div class="form-group">
    -						<label class="control-label col-sm-2" for="alias_domain"><?=$lang['edit']['alias_domain'];?></label>
    +						<label class="control-label col-sm-2" for="target_domain"><?=$lang['edit']['target_domain'];?></label>
     						<div class="col-sm-10">
    -							<input type="text" class="form-control" name="alias_domain" id="alias_domain" value="<?=htmlspecialchars($result['alias_domain']);?>">
    +							<input type="text" class="form-control" name="target_domain" id="target_domain" value="<?=htmlspecialchars($result['target_domain']);?>">
     						</div>
     					</div>
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -								<label><input type="checkbox" name="active" <?=(isset($result['active_int']) && $result['active_int']=="1") ?  "checked" : null ?>> <?=$lang['edit']['active'];?></label>
    +								<label><input type="checkbox" value="1" name="active" <?=(isset($result['active_int']) && $result['active_int']=="1") ?  "checked" : null ?>> <?=$lang['edit']['active'];?></label>
     							</div>
     						</div>
     					</div>
    @@ -398,6 +404,8 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
           ?>
           <h4><?=$lang['edit']['mailbox'];?></h4>
           <form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    +      <input type="hidden" value="0" name="sender_acl">
    +      <input type="hidden" value="0" name="active">
           <input type="hidden" name="username" value="<?=htmlspecialchars($result['username']);?>">
             <div class="form-group">
               <label class="control-label col-sm-2" for="name"><?=$lang['edit']['full_name'];?>:</label>
    @@ -481,7 +489,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
             <div class="form-group">
               <div class="col-sm-offset-2 col-sm-10">
                 <div class="checkbox">
    -            <label><input type="checkbox" name="active" <?=($result['active_int']=="1") ? "checked" : null;?>> <?=$lang['edit']['active'];?></label>
    +            <label><input type="checkbox" value="1" name="active" <?=($result['active_int']=="1") ? "checked" : null;?>> <?=$lang['edit']['active'];?></label>
                 </div>
               </div>
             </div>
    @@ -501,6 +509,8 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
             ?>
     				<h4><?=$lang['edit']['resource'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    +          <input type="hidden" value="0" name="active">
    +          <input type="hidden" value="0" name="multiple_bookings">
               <input type="hidden" name="name" value="<?=htmlspecialchars($result['name']);?>">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="description"><?=$lang['add']['description'];?></label>
    @@ -521,14 +531,14 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="active" <?=($result['active_int']=="1") ? "checked" : null;?>> <?=$lang['edit']['active'];?></label>
    +							<label><input type="checkbox" value="1" name="active" <?=($result['active_int']=="1") ? "checked" : null;?>> <?=$lang['edit']['active'];?></label>
     							</div>
     						</div>
     					</div>
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="multiple_bookings" <?=($result['multiple_bookings_int']=="1") ? "checked" : null;?>> <?=$lang['edit']['multiple_bookings'];?></label>
    +							<label><input type="checkbox" value="1" name="multiple_bookings" <?=($result['multiple_bookings_int']=="1") ? "checked" : null;?>> <?=$lang['edit']['multiple_bookings'];?></label>
     							</div>
     						</div>
     					</div>
    @@ -561,6 +571,9 @@ elseif (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] ==
     			?>
     				<h4><?=$lang['edit']['syncjob'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    +        <input type="hidden" value="0" name="delete2duplicates">
    +        <input type="hidden" value="0" name="delete1">
    +        <input type="hidden" value="0" name="active">
     				<input type="hidden" name="id" value="<?=htmlspecialchars($result['id']);?>">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="host1"><?=$lang['edit']['hostname'];?></label>
    @@ -623,21 +636,21 @@ elseif (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] ==
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="delete2duplicates" <?=($result['delete2duplicates']=="1") ? "checked" : "";?>> <?=$lang['edit']['delete2duplicates'];?></label>
    +							<label><input type="checkbox" value="1" name="delete2duplicates" <?=($result['delete2duplicates']=="1") ? "checked" : "";?>> <?=$lang['edit']['delete2duplicates'];?></label>
     							</div>
     						</div>
     					</div>
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="delete1" <?=($result['delete1']=="1") ? "checked" : "";?>> <?=$lang['edit']['delete1'];?></label>
    +							<label><input type="checkbox" value="1" name="delete1" <?=($result['delete1']=="1") ? "checked" : "";?>> <?=$lang['edit']['delete1'];?></label>
     							</div>
     						</div>
     					</div>
     					<div class="form-group">
     						<div class="col-sm-offset-2 col-sm-10">
     							<div class="checkbox">
    -							<label><input type="checkbox" name="active" <?=($result['active']=="1") ? "checked" : "";?>> <?=$lang['edit']['active'];?></label>
    +							<label><input type="checkbox" value="1" name="active" <?=($result['active']=="1") ? "checked" : "";?>> <?=$lang['edit']['active'];?></label>
     							</div>
     						</div>
     					</div>
    diff --git a/data/web/inc/footer.inc.php b/data/web/inc/footer.inc.php
    index 08fd6d00..d809a160 100644
    --- a/data/web/inc/footer.inc.php
    +++ b/data/web/inc/footer.inc.php
    @@ -226,12 +226,15 @@ $(document).ready(function() {
     			}
     		});
     	});
    +
    +  if ($('#mailcow-alert').hasClass('alert-success')) {
    +    $('#mailcow-alert').delay(5000).animate({right: '-50%'}, 1000);
    +  };
     });
     </script>
     
     <div class="container">
       <div id="mailcow-alert" class="alert" role="alert">
    -    <a href="#" class="close" data-dismiss="alert"> &times;</a>
         <span id="mailcow-alert-text"></span>
       </div>
     </div>
    diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php
    index ac99a014..7d1594ad 100644
    --- a/data/web/inc/functions.inc.php
    +++ b/data/web/inc/functions.inc.php
    @@ -733,9 +733,9 @@ function add_policy_list_item($postarray) {
       // If 'delete_prefid' then delete item id
     	global $lang;
     	global $pdo;
    -  (isset($postarray['username'])) ? $object = $postarray['username'] : null;
    -  (isset($postarray['domain']))   ? $object = $postarray['domain'] : null;
    -  (!isset($object))               ? $object = $_SESSION['mailcow_cc_username'] : null;
    +  $object = (isset($postarray['username'])) ? $postarray['username'] : null;
    +  $object = (isset($postarray['domain'])) ? $postarray['domain'] : null;
    +  (!isset($object)) ? $object = $_SESSION['mailcow_cc_username'] : null;
     
       if (is_valid_domain_name($object)) {
     		if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $object)) {
    @@ -826,9 +826,9 @@ function delete_policy_list_item($postarray) {
       // 'delete_prefid' is item to be deleted
     	global $lang;
     	global $pdo;
    -  (isset($postarray['username'])) ? $object = $postarray['username'] : null;
    -  (isset($postarray['domain']))   ? $object = $postarray['domain'] : null;
    -  (!isset($object))               ? $object = $_SESSION['mailcow_cc_username'] : null;
    +  $object = (isset($postarray['username'])) ? $postarray['username'] : null;
    +  $object = (isset($postarray['domain'])) ? $postarray['domain'] : null;
    +  (!isset($object)) ? $object = $_SESSION['mailcow_cc_username'] : null;
     
       if (is_valid_domain_name($object)) {
     		if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $object)) {
    @@ -1010,9 +1010,10 @@ function add_syncjob($postarray) {
       else {
         $username = $_SESSION['mailcow_cc_username'];
       }
    -  isset($postarray['active']) ? $active = '1' : $active = '0';
    -  isset($postarray['delete2duplicates']) ? $delete2duplicates = '1' : $delete2duplicates = '0';
    -  isset($postarray['delete1']) ? $delete1 = '1' : $delete1 = '0';
    +
    +	$active  = intval($postarray['active']);
    +	$delete2duplicates = intval($postarray['delete2duplicates']);
    +	$delete1  = intval($postarray['delete1']);
       $port1            = $postarray['port1'];
       $host1            = $postarray['host1'];
       $password1        = $postarray['password1'];
    @@ -1137,9 +1138,10 @@ function edit_syncjob($postarray) {
       else {
         $username = $_SESSION['mailcow_cc_username'];
       }
    -  isset($postarray['active']) ? $active = '1' : $active = '0';
    -  isset($postarray['delete2duplicates']) ? $delete2duplicates = '1' : $delete2duplicates = '0';
    -  isset($postarray['delete1']) ? $delete1 = '1' : $delete1 = '0';
    +  
    +	$active           = intval($postarray['active']);
    +	$delete2duplicates = intval($postarray['delete2duplicates']);
    +	$delete1          = intval($postarray['delete1']);
       $id               = $postarray['id'];
       $port1            = $postarray['port1'];
       $host1            = $postarray['host1'];
    @@ -1263,8 +1265,8 @@ function edit_tls_policy($postarray) {
       else {
         $username = $_SESSION['mailcow_cc_username'];
       }
    -	isset($postarray['tls_in']) ? $tls_in = '1' : $tls_in = '0';
    -	isset($postarray['tls_out']) ? $tls_out = '1' : $tls_out = '0';
    +  $tls_out = intval($postarray['tls_out']);
    +  $tls_in = intval($postarray['tls_in']);
     	$username = $_SESSION['mailcow_cc_username'];
     	if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
     		$_SESSION['return'] = array(
    @@ -1480,7 +1482,8 @@ function add_domain_admin($postarray) {
     	$username		= strtolower(trim($postarray['username']));
     	$password		= $postarray['password'];
     	$password2  = $postarray['password2'];
    -	isset($postarray['active']) ? $active = '1' : $active = '0';
    +  $active  = intval($postarray['active']);
    +
     	if ($_SESSION['mailcow_cc_role'] != "admin") {
     		$_SESSION['return'] = array(
     			'type' => 'danger',
    @@ -1793,7 +1796,7 @@ function set_tfa($postarray) {
       
     	switch ($postarray["tfa_method"]) {
     		case "yubi_otp":
    -      (!isset($postarray["key_id"])) ? $key_id = 'unidentified' : $key_id = $postarray["key_id"];
    +      $key_id = (!isset($postarray["key_id"])) ? 'unidentified' : $postarray["key_id"];
           $yubico_id = $postarray['yubico_id'];
           $yubico_key = $postarray['yubico_key'];
           $yubi = new Auth_Yubico($yubico_id, $yubico_key);
    @@ -1845,8 +1848,8 @@ function set_tfa($postarray) {
     		break;
     
     		case "u2f":
    +      $key_id = (!isset($postarray["key_id"])) ? 'unidentified' : $postarray["key_id"];
           try {
    -        (!isset($postarray["key_id"])) ? $key_id = 'unidentified' : $key_id = $postarray["key_id"];
             $reg = $u2f->doRegister(json_decode($_SESSION['regReq']), json_decode($postarray['token']));
             $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `authmech` != 'u2f'");
     				$stmt->execute(array(':username' => $username));
    @@ -1869,7 +1872,7 @@ function set_tfa($postarray) {
     		break;
     
     		case "totp":
    -      (!isset($postarray["key_id"])) ? $key_id = 'unidentified' : $key_id = $postarray["key_id"];
    +      $key_id = (!isset($postarray["key_id"])) ? 'unidentified' : $postarray["key_id"];
           if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
             try {
             $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
    @@ -2139,7 +2142,7 @@ function edit_domain_admin($postarray) {
         $username_now = $postarray['username_now'];
         $password     = $postarray['password'];
         $password2    = $postarray['password2'];
    -    isset($postarray['active']) ? $active = '1' : $active = '0';
    +    $active       = intval($postarray['active']);
     
         if(isset($postarray['domain'])) {
           foreach ($postarray['domain'] as $domain) {
    @@ -2520,11 +2523,10 @@ function dkim_delete_key($postarray) {
           return false;
         }
         try {
    -      foreach ($redis->hGetAll('DKIM_SELECTORS') as $domain_name => $selector) {
    -        $redis->hDel('DKIM_PUB_KEYS', $domain_name);
    -        $redis->hDel('DKIM_PRIV_KEYS', $selector . '.' . $domain_name);
    -        $redis->hDel('DKIM_SELECTORS', $domain_name);
    -      }
    +      $selector = $redis->hGet('DKIM_SELECTORS', $domain);
    +      $redis->hDel('DKIM_PUB_KEYS', $domain);
    +      $redis->hDel('DKIM_PRIV_KEYS', $selector . '.' . $domain);
    +      $redis->hDel('DKIM_SELECTORS', $selector);
         }
         catch (RedisException $e) {
           $_SESSION['return'] = array(
    @@ -2536,7 +2538,7 @@ function dkim_delete_key($postarray) {
       }
       $_SESSION['return'] = array(
         'type' => 'success',
    -    'msg' => sprintf($lang['success']['dkim_removed'])
    +    'msg' => sprintf($lang['success']['dkim_removed'], htmlspecialchars(implode(', ', $domains)))
       );
       return true;
     }
    @@ -2584,10 +2586,10 @@ function mailbox_add_domain($postarray) {
     		return false;
     	}
     
    -	isset($postarray['active'])               ? $active = '1'                 : $active = '0';
    -	isset($postarray['relay_all_recipients'])	? $relay_all_recipients = '1'   : $relay_all_recipients = '0';
    -	isset($postarray['backupmx'])             ? $backupmx = '1'               : $backupmx = '0';
    -	isset($postarray['relay_all_recipients']) ? $backupmx = '1'               : true;
    +  $active = intval($postarray['active']);
    +  $relay_all_recipients = intval($postarray['relay_all_recipients']);
    +  $backupmx = intval($postarray['backupmx']);
    +  ($relay_all_recipients == 1) ? $backupmx = '1' : null;
     
     	if (!is_valid_domain_name($domain)) {
     		$_SESSION['return'] = array(
    @@ -2679,7 +2681,7 @@ function mailbox_add_alias($postarray) {
     	global $pdo;
     	$addresses  = array_map('trim', preg_split( "/( |,|;|\n)/", $postarray['address']));
     	$gotos      = array_map('trim', preg_split( "/( |,|;|\n)/", $postarray['goto']));
    -	isset($postarray['active']) ? $active = '1' : $active = '0';
    +  $active = intval($postarray['active']);
     	if (empty($addresses[0])) {
     		$_SESSION['return'] = array(
     			'type' => 'danger',
    @@ -2695,24 +2697,23 @@ function mailbox_add_alias($postarray) {
     		);
     		return false;
     	}
    -
    -  $stmt = $pdo->prepare("SELECT `address` FROM `alias`
    -    WHERE `address`= :address");
    -  $stmt->execute(array(':address' => $address));
    -  $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
    -  if ($num_results != 0) {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['is_alias_or_mailbox'], htmlspecialchars($address))
    -    );
    -    return false;
    -  }
    -
     	foreach ($addresses as $address) {
     		if (empty($address)) {
     			continue;
     		}
     
    +    $stmt = $pdo->prepare("SELECT `address` FROM `alias`
    +      WHERE `address`= :address");
    +    $stmt->execute(array(':address' => $address));
    +    $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
    +    if ($num_results != 0) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['is_alias_or_mailbox'], htmlspecialchars($address))
    +      );
    +      return false;
    +    }
    +
     		$domain       = idn_to_ascii(substr(strstr($address, '@'), 1));
     		$local_part   = strstr($address, '@', true);
     		$address      = $local_part.'@'.$domain;
    @@ -2725,7 +2726,7 @@ function mailbox_add_alias($postarray) {
           );
           return false;
         }
    -      
    +
     		try {
     			$stmt = $pdo->prepare("SELECT `domain` FROM `domain`
     				WHERE `domain`= :domain1 OR `domain` = (SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain2)");
    @@ -2734,7 +2735,7 @@ function mailbox_add_alias($postarray) {
           if ($num_results == 0) {
             $_SESSION['return'] = array(
               'type' => 'danger',
    -          'msg' => sprintf($lang['danger']['domain_not_found'], $domain)
    +          'msg' => sprintf($lang['danger']['domain_not_found'], htmlspecialchars($domain))
             );
             return false;
           }
    @@ -2874,7 +2875,7 @@ function mailbox_add_alias_domain($postarray) {
       // target_domain  string
     	global $lang;
     	global $pdo;
    -	isset($postarray['active']) ? $active = '1' : $active = '0';
    +  $active = intval($postarray['active']);
     	$alias_domain     = idn_to_ascii(strtolower(trim($postarray['alias_domain'])));
     	$target_domain    = idn_to_ascii(strtolower(trim($postarray['target_domain'])));
     
    @@ -3005,7 +3006,7 @@ function mailbox_add_mailbox($postarray) {
     		$name = $local_part;
     	}
     
    -	isset($postarray['active']) ? $active = '1' : $active = '0';
    +  $active = intval($postarray['active']);
     
     	$quota_b		= ($quota_m * 1048576);
     	$maildir		= $domain."/".$local_part."/";
    @@ -3207,8 +3208,8 @@ function mailbox_add_resource($postarray) {
       $local_part         = preg_replace('/[^\da-z]/i', '', preg_quote($description, '/'));
       $name               = $local_part . '@' . $domain;
       $kind               = $postarray['kind'];
    -	isset($postarray['active']) ? $active = '1' : $active = '0';
    -	isset($postarray['multiple_bookings']) ? $multiple_bookings = '1' : $multiple_bookings = '0';
    +  $active = intval($postarray['active']);
    +  $multiple_bookings = intval($postarray['multiple_bookings']);
     
     	if (!filter_var($name, FILTER_VALIDATE_EMAIL)) {
     		$_SESSION['return'] = array(
    @@ -3331,95 +3332,75 @@ function mailbox_add_resource($postarray) {
     	}
     }
     function mailbox_edit_alias_domain($postarray) {
    -  // Array elements
    -  // active             int
    -  // alias_domain_now   string
    -  // alias_domain       string
    +  // active         int
    +  // target_domain  string
    +  // alias_domain   string/array of strings
     	global $lang;
     	global $pdo;
    -	isset($postarray['active']) ? $active = '1' : $active = '0';
    -	$alias_domain       = idn_to_ascii(strtolower(trim($postarray['alias_domain'])));
    -	$alias_domain_now   = strtolower(trim($postarray['alias_domain_now']));
    -	if (!is_valid_domain_name($alias_domain)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['alias_domain_invalid'])
    -		);
    -		return false;
    -	}
    -
    -	if (!is_valid_domain_name($alias_domain_now)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['alias_domain_invalid'])
    -		);
    -		return false;
    -	}
    -
    -	try {
    -		$stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain`
    -				WHERE `alias_domain`= :alias_domain_now");
    -		$stmt->execute(array(':alias_domain_now' => $alias_domain_now));
    -		$DomainData = $stmt->fetch(PDO::FETCH_ASSOC);
    -	}
    -	catch(PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    -	}
    -	if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $DomainData['target_domain'])) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
    -		return false;
    -	}
    -
    -	try {
    -		$stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain`
    -		WHERE `target_domain`= :alias_domain");
    -		$stmt->execute(array(':alias_domain' => $alias_domain));
    -		$num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
    -	}
    -	catch(PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    -	}
    -	if ($num_results != 0) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['aliasd_targetd_identical'])
    -		);
    -		return false;
    -	}
    -
    -	try {
    -		$stmt = $pdo->prepare("UPDATE `alias_domain` SET
    -      `alias_domain` = :alias_domain,
    -      `active` = :active
    -        WHERE `alias_domain` = :alias_domain_now");
    -		$stmt->execute(array(
    -			':alias_domain' => $alias_domain,
    -			':alias_domain_now' => $alias_domain_now,
    -			':active' => $active
    -		));
    -	}
    -	catch (PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    -	}
    -
    +  if (!is_array($postarray['alias_domain'])) {
    +    $alias_domains = array();
    +    $alias_domains[] = $postarray['alias_domain'];
    +  }
    +  else {
    +    $alias_domains = $postarray['alias_domain'];
    +  }
    +  foreach ($alias_domains as $alias_domain) {
    +    $alias_domain = idn_to_ascii(strtolower(trim($alias_domain)));
    +    $is_now = mailbox_get_alias_domain_details($alias_domain);
    +    if (!empty($is_now)) {
    +      $active         = (isset($postarray['active'])) ? $postarray['active'] : $is_now['active_int'];
    +      $target_domain  = (!empty($postarray['target_domain'])) ? idn_to_ascii(strtolower(trim($postarray['target_domain']))) : $is_now['target_domain'];
    +    }
    +    else {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['alias_domain_invalid'])
    +      );
    +      return false;
    +    }
    +    if (!is_valid_domain_name($target_domain)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['target_domain_invalid'])
    +      );
    +      return false;
    +    }
    +    if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $target_domain)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['access_denied'])
    +      );
    +      return false;
    +    }
    +    if (empty(mailbox_get_domain_details($target_domain))) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['target_domain_invalid'])
    +      );
    +      return false;
    +    }
    +    try {
    +      $stmt = $pdo->prepare("UPDATE `alias_domain` SET
    +        `target_domain` = :target_domain,
    +        `active` = :active
    +          WHERE `alias_domain` = :alias_domain");
    +      $stmt->execute(array(
    +        ':alias_domain' => $alias_domain,
    +        ':target_domain' => $target_domain,
    +        ':active' => $active
    +      ));
    +    }
    +    catch (PDOException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'MySQL: '.$e
    +      );
    +      return false;
    +    }
    +  }
     	$_SESSION['return'] = array(
     		'type' => 'success',
    -		'msg' => sprintf($lang['success']['aliasd_modified'], htmlspecialchars($alias_domain))
    +		'msg' => sprintf($lang['success']['aliasd_modified'], htmlspecialchars(implode(', ', $alias_domains)))
     	);
     }
     function mailbox_edit_alias($postarray) {
    @@ -3430,13 +3411,26 @@ function mailbox_edit_alias($postarray) {
     	global $lang;
     	global $pdo;
       if (!is_array($postarray['address'])) {
    -    $address_array = array();
    -    $address_array[] = $postarray['address'];
    +    $addresses = array();
    +    $addresses[] = $postarray['address'];
       }
       else {
    -    $address_array = $postarray['address'];
    +    $addresses = $postarray['address'];
       }
    -	if (isset($postarray['goto']) || !empty($postarray['goto'])) {
    +  foreach ($addresses as $address) {
    +    $is_now = mailbox_get_alias_details($address);
    +    if (!empty($is_now)) {
    +      $active = (isset($postarray['active'])) ? $postarray['active'] : $is_now['active_int'];
    +      $goto   = (!empty($postarray['goto'])) ? $postarray['goto'] : $is_now['goto'];
    +    }
    +    else {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['alias_invalid'])
    +      );
    +      return false;
    +    }
    +    
         $gotos = array_map('trim', preg_split( "/( |,|;|\n)/", $postarray['goto']));
         foreach ($gotos as &$goto) {
           if (empty($goto)) {
    @@ -3459,11 +3453,10 @@ function mailbox_edit_alias($postarray) {
         }
         $gotos = array_filter($gotos);
         $goto = implode(",", $gotos);
    -  }
    -	isset($postarray['active']) ? $active = '1' : $active = '0';
    -  foreach ($address_array as $address) {
    -    $domain       = idn_to_ascii(substr(strstr($address, '@'), 1));
    -    $local_part   = strstr($address, '@', true);
    +    
    +    $domain = idn_to_ascii(substr(strstr($address, '@'), 1));
    +    $local_part = strstr($address, '@', true);
    +
         if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
           $_SESSION['return'] = array(
             'type' => 'danger',
    @@ -3471,6 +3464,7 @@ function mailbox_edit_alias($postarray) {
           );
           return false;
         }
    +
         if ((!filter_var($address, FILTER_VALIDATE_EMAIL) === true) && !empty($local_part)) {
           $_SESSION['return'] = array(
             'type' => 'danger',
    @@ -3478,8 +3472,9 @@ function mailbox_edit_alias($postarray) {
           );
           return false;
         }
    +
         try {
    -      if (isset($goto) && !empty($goto)) {
    +      if (!empty($goto)) {
             $stmt = $pdo->prepare("UPDATE `alias` SET
               `goto` = :goto,
               `active`= :active
    @@ -3510,7 +3505,7 @@ function mailbox_edit_alias($postarray) {
     	}
       $_SESSION['return'] = array(
         'type' => 'success',
    -    'msg' => sprintf($lang['success']['alias_modified'], htmlspecialchars(implode(', ', $address_array)))
    +    'msg' => sprintf($lang['success']['alias_modified'], htmlspecialchars(implode(', ', $addresses)))
       );
     }
     function mailbox_edit_domain($postarray) {
    @@ -3529,68 +3524,220 @@ function mailbox_edit_domain($postarray) {
     	global $lang;
     	global $pdo;
       
    -  $domain       = idn_to_ascii($postarray['domain']);
    -	if (!is_valid_domain_name($domain)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['domain_invalid'])
    -		);
    -		return false;
    -	}
    -
    -	if ($_SESSION['mailcow_cc_role'] == "domainadmin" && 	hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    -    $description  = $postarray['description'];
    -    isset($postarray['active']) ? $active = '1' : $active = '0';
    -    try {
    -      $stmt = $pdo->prepare("UPDATE `domain` SET 
    -      `description` = :description
    -        WHERE `domain` = :domain");
    -      $stmt->execute(array(
    -        ':description' => $description,
    -        ':domain' => $domain
    -      ));
    -      $_SESSION['return'] = array(
    -        'type' => 'success',
    -        'msg' => sprintf($lang['success']['domain_modified'], htmlspecialchars($domain))
    -      );
    -    }
    -    catch (PDOException $e) {
    +  if (!is_array($postarray['domain'])) {
    +    $domains = array();
    +    $domains[] = $postarray['domain'];
    +  }
    +  else {
    +    $domains = $postarray['domain'];
    +  }
    +  foreach ($domains as $domain) {
    +    $domain = idn_to_ascii($domain);
    +    if (!is_valid_domain_name($domain)) {
           $_SESSION['return'] = array(
             'type' => 'danger',
    -        'msg' => 'MySQL: '.$e
    +        'msg' => sprintf($lang['danger']['domain_invalid'])
           );
           return false;
         }
    +    if ($_SESSION['mailcow_cc_role'] == "domainadmin" &&
    +    hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    +      $description  = $postarray['description'];
    +      $active = intval($postarray['active']);
    +      try {
    +        $stmt = $pdo->prepare("UPDATE `domain` SET 
    +        `description` = :description
    +          WHERE `domain` = :domain");
    +        $stmt->execute(array(
    +          ':description' => $description,
    +          ':domain' => $domain
    +        ));
    +        $_SESSION['return'] = array(
    +          'type' => 'success',
    +          'msg' => sprintf($lang['success']['domain_modified'], htmlspecialchars($domain))
    +        );
    +      }
    +      catch (PDOException $e) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => 'MySQL: '.$e
    +        );
    +        return false;
    +      }
    +    }
    +    elseif ($_SESSION['mailcow_cc_role'] == "admin") {
    +      $is_now = mailbox_get_domain_details($domain);
    +      if (!empty($is_now)) {
    +        $active               = (isset($postarray['active'])) ? $postarray['active'] : $is_now['active_int'];
    +        $backupmx             = (isset($postarray['backupmx'])) ? $postarray['backupmx'] : $is_now['backupmx_int'];
    +        $relay_all_recipients = (isset($postarray['relay_all_recipients'])) ? $postarray['relay_all_recipients'] : $is_now['relay_all_recipients_int'];
    +        $aliases              = (!empty($postarray['aliases'])) ? $postarray['aliases'] : $is_now['max_num_aliases_for_domain'];
    +        $mailboxes            = (!empty($postarray['mailboxes'])) ? $postarray['mailboxes'] : $is_now['max_num_mboxes_for_domain'];
    +        $maxquota             = (!empty($postarray['maxquota'])) ? $postarray['maxquota'] : ($is_now['max_new_mailbox_quota'] / 1048576);
    +        $quota                = (!empty($postarray['quota'])) ? $postarray['quota'] : ($is_now['max_quota_for_domain'] / 1048576);
    +        $description          = (!empty($postarray['description'])) ? $postarray['description'] : $is_now['description'];
    +        ($relay_all_recipients == '1') ? $backupmx = '1' : null;
    +      }
    +      else {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => sprintf($lang['danger']['domain_invalid'])
    +        );
    +        return false;
    +      }
    +      try {
    +        // todo: should be using api here
    +        $stmt = $pdo->prepare("SELECT 
    +            COUNT(*) AS count,
    +            MAX(COALESCE(ROUND(`quota`/1048576), 0)) AS `biggest_mailbox`,
    +            COALESCE(ROUND(SUM(`quota`)/1048576), 0) AS `quota_all`
    +              FROM `mailbox`
    +                WHERE `kind` NOT REGEXP 'location|thing|group'
    +                  AND domain = :domain");
    +        $stmt->execute(array(':domain' => $domain));
    +        $MailboxData = $stmt->fetch(PDO::FETCH_ASSOC);
    +        // todo: should be using api here
    +        $stmt = $pdo->prepare("SELECT COUNT(*) AS `count` FROM `alias`
    +            WHERE domain = :domain
    +            AND address NOT IN (
    +              SELECT `username` FROM `mailbox`
    +            )");
    +        $stmt->execute(array(':domain' => $domain));
    +        $AliasData = $stmt->fetch(PDO::FETCH_ASSOC);
    +      }
    +      catch(PDOException $e) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => 'MySQL: '.$e
    +        );
    +        return false;
    +      }
    +
    +      if ($maxquota > $quota) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => sprintf($lang['danger']['mailbox_quota_exceeds_domain_quota'])
    +        );
    +        return false;
    +      }
    +
    +      if ($maxquota == "0" || empty($maxquota)) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => sprintf($lang['danger']['maxquota_empty'])
    +        );
    +        return false;
    +      }
    +
    +      if ($MailboxData['biggest_mailbox'] > $maxquota) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => sprintf($lang['danger']['max_quota_in_use'], $MailboxData['biggest_mailbox'])
    +        );
    +        return false;
    +      }
    +
    +      if ($MailboxData['quota_all'] > $quota) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => sprintf($lang['danger']['domain_quota_m_in_use'], $MailboxData['quota_all'])
    +        );
    +        return false;
    +      }
    +
    +      if ($MailboxData['count'] > $mailboxes) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => sprintf($lang['danger']['mailboxes_in_use'], $MailboxData['count'])
    +        );
    +        return false;
    +      }
    +
    +      if ($AliasData['count'] > $aliases) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => sprintf($lang['danger']['aliases_in_use'], $AliasData['count'])
    +        );
    +        return false;
    +      }
    +      try {
    +        $stmt = $pdo->prepare("UPDATE `domain` SET 
    +        `relay_all_recipients` = :relay_all_recipients,
    +        `backupmx` = :backupmx,
    +        `active` = :active,
    +        `quota` = :quota,
    +        `maxquota` = :maxquota,
    +        `mailboxes` = :mailboxes,
    +        `aliases` = :aliases,
    +        `description` = :description
    +          WHERE `domain` = :domain");
    +        $stmt->execute(array(
    +          ':relay_all_recipients' => $relay_all_recipients,
    +          ':backupmx' => $backupmx,
    +          ':active' => $active,
    +          ':quota' => $quota,
    +          ':maxquota' => $maxquota,
    +          ':mailboxes' => $mailboxes,
    +          ':aliases' => $aliases,
    +          ':description' => $description,
    +          ':domain' => $domain
    +        ));
    +        $_SESSION['return'] = array(
    +          'type' => 'success',
    +          'msg' => sprintf($lang['success']['domain_modified'], htmlspecialchars($domain))
    +        );
    +      }
    +      catch (PDOException $e) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => 'MySQL: '.$e
    +        );
    +        return false;
    +      }
    +    }
       }
    -  elseif ($_SESSION['mailcow_cc_role'] == "admin") {
    -    $description  = $postarray['description'];
    -    isset($postarray['active']) ? $active = '1' : $active = '0';
    -    $aliases		= filter_var($postarray['aliases'], FILTER_SANITIZE_NUMBER_FLOAT);
    -    $mailboxes  = filter_var($postarray['mailboxes'], FILTER_SANITIZE_NUMBER_FLOAT);
    -    $maxquota		= filter_var($postarray['maxquota'], FILTER_SANITIZE_NUMBER_FLOAT);
    -    $quota			= filter_var($postarray['quota'], FILTER_SANITIZE_NUMBER_FLOAT);
    -    isset($postarray['relay_all_recipients']) ? $relay_all_recipients = '1' : $relay_all_recipients = '0';
    -    isset($postarray['backupmx']) ? $backupmx = '1' : $backupmx = '0';
    -    isset($postarray['relay_all_recipients']) ? $backupmx = '1' : true;
    +}
    +function mailbox_edit_mailbox($postarray) {
    +	global $lang;
    +	global $pdo;
    +  if (!is_array($postarray['username'])) {
    +    $usernames = array();
    +    $usernames[] = $postarray['username'];
    +  }
    +  else {
    +    $usernames = $postarray['username'];
    +  }
    +  foreach ($usernames as $username) {
    +    if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['username_invalid'])
    +      );
    +      return false;
    +    }
    +    $is_now = mailbox_get_mailbox_details($username);
    +    if (!empty($is_now)) {
    +      $active     = (isset($postarray['active'])) ? $postarray['active'] : $is_now['active_int'];
    +      $name       = (!empty($postarray['name'])) ? $postarray['name'] : $is_now['name'];
    +      $domain     = $is_now['domain'];
    +      $quota_m    = (!empty($postarray['quota'])) ? $postarray['quota'] : ($is_now['quota'] / 1048576);
    +      $quota_b    = $quota_m * 1048576;
    +      $password   = (!empty($postarray['password'])) ? $postarray['password'] : null;
    +      $password2  = (!empty($postarray['password2'])) ? $postarray['password2'] : null; 
    +    }
    +    else {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['access_denied'])
    +      );
    +      return false;
    +    }
         try {
    -      // GET MAILBOX DATA
    -      $stmt = $pdo->prepare("SELECT 
    -          COUNT(*) AS count,
    -          MAX(COALESCE(ROUND(`quota`/1048576), 0)) AS `maxquota`,
    -          COALESCE(ROUND(SUM(`quota`)/1048576), 0) AS `quota`
    -            FROM `mailbox`
    -              WHERE `kind` NOT REGEXP 'location|thing|group'
    -                AND domain = :domain");
    +      $stmt = $pdo->prepare("SELECT `quota`, `maxquota`
    +        FROM `domain`
    +          WHERE `domain` = :domain");
           $stmt->execute(array(':domain' => $domain));
    -      $MailboxData = $stmt->fetch(PDO::FETCH_ASSOC);
    -      // GET ALIAS DATA
    -      $stmt = $pdo->prepare("SELECT COUNT(*) AS `count` FROM `alias`
    -          WHERE domain = :domain
    -          AND address NOT IN (
    -            SELECT `username` FROM `mailbox`
    -          )");
    -      $stmt->execute(array(':domain' => $domain));
    -      $AliasData = $stmt->fetch(PDO::FETCH_ASSOC);
    +      $DomainData = $stmt->fetch(PDO::FETCH_ASSOC);
         }
         catch(PDOException $e) {
           $_SESSION['return'] = array(
    @@ -3600,79 +3747,195 @@ function mailbox_edit_domain($postarray) {
           return false;
         }
     
    -    if ($maxquota > $quota) {
    +    if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
           $_SESSION['return'] = array(
             'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['mailbox_quota_exceeds_domain_quota'])
    +        'msg' => sprintf($lang['danger']['access_denied'])
    +      );
    +      return false;
    +    }
    +    if (!is_numeric($quota_m) || $quota_m == "0") {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['quota_not_0_not_numeric'], htmlspecialchars($quota_m))
    +      );
    +      return false;
    +    }
    +    if ($quota_m > $DomainData['maxquota']) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['mailbox_quota_exceeded'], $DomainData['maxquota'])
    +      );
    +      return false;
    +    }
    +    if (((($is_now['quota_used'] / 1048576) - $quota_m) + $quota_m) > $DomainData['quota']) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['mailbox_quota_left_exceeded'], ($is_now['max_new_quota'] / 1048576))
           );
           return false;
         }
     
    -    if ($maxquota == "0" || empty($maxquota)) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['maxquota_empty'])
    +    if (isset($postarray['sender_acl'])) {
    +      // Get sender_acl items set by admin
    +      $sender_acl_admin = array_merge(
    +        mailbox_get_sender_acl_handles($username)['sender_acl_domains']['ro'],
    +        mailbox_get_sender_acl_handles($username)['sender_acl_addresses']['ro']
           );
    -      return false;
    -    }
     
    -    if ($MailboxData['maxquota'] > $maxquota) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['max_quota_in_use'], $MailboxData['maxquota'])
    -      );
    -      return false;
    -    }
    +      // Get sender_acl items from POST array
    +      $sender_acl_domain_admin = ($postarray['sender_acl'] == "0") ? array() : $postarray['sender_acl'];
     
    -    if ($MailboxData['quota'] > $quota) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['domain_quota_m_in_use'], $MailboxData['quota'])
    -      );
    -      return false;
    -    }
    +      if (!empty($sender_acl_domain_admin) || !empty($sender_acl_admin)) {
    +        // Check items in POST array
    +        foreach ($sender_acl_domain_admin as $sender_acl) {
    +          if (!filter_var($sender_acl, FILTER_VALIDATE_EMAIL) && !is_valid_domain_name(ltrim($sender_acl, '@'))) {
    +              $_SESSION['return'] = array(
    +                'type' => 'danger',
    +                'msg' => sprintf($lang['danger']['sender_acl_invalid'])
    +              );
    +              return false;
    +          }
    +          if (is_valid_domain_name(ltrim($sender_acl, '@'))) {
    +            if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], ltrim($sender_acl, '@'))) {
    +              $_SESSION['return'] = array(
    +                'type' => 'danger',
    +                'msg' => sprintf($lang['danger']['sender_acl_invalid'])
    +              );
    +              return false;
    +            }
    +          }
    +          if (filter_var($sender_acl, FILTER_VALIDATE_EMAIL)) {
    +            if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $sender_acl)) {
    +              $_SESSION['return'] = array(
    +                'type' => 'danger',
    +                'msg' => sprintf($lang['danger']['sender_acl_invalid'])
    +              );
    +              return false;
    +            }
    +          }
    +        }
     
    -    if ($MailboxData['count'] > $mailboxes) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['mailboxes_in_use'], $MailboxData['count'])
    -      );
    -      return false;
    -    }
    +        // Merge both arrays
    +        $sender_acl_merged = array_merge($sender_acl_domain_admin, $sender_acl_admin);
     
    -    if ($AliasData['count'] > $aliases) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['aliases_in_use'], $AliasData['count'])
    -      );
    -      return false;
    +        try {
    +          $stmt = $pdo->prepare("DELETE FROM `sender_acl` WHERE `logged_in_as` = :username");
    +          $stmt->execute(array(
    +            ':username' => $username
    +          ));
    +        }
    +        catch (PDOException $e) {
    +          $_SESSION['return'] = array(
    +            'type' => 'danger',
    +            'msg' => 'MySQL: '.$e
    +          );
    +          return false;
    +        }
    +
    +        foreach ($sender_acl_merged as $sender_acl) {
    +          $domain = ltrim($sender_acl, '@');
    +          if (is_valid_domain_name($domain)) {
    +            $sender_acl = '@' . $domain;
    +          }
    +          try {
    +            $stmt = $pdo->prepare("INSERT INTO `sender_acl` (`send_as`, `logged_in_as`)
    +              VALUES (:sender_acl, :username)");
    +            $stmt->execute(array(
    +              ':sender_acl' => $sender_acl,
    +              ':username' => $username
    +            ));
    +          }
    +          catch (PDOException $e) {
    +            $_SESSION['return'] = array(
    +              'type' => 'danger',
    +              'msg' => 'MySQL: '.$e
    +            );
    +            return false;
    +          }
    +        }
    +      }
    +      else {
    +        try {
    +          $stmt = $pdo->prepare("DELETE FROM `sender_acl` WHERE `logged_in_as` = :username");
    +          $stmt->execute(array(
    +            ':username' => $username
    +          ));
    +        }
    +        catch (PDOException $e) {
    +          $_SESSION['return'] = array(
    +            'type' => 'danger',
    +            'msg' => 'MySQL: '.$e
    +          );
    +          return false;
    +        }
    +      }
    +    }
    +    if (!empty($password) && !empty($password2)) {
    +      if (!preg_match('/' . $GLOBALS['PASSWD_REGEP'] . '/', $password)) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => sprintf($lang['danger']['password_complexity'])
    +        );
    +        return false;
    +      }
    +      if ($password != $password2) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => sprintf($lang['danger']['password_mismatch'])
    +        );
    +        return false;
    +      }
    +      $password_hashed = hash_password($password);
    +      try {
    +        $stmt = $pdo->prepare("UPDATE `alias` SET
    +            `active` = :active
    +              WHERE `address` = :address");
    +        $stmt->execute(array(
    +          ':address' => $username,
    +          ':active' => $active
    +        ));
    +        $stmt = $pdo->prepare("UPDATE `mailbox` SET
    +            `active` = :active,
    +            `password` = :password_hashed,
    +            `name`= :name,
    +            `quota` = :quota_b
    +              WHERE `username` = :username");
    +        $stmt->execute(array(
    +          ':password_hashed' => $password_hashed,
    +          ':active' => $active,
    +          ':name' => $name,
    +          ':quota_b' => $quota_b,
    +          ':username' => $username
    +        ));
    +      }
    +      catch (PDOException $e) {
    +        $_SESSION['return'] = array(
    +          'type' => 'danger',
    +          'msg' => 'MySQL: '.$e
    +        );
    +        return false;
    +      }
         }
         try {
    -      $stmt = $pdo->prepare("UPDATE `domain` SET 
    -      `relay_all_recipients` = :relay_all_recipients,
    -      `backupmx` = :backupmx,
    -      `active` = :active,
    -      `quota` = :quota,
    -      `maxquota` = :maxquota,
    -      `mailboxes` = :mailboxes,
    -      `aliases` = :aliases,
    -      `description` = :description
    -        WHERE `domain` = :domain");
    +      $stmt = $pdo->prepare("UPDATE `alias` SET
    +          `active` = :active
    +            WHERE `address` = :address");
    +      $stmt->execute(array(
    +        ':address' => $username,
    +        ':active' => $active
    +      ));
    +      $stmt = $pdo->prepare("UPDATE `mailbox` SET
    +          `active` = :active,
    +          `name`= :name,
    +          `quota` = :quota_b
    +            WHERE `username` = :username");
           $stmt->execute(array(
    -        ':relay_all_recipients' => $relay_all_recipients,
    -        ':backupmx' => $backupmx,
             ':active' => $active,
    -        ':quota' => $quota,
    -        ':maxquota' => $maxquota,
    -        ':mailboxes' => $mailboxes,
    -        ':aliases' => $aliases,
    -        ':description' => $description,
    -        ':domain' => $domain
    +        ':name' => $name,
    +        ':quota_b' => $quota_b,
    +        ':username' => $username
           ));
    -      $_SESSION['return'] = array(
    -        'type' => 'success',
    -        'msg' => sprintf($lang['success']['domain_modified'], htmlspecialchars($domain))
    -      );
         }
         catch (PDOException $e) {
           $_SESSION['return'] = array(
    @@ -3682,336 +3945,99 @@ function mailbox_edit_domain($postarray) {
           return false;
         }
       }
    -}
    -function mailbox_edit_mailbox($postarray) {
    -	global $lang;
    -	global $pdo;
    -	isset($postarray['active']) ? $active = '1' : $active = '0';
    -	if (!filter_var($postarray['username'], FILTER_VALIDATE_EMAIL)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['username_invalid'])
    -		);
    -		return false;
    -	}
    -	$quota_m      = intval($postarray['quota']);
    -	$quota_b      = $quota_m*1048576;
    -	$username     = $postarray['username'];
    -	$name         = $postarray['name'];
    -	$password     = $postarray['password'];
    -	$password2    = $postarray['password2'];
    -
    -	try {
    -		$stmt = $pdo->prepare("SELECT `domain`
    -			FROM `mailbox`
    -				WHERE username = :username");
    -		$stmt->execute(array(':username' => $username));
    -		$MailboxData1 = $stmt->fetch(PDO::FETCH_ASSOC);
    -
    -		$stmt = $pdo->prepare("SELECT 
    -			COALESCE(ROUND(SUM(`quota`)/1048576), 0) as `quota_m_now`
    -				FROM `mailbox`
    -					WHERE `username` = :username");
    -		$stmt->execute(array(':username' => $username));
    -		$MailboxData2 = $stmt->fetch(PDO::FETCH_ASSOC);
    -
    -		$stmt = $pdo->prepare("SELECT 
    -			COALESCE(ROUND(SUM(`quota`)/1048576), 0) as `quota_m_in_use`
    -				FROM `mailbox`
    -					WHERE `domain` = :domain");
    -		$stmt->execute(array(':domain' => $MailboxData1['domain']));
    -		$MailboxData3 = $stmt->fetch(PDO::FETCH_ASSOC);
    -
    -		$stmt = $pdo->prepare("SELECT `quota`, `maxquota`
    -			FROM `domain`
    -				WHERE `domain` = :domain");
    -		$stmt->execute(array(':domain' => $MailboxData1['domain']));
    -		$DomainData = $stmt->fetch(PDO::FETCH_ASSOC);
    -	}
    -	catch(PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    -	}
    -
    -	if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $MailboxData1['domain'])) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
    -		return false;
    -	}
    -	if (!is_numeric($quota_m) || $quota_m == "0") {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['quota_not_0_not_numeric'], htmlspecialchars($quota_m))
    -		);
    -		return false;
    -	}
    -	if ($quota_m > $DomainData['maxquota']) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['mailbox_quota_exceeded'], $DomainData['maxquota'])
    -		);
    -		return false;
    -	}
    -	if (($MailboxData3['quota_m_in_use'] - $MailboxData2['quota_m_now'] + $quota_m) > $DomainData['quota']) {
    -		$quota_left_m = ($DomainData['quota'] - $MailboxData3['quota_m_in_use'] + $MailboxData2['quota_m_now']);
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['mailbox_quota_left_exceeded'], $quota_left_m)
    -		);
    -		return false;
    -	}
    -
    -  // Get sender_acl items set by admin
    -  $sender_acl_admin = array_merge(
    -    mailbox_get_sender_acl_handles($username)['sender_acl_domains']['ro'],
    -    mailbox_get_sender_acl_handles($username)['sender_acl_addresses']['ro']
    +  $_SESSION['return'] = array(
    +    'type' => 'success',
    +    'msg' => sprintf($lang['success']['mailbox_modified'], implode(', ', $usernames))
       );
    -
    -  // Get sender_acl items from POST array
    -  (isset($postarray['sender_acl'])) ? $sender_acl_domain_admin = $postarray['sender_acl'] : $sender_acl_domain_admin = array();
    -
    -	if (!empty($sender_acl_domain_admin) || !empty($sender_acl_admin)) {
    -    // Check items in POST array
    -		foreach ($sender_acl_domain_admin as $sender_acl) {
    -			if (!filter_var($sender_acl, FILTER_VALIDATE_EMAIL) && !is_valid_domain_name(ltrim($sender_acl, '@'))) {
    -					$_SESSION['return'] = array(
    -						'type' => 'danger',
    -						'msg' => sprintf($lang['danger']['sender_acl_invalid'])
    -					);
    -					return false;
    -			}
    -      if (is_valid_domain_name(ltrim($sender_acl, '@'))) {
    -        if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], ltrim($sender_acl, '@'))) {
    -					$_SESSION['return'] = array(
    -						'type' => 'danger',
    -						'msg' => sprintf($lang['danger']['sender_acl_invalid'])
    -					);
    -					return false;
    -        }
    -      }
    -			if (filter_var($sender_acl, FILTER_VALIDATE_EMAIL)) {
    -        if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $sender_acl)) {
    -					$_SESSION['return'] = array(
    -						'type' => 'danger',
    -						'msg' => sprintf($lang['danger']['sender_acl_invalid'])
    -					);
    -					return false;
    -        }
    -      }
    -    }
    -
    -    // Merge both arrays
    -    $sender_acl_merged = array_merge($sender_acl_domain_admin, $sender_acl_admin);
    -
    -    try {
    -      $stmt = $pdo->prepare("DELETE FROM `sender_acl` WHERE `logged_in_as` = :username");
    -      $stmt->execute(array(
    -        ':username' => $username
    -      ));
    -    }
    -    catch (PDOException $e) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => 'MySQL: '.$e
    -      );
    -      return false;
    -    }
    -
    -		foreach ($sender_acl_merged as $sender_acl) {
    -      $domain = ltrim($sender_acl, '@');
    -      if (is_valid_domain_name($domain)) {
    -        $sender_acl = '@' . $domain;
    -      }
    -			try {
    -				$stmt = $pdo->prepare("INSERT INTO `sender_acl` (`send_as`, `logged_in_as`)
    -					VALUES (:sender_acl, :username)");
    -				$stmt->execute(array(
    -					':sender_acl' => $sender_acl,
    -					':username' => $username
    -				));
    -			}
    -			catch (PDOException $e) {
    -				$_SESSION['return'] = array(
    -					'type' => 'danger',
    -					'msg' => 'MySQL: '.$e
    -				);
    -				return false;
    -			}
    -		}
    -	}
    -  else {
    -    try {
    -      $stmt = $pdo->prepare("DELETE FROM `sender_acl` WHERE `logged_in_as` = :username");
    -      $stmt->execute(array(
    -        ':username' => $username
    -      ));
    -    }
    -    catch (PDOException $e) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => 'MySQL: '.$e
    -      );
    -      return false;
    -    }
    -  }
    -	if (!empty($password) && !empty($password2)) {
    -    if (!preg_match('/' . $GLOBALS['PASSWD_REGEP'] . '/', $password)) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['password_complexity'])
    -      );
    -      return false;
    -    }
    -		if ($password != $password2) {
    -			$_SESSION['return'] = array(
    -				'type' => 'danger',
    -				'msg' => sprintf($lang['danger']['password_mismatch'])
    -			);
    -			return false;
    -		}
    -		$password_hashed = hash_password($password);
    -		try {
    -			$stmt = $pdo->prepare("UPDATE `alias` SET
    -					`active` = :active
    -						WHERE `address` = :address");
    -			$stmt->execute(array(
    -				':address' => $username,
    -				':active' => $active
    -			));
    -			$stmt = $pdo->prepare("UPDATE `mailbox` SET
    -					`active` = :active,
    -					`password` = :password_hashed,
    -					`name`= :name,
    -					`quota` = :quota_b
    -						WHERE `username` = :username");
    -			$stmt->execute(array(
    -				':password_hashed' => $password_hashed,
    -				':active' => $active,
    -				':name' => $name,
    -				':quota_b' => $quota_b,
    -				':username' => $username
    -			));
    -			$_SESSION['return'] = array(
    -				'type' => 'success',
    -				'msg' => sprintf($lang['success']['mailbox_modified'], $username)
    -			);
    -			return true;
    -		}
    -		catch (PDOException $e) {
    -			$_SESSION['return'] = array(
    -				'type' => 'danger',
    -				'msg' => 'MySQL: '.$e
    -			);
    -			return false;
    -		}
    -	}
    -	try {
    -		$stmt = $pdo->prepare("UPDATE `alias` SET
    -				`active` = :active
    -					WHERE `address` = :address");
    -		$stmt->execute(array(
    -			':address' => $username,
    -			':active' => $active
    -		));
    -		$stmt = $pdo->prepare("UPDATE `mailbox` SET
    -				`active` = :active,
    -				`name`= :name,
    -				`quota` = :quota_b
    -					WHERE `username` = :username");
    -		$stmt->execute(array(
    -			':active' => $active,
    -			':name' => $name,
    -			':quota_b' => $quota_b,
    -			':username' => $username
    -		));
    -		$_SESSION['return'] = array(
    -			'type' => 'success',
    -			'msg' => sprintf($lang['success']['mailbox_modified'], $username)
    -		);
    -		return true;
    -	}
    -	catch (PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    -	}
    +  return true;
     }
     function mailbox_edit_resource($postarray) {
     	global $lang;
     	global $pdo;
     
    -	isset($postarray['active']) ? $active = '1' : $active = '0';
    -	isset($postarray['multiple_bookings']) ? $multiple_bookings = '1' : $multiple_bookings = '0';
    -	$name               = $postarray['name'];
    -	$kind               = $postarray['kind'];
    -	$description        = $postarray['description'];
    -
    -	if (!filter_var($name, FILTER_VALIDATE_EMAIL)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['resource_invalid'])
    -		);
    -		return false;
    -	}
    -
    -	if (empty($description)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['description_invalid'])
    -		);
    -		return false;
    +  if (!is_array($postarray['name'])) {
    +    $names = array();
    +    $names[] = $postarray['name'];
       }
    -
    -	if ($kind != 'location' && $kind != 'group' && $kind != 'thing') {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['resource_invalid'])
    -		);
    -		return false;
    -	}
    -
    -  if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $name)) {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['access_denied'])
    -    );
    -    return false;
    +  else {
    +    $names = $postarray['name'];
       }
    +  foreach ($names as $name) {
    +    $is_now = mailbox_get_resource_details($name);
    +    if (!empty($is_now)) {
    +      $active             = (isset($postarray['active'])) ? $postarray['active'] : $is_now['active_int'];
    +      $multiple_bookings  = (isset($postarray['multiple_bookings'])) ? $postarray['multiple_bookings'] : $is_now['multiple_bookings_int'];
    +      $description        = (!empty($postarray['description'])) ? $postarray['description'] : $is_now['description'];
    +      $kind               = (!empty($postarray['kind'])) ? $postarray['kind'] : $is_now['kind'];
    +    }
    +    else {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['resource_invalid'])
    +      );
    +      return false;
    +    }
     
    -	try {
    -		$stmt = $pdo->prepare("UPDATE `mailbox` SET
    -				`active` = :active,
    -				`name`= :description,
    -				`kind`= :kind,
    -				`multiple_bookings`= :multiple_bookings
    -          WHERE `username` = :name");
    -		$stmt->execute(array(
    -			':active' => $active,
    -			':description' => $description,
    -			':multiple_bookings' => $multiple_bookings,
    -			':kind' => $kind,
    -			':name' => $name
    -		));
    -		$_SESSION['return'] = array(
    -			'type' => 'success',
    -			'msg' => sprintf($lang['success']['resource_modified'], $name)
    -		);
    -		return true;
    -	}
    -	catch (PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    +    if (!filter_var($name, FILTER_VALIDATE_EMAIL)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['resource_invalid'])
    +      );
    +      return false;
    +    }
    +
    +    if (empty($description)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['description_invalid'])
    +      );
    +      return false;
    +    }
    +
    +    if ($kind != 'location' && $kind != 'group' && $kind != 'thing') {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['resource_invalid'])
    +      );
    +      return false;
    +    }
    +
    +    if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $name)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['access_denied'])
    +      );
    +      return false;
    +    }
    +
    +    try {
    +      $stmt = $pdo->prepare("UPDATE `mailbox` SET
    +          `active` = :active,
    +          `name`= :description,
    +          `kind`= :kind,
    +          `multiple_bookings`= :multiple_bookings
    +            WHERE `username` = :name");
    +      $stmt->execute(array(
    +        ':active' => $active,
    +        ':description' => $description,
    +        ':multiple_bookings' => $multiple_bookings,
    +        ':kind' => $kind,
    +        ':name' => $name
    +      ));
    +    }
    +    catch (PDOException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'MySQL: '.$e
    +      );
    +      return false;
    +    }
     	}
    +  $_SESSION['return'] = array(
    +    'type' => 'success',
    +    'msg' => sprintf($lang['success']['resource_modified'], implode(', ', $names))
    +  );
    +  return true;
     }
     function mailbox_get_mailboxes($domain = null) {
     	global $lang;
    @@ -4564,8 +4590,15 @@ function mailbox_get_resource_details($resource) {
     }
     function mailbox_delete_domain($postarray) {
     	global $lang;
    +	global $redis;
     	global $pdo;
    -	$domain = $postarray['domain'];
    +  if (!is_array($postarray['domain'])) {
    +    $domains = array();
    +    $domains[] = $postarray['domain'];
    +  }
    +  else {
    +    $domains = $postarray['domain'];
    +  }
     	if ($_SESSION['mailcow_cc_role'] != "admin") {
     		$_SESSION['return'] = array(
     			'type' => 'danger',
    @@ -4573,90 +4606,92 @@ function mailbox_delete_domain($postarray) {
     		);
     		return false;
     	}
    -	if (!is_valid_domain_name($domain)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['domain_invalid'])
    -		);
    -		return false;
    -	}
    -	$domain	= idn_to_ascii(strtolower(trim($domain)));
    +  foreach ($domains as $domain) {
    +    if (!is_valid_domain_name($domain)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['domain_invalid'])
    +      );
    +      return false;
    +    }
    +    $domain	= idn_to_ascii(strtolower(trim($domain)));
     
    -	try {
    -		$stmt = $pdo->prepare("SELECT `username` FROM `mailbox`
    -			WHERE `domain` = :domain");
    -		$stmt->execute(array(':domain' => $domain));
    -		$num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
    -	}
    -	catch(PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    -	}
    -	if ($num_results != 0 || !empty($num_results)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['domain_not_empty'])
    -		);
    -		return false;
    -	}
    +    try {
    +      $stmt = $pdo->prepare("SELECT `username` FROM `mailbox`
    +        WHERE `domain` = :domain");
    +      $stmt->execute(array(':domain' => $domain));
    +      $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
    +    }
    +    catch(PDOException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'MySQL: '.$e
    +      );
    +      return false;
    +    }
    +    if ($num_results != 0 || !empty($num_results)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['domain_not_empty'])
    +      );
    +      return false;
    +    }
     
    -	try {
    -		$stmt = $pdo->prepare("DELETE FROM `domain` WHERE `domain` = :domain");
    -		$stmt->execute(array(
    -			':domain' => $domain,
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `domain_admins` WHERE `domain` = :domain");
    -		$stmt->execute(array(
    -			':domain' => $domain,
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `alias` WHERE `domain` = :domain");
    -		$stmt->execute(array(
    -			':domain' => $domain,
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `alias_domain` WHERE `target_domain` = :domain");
    -		$stmt->execute(array(
    -			':domain' => $domain,
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `mailbox` WHERE `domain` = :domain");
    -		$stmt->execute(array(
    -			':domain' => $domain,
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `sender_acl` WHERE `logged_in_as` LIKE :domain");
    -		$stmt->execute(array(
    -			':domain' => '%@'.$domain,
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `quota2` WHERE `username` = :domain");
    -		$stmt->execute(array(
    -			':domain' => '%@'.$domain,
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `spamalias` WHERE `address` = :domain");
    -		$stmt->execute(array(
    -			':domain' => '%@'.$domain,
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `filterconf` WHERE `object` = :domain");
    -		$stmt->execute(array(
    -			':domain' => '%@'.$domain,
    -		));
    -	}
    -	catch (PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    -	}
    -  try {
    -    $redis->hDel('DOMAIN_MAP', $domain);
    -  }
    -  catch (RedisException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'Redis: '.$e
    -		);
    -		return false;
    +    try {
    +      $stmt = $pdo->prepare("DELETE FROM `domain` WHERE `domain` = :domain");
    +      $stmt->execute(array(
    +        ':domain' => $domain,
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `domain_admins` WHERE `domain` = :domain");
    +      $stmt->execute(array(
    +        ':domain' => $domain,
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `alias` WHERE `domain` = :domain");
    +      $stmt->execute(array(
    +        ':domain' => $domain,
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `alias_domain` WHERE `target_domain` = :domain");
    +      $stmt->execute(array(
    +        ':domain' => $domain,
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `mailbox` WHERE `domain` = :domain");
    +      $stmt->execute(array(
    +        ':domain' => $domain,
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sender_acl` WHERE `logged_in_as` LIKE :domain");
    +      $stmt->execute(array(
    +        ':domain' => '%@'.$domain,
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `quota2` WHERE `username` = :domain");
    +      $stmt->execute(array(
    +        ':domain' => '%@'.$domain,
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `spamalias` WHERE `address` = :domain");
    +      $stmt->execute(array(
    +        ':domain' => '%@'.$domain,
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `filterconf` WHERE `object` = :domain");
    +      $stmt->execute(array(
    +        ':domain' => '%@'.$domain,
    +      ));
    +    }
    +    catch (PDOException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'MySQL: '.$e
    +      );
    +      return false;
    +    }
    +    try {
    +      $redis->hDel('DOMAIN_MAP', $domain);
    +    }
    +    catch (RedisException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'Redis: '.$e
    +      );
    +      return false;
    +    }
       }
     	$_SESSION['return'] = array(
     		'type' => 'success',
    @@ -4669,13 +4704,13 @@ function mailbox_delete_alias($postarray) {
     	global $lang;
     	global $pdo;
       if (!is_array($postarray['address'])) {
    -    $address_array = array();
    -    $address_array[] = $postarray['address'];
    +    $addresses = array();
    +    $addresses[] = $postarray['address'];
       }
       else {
    -    $address_array = $postarray['address'];
    +    $addresses = $postarray['address'];
       }
    -  foreach ($address_array as $address) {
    +  foreach ($addresses as $address) {
         $local_part		= strstr($address, '@', true);
         $domain = mailbox_get_alias_details($address)['domain'];
         try {
    @@ -4715,172 +4750,185 @@ function mailbox_delete_alias($postarray) {
       }
     	$_SESSION['return'] = array(
     		'type' => 'success',
    -		'msg' => sprintf($lang['success']['alias_removed'], htmlspecialchars(implode(', ', $address_array)))
    +		'msg' => sprintf($lang['success']['alias_removed'], htmlspecialchars(implode(', ', $addresses)))
     	);
     
     }
     function mailbox_delete_alias_domain($postarray) {
     	global $lang;
     	global $pdo;
    -  $alias_domain = $postarray['alias_domain'];
    -	if (!is_valid_domain_name($postarray['alias_domain'])) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['domain_invalid'])
    -		);
    -		return false;
    -	}
    -	try {
    -		$stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain`
    -			WHERE `alias_domain`= :alias_domain");
    -		$stmt->execute(array(':alias_domain' => $alias_domain));
    -		$DomainData = $stmt->fetch(PDO::FETCH_ASSOC);
    -	}
    -	catch(PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    -	}
    -
    -	if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $DomainData['target_domain'])) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
    -		return false;
    -	}
    -
    -	try {
    -		$stmt = $pdo->prepare("DELETE FROM `alias_domain` WHERE `alias_domain` = :alias_domain");
    -		$stmt->execute(array(
    -			':alias_domain' => $alias_domain,
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `alias` WHERE `domain` = :alias_domain");
    -		$stmt->execute(array(
    -			':alias_domain' => $alias_domain,
    -		));
    -	}
    -	catch (PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    +  if (!is_array($postarray['alias_domain'])) {
    +    $alias_domains = array();
    +    $alias_domains[] = $postarray['alias_domain'];
    +  }
    +  else {
    +    $alias_domains = $postarray['alias_domain'];
    +  }
    +  foreach ($alias_domains as $alias_domain) {
    +    if (!is_valid_domain_name($alias_domain)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['domain_invalid'])
    +      );
    +      return false;
    +    }
    +    try {
    +      $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain`
    +        WHERE `alias_domain`= :alias_domain");
    +      $stmt->execute(array(':alias_domain' => $alias_domain));
    +      $DomainData = $stmt->fetch(PDO::FETCH_ASSOC);
    +    }
    +    catch(PDOException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'MySQL: '.$e
    +      );
    +      return false;
    +    }
    +    if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $DomainData['target_domain'])) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['access_denied'])
    +      );
    +      return false;
    +    }
    +    try {
    +      $stmt = $pdo->prepare("DELETE FROM `alias_domain` WHERE `alias_domain` = :alias_domain");
    +      $stmt->execute(array(
    +        ':alias_domain' => $alias_domain,
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `alias` WHERE `domain` = :alias_domain");
    +      $stmt->execute(array(
    +        ':alias_domain' => $alias_domain,
    +      ));
    +    }
    +    catch (PDOException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'MySQL: '.$e
    +      );
    +      return false;
    +    }
     	}
     	$_SESSION['return'] = array(
     		'type' => 'success',
    -		'msg' => sprintf($lang['success']['alias_domain_removed'], htmlspecialchars($alias_domain))
    +		'msg' => sprintf($lang['success']['alias_domain_removed'], htmlspecialchars(implode(', ', $alias_domains)))
     	);
     }
     function mailbox_delete_mailbox($postarray) {
     	global $lang;
     	global $pdo;
    -	$username	= $postarray['username'];
    +  if (!is_array($postarray['username'])) {
    +    $usernames = array();
    +    $usernames[] = $postarray['username'];
    +  }
    +  else {
    +    $usernames = $postarray['username'];
    +  }
    +  foreach ($usernames as $username) {
    +    if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['access_denied'])
    +      );
    +      return false;
    +    }
     
    -	if (!filter_var($postarray['username'], FILTER_VALIDATE_EMAIL)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
    -		return false;
    -	}
    +    if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['access_denied'])
    +      );
    +      return false;
    +    }
     
    -	if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
    -		return false;
    -	}
    -
    -	try {
    -		$stmt = $pdo->prepare("DELETE FROM `alias` WHERE `goto` = :username");
    -		$stmt->execute(array(
    -			':username' => $username
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `quota2` WHERE `username` = :username");
    -		$stmt->execute(array(
    -			':username' => $username
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `mailbox` WHERE `username` = :username");
    -		$stmt->execute(array(
    -			':username' => $username
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `sender_acl` WHERE `logged_in_as` = :username");
    -		$stmt->execute(array(
    -			':username' => $username
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `spamalias` WHERE `goto` = :username");
    -		$stmt->execute(array(
    -			':username' => $username
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `imapsync` WHERE `user2` = :username");
    -		$stmt->execute(array(
    -			':username' => $username
    -		));
    -		$stmt = $pdo->prepare("DELETE FROM `filterconf` WHERE `object` = :username");
    -		$stmt->execute(array(
    -			':username' => $username
    -		));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_user_profile` WHERE `c_uid` = :username");
    -    $stmt->execute(array(
    -      ':username' => $username
    -    ));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_cache_folder` WHERE `c_uid` = :username");
    -    $stmt->execute(array(
    -      ':username' => $username
    -    ));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_acl` WHERE `c_object` LIKE '%/" . $username . "/%' OR `c_uid` = :username");
    -    $stmt->execute(array(
    -      ':username' => $username
    -    ));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_store` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");
    -    $stmt->execute(array(
    -      ':username' => $username
    -    ));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_quick_contact` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");
    -    $stmt->execute(array(
    -      ':username' => $username
    -    ));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_quick_appointment` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");
    -    $stmt->execute(array(
    -      ':username' => $username
    -    ));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_folder_info` WHERE `c_path2` = :username");
    -    $stmt->execute(array(
    -      ':username' => $username
    -    ));
    -		$stmt = $pdo->prepare("SELECT `address`, `goto` FROM `alias`
    -				WHERE `goto` REGEXP :username");
    -		$stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
    -		$GotoData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    -		foreach ($GotoData as $gotos) {
    -			$goto_exploded = explode(',', $gotos['goto']);
    -			if (($key = array_search($username, $goto_exploded)) !== false) {
    -				unset($goto_exploded[$key]);
    -			}
    -			$gotos_rebuild = implode(',', $goto_exploded);
    -			$stmt = $pdo->prepare("UPDATE `alias` SET
    -        `goto` = :goto
    -          WHERE `address` = :address");
    -			$stmt->execute(array(
    -				':goto' => $gotos_rebuild,
    -				':address' => $gotos['address']
    -			));
    -		}
    -	}
    -	catch (PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    +    try {
    +      $stmt = $pdo->prepare("DELETE FROM `alias` WHERE `goto` = :username");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `quota2` WHERE `username` = :username");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `mailbox` WHERE `username` = :username");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sender_acl` WHERE `logged_in_as` = :username");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `spamalias` WHERE `goto` = :username");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `imapsync` WHERE `user2` = :username");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `filterconf` WHERE `object` = :username");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_user_profile` WHERE `c_uid` = :username");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_cache_folder` WHERE `c_uid` = :username");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_acl` WHERE `c_object` LIKE '%/" . $username . "/%' OR `c_uid` = :username");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_store` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_quick_contact` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_quick_appointment` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_folder_info` WHERE `c_path2` = :username");
    +      $stmt->execute(array(
    +        ':username' => $username
    +      ));
    +      $stmt = $pdo->prepare("SELECT `address`, `goto` FROM `alias`
    +          WHERE `goto` REGEXP :username");
    +      $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
    +      $GotoData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    +      foreach ($GotoData as $gotos) {
    +        $goto_exploded = explode(',', $gotos['goto']);
    +        if (($key = array_search($username, $goto_exploded)) !== false) {
    +          unset($goto_exploded[$key]);
    +        }
    +        $gotos_rebuild = implode(',', $goto_exploded);
    +        $stmt = $pdo->prepare("UPDATE `alias` SET
    +          `goto` = :goto
    +            WHERE `address` = :address");
    +        $stmt->execute(array(
    +          ':goto' => $gotos_rebuild,
    +          ':address' => $gotos['address']
    +        ));
    +      }
    +    }
    +    catch (PDOException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'MySQL: '.$e
    +      );
    +      return false;
    +    }
     	}
     	$_SESSION['return'] = array(
     		'type' => 'success',
    -		'msg' => sprintf($lang['success']['mailbox_removed'], htmlspecialchars($username))
    +		'msg' => sprintf($lang['success']['mailbox_removed'], htmlspecialchars(implode(', ', $usernames)))
     	);
     }
     function mailbox_reset_eas($username) {
    @@ -4926,67 +4974,73 @@ function mailbox_reset_eas($username) {
     function mailbox_delete_resource($postarray) {
     	global $lang;
     	global $pdo;
    -	$name	= $postarray['name'];
    -	if (!filter_var($postarray['name'], FILTER_VALIDATE_EMAIL)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
    -		return false;
    -	}
    -
    -	if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $name)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
    -		return false;
    -	}
    -
    -	try {
    -		$stmt = $pdo->prepare("DELETE FROM `mailbox` WHERE `username` = :username");
    -		$stmt->execute(array(
    -			':username' => $name
    -		));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_user_profile` WHERE `c_uid` = :username");
    -    $stmt->execute(array(
    -      ':username' => $name
    -    ));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_cache_folder` WHERE `c_uid` = :username");
    -    $stmt->execute(array(
    -      ':username' => $name
    -    ));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_acl` WHERE `c_object` LIKE '%/" . $name . "/%' OR `c_uid` = :username");
    -    $stmt->execute(array(
    -      ':username' => $name
    -    ));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_store` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");
    -    $stmt->execute(array(
    -      ':username' => $name
    -    ));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_quick_contact` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");
    -    $stmt->execute(array(
    -      ':username' => $name
    -    ));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_quick_appointment` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");
    -    $stmt->execute(array(
    -      ':username' => $name
    -    ));
    -    $stmt = $pdo->prepare("DELETE FROM `sogo_folder_info` WHERE `c_path2` = :username");
    -    $stmt->execute(array(
    -      ':username' => $name
    -    ));
    -	}
    -	catch (PDOException $e) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => 'MySQL: '.$e
    -		);
    -		return false;
    +  if (!is_array($postarray['name'])) {
    +    $names = array();
    +    $names[] = $postarray['name'];
    +  }
    +  else {
    +    $names = $postarray['name'];
    +  }
    +  foreach ($names as $name) {
    +    if (!filter_var($name, FILTER_VALIDATE_EMAIL)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['access_denied'])
    +      );
    +      return false;
    +    }
    +    if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $name)) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => sprintf($lang['danger']['access_denied'])
    +      );
    +      return false;
    +    }
    +    try {
    +      $stmt = $pdo->prepare("DELETE FROM `mailbox` WHERE `username` = :username");
    +      $stmt->execute(array(
    +        ':username' => $name
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_user_profile` WHERE `c_uid` = :username");
    +      $stmt->execute(array(
    +        ':username' => $name
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_cache_folder` WHERE `c_uid` = :username");
    +      $stmt->execute(array(
    +        ':username' => $name
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_acl` WHERE `c_object` LIKE '%/" . $name . "/%' OR `c_uid` = :username");
    +      $stmt->execute(array(
    +        ':username' => $name
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_store` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");
    +      $stmt->execute(array(
    +        ':username' => $name
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_quick_contact` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");
    +      $stmt->execute(array(
    +        ':username' => $name
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_quick_appointment` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");
    +      $stmt->execute(array(
    +        ':username' => $name
    +      ));
    +      $stmt = $pdo->prepare("DELETE FROM `sogo_folder_info` WHERE `c_path2` = :username");
    +      $stmt->execute(array(
    +        ':username' => $name
    +      ));
    +    }
    +    catch (PDOException $e) {
    +      $_SESSION['return'] = array(
    +        'type' => 'danger',
    +        'msg' => 'MySQL: '.$e
    +      );
    +      return false;
    +    }
     	}
     	$_SESSION['return'] = array(
     		'type' => 'success',
    -		'msg' => sprintf($lang['success']['resource_removed'], htmlspecialchars($name))
    +		'msg' => sprintf($lang['success']['resource_removed'], htmlspecialchars(implode(', ', $names)))
     	);
     }
     function mailbox_get_sender_acl_handles($mailbox) {
    @@ -5178,7 +5232,6 @@ function add_forwarding_host($postarray) {
     	else {
     		$hosts = get_outgoing_hosts_best_guess($host);
     	}
    -  print_r($hosts);
     	if (empty($hosts)) {
     		$_SESSION['return'] = array(
     			'type' => 'danger',
    diff --git a/data/web/inc/vars.inc.php b/data/web/inc/vars.inc.php
    index 67c6c34e..4c8a10cd 100644
    --- a/data/web/inc/vars.inc.php
    +++ b/data/web/inc/vars.inc.php
    @@ -1,6 +1,7 @@
     <?php
    -error_reporting(E_ERROR);
    -//error_reporting(E_ALL);
    +//error_reporting(E_ERROR);
    +error_reporting(E_ALL);
    +header('X-Powered-By: mailcow');
     
     /*
     PLEASE USE THE FILE "vars.local.inc.php" TO OVERWRITE SETTINGS AND MAKE THEM PERSISTENT!
    diff --git a/data/web/js/admin.js b/data/web/js/admin.js
    index 4ad8246b..e76feef7 100644
    --- a/data/web/js/admin.js
    +++ b/data/web/js/admin.js
    @@ -1,17 +1,16 @@
     $(document).ready(function() {
    -  
    -  // Collect values of input fields with name multi_select with same data-form-id to js array multi_data[data-form-id-of-checkbox]
    +  // Collect values of input fields with name multi_select with same data-id to js array multi_data[data-id]
       var multi_data = [];
       $(document).on('change', 'input[name=multi_select]:checkbox', function() {
    -    if ($(this).is(':checked') && $(this).attr('data-form-id')) {
    -      var id = $(this).data('form-id');
    +    if ($(this).is(':checked') && $(this).data('id')) {
    +      var id = $(this).data('id');
           if (typeof multi_data[id] == "undefined") {
             multi_data[id] = [];
           }
           multi_data[id].push($(this).val());
         }
         else {
    -      var id = $(this).data('form-id');
    +      var id = $(this).data('id');
           multi_data[id].splice($.inArray($(this).val(), multi_data[id]),1);
         }
       });
    @@ -24,104 +23,21 @@ $(document).ready(function() {
           checkbox.trigger('click');
         }
       });
    -  // Select or deselect all checkboxes with same data-form-id
    +  // Select or deselect all checkboxes with same data-id
       $(document).on('click', '#toggle_multi_select_all', function(e) {
         e.preventDefault();
    -    var all_checkboxes = $("input[data-form-id=" + $(this).attr("data-form-id") + "]");
    +    id = $(this).data("id");
    +    multi_data[id] = [];
    +    var all_checkboxes = $("input[data-id=" + id + "]:enabled");
         all_checkboxes.prop("checked", !all_checkboxes.prop("checked")).change();
       });
    -
    -  // Draw domain admin table
    -  $.ajax({
    -    dataType: 'json',
    -    url: '/api/v1/get/domain-admin/all',
    -    jsonp: false,
    -    error: function () {
    -      console.log('Cannot draw domain admin table');
    -    },
    -    success: function (data) {
    -      $.each(data, function (i, item) {
    -        item.action = '<div class="btn-group">' +
    -          '<a href="/edit.php?domainadmin=' + encodeURI(item.username) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    -          '<a href="/delete.php?domainadmin=' + encodeURI(item.username) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    -					'</div>';
    -      });
    -      $('#domainadminstable').footable({
    -        "columns": [
    -          {"sorted": true,"name":"username","title":lang.username,"style":{"width":"250px"}},
    -          {"name":"selected_domains","title":lang.admin_domains,"breakpoints":"xs sm"},
    -          {"name":"tfa_active","title":"TFA", "filterable": false,"style":{"maxWidth":"80px","width":"80px"}},
    -          {"name":"active","filterable": false,"style":{"maxWidth":"80px","width":"80px"},"title":lang.active},
    -          {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
    -        ],
    -        "rows": data,
    -        "empty": lang.empty,
    -        "paging": {
    -          "enabled": true,
    -          "limit": 5,
    -          "size": pagination_size
    -        },
    -        "filtering": {
    -          "enabled": true,
    -          "position": "left",
    -          "placeholder": lang.filter_table
    -        },
    -        "sorting": {
    -          "enabled": true
    -        }
    -      });
    -    }
    -  });
    -  
    -  // Draw fwd hosts table
    -  $.ajax({
    -    dataType: 'json',
    -    url: '/api/v1/get/fwdhost/all',
    -    jsonp: false,
    -    error: function () {
    -      console.log('Cannot draw forwarding hosts table');
    -    },
    -    success: function (data) {
    -      $.each(data, function (i, item) {
    -        item.action = '<div class="btn-group">' +
    -          '<a href="/delete.php?forwardinghost=' + encodeURI(item.host) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    -					'</div>';
    -        if (item.keep_spam == "yes") {
    -          item.keep_spam = lang.no;
    -        }
    -        else {
    -          item.keep_spam = lang.yes;
    -        }
    -        item.chkbox = '<input type="checkbox" data-form-id="fwdhosts" name="multi_select" value="' + item.host + '" />';
    -      });
    -      $('#forwardinghoststable').footable({
    -        "columns": [
    -          {"name":"chkbox","title":"","style":{"maxWidth":"40px","width":"40px"},"filterable": false,"sortable": false,"type":"html"},
    -          {"name":"host","type":"text","title":lang.host,"style":{"width":"250px"}},
    -          {"name":"source","title":lang.source,"breakpoints":"xs sm"},
    -          {"name":"keep_spam","title":lang.spamfilter, "type": "text","style":{"maxWidth":"80px","width":"80px"}},
    -          {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
    -        ],
    -        "rows": data,
    -        "empty": lang.empty,
    -        "paging": {
    -          "enabled": true,
    -          "limit": 5,
    -          "size": pagination_size
    -        },
    -        "sorting": {
    -          "enabled": true
    -        }
    -      });
    -    }
    -  });
    -  
    -  $(document).on('click', '#delete_fwdhosts', function(e) {
    +  // General API edit function
    +  $(document).on('click', '#delete_selected', function(e) {
         e.preventDefault();
    -    var id = $(this).closest("form").attr('data-id');
    -    if (typeof multi_data[id] == "undefined") return;
    +    var id = $(this).data('id');
    +    if (typeof multi_data[id] == "undefined" || multi_data[id] == "") return;
         data_array = multi_data[id];
    -    if (Object.keys(data_array).length !== 0) {
    +    api_url = $(this).data('api-url');
           $(document).on('show.bs.modal','#ConfirmDeleteModal', function () {
             $("#ItemsToDelete").empty();
             for (var i in data_array) {
    @@ -136,41 +52,11 @@ $(document).ready(function() {
             $.ajax({
               type: "POST",
               dataType: "json",
    -          data: { "forwardinghost": JSON.stringify(data_array) },
    -          url: '/api/v1/delete/fwdhost',
    +          data: { "items": JSON.stringify(data_array) },
    +          url: '/api/v1/' + api_url,
               jsonp: false,
               complete: function (data) {
    -            window.location.href = window.location.href;
    -          }
    -        });
    -      })
    -      .one('click', '#isCanceled', function(e) {
    -        $('#ConfirmDeleteModal').modal('hide');
    -      });;
    -    }
    -  });
    -
    -  $(document).on('click', '#delete_dkim_key', function(e) {
    -    e.preventDefault();
    -    var dkim_domain = $(this).data('dkim-domain');
    -    var dkim_selector = $(this).data('dkim-selector');
    -      $(document).on('show.bs.modal','#ConfirmDeleteModal', function () {
    -        $("#ItemsToDelete").empty();
    -        $("#ItemsToDelete").append("<li>" + dkim_domain + ", " + dkim_selector + "</li>");
    -      })
    -      $('#ConfirmDeleteModal').modal({
    -        backdrop: 'static',
    -        keyboard: false
    -      })
    -      .one('click', '#IsConfirmed', function(e) {
    -        $.ajax({
    -          type: "POST",
    -          dataType: "json",
    -          data: { "domains": JSON.stringify(dkim_domain) },
    -          url: '/api/v1/delete/dkim',
    -          jsonp: false,
    -          complete: function (data) {
    -            mailcow_alert_box("warn", "asd");
    +            location.assign(window.location);
               }
             });
           })
    @@ -179,72 +65,28 @@ $(document).ready(function() {
           });;
       });
     
    -  $("#refresh_dovecot_log").on('click', function(e) {
    -      function unix_time_format(tm) {
    -        var date = new Date(tm ? tm * 1000 : 0);
    -        return date.toLocaleString();
    -      }
    -      e.preventDefault();
    -      if (typeof ft_dovecot_logs != 'undefined') {
    -        ft_dovecot_logs.destroy();
    -      }
    -      $.ajax({
    -        dataType: 'json',
    -        url: '/api/v1/get/logs/dovecot/1000',
    -        jsonp: false,
    -        error: function () {
    -          console.log('Cannot draw dovecot log table');
    -        },
    -        success: function (data) {
    -          $.each(data, function (i, item) {
    -            var danger_class = ["emerg", "alert", "crit"];
    -            var warning_class = ["warning"];
    -            var info_class = ["notice", "info", "debug"];
    -            if (jQuery.inArray(item.priority, danger_class) !== -1) {
    -              item.priority = '<span class="label label-danger">' + item.priority + '</span>';
    -            } 
    -            else if (jQuery.inArray(item.priority, warning_class) !== -1) {
    -              item.priority = '<span class="label label-warning">' + item.priority + '</span>';
    -            }
    -            else if (jQuery.inArray(item.priority, info_class) !== -1) {
    -              item.priority = '<span class="label label-info">' + item.priority + '</span>';
    -            }
    -          });
    -          ft_dovecot_logs = FooTable.init("#dovecot_log", {
    -            "columns": [
    -              {"name":"time","formatter":function unix_time_format(tm) {var date = new Date(tm ? tm * 1000 : 0); return date.toLocaleString();},"title":lang.time,"style":{"width":"170px"}},
    -              {"name":"priority","title":lang.priority,"style":{"width":"80px"}},
    -              {"name":"message","title":lang.message},
    -            ],
    -            "rows": data,
    -            "empty": lang.empty,
    -            "paging": {
    -              "enabled": true,
    -              "limit": 5,
    -              "size": pagination_size
    -            },
    -            "filtering": {
    -              "enabled": true,
    -              "position": "left",
    -              "placeholder": lang.filter_table
    -            },
    -            "sorting": {
    -              "enabled": true
    -            }
    -          });
    -        }
    -      });
    -  });
    +});
    +jQuery(function($){
    +  function unix_time_format(tm) {
    +    var date = new Date(tm ? tm * 1000 : 0);
    +    return date.toLocaleString();
    +  }
       $("#refresh_postfix_log").on('click', function(e) {
    -      function unix_time_format(tm) {
    -        var date = new Date(tm ? tm * 1000 : 0);
    -        return date.toLocaleString();
    -      }
    -      e.preventDefault();
    -      if (typeof ft_postfix_logs != 'undefined') {
    -        ft_postfix_logs.destroy();
    -      }
    -      $.ajax({
    +    e.preventDefault();
    +    draw_postfix_logs();
    +  });
    +  $("#refresh_dovecot_log").on('click', function(e) {
    +    e.preventDefault();
    +    draw_dovecot_logs();
    +  });
    +  function draw_postfix_logs() {
    +    ft_postfix_logs = FooTable.init('#postfix_log', {
    +      "columns": [
    +        {"name":"time","formatter":function unix_time_format(tm) { var date = new Date(tm ? tm * 1000 : 0); return date.toLocaleString();},"title":lang.time,"style":{"width":"170px"}},
    +        {"name":"priority","title":lang.priority,"style":{"width":"80px"}},
    +        {"name":"message","title":lang.message},
    +      ],
    +      "rows": $.ajax({
             dataType: 'json',
             url: '/api/v1/get/logs/postfix/1000',
             jsonp: false,
    @@ -266,31 +108,158 @@ $(document).ready(function() {
                   item.priority = '<span class="label label-info">' + item.priority + '</span>';
                 }
               });
    -          ft_postfix_logs = FooTable.init("#postfix_log", {
    -            "columns": [
    -              {"name":"time","formatter":function unix_time_format(tm) { var date = new Date(tm ? tm * 1000 : 0); return date.toLocaleString();},"title":lang.time,"style":{"width":"170px"}},
    -              {"name":"priority","title":lang.priority,"style":{"width":"80px"}},
    -              {"name":"message","title":lang.message},
    -            ],
    -            "rows": data,
    -            "empty": lang.empty,
    -            "paging": {
    -              "enabled": true,
    -              "limit": 5,
    -              "size": pagination_size
    -            },
    -            "filtering": {
    -              "enabled": true,
    -              "position": "left",
    -              "placeholder": lang.filter_table
    -            },
    -            "sorting": {
    -              "enabled": true
    +        }
    +      }),
    +      "empty": lang.empty,
    +      "paging": {
    +        "enabled": true,
    +        "limit": 5,
    +        "size": pagination_size
    +      },
    +      "filtering": {
    +        "enabled": true,
    +        "position": "left",
    +        "placeholder": lang.filter_table
    +      },
    +      "sorting": {
    +        "enabled": true
    +      }
    +    });
    +  }
    +  function draw_dovecot_logs() {
    +    ft_postfix_logs = FooTable.init('#dovecot_log', {
    +      "columns": [
    +        {"name":"time","formatter":function unix_time_format(tm) { var date = new Date(tm ? tm * 1000 : 0); return date.toLocaleString();},"title":lang.time,"style":{"width":"170px"}},
    +        {"name":"priority","title":lang.priority,"style":{"width":"80px"}},
    +        {"name":"message","title":lang.message},
    +      ],
    +      "rows": $.ajax({
    +        dataType: 'json',
    +        url: '/api/v1/get/logs/dovecot/1000',
    +        jsonp: false,
    +        error: function () {
    +          console.log('Cannot draw dovecot log table');
    +        },
    +        success: function (data) {
    +          $.each(data, function (i, item) {
    +            var danger_class = ["emerg", "alert", "crit"];
    +            var warning_class = ["warning"];
    +            var info_class = ["notice", "info", "debug"];
    +            if (jQuery.inArray(item.priority, danger_class) !== -1) {
    +              item.priority = '<span class="label label-danger">' + item.priority + '</span>';
    +            } 
    +            else if (jQuery.inArray(item.priority, warning_class) !== -1) {
    +              item.priority = '<span class="label label-warning">' + item.priority + '</span>';
    +            }
    +            else if (jQuery.inArray(item.priority, info_class) !== -1) {
    +              item.priority = '<span class="label label-info">' + item.priority + '</span>';
                 }
               });
             }
    -      });
    -  });
    -  $("#refresh_dovecot_log").trigger('click');
    -  $("#refresh_postfix_log").trigger('click');
    +      }),
    +      "empty": lang.empty,
    +      "paging": {
    +        "enabled": true,
    +        "limit": 5,
    +        "size": pagination_size
    +      },
    +      "filtering": {
    +        "enabled": true,
    +        "position": "left",
    +        "placeholder": lang.filter_table
    +      },
    +      "sorting": {
    +        "enabled": true
    +      }
    +    });
    +  }
    +  function draw_domain_admins() {
    +    ft_domainadmins = FooTable.init('#domainadminstable', {
    +      "columns": [
    +        {"sorted": true,"name":"username","title":lang.username,"style":{"width":"250px"}},
    +        {"name":"selected_domains","title":lang.admin_domains,"breakpoints":"xs sm"},
    +        {"name":"tfa_active","title":"TFA", "filterable": false,"style":{"maxWidth":"80px","width":"80px"}},
    +        {"name":"active","filterable": false,"style":{"maxWidth":"80px","width":"80px"},"title":lang.active},
    +        {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
    +      ],
    +      "rows": $.ajax({
    +        dataType: 'json',
    +        url: '/api/v1/get/domain-admin/all',
    +        jsonp: false,
    +        error: function () {
    +          console.log('Cannot draw domain admin table');
    +        },
    +        success: function (data) {
    +          $.each(data, function (i, item) {
    +            item.action = '<div class="btn-group">' +
    +              '<a href="/edit.php?domainadmin=' + encodeURI(item.username) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    +              '<a href="/delete.php?domainadmin=' + encodeURI(item.username) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    +              '</div>';
    +          });
    +        }
    +      }),
    +      "empty": lang.empty,
    +      "paging": {
    +        "enabled": true,
    +        "limit": 5,
    +        "size": pagination_size
    +      },
    +      "filtering": {
    +        "enabled": true,
    +        "position": "left",
    +        "placeholder": lang.filter_table
    +      },
    +      "sorting": {
    +        "enabled": true
    +      }
    +    });
    +  }
    +
    +  function draw_fwd_hosts() {
    +    ft_domainadmins = FooTable.init('#forwardinghoststable', {
    +      "columns": [
    +        {"name":"chkbox","title":"","style":{"maxWidth":"40px","width":"40px"},"filterable": false,"sortable": false,"type":"html"},
    +        {"name":"host","type":"text","title":lang.host,"style":{"width":"250px"}},
    +        {"name":"source","title":lang.source,"breakpoints":"xs sm"},
    +        {"name":"keep_spam","title":lang.spamfilter, "type": "text","style":{"maxWidth":"80px","width":"80px"}},
    +        {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
    +      ],
    +      "rows": $.ajax({
    +        dataType: 'json',
    +        url: '/api/v1/get/fwdhost/all',
    +        jsonp: false,
    +        error: function () {
    +          console.log('Cannot draw forwarding hosts table');
    +        },
    +        success: function (data) {
    +          $.each(data, function (i, item) {
    +            item.action = '<div class="btn-group">' +
    +              '<a href="/delete.php?forwardinghost=' + encodeURI(item.host) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    +              '</div>';
    +            if (item.keep_spam == "yes") {
    +              item.keep_spam = lang.no;
    +            }
    +            else {
    +              item.keep_spam = lang.yes;
    +            }
    +            item.chkbox = '<input type="checkbox" data-id="fwdhosts" name="multi_select" value="' + item.host + '" />';
    +          });
    +        }
    +      }),
    +      "empty": lang.empty,
    +      "paging": {
    +        "enabled": true,
    +        "limit": 5,
    +        "size": pagination_size
    +      },
    +      "sorting": {
    +        "enabled": true
    +      }
    +    });
    +  }
    +
    +  draw_postfix_logs();
    +  draw_dovecot_logs();
    +  draw_domain_admins();
    +  draw_fwd_hosts();
     });
    \ No newline at end of file
    diff --git a/data/web/js/mailbox.js b/data/web/js/mailbox.js
    index 39f2d976..70435ca1 100644
    --- a/data/web/js/mailbox.js
    +++ b/data/web/js/mailbox.js
    @@ -1,5 +1,98 @@
     $(document).ready(function() {
    -	$('[data-toggle="tooltip"]').tooltip();
    +  // Collect values of input fields with name multi_select with same data-id to js array multi_data[data-id]
    +  var multi_data = [];
    +  $(document).on('change', 'input[name=multi_select]:checkbox', function() {
    +    if ($(this).is(':checked') && $(this).data('id')) {
    +      var id = $(this).data('id');
    +      if (typeof multi_data[id] == "undefined") {
    +        multi_data[id] = [];
    +      }
    +      multi_data[id].push($(this).val());
    +    }
    +    else {
    +      var id = $(this).data('id');
    +      multi_data[id].splice($.inArray($(this).val(), multi_data[id]),1);
    +    }
    +  });
    +  // Select checkbox by click on parent tr
    +  $(document).on('click', 'tr', function(e) {
    +    if (e.target.type == "checkbox") {
    +      e.stopPropagation();
    +    } else {
    +      var checkbox = $(this).find(':checkbox');
    +      checkbox.trigger('click');
    +    }
    +  });
    +  // Select or deselect all checkboxes with same data-id
    +  $(document).on('click', '#toggle_multi_select_all', function(e) {
    +    e.preventDefault();
    +    id = $(this).data("id");
    +    multi_data[id] = [];
    +    var all_checkboxes = $("input[data-id=" + id + "]:enabled");
    +    all_checkboxes.prop("checked", !all_checkboxes.prop("checked")).change();
    +  });
    +  // General API edit actions
    +  $(document).on('click', '#edit_selected', function(e) {
    +    e.preventDefault();
    +    var id = $(this).data('id');
    +    if (typeof multi_data[id] == "undefined") return;
    +    data_array = multi_data[id];
    +    api_url = $(this).data('api-url');
    +    api_attr = $(this).data('api-attr');
    +    if (Object.keys(data_array).length !== 0) {
    +      $.ajax({
    +        type: "POST",
    +        dataType: "json",
    +        data: { "items": JSON.stringify(data_array), "attr": JSON.stringify(api_attr) },
    +        url: '/api/v1/' + api_url,
    +        jsonp: false,
    +        complete: function (data) {
    +          // var reponse = (JSON.parse(data.responseText));
    +          // alert(reponse.type);
    +          // alert(reponse.msg);
    +          location.assign(window.location);
    +        }
    +      });
    +    }
    +  });
    +  // General API delete actions
    +  $(document).on('click', '#delete_selected', function(e) {
    +    e.preventDefault();
    +    var id = $(this).data('id');
    +    if (typeof multi_data[id] == "undefined" || multi_data[id] == "") return;
    +    data_array = multi_data[id];
    +    api_url = $(this).data('api-url');
    +      $(document).on('show.bs.modal','#ConfirmDeleteModal', function () {
    +        $("#ItemsToDelete").empty();
    +        for (var i in data_array) {
    +          $("#ItemsToDelete").append("<li>" + data_array[i] + "</li>");
    +        }
    +      })
    +      $('#ConfirmDeleteModal').modal({
    +        backdrop: 'static',
    +        keyboard: false
    +      })
    +      .one('click', '#IsConfirmed', function(e) {
    +        $.ajax({
    +          type: "POST",
    +          dataType: "json",
    +          data: { "items": JSON.stringify(data_array) },
    +          url: '/api/v1/' + api_url,
    +          jsonp: false,
    +          complete: function (data) {
    +            location.assign(window.location);
    +          }
    +        });
    +      })
    +      .one('click', '#isCanceled', function(e) {
    +        $('#ConfirmDeleteModal').modal('hide');
    +      });;
    +  });
    +
    +});
    +
    +jQuery(function($){
    +  // Calculation human readable file sizes
       function humanFileSize(bytes) {
         if(Math.abs(bytes) < 1024) {
             return bytes + ' B';
    @@ -12,358 +105,285 @@ $(document).ready(function() {
         } while(Math.abs(bytes) >= 1024 && u < units.length - 1);
         return bytes.toFixed(1)+' '+units[u];
       }
    -
    -  $.ajax({
    -    dataType: 'json',
    -    url: '/api/v1/get/domain/all',
    -    jsonp: false,
    -    error: function () {
    -      alert('Cannot draw domain table');
    -    },
    -    success: function (data) {
    -      $.each(data, function (i, item) {
    -        item.aliases = item.aliases_in_domain + " / " + item.max_num_aliases_for_domain;
    -        item.mailboxes = item.mboxes_in_domain + " / " + item.max_num_mboxes_for_domain;
    -        item.quota = item.quota_used_in_domain + "/" + item.max_quota_for_domain;
    -        item.max_quota_for_mbox = humanFileSize(item.max_quota_for_mbox);
    -        if (role == "admin") {
    -        item.action = '<div class="btn-group">' +
    -          '<a href="/edit.php?domain=' + encodeURI(item.domain_name) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    -          '<a href="/delete.php?domain=' + encodeURI(item.domain_name) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    -					'</div>';
    -        }
    -        else {
    -        item.action = '<div class="btn-group">' +
    -          '<a href="/edit.php?domain=' + encodeURI(item.domain_name) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    -					'</div>';
    -        }
    -      });
    -      $('#domain_table').footable({
    -        "columns": [
    -          {"sorted": true,"name":"domain_name","title":lang.domain,"style":{"width":"250px"}},
    -          {"name":"aliases","title":lang.aliases,"breakpoints":"xs sm"},
    -          {"name":"mailboxes","title":lang.mailboxes},
    -          {"name":"quota","style":{"whiteSpace":"nowrap"},"title":lang.domain_quota,"formatter": function(value){
    -            res = value.split("/");
    -            return humanFileSize(res[0]) + " / " + humanFileSize(res[1]);
    -          },
    -          "sortValue": function(value){
    -            res = value.split("/");
    -            return res[0];
    -          },
    -          },
    -          {"name":"max_quota_for_mbox","title":lang.mailbox_quota,"breakpoints":"xs sm"},
    -          {"name":"backupmx","filterable": false,"style":{"maxWidth":"120px","width":"120px"},"title":lang.backup_mx,"breakpoints":"xs sm"},
    -          {"name":"active","filterable": false,"style":{"maxWidth":"80px","width":"80px"},"title":lang.active},
    -          {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
    -        ],
    -        "rows": data,
    -        "empty": lang.empty,
    -        "paging": {
    -          "enabled": true,
    -          "limit": 5,
    -          "size": pagination_size
    +  function unix_time_format(tm) {
    +    var date = new Date(tm ? tm * 1000 : 0);
    +    return date.toLocaleString();
    +  }
    +  function draw_domain_table() {
    +    ft_domain_table = FooTable.init('#domain_table', {
    +      "columns": [
    +        {"name":"chkbox","title":"","style":{"maxWidth":"40px","width":"40px"},"filterable": false,"sortable": false,"type":"html"},
    +        {"sorted": true,"name":"domain_name","title":lang.domain,"style":{"width":"250px"}},
    +        {"name":"aliases","title":lang.aliases,"breakpoints":"xs sm"},
    +        {"name":"mailboxes","title":lang.mailboxes},
    +        {"name":"quota","style":{"whiteSpace":"nowrap"},"title":lang.domain_quota,"formatter": function(value){
    +          res = value.split("/");
    +          return humanFileSize(res[0]) + " / " + humanFileSize(res[1]);
             },
    -        "filtering": {
    -          "enabled": true,
    -          "position": "left",
    -          "placeholder": lang.filter_table
    +        "sortValue": function(value){
    +          res = value.split("/");
    +          return res[0];
             },
    -        "sorting": {
    -          "enabled": true
    -        }
    -      });
    -    }
    -  });
    -
    -  $.ajax({
    -    dataType: 'json',
    -    url: '/api/v1/get/mailbox/all',
    -    jsonp: false,
    -    error: function () {
    -      alert('Cannot draw mailbox table');
    -    },
    -    success: function (data) {
    -      $.each(data, function (i, item) {
    -        item.quota = item.quota_used + "/" + item.quota;
    -        item.max_quota_for_mbox = humanFileSize(item.max_quota_for_mbox);
    -        if (role == "admin") {
    -        item.action = '<div class="btn-group">' +
    -          '<a href="/edit.php?mailbox=' + encodeURI(item.username) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    -          '<a href="/delete.php?mailbox=' + encodeURI(item.username) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    -          '<a href="/index.php?duallogin=' + encodeURI(item.username) + '" class="btn btn-xs btn-success"><span class="glyphicon glyphicon-user"></span> Login</a>' +
    -					'</div>';
    -        }
    -        else {
    -        item.action = '<div class="btn-group">' +
    -          '<a href="/edit.php?mailbox=' + encodeURI(item.username) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    -          '<a href="/delete.php?mailbox=' + encodeURI(item.username) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    -					'</div>';
    -        }
    -        item.in_use = '<div class="progress">' +
    -				  '<div class="progress-bar progress-bar-' + item.percent_class + ' role="progressbar" aria-valuenow="' + item.percent_in_use + '" aria-valuemin="0" aria-valuemax="100" ' +
    -          'style="min-width:2em;width:' + item.percent_in_use + '%">' + item.percent_in_use + '%' + '</div></div>';
    -
    -      });
    -      $('#mailbox_table').footable({
    -        "columns": [
    -          {"sorted": true,"name":"username","style":{"word-break":"break-all","min-width":"120px"},"title":lang.username},
    -          {"name":"name","title":lang.fname,"style":{"word-break":"break-all","min-width":"120px"},"breakpoints":"xs sm"},
    -          {"name":"domain","title":lang.domain,"breakpoints":"xs sm"},
    -          {"name":"quota","style":{"whiteSpace":"nowrap"},"title":lang.domain_quota,"formatter": function(value){
    -            res = value.split("/");
    -            return humanFileSize(res[0]) + " / " + humanFileSize(res[1]);
    -          },
    -          "sortValue": function(value){
    -            res = value.split("/");
    -            return res[0];
    -          },
    -          },
    -          {"name":"spam_aliases","filterable": false,"title":lang.spam_aliases,"breakpoints":"xs sm md"},
    -          {"name":"in_use","filterable": false,"type":"html","title":lang.in_use},
    -          {"name":"messages","filterable": false,"title":lang.msg_num,"breakpoints":"xs sm md"},
    -          {"name":"active","filterable": false,"title":lang.active},
    -          {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","min-width":"250px"},"type":"html","title":lang.action,"breakpoints":"xs sm md"}
    -        ],
    -        "empty": lang.empty,
    -        "rows": data,
    -        "paging": {
    -          "enabled": true,
    -          "limit": 5,
    -          "size": pagination_size
             },
    -        "filtering": {
    -          "enabled": true,
    -          "position": "left",
    -          "placeholder": lang.filter_table
    +        {"name":"max_quota_for_mbox","title":lang.mailbox_quota,"breakpoints":"xs sm"},
    +        {"name":"backupmx","filterable": false,"style":{"maxWidth":"120px","width":"120px"},"title":lang.backup_mx,"breakpoints":"xs sm"},
    +        {"name":"active","filterable": false,"style":{"maxWidth":"80px","width":"80px"},"title":lang.active},
    +      ],
    +      "rows": $.ajax({
    +        dataType: 'json',
    +        url: '/api/v1/get/domain/all',
    +        jsonp: false,
    +        error: function () {
    +          alert('Cannot draw domain table');
             },
    -        "sorting": {
    -          "enabled": true
    -        }
    -      });
    -    }
    -  });
    -
    -  $.ajax({
    -    dataType: 'json',
    -    url: '/api/v1/get/resource/all',
    -    jsonp: false,
    -    error: function () {
    -      alert('Cannot draw resource table');
    -    },
    -    success: function (data) {
    -      $.each(data, function (i, item) {
    -        item.action = '<div class="btn-group">' +
    -          '<a href="/edit.php?resource=' + encodeURI(item.name) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    -          '<a href="/delete.php?resource=' + encodeURI(item.name) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    -					'</div>';
    -      });
    -      $('#resources_table').footable({
    -        "columns": [
    -          {"sorted": true,"name":"description","title":lang.description,"style":{"width":"250px"}},
    -          {"name":"kind","title":lang.kind},
    -          {"name":"domain","title":lang.domain,"breakpoints":"xs sm"},
    -          {"name":"multiple_bookings","filterable": false,"style":{"maxWidth":"120px","width":"120px"},"title":lang.multiple_bookings,"breakpoints":"xs sm"},
    -          {"name":"active","filterable": false,"style":{"maxWidth":"80px","width":"80px"},"title":lang.active},
    -          {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
    -        ],
    -        "empty": lang.empty,
    -        "rows": data,
    -        "paging": {
    -          "enabled": true,
    -          "limit": 5,
    -          "size": pagination_size
    -        },
    -        "filtering": {
    -          "enabled": true,
    -          "position": "left",
    -          "placeholder": lang.filter_table
    -        },
    -        "sorting": {
    -          "enabled": true
    -        }
    -      });
    -    }
    -  });
    -
    -  $.ajax({
    -    dataType: 'json',
    -    url: '/api/v1/get/alias-domain/all',
    -    jsonp: false,
    -    error: function () {
    -      alert('Cannot draw alias domain table');
    -    },
    -    success: function (data) {
    -      $.each(data, function (i, item) {
    -        item.action = '<div class="btn-group">' +
    -          '<a href="/edit.php?aliasdomain=' + encodeURI(item.alias_domain) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    -          '<a href="/delete.php?aliasdomain=' + encodeURI(item.alias_domain) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    -					'</div>';
    -      });
    -      $('#aliasdomain_table').footable({
    -        "columns": [
    -          {"sorted": true,"name":"alias_domain","title":lang.alias,"style":{"width":"250px"}},
    -          {"name":"target_domain","title":lang.target_domain},
    -          {"name":"active","filterable": false,"style":{"maxWidth":"50px","width":"70px"},"title":lang.active},
    -          {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
    -        ],
    -        "empty": lang.empty,
    -        "rows": data,
    -        "paging": {
    -          "enabled": true,
    -          "limit": 5,
    -          "size": pagination_size
    -        },
    -        "filtering": {
    -          "enabled": true,
    -          "position": "left",
    -          "placeholder": lang.filter_table
    -        },
    -        "sorting": {
    -          "enabled": true
    -        }
    -      });
    -    }
    -  });
    -
    -  $.ajax({
    -    dataType: 'json',
    -    url: '/api/v1/get/alias/all',
    -    jsonp: false,
    -    error: function () {
    -      alert('Cannot draw alias table');
    -    },
    -    success: function (data) {
    -      $.each(data, function (i, item) {
    -        item.action = '<div class="btn-group">' +
    -          '<a href="/edit.php?alias=' + encodeURI(item.address) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    -          '<a href="/delete.php?alias=' + encodeURI(item.address) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-pencil"></span> ' + lang.remove + '</a>' +
    -					'</div>';
    -        item.chkbox = '<input type="checkbox" class="alias_item" name="sel_aliases" value="' + item.address + '" />';
    -        if (item.is_catch_all == 1) {
    -          item.address = '<div class="label label-default">Catch-All</div> ' + item.address;
    -        }
    -        if (item.in_primary_domain !== "") {
    -          item.domain = "↳ " + item.domain + " (" + item.in_primary_domain + ")";
    -        }
    -      });
    -      ft_aliases = FooTable.init("#alias_table", {
    -        "columns": [
    -          {"name":"chkbox","title":"","style":{"maxWidth":"40px","width":"40px"},"filterable": false,"sortable": false,"type":"html"},
    -          {"sorted": true,"name":"address","title":lang.alias,"style":{"width":"250px"}},
    -          {"name":"goto","title":lang.target_address},
    -          {"name":"domain","title":lang.domain,"breakpoints":"xs sm"},
    -          {"name":"active","filterable": false,"style":{"maxWidth":"50px","width":"70px"},"title":lang.active},
    -          {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
    -        ],
    -        "empty": lang.empty,
    -        "rows": data,
    -        "paging": {
    -          "enabled": true,
    -          "limit": 5,
    -          "size": pagination_size
    -        },
    -        "filtering": {
    -          "enabled": true,
    -          "position": "left",
    -          "placeholder": lang.filter_table
    -        },
    -        "sorting": {
    -          "enabled": true
    -        }
    -      });
    -
    -      var selected_aliases = [];
    -
    -      $(document).on('click', 'tr', function(e) {
    -        if (e.target.type == "checkbox") {
    -          e.stopPropagation();
    -        } else {
    -          var checkbox = $(this).find(':checkbox');
    -          checkbox.trigger('click');
    -        }
    -      });
    -
    -      $(document).on('change', 'input[name=sel_aliases]:checkbox', function() {
    -        if ($(this).is(':checked')) {
    -          selected_aliases.push($(this).val());
    -        }
    -        else {
    -          selected_aliases.splice($.inArray($(this).val(), selected_aliases),1);
    -        }
    -      });
    -
    -      $(document).on('click', '#select_all_aliases', function(e) {
    -        e.preventDefault();
    -        var alias_chkbxs = $("input[name=sel_aliases]");
    -        alias_chkbxs.prop("checked", !alias_chkbxs.prop("checked")).change();
    -      });
    -
    -      $(document).on('click', '#activate_selected_alias', function(e) {
    -        e.preventDefault();
    -        if (Object.keys(selected_aliases).length !== 0) {
    -          $.ajax({
    -            type: "POST",
    -            dataType: "json",
    -            data: { "address": JSON.stringify(selected_aliases), "active": "1" },
    -            url: '/api/v1/edit/alias',
    -            jsonp: false,
    -            complete: function (data) {
    -              window.location.href = window.location.href;
    +        success: function (data) {
    +          $.each(data, function (i, item) {
    +            item.aliases = item.aliases_in_domain + " / " + item.max_num_aliases_for_domain;
    +            item.mailboxes = item.mboxes_in_domain + " / " + item.max_num_mboxes_for_domain;
    +            item.quota = item.quota_used_in_domain + "/" + item.max_quota_for_domain;
    +            item.max_quota_for_mbox = humanFileSize(item.max_quota_for_mbox);
    +            item.chkbox = '<input type="checkbox" data-id="domain" name="multi_select" value="' + item.domain_name + '" />';
    +            if (role == "admin") {
    +              item.action = '<div class="btn-group">' +
    +                '<a href="/edit.php?domain=' + encodeURI(item.domain_name) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    +                '<a href="/delete.php?domain=' + encodeURI(item.domain_name) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    +                '</div>';
    +            }
    +            else {
    +              item.action = '<div class="btn-group">' +
    +                '<a href="/edit.php?domain=' + encodeURI(item.domain_name) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    +                '</div>';
                 }
               });
             }
    -      });
    +      }),
    +      "empty": lang.empty,
    +      "paging": {
    +        "enabled": true,
    +        "limit": 5,
    +        "size": pagination_size
    +      },
    +      "filtering": {
    +        "enabled": true,
    +        "position": "left",
    +        "placeholder": lang.filter_table
    +      },
    +      "sorting": {
    +        "enabled": true
    +      }
    +    });
    +  }
    +  function draw_mailbox_table() {
    +    ft_mailbox_table = FooTable.init('#mailbox_table', {
    +      "columns": [
    +        {"name":"chkbox","title":"","style":{"maxWidth":"40px","width":"40px"},"filterable": false,"sortable": false,"type":"html"},
    +        {"sorted": true,"name":"username","style":{"word-break":"break-all","min-width":"120px"},"title":lang.username},
    +        {"name":"name","title":lang.fname,"style":{"word-break":"break-all","min-width":"120px"},"breakpoints":"xs sm"},
    +        {"name":"domain","title":lang.domain,"breakpoints":"xs sm"},
    +        {"name":"quota","style":{"whiteSpace":"nowrap"},"title":lang.domain_quota,"formatter": function(value){
    +          res = value.split("/");
    +          return humanFileSize(res[0]) + " / " + humanFileSize(res[1]);
    +        },
    +        "sortValue": function(value){
    +          res = value.split("/");
    +          return res[0];
    +        },
    +        },
    +        {"name":"spam_aliases","filterable": false,"title":lang.spam_aliases,"breakpoints":"xs sm md"},
    +        {"name":"in_use","filterable": false,"type":"html","title":lang.in_use},
    +        {"name":"messages","filterable": false,"title":lang.msg_num,"breakpoints":"xs sm md"},
    +        {"name":"active","filterable": false,"title":lang.active},
    +        {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","min-width":"250px"},"type":"html","title":lang.action,"breakpoints":"xs sm md"}
    +      ],
    +      "empty": lang.empty,
    +      "rows": $.ajax({
    +        dataType: 'json',
    +        url: '/api/v1/get/mailbox/all',
    +        jsonp: false,
    +        error: function () {
    +          alert('Cannot draw mailbox table');
    +        },
    +        success: function (data) {
    +          $.each(data, function (i, item) {
    +            item.quota = item.quota_used + "/" + item.quota;
    +            item.max_quota_for_mbox = humanFileSize(item.max_quota_for_mbox);
    +            item.chkbox = '<input type="checkbox" data-id="mailbox" name="multi_select" value="' + item.username + '" />';
    +            if (role == "admin") {
    +            item.action = '<div class="btn-group">' +
    +              '<a href="/edit.php?mailbox=' + encodeURI(item.username) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    +              '<a href="/delete.php?mailbox=' + encodeURI(item.username) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    +              '<a href="/index.php?duallogin=' + encodeURI(item.username) + '" class="btn btn-xs btn-success"><span class="glyphicon glyphicon-user"></span> Login</a>' +
    +              '</div>';
    +            }
    +            else {
    +            item.action = '<div class="btn-group">' +
    +              '<a href="/edit.php?mailbox=' + encodeURI(item.username) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    +              '<a href="/delete.php?mailbox=' + encodeURI(item.username) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    +              '</div>';
    +            }
    +            item.in_use = '<div class="progress">' +
    +              '<div class="progress-bar progress-bar-' + item.percent_class + ' role="progressbar" aria-valuenow="' + item.percent_in_use + '" aria-valuemin="0" aria-valuemax="100" ' +
    +              'style="min-width:2em;width:' + item.percent_in_use + '%">' + item.percent_in_use + '%' + '</div></div>';
     
    -      $(document).on('click', '#deactivate_selected_alias', function(e) {
    -        e.preventDefault();
    -        if (Object.keys(selected_aliases).length !== 0) {
    -          $.ajax({
    -            type: "POST",
    -            dataType: "json",
    -            data: { "address": JSON.stringify(selected_aliases), "active": "0" },
    -            url: '/api/v1/edit/alias',
    -            jsonp: false,
    -            complete: function (data) {
    -              window.location.href = window.location.href;
    +          });
    +        }
    +      }),
    +      "paging": {
    +        "enabled": true,
    +        "limit": 5,
    +        "size": pagination_size
    +      },
    +      "filtering": {
    +        "enabled": true,
    +        "position": "left",
    +        "placeholder": lang.filter_table
    +      },
    +      "sorting": {
    +        "enabled": true
    +      }
    +    });
    +  }
    +  function draw_resource_table() {
    +    ft_resource_table = FooTable.init('#resource_table', {
    +      "columns": [
    +        {"name":"chkbox","title":"","style":{"maxWidth":"40px","width":"40px"},"filterable": false,"sortable": false,"type":"html"},
    +        {"sorted": true,"name":"description","title":lang.description,"style":{"width":"250px"}},
    +        {"name":"kind","title":lang.kind},
    +        {"name":"domain","title":lang.domain,"breakpoints":"xs sm"},
    +        {"name":"multiple_bookings","filterable": false,"style":{"maxWidth":"120px","width":"120px"},"title":lang.multiple_bookings,"breakpoints":"xs sm"},
    +        {"name":"active","filterable": false,"style":{"maxWidth":"80px","width":"80px"},"title":lang.active},
    +        {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
    +      ],
    +      "empty": lang.empty,
    +      "rows": $.ajax({
    +        dataType: 'json',
    +        url: '/api/v1/get/resource/all',
    +        jsonp: false,
    +        error: function () {
    +          alert('Cannot draw resource table');
    +        },
    +        success: function (data) {
    +          $.each(data, function (i, item) {
    +            item.action = '<div class="btn-group">' +
    +              '<a href="/edit.php?resource=' + encodeURI(item.name) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    +              '<a href="/delete.php?resource=' + encodeURI(item.name) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    +              '</div>';
    +            item.chkbox = '<input type="checkbox" data-id="resource" name="multi_select" value="' + item.name + '" />';
    +          });
    +        }
    +      }),
    +      "paging": {
    +        "enabled": true,
    +        "limit": 5,
    +        "size": pagination_size
    +      },
    +      "filtering": {
    +        "enabled": true,
    +        "position": "left",
    +        "placeholder": lang.filter_table
    +      },
    +      "sorting": {
    +        "enabled": true
    +      }
    +    });
    +  }
    +
    +  function draw_alias_table() {
    +    ft_alias_table = FooTable.init('#alias_table', {
    +      "columns": [
    +        {"name":"chkbox","title":"","style":{"maxWidth":"40px","width":"40px"},"filterable": false,"sortable": false,"type":"html"},
    +        {"sorted": true,"name":"address","title":lang.alias,"style":{"width":"250px"}},
    +        {"name":"goto","title":lang.target_address},
    +        {"name":"domain","title":lang.domain,"breakpoints":"xs sm"},
    +        {"name":"active","filterable": false,"style":{"maxWidth":"50px","width":"70px"},"title":lang.active},
    +        {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
    +      ],
    +      "empty": lang.empty,
    +      "rows": $.ajax({
    +        dataType: 'json',
    +        url: '/api/v1/get/alias/all',
    +        jsonp: false,
    +        error: function () {
    +          alert('Cannot draw alias table');
    +        },
    +        success: function (data) {
    +          $.each(data, function (i, item) {
    +            item.action = '<div class="btn-group">' +
    +              '<a href="/edit.php?alias=' + encodeURI(item.address) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    +              '<a href="/delete.php?alias=' + encodeURI(item.address) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-pencil"></span> ' + lang.remove + '</a>' +
    +              '</div>';
    +            item.chkbox = '<input type="checkbox" data-id="alias" name="multi_select" value="' + item.address + '" />';
    +            if (item.is_catch_all == 1) {
    +              item.address = '<div class="label label-default">Catch-All</div> ' + item.address;
    +            }
    +            if (item.in_primary_domain !== "") {
    +              item.domain = "↳ " + item.domain + " (" + item.in_primary_domain + ")";
                 }
               });
             }
    -      });
    -
    -      $(document).on('click', '#delete_selected_alias', function(e) {
    -        e.preventDefault();
    -        if (Object.keys(selected_aliases).length !== 0) {
    -          $(document).on('show.bs.modal','#ConfirmDeleteModal', function () {
    -            $("#ItemsToDelete").empty();
    -            for (var i in selected_aliases) {
    -              $("#ItemsToDelete").append("<li>" + selected_aliases[i] + "</li>");
    -            }
    -          })
    -          $('#ConfirmDeleteModal').modal({
    -            backdrop: 'static',
    -            keyboard: false
    -          })
    -          .one('click', '#IsConfirmed', function(e) {
    -            $.ajax({
    -              type: "POST",
    -              dataType: "json",
    -              data: { "address": JSON.stringify(selected_aliases) },
    -              url: '/api/v1/delete/alias',
    -              jsonp: false,
    -              complete: function (data) {
    -              window.location.href = window.location.href;
    -              }
    -            });
    -          })
    -          .one('click', '#isCanceled', function(e) {
    -            $('#ConfirmDeleteModal').modal('hide');
    -          });;
    +      }),
    +      "paging": {
    +        "enabled": true,
    +        "limit": 5,
    +        "size": pagination_size
    +      },
    +      "filtering": {
    +        "enabled": true,
    +        "position": "left",
    +        "placeholder": lang.filter_table
    +      },
    +      "sorting": {
    +        "enabled": true
    +      }
    +    });
    +  }
     
    +  function draw_aliasdomain_table() {
    +    ft_aliasdomain_table = FooTable.init('#aliasdomain_table', {
    +      "columns": [
    +        {"name":"chkbox","title":"","style":{"maxWidth":"40px","width":"40px"},"filterable": false,"sortable": false,"type":"html"},
    +        {"sorted": true,"name":"alias_domain","title":lang.alias,"style":{"width":"250px"}},
    +        {"name":"target_domain","title":lang.target_domain},
    +        {"name":"active","filterable": false,"style":{"maxWidth":"50px","width":"70px"},"title":lang.active},
    +        {"name":"action","filterable": false,"sortable": false,"style":{"text-align":"right","maxWidth":"180px","width":"180px"},"type":"html","title":lang.action,"breakpoints":"xs sm"}
    +      ],
    +      "empty": lang.empty,
    +      "rows": $.ajax({
    +        dataType: 'json',
    +        url: '/api/v1/get/alias-domain/all',
    +        jsonp: false,
    +        error: function () {
    +          alert('Cannot draw alias domain table');
    +        },
    +        success: function (data) {
    +          $.each(data, function (i, item) {
    +            item.action = '<div class="btn-group">' +
    +              '<a href="/edit.php?aliasdomain=' + encodeURI(item.alias_domain) + '" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> ' + lang.edit + '</a>' +
    +              '<a href="/delete.php?aliasdomain=' + encodeURI(item.alias_domain) + '" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-trash"></span> ' + lang.remove + '</a>' +
    +              '</div>';
    +            item.chkbox = '<input type="checkbox" data-id="alias-domain" name="multi_select" value="' + item.alias_domain + '" />';
    +          });
             }
    -      });
    +      }),
    +      "paging": {
    +        "enabled": true,
    +        "limit": 5,
    +        "size": pagination_size
    +      },
    +      "filtering": {
    +        "enabled": true,
    +        "position": "left",
    +        "placeholder": lang.filter_table
    +      },
    +      "sorting": {
    +        "enabled": true
    +      }
    +    });
    +  }
     
    -    }
    -
    -  });
    -});
    +  draw_domain_table();
    +  draw_mailbox_table();
    +  draw_resource_table();
    +  draw_alias_table();
    +  draw_aliasdomain_table();
    +});
    \ No newline at end of file
    diff --git a/data/web/js/notify.min.js b/data/web/js/notify.min.js
    deleted file mode 100644
    index 6766fd1d..00000000
    --- a/data/web/js/notify.min.js
    +++ /dev/null
    @@ -1 +0,0 @@
    -(function(e){typeof define=="function"&&define.amd?define(["jquery"],e):typeof module=="object"&&module.exports?module.exports=function(t,n){return n===undefined&&(typeof window!="undefined"?n=require("jquery"):n=require("jquery")(t)),e(n),n}:e(jQuery)})(function(e){function A(t,n,i){typeof i=="string"&&(i={className:i}),this.options=E(w,e.isPlainObject(i)?i:{}),this.loadHTML(),this.wrapper=e(h.html),this.options.clickToHide&&this.wrapper.addClass(r+"-hidable"),this.wrapper.data(r,this),this.arrow=this.wrapper.find("."+r+"-arrow"),this.container=this.wrapper.find("."+r+"-container"),this.container.append(this.userContainer),t&&t.length&&(this.elementType=t.attr("type"),this.originalElement=t,this.elem=N(t),this.elem.data(r,this),this.elem.before(this.wrapper)),this.container.hide(),this.run(n)}var t=[].indexOf||function(e){for(var t=0,n=this.length;t<n;t++)if(t in this&&this[t]===e)return t;return-1},n="notify",r=n+"js",i=n+"!blank",s={t:"top",m:"middle",b:"bottom",l:"left",c:"center",r:"right"},o=["l","c","r"],u=["t","m","b"],a=["t","b","l","r"],f={t:"b",m:null,b:"t",l:"r",c:null,r:"l"},l=function(t){var n;return n=[],e.each(t.split(/\W+/),function(e,t){var r;r=t.toLowerCase().charAt(0);if(s[r])return n.push(r)}),n},c={},h={name:"core",html:'<div class="'+r+'-wrapper">\n	<div class="'+r+'-arrow"></div>\n	<div class="'+r+'-container"></div>\n</div>',css:"."+r+"-corner {\n	position: fixed;\n	margin: 5px;\n	z-index: 1050;\n}\n\n."+r+"-corner ."+r+"-wrapper,\n."+r+"-corner ."+r+"-container {\n	position: relative;\n	display: block;\n	height: inherit;\n	width: inherit;\n	margin: 3px;\n}\n\n."+r+"-wrapper {\n	z-index: 1;\n	position: absolute;\n	display: inline-block;\n	height: 0;\n	width: 0;\n}\n\n."+r+"-container {\n	display: none;\n	z-index: 1;\n	position: absolute;\n}\n\n."+r+"-hidable {\n	cursor: pointer;\n}\n\n[data-notify-text],[data-notify-html] {\n	position: relative;\n}\n\n."+r+"-arrow {\n	position: absolute;\n	z-index: 2;\n	width: 0;\n	height: 0;\n}"},p={"border-radius":["-webkit-","-moz-"]},d=function(e){return c[e]},v=function(e){if(!e)throw"Missing Style name";c[e]&&delete c[e]},m=function(t,i){if(!t)throw"Missing Style name";if(!i)throw"Missing Style definition";if(!i.html)throw"Missing Style HTML";var s=c[t];s&&s.cssElem&&(window.console&&console.warn(n+": overwriting style '"+t+"'"),c[t].cssElem.remove()),i.name=t,c[t]=i;var o="";i.classes&&e.each(i.classes,function(t,n){return o+="."+r+"-"+i.name+"-"+t+" {\n",e.each(n,function(t,n){return p[t]&&e.each(p[t],function(e,r){return o+="	"+r+t+": "+n+";\n"}),o+="	"+t+": "+n+";\n"}),o+="}\n"}),i.css&&(o+="/* styles for "+i.name+" */\n"+i.css),o&&(i.cssElem=g(o),i.cssElem.attr("id","notify-"+i.name));var u={},a=e(i.html);y("html",a,u),y("text",a,u),i.fields=u},g=function(t){var n,r,i;r=x("style"),r.attr("type","text/css"),e("head").append(r);try{r.html(t)}catch(s){r[0].styleSheet.cssText=t}return r},y=function(t,n,r){var s;return t!=="html"&&(t="text"),s="data-notify-"+t,b(n,"["+s+"]").each(function(){var n;n=e(this).attr(s),n||(n=i),r[n]=t})},b=function(e,t){return e.is(t)?e:e.find(t)},w={clickToHide:!0,autoHide:!0,autoHideDelay:5e3,arrowShow:!0,arrowSize:5,breakNewLines:!0,elementPosition:"bottom",globalPosition:"top right",style:"bootstrap",className:"error",showAnimation:"slideDown",showDuration:400,hideAnimation:"slideUp",hideDuration:200,gap:5},E=function(t,n){var r;return r=function(){},r.prototype=t,e.extend(!0,new r,n)},S=function(t){return e.extend(w,t)},x=function(t){return e("<"+t+"></"+t+">")},T={},N=function(t){var n;return t.is("[type=radio]")&&(n=t.parents("form:first").find("[type=radio]").filter(function(n,r){return e(r).attr("name")===t.attr("name")}),t=n.first()),t},C=function(e,t,n){var r,i;if(typeof n=="string")n=parseInt(n,10);else if(typeof n!="number")return;if(isNaN(n))return;return r=s[f[t.charAt(0)]],i=t,e[r]!==undefined&&(t=s[r.charAt(0)],n=-n),e[t]===undefined?e[t]=n:e[t]+=n,null},k=function(e,t,n){if(e==="l"||e==="t")return 0;if(e==="c"||e==="m")return n/2-t/2;if(e==="r"||e==="b")return n-t;throw"Invalid alignment"},L=function(e){return L.e=L.e||x("div"),L.e.text(e).html()};A.prototype.loadHTML=function(){var t;t=this.getStyle(),this.userContainer=e(t.html),this.userFields=t.fields},A.prototype.show=function(e,t){var n,r,i,s,o;r=function(n){return function(){!e&&!n.elem&&n.destroy();if(t)return t()}}(this),o=this.container.parent().parents(":hidden").length>0,i=this.container.add(this.arrow),n=[];if(o&&e)s="show";else if(o&&!e)s="hide";else if(!o&&e)s=this.options.showAnimation,n.push(this.options.showDuration);else{if(!!o||!!e)return r();s=this.options.hideAnimation,n.push(this.options.hideDuration)}return n.push(r),i[s].apply(i,n)},A.prototype.setGlobalPosition=function(){var t=this.getPosition(),n=t[0],i=t[1],o=s[n],u=s[i],a=n+"|"+i,f=T[a];if(!f||!document.body.contains(f[0])){f=T[a]=x("div");var l={};l[o]=0,u==="middle"?l.top="45%":u==="center"?l.left="45%":l[u]=0,f.css(l).addClass(r+"-corner"),e("body").append(f)}return f.prepend(this.wrapper)},A.prototype.setElementPosition=function(){var n,r,i,l,c,h,p,d,v,m,g,y,b,w,E,S,x,T,N,L,A,O,M,_,D,P,H,B,j;H=this.getPosition(),_=H[0],O=H[1],M=H[2],g=this.elem.position(),d=this.elem.outerHeight(),y=this.elem.outerWidth(),v=this.elem.innerHeight(),m=this.elem.innerWidth(),j=this.wrapper.position(),c=this.container.height(),h=this.container.width(),T=s[_],L=f[_],A=s[L],p={},p[A]=_==="b"?d:_==="r"?y:0,C(p,"top",g.top-j.top),C(p,"left",g.left-j.left),B=["top","left"];for(w=0,S=B.length;w<S;w++)D=B[w],N=parseInt(this.elem.css("margin-"+D),10),N&&C(p,D,N);b=Math.max(0,this.options.gap-(this.options.arrowShow?i:0)),C(p,A,b);if(!this.options.arrowShow)this.arrow.hide();else{i=this.options.arrowSize,r=e.extend({},p),n=this.userContainer.css("border-color")||this.userContainer.css("border-top-color")||this.userContainer.css("background-color")||"white";for(E=0,x=a.length;E<x;E++){D=a[E],P=s[D];if(D===L)continue;l=P===T?n:"transparent",r["border-"+P]=i+"px solid "+l}C(p,s[L],i),t.call(a,O)>=0&&C(r,s[O],i*2)}t.call(u,_)>=0?(C(p,"left",k(O,h,y)),r&&C(r,"left",k(O,i,m))):t.call(o,_)>=0&&(C(p,"top",k(O,c,d)),r&&C(r,"top",k(O,i,v))),this.container.is(":visible")&&(p.display="block"),this.container.removeAttr("style").css(p);if(r)return this.arrow.removeAttr("style").css(r)},A.prototype.getPosition=function(){var e,n,r,i,s,f,c,h;h=this.options.position||(this.elem?this.options.elementPosition:this.options.globalPosition),e=l(h),e.length===0&&(e[0]="b");if(n=e[0],t.call(a,n)<0)throw"Must be one of ["+a+"]";if(e.length===1||(r=e[0],t.call(u,r)>=0)&&(i=e[1],t.call(o,i)<0)||(s=e[0],t.call(o,s)>=0)&&(f=e[1],t.call(u,f)<0))e[1]=(c=e[0],t.call(o,c)>=0)?"m":"l";return e.length===2&&(e[2]=e[1]),e},A.prototype.getStyle=function(e){var t;e||(e=this.options.style),e||(e="default"),t=c[e];if(!t)throw"Missing style: "+e;return t},A.prototype.updateClasses=function(){var t,n;return t=["base"],e.isArray(this.options.className)?t=t.concat(this.options.className):this.options.className&&t.push(this.options.className),n=this.getStyle(),t=e.map(t,function(e){return r+"-"+n.name+"-"+e}).join(" "),this.userContainer.attr("class",t)},A.prototype.run=function(t,n){var r,s,o,u,a;e.isPlainObject(n)?e.extend(this.options,n):e.type(n)==="string"&&(this.options.className=n);if(this.container&&!t){this.show(!1);return}if(!this.container&&!t)return;s={},e.isPlainObject(t)?s=t:s[i]=t;for(o in s){r=s[o],u=this.userFields[o];if(!u)continue;u==="text"&&(r=L(r),this.options.breakNewLines&&(r=r.replace(/\n/g,"<br/>"))),a=o===i?"":"="+o,b(this.userContainer,"[data-notify-"+u+a+"]").html(r)}this.updateClasses(),this.elem?this.setElementPosition():this.setGlobalPosition(),this.show(!0),this.options.autoHide&&(clearTimeout(this.autohideTimer),this.autohideTimer=setTimeout(this.show.bind(this,!1),this.options.autoHideDelay))},A.prototype.destroy=function(){this.wrapper.data(r,null),this.wrapper.remove()},e[n]=function(t,r,i){return t&&t.nodeName||t.jquery?e(t)[n](r,i):(i=r,r=t,new A(null,r,i)),t},e.fn[n]=function(t,n){return e(this).each(function(){var i=N(e(this)).data(r);i&&i.destroy();var s=new A(e(this),t,n)}),this},e.extend(e[n],{defaults:S,addStyle:m,removeStyle:v,pluginOptions:w,getStyle:d,insertCSS:g}),m("bootstrap",{html:"<div>\n<span data-notify-text></span>\n</div>",classes:{base:{"font-weight":"bold",padding:"8px 15px 8px 14px","text-shadow":"0 1px 0 rgba(255, 255, 255, 0.5)","background-color":"#fcf8e3",border:"1px solid #fbeed5","border-radius":"4px","white-space":"nowrap","padding-left":"25px","background-repeat":"no-repeat","background-position":"3px 7px"},error:{color:"#B94A48","background-color":"#F2DEDE","border-color":"#EED3D7","background-image":"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAtRJREFUeNqkVc1u00AQHq+dOD+0poIQfkIjalW0SEGqRMuRnHos3DjwAH0ArlyQeANOOSMeAA5VjyBxKBQhgSpVUKKQNGloFdw4cWw2jtfMOna6JOUArDTazXi/b3dm55socPqQhFka++aHBsI8GsopRJERNFlY88FCEk9Yiwf8RhgRyaHFQpPHCDmZG5oX2ui2yilkcTT1AcDsbYC1NMAyOi7zTX2Agx7A9luAl88BauiiQ/cJaZQfIpAlngDcvZZMrl8vFPK5+XktrWlx3/ehZ5r9+t6e+WVnp1pxnNIjgBe4/6dAysQc8dsmHwPcW9C0h3fW1hans1ltwJhy0GxK7XZbUlMp5Ww2eyan6+ft/f2FAqXGK4CvQk5HueFz7D6GOZtIrK+srupdx1GRBBqNBtzc2AiMr7nPplRdKhb1q6q6zjFhrklEFOUutoQ50xcX86ZlqaZpQrfbBdu2R6/G19zX6XSgh6RX5ubyHCM8nqSID6ICrGiZjGYYxojEsiw4PDwMSL5VKsC8Yf4VRYFzMzMaxwjlJSlCyAQ9l0CW44PBADzXhe7xMdi9HtTrdYjFYkDQL0cn4Xdq2/EAE+InCnvADTf2eah4Sx9vExQjkqXT6aAERICMewd/UAp/IeYANM2joxt+q5VI+ieq2i0Wg3l6DNzHwTERPgo1ko7XBXj3vdlsT2F+UuhIhYkp7u7CarkcrFOCtR3H5JiwbAIeImjT/YQKKBtGjRFCU5IUgFRe7fF4cCNVIPMYo3VKqxwjyNAXNepuopyqnld602qVsfRpEkkz+GFL1wPj6ySXBpJtWVa5xlhpcyhBNwpZHmtX8AGgfIExo0ZpzkWVTBGiXCSEaHh62/PoR0p/vHaczxXGnj4bSo+G78lELU80h1uogBwWLf5YlsPmgDEd4M236xjm+8nm4IuE/9u+/PH2JXZfbwz4zw1WbO+SQPpXfwG/BBgAhCNZiSb/pOQAAAAASUVORK5CYII=)"},success:{color:"#468847","background-color":"#DFF0D8","border-color":"#D6E9C6","background-image":"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAutJREFUeNq0lctPE0Ecx38zu/RFS1EryqtgJFA08YCiMZIAQQ4eRG8eDGdPJiYeTIwHTfwPiAcvXIwXLwoXPaDxkWgQ6islKlJLSQWLUraPLTv7Gme32zoF9KSTfLO7v53vZ3d/M7/fIth+IO6INt2jjoA7bjHCJoAlzCRw59YwHYjBnfMPqAKWQYKjGkfCJqAF0xwZjipQtA3MxeSG87VhOOYegVrUCy7UZM9S6TLIdAamySTclZdYhFhRHloGYg7mgZv1Zzztvgud7V1tbQ2twYA34LJmF4p5dXF1KTufnE+SxeJtuCZNsLDCQU0+RyKTF27Unw101l8e6hns3u0PBalORVVVkcaEKBJDgV3+cGM4tKKmI+ohlIGnygKX00rSBfszz/n2uXv81wd6+rt1orsZCHRdr1Imk2F2Kob3hutSxW8thsd8AXNaln9D7CTfA6O+0UgkMuwVvEFFUbbAcrkcTA8+AtOk8E6KiQiDmMFSDqZItAzEVQviRkdDdaFgPp8HSZKAEAL5Qh7Sq2lIJBJwv2scUqkUnKoZgNhcDKhKg5aH+1IkcouCAdFGAQsuWZYhOjwFHQ96oagWgRoUov1T9kRBEODAwxM2QtEUl+Wp+Ln9VRo6BcMw4ErHRYjH4/B26AlQoQQTRdHWwcd9AH57+UAXddvDD37DmrBBV34WfqiXPl61g+vr6xA9zsGeM9gOdsNXkgpEtTwVvwOklXLKm6+/p5ezwk4B+j6droBs2CsGa/gNs6RIxazl4Tc25mpTgw/apPR1LYlNRFAzgsOxkyXYLIM1V8NMwyAkJSctD1eGVKiq5wWjSPdjmeTkiKvVW4f2YPHWl3GAVq6ymcyCTgovM3FzyRiDe2TaKcEKsLpJvNHjZgPNqEtyi6mZIm4SRFyLMUsONSSdkPeFtY1n0mczoY3BHTLhwPRy9/lzcziCw9ACI+yql0VLzcGAZbYSM5CCSZg1/9oc/nn7+i8N9p/8An4JMADxhH+xHfuiKwAAAABJRU5ErkJggg==)"},info:{color:"#3A87AD","background-color":"#D9EDF7","border-color":"#BCE8F1","background-image":"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QYFAhkSsdes/QAAA8dJREFUOMvVlGtMW2UYx//POaWHXg6lLaW0ypAtw1UCgbniNOLcVOLmAjHZolOYlxmTGXVZdAnRfXQm+7SoU4mXaOaiZsEpC9FkiQs6Z6bdCnNYruM6KNBw6YWewzl9z+sHImEWv+vz7XmT95f/+3/+7wP814v+efDOV3/SoX3lHAA+6ODeUFfMfjOWMADgdk+eEKz0pF7aQdMAcOKLLjrcVMVX3xdWN29/GhYP7SvnP0cWfS8caSkfHZsPE9Fgnt02JNutQ0QYHB2dDz9/pKX8QjjuO9xUxd/66HdxTeCHZ3rojQObGQBcuNjfplkD3b19Y/6MrimSaKgSMmpGU5WevmE/swa6Oy73tQHA0Rdr2Mmv/6A1n9w9suQ7097Z9lM4FlTgTDrzZTu4StXVfpiI48rVcUDM5cmEksrFnHxfpTtU/3BFQzCQF/2bYVoNbH7zmItbSoMj40JSzmMyX5qDvriA7QdrIIpA+3cdsMpu0nXI8cV0MtKXCPZev+gCEM1S2NHPvWfP/hL+7FSr3+0p5RBEyhEN5JCKYr8XnASMT0xBNyzQGQeI8fjsGD39RMPk7se2bd5ZtTyoFYXftF6y37gx7NeUtJJOTFlAHDZLDuILU3j3+H5oOrD3yWbIztugaAzgnBKJuBLpGfQrS8wO4FZgV+c1IxaLgWVU0tMLEETCos4xMzEIv9cJXQcyagIwigDGwJgOAtHAwAhisQUjy0ORGERiELgG4iakkzo4MYAxcM5hAMi1WWG1yYCJIcMUaBkVRLdGeSU2995TLWzcUAzONJ7J6FBVBYIggMzmFbvdBV44Corg8vjhzC+EJEl8U1kJtgYrhCzgc/vvTwXKSib1paRFVRVORDAJAsw5FuTaJEhWM2SHB3mOAlhkNxwuLzeJsGwqWzf5TFNdKgtY5qHp6ZFf67Y/sAVadCaVY5YACDDb3Oi4NIjLnWMw2QthCBIsVhsUTU9tvXsjeq9+X1d75/KEs4LNOfcdf/+HthMnvwxOD0wmHaXr7ZItn2wuH2SnBzbZAbPJwpPx+VQuzcm7dgRCB57a1uBzUDRL4bfnI0RE0eaXd9W89mpjqHZnUI5Hh2l2dkZZUhOqpi2qSmpOmZ64Tuu9qlz/SEXo6MEHa3wOip46F1n7633eekV8ds8Wxjn37Wl63VVa+ej5oeEZ/82ZBETJjpJ1Rbij2D3Z/1trXUvLsblCK0XfOx0SX2kMsn9dX+d+7Kf6h8o4AIykuffjT8L20LU+w4AZd5VvEPY+XpWqLV327HR7DzXuDnD8r+ovkBehJ8i+y8YAAAAASUVORK5CYII=)"},warn:{color:"#C09853","background-color":"#FCF8E3","border-color":"#FBEED5","background-image":"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAMAAAC6V+0/AAABJlBMVEXr6eb/2oD/wi7/xjr/0mP/ykf/tQD/vBj/3o7/uQ//vyL/twebhgD/4pzX1K3z8e349vK6tHCilCWbiQymn0jGworr6dXQza3HxcKkn1vWvV/5uRfk4dXZ1bD18+/52YebiAmyr5S9mhCzrWq5t6ufjRH54aLs0oS+qD751XqPhAybhwXsujG3sm+Zk0PTwG6Shg+PhhObhwOPgQL4zV2nlyrf27uLfgCPhRHu7OmLgAafkyiWkD3l49ibiAfTs0C+lgCniwD4sgDJxqOilzDWowWFfAH08uebig6qpFHBvH/aw26FfQTQzsvy8OyEfz20r3jAvaKbhgG9q0nc2LbZxXanoUu/u5WSggCtp1anpJKdmFz/zlX/1nGJiYmuq5Dx7+sAAADoPUZSAAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfdBgUBGhh4aah5AAAAlklEQVQY02NgoBIIE8EUcwn1FkIXM1Tj5dDUQhPU502Mi7XXQxGz5uVIjGOJUUUW81HnYEyMi2HVcUOICQZzMMYmxrEyMylJwgUt5BljWRLjmJm4pI1hYp5SQLGYxDgmLnZOVxuooClIDKgXKMbN5ggV1ACLJcaBxNgcoiGCBiZwdWxOETBDrTyEFey0jYJ4eHjMGWgEAIpRFRCUt08qAAAAAElFTkSuQmCC)"}}}),e(function(){g(h.css).attr("id","core-notify"),e(document).on("click","."+r+"-hidable",function(t){e(this).trigger("notify-hide")}),e(document).on("notify-hide","."+r+"-wrapper",function(t){var n=e(this).data(r);n&&n.show(!1)})})})
    \ No newline at end of file
    diff --git a/data/web/js/noty.min.js b/data/web/js/noty.min.js
    deleted file mode 100644
    index 2cdeac52..00000000
    --- a/data/web/js/noty.min.js
    +++ /dev/null
    @@ -1,9 +0,0 @@
    -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("Noty",[],e):"object"==typeof exports?exports.Noty=e():t.Noty=e()}(this,function(){return function(t){function e(o){if(n[o])return n[o].exports;var i=n[o]={i:o,l:!1,exports:{}};return t[o].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,o){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:o})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=6)}([function(t,e,n){"use strict";function o(t,e,n){var o=void 0;if(!n){for(o in e)if(e.hasOwnProperty(o)&&e[o]===t)return!0}else for(o in e)if(e.hasOwnProperty(o)&&e[o]===t)return!0;return!1}function i(t){t=t||window.event,void 0!==t.stopPropagation?t.stopPropagation():t.cancelBubble=!0}function r(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",e="noty_"+t+"_";return e+="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function s(t){var e=t.offsetHeight,n=window.getComputedStyle(t);return e+=parseInt(n.marginTop)+parseInt(n.marginBottom)}function u(t,e,n){var o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];e=e.split(" ");for(var i=0;i<e.length;i++)document.addEventListener?t.addEventListener(e[i],n,o):document.attachEvent&&t.attachEvent("on"+e[i],n)}function a(t,e){return("string"==typeof t?t:f(t)).indexOf(" "+e+" ")>=0}function c(t,e){var n=f(t),o=n+e;a(n,e)||(t.className=o.substring(1))}function l(t,e){var n=f(t),o=void 0;a(t,e)&&(o=n.replace(" "+e+" "," "),t.className=o.substring(1,o.length-1))}function d(t){t.parentNode&&t.parentNode.removeChild(t)}function f(t){return(" "+(t&&t.className||"")+" ").replace(/\s+/gi," ")}function h(){function t(){b.PageHidden=document[s],o()}function e(){b.PageHidden=!0,o()}function n(){b.PageHidden=!1,o()}function o(){b.PageHidden?i():r()}function i(){setTimeout(function(){Object.keys(b.Store).forEach(function(t){b.Store.hasOwnProperty(t)&&b.Store[t].options.visibilityControl&&b.Store[t].stop()})},100)}function r(){setTimeout(function(){Object.keys(b.Store).forEach(function(t){b.Store.hasOwnProperty(t)&&b.Store[t].options.visibilityControl&&b.Store[t].resume()}),b.queueRenderAll()},100)}var s=void 0,a=void 0;void 0!==document.hidden?(s="hidden",a="visibilitychange"):void 0!==document.msHidden?(s="msHidden",a="msvisibilitychange"):void 0!==document.webkitHidden&&(s="webkitHidden",a="webkitvisibilitychange"),u(document,a,t),u(window,"blur",e),u(window,"focus",n)}function p(t){if(t.hasSound){var e=document.createElement("audio");t.options.sounds.sources.forEach(function(t){var n=document.createElement("source");n.src=t,n.type="audio/"+m(t),e.appendChild(n)}),t.barDom?t.barDom.appendChild(e):document.querySelector("body").appendChild(e),e.volume=t.options.sounds.volume,t.soundPlayed||(e.play(),t.soundPlayed=!0),e.onended=function(){d(e)}}}function m(t){return t.match(/\.([^.]+)$/)[1]}Object.defineProperty(e,"__esModule",{value:!0}),e.css=e.deepExtend=e.animationEndEvents=void 0;var v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};e.inArray=o,e.stopPropagation=i,e.generateID=r,e.outerHeight=s,e.addListener=u,e.hasClass=a,e.addClass=c,e.removeClass=l,e.remove=d,e.classList=f,e.visibilityChangeFlow=h,e.createAudioElements=p;var y=n(1),b=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}(y);e.animationEndEvents="webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend",e.deepExtend=function t(e){e=e||{};for(var n=1;n<arguments.length;n++){var o=arguments[n];if(o)for(var i in o)o.hasOwnProperty(i)&&(Array.isArray(o[i])?e[i]=o[i]:"object"===v(o[i])&&null!==o[i]?e[i]=t(e[i],o[i]):e[i]=o[i])}return e},e.css=function(){function t(t){return t.replace(/^-ms-/,"ms-").replace(/-([\da-z])/gi,function(t,e){return e.toUpperCase()})}function e(t){var e=document.body.style;if(t in e)return t;for(var n=i.length,o=t.charAt(0).toUpperCase()+t.slice(1),r=void 0;n--;)if((r=i[n]+o)in e)return r;return t}function n(n){return n=t(n),r[n]||(r[n]=e(n))}function o(t,e,o){e=n(e),t.style[e]=o}var i=["Webkit","O","Moz","ms"],r={};return function(t,e){var n=arguments,i=void 0,r=void 0;if(2===n.length)for(i in e)e.hasOwnProperty(i)&&void 0!==(r=e[i])&&e.hasOwnProperty(i)&&o(t,i,r);else o(t,n[1],n[2])}}()},function(t,e,n){"use strict";function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"global",e=0,n=x;return E.hasOwnProperty(t)&&(n=E[t].maxVisible,Object.keys(P).forEach(function(n){P[n].options.queue!==t||P[n].closed||e++})),{current:e,maxVisible:n}}function i(t){E.hasOwnProperty(t.options.queue)||(E[t.options.queue]={maxVisible:x,queue:[]}),E[t.options.queue].queue.push(t)}function r(t){if(E.hasOwnProperty(t.options.queue)){var e=[];Object.keys(E[t.options.queue].queue).forEach(function(n){E[t.options.queue].queue[n].id!==t.id&&e.push(E[t.options.queue].queue[n])}),E[t.options.queue].queue=e}}function s(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"global";if(E.hasOwnProperty(t)){var e=E[t].queue.shift();e&&e.show()}}function u(){Object.keys(E).forEach(function(t){s(t)})}function a(t){var e=k.generateID("ghost"),n=document.createElement("div");n.setAttribute("id",e),k.css(n,{height:k.outerHeight(t.barDom)+"px"}),t.barDom.insertAdjacentHTML("afterend",n.outerHTML),k.remove(t.barDom),n=document.getElementById(e),k.addClass(n,"noty_fix_effects_height"),k.addListener(n,k.animationEndEvents,function(){k.remove(n)})}function c(t){m(t);var e='<div class="noty_body">'+t.options.text+"</div>"+d(t)+'<div class="noty_progressbar"></div>';t.barDom=document.createElement("div"),t.barDom.setAttribute("id",t.id),k.addClass(t.barDom,"noty_bar noty_type__"+t.options.type+" noty_theme__"+t.options.theme),t.barDom.innerHTML=e,b(t,"onTemplate")}function l(t){return!(!t.options.buttons||!Object.keys(t.options.buttons).length)}function d(t){if(l(t)){var e=document.createElement("div");return k.addClass(e,"noty_buttons"),Object.keys(t.options.buttons).forEach(function(n){e.appendChild(t.options.buttons[n].dom)}),t.options.buttons.forEach(function(t){e.appendChild(t.dom)}),e.outerHTML}return""}function f(t){t.options.modal&&(0===S&&p(),e.DocModalCount=S+=1)}function h(t){if(t.options.modal&&S>0&&(e.DocModalCount=S-=1,S<=0)){var n=document.querySelector(".noty_modal");n&&(k.removeClass(n,"noty_modal_open"),k.addClass(n,"noty_modal_close"),k.addListener(n,k.animationEndEvents,function(){k.remove(n)}))}}function p(){var t=document.querySelector("body"),e=document.createElement("div");k.addClass(e,"noty_modal"),t.insertBefore(e,t.firstChild),k.addClass(e,"noty_modal_open"),k.addListener(e,k.animationEndEvents,function(){k.removeClass(e,"noty_modal_open")})}function m(t){if(t.options.container)return void(t.layoutDom=document.querySelector(t.options.container));var e="noty_layout__"+t.options.layout;t.layoutDom=document.querySelector("div#"+e),t.layoutDom||(t.layoutDom=document.createElement("div"),t.layoutDom.setAttribute("id",e),k.addClass(t.layoutDom,"noty_layout"),document.querySelector("body").appendChild(t.layoutDom))}function v(t){t.options.timeout&&(t.options.progressBar&&t.progressDom&&k.css(t.progressDom,{transition:"width "+t.options.timeout+"ms linear",width:"0%"}),clearTimeout(t.closeTimer),t.closeTimer=setTimeout(function(){t.close()},t.options.timeout))}function y(t){t.options.timeout&&t.closeTimer&&(clearTimeout(t.closeTimer),t.closeTimer=-1,t.options.progressBar&&t.progressDom&&k.css(t.progressDom,{transition:"width 0ms linear",width:"100%"}))}function b(t,e){t.listeners.hasOwnProperty(e)&&t.listeners[e].forEach(function(e){"function"==typeof e&&e.apply(t)})}function w(t){b(t,"afterShow"),v(t),k.addListener(t.barDom,"mouseenter",function(){y(t)}),k.addListener(t.barDom,"mouseleave",function(){v(t)})}function g(t){delete P[t.id],t.closing=!1,b(t,"afterClose"),k.remove(t.barDom),0!==t.layoutDom.querySelectorAll(".noty_bar").length||t.options.container||k.remove(t.layoutDom),(k.inArray("docVisible",t.options.titleCount.conditions)||k.inArray("docHidden",t.options.titleCount.conditions))&&D.decrement(),s(t.options.queue)}Object.defineProperty(e,"__esModule",{value:!0}),e.Defaults=e.Store=e.Queues=e.DefaultMaxVisible=e.docTitle=e.DocModalCount=e.PageHidden=void 0,e.getQueueCounts=o,e.addToQueue=i,e.removeFromQueue=r,e.queueRender=s,e.queueRenderAll=u,e.ghostFix=a,e.build=c,e.hasButtons=l,e.handleModal=f,e.handleModalClose=h,e.queueClose=v,e.dequeueClose=y,e.fire=b,e.openFlow=w,e.closeFlow=g;var _=n(0),k=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}(_),S=(e.PageHidden=!1,e.DocModalCount=0),C={originalTitle:null,count:0,changed:!1,timer:-1},D=e.docTitle={increment:function(){C.count++,D._update()},decrement:function(){if(--C.count<=0)return void D._clear();D._update()},_update:function(){var t=document.title;C.changed?document.title="("+C.count+") "+C.originalTitle:(C.originalTitle=t,document.title="("+C.count+") "+t,C.changed=!0)},_clear:function(){C.changed&&(C.count=0,document.title=C.originalTitle,C.changed=!1)}},x=e.DefaultMaxVisible=5,E=e.Queues={global:{maxVisible:x,queue:[]}},P=e.Store={};e.Defaults={type:"alert",layout:"topRight",theme:"mint",text:"",timeout:!1,progressBar:!0,closeWith:["click"],animation:{open:"noty_effects_open",close:"noty_effects_close"},id:!1,force:!1,killer:!1,queue:"global",container:!1,buttons:[],callbacks:{beforeShow:null,onShow:null,afterShow:null,onClose:null,afterClose:null,onHover:null,onTemplate:null},sounds:{sources:[],volume:1,conditions:[]},titleCount:{conditions:[]},modal:!1,visibilityControl:!0}},function(t,e,n){"use strict";function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.NotyButton=void 0;var i=n(0),r=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}(i);e.NotyButton=function t(e,n,i){var s=this,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return o(this,t),this.dom=document.createElement("button"),this.dom.innerHTML=e,this.id=u.id=u.id||r.generateID("button"),this.cb=i,Object.keys(u).forEach(function(t){s.dom.setAttribute(t,u[t])}),r.addClass(this.dom,n||"noty_btn"),this}},function(t,e,n){"use strict";function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}return function(e,n,o){return n&&t(e.prototype,n),o&&t(e,o),e}}();e.Push=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/service-worker.js";return o(this,t),this.subData={},this.workerPath=e,this.listeners={onPermissionGranted:[],onPermissionDenied:[],onSubscriptionSuccess:[],onSubscriptionCancel:[],onWorkerError:[],onWorkerSuccess:[],onWorkerNotSupported:[]},this}return i(t,[{key:"on",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){};return"function"==typeof e&&this.listeners.hasOwnProperty(t)&&this.listeners[t].push(e),this}},{key:"fire",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.listeners.hasOwnProperty(t)&&this.listeners[t].forEach(function(t){"function"==typeof t&&t.apply(e,n)})}},{key:"create",value:function(){console.log("NOT IMPLEMENTED YET")}},{key:"isSupported",value:function(){var t=!1;try{t=window.Notification||window.webkitNotifications||navigator.mozNotification||window.external&&void 0!==window.external.msIsSiteMode()}catch(t){}return t}},{key:"getPermissionStatus",value:function(){var t="default";if(window.Notification&&window.Notification.permissionLevel)t=window.Notification.permissionLevel;else if(window.webkitNotifications&&window.webkitNotifications.checkPermission)switch(window.webkitNotifications.checkPermission()){case 1:t="default";break;case 0:t="granted";break;default:t="denied"}else window.Notification&&window.Notification.permission?t=window.Notification.permission:navigator.mozNotification?t="granted":window.external&&void 0!==window.external.msIsSiteMode()&&(t=window.external.msIsSiteMode()?"granted":"default");return t.toString().toLowerCase()}},{key:"getEndpoint",value:function(t){var e=t.endpoint,n=t.subscriptionId;return n&&-1===e.indexOf(n)&&(e+="/"+n),e}},{key:"isSWRegistered",value:function(){try{return"activated"===navigator.serviceWorker.controller.state}catch(t){return!1}}},{key:"unregisterWorker",value:function(){var t=this;"serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(function(e){var n=!0,o=!1,i=void 0;try{for(var r,s=e[Symbol.iterator]();!(n=(r=s.next()).done);n=!0){r.value.unregister(),t.fire("onSubscriptionCancel")}}catch(t){o=!0,i=t}finally{try{!n&&s.return&&s.return()}finally{if(o)throw i}}})}},{key:"requestSubscription",value:function(){var t=this,e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=this,o=this.getPermissionStatus(),i=function(o){"granted"===o?(t.fire("onPermissionGranted"),"serviceWorker"in navigator?navigator.serviceWorker.register(t.workerPath).then(function(){navigator.serviceWorker.ready.then(function(t){n.fire("onWorkerSuccess"),t.pushManager.subscribe({userVisibleOnly:e}).then(function(t){var e=t.getKey("p256dh"),o=t.getKey("auth");n.subData={endpoint:n.getEndpoint(t),p256dh:e?window.btoa(String.fromCharCode.apply(null,new Uint8Array(e))):null,auth:o?window.btoa(String.fromCharCode.apply(null,new Uint8Array(o))):null},n.fire("onSubscriptionSuccess",[n.subData])}).catch(function(t){n.fire("onWorkerError",[t])})})}):n.fire("onWorkerNotSupported")):"denied"===o&&(t.fire("onPermissionDenied"),t.unregisterWorker())};"default"===o?window.Notification&&window.Notification.requestPermission?window.Notification.requestPermission(i):window.webkitNotifications&&window.webkitNotifications.checkPermission&&window.webkitNotifications.requestPermission(i):i(o)}}]),t}()},function(t,e,n){(function(e,o){/*!
    - * @overview es6-promise - a tiny implementation of Promises/A+.
    - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
    - * @license   Licensed under MIT license
    - *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
    - * @version   4.1.0
    - */
    -!function(e,n){t.exports=n()}(0,function(){"use strict";function t(t){return"function"==typeof t||"object"==typeof t&&null!==t}function i(t){return"function"==typeof t}function r(t){z=t}function s(t){U=t}function u(){return void 0!==R?function(){R(c)}:a()}function a(){var t=setTimeout;return function(){return t(c,1)}}function c(){for(var t=0;t<Q;t+=2){(0,X[t])(X[t+1]),X[t]=void 0,X[t+1]=void 0}Q=0}function l(t,e){var n=arguments,o=this,i=new this.constructor(f);void 0===i[tt]&&A(i);var r=o._state;return r?function(){var t=n[r-1];U(function(){return P(r,i,t,o._result)})}():C(o,i,t,e),i}function d(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var n=new e(f);return g(n,t),n}function f(){}function h(){return new TypeError("You cannot resolve a promise with itself")}function p(){return new TypeError("A promises callback cannot return that same promise.")}function m(t){try{return t.then}catch(t){return it.error=t,it}}function v(t,e,n,o){try{t.call(e,n,o)}catch(t){return t}}function y(t,e,n){U(function(t){var o=!1,i=v(n,e,function(n){o||(o=!0,e!==n?g(t,n):k(t,n))},function(e){o||(o=!0,S(t,e))},"Settle: "+(t._label||" unknown promise"));!o&&i&&(o=!0,S(t,i))},t)}function b(t,e){e._state===nt?k(t,e._result):e._state===ot?S(t,e._result):C(e,void 0,function(e){return g(t,e)},function(e){return S(t,e)})}function w(t,e,n){e.constructor===t.constructor&&n===l&&e.constructor.resolve===d?b(t,e):n===it?(S(t,it.error),it.error=null):void 0===n?k(t,e):i(n)?y(t,e,n):k(t,e)}function g(e,n){e===n?S(e,h()):t(n)?w(e,n,m(n)):k(e,n)}function _(t){t._onerror&&t._onerror(t._result),D(t)}function k(t,e){t._state===et&&(t._result=e,t._state=nt,0!==t._subscribers.length&&U(D,t))}function S(t,e){t._state===et&&(t._state=ot,t._result=e,U(_,t))}function C(t,e,n,o){var i=t._subscribers,r=i.length;t._onerror=null,i[r]=e,i[r+nt]=n,i[r+ot]=o,0===r&&t._state&&U(D,t)}function D(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var o=void 0,i=void 0,r=t._result,s=0;s<e.length;s+=3)o=e[s],i=e[s+n],o?P(n,o,i,r):i(r);t._subscribers.length=0}}function x(){this.error=null}function E(t,e){try{return t(e)}catch(t){return rt.error=t,rt}}function P(t,e,n,o){var r=i(n),s=void 0,u=void 0,a=void 0,c=void 0;if(r){if(s=E(n,o),s===rt?(c=!0,u=s.error,s.error=null):a=!0,e===s)return void S(e,p())}else s=o,a=!0;e._state!==et||(r&&a?g(e,s):c?S(e,u):t===nt?k(e,s):t===ot&&S(e,s))}function T(t,e){try{e(function(e){g(t,e)},function(e){S(t,e)})}catch(e){S(t,e)}}function O(){return st++}function A(t){t[tt]=st++,t._state=void 0,t._result=void 0,t._subscribers=[]}function M(t,e){this._instanceConstructor=t,this.promise=new t(f),this.promise[tt]||A(this.promise),I(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?k(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&k(this.promise,this._result))):S(this.promise,q())}function q(){return new Error("Array Methods must be provided an Array")}function j(t){return new M(this,t).promise}function N(t){var e=this;return new e(I(t)?function(n,o){for(var i=t.length,r=0;r<i;r++)e.resolve(t[r]).then(n,o)}:function(t,e){return e(new TypeError("You must pass an array to race."))})}function H(t){var e=this,n=new e(f);return S(n,t),n}function L(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function W(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function V(t){this[tt]=O(),this._result=this._state=void 0,this._subscribers=[],f!==t&&("function"!=typeof t&&L(),this instanceof V?T(this,t):W())}function B(){var t=void 0;if(void 0!==o)t=o;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(t){throw new Error("polyfill failed because global object is unavailable in this environment")}var e=t.Promise;if(e){var n=null;try{n=Object.prototype.toString.call(e.resolve())}catch(t){}if("[object Promise]"===n&&!e.cast)return}t.Promise=V}var F=void 0;F=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var I=F,Q=0,R=void 0,z=void 0,U=function(t,e){X[Q]=t,X[Q+1]=e,2===(Q+=2)&&(z?z(c):Z())},Y="undefined"!=typeof window?window:void 0,K=Y||{},G=K.MutationObserver||K.WebKitMutationObserver,$="undefined"==typeof self&&void 0!==e&&"[object process]"==={}.toString.call(e),J="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,X=new Array(1e3),Z=void 0;Z=$?function(){return function(){return e.nextTick(c)}}():G?function(){var t=0,e=new G(c),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}():J?function(){var t=new MessageChannel;return t.port1.onmessage=c,function(){return t.port2.postMessage(0)}}():void 0===Y?function(){try{var t=n(9);return R=t.runOnLoop||t.runOnContext,u()}catch(t){return a()}}():a();var tt=Math.random().toString(36).substring(16),et=void 0,nt=1,ot=2,it=new x,rt=new x,st=0;return M.prototype._enumerate=function(){for(var t=this.length,e=this._input,n=0;this._state===et&&n<t;n++)this._eachEntry(e[n],n)},M.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,o=n.resolve;if(o===d){var i=m(t);if(i===l&&t._state!==et)this._settledAt(t._state,e,t._result);else if("function"!=typeof i)this._remaining--,this._result[e]=t;else if(n===V){var r=new n(f);w(r,t,i),this._willSettleAt(r,e)}else this._willSettleAt(new n(function(e){return e(t)}),e)}else this._willSettleAt(o(t),e)},M.prototype._settledAt=function(t,e,n){var o=this.promise;o._state===et&&(this._remaining--,t===ot?S(o,n):this._result[e]=n),0===this._remaining&&k(o,this._result)},M.prototype._willSettleAt=function(t,e){var n=this;C(t,void 0,function(t){return n._settledAt(nt,e,t)},function(t){return n._settledAt(ot,e,t)})},V.all=j,V.race=N,V.resolve=d,V.reject=H,V._setScheduler=r,V._setAsap=s,V._asap=U,V.prototype={constructor:V,then:l,catch:function(t){return this.then(null,t)}},V.polyfill=B,V.Promise=V,V})}).call(e,n(7),n(8))},function(t,e){},function(t,e,n){"use strict";function o(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}return function(e,n,o){return n&&t(e.prototype,n),o&&t(e,o),e}}();n(5);var s=n(4),u=function(t){return t&&t.__esModule?t:{default:t}}(s),a=n(0),c=o(a),l=n(1),d=o(l),f=n(2),h=n(3),p=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return i(this,t),this.options=c.deepExtend({},d.Defaults,e),this.id=this.options.id||c.generateID("bar"),this.closeTimer=-1,this.barDom=null,this.layoutDom=null,this.progressDom=null,this.showing=!1,this.shown=!1,this.closed=!1,this.closing=!1,this.killable=this.options.timeout||this.options.closeWith.length>0,this.hasSound=this.options.sounds.sources.length>0,this.soundPlayed=!1,this.listeners={beforeShow:[],onShow:[],afterShow:[],onClose:[],afterClose:[],onHover:[],onTemplate:[]},this.promises={show:null,close:null},this.on("beforeShow",this.options.callbacks.beforeShow),this.on("onShow",this.options.callbacks.onShow),this.on("afterShow",this.options.callbacks.afterShow),this.on("onClose",this.options.callbacks.onClose),this.on("afterClose",this.options.callbacks.afterClose),this.on("onHover",this.options.callbacks.onHover),this.on("onTemplate",this.options.callbacks.onTemplate),this}return r(t,[{key:"on",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){};return"function"==typeof e&&this.listeners.hasOwnProperty(t)&&this.listeners[t].push(e),this}},{key:"show",value:function(){var e=this;if(!0!==this.options.killer||d.PageHidden)if("string"!=typeof this.options.killer||d.PageHidden){var n=d.getQueueCounts(this.options.queue);if(n.current>=n.maxVisible||d.PageHidden)return d.addToQueue(this),d.PageHidden&&this.hasSound&&c.inArray("docHidden",this.options.sounds.conditions)&&c.createAudioElements(this),d.PageHidden&&c.inArray("docHidden",this.options.titleCount.conditions)&&d.docTitle.increment(),this}else t.closeAll(this.options.killer);else t.closeAll();if(d.Store[this.id]=this,d.fire(this,"beforeShow"),this.showing=!0,this.closing)return this.showing=!1,this;if(d.build(this),d.handleModal(this),this.options.force?this.layoutDom.insertBefore(this.barDom,this.layoutDom.firstChild):this.layoutDom.appendChild(this.barDom),this.hasSound&&!this.soundPlayed&&c.inArray("docVisible",this.options.sounds.conditions)&&c.createAudioElements(this),c.inArray("docVisible",this.options.titleCount.conditions)&&d.docTitle.increment(),this.shown=!0,this.closed=!1,d.hasButtons(this)&&Object.keys(this.options.buttons).forEach(function(t){var n=e.barDom.querySelector("#"+e.options.buttons[t].id);c.addListener(n,"click",function(n){c.stopPropagation(n),e.options.buttons[t].cb()})}),this.progressDom=this.barDom.querySelector(".noty_progressbar"),c.inArray("click",this.options.closeWith)&&(c.addClass(this.barDom,"noty_close_with_click"),c.addListener(this.barDom,"click",function(t){c.stopPropagation(t),e.close()},!1)),c.addListener(this.barDom,"mouseenter",function(){d.fire(e,"onHover")},!1),this.options.timeout&&c.addClass(this.barDom,"noty_has_timeout"),c.inArray("button",this.options.closeWith)){c.addClass(this.barDom,"noty_close_with_button");var o=document.createElement("div");c.addClass(o,"noty_close_button"),o.innerHTML="×",this.barDom.appendChild(o),c.addListener(o,"click",function(t){c.stopPropagation(t),e.close()},!1)}return d.fire(this,"onShow"),null===this.options.animation.open?this.promises.show=new u.default(function(t){t()}):"function"==typeof this.options.animation.open?this.promises.show=new u.default(this.options.animation.open.bind(this)):(c.addClass(this.barDom,this.options.animation.open),this.promises.show=new u.default(function(t){c.addListener(e.barDom,c.animationEndEvents,function(){c.removeClass(e.barDom,e.options.animation.open),t()})})),this.promises.show.then(function(){var t=e;setTimeout(function(){d.openFlow(t)},100)}),this}},{key:"stop",value:function(){return d.dequeueClose(this),this}},{key:"resume",value:function(){return d.queueClose(this),this}},{key:"setTimeout",value:function(t){function e(e){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}(function(t){if(this.stop(),this.options.timeout=t,this.barDom){this.options.timeout?c.addClass(this.barDom,"noty_has_timeout"):c.removeClass(this.barDom,"noty_has_timeout");var e=this;setTimeout(function(){e.resume()},100)}return this})},{key:"setText",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.barDom&&(this.barDom.querySelector(".noty_body").innerHTML=t),e&&(this.options.text=t),this}},{key:"setType",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.barDom){c.classList(this.barDom).split(" ").forEach(function(t){"noty_type__"===t.substring(0,11)&&c.removeClass(e.barDom,t)}),c.addClass(this.barDom,"noty_type__"+t)}return n&&(this.options.type=t),this}},{key:"setTheme",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.barDom){c.classList(this.barDom).split(" ").forEach(function(t){"noty_theme__"===t.substring(0,12)&&c.removeClass(e.barDom,t)}),c.addClass(this.barDom,"noty_theme__"+t)}return n&&(this.options.theme=t),this}},{key:"close",value:function(){var t=this;return this.closed?this:this.shown?(d.fire(this,"onClose"),this.closing=!0,null===this.options.animation.close?this.promises.close=new u.default(function(t){t()}):"function"==typeof this.options.animation.close?this.promises.close=new u.default(this.options.animation.close.bind(this)):(c.addClass(this.barDom,this.options.animation.close),this.promises.close=new u.default(function(e){c.addListener(t.barDom,c.animationEndEvents,function(){t.options.force?c.remove(t.barDom):d.ghostFix(t),e()})})),this.promises.close.then(function(){d.closeFlow(t),d.handleModalClose(t)}),this.closed=!0,this):(d.removeFromQueue(this),this)}}],[{key:"closeAll",value:function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Object.keys(d.Store).forEach(function(e){t?d.Store[e].options.queue===t&&d.Store[e].killable&&d.Store[e].close():d.Store[e].killable&&d.Store[e].close()}),this}},{key:"overrideDefaults",value:function(t){return d.Defaults=c.deepExtend({},d.Defaults,t),this}},{key:"setMaxVisible",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:d.DefaultMaxVisible,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"global";return d.Queues.hasOwnProperty(e)||(d.Queues[e]={maxVisible:t,queue:[]}),d.Queues[e].maxVisible=t,this}},{key:"button",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return new f.NotyButton(t,e,n,o)}},{key:"version",value:function(){return"3.1.0"}},{key:"Push",value:function(t){return new h.Push(t)}}]),t}();e.default=p,c.visibilityChangeFlow(),t.exports=e.default},function(t,e){function n(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function i(t){if(l===setTimeout)return setTimeout(t,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(t,0);try{return l(t,0)}catch(e){try{return l.call(null,t,0)}catch(e){return l.call(this,t,0)}}}function r(t){if(d===clearTimeout)return clearTimeout(t);if((d===o||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(t);try{return d(t)}catch(e){try{return d.call(null,t)}catch(e){return d.call(this,t)}}}function s(){m&&h&&(m=!1,h.length?p=h.concat(p):v=-1,p.length&&u())}function u(){if(!m){var t=i(s);m=!0;for(var e=p.length;e;){for(h=p,p=[];++v<e;)h&&h[v].run();v=-1,e=p.length}h=null,m=!1,r(t)}}function a(t,e){this.fun=t,this.array=e}function c(){}var l,d,f=t.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(t){l=n}try{d="function"==typeof clearTimeout?clearTimeout:o}catch(t){d=o}}();var h,p=[],m=!1,v=-1;f.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];p.push(new a(t,e)),1!==p.length||m||i(u)},a.prototype.run=function(){this.fun.apply(null,this.array)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=c,f.addListener=c,f.once=c,f.off=c,f.removeListener=c,f.removeAllListeners=c,f.emit=c,f.binding=function(t){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(t){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e){}])});
    -//# sourceMappingURL=noty.min.js.map
    \ No newline at end of file
    diff --git a/data/web/json_api.php b/data/web/json_api.php
    index 3d15d3f3..99dd1f16 100644
    --- a/data/web/json_api.php
    +++ b/data/web/json_api.php
    @@ -356,18 +356,6 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                   return;
                 }
               break;
    -          case "csrf-cookie":
    -            if (isset($_SESSION['mailcow_cc_username']) && isset($_SESSION['mailcow_cc_role'])) {
    -              csrfprotector::refreshToken();
    -              echo json_encode(array(
    -                'type' => 'success',
    -                'msg' => 'Cookie refreshed'
    -              ));
    -            }
    -            else {
    -              return;
    -            }
    -          break;
               default:
                 echo '{}';
               break;
    @@ -376,10 +364,10 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
           case "delete":
             switch ($category) {
               case "alias":
    -            if (isset($_POST['address'])) {
    -              $address = json_decode($_POST['address'], true);
    -              if (is_array($address)) {
    -                if (mailbox_delete_alias(array('address' => $address)) === false) {
    +            if (isset($_POST['items'])) {
    +              $items = (array)json_decode($_POST['items'], true);
    +              if (is_array($items)) {
    +                if (mailbox_delete_alias(array('address' => $items)) === false) {
                       if (isset($_SESSION['return'])) {
                         echo json_encode($_SESSION['return']);
                       }
    @@ -389,59 +377,79 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                           'msg' => 'Deletion of items/s failed'
                         ));
                       }
    -                  exit();
    -                }
    -                if (isset($_SESSION['return'])) {
    -                  echo json_encode($_SESSION['return']);
                     }
                     else {
    -                  echo json_encode(array(
    -                    'type' => 'success',
    -                    'msg' => 'Item/s deleted: ' . $domains
    -                  ));
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'success',
    +                      'msg' => 'Task completed'
    +                    ));
    +                  }
                     }
                   }
    -            }
    -          break;
    -          case "fwdhost":
    -            if (isset($_POST['forwardinghost'])) {
    -              $forwardinghost = (array)json_decode($_POST['forwardinghost'], true);
    -              if (is_array($forwardinghost)) {
    -                if (delete_forwarding_host(array('forwardinghost' => $forwardinghost)) === false) {
    -                  if (isset($_SESSION['return'])) {
    -                    echo json_encode($_SESSION['return']);
    -                  }
    -                  else {
    -                    echo json_encode(array(
    -                      'type' => 'error',
    -                      'msg' => 'Deletion of items/s failed'
    -                    ));
    -                  }
    -                  exit();
    -                }
    -                if (isset($_SESSION['return'])) {
    -                  echo json_encode($_SESSION['return']);
    -                }
    -                else {
    -                  echo json_encode(array(
    -                    'type' => 'success',
    -                    'msg' => 'Item/s deleted: ' . $domains
    -                  ));
    -                }
    +              else {
    +                echo json_encode(array(
    +                  'type' => 'error',
    +                  'msg' => 'Cannot find address array in post data'
    +                ));
                   }
                 }
                 else {
                   echo json_encode(array(
                     'type' => 'error',
    -                'msg' => 'Cannot find forwardinghost array in post data'
    +                'msg' => 'Cannot find items in post data'
    +              ));
    +            }
    +          break;
    +          case "fwdhost":
    +            if (isset($_POST['items'])) {
    +              $items = (array)json_decode($_POST['items'], true);
    +              if (is_array($items)) {
    +                if (delete_forwarding_host(array('forwardinghost' => $items)) === false) {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Deletion of items/s failed'
    +                    ));
    +                  }
    +                }
    +                else {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'success',
    +                      'msg' => 'Task completed'
    +                    ));
    +                  }
    +                }
    +              }
    +              else {
    +                echo json_encode(array(
    +                  'type' => 'error',
    +                  'msg' => 'Cannot find forwardinghost array in post data'
    +                ));
    +              }
    +            }
    +            else {
    +              echo json_encode(array(
    +                'type' => 'error',
    +                'msg' => 'Cannot find items in post data'
                   ));
                 }
               break;
               case "dkim":
    -            if (isset($_POST['domains'])) {
    -              $domains = (array)json_decode($_POST['domains'], true);
    -              if (is_array($domains)) {
    -                if (dkim_delete_key(array('domains' => $domains)) === false) {
    +            if (isset($_POST['items'])) {
    +              $items = (array)json_decode($_POST['items'], true);
    +              if (is_array($items)) {
    +                if (dkim_delete_key(array('domains' => $items)) === false) {
                       if (isset($_SESSION['return'])) {
                         echo json_encode($_SESSION['return']);
                       }
    @@ -451,23 +459,194 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                           'msg' => 'Deletion of items/s failed'
                         ));
                       }
    -                  exit();
    -                }
    -                if (isset($_SESSION['return'])) {
    -                  echo json_encode($_SESSION['return']);
                     }
                     else {
    -                  echo json_encode(array(
    -                    'type' => 'success',
    -                    'msg' => 'Item/s deleted: ' . $domains
    -                  ));
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'success',
    +                      'msg' => 'Task completed'
    +                    ));
    +                  }
                     }
                   }
    +              else {
    +                echo json_encode(array(
    +                  'type' => 'error',
    +                  'msg' => 'Cannot find domains array in post data'
    +                ));
    +              }
                 }
                 else {
                   echo json_encode(array(
                     'type' => 'error',
    -                'msg' => 'Cannot find domains array in post data'
    +                'msg' => 'Cannot find items in post data'
    +              ));
    +            }
    +          break;
    +          case "domain":
    +            if (isset($_POST['items'])) {
    +              $items = (array)json_decode($_POST['items'], true);
    +              if (is_array($items)) {
    +                if (mailbox_delete_domain(array('domain' => $items)) === false) {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Task failed'
    +                    ));
    +                  }
    +                }
    +                else {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'success',
    +                      'msg' => 'Task completed'
    +                    ));
    +                  }
    +                }
    +              }
    +              else {
    +                echo json_encode(array(
    +                  'type' => 'error',
    +                  'msg' => 'Cannot find domain array in post data'
    +                ));
    +              }
    +            }
    +            else {
    +              echo json_encode(array(
    +                'type' => 'error',
    +                'msg' => 'Cannot find items in post data'
    +              ));
    +            }
    +          break;
    +          case "alias-domain":
    +            if (isset($_POST['items'])) {
    +              $items = (array)json_decode($_POST['items'], true);
    +              if (is_array($items)) {
    +                if (mailbox_delete_alias_domain(array('alias_domain' => $items)) === false) {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Task failed'
    +                    ));
    +                  }
    +                }
    +                else {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'success',
    +                      'msg' => 'Task completed'
    +                    ));
    +                  }
    +                }
    +              }
    +              else {
    +                echo json_encode(array(
    +                  'type' => 'error',
    +                  'msg' => 'Cannot find alias_domain array in post data'
    +                ));
    +              }
    +            }
    +            else {
    +              echo json_encode(array(
    +                'type' => 'error',
    +                'msg' => 'Cannot find items in post data'
    +              ));
    +            }
    +          break;
    +          case "mailbox":
    +            if (isset($_POST['items'])) {
    +              $items = (array)json_decode($_POST['items'], true);
    +              if (is_array($items)) {
    +                if (mailbox_delete_mailbox(array('username' => $items)) === false) {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Task failed'
    +                    ));
    +                  }
    +                }
    +                else {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'success',
    +                      'msg' => 'Task completed'
    +                    ));
    +                  }
    +                }
    +              }
    +              else {
    +                echo json_encode(array(
    +                  'type' => 'error',
    +                  'msg' => 'Cannot find username array in post data'
    +                ));
    +              }
    +            }
    +            else {
    +              echo json_encode(array(
    +                'type' => 'error',
    +                'msg' => 'Cannot find items in post data'
    +              ));
    +            }
    +          break;
    +          case "resource":
    +            if (isset($_POST['items'])) {
    +              $items = (array)json_decode($_POST['items'], true);
    +              if (is_array($items)) {
    +                if (mailbox_delete_resource(array('name' => $items)) === false) {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Task failed'
    +                    ));
    +                  }
    +                }
    +                else {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'success',
    +                      'msg' => 'Task completed'
    +                    ));
    +                  }
    +                }
    +              }
    +              else {
    +                echo json_encode(array(
    +                  'type' => 'error',
    +                  'msg' => 'Cannot find name array in post data'
    +                ));
    +              }
    +            }
    +            else {
    +              echo json_encode(array(
    +                'type' => 'error',
    +                'msg' => 'Cannot find items in post data'
                   ));
                 }
               break;
    @@ -476,26 +655,222 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
           case "edit":
             switch ($category) {
               case "alias":
    -            if (isset($_POST['address']) && isset($_POST['active'])) {
    -              $address = (array)json_decode($_POST['address'], true);
    -              if (is_array($address)) {
    -                if (mailbox_edit_alias(array('address' => $address, 'active' => ($_POST['active'] == "1") ? $active = 1 : null)) === false) {
    -                  echo json_encode(array(
    -                    'type' => 'error',
    -                    'msg' => 'Edit item failed'
    -                  ));
    +            if (isset($_POST['items']) && isset($_POST['attr'])) {
    +              $items = (array)json_decode($_POST['items'], true);
    +              $attr = (array)json_decode($_POST['attr'], true);
    +              $postarray = array_merge(array('address' => $items), $attr);
    +              if (is_array($postarray['address'])) {
    +                if (mailbox_edit_alias($postarray) === false) {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Edit failed'
    +                    ));
    +                  }
                       exit();
                     }
    +                else {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'success',
    +                      'msg' => 'Task completed'
    +                    ));
    +                  }
    +                }
    +              }
    +              else {
                     echo json_encode(array(
    -                  'type' => 'success',
    -                  'msg' => 'Task completed'
    +                  'type' => 'error',
    +                  'msg' => 'Incomplete post data'
                     ));
                   }
                 }
                 else {
                   echo json_encode(array(
                     'type' => 'error',
    -                'msg' => 'Cannot find address array in post data'
    +                'msg' => 'Incomplete post data'
    +              ));
    +            }
    +          break;
    +          case "mailbox":
    +            if (isset($_POST['items']) && isset($_POST['attr'])) {
    +              $items = (array)json_decode($_POST['items'], true);
    +              $attr = (array)json_decode($_POST['attr'], true);
    +              $postarray = array_merge(array('username' => $items), $attr);
    +              if (is_array($postarray['username'])) {
    +                if (mailbox_edit_mailbox($postarray) === false) {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Edit failed'
    +                    ));
    +                  }
    +                  exit();
    +                }
    +                else {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'success',
    +                      'msg' => 'Task completed'
    +                    ));
    +                  }
    +                }
    +              }
    +              else {
    +                echo json_encode(array(
    +                  'type' => 'error',
    +                  'msg' => 'Incomplete post data'
    +                ));
    +              }
    +            }
    +            else {
    +              echo json_encode(array(
    +                'type' => 'error',
    +                'msg' => 'Incomplete post data'
    +              ));
    +            }
    +          break;
    +          case "resource":
    +            if (isset($_POST['items']) && isset($_POST['attr'])) {
    +              $items = (array)json_decode($_POST['items'], true);
    +              $attr = (array)json_decode($_POST['attr'], true);
    +              $postarray = array_merge(array('name' => $items), $attr);
    +              if (is_array($postarray['name'])) {
    +                if (mailbox_edit_resource($postarray) === false) {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Edit failed'
    +                    ));
    +                  }
    +                  exit();
    +                }
    +                else {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'success',
    +                      'msg' => 'Task completed'
    +                    ));
    +                  }
    +                }
    +              }
    +              else {
    +                echo json_encode(array(
    +                  'type' => 'error',
    +                  'msg' => 'Incomplete post data'
    +                ));
    +              }
    +            }
    +            else {
    +              echo json_encode(array(
    +                'type' => 'error',
    +                'msg' => 'Incomplete post data'
    +              ));
    +            }
    +          break;
    +          case "domain":
    +            if (isset($_POST['items']) && isset($_POST['attr'])) {
    +              $items = (array)json_decode($_POST['items'], true);
    +              $attr = (array)json_decode($_POST['attr'], true);
    +              $postarray = array_merge(array('domain' => $items), $attr);
    +              if (is_array($postarray['domain'])) {
    +                if (mailbox_edit_domain($postarray) === false) {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Edit failed'
    +                    ));
    +                  }
    +                  exit();
    +                }
    +                else {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'success',
    +                      'msg' => 'Task completed'
    +                    ));
    +                  }
    +                }
    +              }
    +              else {
    +                echo json_encode(array(
    +                  'type' => 'error',
    +                  'msg' => 'Incomplete post data'
    +                ));
    +              }
    +            }
    +            else {
    +              echo json_encode(array(
    +                'type' => 'error',
    +                'msg' => 'Incomplete post data'
    +              ));
    +            }
    +          break;
    +          case "alias-domain":
    +            if (isset($_POST['items']) && isset($_POST['attr'])) {
    +              $items = (array)json_decode($_POST['items'], true);
    +              $attr = (array)json_decode($_POST['attr'], true);
    +              $postarray = array_merge(array('alias_domain' => $items), $attr);
    +              if (is_array($postarray['alias_domain'])) {
    +                if (mailbox_edit_alias_domain($postarray) === false) {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'error',
    +                      'msg' => 'Edit failed'
    +                    ));
    +                  }
    +                  exit();
    +                }
    +                else {
    +                  if (isset($_SESSION['return'])) {
    +                    echo json_encode($_SESSION['return']);
    +                  }
    +                  else {
    +                    echo json_encode(array(
    +                      'type' => 'success',
    +                      'msg' => 'Task completed'
    +                    ));
    +                  }
    +                }
    +              }
    +              else {
    +                echo json_encode(array(
    +                  'type' => 'error',
    +                  'msg' => 'Incomplete post data'
    +                ));
    +              }
    +            }
    +            else {
    +              echo json_encode(array(
    +                'type' => 'error',
    +                'msg' => 'Incomplete post data'
                   ));
                 }
               break;
    diff --git a/data/web/lang/lang.de.php b/data/web/lang/lang.de.php
    index bc254ccb..d1a8300d 100644
    --- a/data/web/lang/lang.de.php
    +++ b/data/web/lang/lang.de.php
    @@ -70,12 +70,12 @@ $lang['danger']['login_failed'] = 'Anmeldung fehlgeschlagen';
     $lang['danger']['mailbox_invalid'] = 'Mailboxname ist ungültig';
     $lang['danger']['resource_invalid'] = 'Ressourcenname ist ungültig';
     $lang['danger']['description_invalid'] = 'Ressourcenbeschreibung ist ungültig';
    -$lang['danger']['mailbox_invalid_suggest'] = 'Mailboxname ist ungültig, meinten Sie vielleicht "%s"?';
    +$lang['danger']['mailbox_invalid_suggest'] = 'Mailboxname ist ungültig, meinten Sie vielleicht %s?';
     $lang['danger']['is_alias'] = '%s lautet bereits eine Alias-Adresse';
     $lang['danger']['is_alias_or_mailbox'] = "Eine Mailbox oder ein Alias mit der Adresse %s ist bereits vorhanden";
     $lang['danger']['is_spam_alias'] = '%s lautet bereits eine Spam-Alias-Adresse';
     $lang['danger']['quota_not_0_not_numeric'] = 'Speicherplatz muss numerisch und >= 0 sein';
    -$lang['danger']['domain_not_found'] = 'Domain "%s" nicht gefunden.';
    +$lang['danger']['domain_not_found'] = 'Domain %s nicht gefunden';
     $lang['danger']['max_mailbox_exceeded'] = 'Anzahl an Mailboxen überschritten (%d von %d)';
     $lang['danger']['max_alias_exceeded'] = 'Anzahl an Alias-Adressen überschritten';
     $lang['danger']['mailbox_quota_exceeded'] = 'Speicherplatz überschreitet das Limit (max. %d MiB)';
    diff --git a/data/web/lang/lang.en.php b/data/web/lang/lang.en.php
    index af500355..f562d498 100644
    --- a/data/web/lang/lang.en.php
    +++ b/data/web/lang/lang.en.php
    @@ -77,7 +77,7 @@ $lang['danger']['is_alias'] = "%s is already known as an alias address";
     $lang['danger']['is_alias_or_mailbox'] = "%s is already known as an alias or a mailbox";
     $lang['danger']['is_spam_alias'] = "%s is already known as a spam alias address";
     $lang['danger']['quota_not_0_not_numeric'] = "Quota must be numeric and >= 0";
    -$lang['danger']['domain_not_found'] = "Domain not found.";
    +$lang['danger']['domain_not_found'] = 'Domain "%s" not found';
     $lang['danger']['max_mailbox_exceeded'] = "Max. mailboxes exceeded (%d of %d)";
     $lang['danger']['max_alias_exceeded'] = 'Max. aliases exceeded';
     $lang['danger']['mailbox_quota_exceeded'] = "Quota exceeds the domain limit (max. %d MiB)";
    diff --git a/data/web/mailbox.php b/data/web/mailbox.php
    index 864ea676..e35a3601 100644
    --- a/data/web/mailbox.php
    +++ b/data/web/mailbox.php
    @@ -31,16 +31,28 @@ $_SESSION['return_to'] = $_SERVER['REQUEST_URI'];
                 <?php
                 if ($_SESSION['mailcow_cc_role'] == "admin"):
                 ?>
    -              <a href="/add.php?domain"><span class="glyphicon glyphicon-plus"></span></a>
    +            <a href="/add.php?domain"><span class="glyphicon glyphicon-plus"></span></a></li>
                 <?php
                 endif;
                 ?>
                 </div>
    -            <h3 class="panel-title"><?=$lang['mailbox']['domains'];?></h3>
    +            <?=$lang['mailbox']['domains'];?>
                 </div>
                 <div class="table-responsive">
                   <table id="domain_table" class="table table-striped"></table>
                 </div>
    +            <div class="mass-actions-mailbox">
    +              <div class="btn-group">
    +                <a class="btn btn-sm btn-default" id="toggle_multi_select_all" data-id="domain" href="#"><span class="glyphicon glyphicon-check" aria-hidden="true"></span> <?=$lang['mailbox']['toggle_all'];?></a>
    +                <a class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#"><?=$lang['mailbox']['quick_actions'];?> <span class="caret"></span></a>
    +                <ul class="dropdown-menu">
    +                  <li><a id="edit_selected" data-id="domain" data-api-url='edit/domain' data-api-attr='{"active":"1"}' href="#"><?=$lang['mailbox']['activate'];?></a></li>
    +                  <li><a id="edit_selected" data-id="domain" data-api-url='edit/domain' data-api-attr='{"active":"0"}' href="#"><?=$lang['mailbox']['deactivate'];?></a></li>
    +                  <li role="separator" class="divider"></li>
    +                  <li><a id="delete_selected" data-id="domain" data-api-url='delete/domain' href="#"><?=$lang['mailbox']['remove'];?></a></li>
    +                </ul>
    +              </div>
    +            </div>
                 <span class="footer-add-item"><a href="/add.php?domain"><?=$lang['mailbox']['add_domain'];?></a></span>
               </div>
             </div>
    @@ -56,6 +68,18 @@ $_SESSION['return_to'] = $_SERVER['REQUEST_URI'];
                 <div class="table-responsive">
                   <table id="mailbox_table" class="table table-striped"></table>
                 </div>
    +            <div class="mass-actions-mailbox">
    +              <div class="btn-group">
    +                <a class="btn btn-sm btn-default" id="toggle_multi_select_all" data-id="mailbox" href="#"><span class="glyphicon glyphicon-check" aria-hidden="true"></span> <?=$lang['mailbox']['toggle_all'];?></a>
    +                <a class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#"><?=$lang['mailbox']['quick_actions'];?> <span class="caret"></span></a>
    +                <ul class="dropdown-menu">
    +                  <li><a id="edit_selected" data-id="mailbox" data-api-url='edit/mailbox' data-api-attr='{"active":"1"}' href="#"><?=$lang['mailbox']['activate'];?></a></li>
    +                  <li><a id="edit_selected" data-id="mailbox" data-api-url='edit/mailbox' data-api-attr='{"active":"0"}' href="#"><?=$lang['mailbox']['deactivate'];?></a></li>
    +                  <li role="separator" class="divider"></li>
    +                  <li><a id="delete_selected" data-id="mailbox" data-api-url='delete/mailbox' href="#"><?=$lang['mailbox']['remove'];?></a></li>
    +                </ul>
    +              </div>
    +            </div>
                 <span class="footer-add-item"><a href="/add.php?mailbox"><?=$lang['mailbox']['add_mailbox'];?></a></span>
               </div>
             </div>
    @@ -71,6 +95,18 @@ $_SESSION['return_to'] = $_SERVER['REQUEST_URI'];
                 <div class="table-responsive">
                   <table id="resources_table" class="table table-striped"></table>
                 </div>
    +            <div class="mass-actions-mailbox">
    +              <div class="btn-group">
    +                <a class="btn btn-sm btn-default" id="toggle_multi_select_all" data-id="resource" href="#"><span class="glyphicon glyphicon-check" aria-hidden="true"></span> <?=$lang['mailbox']['toggle_all'];?></a>
    +                <a class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#"><?=$lang['mailbox']['quick_actions'];?> <span class="caret"></span></a>
    +                <ul class="dropdown-menu">
    +                  <li><a id="edit_selected" data-id="resource" data-api-url='edit/resource' data-api-attr='{"active":"1"}' href="#"><?=$lang['mailbox']['activate'];?></a></li>
    +                  <li><a id="edit_selected" data-id="resource" data-api-url='edit/resource' data-api-attr='{"active":"0"}' href="#"><?=$lang['mailbox']['deactivate'];?></a></li>
    +                  <li role="separator" class="divider"></li>
    +                  <li><a id="delete_selected" data-id="resource" data-api-url='delete/resource' href="#"><?=$lang['mailbox']['remove'];?></a></li>
    +                </ul>
    +              </div>
    +            </div>
                 <span class="footer-add-item"><a href="/add.php?resource"><?=$lang['mailbox']['add_resource'];?></a></span>
               </div>
             </div>
    @@ -86,6 +122,18 @@ $_SESSION['return_to'] = $_SERVER['REQUEST_URI'];
                 <div class="table-responsive">
                   <table id="aliasdomain_table" class="table table-striped"></table>
                 </div>
    +            <div class="mass-actions-mailbox">
    +              <div class="btn-group">
    +                <a class="btn btn-sm btn-default" id="toggle_multi_select_all" data-id="alias-domain" href="#"><span class="glyphicon glyphicon-check" aria-hidden="true"></span> <?=$lang['mailbox']['toggle_all'];?></a>
    +                <a class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#"><?=$lang['mailbox']['quick_actions'];?> <span class="caret"></span></a>
    +                <ul class="dropdown-menu">
    +                  <li><a id="edit_selected" data-id="alias-domain" data-api-url='edit/alias-domain' data-api-attr='{"active":"1"}' href="#"><?=$lang['mailbox']['activate'];?></a></li>
    +                  <li><a id="edit_selected" data-id="alias-domain" data-api-url='edit/alias-domain' data-api-attr='{"active":"0"}' href="#"><?=$lang['mailbox']['deactivate'];?></a></li>
    +                  <li role="separator" class="divider"></li>
    +                  <li><a id="delete_selected" data-id="alias-domain" data-api-url='delete/alias-domain' href="#"><?=$lang['mailbox']['remove'];?></a></li>
    +                </ul>
    +              </div>
    +            </div>
                 <span class="footer-add-item"><a href="/add.php?aliasdomain"><?=$lang['mailbox']['add_domain_alias'];?></a></span>
               </div>
             </div>
    @@ -99,18 +147,19 @@ $_SESSION['return_to'] = $_SERVER['REQUEST_URI'];
                 <div class="table-responsive">
                   <table id="alias_table" class="table table-striped"></table>
                 </div>
    -            <div class="mass-actions">
    -              <p id="select_all_aliases" class="mass-select-all">
    -                ↪ <?=$lang['mailbox']['toggle_all'];?>
    -              </p>
    -            </div>
    -            <div class="footer-add-item">
    -              <a class="pull-right" href="/add.php?alias"><span class="glyphicon glyphicon-plus"></span></a>
    -              <b><?=$lang['mailbox']['quick_actions'];?>:</b>
    -              <a id="delete_selected_alias" href="#" class="mass-each-action"><?=$lang['mailbox']['remove'];?></a> |
    -              <a id="activate_selected_alias" href="#" class="mass-each-action"><?=$lang['mailbox']['activate'];?></a> |
    -              <a id="deactivate_selected_alias" href="#" class="mass-each-action"><?=$lang['mailbox']['deactivate'];?></a>
    +            <div class="mass-actions-mailbox">
    +              <div class="btn-group">
    +                <a class="btn btn-sm btn-default" id="toggle_multi_select_all" data-id="alias" href="#"><span class="glyphicon glyphicon-check" aria-hidden="true"></span> <?=$lang['mailbox']['toggle_all'];?></a>
    +                <a class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#"><?=$lang['mailbox']['quick_actions'];?> <span class="caret"></span></a>
    +                <ul class="dropdown-menu">
    +                  <li><a id="edit_selected" data-id="alias" data-api-url='edit/alias' data-api-attr='{"active":"1","active1":"12"}' href="#"><?=$lang['mailbox']['activate'];?></a></li>
    +                  <li><a id="edit_selected" data-id="alias" data-api-url='edit/alias' data-api-attr='{"active":"0"}' href="#"><?=$lang['mailbox']['deactivate'];?></a></li>
    +                  <li role="separator" class="divider"></li>
    +                  <li><a id="delete_selected" data-id="alias" data-api-url='delete/alias' href="#"><?=$lang['mailbox']['remove'];?></a></li>
    +                </ul>
    +              </div>
                 </div>
    +            <span class="footer-add-item"><a href="/add.php?alias"><?=$lang['mailbox']['add_alias'];?></a></span>
               </div>
             </div>
     
    diff --git a/data/web/user.php b/data/web/user.php
    index ec25dc94..d5c75abc 100644
    --- a/data/web/user.php
    +++ b/data/web/user.php
    @@ -382,18 +382,20 @@ elseif (isset($_SESSION['mailcow_cc_role']) && $_SESSION['mailcow_cc_role'] == '
     	</div>
     	<div role="tabpanel" class="tab-pane" id="TLSPolicy">
     		<form class="form-horizontal" role="form" method="post">
    +      <input type="hidden" value="0" name="tls_in">
    +      <input type="hidden" value="0" name="tls_out">
     			<p class="help-block"><?=$lang['user']['tls_policy_warning'];?></p>
     			<div class="form-group">
     				<div class="col-sm-6">
     					<div class="checkbox">
     						<h4><span class="glyphicon glyphicon-download" aria-hidden="true"></span> <?=$lang['user']['tls_enforce_in'];?></h4>
    -						<input type="checkbox" id="tls_in" name="tls_in" <?=($get_tls_policy['tls_enforce_in'] == "1") ? "checked" : null;?> data-on-text="<?=$lang['user']['on'];?>" data-off-text="<?=$lang['user']['off'];?>">
    +						<input type="checkbox" value="1" id="tls_in" name="tls_in" <?=($get_tls_policy['tls_enforce_in'] == "1") ? "checked" : null;?> data-on-text="<?=$lang['user']['on'];?>" data-off-text="<?=$lang['user']['off'];?>">
     					</div>
     				</div>
     				<div class="col-sm-6">
     					<div class="checkbox">
     						<h4><span class="glyphicon glyphicon-upload" aria-hidden="true"></span> <?=$lang['user']['tls_enforce_out'];?></h4>
    -						<input type="checkbox" id="tls_out" name="tls_out" <?=($get_tls_policy['tls_enforce_out'] == "1") ? "checked" : null;?> data-on-text="<?=$lang['user']['on'];?>" data-off-text="<?=$lang['user']['off'];?>">
    +						<input type="checkbox" value="1" id="tls_out" name="tls_out" <?=($get_tls_policy['tls_enforce_out'] == "1") ? "checked" : null;?> data-on-text="<?=$lang['user']['on'];?>" data-off-text="<?=$lang['user']['off'];?>">
     					</div>
     				</div>
     			</div>
    
    From a478c5068138d2701f11460e217e0aa0c808f397 Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Thu, 11 May 2017 23:15:06 +0200
    Subject: [PATCH 35/49] Change to tabstops
    
    ---
     data/web/add.php  | 22 +++++++++++-----------
     data/web/edit.php | 46 +++++++++++++++++++++++-----------------------
     2 files changed, 34 insertions(+), 34 deletions(-)
    
    diff --git a/data/web/add.php b/data/web/add.php
    index 88e60b06..147619fd 100644
    --- a/data/web/add.php
    +++ b/data/web/add.php
    @@ -21,9 +21,9 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     ?>
     				<h4><?=$lang['add']['domain'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -          <input type="hidden" value="0" name="active">
    -          <input type="hidden" value="0" name="backupmx">
    -          <input type="hidden" value="0" name="relay_all_recipients">
    +					<input type="hidden" value="0" name="active">
    +					<input type="hidden" value="0" name="backupmx">
    +					<input type="hidden" value="0" name="relay_all_recipients">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="domain"><?=$lang['add']['domain'];?>:</label>
     						<div class="col-sm-10">
    @@ -92,7 +92,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     				<h4><?=$lang['add']['alias'];?></h4>
     				<p><?=$lang['add']['alias_spf_fail'];?></p>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -          <input type="hidden" value="0" name="active">
    +					<input type="hidden" value="0" name="active">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="address"><?=$lang['add']['alias_address'];?></label>
     						<div class="col-sm-10">
    @@ -126,7 +126,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     	?>
     				<h4><?=$lang['add']['alias_domain'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -          <input type="hidden" value="0" name="active">
    +					<input type="hidden" value="0" name="active">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="alias_domain"><?=$lang['add']['alias_domain'];?></label>
     						<div class="col-sm-10">
    @@ -165,7 +165,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     	?>
     				<h4><?=$lang['add']['mailbox'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -          <input type="hidden" value="0" name="active">
    +					<input type="hidden" value="0" name="active">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="local_part"><?=$lang['add']['mailbox_username'];?></label>
     						<div class="col-sm-10">
    @@ -229,8 +229,8 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     	?>
     				<h4><?=$lang['add']['resource'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -          <input type="hidden" value="0" name="active">
    -          <input type="hidden" value="0" name="multiple_bookings">
    +					<input type="hidden" value="0" name="active">
    +					<input type="hidden" value="0" name="multiple_bookings">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="description"><?=$lang['add']['description'];?></label>
     						<div class="col-sm-10">
    @@ -293,9 +293,9 @@ elseif (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] ==
     				<h4><?=$lang['add']['syncjob'];?></h4>
     				<p><?=$lang['add']['syncjob_hint'];?></p>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -          <input type="hidden" value="0" name="active">
    -          <input type="hidden" value="0" name="delete1">
    -          <input type="hidden" value="0" name="delete2duplicates">
    +					<input type="hidden" value="0" name="active">
    +					<input type="hidden" value="0" name="delete1">
    +					<input type="hidden" value="0" name="delete2duplicates">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="host1"><?=$lang['add']['hostname'];?></label>
     						<div class="col-sm-10">
    diff --git a/data/web/edit.php b/data/web/edit.php
    index 1532d06b..9f711dc2 100644
    --- a/data/web/edit.php
    +++ b/data/web/edit.php
    @@ -26,8 +26,8 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     					<h4><?=$lang['edit']['alias'];?></h4>
     					<br />
     					<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -          <input type="hidden" value="0" name="active">
    -					<input type="hidden" name="address" value="<?=htmlspecialchars($alias);?>">
    +						<input type="hidden" value="0" name="active">
    +						<input type="hidden" name="address" value="<?=htmlspecialchars($alias);?>">
     						<div class="form-group">
     							<label class="control-label col-sm-2" for="goto"><?=$lang['edit']['target_address'];?></label>
     							<div class="col-sm-10">
    @@ -67,8 +67,8 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     				<h4><?=$lang['edit']['domain_admin'];?></h4>
     				<br />
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -        <input type="hidden" value="0" name="active">
    -				<input type="hidden" name="username_now" value="<?=htmlspecialchars($domain_admin);?>">
    +					<input type="hidden" value="0" name="active">
    +					<input type="hidden" name="username_now" value="<?=htmlspecialchars($domain_admin);?>">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="username"><?=$lang['edit']['username'];?></label>
     						<div class="col-sm-10">
    @@ -143,10 +143,10 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     			?>
     				<h4><?=$lang['edit']['domain'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -        <input type="hidden" value="0" name="active">
    -        <input type="hidden" value="0" name="backupmx">
    -        <input type="hidden" value="0" name="relay_all_recipients">
    -				<input type="hidden" name="domain" value="<?=htmlspecialchars($domain);?>">
    +					<input type="hidden" value="0" name="active">
    +					<input type="hidden" value="0" name="backupmx">
    +					<input type="hidden" value="0" name="relay_all_recipients">
    +					<input type="hidden" name="domain" value="<?=htmlspecialchars($domain);?>">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="description"><?=$lang['edit']['description'];?></label>
     						<div class="col-sm-10">
    @@ -249,9 +249,9 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
                   <?php
                   if ($wl['object'] == $domain):
                   ?>
    -                <input type="hidden" name="delete_prefid" value="<?=$wl['prefid'];?>">
    -                <input type="hidden" name="delete_policy_list_item">
    -                <input type="hidden" name="domain" value="<?=$domain;?>">
    +							<input type="hidden" name="delete_prefid" value="<?=$wl['prefid'];?>">
    +							<input type="hidden" name="delete_policy_list_item">
    +							<input type="hidden" name="domain" value="<?=$domain;?>">
                     <a href="#" onclick="$(this).closest('form').submit()" data-toggle="tooltip" data-placement="left" title="<?=$lang['user']['delete_now'];?>"><span class="glyphicon glyphicon-remove"></span></a>
                   <?php
                   else:
    @@ -302,12 +302,12 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
                 <form class="form-inline" method="post">
                 <div class="col-xs-6"><code><?=$bl['value'];?></code></div>
                 <div class="col-xs-6">
    -              <input type="hidden" name="delete_prefid" value="<?=$bl['prefid'];?>">
    +							<input type="hidden" name="delete_prefid" value="<?=$bl['prefid'];?>">
                   <?php
                   if ($bl['object'] == $domain):
                   ?>
    -                <input type="hidden" name="delete_policy_list_item">
    -                <input type="hidden" name="domain" value="<?=$domain;?>">
    +								<input type="hidden" name="delete_policy_list_item">
    +								<input type="hidden" name="domain" value="<?=$domain;?>">
                     <a href="#" onclick="$(this).closest('form').submit()" data-toggle="tooltip" data-placement="left" title="<?=$lang['user']['delete_now'];?>"><span class="glyphicon glyphicon-remove"></span></a>
                   <?php
                   else:
    @@ -355,8 +355,8 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     			?>
     				<h4><?=$lang['edit']['edit_alias_domain'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -          <input type="hidden" value="0" name="active">
    -          <input type="hidden" value="<?=$result['alias_domain'];?>" name="alias_domain">
    +					<input type="hidden" value="0" name="active">
    +					<input type="hidden" value="<?=$result['alias_domain'];?>" name="alias_domain">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="target_domain"><?=$lang['edit']['target_domain'];?></label>
     						<div class="col-sm-10">
    @@ -404,9 +404,9 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
           ?>
           <h4><?=$lang['edit']['mailbox'];?></h4>
           <form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -      <input type="hidden" value="0" name="sender_acl">
    -      <input type="hidden" value="0" name="active">
    -      <input type="hidden" name="username" value="<?=htmlspecialchars($result['username']);?>">
    +				<input type="hidden" value="0" name="sender_acl">
    +				<input type="hidden" value="0" name="active">
    +				<input type="hidden" name="username" value="<?=htmlspecialchars($result['username']);?>">
             <div class="form-group">
               <label class="control-label col-sm-2" for="name"><?=$lang['edit']['full_name'];?>:</label>
               <div class="col-sm-10">
    @@ -571,10 +571,10 @@ elseif (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] ==
     			?>
     				<h4><?=$lang['edit']['syncjob'];?></h4>
     				<form class="form-horizontal" role="form" method="post" action="<?=($FORM_ACTION == "previous") ? $_SESSION['return_to'] : null;?>">
    -        <input type="hidden" value="0" name="delete2duplicates">
    -        <input type="hidden" value="0" name="delete1">
    -        <input type="hidden" value="0" name="active">
    -				<input type="hidden" name="id" value="<?=htmlspecialchars($result['id']);?>">
    +          <input type="hidden" value="0" name="delete2duplicates">
    +          <input type="hidden" value="0" name="delete1">
    +          <input type="hidden" value="0" name="active">
    +          <input type="hidden" name="id" value="<?=htmlspecialchars($result['id']);?>">
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="host1"><?=$lang['edit']['hostname'];?></label>
     						<div class="col-sm-10">
    
    From b1d0776ad1d698b37c0868ff0af5c79abad9a346 Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Thu, 11 May 2017 23:18:57 +0200
    Subject: [PATCH 36/49] Fix selection in filter field
    
    ---
     data/web/js/admin.js   | 2 +-
     data/web/js/mailbox.js | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/data/web/js/admin.js b/data/web/js/admin.js
    index e76feef7..b0fdbbde 100644
    --- a/data/web/js/admin.js
    +++ b/data/web/js/admin.js
    @@ -15,7 +15,7 @@ $(document).ready(function() {
         }
       });
       // Select checkbox by click on parent tr
    -  $(document).on('click', 'tr', function(e) {
    +  $(document).on('click', 'tbody>tr', function(e) {
         if (e.target.type == "checkbox") {
           e.stopPropagation();
         } else {
    diff --git a/data/web/js/mailbox.js b/data/web/js/mailbox.js
    index 70435ca1..e1f0424f 100644
    --- a/data/web/js/mailbox.js
    +++ b/data/web/js/mailbox.js
    @@ -15,7 +15,7 @@ $(document).ready(function() {
         }
       });
       // Select checkbox by click on parent tr
    -  $(document).on('click', 'tr', function(e) {
    +  $(document).on('click', 'tbody>tr', function(e) {
         if (e.target.type == "checkbox") {
           e.stopPropagation();
         } else {
    
    From 6cd97c46c519958436d1734aff61727ede90043b Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Michael=20K=C3=A4ufl?= <mailcow@c.michael-kaeufl.de>
    Date: Fri, 12 May 2017 20:54:23 +0200
    Subject: [PATCH 37/49] Used tabs for indentation in Dockerfiles
    
    ---
     data/Dockerfiles/clamav/Dockerfile  | 28 ++++++++++++++--------------
     data/Dockerfiles/dovecot/Dockerfile |  4 ++--
     data/Dockerfiles/postfix/Dockerfile |  2 +-
     data/Dockerfiles/rspamd/Dockerfile  |  6 +++---
     data/Dockerfiles/sogo/Dockerfile    | 18 +++++++++---------
     5 files changed, 29 insertions(+), 29 deletions(-)
    
    diff --git a/data/Dockerfiles/clamav/Dockerfile b/data/Dockerfiles/clamav/Dockerfile
    index 170b7d8f..26867111 100755
    --- a/data/Dockerfiles/clamav/Dockerfile
    +++ b/data/Dockerfiles/clamav/Dockerfile
    @@ -6,16 +6,16 @@ ENV DEBIAN_VERSION stretch
     
     # initial install of av daemon
     RUN echo "deb http://http.debian.net/debian/ $DEBIAN_VERSION main contrib non-free" > /etc/apt/sources.list && \
    -    echo "deb http://http.debian.net/debian/ $DEBIAN_VERSION-updates main contrib non-free" >> /etc/apt/sources.list && \
    -    echo "deb http://security.debian.org/ $DEBIAN_VERSION/updates main contrib non-free" >> /etc/apt/sources.list && \
    -    apt-get update && \
    -    DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends -y -qq \
    -        clamav-daemon \
    -        clamav-freshclam \
    -        libclamunrar7 \
    -        curl && \
    -    apt-get clean && \
    -    rm -rf /var/lib/apt/lists/*
    +	echo "deb http://http.debian.net/debian/ $DEBIAN_VERSION-updates main contrib non-free" >> /etc/apt/sources.list && \
    +	echo "deb http://security.debian.org/ $DEBIAN_VERSION/updates main contrib non-free" >> /etc/apt/sources.list && \
    +	apt-get update && \
    +	DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends -y -qq \
    +		clamav-daemon \
    +		clamav-freshclam \
    +		libclamunrar7 \
    +		curl && \
    +	apt-get clean && \
    +	rm -rf /var/lib/apt/lists/*
     
     # initial update of av databases
     COPY dl_files.sh /dl_files.sh
    @@ -24,13 +24,13 @@ RUN /dl_files.sh
     
     # permission juggling
     RUN mkdir /var/run/clamav && \
    -    chown clamav:clamav /var/run/clamav && \
    -    chmod 750 /var/run/clamav
    +	chown clamav:clamav /var/run/clamav && \
    +	chmod 750 /var/run/clamav
     
     # av configuration update
     RUN sed -i 's/^Foreground .*$/Foreground true/g' /etc/clamav/clamd.conf && \
    -    echo "TCPSocket 3310" >> /etc/clamav/clamd.conf && \
    -    sed -i 's/^Foreground .*$/Foreground true/g' /etc/clamav/freshclam.conf
    +	echo "TCPSocket 3310" >> /etc/clamav/clamd.conf && \
    +	sed -i 's/^Foreground .*$/Foreground true/g' /etc/clamav/freshclam.conf
     
     # port provision
     EXPOSE 3310
    diff --git a/data/Dockerfiles/dovecot/Dockerfile b/data/Dockerfiles/dovecot/Dockerfile
    index aa3ed9da..0a357855 100644
    --- a/data/Dockerfiles/dovecot/Dockerfile
    +++ b/data/Dockerfiles/dovecot/Dockerfile
    @@ -20,7 +20,7 @@ RUN apt-get update \
     	automake \
     	syslog-ng \
     	syslog-ng-core \
    -    syslog-ng-mod-redis \
    +	syslog-ng-mod-redis \
     	ca-certificates \
     	supervisor \
     	wget \
    @@ -88,7 +88,7 @@ RUN chmod +x /usr/local/lib/dovecot/sieve/rspamd-pipe-ham \
     
     RUN groupadd -g 5000 vmail \
     	&& groupadd -g 401 dovecot \
    -    && groupadd -g 402 dovenull \
    +	&& groupadd -g 402 dovenull \
     	&& useradd -g vmail -u 5000 vmail -d /var/vmail \
     	&& useradd -c "Dovecot unprivileged user" -d /dev/null -u 401 -g dovecot -s /bin/false dovecot \
     	&& useradd -c "Dovecot login user" -d /dev/null -u 402 -g dovenull -s /bin/false dovenull
    diff --git a/data/Dockerfiles/postfix/Dockerfile b/data/Dockerfiles/postfix/Dockerfile
    index 87c40cfb..4616ba9a 100644
    --- a/data/Dockerfiles/postfix/Dockerfile
    +++ b/data/Dockerfiles/postfix/Dockerfile
    @@ -19,7 +19,7 @@ RUN apt-get install -y --no-install-recommends supervisor \
     	postfix-pcre \
     	syslog-ng \
     	syslog-ng-core \
    -    syslog-ng-mod-redis \
    +	syslog-ng-mod-redis \
     	ca-certificates \
     	gnupg \
     	python-gpgme \
    diff --git a/data/Dockerfiles/rspamd/Dockerfile b/data/Dockerfiles/rspamd/Dockerfile
    index 2a4ff29c..5adb9dce 100644
    --- a/data/Dockerfiles/rspamd/Dockerfile
    +++ b/data/Dockerfiles/rspamd/Dockerfile
    @@ -5,9 +5,9 @@ ENV DEBIAN_FRONTEND noninteractive
     ENV LC_ALL C
     
     RUN apt-key adv --fetch-keys http://rspamd.com/apt-stable/gpg.key \
    -    && echo "deb http://rspamd.com/apt-stable/ jessie main" > /etc/apt/sources.list.d/rspamd.list \
    -    && apt-get update \
    -    && apt-get -y install rspamd ca-certificates python-pip
    +	&& echo "deb http://rspamd.com/apt-stable/ jessie main" > /etc/apt/sources.list.d/rspamd.list \
    +	&& apt-get update \
    +	&& apt-get -y install rspamd ca-certificates python-pip
     
     RUN echo '.include $LOCAL_CONFDIR/local.d/rspamd.conf.local' > /etc/rspamd/rspamd.conf.local
     
    diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile
    index 348231de..b1b9d249 100644
    --- a/data/Dockerfiles/sogo/Dockerfile
    +++ b/data/Dockerfiles/sogo/Dockerfile
    @@ -14,15 +14,15 @@ RUN apt-get update \
     		supervisor \
     		mysql-client \
     		cron \
    -    && dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \
    -    && wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \
    -    && wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch.asc" \
    -    && export GNUPGHOME="$(mktemp -d)" \
    -    && gpg --keyserver ha.pool.sks-keyservers.net --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4 \
    -    && gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu \
    -    && rm -r "$GNUPGHOME" /usr/local/bin/gosu.asc \
    -    && chmod +x /usr/local/bin/gosu \
    -    && gosu nobody true
    +	&& dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \
    +	&& wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \
    +	&& wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch.asc" \
    +	&& export GNUPGHOME="$(mktemp -d)" \
    +	&& gpg --keyserver ha.pool.sks-keyservers.net --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4 \
    +	&& gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu \
    +	&& rm -r "$GNUPGHOME" /usr/local/bin/gosu.asc \
    +	&& chmod +x /usr/local/bin/gosu \
    +	&& gosu nobody true
     
     RUN mkdir /usr/share/doc/sogo
     RUN touch /usr/share/doc/sogo/empty.sh
    
    From 15853df84c8805733e41da2c054a67d1bb451e2a Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Sat, 13 May 2017 08:55:34 +0200
    Subject: [PATCH 38/49] JS changes and fixes
    
    ---
     data/web/css/animate.min.css       |  11 +++
     data/web/css/mailbox.css           |   2 +-
     data/web/inc/footer.inc.php        |  34 ++------
     data/web/inc/functions.inc.php     | 122 +++--------------------------
     data/web/inc/header.inc.php        |   1 +
     data/web/inc/prerequisites.inc.php |  12 +++
     data/web/js/mailbox.js             |  16 ++--
     data/web/js/notifications.min.js   |   1 +
     data/web/mailbox.php               |   2 +-
     9 files changed, 54 insertions(+), 147 deletions(-)
     create mode 100644 data/web/css/animate.min.css
     create mode 100644 data/web/js/notifications.min.js
    
    diff --git a/data/web/css/animate.min.css b/data/web/css/animate.min.css
    new file mode 100644
    index 00000000..104f7c40
    --- /dev/null
    +++ b/data/web/css/animate.min.css
    @@ -0,0 +1,11 @@
    +@charset "UTF-8";
    +
    +/*!
    + * animate.css -http://daneden.me/animate
    + * Version - 3.5.2
    + * Licensed under the MIT license - http://opensource.org/licenses/MIT
    + *
    + * Copyright (c) 2017 Daniel Eden
    + */
    +
    +.animated{animation-duration:1s;animation-fill-mode:both}.animated.infinite{animation-iteration-count:infinite}.animated.hinge{animation-duration:2s}.animated.bounceIn,.animated.bounceOut,.animated.flipOutX,.animated.flipOutY{animation-duration:.75s}@keyframes bounce{0%,20%,53%,80%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1);transform:translateZ(0)}40%,43%{animation-timing-function:cubic-bezier(.755,.05,.855,.06);transform:translate3d(0,-30px,0)}70%{animation-timing-function:cubic-bezier(.755,.05,.855,.06);transform:translate3d(0,-15px,0)}90%{transform:translate3d(0,-4px,0)}}.bounce{animation-name:bounce;transform-origin:center bottom}@keyframes flash{0%,50%,to{opacity:1}25%,75%{opacity:0}}.flash{animation-name:flash}@keyframes pulse{0%{transform:scaleX(1)}50%{transform:scale3d(1.05,1.05,1.05)}to{transform:scaleX(1)}}.pulse{animation-name:pulse}@keyframes rubberBand{0%{transform:scaleX(1)}30%{transform:scale3d(1.25,.75,1)}40%{transform:scale3d(.75,1.25,1)}50%{transform:scale3d(1.15,.85,1)}65%{transform:scale3d(.95,1.05,1)}75%{transform:scale3d(1.05,.95,1)}to{transform:scaleX(1)}}.rubberBand{animation-name:rubberBand}@keyframes shake{0%,to{transform:translateZ(0)}10%,30%,50%,70%,90%{transform:translate3d(-10px,0,0)}20%,40%,60%,80%{transform:translate3d(10px,0,0)}}.shake{animation-name:shake}@keyframes headShake{0%{transform:translateX(0)}6.5%{transform:translateX(-6px) rotateY(-9deg)}18.5%{transform:translateX(5px) rotateY(7deg)}31.5%{transform:translateX(-3px) rotateY(-5deg)}43.5%{transform:translateX(2px) rotateY(3deg)}50%{transform:translateX(0)}}.headShake{animation-timing-function:ease-in-out;animation-name:headShake}@keyframes swing{20%{transform:rotate(15deg)}40%{transform:rotate(-10deg)}60%{transform:rotate(5deg)}80%{transform:rotate(-5deg)}to{transform:rotate(0deg)}}.swing{transform-origin:top center;animation-name:swing}@keyframes tada{0%{transform:scaleX(1)}10%,20%{transform:scale3d(.9,.9,.9) rotate(-3deg)}30%,50%,70%,90%{transform:scale3d(1.1,1.1,1.1) rotate(3deg)}40%,60%,80%{transform:scale3d(1.1,1.1,1.1) rotate(-3deg)}to{transform:scaleX(1)}}.tada{animation-name:tada}@keyframes wobble{0%{transform:none}15%{transform:translate3d(-25%,0,0) rotate(-5deg)}30%{transform:translate3d(20%,0,0) rotate(3deg)}45%{transform:translate3d(-15%,0,0) rotate(-3deg)}60%{transform:translate3d(10%,0,0) rotate(2deg)}75%{transform:translate3d(-5%,0,0) rotate(-1deg)}to{transform:none}}.wobble{animation-name:wobble}@keyframes jello{0%,11.1%,to{transform:none}22.2%{transform:skewX(-12.5deg) skewY(-12.5deg)}33.3%{transform:skewX(6.25deg) skewY(6.25deg)}44.4%{transform:skewX(-3.125deg) skewY(-3.125deg)}55.5%{transform:skewX(1.5625deg) skewY(1.5625deg)}66.6%{transform:skewX(-.78125deg) skewY(-.78125deg)}77.7%{transform:skewX(.390625deg) skewY(.390625deg)}88.8%{transform:skewX(-.1953125deg) skewY(-.1953125deg)}}.jello{animation-name:jello;transform-origin:center}@keyframes bounceIn{0%,20%,40%,60%,80%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:scale3d(.3,.3,.3)}20%{transform:scale3d(1.1,1.1,1.1)}40%{transform:scale3d(.9,.9,.9)}60%{opacity:1;transform:scale3d(1.03,1.03,1.03)}80%{transform:scale3d(.97,.97,.97)}to{opacity:1;transform:scaleX(1)}}.bounceIn{animation-name:bounceIn}@keyframes bounceInDown{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,-3000px,0)}60%{opacity:1;transform:translate3d(0,25px,0)}75%{transform:translate3d(0,-10px,0)}90%{transform:translate3d(0,5px,0)}to{transform:none}}.bounceInDown{animation-name:bounceInDown}@keyframes bounceInLeft{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(-3000px,0,0)}60%{opacity:1;transform:translate3d(25px,0,0)}75%{transform:translate3d(-10px,0,0)}90%{transform:translate3d(5px,0,0)}to{transform:none}}.bounceInLeft{animation-name:bounceInLeft}@keyframes bounceInRight{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(3000px,0,0)}60%{opacity:1;transform:translate3d(-25px,0,0)}75%{transform:translate3d(10px,0,0)}90%{transform:translate3d(-5px,0,0)}to{transform:none}}.bounceInRight{animation-name:bounceInRight}@keyframes bounceInUp{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,3000px,0)}60%{opacity:1;transform:translate3d(0,-20px,0)}75%{transform:translate3d(0,10px,0)}90%{transform:translate3d(0,-5px,0)}to{transform:translateZ(0)}}.bounceInUp{animation-name:bounceInUp}@keyframes bounceOut{20%{transform:scale3d(.9,.9,.9)}50%,55%{opacity:1;transform:scale3d(1.1,1.1,1.1)}to{opacity:0;transform:scale3d(.3,.3,.3)}}.bounceOut{animation-name:bounceOut}@keyframes bounceOutDown{20%{transform:translate3d(0,10px,0)}40%,45%{opacity:1;transform:translate3d(0,-20px,0)}to{opacity:0;transform:translate3d(0,2000px,0)}}.bounceOutDown{animation-name:bounceOutDown}@keyframes bounceOutLeft{20%{opacity:1;transform:translate3d(20px,0,0)}to{opacity:0;transform:translate3d(-2000px,0,0)}}.bounceOutLeft{animation-name:bounceOutLeft}@keyframes bounceOutRight{20%{opacity:1;transform:translate3d(-20px,0,0)}to{opacity:0;transform:translate3d(2000px,0,0)}}.bounceOutRight{animation-name:bounceOutRight}@keyframes bounceOutUp{20%{transform:translate3d(0,-10px,0)}40%,45%{opacity:1;transform:translate3d(0,20px,0)}to{opacity:0;transform:translate3d(0,-2000px,0)}}.bounceOutUp{animation-name:bounceOutUp}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.fadeIn{animation-name:fadeIn}@keyframes fadeInDown{0%{opacity:0;transform:translate3d(0,-100%,0)}to{opacity:1;transform:none}}.fadeInDown{animation-name:fadeInDown}@keyframes fadeInDownBig{0%{opacity:0;transform:translate3d(0,-2000px,0)}to{opacity:1;transform:none}}.fadeInDownBig{animation-name:fadeInDownBig}@keyframes fadeInLeft{0%{opacity:0;transform:translate3d(-100%,0,0)}to{opacity:1;transform:none}}.fadeInLeft{animation-name:fadeInLeft}@keyframes fadeInLeftBig{0%{opacity:0;transform:translate3d(-2000px,0,0)}to{opacity:1;transform:none}}.fadeInLeftBig{animation-name:fadeInLeftBig}@keyframes fadeInRight{0%{opacity:0;transform:translate3d(100%,0,0)}to{opacity:1;transform:none}}.fadeInRight{animation-name:fadeInRight}@keyframes fadeInRightBig{0%{opacity:0;transform:translate3d(2000px,0,0)}to{opacity:1;transform:none}}.fadeInRightBig{animation-name:fadeInRightBig}@keyframes fadeInUp{0%{opacity:0;transform:translate3d(0,100%,0)}to{opacity:1;transform:none}}.fadeInUp{animation-name:fadeInUp}@keyframes fadeInUpBig{0%{opacity:0;transform:translate3d(0,2000px,0)}to{opacity:1;transform:none}}.fadeInUpBig{animation-name:fadeInUpBig}@keyframes fadeOut{0%{opacity:1}to{opacity:0}}.fadeOut{animation-name:fadeOut}@keyframes fadeOutDown{0%{opacity:1}to{opacity:0;transform:translate3d(0,100%,0)}}.fadeOutDown{animation-name:fadeOutDown}@keyframes fadeOutDownBig{0%{opacity:1}to{opacity:0;transform:translate3d(0,2000px,0)}}.fadeOutDownBig{animation-name:fadeOutDownBig}@keyframes fadeOutLeft{0%{opacity:1}to{opacity:0;transform:translate3d(-100%,0,0)}}.fadeOutLeft{animation-name:fadeOutLeft}@keyframes fadeOutLeftBig{0%{opacity:1}to{opacity:0;transform:translate3d(-2000px,0,0)}}.fadeOutLeftBig{animation-name:fadeOutLeftBig}@keyframes fadeOutRight{0%{opacity:1}to{opacity:0;transform:translate3d(100%,0,0)}}.fadeOutRight{animation-name:fadeOutRight}@keyframes fadeOutRightBig{0%{opacity:1}to{opacity:0;transform:translate3d(2000px,0,0)}}.fadeOutRightBig{animation-name:fadeOutRightBig}@keyframes fadeOutUp{0%{opacity:1}to{opacity:0;transform:translate3d(0,-100%,0)}}.fadeOutUp{animation-name:fadeOutUp}@keyframes fadeOutUpBig{0%{opacity:1}to{opacity:0;transform:translate3d(0,-2000px,0)}}.fadeOutUpBig{animation-name:fadeOutUpBig}@keyframes flip{0%{transform:perspective(400px) rotateY(-1turn);animation-timing-function:ease-out}40%{transform:perspective(400px) translateZ(150px) rotateY(-190deg);animation-timing-function:ease-out}50%{transform:perspective(400px) translateZ(150px) rotateY(-170deg);animation-timing-function:ease-in}80%{transform:perspective(400px) scale3d(.95,.95,.95);animation-timing-function:ease-in}to{transform:perspective(400px);animation-timing-function:ease-in}}.animated.flip{-webkit-backface-visibility:visible;backface-visibility:visible;animation-name:flip}@keyframes flipInX{0%{transform:perspective(400px) rotateX(90deg);animation-timing-function:ease-in;opacity:0}40%{transform:perspective(400px) rotateX(-20deg);animation-timing-function:ease-in}60%{transform:perspective(400px) rotateX(10deg);opacity:1}80%{transform:perspective(400px) rotateX(-5deg)}to{transform:perspective(400px)}}.flipInX{-webkit-backface-visibility:visible!important;backface-visibility:visible!important;animation-name:flipInX}@keyframes flipInY{0%{transform:perspective(400px) rotateY(90deg);animation-timing-function:ease-in;opacity:0}40%{transform:perspective(400px) rotateY(-20deg);animation-timing-function:ease-in}60%{transform:perspective(400px) rotateY(10deg);opacity:1}80%{transform:perspective(400px) rotateY(-5deg)}to{transform:perspective(400px)}}.flipInY{-webkit-backface-visibility:visible!important;backface-visibility:visible!important;animation-name:flipInY}@keyframes flipOutX{0%{transform:perspective(400px)}30%{transform:perspective(400px) rotateX(-20deg);opacity:1}to{transform:perspective(400px) rotateX(90deg);opacity:0}}.flipOutX{animation-name:flipOutX;-webkit-backface-visibility:visible!important;backface-visibility:visible!important}@keyframes flipOutY{0%{transform:perspective(400px)}30%{transform:perspective(400px) rotateY(-15deg);opacity:1}to{transform:perspective(400px) rotateY(90deg);opacity:0}}.flipOutY{-webkit-backface-visibility:visible!important;backface-visibility:visible!important;animation-name:flipOutY}@keyframes lightSpeedIn{0%{transform:translate3d(100%,0,0) skewX(-30deg);opacity:0}60%{transform:skewX(20deg);opacity:1}80%{transform:skewX(-5deg);opacity:1}to{transform:none;opacity:1}}.lightSpeedIn{animation-name:lightSpeedIn;animation-timing-function:ease-out}@keyframes lightSpeedOut{0%{opacity:1}to{transform:translate3d(100%,0,0) skewX(30deg);opacity:0}}.lightSpeedOut{animation-name:lightSpeedOut;animation-timing-function:ease-in}@keyframes rotateIn{0%{transform-origin:center;transform:rotate(-200deg);opacity:0}to{transform-origin:center;transform:none;opacity:1}}.rotateIn{animation-name:rotateIn}@keyframes rotateInDownLeft{0%{transform-origin:left bottom;transform:rotate(-45deg);opacity:0}to{transform-origin:left bottom;transform:none;opacity:1}}.rotateInDownLeft{animation-name:rotateInDownLeft}@keyframes rotateInDownRight{0%{transform-origin:right bottom;transform:rotate(45deg);opacity:0}to{transform-origin:right bottom;transform:none;opacity:1}}.rotateInDownRight{animation-name:rotateInDownRight}@keyframes rotateInUpLeft{0%{transform-origin:left bottom;transform:rotate(45deg);opacity:0}to{transform-origin:left bottom;transform:none;opacity:1}}.rotateInUpLeft{animation-name:rotateInUpLeft}@keyframes rotateInUpRight{0%{transform-origin:right bottom;transform:rotate(-90deg);opacity:0}to{transform-origin:right bottom;transform:none;opacity:1}}.rotateInUpRight{animation-name:rotateInUpRight}@keyframes rotateOut{0%{transform-origin:center;opacity:1}to{transform-origin:center;transform:rotate(200deg);opacity:0}}.rotateOut{animation-name:rotateOut}@keyframes rotateOutDownLeft{0%{transform-origin:left bottom;opacity:1}to{transform-origin:left bottom;transform:rotate(45deg);opacity:0}}.rotateOutDownLeft{animation-name:rotateOutDownLeft}@keyframes rotateOutDownRight{0%{transform-origin:right bottom;opacity:1}to{transform-origin:right bottom;transform:rotate(-45deg);opacity:0}}.rotateOutDownRight{animation-name:rotateOutDownRight}@keyframes rotateOutUpLeft{0%{transform-origin:left bottom;opacity:1}to{transform-origin:left bottom;transform:rotate(-45deg);opacity:0}}.rotateOutUpLeft{animation-name:rotateOutUpLeft}@keyframes rotateOutUpRight{0%{transform-origin:right bottom;opacity:1}to{transform-origin:right bottom;transform:rotate(90deg);opacity:0}}.rotateOutUpRight{animation-name:rotateOutUpRight}@keyframes hinge{0%{transform-origin:top left;animation-timing-function:ease-in-out}20%,60%{transform:rotate(80deg);transform-origin:top left;animation-timing-function:ease-in-out}40%,80%{transform:rotate(60deg);transform-origin:top left;animation-timing-function:ease-in-out;opacity:1}to{transform:translate3d(0,700px,0);opacity:0}}.hinge{animation-name:hinge}@keyframes jackInTheBox{0%{opacity:0;transform:scale(.1) rotate(30deg);transform-origin:center bottom}50%{transform:rotate(-10deg)}70%{transform:rotate(3deg)}to{opacity:1;transform:scale(1)}}.jackInTheBox{animation-name:jackInTheBox}@keyframes rollIn{0%{opacity:0;transform:translate3d(-100%,0,0) rotate(-120deg)}to{opacity:1;transform:none}}.rollIn{animation-name:rollIn}@keyframes rollOut{0%{opacity:1}to{opacity:0;transform:translate3d(100%,0,0) rotate(120deg)}}.rollOut{animation-name:rollOut}@keyframes zoomIn{0%{opacity:0;transform:scale3d(.3,.3,.3)}50%{opacity:1}}.zoomIn{animation-name:zoomIn}@keyframes zoomInDown{0%{opacity:0;transform:scale3d(.1,.1,.1) translate3d(0,-1000px,0);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}60%{opacity:1;transform:scale3d(.475,.475,.475) translate3d(0,60px,0);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}.zoomInDown{animation-name:zoomInDown}@keyframes zoomInLeft{0%{opacity:0;transform:scale3d(.1,.1,.1) translate3d(-1000px,0,0);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}60%{opacity:1;transform:scale3d(.475,.475,.475) translate3d(10px,0,0);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}.zoomInLeft{animation-name:zoomInLeft}@keyframes zoomInRight{0%{opacity:0;transform:scale3d(.1,.1,.1) translate3d(1000px,0,0);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}60%{opacity:1;transform:scale3d(.475,.475,.475) translate3d(-10px,0,0);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}.zoomInRight{animation-name:zoomInRight}@keyframes zoomInUp{0%{opacity:0;transform:scale3d(.1,.1,.1) translate3d(0,1000px,0);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}60%{opacity:1;transform:scale3d(.475,.475,.475) translate3d(0,-60px,0);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}.zoomInUp{animation-name:zoomInUp}@keyframes zoomOut{0%{opacity:1}50%{opacity:0;transform:scale3d(.3,.3,.3)}to{opacity:0}}.zoomOut{animation-name:zoomOut}@keyframes zoomOutDown{40%{opacity:1;transform:scale3d(.475,.475,.475) translate3d(0,-60px,0);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}to{opacity:0;transform:scale3d(.1,.1,.1) translate3d(0,2000px,0);transform-origin:center bottom;animation-timing-function:cubic-bezier(.175,.885,.32,1)}}.zoomOutDown{animation-name:zoomOutDown}@keyframes zoomOutLeft{40%{opacity:1;transform:scale3d(.475,.475,.475) translate3d(42px,0,0)}to{opacity:0;transform:scale(.1) translate3d(-2000px,0,0);transform-origin:left center}}.zoomOutLeft{animation-name:zoomOutLeft}@keyframes zoomOutRight{40%{opacity:1;transform:scale3d(.475,.475,.475) translate3d(-42px,0,0)}to{opacity:0;transform:scale(.1) translate3d(2000px,0,0);transform-origin:right center}}.zoomOutRight{animation-name:zoomOutRight}@keyframes zoomOutUp{40%{opacity:1;transform:scale3d(.475,.475,.475) translate3d(0,60px,0);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}to{opacity:0;transform:scale3d(.1,.1,.1) translate3d(0,-2000px,0);transform-origin:center bottom;animation-timing-function:cubic-bezier(.175,.885,.32,1)}}.zoomOutUp{animation-name:zoomOutUp}@keyframes slideInDown{0%{transform:translate3d(0,-100%,0);visibility:visible}to{transform:translateZ(0)}}.slideInDown{animation-name:slideInDown}@keyframes slideInLeft{0%{transform:translate3d(-100%,0,0);visibility:visible}to{transform:translateZ(0)}}.slideInLeft{animation-name:slideInLeft}@keyframes slideInRight{0%{transform:translate3d(100%,0,0);visibility:visible}to{transform:translateZ(0)}}.slideInRight{animation-name:slideInRight}@keyframes slideInUp{0%{transform:translate3d(0,100%,0);visibility:visible}to{transform:translateZ(0)}}.slideInUp{animation-name:slideInUp}@keyframes slideOutDown{0%{transform:translateZ(0)}to{visibility:hidden;transform:translate3d(0,100%,0)}}.slideOutDown{animation-name:slideOutDown}@keyframes slideOutLeft{0%{transform:translateZ(0)}to{visibility:hidden;transform:translate3d(-100%,0,0)}}.slideOutLeft{animation-name:slideOutLeft}@keyframes slideOutRight{0%{transform:translateZ(0)}to{visibility:hidden;transform:translate3d(100%,0,0)}}.slideOutRight{animation-name:slideOutRight}@keyframes slideOutUp{0%{transform:translateZ(0)}to{visibility:hidden;transform:translate3d(0,-100%,0)}}.slideOutUp{animation-name:slideOutUp}
    \ No newline at end of file
    diff --git a/data/web/css/mailbox.css b/data/web/css/mailbox.css
    index 8db97c31..b76f3f29 100644
    --- a/data/web/css/mailbox.css
    +++ b/data/web/css/mailbox.css
    @@ -29,4 +29,4 @@ table.footable>tbody>tr.footable-empty>td {
       .container {
           width: 80%;
       }
    -}
    \ No newline at end of file
    +}
    diff --git a/data/web/inc/footer.inc.php b/data/web/inc/footer.inc.php
    index d809a160..05b7a599 100644
    --- a/data/web/inc/footer.inc.php
    +++ b/data/web/inc/footer.inc.php
    @@ -44,6 +44,7 @@ endif;
     <script src="/js/bootstrap-switch.min.js"></script>
     <script src="/js/bootstrap-slider.min.js"></script>
     <script src="/js/bootstrap-select.min.js"></script>
    +<script src="/js/notifications.min.js"></script>
     <script src="/js/u2f-api.js"></script>
     <script>
     // Select language and reopen active URL without POST
    @@ -53,14 +54,12 @@ function setLang(sel) {
     }
     
     $(document).ready(function() {
    -  function mailcow_alert_box(type, message) {
    -    $('.mailcow-alert-box').show();
    -    $('.mailcow-alert-box').addClass("alert-" + type);
    -    $('#mailcow-alert-text').text(message);
    +  function mailcow_alert_box(message, type) {
    +    $.notify({message: message},{type: type,placement: {from: "bottom",align: "right"},animate: {enter: 'animated fadeInUp',exit: 'animated fadeOutDown'}});
       }
    -  // PHP error handler
    -
    -
    +  <?php if (isset($_SESSION['return'])): ?>
    +  mailcow_alert_box("<?=$_SESSION['return']['msg'];?>",  "<?=$_SESSION['return']['type'];?>");
    +  <?php endif; unset($_SESSION['return']); ?>
       // Confirm TFA modal
       <?php if (isset($_SESSION['pending_tfa_method'])):?>
       $('#ConfirmTFAModal').modal({
    @@ -226,30 +225,9 @@ $(document).ready(function() {
     			}
     		});
     	});
    -
    -  if ($('#mailcow-alert').hasClass('alert-success')) {
    -    $('#mailcow-alert').delay(5000).animate({right: '-50%'}, 1000);
    -  };
     });
     </script>
     
    -<div class="container">
    -  <div id="mailcow-alert" class="alert" role="alert">
    -    <span id="mailcow-alert-text"></span>
    -  </div>
    -</div>
    -
     </body>
    -<?php // Notifications ?>
    -<script>
    -function mailcow_alert_box(msg, type) {
    -  document.getElementById('mailcow-alert').style.display = 'visible';
    -  document.getElementById('mailcow-alert-text').innerHTML = msg;
    -  document.getElementById("mailcow-alert").className = "alert alert-" + type;
    -}
    -<?php if (isset($_SESSION['return'])): ?>
    -mailcow_alert_box("<?=$_SESSION['return']['msg'];?>",  "<?=$_SESSION['return']['type'];?>");
    -<?php endif; unset($_SESSION['return']); ?>
    -</script>
     </html>
     <?php $stmt = null; $pdo = null; ?>
    diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php
    index 7d1594ad..0c0f69c3 100644
    --- a/data/web/inc/functions.inc.php
    +++ b/data/web/inc/functions.inc.php
    @@ -457,10 +457,6 @@ function get_time_limited_aliases($username = null) {
       $data = array();
       if (isset($username) && filter_var($username, FILTER_VALIDATE_EMAIL)) {
         if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['access_denied'])
    -      );
           return false;
         }
       }
    @@ -687,19 +683,11 @@ function get_policy_list($object = null) {
         if (!filter_var($object, FILTER_VALIDATE_EMAIL) && is_valid_domain_name($object)) {
           $object = idn_to_ascii(strtolower(trim($object)));
           if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $object)) {
    -        $_SESSION['return'] = array(
    -          'type' => 'danger',
    -          'msg' => sprintf($lang['danger']['access_denied'])
    -        );
             return false;
           }
         }
         elseif (filter_var($object, FILTER_VALIDATE_EMAIL)) {
           if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $object)) {
    -        $_SESSION['return'] = array(
    -          'type' => 'danger',
    -          'msg' => sprintf($lang['danger']['access_denied'])
    -        );
             return false;
           }
         }
    @@ -885,10 +873,6 @@ function get_syncjobs($username = null) {
       $data = array();
       if (isset($username) && filter_var($username, FILTER_VALIDATE_EMAIL)) {
         if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['access_denied'])
    -      );
           return false;
         }
       }
    @@ -916,17 +900,9 @@ function get_syncjob_details($id) {
       $syncjobdetails = array();
     	if ($_SESSION['mailcow_cc_role'] != "user" &&
     		$_SESSION['mailcow_cc_role'] != "admin") {
    -			$_SESSION['return'] = array(
    -				'type' => 'danger',
    -				'msg' => sprintf($lang['danger']['access_denied'])
    -			);
     			return false;
     	}
       if (!is_numeric($id)) {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['access_denied'])
    -    );
         return false;
       }
       try {
    @@ -1301,10 +1277,6 @@ function get_tls_policy($username = null) {
       $data = array();
       if (isset($username) && filter_var($username, FILTER_VALIDATE_EMAIL)) {
         if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['access_denied'])
    -      );
           return false;
         }
       }
    @@ -1687,26 +1659,14 @@ function get_domain_admin_details($domain_admin) {
     	global $lang;
       $domainadmindata = array();
     	if (isset($domain_admin) && $_SESSION['mailcow_cc_role'] != "admin") {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
     		return false;
     	}
       if (!isset($domain_admin) && $_SESSION['mailcow_cc_role'] != "domainadmin") {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
     		return false;
     	}
       (!isset($domain_admin)) ? $domain_admin = $_SESSION['mailcow_cc_username'] : null;
       
       if (!ctype_alnum(str_replace(array('_', '.', '-'), '', $domain_admin))) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['username_invalid'])
    -		);
     		return false;
     	}
       try {
    @@ -2351,10 +2311,6 @@ function get_admin_details() {
     	global $lang;
       $data = array();
       if ($_SESSION['mailcow_cc_role'] != 'admin') {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['access_denied'])
    -    );
         return false;
       }
       try {
    @@ -2469,15 +2425,16 @@ function dkim_add_key($postarray) {
       }
     }
     function dkim_get_key_details($domain) {
    -  $data = array();
       global $redis;
    -  if (hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    -    if ($redis_dkim_key_data = $redis->hGet('DKIM_PUB_KEYS', $domain)) {
    -      $data['pubkey'] = $redis_dkim_key_data;
    -      $data['length'] = (strlen($data['pubkey']) < 391) ? 1024 : 2048;
    -      $data['dkim_txt'] = 'v=DKIM1;k=rsa;t=s;s=email;p=' . $redis_dkim_key_data;
    -      $data['dkim_selector'] = $redis->hGet('DKIM_SELECTORS', $domain);
    -    }
    +  if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    +    return false;
    +  }
    +  $data = array();
    +  if ($redis_dkim_key_data = $redis->hGet('DKIM_PUB_KEYS', $domain)) {
    +    $data['pubkey'] = $redis_dkim_key_data;
    +    $data['length'] = (strlen($data['pubkey']) < 391) ? 1024 : 2048;
    +    $data['dkim_txt'] = 'v=DKIM1;k=rsa;t=s;s=email;p=' . $redis_dkim_key_data;
    +    $data['dkim_selector'] = $redis->hGet('DKIM_SELECTORS', $domain);
       }
       return $data;
     }
    @@ -2485,10 +2442,6 @@ function dkim_get_blind_keys() {
       global $redis;
     	global $lang;
       if ($_SESSION['mailcow_cc_role'] != "admin") {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['access_denied'])
    -    );
         return false;
       }
       $domains = array();
    @@ -4044,10 +3997,6 @@ function mailbox_get_mailboxes($domain = null) {
     	global $pdo;
       $mailboxes = array();
     	if (isset($domain) && !hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
     		return false;
     	}
       elseif (isset($domain) && hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    @@ -4096,10 +4045,6 @@ function mailbox_get_resources($domain = null) {
     	global $pdo;
       $resources = array();
     	if (isset($domain) && !hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
     		return false;
     	}
       elseif (isset($domain) && hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    @@ -4151,10 +4096,6 @@ function mailbox_get_alias_domains($domain = null) {
     	global $pdo;
       $aliasdomains = array();
     	if (isset($domain) && !hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
     		return false;
       }
       elseif (isset($domain) && hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    @@ -4203,10 +4144,6 @@ function mailbox_get_aliases($domain) {
     	global $pdo;
       $aliases = array();
     	if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
     		return false;
     	}
     
    @@ -4268,10 +4205,6 @@ function mailbox_get_alias_details($address) {
         $aliasdata['created'] = $row['created'];
         $aliasdata['modified'] = $row['modified'];
         if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $aliasdata['domain'])) {
    -      $_SESSION['return'] = array(
    -        'type' => 'danger',
    -        'msg' => sprintf($lang['danger']['access_denied'])
    -      );
           return false;
         }
       }
    @@ -4317,10 +4250,6 @@ function mailbox_get_alias_domain_details($aliasdomain) {
         return false;
       }
       if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $aliasdomaindata['target_domain'])) {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['access_denied'])
    -    );
         return false;
       }
       return $aliasdomaindata;
    @@ -4331,9 +4260,11 @@ function mailbox_get_domains() {
       // Domain does not need to be active
     	global $lang;
     	global $pdo;
    -
    +  $domains = array();
    +	if ($_SESSION['mailcow_cc_role'] != "admin" && $_SESSION['mailcow_cc_role'] != "domainadmin") {
    +    return false;
    +	}
       try {
    -    $domains = array();
         $stmt = $pdo->prepare("SELECT `domain` FROM `domain`
           WHERE (`domain` IN (
             SELECT `domain` from `domain_admins`
    @@ -4367,10 +4298,6 @@ function mailbox_get_domain_details($domain) {
     	$domain = idn_to_ascii(strtolower(trim($domain)));
     
     	if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
     		return false;
     	}
     
    @@ -4461,10 +4388,6 @@ function mailbox_get_mailbox_details($mailbox) {
     	global $lang;
     	global $pdo;
       if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $mailbox)) {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['access_denied'])
    -    );
         return false;
       }
       $mailboxdata = array();
    @@ -4538,10 +4461,6 @@ function mailbox_get_resource_details($resource) {
     	global $pdo;
       $resourcedata = array();
       if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $resource)) {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['access_denied'])
    -    );
         return false;
       }
       try {
    @@ -4579,10 +4498,6 @@ function mailbox_get_resource_details($resource) {
       }
       if (!isset($resourcedata['domain']) ||
         (isset($resourcedata['domain']) && !hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $resourcedata['domain']))) {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['access_denied'])
    -    );
         return false;
       }
       
    @@ -5047,10 +4962,6 @@ function mailbox_get_sender_acl_handles($mailbox) {
     	global $pdo;
     	global $lang;
     	if ($_SESSION['mailcow_cc_role'] != "admin" && $_SESSION['mailcow_cc_role'] != "domainadmin") {
    -    $_SESSION['return'] = array(
    -      'type' => 'danger',
    -      'msg' => sprintf($lang['danger']['access_denied'])
    -    );
         return false;
     	}
     
    @@ -5184,9 +5095,6 @@ function get_forwarding_host_details($host) {
       if (!isset($host) || empty($host)) {
         return false;
       }
    -  if (filter_var($host, FILTER_VALIDATE_IP)) {
    -    return;
    -  }
       try {
         if ($source = $redis->hGet('WHITELISTED_FWD_HOST', $host)) {
           $data['host'] = $host;
    @@ -5301,10 +5209,6 @@ function get_logs($container, $lines = 100) {
     	global $lang;
     	global $redis;
     	if ($_SESSION['mailcow_cc_role'] != "admin") {
    -		$_SESSION['return'] = array(
    -			'type' => 'danger',
    -			'msg' => sprintf($lang['danger']['access_denied'])
    -		);
     		return false;
     	}
       $lines = intval($lines);
    diff --git a/data/web/inc/header.inc.php b/data/web/inc/header.inc.php
    index 678c2590..ca692e0d 100644
    --- a/data/web/inc/header.inc.php
    +++ b/data/web/inc/header.inc.php
    @@ -18,6 +18,7 @@
     <link rel="stylesheet" href="/css/footable.bootstrap.min.css">
     <link rel="stylesheet" href="/inc/languages.min.css">
     <link rel="stylesheet" href="/css/mailcow.css">
    +<link rel="stylesheet" href="/css/animate.min.css">
     <?=(preg_match("/mailbox.php/i", $_SERVER['REQUEST_URI'])) ? '<link rel="stylesheet" href="/css/mailbox.css">' : null;?>
     <?=(preg_match("/admin.php/i", $_SERVER['REQUEST_URI'])) ? '<link rel="stylesheet" href="/css/admin.css">' : null;?>
     <link rel="shortcut icon" href="/favicon.png" type="image/png">
    diff --git a/data/web/inc/prerequisites.inc.php b/data/web/inc/prerequisites.inc.php
    index 8a96e66e..19b63e9b 100644
    --- a/data/web/inc/prerequisites.inc.php
    +++ b/data/web/inc/prerequisites.inc.php
    @@ -16,6 +16,18 @@ require_once $_SERVER['DOCUMENT_ROOT'] . '/inc/lib/vendor/autoload.php';
     $u2f = new u2flib_server\U2F('https://' . $_SERVER['HTTP_HOST']);
     $tfa = new RobThree\Auth\TwoFactorAuth('mailcow UI');
     
    +// OWASP CSRF Protector
    +$csrfProtector = new csrfProtector;
    +class mailcowCsrfProtector extends csrfprotector {
    +  public static function logCSRFattack() {
    +    $_SESSION['return'] = array(
    +      'type' => 'danger',
    +      'msg' => 'CSRF violation'
    +    );
    +  }
    +}
    +mailcowCsrfProtector::init();
    +
     // Redis
     $redis = new Redis();
     $redis->connect('redis-mailcow', 6379);
    diff --git a/data/web/js/mailbox.js b/data/web/js/mailbox.js
    index e1f0424f..5bd9a64e 100644
    --- a/data/web/js/mailbox.js
    +++ b/data/web/js/mailbox.js
    @@ -48,8 +48,8 @@ $(document).ready(function() {
             jsonp: false,
             complete: function (data) {
               // var reponse = (JSON.parse(data.responseText));
    -          // alert(reponse.type);
    -          // alert(reponse.msg);
    +          // console.log(reponse.type);
    +          // console.log(reponse.msg);
               location.assign(window.location);
             }
           });
    @@ -133,8 +133,8 @@ jQuery(function($){
             dataType: 'json',
             url: '/api/v1/get/domain/all',
             jsonp: false,
    -        error: function () {
    -          alert('Cannot draw domain table');
    +        error: function (data) {
    +          console.log('Cannot draw domain table');
             },
             success: function (data) {
               $.each(data, function (i, item) {
    @@ -201,7 +201,7 @@ jQuery(function($){
             url: '/api/v1/get/mailbox/all',
             jsonp: false,
             error: function () {
    -          alert('Cannot draw mailbox table');
    +          console.log('Cannot draw mailbox table');
             },
             success: function (data) {
               $.each(data, function (i, item) {
    @@ -260,7 +260,7 @@ jQuery(function($){
             url: '/api/v1/get/resource/all',
             jsonp: false,
             error: function () {
    -          alert('Cannot draw resource table');
    +          console.log('Cannot draw resource table');
             },
             success: function (data) {
               $.each(data, function (i, item) {
    @@ -304,7 +304,7 @@ jQuery(function($){
             url: '/api/v1/get/alias/all',
             jsonp: false,
             error: function () {
    -          alert('Cannot draw alias table');
    +          console.log('Cannot draw alias table');
             },
             success: function (data) {
               $.each(data, function (i, item) {
    @@ -353,7 +353,7 @@ jQuery(function($){
             url: '/api/v1/get/alias-domain/all',
             jsonp: false,
             error: function () {
    -          alert('Cannot draw alias domain table');
    +          console.log('Cannot draw alias domain table');
             },
             success: function (data) {
               $.each(data, function (i, item) {
    diff --git a/data/web/js/notifications.min.js b/data/web/js/notifications.min.js
    new file mode 100644
    index 00000000..01e7f309
    --- /dev/null
    +++ b/data/web/js/notifications.min.js
    @@ -0,0 +1 @@
    +!function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t("object"==typeof exports?require("jquery"):jQuery)}(function(t){function s(s){var e=!1;return t('[data-notify="container"]').each(function(i,n){var a=t(n),o=a.find('[data-notify="title"]').text().trim(),r=a.find('[data-notify="message"]').html().trim(),l=o===t("<div>"+s.settings.content.title+"</div>").html().trim(),d=r===t("<div>"+s.settings.content.message+"</div>").html().trim(),g=a.hasClass("alert-"+s.settings.type);return l&&d&&g&&(e=!0),!e}),e}function e(e,n,a){var o={content:{message:"object"==typeof n?n.message:n,title:n.title?n.title:"",icon:n.icon?n.icon:"",url:n.url?n.url:"#",target:n.target?n.target:"-"}};a=t.extend(!0,{},o,a),this.settings=t.extend(!0,{},i,a),this._defaults=i,"-"===this.settings.content.target&&(this.settings.content.target=this.settings.url_target),this.animations={start:"webkitAnimationStart oanimationstart MSAnimationStart animationstart",end:"webkitAnimationEnd oanimationend MSAnimationEnd animationend"},"number"==typeof this.settings.offset&&(this.settings.offset={x:this.settings.offset,y:this.settings.offset}),(this.settings.allow_duplicates||!this.settings.allow_duplicates&&!s(this))&&this.init()}var i={element:"body",position:null,type:"info",allow_dismiss:!0,allow_duplicates:!0,newest_on_top:!1,showProgressbar:!1,placement:{from:"top",align:"right"},offset:20,spacing:10,z_index:1031,delay:5e3,timer:1e3,url_target:"_blank",mouse_over:null,animate:{enter:"animated fadeInDown",exit:"animated fadeOutUp"},onShow:null,onShown:null,onClose:null,onClosed:null,icon_type:"class",template:'<div data-notify="container" class="col-xs-11 col-sm-4 alert alert-{0}" role="alert"><button type="button" aria-hidden="true" class="close" data-notify="dismiss">&times;</button><span data-notify="icon"></span> <span data-notify="title">{1}</span> <span data-notify="message">{2}</span><div class="progress" data-notify="progressbar"><div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div></div><a href="{3}" target="{4}" data-notify="url"></a></div>'};String.format=function(){for(var t=arguments[0],s=1;s<arguments.length;s++)t=t.replace(RegExp("\\{"+(s-1)+"\\}","gm"),arguments[s]);return t},t.extend(e.prototype,{init:function(){var t=this;this.buildNotify(),this.settings.content.icon&&this.setIcon(),"#"!=this.settings.content.url&&this.styleURL(),this.styleDismiss(),this.placement(),this.bind(),this.notify={$ele:this.$ele,update:function(s,e){var i={};"string"==typeof s?i[s]=e:i=s;for(var n in i)switch(n){case"type":this.$ele.removeClass("alert-"+t.settings.type),this.$ele.find('[data-notify="progressbar"] > .progress-bar').removeClass("progress-bar-"+t.settings.type),t.settings.type=i[n],this.$ele.addClass("alert-"+i[n]).find('[data-notify="progressbar"] > .progress-bar').addClass("progress-bar-"+i[n]);break;case"icon":var a=this.$ele.find('[data-notify="icon"]');"class"===t.settings.icon_type.toLowerCase()?a.removeClass(t.settings.content.icon).addClass(i[n]):(a.is("img")||a.find("img"),a.attr("src",i[n]));break;case"progress":var o=t.settings.delay-t.settings.delay*(i[n]/100);this.$ele.data("notify-delay",o),this.$ele.find('[data-notify="progressbar"] > div').attr("aria-valuenow",i[n]).css("width",i[n]+"%");break;case"url":this.$ele.find('[data-notify="url"]').attr("href",i[n]);break;case"target":this.$ele.find('[data-notify="url"]').attr("target",i[n]);break;default:this.$ele.find('[data-notify="'+n+'"]').html(i[n])}var r=this.$ele.outerHeight()+parseInt(t.settings.spacing)+parseInt(t.settings.offset.y);t.reposition(r)},close:function(){t.close()}}},buildNotify:function(){var s=this.settings.content;this.$ele=t(String.format(this.settings.template,this.settings.type,s.title,s.message,s.url,s.target)),this.$ele.attr("data-notify-position",this.settings.placement.from+"-"+this.settings.placement.align),this.settings.allow_dismiss||this.$ele.find('[data-notify="dismiss"]').css("display","none"),(this.settings.delay<=0&&!this.settings.showProgressbar||!this.settings.showProgressbar)&&this.$ele.find('[data-notify="progressbar"]').remove()},setIcon:function(){"class"===this.settings.icon_type.toLowerCase()?this.$ele.find('[data-notify="icon"]').addClass(this.settings.content.icon):this.$ele.find('[data-notify="icon"]').is("img")?this.$ele.find('[data-notify="icon"]').attr("src",this.settings.content.icon):this.$ele.find('[data-notify="icon"]').append('<img src="'+this.settings.content.icon+'" alt="Notify Icon" />')},styleDismiss:function(){this.$ele.find('[data-notify="dismiss"]').css({position:"absolute",right:"10px",top:"5px",zIndex:this.settings.z_index+2})},styleURL:function(){this.$ele.find('[data-notify="url"]').css({backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)",height:"100%",left:0,position:"absolute",top:0,width:"100%",zIndex:this.settings.z_index+1})},placement:function(){var s=this,e=this.settings.offset.y,i={display:"inline-block",margin:"0px auto",position:this.settings.position?this.settings.position:"body"===this.settings.element?"fixed":"absolute",transition:"all .5s ease-in-out",zIndex:this.settings.z_index},n=!1,a=this.settings;switch(t('[data-notify-position="'+this.settings.placement.from+"-"+this.settings.placement.align+'"]:not([data-closing="true"])').each(function(){e=Math.max(e,parseInt(t(this).css(a.placement.from))+parseInt(t(this).outerHeight())+parseInt(a.spacing))}),this.settings.newest_on_top===!0&&(e=this.settings.offset.y),i[this.settings.placement.from]=e+"px",this.settings.placement.align){case"left":case"right":i[this.settings.placement.align]=this.settings.offset.x+"px";break;case"center":i.left=0,i.right=0}this.$ele.css(i).addClass(this.settings.animate.enter),t.each(Array("webkit-","moz-","o-","ms-",""),function(t,e){s.$ele[0].style[e+"AnimationIterationCount"]=1}),t(this.settings.element).append(this.$ele),this.settings.newest_on_top===!0&&(e=parseInt(e)+parseInt(this.settings.spacing)+this.$ele.outerHeight(),this.reposition(e)),t.isFunction(s.settings.onShow)&&s.settings.onShow.call(this.$ele),this.$ele.one(this.animations.start,function(){n=!0}).one(this.animations.end,function(){s.$ele.removeClass(s.settings.animate.enter),t.isFunction(s.settings.onShown)&&s.settings.onShown.call(this)}),setTimeout(function(){n||t.isFunction(s.settings.onShown)&&s.settings.onShown.call(this)},600)},bind:function(){var s=this;if(this.$ele.find('[data-notify="dismiss"]').on("click",function(){s.close()}),this.$ele.mouseover(function(){t(this).data("data-hover","true")}).mouseout(function(){t(this).data("data-hover","false")}),this.$ele.data("data-hover","false"),this.settings.delay>0){s.$ele.data("notify-delay",s.settings.delay);var e=setInterval(function(){var t=parseInt(s.$ele.data("notify-delay"))-s.settings.timer;if("false"===s.$ele.data("data-hover")&&"pause"===s.settings.mouse_over||"pause"!=s.settings.mouse_over){var i=(s.settings.delay-t)/s.settings.delay*100;s.$ele.data("notify-delay",t),s.$ele.find('[data-notify="progressbar"] > div').attr("aria-valuenow",i).css("width",i+"%")}t<=-s.settings.timer&&(clearInterval(e),s.close())},s.settings.timer)}},close:function(){var s=this,e=parseInt(this.$ele.css(this.settings.placement.from)),i=!1;this.$ele.attr("data-closing","true").addClass(this.settings.animate.exit),s.reposition(e),t.isFunction(s.settings.onClose)&&s.settings.onClose.call(this.$ele),this.$ele.one(this.animations.start,function(){i=!0}).one(this.animations.end,function(){t(this).remove(),t.isFunction(s.settings.onClosed)&&s.settings.onClosed.call(this)}),setTimeout(function(){i||(s.$ele.remove(),s.settings.onClosed&&s.settings.onClosed(s.$ele))},600)},reposition:function(s){var e=this,i='[data-notify-position="'+this.settings.placement.from+"-"+this.settings.placement.align+'"]:not([data-closing="true"])',n=this.$ele.nextAll(i);this.settings.newest_on_top===!0&&(n=this.$ele.prevAll(i)),n.each(function(){t(this).css(e.settings.placement.from,s),s=parseInt(s)+parseInt(e.settings.spacing)+t(this).outerHeight()})}}),t.notify=function(t,s){var i=new e(this,t,s);return i.notify},t.notifyDefaults=function(s){return i=t.extend(!0,{},i,s)},t.notifyClose=function(s){"warning"===s&&(s="danger"),"undefined"==typeof s||"all"===s?t("[data-notify]").find('[data-notify="dismiss"]').trigger("click"):"success"===s||"info"===s||"warning"===s||"danger"===s?t(".alert-"+s+"[data-notify]").find('[data-notify="dismiss"]').trigger("click"):s?t(s+"[data-notify]").find('[data-notify="dismiss"]').trigger("click"):t('[data-notify-position="'+s+'"]').find('[data-notify="dismiss"]').trigger("click")},t.notifyCloseExcept=function(s){"warning"===s&&(s="danger"),"success"===s||"info"===s||"warning"===s||"danger"===s?t("[data-notify]").not(".alert-"+s).find('[data-notify="dismiss"]').trigger("click"):t("[data-notify]").not(s).find('[data-notify="dismiss"]').trigger("click")}});
    \ No newline at end of file
    diff --git a/data/web/mailbox.php b/data/web/mailbox.php
    index e35a3601..6853a9d9 100644
    --- a/data/web/mailbox.php
    +++ b/data/web/mailbox.php
    @@ -93,7 +93,7 @@ $_SESSION['return_to'] = $_SERVER['REQUEST_URI'];
                   <h3 class="panel-title"><?=$lang['mailbox']['resources'];?></h3>
                 </div>
                 <div class="table-responsive">
    -              <table id="resources_table" class="table table-striped"></table>
    +              <table id="resource_table" class="table table-striped"></table>
                 </div>
                 <div class="mass-actions-mailbox">
                   <div class="btn-group">
    
    From 66634b19fd56d1fbbc20b93a5dc1c0e7e886cc9f Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Sat, 13 May 2017 09:04:10 +0200
    Subject: [PATCH 39/49] Use more alpine images, thanks to K2rool
    
    ---
     docker-compose.yml | 8 ++++----
     1 file changed, 4 insertions(+), 4 deletions(-)
    
    diff --git a/docker-compose.yml b/docker-compose.yml
    index eb43d8d9..0d71648f 100644
    --- a/docker-compose.yml
    +++ b/docker-compose.yml
    @@ -41,7 +41,7 @@ services:
                 - mysql
     
         redis-mailcow:
    -      image: redis
    +      image: redis:alpine
           depends_on:
             - bind9-mailcow
           volumes:
    @@ -217,7 +217,7 @@ services:
                 - postfix
     
         memcached-mailcow:
    -      image: memcached
    +      image: memcached:alpine
           depends_on:
             - bind9-mailcow
           restart: always
    @@ -233,13 +233,13 @@ services:
           depends_on:
             - sogo-mailcow
             - php-fpm-mailcow
    -      image: nginx:mainline
    +      image: nginx:mainline-alpine
           healthcheck:
             test: ["CMD", "ping", "php-fpm-mailcow", "-c", "10"]
             interval: 10s
             timeout: 30s
             retries: 5
    -      command: /bin/bash -c "envsubst < /etc/nginx/conf.d/templates/listen_plain.template > /etc/nginx/conf.d/listen_plain.active &&
    +      command: /bin/sh -c "envsubst < /etc/nginx/conf.d/templates/listen_plain.template > /etc/nginx/conf.d/listen_plain.active &&
             envsubst < /etc/nginx/conf.d/templates/listen_ssl.template > /etc/nginx/conf.d/listen_ssl.active &&
             envsubst < /etc/nginx/conf.d/templates/server_name.template > /etc/nginx/conf.d/server_name.active &&
             nginx -g 'daemon off;'"
    
    From 0a90bdc4df0195893c11fa64e0da2c2c193ef245 Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Sat, 13 May 2017 09:42:17 +0200
    Subject: [PATCH 40/49] Fixes #264
    
    ---
     data/web/add.php   |  2 +-
     data/web/js/add.js | 15 +++++++++++----
     2 files changed, 12 insertions(+), 5 deletions(-)
    
    diff --git a/data/web/add.php b/data/web/add.php
    index 147619fd..d3c7ca95 100644
    --- a/data/web/add.php
    +++ b/data/web/add.php
    @@ -175,7 +175,7 @@ if (isset($_SESSION['mailcow_cc_role']) && ($_SESSION['mailcow_cc_role'] == "adm
     					<div class="form-group">
     						<label class="control-label col-sm-2" for="domain"><?=$lang['add']['domain'];?>:</label>
     						<div class="col-sm-10">
    -							<select id="addSelectDomain" name="domain" id="domain" title="<?=$lang['add']['select'];?>" required>
    +							<select id="addSelectDomain" name="domain" id="domain" required>
     							<?php
                   foreach (mailbox_get_domains() as $domain) {
     								echo "<option>".htmlspecialchars($domain)."</option>";
    diff --git a/data/web/js/add.js b/data/web/js/add.js
    index 05171d10..f8fc3809 100644
    --- a/data/web/js/add.js
    +++ b/data/web/js/add.js
    @@ -1,18 +1,25 @@
     $(document).ready(function() {
    -	// add.php
    -	// Get max. possible quota for a domain when domain field changes
    -	$('#addSelectDomain').on('change', function() {
    -		$.get("/api/v1/get/domain/" + this.value, function(data){
    +
    +  auto_fill_quota = function(domain) {
    +		$.get("/api/v1/get/domain/" + domain, function(data){
           var result = $.parseJSON(JSON.stringify(data));
           max_new_mailbox_quota = ( result.max_new_mailbox_quota / 1048576);
     			if (max_new_mailbox_quota != '0') {
     				$("#quotaBadge").html('max. ' +  max_new_mailbox_quota + ' MiB');
     				$('#addInputQuota').attr({"disabled": false, "value": "", "type": "number", "max": max_new_mailbox_quota});
    +				$('#addInputQuota').val(max_new_mailbox_quota);
     			}
     			else {
     				$("#quotaBadge").html('max. ' + max_new_mailbox_quota + ' MiB');
     				$('#addInputQuota').attr({"disabled": true, "value": "", "type": "text", "value": "n/a"});
    +				$('#addInputQuota').val(max_new_mailbox_quota);
     			}
     		});
    +  }
    +
    +	$('#addSelectDomain').on('change', function() {
    +    auto_fill_quota($('#addSelectDomain').val());
     	});
    +
    +  auto_fill_quota($('#addSelectDomain').val());
     });
    
    From d0d0961006bd6002f479b40743ea018d02f4d1b4 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Michael=20K=C3=A4ufl?= <mailcow@c.michael-kaeufl.de>
    Date: Sat, 13 May 2017 15:33:32 +0200
    Subject: [PATCH 41/49] [Dockerfiles] Replaced deprecated MAINTAINER with LABEL
    
    Used format proposed in
    https://docs.docker.com/engine/reference/builder/#maintainer-deprecated
    ---
     data/Dockerfiles/clamav/Dockerfile  | 2 +-
     data/Dockerfiles/dovecot/Dockerfile | 2 +-
     data/Dockerfiles/php-fpm/Dockerfile | 2 +-
     data/Dockerfiles/postfix/Dockerfile | 2 +-
     data/Dockerfiles/rmilter/Dockerfile | 2 +-
     data/Dockerfiles/rspamd/Dockerfile  | 2 +-
     data/Dockerfiles/sogo/Dockerfile    | 2 +-
     7 files changed, 7 insertions(+), 7 deletions(-)
    
    diff --git a/data/Dockerfiles/clamav/Dockerfile b/data/Dockerfiles/clamav/Dockerfile
    index 26867111..5ecde1c9 100755
    --- a/data/Dockerfiles/clamav/Dockerfile
    +++ b/data/Dockerfiles/clamav/Dockerfile
    @@ -1,5 +1,5 @@
     FROM debian:stretch-slim
    -MAINTAINER https://m-ko.de Markus Kosmal <code@cnfg.io>
    +LABEL maintainer "https://m-ko.de Markus Kosmal <code@cnfg.io>"
     
     # Debian Base to use
     ENV DEBIAN_VERSION stretch
    diff --git a/data/Dockerfiles/dovecot/Dockerfile b/data/Dockerfiles/dovecot/Dockerfile
    index 0a357855..a28b6628 100644
    --- a/data/Dockerfiles/dovecot/Dockerfile
    +++ b/data/Dockerfiles/dovecot/Dockerfile
    @@ -1,6 +1,6 @@
     FROM debian:stretch-slim
     #ubuntu:xenial
    -MAINTAINER Andre Peters <andre.peters@servercow.de>
    +LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
     ENV DEBIAN_FRONTEND noninteractive
     ENV LC_ALL C
    diff --git a/data/Dockerfiles/php-fpm/Dockerfile b/data/Dockerfiles/php-fpm/Dockerfile
    index ad03b8ad..0cee7e80 100644
    --- a/data/Dockerfiles/php-fpm/Dockerfile
    +++ b/data/Dockerfiles/php-fpm/Dockerfile
    @@ -1,5 +1,5 @@
     FROM php:7.1-fpm
    -MAINTAINER Andre Peters <andre.peters@servercow.de>
    +LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
     ENV DEBIAN_FRONTEND noninteractive
     
    diff --git a/data/Dockerfiles/postfix/Dockerfile b/data/Dockerfiles/postfix/Dockerfile
    index 4616ba9a..fbf8f10a 100644
    --- a/data/Dockerfiles/postfix/Dockerfile
    +++ b/data/Dockerfiles/postfix/Dockerfile
    @@ -1,5 +1,5 @@
     FROM debian:stretch-slim
    -MAINTAINER Andre Peters <andre.peters@servercow.de>
    +LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
     ENV DEBIAN_FRONTEND noninteractive
     ENV LC_ALL C
    diff --git a/data/Dockerfiles/rmilter/Dockerfile b/data/Dockerfiles/rmilter/Dockerfile
    index 1d5db5b0..366f675d 100644
    --- a/data/Dockerfiles/rmilter/Dockerfile
    +++ b/data/Dockerfiles/rmilter/Dockerfile
    @@ -1,5 +1,5 @@
     FROM debian:jessie-slim
    -MAINTAINER Andre Peters <andre.peters@servercow.de>
    +LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
     ENV DEBIAN_FRONTEND noninteractive
     ENV LC_ALL C
    diff --git a/data/Dockerfiles/rspamd/Dockerfile b/data/Dockerfiles/rspamd/Dockerfile
    index 5adb9dce..4d14c6f9 100644
    --- a/data/Dockerfiles/rspamd/Dockerfile
    +++ b/data/Dockerfiles/rspamd/Dockerfile
    @@ -1,5 +1,5 @@
     FROM debian:jessie-slim
    -MAINTAINER Andre Peters <andre.peters@servercow.de>
    +LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
     ENV DEBIAN_FRONTEND noninteractive
     ENV LC_ALL C
    diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile
    index b1b9d249..8210ab82 100644
    --- a/data/Dockerfiles/sogo/Dockerfile
    +++ b/data/Dockerfiles/sogo/Dockerfile
    @@ -1,5 +1,5 @@
     FROM debian:jessie-slim
    -MAINTAINER Andre Peters <andre.peters@servercow.de>
    +LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
     ENV DEBIAN_FRONTEND noninteractive
     ENV LC_ALL C
    
    From 9ab9d7624074b5567c4510e647b68a86eb71311b Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Michael=20K=C3=A4ufl?= <mailcow@c.michael-kaeufl.de>
    Date: Sat, 13 May 2017 15:52:16 +0200
    Subject: [PATCH 42/49] [Dockerfiles] Used best practices for apt-get
    
    See https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/#apt-get
    
    - Replaced `-y install` with `install -y` (unification)
    
    - Put every package on its own line
    
    - Moved `rm -rf /var/lib/apt/lists/*` in the same `RUN` statement as `apt-get`
    
    - Removed unnecessary `apt-get clean`
      See https://github.com/moby/moby/blob/03e2923e42446dbb830c654d0eec323a0b4ef02a/contrib/mkimage/debootstrap#L82-L105
    ---
     data/Dockerfiles/clamav/Dockerfile  |  8 +++-----
     data/Dockerfiles/dovecot/Dockerfile | 10 +++++-----
     data/Dockerfiles/php-fpm/Dockerfile |  7 ++++---
     data/Dockerfiles/postfix/Dockerfile |  9 +++++----
     data/Dockerfiles/rmilter/Dockerfile | 11 ++++++++---
     data/Dockerfiles/rspamd/Dockerfile  |  9 ++++++---
     data/Dockerfiles/sogo/Dockerfile    | 14 +++++++++-----
     7 files changed, 40 insertions(+), 28 deletions(-)
    
    diff --git a/data/Dockerfiles/clamav/Dockerfile b/data/Dockerfiles/clamav/Dockerfile
    index 5ecde1c9..b57fb143 100755
    --- a/data/Dockerfiles/clamav/Dockerfile
    +++ b/data/Dockerfiles/clamav/Dockerfile
    @@ -8,14 +8,12 @@ ENV DEBIAN_VERSION stretch
     RUN echo "deb http://http.debian.net/debian/ $DEBIAN_VERSION main contrib non-free" > /etc/apt/sources.list && \
     	echo "deb http://http.debian.net/debian/ $DEBIAN_VERSION-updates main contrib non-free" >> /etc/apt/sources.list && \
     	echo "deb http://security.debian.org/ $DEBIAN_VERSION/updates main contrib non-free" >> /etc/apt/sources.list && \
    -	apt-get update && \
    -	DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends -y -qq \
    +	apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \
     		clamav-daemon \
     		clamav-freshclam \
     		libclamunrar7 \
    -		curl && \
    -	apt-get clean && \
    -	rm -rf /var/lib/apt/lists/*
    +		curl \
    +	&& rm -rf /var/lib/apt/lists/*
     
     # initial update of av databases
     COPY dl_files.sh /dl_files.sh
    diff --git a/data/Dockerfiles/dovecot/Dockerfile b/data/Dockerfiles/dovecot/Dockerfile
    index a28b6628..375852f2 100644
    --- a/data/Dockerfiles/dovecot/Dockerfile
    +++ b/data/Dockerfiles/dovecot/Dockerfile
    @@ -7,8 +7,8 @@ ENV LC_ALL C
     ENV DOVECOT_VERSION 2.2.29.1
     ENV PIGEONHOLE_VERSION 0.4.18
     
    -RUN apt-get update \
    -	&& apt-get -y install libpam-dev \
    +RUN apt-get update && apt-get -y install \
    +	libpam-dev \
     	default-libmysqlclient-dev \
     	lzma-dev \
     	liblz-dev \
    @@ -48,7 +48,8 @@ RUN apt-get update \
     	libdbd-mysql-perl \
     	libipc-run-perl \
     	make \
    -	cpanminus
    +	cpanminus \
    +	&& rm -rf /var/lib/apt/lists/*
     
     
     RUN wget https://www.dovecot.org/releases/2.2/dovecot-$DOVECOT_VERSION.tar.gz -O - | tar xvz  \
    @@ -100,8 +101,7 @@ EXPOSE 24 10001
     ENTRYPOINT ["/docker-entrypoint.sh"]
     CMD exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
     
    -RUN apt-get clean \
    -	&& rm -rf /var/lib/apt/lists/* \
    +RUN rm -rf \
     	/tmp/* \
     	/var/tmp/* \
     	/dovecot-2.2-pigeonhole-$PIGEONHOLE_VERSION \
    diff --git a/data/Dockerfiles/php-fpm/Dockerfile b/data/Dockerfiles/php-fpm/Dockerfile
    index 0cee7e80..cfcfebb7 100644
    --- a/data/Dockerfiles/php-fpm/Dockerfile
    +++ b/data/Dockerfiles/php-fpm/Dockerfile
    @@ -3,14 +3,15 @@ LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
     ENV DEBIAN_FRONTEND noninteractive
     
    -RUN apt-get update \
    -	&& apt-get install -y zlib1g-dev \
    +RUN apt-get update && apt-get install -y \
    +	zlib1g-dev \
     	libicu-dev \
     	g++ \
     	libidn11-dev \
     	libxml2-dev \
     	redis-tools \
    -	mysql-client
    +	mysql-client \
    +	&& rm -rf /var/lib/apt/lists/*
     
     RUN docker-php-ext-configure intl
     RUN docker-php-ext-install intl pdo pdo_mysql xmlrpc
    diff --git a/data/Dockerfiles/postfix/Dockerfile b/data/Dockerfiles/postfix/Dockerfile
    index fbf8f10a..ace78f7a 100644
    --- a/data/Dockerfiles/postfix/Dockerfile
    +++ b/data/Dockerfiles/postfix/Dockerfile
    @@ -9,8 +9,8 @@ RUN dpkg-divert --local --rename --add /sbin/initctl \
     	&& dpkg-divert --local --rename --add /usr/bin/ischroot \
     	&& ln -sf /bin/true /usr/bin/ischroot
     
    -RUN apt-get update
    -RUN apt-get install -y --no-install-recommends supervisor \
    +RUN apt-get update && apt-get install -y --no-install-recommends \
    +	supervisor \
     	postfix \
     	sasl2-bin \
     	libsasl2-modules \
    @@ -25,7 +25,8 @@ RUN apt-get install -y --no-install-recommends supervisor \
     	python-gpgme \
     	sudo \
     	curl \
    -	dirmngr
    +	dirmngr \
    +	&& rm -rf /var/lib/apt/lists/*
     
     RUN addgroup --system --gid 600 zeyple
     RUN adduser --system --home /var/lib/zeyple --no-create-home --uid 600 --gid 600 --disabled-login zeyple
    @@ -44,4 +45,4 @@ EXPOSE 588
     
     CMD exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
     
    -RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
    +RUN rm -rf /tmp/* /var/tmp/*
    diff --git a/data/Dockerfiles/rmilter/Dockerfile b/data/Dockerfiles/rmilter/Dockerfile
    index 366f675d..725a2596 100644
    --- a/data/Dockerfiles/rmilter/Dockerfile
    +++ b/data/Dockerfiles/rmilter/Dockerfile
    @@ -6,8 +6,13 @@ ENV LC_ALL C
     
     RUN apt-key adv --fetch-keys http://rspamd.com/apt-stable/gpg.key \
     	&& echo "deb http://rspamd.com/apt-stable/ jessie main" > /etc/apt/sources.list.d/rspamd.list \
    -	&& apt-get update \
    -	&& apt-get --no-install-recommends -y --force-yes install rmilter cron syslog-ng syslog-ng-core supervisor
    +	&& apt-get update && apt-get install -y --force-yes --no-install-recommends \
    +		rmilter \
    +		cron \
    +		syslog-ng \
    +		syslog-ng-core \
    +		supervisor \
    +	&& rm -rf /var/lib/apt/lists/*
     
     COPY supervisord.conf /etc/supervisor/supervisord.conf
     
    @@ -18,4 +23,4 @@ RUN touch /var/log/mail.log && chmod 640 /var/log/mail.log && chown root:adm /va
     
     CMD exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
     
    -RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
    +RUN rm -rf /tmp/* /var/tmp/*
    diff --git a/data/Dockerfiles/rspamd/Dockerfile b/data/Dockerfiles/rspamd/Dockerfile
    index 4d14c6f9..bc0ecceb 100644
    --- a/data/Dockerfiles/rspamd/Dockerfile
    +++ b/data/Dockerfiles/rspamd/Dockerfile
    @@ -6,8 +6,11 @@ ENV LC_ALL C
     
     RUN apt-key adv --fetch-keys http://rspamd.com/apt-stable/gpg.key \
     	&& echo "deb http://rspamd.com/apt-stable/ jessie main" > /etc/apt/sources.list.d/rspamd.list \
    -	&& apt-get update \
    -	&& apt-get -y install rspamd ca-certificates python-pip
    +	&& apt-get update && apt-get install -y \
    +		rspamd \
    +		ca-certificates \
    +		python-pip \
    +	&& rm -rf /var/lib/apt/lists/*
     
     RUN echo '.include $LOCAL_CONFDIR/local.d/rspamd.conf.local' > /etc/rspamd/rspamd.conf.local
     
    @@ -18,7 +21,7 @@ RUN pip install -U oletools
     
     CMD /usr/bin/rspamd -f -u _rspamd -g _rspamd
     
    -RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
    +RUN rm -rf /tmp/* /var/tmp/*
     
     USER _rspamd
     
    diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile
    index 8210ab82..56dc1e75 100644
    --- a/data/Dockerfiles/sogo/Dockerfile
    +++ b/data/Dockerfiles/sogo/Dockerfile
    @@ -5,8 +5,9 @@ ENV DEBIAN_FRONTEND noninteractive
     ENV LC_ALL C
     ENV GOSU_VERSION 1.9
     
    -RUN apt-get update \
    -	&& apt-get install -y --no-install-recommends apt-transport-https gnupg \
    +RUN apt-get update && apt-get install -y --no-install-recommends \
    +		apt-transport-https \
    +		gnupg \
     		ca-certificates \
     		wget \
     		syslog-ng \
    @@ -14,6 +15,7 @@ RUN apt-get update \
     		supervisor \
     		mysql-client \
     		cron \
    +	&& rm -rf /var/lib/apt/lists/* \
     	&& dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \
     	&& wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \
     	&& wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch.asc" \
    @@ -29,8 +31,10 @@ RUN touch /usr/share/doc/sogo/empty.sh
     
     RUN apt-key adv --keyserver keys.gnupg.net --recv-key 0x810273C4 \
     	&& echo "deb http://packages.inverse.ca/SOGo/nightly/3/debian/ jessie jessie" > /etc/apt/sources.list.d/sogo.list \
    -	&& apt-get update \
    -	&& apt-get -y --force-yes install sogo sogo-activesync 
    +	&& apt-get update && apt-get install -y --force-yes \
    +		sogo \
    +		sogo-activesync \
    +	&& rm -rf /var/lib/apt/lists/*
     
     RUN sed -i -E 's/^(\s*)system\(\);/\1unix-stream("\/dev\/log");/' /etc/syslog-ng/syslog-ng.conf
     RUN echo '* * * * *   sogo   /usr/sbin/sogo-ealarms-notify' > /etc/cron.d/sogo
    @@ -42,4 +46,4 @@ COPY supervisord.conf /etc/supervisor/supervisord.conf
     
     CMD exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
     
    -RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
    +RUN rm -rf /tmp/* /var/tmp/*
    
    From 85be7aa973f4882346bc9ef65c11f83fa3b239fb Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Michael=20K=C3=A4ufl?= <mailcow@c.michael-kaeufl.de>
    Date: Sat, 13 May 2017 16:07:06 +0200
    Subject: [PATCH 43/49] [Dockerfiles] Sorted list of packages
    
    ---
     data/Dockerfiles/clamav/Dockerfile  |  2 +-
     data/Dockerfiles/dovecot/Dockerfile | 40 ++++++++++++++---------------
     data/Dockerfiles/php-fpm/Dockerfile |  6 ++---
     data/Dockerfiles/postfix/Dockerfile | 18 ++++++-------
     data/Dockerfiles/rmilter/Dockerfile |  4 +--
     data/Dockerfiles/rspamd/Dockerfile  |  2 +-
     data/Dockerfiles/sogo/Dockerfile    | 10 ++++----
     7 files changed, 41 insertions(+), 41 deletions(-)
    
    diff --git a/data/Dockerfiles/clamav/Dockerfile b/data/Dockerfiles/clamav/Dockerfile
    index b57fb143..63dcf118 100755
    --- a/data/Dockerfiles/clamav/Dockerfile
    +++ b/data/Dockerfiles/clamav/Dockerfile
    @@ -11,8 +11,8 @@ RUN echo "deb http://http.debian.net/debian/ $DEBIAN_VERSION main contrib non-fr
     	apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \
     		clamav-daemon \
     		clamav-freshclam \
    -		libclamunrar7 \
     		curl \
    +		libclamunrar7 \
     	&& rm -rf /var/lib/apt/lists/*
     
     # initial update of av databases
    diff --git a/data/Dockerfiles/dovecot/Dockerfile b/data/Dockerfiles/dovecot/Dockerfile
    index 375852f2..9664bc54 100644
    --- a/data/Dockerfiles/dovecot/Dockerfile
    +++ b/data/Dockerfiles/dovecot/Dockerfile
    @@ -8,47 +8,47 @@ ENV DOVECOT_VERSION 2.2.29.1
     ENV PIGEONHOLE_VERSION 0.4.18
     
     RUN apt-get update && apt-get -y install \
    -	libpam-dev \
    -	default-libmysqlclient-dev \
    -	lzma-dev \
    -	liblz-dev \
    -	libbz2-dev \
    -	liblz4-dev \
    -	liblzma-dev \
    -	build-essential \
    -	autotools-dev \
     	automake \
    -	syslog-ng \
    -	syslog-ng-core \
    -	syslog-ng-mod-redis \
    +	autotools-dev \
    +	build-essential \
     	ca-certificates \
    -	supervisor \
    -	wget \
    +	cpanminus \
     	curl \
    -	libssl-dev \
    +	default-libmysqlclient-dev \
     	libauthen-ntlm-perl \
    +	libbz2-dev \
     	libcrypt-ssleay-perl \
    +	libdbd-mysql-perl \
    +	libdbi-perl \
     	libdigest-hmac-perl \
     	libfile-copy-recursive-perl \
     	libio-compress-perl \
     	libio-socket-inet6-perl \
     	libio-socket-ssl-perl \
     	libio-tee-perl \
    +	libipc-run-perl \
    +	liblockfile-simple-perl \
    +	liblz-dev \
    +	liblz4-dev \
    +	liblzma-dev \
     	libmodule-scandeps-perl \
     	libnet-ssleay-perl \
    +	libpam-dev \
     	libpar-packer-perl \
     	libreadonly-perl \
    +	libssl-dev \
     	libterm-readkey-perl \
     	libtest-pod-perl \
     	libtest-simple-perl \
     	libunicode-string-perl \
     	liburi-perl \
    -	libdbi-perl \
    -	liblockfile-simple-perl \
    -	libdbd-mysql-perl \
    -	libipc-run-perl \
    +	lzma-dev \
     	make \
    -	cpanminus \
    +	supervisor \
    +	syslog-ng \
    +	syslog-ng-core \
    +	syslog-ng-mod-redis \
    +	wget \
     	&& rm -rf /var/lib/apt/lists/*
     
     
    diff --git a/data/Dockerfiles/php-fpm/Dockerfile b/data/Dockerfiles/php-fpm/Dockerfile
    index cfcfebb7..9d7e5c0b 100644
    --- a/data/Dockerfiles/php-fpm/Dockerfile
    +++ b/data/Dockerfiles/php-fpm/Dockerfile
    @@ -4,13 +4,13 @@ LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     ENV DEBIAN_FRONTEND noninteractive
     
     RUN apt-get update && apt-get install -y \
    -	zlib1g-dev \
    -	libicu-dev \
     	g++ \
    +	libicu-dev \
     	libidn11-dev \
     	libxml2-dev \
    -	redis-tools \
     	mysql-client \
    +	redis-tools \
    +	zlib1g-dev \
     	&& rm -rf /var/lib/apt/lists/*
     
     RUN docker-php-ext-configure intl
    diff --git a/data/Dockerfiles/postfix/Dockerfile b/data/Dockerfiles/postfix/Dockerfile
    index ace78f7a..ad7ca5f3 100644
    --- a/data/Dockerfiles/postfix/Dockerfile
    +++ b/data/Dockerfiles/postfix/Dockerfile
    @@ -10,22 +10,22 @@ RUN dpkg-divert --local --rename --add /sbin/initctl \
     	&& ln -sf /bin/true /usr/bin/ischroot
     
     RUN apt-get update && apt-get install -y --no-install-recommends \
    -	supervisor \
    -	postfix \
    -	sasl2-bin \
    +	ca-certificates \
    +	curl \
    +	dirmngr \
    +	gnupg \
     	libsasl2-modules \
     	postfix \
    +	postfix \
     	postfix-mysql \
     	postfix-pcre \
    +	python-gpgme \
    +	sasl2-bin \
    +	sudo \
    +	supervisor \
     	syslog-ng \
     	syslog-ng-core \
     	syslog-ng-mod-redis \
    -	ca-certificates \
    -	gnupg \
    -	python-gpgme \
    -	sudo \
    -	curl \
    -	dirmngr \
     	&& rm -rf /var/lib/apt/lists/*
     
     RUN addgroup --system --gid 600 zeyple
    diff --git a/data/Dockerfiles/rmilter/Dockerfile b/data/Dockerfiles/rmilter/Dockerfile
    index 725a2596..405dc90e 100644
    --- a/data/Dockerfiles/rmilter/Dockerfile
    +++ b/data/Dockerfiles/rmilter/Dockerfile
    @@ -7,11 +7,11 @@ ENV LC_ALL C
     RUN apt-key adv --fetch-keys http://rspamd.com/apt-stable/gpg.key \
     	&& echo "deb http://rspamd.com/apt-stable/ jessie main" > /etc/apt/sources.list.d/rspamd.list \
     	&& apt-get update && apt-get install -y --force-yes --no-install-recommends \
    -		rmilter \
     		cron \
    +		rmilter \
    +		supervisor \
     		syslog-ng \
     		syslog-ng-core \
    -		supervisor \
     	&& rm -rf /var/lib/apt/lists/*
     
     COPY supervisord.conf /etc/supervisor/supervisord.conf
    diff --git a/data/Dockerfiles/rspamd/Dockerfile b/data/Dockerfiles/rspamd/Dockerfile
    index bc0ecceb..61386754 100644
    --- a/data/Dockerfiles/rspamd/Dockerfile
    +++ b/data/Dockerfiles/rspamd/Dockerfile
    @@ -7,9 +7,9 @@ ENV LC_ALL C
     RUN apt-key adv --fetch-keys http://rspamd.com/apt-stable/gpg.key \
     	&& echo "deb http://rspamd.com/apt-stable/ jessie main" > /etc/apt/sources.list.d/rspamd.list \
     	&& apt-get update && apt-get install -y \
    -		rspamd \
     		ca-certificates \
     		python-pip \
    +		rspamd \
     	&& rm -rf /var/lib/apt/lists/*
     
     RUN echo '.include $LOCAL_CONFDIR/local.d/rspamd.conf.local' > /etc/rspamd/rspamd.conf.local
    diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile
    index 56dc1e75..054f5a77 100644
    --- a/data/Dockerfiles/sogo/Dockerfile
    +++ b/data/Dockerfiles/sogo/Dockerfile
    @@ -7,14 +7,14 @@ ENV GOSU_VERSION 1.9
     
     RUN apt-get update && apt-get install -y --no-install-recommends \
     		apt-transport-https \
    -		gnupg \
     		ca-certificates \
    -		wget \
    +		cron \
    +		gnupg \
    +		mysql-client \
    +		supervisor \
     		syslog-ng \
     		syslog-ng-core \
    -		supervisor \
    -		mysql-client \
    -		cron \
    +		wget \
     	&& rm -rf /var/lib/apt/lists/* \
     	&& dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \
     	&& wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \
    
    From 559d9dda719f44a7c67ddb329a0719cb57b1c600 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Michael=20K=C3=A4ufl?= <mailcow@c.michael-kaeufl.de>
    Date: Sat, 13 May 2017 16:11:04 +0200
    Subject: [PATCH 44/49] [Dockerfiles] Run rm as early as possible
    
    ---
     data/Dockerfiles/dovecot/Dockerfile | 10 +++++-----
     1 file changed, 5 insertions(+), 5 deletions(-)
    
    diff --git a/data/Dockerfiles/dovecot/Dockerfile b/data/Dockerfiles/dovecot/Dockerfile
    index 9664bc54..708ff8bd 100644
    --- a/data/Dockerfiles/dovecot/Dockerfile
    +++ b/data/Dockerfiles/dovecot/Dockerfile
    @@ -57,14 +57,16 @@ RUN wget https://www.dovecot.org/releases/2.2/dovecot-$DOVECOT_VERSION.tar.gz -O
     	&& ./configure --with-mysql --with-lzma --with-lz4 --with-ssl=openssl --with-notify=inotify --with-storages=mdbox,sdbox,maildir,mbox,imapc,pop3c --with-bzlib --with-zlib \
     	&& make -j3 \
     	&& make install \
    -	&& make clean
    +	&& make clean \
    +	&& cd .. && rm -rf dovecot-$DOVECOT_VERSION
     
     RUN wget https://pigeonhole.dovecot.org/releases/2.2/dovecot-2.2-pigeonhole-$PIGEONHOLE_VERSION.tar.gz -O - | tar xvz  \
     	&& cd dovecot-2.2-pigeonhole-$PIGEONHOLE_VERSION \
     	&& ./configure \
     	&& make -j3 \
     	&& make install \
    -	&& make clean
    +	&& make clean \
    +	&& cd .. && rm -rf dovecot-2.2-pigeonhole-$PIGEONHOLE_VERSION
     
     RUN cpanm Data::Uniqid Mail::IMAPClient String::Util
     RUN echo '* * * * *   root   /usr/local/bin/imapsync_cron.pl' > /etc/cron.d/imapsync
    @@ -103,6 +105,4 @@ CMD exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
     
     RUN rm -rf \
     	/tmp/* \
    -	/var/tmp/* \
    -	/dovecot-2.2-pigeonhole-$PIGEONHOLE_VERSION \
    -	/dovecot-$DOVECOT_VERSION
    +	/var/tmp/*
    
    From e081a847a19d841f2e269c5521a7d8ff92f8f110 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Michael=20K=C3=A4ufl?= <mailcow@c.michael-kaeufl.de>
    Date: Sat, 13 May 2017 16:28:23 +0200
    Subject: [PATCH 45/49] [Dockerfiles] Do not keep curl installed
    
    ---
     data/Dockerfiles/clamav/Dockerfile | 13 +++++++++++--
     1 file changed, 11 insertions(+), 2 deletions(-)
    
    diff --git a/data/Dockerfiles/clamav/Dockerfile b/data/Dockerfiles/clamav/Dockerfile
    index 63dcf118..ce37fe25 100755
    --- a/data/Dockerfiles/clamav/Dockerfile
    +++ b/data/Dockerfiles/clamav/Dockerfile
    @@ -11,14 +11,23 @@ RUN echo "deb http://http.debian.net/debian/ $DEBIAN_VERSION main contrib non-fr
     	apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \
     		clamav-daemon \
     		clamav-freshclam \
    -		curl \
     		libclamunrar7 \
     	&& rm -rf /var/lib/apt/lists/*
     
     # initial update of av databases
     COPY dl_files.sh /dl_files.sh
     RUN chmod +x /dl_files.sh
    -RUN /dl_files.sh
    +
    +RUN set -ex; \
    +	\
    +	fetchDeps=' \
    +		curl \
    +	'; \
    +	apt-get update; \
    +	apt-get install -y --no-install-recommends $fetchDeps; \
    +	rm -rf /var/lib/apt/lists/*; \
    +	/dl_files.sh \
    +	apt-get purge -y --auto-remove $fetchDeps
     
     # permission juggling
     RUN mkdir /var/run/clamav && \
    
    From 7fd982f948317af489ef9d886d51013518bbefb3 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Michael=20K=C3=A4ufl?= <mailcow@c.michael-kaeufl.de>
    Date: Sat, 13 May 2017 16:29:18 +0200
    Subject: [PATCH 46/49] [Dockerfiles] Do not persist
     DEBIAN_FRONTEND=noninteractive in images
    
    According to https://github.com/moby/moby/issues/4032#issuecomment-163689851
    (and some other comments in the issue) it's not recommended to set
    `DEBIAN_FRONTEND` via `ENV` in a Dockerfile.  `ARG` has the same
    effect at build time but does not change `DEBIAN_FRONTEND` in the
    final image, so I switched to it.  It should also work to remove it
    completely.
    ---
     data/Dockerfiles/clamav/Dockerfile  | 3 ++-
     data/Dockerfiles/dovecot/Dockerfile | 2 +-
     data/Dockerfiles/php-fpm/Dockerfile | 2 +-
     data/Dockerfiles/postfix/Dockerfile | 2 +-
     data/Dockerfiles/rmilter/Dockerfile | 2 +-
     data/Dockerfiles/rspamd/Dockerfile  | 2 +-
     data/Dockerfiles/sogo/Dockerfile    | 2 +-
     7 files changed, 8 insertions(+), 7 deletions(-)
    
    diff --git a/data/Dockerfiles/clamav/Dockerfile b/data/Dockerfiles/clamav/Dockerfile
    index ce37fe25..a2551677 100755
    --- a/data/Dockerfiles/clamav/Dockerfile
    +++ b/data/Dockerfiles/clamav/Dockerfile
    @@ -3,12 +3,13 @@ LABEL maintainer "https://m-ko.de Markus Kosmal <code@cnfg.io>"
     
     # Debian Base to use
     ENV DEBIAN_VERSION stretch
    +ARG DEBIAN_FRONTEND=noninteractive
     
     # initial install of av daemon
     RUN echo "deb http://http.debian.net/debian/ $DEBIAN_VERSION main contrib non-free" > /etc/apt/sources.list && \
     	echo "deb http://http.debian.net/debian/ $DEBIAN_VERSION-updates main contrib non-free" >> /etc/apt/sources.list && \
     	echo "deb http://security.debian.org/ $DEBIAN_VERSION/updates main contrib non-free" >> /etc/apt/sources.list && \
    -	apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \
    +	apt-get update && apt-get install -y -qq --no-install-recommends \
     		clamav-daemon \
     		clamav-freshclam \
     		libclamunrar7 \
    diff --git a/data/Dockerfiles/dovecot/Dockerfile b/data/Dockerfiles/dovecot/Dockerfile
    index 708ff8bd..1aafecd0 100644
    --- a/data/Dockerfiles/dovecot/Dockerfile
    +++ b/data/Dockerfiles/dovecot/Dockerfile
    @@ -2,7 +2,7 @@ FROM debian:stretch-slim
     #ubuntu:xenial
     LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
    -ENV DEBIAN_FRONTEND noninteractive
    +ARG DEBIAN_FRONTEND=noninteractive
     ENV LC_ALL C
     ENV DOVECOT_VERSION 2.2.29.1
     ENV PIGEONHOLE_VERSION 0.4.18
    diff --git a/data/Dockerfiles/php-fpm/Dockerfile b/data/Dockerfiles/php-fpm/Dockerfile
    index 9d7e5c0b..0d65040f 100644
    --- a/data/Dockerfiles/php-fpm/Dockerfile
    +++ b/data/Dockerfiles/php-fpm/Dockerfile
    @@ -1,7 +1,7 @@
     FROM php:7.1-fpm
     LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
    -ENV DEBIAN_FRONTEND noninteractive
    +ARG DEBIAN_FRONTEND=noninteractive
     
     RUN apt-get update && apt-get install -y \
     	g++ \
    diff --git a/data/Dockerfiles/postfix/Dockerfile b/data/Dockerfiles/postfix/Dockerfile
    index ad7ca5f3..e74e8725 100644
    --- a/data/Dockerfiles/postfix/Dockerfile
    +++ b/data/Dockerfiles/postfix/Dockerfile
    @@ -1,7 +1,7 @@
     FROM debian:stretch-slim
     LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
    -ENV DEBIAN_FRONTEND noninteractive
    +ARG DEBIAN_FRONTEND=noninteractive
     ENV LC_ALL C
     
     RUN dpkg-divert --local --rename --add /sbin/initctl \
    diff --git a/data/Dockerfiles/rmilter/Dockerfile b/data/Dockerfiles/rmilter/Dockerfile
    index 405dc90e..abe286f6 100644
    --- a/data/Dockerfiles/rmilter/Dockerfile
    +++ b/data/Dockerfiles/rmilter/Dockerfile
    @@ -1,7 +1,7 @@
     FROM debian:jessie-slim
     LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
    -ENV DEBIAN_FRONTEND noninteractive
    +ARG DEBIAN_FRONTEND=noninteractive
     ENV LC_ALL C
     
     RUN apt-key adv --fetch-keys http://rspamd.com/apt-stable/gpg.key \
    diff --git a/data/Dockerfiles/rspamd/Dockerfile b/data/Dockerfiles/rspamd/Dockerfile
    index 61386754..cb097a66 100644
    --- a/data/Dockerfiles/rspamd/Dockerfile
    +++ b/data/Dockerfiles/rspamd/Dockerfile
    @@ -1,7 +1,7 @@
     FROM debian:jessie-slim
     LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
    -ENV DEBIAN_FRONTEND noninteractive
    +ARG DEBIAN_FRONTEND=noninteractive
     ENV LC_ALL C
     
     RUN apt-key adv --fetch-keys http://rspamd.com/apt-stable/gpg.key \
    diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile
    index 054f5a77..475468b1 100644
    --- a/data/Dockerfiles/sogo/Dockerfile
    +++ b/data/Dockerfiles/sogo/Dockerfile
    @@ -1,7 +1,7 @@
     FROM debian:jessie-slim
     LABEL maintainer "Andre Peters <andre.peters@servercow.de>"
     
    -ENV DEBIAN_FRONTEND noninteractive
    +ARG DEBIAN_FRONTEND=noninteractive
     ENV LC_ALL C
     ENV GOSU_VERSION 1.9
     
    
    From 766a986f277b4c4c17034898761e68d55eba2e96 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Michael=20K=C3=A4ufl?= <mailcow@c.michael-kaeufl.de>
    Date: Sat, 13 May 2017 16:49:10 +0200
    Subject: [PATCH 47/49] [Dockerfiles] Do not install both curl and wget
    
    curl is used in rspamd-pipe-*, so I kept curl
    ---
     data/Dockerfiles/dovecot/Dockerfile | 5 ++---
     1 file changed, 2 insertions(+), 3 deletions(-)
    
    diff --git a/data/Dockerfiles/dovecot/Dockerfile b/data/Dockerfiles/dovecot/Dockerfile
    index 1aafecd0..b195510a 100644
    --- a/data/Dockerfiles/dovecot/Dockerfile
    +++ b/data/Dockerfiles/dovecot/Dockerfile
    @@ -48,11 +48,10 @@ RUN apt-get update && apt-get -y install \
     	syslog-ng \
     	syslog-ng-core \
     	syslog-ng-mod-redis \
    -	wget \
     	&& rm -rf /var/lib/apt/lists/*
     
     
    -RUN wget https://www.dovecot.org/releases/2.2/dovecot-$DOVECOT_VERSION.tar.gz -O - | tar xvz  \
    +RUN curl https://www.dovecot.org/releases/2.2/dovecot-$DOVECOT_VERSION.tar.gz | tar xvz  \
     	&& cd dovecot-$DOVECOT_VERSION \
     	&& ./configure --with-mysql --with-lzma --with-lz4 --with-ssl=openssl --with-notify=inotify --with-storages=mdbox,sdbox,maildir,mbox,imapc,pop3c --with-bzlib --with-zlib \
     	&& make -j3 \
    @@ -60,7 +59,7 @@ RUN wget https://www.dovecot.org/releases/2.2/dovecot-$DOVECOT_VERSION.tar.gz -O
     	&& make clean \
     	&& cd .. && rm -rf dovecot-$DOVECOT_VERSION
     
    -RUN wget https://pigeonhole.dovecot.org/releases/2.2/dovecot-2.2-pigeonhole-$PIGEONHOLE_VERSION.tar.gz -O - | tar xvz  \
    +RUN curl https://pigeonhole.dovecot.org/releases/2.2/dovecot-2.2-pigeonhole-$PIGEONHOLE_VERSION.tar.gz | tar xvz  \
     	&& cd dovecot-2.2-pigeonhole-$PIGEONHOLE_VERSION \
     	&& ./configure \
     	&& make -j3 \
    
    From 980acb507e0d276b0024e0bb21f35b71a7ac2af5 Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Sat, 13 May 2017 22:58:10 +0200
    Subject: [PATCH 48/49] Log to redis and file
    
    ---
     data/Dockerfiles/sogo/Dockerfile       |  7 +++--
     data/Dockerfiles/sogo/supervisord.conf |  2 +-
     data/Dockerfiles/sogo/syslog-ng.conf   | 37 ++++++++++++++++++++++++++
     3 files changed, 43 insertions(+), 3 deletions(-)
     create mode 100644 data/Dockerfiles/sogo/syslog-ng.conf
    
    diff --git a/data/Dockerfiles/sogo/Dockerfile b/data/Dockerfiles/sogo/Dockerfile
    index 475468b1..f1e820d7 100644
    --- a/data/Dockerfiles/sogo/Dockerfile
    +++ b/data/Dockerfiles/sogo/Dockerfile
    @@ -14,6 +14,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
     		supervisor \
     		syslog-ng \
     		syslog-ng-core \
    +		syslog-ng-mod-redis \
     		wget \
     	&& rm -rf /var/lib/apt/lists/* \
     	&& dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \
    @@ -36,12 +37,14 @@ RUN apt-key adv --keyserver keys.gnupg.net --recv-key 0x810273C4 \
     		sogo-activesync \
     	&& rm -rf /var/lib/apt/lists/*
     
    -RUN sed -i -E 's/^(\s*)system\(\);/\1unix-stream("\/dev\/log");/' /etc/syslog-ng/syslog-ng.conf
    -RUN echo '* * * * *   sogo   /usr/sbin/sogo-ealarms-notify' > /etc/cron.d/sogo
    +RUN echo '* * * * *   sogo   /usr/sbin/sogo-ealarms-notify 2>/dev/null' > /etc/cron.d/sogo
     RUN echo '* * * * *   sogo   /usr/sbin/sogo-tool expire-sessions 60' >> /etc/cron.d/sogo
     RUN echo '0 0 * * *   sogo   /usr/sbin/sogo-tool update-autoreply -p /etc/sogo/sieve.creds' >> /etc/cron.d/sogo
     
    +RUN touch /etc/default/locale
    +
     COPY ./reconf-domains.sh /
    +COPY syslog-ng.conf /etc/syslog-ng/syslog-ng.conf
     COPY supervisord.conf /etc/supervisor/supervisord.conf
     
     CMD exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
    diff --git a/data/Dockerfiles/sogo/supervisord.conf b/data/Dockerfiles/sogo/supervisord.conf
    index a2d32e76..6f8e6e35 100644
    --- a/data/Dockerfiles/sogo/supervisord.conf
    +++ b/data/Dockerfiles/sogo/supervisord.conf
    @@ -19,7 +19,7 @@ autorestart=true
     priority=10
     
     [program:sogo-syslog]
    -command=/usr/bin/tail -f /var/log/syslog -f /var/log/sogo/sogo.log
    +command=/usr/bin/tail -f /var/log/combined.log
     stdout_logfile=/dev/fd/1
     stdout_logfile_maxbytes=0
     
    diff --git a/data/Dockerfiles/sogo/syslog-ng.conf b/data/Dockerfiles/sogo/syslog-ng.conf
    new file mode 100644
    index 00000000..6e9ba2a2
    --- /dev/null
    +++ b/data/Dockerfiles/sogo/syslog-ng.conf
    @@ -0,0 +1,37 @@
    +@version: 3.5
    +@include "scl.conf"
    +options {
    +  chain_hostnames(off);
    +  flush_lines(0);
    +  use_dns(no);
    +  use_fqdn(no);
    +  owner("root"); group("adm"); perm(0640);
    +  stats_freq(0);
    +  bad_hostname("^gconfd$");
    +};
    +source s_src {
    +  unix-stream("/dev/log");
    +  internal();
    +};
    +source s_sogo {
    +  file("/var/log/sogo/sogo.log");
    +};
    +destination d_combined {
    +  file("/var/log/combined.log");
    +};
    +destination d_redis {
    +  redis(
    +    host("redis-mailcow")
    +    port(6379)
    +    command("LPUSH" "SOGO_LOG" "$(format-json time=\"$S_UNIXTIME\" priority=\"$PRIORITY\" program=\"$PROGRAM\" message=\"$MESSAGE\")\n")
    +  );
    +};
    +log {
    +  source(s_sogo);
    +  source(s_src);
    +  destination(d_combined);
    +};
    +log {
    +  source(s_sogo);
    +  destination(d_redis);
    +};
    
    From 2291b4e1215a0c541eb975c7f8b43df719753bbe Mon Sep 17 00:00:00 2001
    From: andryyy <andre.peters@debinux.de>
    Date: Sat, 13 May 2017 22:58:29 +0200
    Subject: [PATCH 49/49] Added SOGo logs
    
    ---
     data/web/admin.php             | 15 ++++++++++
     data/web/inc/functions.inc.php |  8 +++++
     data/web/js/admin.js           | 53 +++++++++++++++++++++++++++++++++-
     data/web/json_api.php          | 16 +++++++++-
     data/web/lang/lang.de.php      |  4 +--
     5 files changed, 92 insertions(+), 4 deletions(-)
    
    diff --git a/data/web/admin.php b/data/web/admin.php
    index 2d800622..384e20da 100644
    --- a/data/web/admin.php
    +++ b/data/web/admin.php
    @@ -328,6 +328,21 @@ $tfa_data = get_tfa();
             </div>
           </div>
         </div>
    +    <div class="panel panel-default">
    +      <div class="panel-heading">SOGo
    +        <div class="btn-group pull-right">
    +          <a class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown" href="#"><?=$lang['admin']['action'];?> <span class="caret"></span></a>
    +          <ul class="dropdown-menu">
    +            <li><a href="#" id="refresh_sogo_log"><?=$lang['admin']['refresh'];?></a></li>
    +          </ul>
    +        </div>
    +      </div>
    +      <div class="panel-body">
    +        <div class="table-responsive">
    +          <table class="table table-striped" id="sogo_log"></table>
    +        </div>
    +      </div>
    +    </div>
       </div>
     
       </div>
    diff --git a/data/web/inc/functions.inc.php b/data/web/inc/functions.inc.php
    index 0c0f69c3..a1a6d935 100644
    --- a/data/web/inc/functions.inc.php
    +++ b/data/web/inc/functions.inc.php
    @@ -5228,6 +5228,14 @@ function get_logs($container, $lines = 100) {
           return $data_array;
         }
       }
    +  if ($container == "sogo-mailcow") {
    +    if ($data = $redis->lRange('SOGO_LOG', 1, $lines)) {
    +      foreach ($data as $json_line) {
    +        $data_array[] = json_decode($json_line, true);
    +      }
    +      return $data_array;
    +    }
    +  }
       return false;
     }
     ?>
    diff --git a/data/web/js/admin.js b/data/web/js/admin.js
    index b0fdbbde..96c189be 100644
    --- a/data/web/js/admin.js
    +++ b/data/web/js/admin.js
    @@ -79,6 +79,10 @@ jQuery(function($){
         e.preventDefault();
         draw_dovecot_logs();
       });
    +  $("#refresh_sogo_log").on('click', function(e) {
    +    e.preventDefault();
    +    draw_sogo_logs();
    +  });
       function draw_postfix_logs() {
         ft_postfix_logs = FooTable.init('#postfix_log', {
           "columns": [
    @@ -126,6 +130,53 @@ jQuery(function($){
           }
         });
       }
    +  function draw_sogo_logs() {
    +    ft_sogo_logs = FooTable.init('#sogo_log', {
    +      "columns": [
    +        {"name":"time","formatter":function unix_time_format(tm) { var date = new Date(tm ? tm * 1000 : 0); return date.toLocaleString();},"title":lang.time,"style":{"width":"170px"}},
    +        {"name":"priority","title":lang.priority,"style":{"width":"80px"}},
    +        {"name":"message","title":lang.message},
    +      ],
    +      "rows": $.ajax({
    +        dataType: 'json',
    +        url: '/api/v1/get/logs/sogo/1000',
    +        jsonp: false,
    +        error: function () {
    +          console.log('Cannot draw sogo log table');
    +        },
    +        success: function (data) {
    +          $.each(data, function (i, item) {
    +            var danger_class = ["emerg", "alert", "crit"];
    +            var warning_class = ["warning"];
    +            var info_class = ["notice", "info", "debug"];
    +            if (jQuery.inArray(item.priority, danger_class) !== -1) {
    +              item.priority = '<span class="label label-danger">' + item.priority + '</span>';
    +            } 
    +            else if (jQuery.inArray(item.priority, warning_class) !== -1) {
    +              item.priority = '<span class="label label-warning">' + item.priority + '</span>';
    +            }
    +            else if (jQuery.inArray(item.priority, info_class) !== -1) {
    +              item.priority = '<span class="label label-info">' + item.priority + '</span>';
    +            }
    +          });
    +        }
    +      }),
    +      "empty": lang.empty,
    +      "paging": {
    +        "enabled": true,
    +        "limit": 5,
    +        "size": pagination_size
    +      },
    +      "filtering": {
    +        "enabled": true,
    +        "position": "left",
    +        "placeholder": lang.filter_table
    +      },
    +      "sorting": {
    +        "enabled": true
    +      }
    +    });
    +  }
       function draw_dovecot_logs() {
         ft_postfix_logs = FooTable.init('#dovecot_log', {
           "columns": [
    @@ -214,7 +265,6 @@ jQuery(function($){
           }
         });
       }
    -
       function draw_fwd_hosts() {
         ft_domainadmins = FooTable.init('#forwardinghoststable', {
           "columns": [
    @@ -260,6 +310,7 @@ jQuery(function($){
     
       draw_postfix_logs();
       draw_dovecot_logs();
    +  draw_sogo_logs();
       draw_domain_admins();
       draw_fwd_hosts();
     });
    \ No newline at end of file
    diff --git a/data/web/json_api.php b/data/web/json_api.php
    index 99dd1f16..0301659a 100644
    --- a/data/web/json_api.php
    +++ b/data/web/json_api.php
    @@ -80,7 +80,6 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                       echo '{}';
                     }
                   break;
    -
                   case "postfix":
                     if (isset($extra) && !empty($extra)) {
                       $extra = intval($extra);
    @@ -96,6 +95,21 @@ if (isset($_SESSION['mailcow_cc_role']) || isset($_SESSION['pending_mailcow_cc_u
                       echo '{}';
                     }
                   break;
    +              case "sogo":
    +                if (isset($extra) && !empty($extra)) {
    +                  $extra = intval($extra);
    +                  $logs = get_logs('sogo-mailcow', $extra);
    +                }
    +                else {
    +                  $logs = get_logs('sogo-mailcow', -1);
    +                }
    +                if (isset($logs) && !empty($logs)) {
    +                  echo json_encode($logs, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    +                }
    +                else {
    +                  echo '{}';
    +                }
    +              break;
                 }
               break;
               case "mailbox":
    diff --git a/data/web/lang/lang.de.php b/data/web/lang/lang.de.php
    index d1a8300d..a182ff4a 100644
    --- a/data/web/lang/lang.de.php
    +++ b/data/web/lang/lang.de.php
    @@ -33,8 +33,8 @@ $lang['danger']['alias_empty'] = 'Alias-Adresse darf nicht leer sein';
     $lang['danger']['goto_empty'] = 'Ziel-Adresse darf nicht leer sein';
     $lang['danger']['policy_list_from_exists'] = 'Ein Eintrag mit diesem Wert existiert bereits';
     $lang['danger']['policy_list_from_invalid'] = 'Eintrag hat ungültiges Format';
    -$lang['danger']['alias_invalid'] = 'Alias-Adrese ist ungültig';
    -$lang['danger']['goto_invalid'] = 'Ziel-Adrese ist ungültig';
    +$lang['danger']['alias_invalid'] = 'Alias-Adresse ist ungültig';
    +$lang['danger']['goto_invalid'] = 'Ziel-Adresse ist ungültig';
     $lang['danger']['last_key'] = 'Letzter Key kann nicht gelöscht werden';
     $lang['danger']['alias_domain_invalid'] = 'Alias-Domain ist ungültig';
     $lang['danger']['target_domain_invalid'] = 'Ziel-Domain ist ungültig';