From f664be190dbdf7d64c94ec53792b5afe3b4953e8 Mon Sep 17 00:00:00 2001 From: "mk.keck" Date: Wed, 15 Mar 2017 21:18:19 +0100 Subject: [PATCH 01/24] Version 2.2 Fork / Login Form * Login form * Added session class for login form * Display different navigations if user is logged in / logged out --- .gitignore | 1 + CHANGELOG | 9 + README.md | 3 +- add_group.php | 4 +- add_user.php | 4 +- configs/config_example.php | 12 +- edit_group.php | 4 +- edit_user.php | 4 +- groups.php | 8 +- includes/AdminClass.php | 2 +- includes/Session.php | 284 ++++++++++++++++++++++++ includes/ez_sql_sqlite3.php | 430 ++++++++++++++++++------------------ includes/header.php | 28 ++- index.php | 148 +++++++++---- remove_group.php | 4 +- remove_user.php | 4 +- users.php | 6 +- 17 files changed, 673 insertions(+), 282 deletions(-) create mode 100644 includes/Session.php diff --git a/.gitignore b/.gitignore index 1e2ca39..0a69696 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ /nbproject/ /doctemp/ /docs/ +/configs/auth.sqlite3 /configs/config.php /configs/config_live.php /configs/config_old.php diff --git a/CHANGELOG b/CHANGELOG index 90b1465..af0f11f 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -6,8 +6,17 @@ * @copyright Lex Brugman * @copyright Christian Beer * @copyright Ricardo Padilha + * @copyright 2017 Michael Keck */ +2017-03-15 +---------- +Changes: +* Login form +* Added session class for login form +* Display different navigations user is logged in / logged out + + Release: 2.2 Changes: * added UID/GID limits (from Greg Arnold) diff --git a/README.md b/README.md index c80a28e..a96c8c2 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,8 @@ Graphical User Interface for ProFTPd with MySQL and sqlite3 support © 2004 The Netherlands, Lex Brugman
© 2012 Christian Beer
-© 2015 Ricardo Padilha +© 2015 Ricardo Padilha
+© 2017 Michael Keck Published under the GPLv2 License (see LICENSE for details) diff --git a/add_group.php b/add_group.php index 334916f..86c826b 100644 --- a/add_group.php +++ b/add_group.php @@ -11,9 +11,11 @@ * */ +global $cfg; + include_once ("configs/config.php"); +include_once ("includes/Session.php"); include_once ("includes/AdminClass.php"); -global $cfg; $ac = new AdminClass($cfg); diff --git a/add_user.php b/add_user.php index ee890a1..885d080 100644 --- a/add_user.php +++ b/add_user.php @@ -11,9 +11,11 @@ * */ +global $cfg; + include_once ("configs/config.php"); +include_once ("includes/Session.php"); include_once ("includes/AdminClass.php"); -global $cfg; $ac = new AdminClass($cfg); diff --git a/configs/config_example.php b/configs/config_example.php index bb6a8cf..1dba1c5 100644 --- a/configs/config_example.php +++ b/configs/config_example.php @@ -12,6 +12,16 @@ $cfg = array(); +// Login data +$cfg['login'] = array( + // Username + 'username' => 'admin', + // Password + 'password' => 'password', + // Blowfish secret key (22 chars) + 'blowfish' => 'XBu5pjOTa8H7UIwYSzMZxD' +); + $cfg['table_users'] = "users"; $cfg['field_userid'] = "userid"; $cfg['field_id'] = "id"; @@ -78,4 +88,4 @@ //$cfg['db_type'] = "sqlite3"; //$cfg['db_path'] = "configs/"; //$cfg['db_name'] = "auth.sqlite3"; -?> + diff --git a/edit_group.php b/edit_group.php index ff42a4b..fc478b9 100644 --- a/edit_group.php +++ b/edit_group.php @@ -11,9 +11,11 @@ * */ +global $cfg; + include_once ("configs/config.php"); +include_once ("includes/Session.php"); include_once ("includes/AdminClass.php"); -global $cfg; $ac = new AdminClass($cfg); diff --git a/edit_user.php b/edit_user.php index b18da80..0c2fd4b 100644 --- a/edit_user.php +++ b/edit_user.php @@ -11,9 +11,11 @@ * */ +global $cfg; + include_once ("configs/config.php"); +include_once ("includes/Session.php"); include_once ("includes/AdminClass.php"); -global $cfg; $ac = new AdminClass($cfg); diff --git a/groups.php b/groups.php index fc964ac..768a57c 100644 --- a/groups.php +++ b/groups.php @@ -11,9 +11,11 @@ * */ +global $cfg; + include_once ("configs/config.php"); +include_once ("includes/Session.php"); include_once ("includes/AdminClass.php"); -global $cfg; $ac = new AdminClass($cfg); @@ -66,7 +68,7 @@ get_user_count_by_gid($g_gid); + $n_main = $ac->get_user_count_by_gid($g_gid); $n_add = $ac->get_user_add_count_by_gid($g_gid); ?> @@ -96,4 +98,4 @@ - \ No newline at end of file + diff --git a/includes/AdminClass.php b/includes/AdminClass.php index 98b4a4e..06dd2bd 100644 --- a/includes/AdminClass.php +++ b/includes/AdminClass.php @@ -654,4 +654,4 @@ function is_valid_id($id) { return is_numeric($id) && (int)$id > 0 && $id == round($id); } } -?> + diff --git a/includes/Session.php b/includes/Session.php new file mode 100644 index 0000000..a946094 --- /dev/null +++ b/includes/Session.php @@ -0,0 +1,284 @@ + $_POST['username'], + 'password' => $_POST['password'], + ) + ); + header('Location: ./'); + exit(); + } + if (isset($_GET['logout'])) { + Session::user( + $cfg['login'], + 'logout' + ); + header('Location: ./?login'); + exit(); + } + if (!Session::user($cfg['login'])) { + if (!isset($_GET['login'])) { + header('Location: ./?login'); + exit(); + } + } + else { + $session_valid = true; + } +} diff --git a/includes/ez_sql_sqlite3.php b/includes/ez_sql_sqlite3.php index 1b25241..732a154 100644 --- a/includes/ez_sql_sqlite3.php +++ b/includes/ez_sql_sqlite3.php @@ -1,215 +1,215 @@ - 'Require $dbpath and $dbname to open an SQLite database' - ); - - /********************************************************************** - * ezSQL Database specific class - SQLite - */ - - if ( ! class_exists ('SQLite3') ) die('Fatal Error: ezSQL_sqlite3 requires SQLite3 Lib to be compiled and or linked in to the PHP engine'); - if ( ! class_exists ('ezSQLcore') ) die('Fatal Error: ezSQL_sqlite3 requires ezSQLcore (ez_sql_core.php) to be included/loaded before it can be used'); - - class ezSQL_sqlite3 extends ezSQLcore - { - - var $rows_affected = false; - - /********************************************************************** - * Constructor - allow the user to perform a quick connect at the - * same time as initialising the ezSQL_sqlite3 class - */ - - function ezSQL_sqlite3($dbpath='', $dbname='') - { - // Turn on track errors - ini_set('track_errors',1); - - if ( $dbpath && $dbname ) - { - $this->connect($dbpath, $dbname); - } - } - - /********************************************************************** - * Try to connect to SQLite database server - */ - - function connect($dbpath='', $dbname='') - { - global $ezsql_sqlite3_str; $return_val = false; - - // Must have a user and a password - if ( ! $dbpath || ! $dbname ) - { - $this->register_error($ezsql_sqlite3_str[1].' in '.__FILE__.' on line '.__LINE__); - $this->show_errors ? trigger_error($ezsql_sqlite3_str[1],E_USER_WARNING) : null; - } - // Try to establish the server database handle - else if ( ! $this->dbh = @new SQLite3($dbpath.$dbname) ) - { - $this->register_error($php_errormsg); - $this->show_errors ? trigger_error($php_errormsg,E_USER_WARNING) : null; - } - else - { - $return_val = true; - $this->conn_queries = 0; - } - - return $return_val; - } - - /********************************************************************** - * In the case of SQLite quick_connect is not really needed - * because std. connect already does what quick connect does - - * but for the sake of consistency it has been included - */ - - function quick_connect($dbpath='', $dbname='') - { - return $this->connect($dbpath, $dbname); - } - - /********************************************************************** - * No real equivalent of mySQL select in SQLite - * once again, function included for the sake of consistency - */ - - function select($dbpath='', $dbname='') - { - return $this->connect($dbpath, $dbname); - } - - /********************************************************************** - * Format a SQLite string correctly for safe SQLite insert - * (no mater if magic quotes are on or not) - */ - - function escape($str) - { - return $this->dbh->escapeString(stripslashes(preg_replace("/[\r\n]/",'',$str))); - } - - /********************************************************************** - * Return SQLite specific system date syntax - * i.e. Oracle: SYSDATE Mysql: NOW() - */ - - function sysdate() - { - return 'now'; - } - - /********************************************************************** - * Perform SQLite query and try to detirmin result value - */ - - // ================================================================== - // Basic Query - see docs for more detail - - function query($query) - { - - // For reg expressions - $query = str_replace("/[\n\r]/",'',trim($query)); - - // initialise return - $return_val = 0; - - // Flush cached values.. - $this->flush(); - - // Log how the function was called - $this->func_call = "\$db->query(\"$query\")"; - - // Keep track of the last query for debug.. - $this->last_query = $query; - - // Perform the query via std mysql_query function.. - $this->result = $this->dbh->query($query); - $this->count(true, true); - - // If there is an error then take note of it.. - if (@$this->dbh->lastErrorCode()) - { - $err_str = $this->dbh->lastErrorMsg(); - $this->register_error($err_str); - $this->show_errors ? trigger_error($err_str,E_USER_WARNING) : null; - return false; - } - - // Query was an insert, delete, update, replace - if ( preg_match("/^(insert|delete|update|replace)\s+/i",$query) ) - { - $this->rows_affected = @$this->dbh->changes(); - - // Take note of the insert_id - if ( preg_match("/^(insert|replace)\s+/i",$query) ) - { - $this->insert_id = @$this->dbh->lastInsertRowID(); - } - - // Return number fo rows affected - $return_val = $this->rows_affected; - - } - // Query was an select - else - { - - // Take note of column info - $i=0; - $this->col_info = array(); - while ($i < @$this->result->numColumns()) - { - $this->col_info[$i] = new StdClass; - $this->col_info[$i]->name = $this->result->columnName($i); - $this->col_info[$i]->type = null; - $this->col_info[$i]->max_length = null; - $i++; - } - - // Store Query Results - $num_rows=0; - while ($row = @$this->result->fetchArray(SQLITE3_ASSOC)) - { - // Store relults as an objects within main array - $obj= (object) $row; //convert to object - $this->last_result[$num_rows] = $obj; - $num_rows++; - } - - // Log number of rows the query returned - $this->num_rows = $num_rows; - - // Return number of rows selected - $return_val = $this->num_rows; - - } - - // If debug ALL queries - $this->trace||$this->debug_all ? $this->debug() : null ; - - return $return_val; - - } - - } - + 'Require $dbpath and $dbname to open an SQLite database' + ); + + /********************************************************************** + * ezSQL Database specific class - SQLite + */ + + if ( ! class_exists ('SQLite3') ) die('Fatal Error: ezSQL_sqlite3 requires SQLite3 Lib to be compiled and or linked in to the PHP engine'); + if ( ! class_exists ('ezSQLcore') ) die('Fatal Error: ezSQL_sqlite3 requires ezSQLcore (ez_sql_core.php) to be included/loaded before it can be used'); + + class ezSQL_sqlite3 extends ezSQLcore + { + + var $rows_affected = false; + + /********************************************************************** + * Constructor - allow the user to perform a quick connect at the + * same time as initialising the ezSQL_sqlite3 class + */ + + function ezSQL_sqlite3($dbpath='', $dbname='') + { + // Turn on track errors + ini_set('track_errors',1); + + if ( $dbpath && $dbname ) + { + $this->connect($dbpath, $dbname); + } + } + + /********************************************************************** + * Try to connect to SQLite database server + */ + + function connect($dbpath='', $dbname='') + { + global $ezsql_sqlite3_str; $return_val = false; + + // Must have a user and a password + if ( ! $dbpath || ! $dbname ) + { + $this->register_error($ezsql_sqlite3_str[1].' in '.__FILE__.' on line '.__LINE__); + $this->show_errors ? trigger_error($ezsql_sqlite3_str[1],E_USER_WARNING) : null; + } + // Try to establish the server database handle + else if ( ! $this->dbh = @new SQLite3($dbpath.$dbname) ) + { + $this->register_error($php_errormsg); + $this->show_errors ? trigger_error($php_errormsg,E_USER_WARNING) : null; + } + else + { + $return_val = true; + $this->conn_queries = 0; + } + + return $return_val; + } + + /********************************************************************** + * In the case of SQLite quick_connect is not really needed + * because std. connect already does what quick connect does - + * but for the sake of consistency it has been included + */ + + function quick_connect($dbpath='', $dbname='') + { + return $this->connect($dbpath, $dbname); + } + + /********************************************************************** + * No real equivalent of mySQL select in SQLite + * once again, function included for the sake of consistency + */ + + function select($dbpath='', $dbname='') + { + return $this->connect($dbpath, $dbname); + } + + /********************************************************************** + * Format a SQLite string correctly for safe SQLite insert + * (no mater if magic quotes are on or not) + */ + + function escape($str) + { + return $this->dbh->escapeString(stripslashes(preg_replace("/[\r\n]/",'',$str))); + } + + /********************************************************************** + * Return SQLite specific system date syntax + * i.e. Oracle: SYSDATE Mysql: NOW() + */ + + function sysdate() + { + return 'now'; + } + + /********************************************************************** + * Perform SQLite query and try to detirmin result value + */ + + // ================================================================== + // Basic Query - see docs for more detail + + function query($query) + { + + // For reg expressions + $query = str_replace("/[\n\r]/",'',trim($query)); + + // initialise return + $return_val = 0; + + // Flush cached values.. + $this->flush(); + + // Log how the function was called + $this->func_call = "\$db->query(\"$query\")"; + + // Keep track of the last query for debug.. + $this->last_query = $query; + + // Perform the query via std mysql_query function.. + $this->result = $this->dbh->query($query); + $this->count(true, true); + + // If there is an error then take note of it.. + if (@$this->dbh->lastErrorCode()) + { + $err_str = $this->dbh->lastErrorMsg(); + $this->register_error($err_str); + $this->show_errors ? trigger_error($err_str,E_USER_WARNING) : null; + return false; + } + + // Query was an insert, delete, update, replace + if ( preg_match("/^(insert|delete|update|replace)\s+/i",$query) ) + { + $this->rows_affected = @$this->dbh->changes(); + + // Take note of the insert_id + if ( preg_match("/^(insert|replace)\s+/i",$query) ) + { + $this->insert_id = @$this->dbh->lastInsertRowID(); + } + + // Return number fo rows affected + $return_val = $this->rows_affected; + + } + // Query was an select + else + { + + // Take note of column info + $i=0; + $this->col_info = array(); + while ($i < @$this->result->numColumns()) + { + $this->col_info[$i] = new StdClass; + $this->col_info[$i]->name = $this->result->columnName($i); + $this->col_info[$i]->type = null; + $this->col_info[$i]->max_length = null; + $i++; + } + + // Store Query Results + $num_rows=0; + while ($row = @$this->result->fetchArray(SQLITE3_ASSOC)) + { + // Store relults as an objects within main array + $obj= (object) $row; //convert to object + $this->last_result[$num_rows] = $obj; + $num_rows++; + } + + // Log number of rows the query returned + $this->num_rows = $num_rows; + + // Return number of rows selected + $return_val = $this->num_rows; + + } + + // If debug ALL queries + $this->trace||$this->debug_all ? $this->debug() : null ; + + return $return_val; + + } + + } + diff --git a/includes/header.php b/includes/header.php index bbd40a7..1224aec 100644 --- a/includes/header.php +++ b/includes/header.php @@ -19,11 +19,29 @@ diff --git a/index.php b/index.php index 8a8b45e..3898094 100644 --- a/index.php +++ b/index.php @@ -11,68 +11,120 @@ * */ +global $cfg; + include_once ("configs/config.php"); +include_once ("includes/Session.php"); include_once ("includes/AdminClass.php"); -global $cfg; + $ac = new AdminClass($cfg); include ("includes/header.php"); -?> - +include ("includes/messages.php"); -
-
-
-

Groups

-
-
-
-
-

Groups in database:

-
-
-

get_group_count(); ?>

-
-
-

Empty groups in database:

-
-
-

get_group_count(true); ?>

-
-
-

View groups »

+ +if ( + ( + (!isset($session_usage) || $session_usage !== true) && + (!isset($session_valid) || $session_valid !== true) + ) || ( + isset($session_usage) && $session_usage === true && + isset($session_valid) && $session_valid === true + ) + ) { + ?> +
+
+
+

Groups

+
+
+
+
+

Groups in database:

+
+
+

get_group_count(); ?>

+
+
+

Empty groups in database:

+
+
+

get_group_count(TRUE); ?>

+
+
-
-
-
-
-

Users

-
-
-
-
-

Users in database:

-
-
-

get_user_count(); ?>

-
-
-

Deactivated users in database:

-
-
-

get_user_count(true); ?>

-
-
-

View users »

+
+
+
+

Users

+
+
+
+
+

Users in database:

+
+
+

get_user_count(); ?>

+
+
+

Deactivated users in database:

+
+
+

get_user_count(TRUE); ?>

+
+
-
+ +
+
+
+

+ Login +

+
+
+ +
+
+
+ + +
+
+
+
+ + +
+
+
+
+ +
+
+
- \ No newline at end of file +
+
+
+ diff --git a/remove_group.php b/remove_group.php index 74a3e4f..aa44e67 100644 --- a/remove_group.php +++ b/remove_group.php @@ -11,9 +11,11 @@ * */ +global $cfg; + include_once ("configs/config.php"); +include_once ("includes/Session.php"); include_once ("includes/AdminClass.php"); -global $cfg; $ac = new AdminClass($cfg); diff --git a/remove_user.php b/remove_user.php index 14b885b..c682882 100644 --- a/remove_user.php +++ b/remove_user.php @@ -11,9 +11,11 @@ * */ +global $cfg; + include_once ("configs/config.php"); +include_once ("includes/Session.php"); include_once ("includes/AdminClass.php"); -global $cfg; $ac = new AdminClass($cfg); diff --git a/users.php b/users.php index 440e27b..43d460b 100644 --- a/users.php +++ b/users.php @@ -11,9 +11,11 @@ * */ +global $cfg; + include_once ("configs/config.php"); +include_once ("includes/Session.php"); include_once ("includes/AdminClass.php"); -global $cfg; $ac = new AdminClass($cfg); @@ -61,7 +63,7 @@ /* filter users */ if (!empty($all_users)) { - foreach ($all_users as $user) { + foreach ($all_users as $user) { if ($ufilter != "") { if ($ufilter == "None" && strpos($user[$field_userid], $cfg['userid_filter_separator'])) { // filter is None and user has a prefix From a0ed02f0fe955d7284c4549f67d187b5ed1117c2 Mon Sep 17 00:00:00 2001 From: "mk.keck" Date: Thu, 16 Mar 2017 09:38:11 +0100 Subject: [PATCH 02/24] Version 2.2 Fork / Description for login details in config Better description for login details in config_example.php --- configs/config_example.php | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/configs/config_example.php b/configs/config_example.php index 1dba1c5..2fafae5 100644 --- a/configs/config_example.php +++ b/configs/config_example.php @@ -12,13 +12,18 @@ $cfg = array(); -// Login data +/** + * Login data + * + * Important: Please change this values in + * live systems! + */ $cfg['login'] = array( - // Username + /* Username. Please use any username you want */ 'username' => 'admin', - // Password + /* Password. CHANGE IT and use secure password! */ 'password' => 'password', - // Blowfish secret key (22 chars) + /* Blowfish secret key (22 chars). CHANGE IT! */ 'blowfish' => 'XBu5pjOTa8H7UIwYSzMZxD' ); From 748547ba6e238a9c2a6ec7a4c6531e41c7ea1134 Mon Sep 17 00:00:00 2001 From: "mk.keck" Date: Thu, 16 Mar 2017 09:43:51 +0100 Subject: [PATCH 03/24] Version 2.2 Fork / Update README.md * Readme section restructured * Config / Install description updated for admin login * Linking to Issues * Linking to original project from Christian Beer --- README.md | 168 ++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 113 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index a96c8c2..f2793f7 100644 --- a/README.md +++ b/README.md @@ -2,57 +2,36 @@ Graphical User Interface for ProFTPd with MySQL and sqlite3 support -© 2004 The Netherlands, Lex Brugman
-© 2012 Christian Beer
-© 2015 Ricardo Padilha
-© 2017 Michael Keck -Published under the GPLv2 License (see LICENSE for details) -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License version 2, -as published by the Free Software Foundation. +## About ProFTPd Admin -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, download from http://www.gnu.org/licenses/gpl-2.0.txt - -## Information about ProFTPd Admin -This GUI for ProFTPd was written to support a basic user management feature when using the SQL module. Originally written by Lex Brugmann in 2004 it was updated by Christian Beer in 2012 to support the latest PHP version. +This GUI for ProFTPd was written to support a basic user management feature +when using the SQL module. Originally written by Lex Brugmann in 2004, +updated by [Christian Beer](https://github.com/ChristianBeer/ProFTPd-Admin) +in 2012 to support the latest PHP version. +2017 updated by Michael Keck with build-in login for the admin user. -There is no build-in security, so you have to protect the directory with something else, like Apache Basic Authentication. +It's possible to use either of SHA1 and pbkdf2 with either of MySQL/MariaDB +and sqlite3. pbkdf2 is supported since ProFTPd 1.3.5. -It's possible to use either of SHA1 and pbkdf2 with either of MySQL/MariaDB and sqlite3. pbkdf2 is supported since ProFTPd 1.3.5. +You can look at some [screenshots](screenshots/README.md) to see if this is +the tool you need. -You can look at some [screenshots](screenshots/README.md) to see if this is the tool you need. -## To-Do - -* add postgresql support (#26) -* Add default user settings to groups so it is easier to create a new user with default values (#28) -* Email new users with password (#35) - -## Upgrade - -If you want to upgrade the hashing algorithm you have to change all passwords after changing the configs (both ProFTPd and ProFTPd Admin). ## Installation -### Using MySQL and SHA1 + +#### (A) Using MySQL and SHA1 1. Install ProFTPd with MySQL support - - Debian: apt-get install proftpd-mod-mysql - - Gentoo: USE="mysql" emerge proftpd -2. Create a MySQL database (use something like phpMyAdmin for this), for example: "proftpd". -3. Use tables.sql to populate the database (you can use phpMyAdmin for this). -4. Add the following to your proftpd.conf and sql.conf (edit to your needs): +2. Create a MySQL database, for example: "proftpd". +3. Use the file [tables.sql](tables.sql) to populate the database. +4. Add the following to your _`proftpd.conf`_ and _`sql.conf`_ (edit to your needs): -``` +```ini CreateHome on 775 AuthOrder mod_sql.c @@ -69,7 +48,7 @@ SQLUserWhereClause "disabled != 1" SQLLog PASS updatecount SQLNamedQuery updatecount UPDATE "login_count=login_count+1, last_login=now() WHERE userid='%u'" users - # Used to track xfer traffic per user (without invoking a quota) +# Used to track xfer traffic per user (without invoking a quota) SQLLog RETR bytes-out-count SQLNamedQuery bytes-out-count UPDATE "bytes_out_used=bytes_out_used+%b WHERE userid='%u'" users SQLLog RETR files-out-count @@ -82,19 +61,36 @@ SQLNamedQuery files-in-count UPDATE "files_in_used=files_in_used+1 WHE ``` 5. Extract all files to your webspace (into a subdirectory like "proftpdadmin"). -6. Secure access to this directory (for example: create a .htaccess file if using apache) -7. Edit the configs/config_example.php file to your needs and rename it to config.php. -8. Start ProFTPd. -9. Go to http://yourwebspace/proftpdadmin/ and start using it! +6. Edit the configs/config_example.php file to your needs and rename it to config.php. +**Notice:** Change the default login settings! + ```php +/** + * Login data + * + * Important: Please change this values in + * live systems! + */ +$cfg['login'] = array( + /* Username. Please use any username you want */ + 'username' => 'admin', + /* Password. CHANGE IT and use secure password! */ + 'password' => 'password', + /* Blowfish secret key (22 chars). CHANGE IT! */ + 'blowfish' => 'XBu5pjOTa8H7UIwYSzMZxD' +); +``` +7. Start ProFTPd. +8. Go to http://yourwebspace/proftpdadmin/ and start using it! + -### Using sqlite3 and pbkdf2 +#### (B) Using sqlite3 and pbkdf2 1. Install ProFTPd with sqlite3 support -2. Use tables-sqlite3.sql to create an sqlite3 database: +2. Use [tables-sqlite3.sql](tables-sqlite3.sql) to create an sqlite3 database: `sqlite3 auth.sqlite3 < tables-sqlite3.sql` -3. Add the following to your proftpd.conf and sql.conf (edit to your needs): +3. Add the following to your _`proftpd.conf`_ and _`sql.conf`_ (edit to your needs): -``` +```ini CreateHome on 775 AuthOrder mod_sql.c @@ -114,7 +110,7 @@ SQLUserWhereClause "disabled != 1" SQLLog PASS updatecount SQLNamedQuery updatecount UPDATE "login_count=login_count+1, last_login=now() WHERE userid='%u'" users - # Used to track xfer traffic per user (without invoking a quota) +# Used to track xfer traffic per user (without invoking a quota) SQLLog RETR bytes-out-count SQLNamedQuery bytes-out-count UPDATE "bytes_out_used=bytes_out_used+%b WHERE userid='%u'" users SQLLog RETR files-out-count @@ -127,13 +123,75 @@ SQLNamedQuery files-in-count UPDATE "files_in_used=files_in_used+1 WHE ``` 5. Extract all files to your webspace (into a subdirectory like "proftpdadmin"). -6. Secure access to this directory (for example: create a .htaccess file if using apache) -7. Edit the configs/config_example.php file to your needs and rename it to config.php. -8. Start ProFTPd. -9. Go to http://yourwebspace/proftpdadmin/ and start using it! +6. Edit the configs/config_example.php file to your needs and rename it to config.php. +**Notice:** Change the default login settings + ```php +/** + * Login data + * + * Important: Please change this values in + * live systems! + */ +$cfg['login'] = array( + /* Username. Please use any username you want */ + 'username' => 'admin', + /* Password. CHANGE IT and use secure password! */ + 'password' => 'password', + /* Blowfish secret key (22 chars). CHANGE IT! */ + 'blowfish' => 'XBu5pjOTa8H7UIwYSzMZxD' +); +``` +7. Start ProFTPd. +8. Go to http://yourwebspace/proftpdadmin/ and start using it! + + +### Upgrade + +If you want to upgrade the hashing algorithm you have to change all passwords after +changing the configs (both ProFTPd and ProFTPd Admin). + + -## Thanks / Links +## Plans + +* Add postgresql support [#26](https://github.com/ChristianBeer/ProFTPd-Admin/issues/26) + +* Add default user settings to groups so it is easier to create a new user + with default values [#28](https://github.com/ChristianBeer/ProFTPd-Admin/issues/28) + +* Email new users with password [#35](https://github.com/ChristianBeer/ProFTPd-Admin/issues/35) + + + +## Thanks + +- Lex Brugman for initiating this project +- Justin Vincent for the ezSQL library +- Ricardo Padilha for implementing sqlite3, pbkdf2 and bootstrap support +- Christian Beer for his update to support the latest PHP version + + + +## Copyright / License + +- © 2004 The Netherlands, Lex Brugman; lex_brugman@users.sourceforge.net +- © 2012 Christian Beer; djangofett@gmx.net +- © 2015 Ricardo Padilha; ricardo@droboports.com +- © 2017 Michael Keck; https://github.com/mkkeck + +--------------------------------------------------------------------------- + +Published under the GPLv2 License (see [LICENSE](LICENSE) for details) + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +version 2, as published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. -Lex Brugman for initiating this project
-Justin Vincent for the ezSQL library
-Ricardo Padilha for implementing sqlite3, pbkdf2 and bootstrap support +You should have received a copy of the GNU General Public License along with +this program; if not, download from +[http://www.gnu.org/licenses/gpl-2.0.txt](http://www.gnu.org/licenses/gpl-2.0.txt) From d36e3aa7a8a147dbd34f2c2e3ae5d619dea39a67 Mon Sep 17 00:00:00 2001 From: "mk.keck" Date: Thu, 16 Mar 2017 09:59:00 +0100 Subject: [PATCH 04/24] Version 2.2 Fork / Update README.md * Readme section restructured * Config / Install description updated for admin login * Linking to Issues * Linking to original project from Christian Beer --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index f2793f7..e6878ae 100644 --- a/README.md +++ b/README.md @@ -60,8 +60,8 @@ SQLLog STOR files-in-count SQLNamedQuery files-in-count UPDATE "files_in_used=files_in_used+1 WHERE userid='%u'" users ``` -5. Extract all files to your webspace (into a subdirectory like "proftpdadmin"). -6. Edit the configs/config_example.php file to your needs and rename it to config.php. +5. Extract all files to your webspace (into a subdirectory like _`proftpdadmin`_). +6. Edit the _`configs/config_example.php`_ file to your needs and rename it to _**`config.php`**_. **Notice:** Change the default login settings! ```php /** @@ -80,7 +80,7 @@ $cfg['login'] = array( ); ``` 7. Start ProFTPd. -8. Go to http://yourwebspace/proftpdadmin/ and start using it! +8. Go to `http://your.server.com/proftpdadmin/` and start using it! #### (B) Using sqlite3 and pbkdf2 @@ -122,10 +122,10 @@ SQLLog STOR files-in-count SQLNamedQuery files-in-count UPDATE "files_in_used=files_in_used+1 WHERE userid='%u'" users ``` -5. Extract all files to your webspace (into a subdirectory like "proftpdadmin"). -6. Edit the configs/config_example.php file to your needs and rename it to config.php. -**Notice:** Change the default login settings - ```php +5. Extract all files to your webspace (into a subdirectory like _`proftpdadmin`_). +6. Edit the _`configs/config_example.php`_ file to your needs and rename it to _**`config.php`**_. + **Notice:** Change the default login settings! +```php /** * Login data * @@ -142,7 +142,7 @@ $cfg['login'] = array( ); ``` 7. Start ProFTPd. -8. Go to http://yourwebspace/proftpdadmin/ and start using it! +8. Go to `http://your.server.com/proftpdadmin/` and start using it! ### Upgrade From c74b005a54de69a7ffb231364ac7c717d1104bfc Mon Sep 17 00:00:00 2001 From: "mk.keck" Date: Thu, 16 Mar 2017 10:05:48 +0100 Subject: [PATCH 05/24] Version 2.2 Fork / Update README.md * Readme section restructured * Config / Install description updated for admin login * Linking to Issues * Linking to original project from Christian Beer --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e6878ae..1ac5546 100644 --- a/README.md +++ b/README.md @@ -154,12 +154,15 @@ changing the configs (both ProFTPd and ProFTPd Admin). ## Plans -* Add postgresql support [#26](https://github.com/ChristianBeer/ProFTPd-Admin/issues/26) +* Add postgresql support + » [Issue #26 / Feature request](https://github.com/ChristianBeer/ProFTPd-Admin/issues/26) * Add default user settings to groups so it is easier to create a new user - with default values [#28](https://github.com/ChristianBeer/ProFTPd-Admin/issues/28) + with default values + » [Issue #28 / Feature request](https://github.com/ChristianBeer/ProFTPd-Admin/issues/28) -* Email new users with password [#35](https://github.com/ChristianBeer/ProFTPd-Admin/issues/35) +* Send e-mail to new users with their password + » [Issue #35 / Feature request](https://github.com/ChristianBeer/ProFTPd-Admin/issues/35) From 16865f785189beaf0dfd8348abcdfa0f5acd26a3 Mon Sep 17 00:00:00 2001 From: "mk.keck" Date: Thu, 16 Mar 2017 12:04:35 +0100 Subject: [PATCH 06/24] Version 2.2 Fork / Secure config and includes directories * Added security for Apache Webserver: - `configs/` not accessible via browser - `includes/` not accessible via browser * Moved `tables*.sql` to `install/tables*.sql` * Added `install/config-examples` for Linux Distributions * Added `install/config-examples/debian` as example and info how to setup on Debian Jessie --- CHANGELOG | 12 +- README.md | 133 ++++++------ configs/.htaccess | 9 + configs/config_example.php | 1 + includes/.htaccess | 9 + install/.htaccess | 9 + .../config-examples/debian/config-example.php | 100 +++++++++ install/config-examples/debian/modules.conf | 99 +++++++++ install/config-examples/debian/proftpd.conf | 201 ++++++++++++++++++ install/config-examples/debian/sql.conf | 60 ++++++ .../tables-sqlite3.sql | 0 tables.sql => install/tables.sql | 0 12 files changed, 568 insertions(+), 65 deletions(-) create mode 100644 configs/.htaccess create mode 100644 includes/.htaccess create mode 100644 install/.htaccess create mode 100644 install/config-examples/debian/config-example.php create mode 100644 install/config-examples/debian/modules.conf create mode 100644 install/config-examples/debian/proftpd.conf create mode 100644 install/config-examples/debian/sql.conf rename tables-sqlite3.sql => install/tables-sqlite3.sql (100%) rename tables.sql => install/tables.sql (100%) diff --git a/CHANGELOG b/CHANGELOG index af0f11f..ecb9194 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -6,15 +6,21 @@ * @copyright Lex Brugman * @copyright Christian Beer * @copyright Ricardo Padilha - * @copyright 2017 Michael Keck + * @copyright Michael Keck */ -2017-03-15 +2017-03-16 ---------- -Changes: +Changes: Michael Keck * Login form * Added session class for login form * Display different navigations user is logged in / logged out +* Added security for Apache Webserver: + - `configs/` not accessible via browser + - `includes/` not accessible via browser +* Moved `tables*.sql` to `install/tables*.sql` +* Added `install/config-examples` for Linux Distributions +* Added `install/config-examples/debian` as example and info how to setup on Debian Jessie Release: 2.2 diff --git a/README.md b/README.md index 1ac5546..b16749f 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,11 @@ Graphical User Interface for ProFTPd with MySQL and sqlite3 support This GUI for ProFTPd was written to support a basic user management feature when using the SQL module. Originally written by Lex Brugmann in 2004, updated by [Christian Beer](https://github.com/ChristianBeer/ProFTPd-Admin) -in 2012 to support the latest PHP version. -2017 updated by Michael Keck with build-in login for the admin user. +in 2012 to support the latest PHP version. +2017 updated by [Michael Keck](https://github.com/mkkeck) with build-in login for +the admin user, secure the directories _`configs/`_ and _`includes` and moved +_`tables*.sql`_ to _`install/tables*.sql`_. +Added _`install/config-examples`_ for [OS specific configurations](install/config-examples). It's possible to use either of SHA1 and pbkdf2 with either of MySQL/MariaDB and sqlite3. pbkdf2 is supported since ProFTPd 1.3.5. @@ -28,40 +31,41 @@ the tool you need. 1. Install ProFTPd with MySQL support 2. Create a MySQL database, for example: "proftpd". -3. Use the file [tables.sql](tables.sql) to populate the database. +3. Use the file [install/tables.sql](install/tables.sql) to populate the database. 4. Add the following to your _`proftpd.conf`_ and _`sql.conf`_ (edit to your needs): ```ini -CreateHome on 775 -AuthOrder mod_sql.c - -SQLBackend mysql -SQLEngine on -SQLPasswordEngine on -SQLAuthenticate on -SQLAuthTypes SHA1 - -SQLConnectInfo database@localhost username password -SQLUserInfo users userid passwd uid gid homedir shell -SQLGroupInfo groups groupname gid members -SQLUserWhereClause "disabled != 1" -SQLLog PASS updatecount -SQLNamedQuery updatecount UPDATE "login_count=login_count+1, last_login=now() WHERE userid='%u'" users +CreateHome on 775 +AuthOrder mod_sql.c + +SQLBackend mysql +SQLEngine on +SQLPasswordEngine on +SQLAuthenticate on +SQLAuthTypes SHA1 + +SQLConnectInfo database@localhost username password +SQLUserInfo users userid passwd uid gid homedir shell +SQLGroupInfo groups groupname gid members +SQLUserWhereClause "disabled != 1" +SQLLog PASS updatecount +SQLNamedQuery updatecount UPDATE "login_count=login_count+1, last_login=now() WHERE userid='%u'" users # Used to track xfer traffic per user (without invoking a quota) -SQLLog RETR bytes-out-count -SQLNamedQuery bytes-out-count UPDATE "bytes_out_used=bytes_out_used+%b WHERE userid='%u'" users -SQLLog RETR files-out-count -SQLNamedQuery files-out-count UPDATE "files_out_used=files_out_used+1 WHERE userid='%u'" users - -SQLLog STOR bytes-in-count -SQLNamedQuery bytes-in-count UPDATE "bytes_in_used=bytes_in_used+%b WHERE userid='%u'" users -SQLLog STOR files-in-count -SQLNamedQuery files-in-count UPDATE "files_in_used=files_in_used+1 WHERE userid='%u'" users +SQLLog RETR bytes-out-count +SQLNamedQuery bytes-out-count UPDATE "bytes_out_used=bytes_out_used+%b WHERE userid='%u'" users +SQLLog RETR files-out-count +SQLNamedQuery files-out-count UPDATE "files_out_used=files_out_used+1 WHERE userid='%u'" users + +SQLLog STOR bytes-in-count +SQLNamedQuery bytes-in-count UPDATE "bytes_in_used=bytes_in_used+%b WHERE userid='%u'" users +SQLLog STOR files-in-count +SQLNamedQuery files-in-count UPDATE "files_in_used=files_in_used+1 WHERE userid='%u'" users ``` 5. Extract all files to your webspace (into a subdirectory like _`proftpdadmin`_). -6. Edit the _`configs/config_example.php`_ file to your needs and rename it to _**`config.php`**_. +6. Copy the _`configs/config_example.php`_ to _**`config.php`**_ and edit the new copied file + to your needs. **Notice:** Change the default login settings! ```php /** @@ -79,51 +83,53 @@ $cfg['login'] = array( 'blowfish' => 'XBu5pjOTa8H7UIwYSzMZxD' ); ``` -7. Start ProFTPd. -8. Go to `http://your.server.com/proftpdadmin/` and start using it! +7. Optional remove or secure the folder _`install`_. +8. Start ProFTPd. +9. Go to `http://your.server.com/proftpdadmin/` and start using it! #### (B) Using sqlite3 and pbkdf2 1. Install ProFTPd with sqlite3 support -2. Use [tables-sqlite3.sql](tables-sqlite3.sql) to create an sqlite3 database: - `sqlite3 auth.sqlite3 < tables-sqlite3.sql` +2. Use [install/tables-sqlite3.sql](install/tables-sqlite3.sql) to create an sqlite3 database: + `sqlite3 auth.sqlite3 < install/tables-sqlite3.sql` 3. Add the following to your _`proftpd.conf`_ and _`sql.conf`_ (edit to your needs): ```ini -CreateHome on 775 -AuthOrder mod_sql.c - -SQLBackend sqlite3 -SQLEngine on -SQLPasswordEngine on -SQLAuthenticate on -SQLAuthTypes pbkdf2 -SQLPasswordPBKDF2 sha1 5000 20 -SQLPasswordUserSalt name Prepend -SQLPasswordEncoding hex - -SQLConnectInfo /path/to/auth.sqlite3 -SQLUserInfo users userid passwd uid gid homedir shell -SQLGroupInfo groups groupname gid members -SQLUserWhereClause "disabled != 1" -SQLLog PASS updatecount -SQLNamedQuery updatecount UPDATE "login_count=login_count+1, last_login=now() WHERE userid='%u'" users +CreateHome on 775 +AuthOrder mod_sql.c + +SQLBackend sqlite3 +SQLEngine on +SQLPasswordEngine on +SQLAuthenticate on +SQLAuthTypes pbkdf2 +SQLPasswordPBKDF2 sha1 5000 20 +SQLPasswordUserSalt name Prepend +SQLPasswordEncoding hex + +SQLConnectInfo /path/to/auth.sqlite3 +SQLUserInfo users userid passwd uid gid homedir shell +SQLGroupInfo groups groupname gid members +SQLUserWhereClause "disabled != 1" +SQLLog PASS updatecount +SQLNamedQuery updatecount UPDATE "login_count=login_count+1, last_login=now() WHERE userid='%u'" users # Used to track xfer traffic per user (without invoking a quota) -SQLLog RETR bytes-out-count -SQLNamedQuery bytes-out-count UPDATE "bytes_out_used=bytes_out_used+%b WHERE userid='%u'" users -SQLLog RETR files-out-count -SQLNamedQuery files-out-count UPDATE "files_out_used=files_out_used+1 WHERE userid='%u'" users - -SQLLog STOR bytes-in-count -SQLNamedQuery bytes-in-count UPDATE "bytes_in_used=bytes_in_used+%b WHERE userid='%u'" users -SQLLog STOR files-in-count -SQLNamedQuery files-in-count UPDATE "files_in_used=files_in_used+1 WHERE userid='%u'" users +SQLLog RETR bytes-out-count +SQLNamedQuery bytes-out-count UPDATE "bytes_out_used=bytes_out_used+%b WHERE userid='%u'" users +SQLLog RETR files-out-count +SQLNamedQuery files-out-count UPDATE "files_out_used=files_out_used+1 WHERE userid='%u'" users + +SQLLog STOR bytes-in-count +SQLNamedQuery bytes-in-count UPDATE "bytes_in_used=bytes_in_used+%b WHERE userid='%u'" users +SQLLog STOR files-in-count +SQLNamedQuery files-in-count UPDATE "files_in_used=files_in_used+1 WHERE userid='%u'" users ``` 5. Extract all files to your webspace (into a subdirectory like _`proftpdadmin`_). -6. Edit the _`configs/config_example.php`_ file to your needs and rename it to _**`config.php`**_. +6. Copy the _`configs/config_example.php`_ to _**`config.php`**_ and edit the new copied file + to your needs. **Notice:** Change the default login settings! ```php /** @@ -141,8 +147,9 @@ $cfg['login'] = array( 'blowfish' => 'XBu5pjOTa8H7UIwYSzMZxD' ); ``` -7. Start ProFTPd. -8. Go to `http://your.server.com/proftpdadmin/` and start using it! +7. Optional remove or secure the folder _`install`_. +8. Start ProFTPd. +9. Go to `http://your.server.com/proftpdadmin/` and start using it! ### Upgrade @@ -172,6 +179,7 @@ changing the configs (both ProFTPd and ProFTPd Admin). - Justin Vincent for the ezSQL library - Ricardo Padilha for implementing sqlite3, pbkdf2 and bootstrap support - Christian Beer for his update to support the latest PHP version +- Robert Tulke for the Debian Jessie example @@ -180,6 +188,7 @@ changing the configs (both ProFTPd and ProFTPd Admin). - © 2004 The Netherlands, Lex Brugman; lex_brugman@users.sourceforge.net - © 2012 Christian Beer; djangofett@gmx.net - © 2015 Ricardo Padilha; ricardo@droboports.com +- © 2017 Robert Tulke; https://github.com/rtulke/ - © 2017 Michael Keck; https://github.com/mkkeck --------------------------------------------------------------------------- diff --git a/configs/.htaccess b/configs/.htaccess new file mode 100644 index 0000000..cde5b44 --- /dev/null +++ b/configs/.htaccess @@ -0,0 +1,9 @@ + + # Apache 2.4 + Require all denied + + + # Apache 2.2 + Order deny,allow + Deny from all + diff --git a/configs/config_example.php b/configs/config_example.php index 2fafae5..ef4d180 100644 --- a/configs/config_example.php +++ b/configs/config_example.php @@ -8,6 +8,7 @@ * @copyright Ricardo Padilha * @copyright Christian Beer * @copyright Lex Brugman + * @copyright Michael Leck */ $cfg = array(); diff --git a/includes/.htaccess b/includes/.htaccess new file mode 100644 index 0000000..cde5b44 --- /dev/null +++ b/includes/.htaccess @@ -0,0 +1,9 @@ + + # Apache 2.4 + Require all denied + + + # Apache 2.2 + Order deny,allow + Deny from all + diff --git a/install/.htaccess b/install/.htaccess new file mode 100644 index 0000000..cde5b44 --- /dev/null +++ b/install/.htaccess @@ -0,0 +1,9 @@ + + # Apache 2.4 + Require all denied + + + # Apache 2.2 + Order deny,allow + Deny from all + diff --git a/install/config-examples/debian/config-example.php b/install/config-examples/debian/config-example.php new file mode 100644 index 0000000..1d86793 --- /dev/null +++ b/install/config-examples/debian/config-example.php @@ -0,0 +1,100 @@ + + * @copyright Christian Beer + * @copyright Lex Brugman + * @copyright Robert Tulke + * @copyright Michael Leck + * + * rename to config.php + */ + +$cfg = array(); + + +/** + * Login data + * + * Important: Please change this values in + * live systems! + */ +$cfg['login'] = array( + /* Username. Please use any username you want */ + 'username' => 'admin', + /* Password. CHANGE IT and use secure password! */ + 'password' => 'password', + /* Blowfish secret key (22 chars). CHANGE IT! */ + 'blowfish' => 'XBu5pjOTa8H7UIwYSzMZxD' +); + +$cfg['table_users'] = "users"; +$cfg['field_userid'] = "userid"; +$cfg['field_id'] = "id"; +$cfg['field_uid'] = "uid"; +$cfg['field_ugid'] = "gid"; +$cfg['field_passwd'] = "passwd"; +$cfg['field_homedir'] = "homedir"; +$cfg['field_shell'] = "shell"; +$cfg['field_title'] = "title"; +$cfg['field_name'] = "name"; +$cfg['field_company'] = "company"; +$cfg['field_email'] = "email"; +$cfg['field_comment'] = "comment"; +$cfg['field_disabled'] = "disabled"; +$cfg['field_login_count'] = "login_count"; +$cfg['field_last_login'] = "last_login"; +$cfg['field_last_modified'] = "last_modified"; +$cfg['field_bytes_in_used'] = "bytes_in_used"; +$cfg['field_bytes_out_used'] = "bytes_out_used"; +$cfg['field_files_in_used'] = "files_in_used"; +$cfg['field_files_out_used'] = "files_out_used"; + +$cfg['table_groups'] = "groups"; +$cfg['field_groupname'] = "groupname"; +$cfg['field_gid'] = "gid"; +$cfg['field_members'] = "members"; + +$cfg['default_uid'] = "8000"; //if empty next incremental will be default +$cfg['default_homedir'] = "/home/web"; +// Use either SHA1 or MD5 or any other supported by your MySQL-Server and ProFTPd +// "pbkdf2" is supported if you are using ProFTPd 1.3.5. +// "crypt" uses the unix crypt() function. +// "OpenSSL:sha1" other digest-names also possible; see: http://www.proftpd.org/docs/directives/configuration_full.html#SQLAUTHTYPES +$cfg['passwd_encryption'] = "crypt"; +$cfg['min_passwd_length'] = "4"; +$cfg['max_userid_length'] = "32"; +$cfg['max_groupname_length'] = "32"; +// the expressions used to validate user and groupnames are used in two places +// on the website (HTML5) and on the server (PHP) +// the HTML5 validation doesn't understand the i modifier so you need to specify lowercase and uppercase characters +// for some reason the PHP validation still needs the i modifier so just leave it in +$cfg['userid_regex'] = "/^([a-zA-Z][a-zA-Z0-9_\-]{0,".($cfg['max_userid_length']-1)."})$/i"; //every username must comply with this regex +$cfg['groupname_regex'] = "/^([a-zA-Z][a-zA-Z0-9_\-]{0,".($cfg['max_groupname_length']-1)."})$/i"; //every username must comply with this regex +// Set any of these to -1 to remove the constraint +$cfg['min_uid'] = 8000; +$cfg['max_uid'] = 8999; +$cfg['min_gid'] = 8000; +$cfg['max_gid'] = 8999; +// Uncomment this to read crypt() settings from login.defs. +// $cfg['read_login_defs'] = true; + +// next option activates a userid filter on users.php. Usefull if you want to manage a lot of users +// that have a prefix like "pre-username", the first occurence of separator is recognized only! +$cfg['userid_filter_separator'] = ""; // try "-" or "_" as separators + +// use this block for a mysql backend +$cfg['db_type'] = "mysqli"; // if unset, 'db_type' defaults to mysqli +$cfg['db_host'] = "localhost"; +$cfg['db_name'] = "proftpd"; +$cfg['db_user'] = "proftpd"; +$cfg['db_pass'] = "yourdbpasswordhere"; + +// use this block for an sqlite3 backend +//$cfg['db_type'] = "sqlite3"; +//$cfg['db_path'] = "configs/"; +//$cfg['db_name'] = "auth.sqlite3"; diff --git a/install/config-examples/debian/modules.conf b/install/config-examples/debian/modules.conf new file mode 100644 index 0000000..3617af2 --- /dev/null +++ b/install/config-examples/debian/modules.conf @@ -0,0 +1,99 @@ +# +# This file is used to manage DSO modules and features. +# based on default config proftpd debian jessie +# +# Thanks to Robert Tulke +# https://github.com/rtulke/ + +# This is the directory where DSO modules reside + +ModulePath /usr/lib/proftpd + +# Allow only user root to load and unload modules, but allow everyone +# to see which modules have been loaded + +ModuleControlsACLs insmod,rmmod allow user root +ModuleControlsACLs lsmod allow user * + +LoadModule mod_ctrls_admin.c +LoadModule mod_tls.c + +# Install one of proftpd-mod-mysql, proftpd-mod-pgsql or any other +# SQL backend engine to use this module and the required backend. +# This module must be mandatory loaded before anyone of +# the existent SQL backeds. +LoadModule mod_sql.c + +# Install proftpd-mod-ldap to use this +#LoadModule mod_ldap.c + +# +# 'SQLBackend mysql' or 'SQLBackend postgres' (or any other valid backend) directives +# are required to have SQL authorization working. You can also comment out the +# unused module here, in alternative. +# + +# Install proftpd-mod-mysql and decomment the previous +# mod_sql.c module to use this. +LoadModule mod_sql_mysql.c + +# Install proftpd-mod-pgsql and decomment the previous +# mod_sql.c module to use this. +#LoadModule mod_sql_postgres.c + +# Install proftpd-mod-sqlite and decomment the previous +# mod_sql.c module to use this +#LoadModule mod_sql_sqlite.c + +# Install proftpd-mod-odbc and decomment the previous +# mod_sql.c module to use this +#LoadModule mod_sql_odbc.c + +# Install one of the previous SQL backends and decomment +# the previous mod_sql.c module to use this +LoadModule mod_sql_passwd.c + +LoadModule mod_radius.c +LoadModule mod_quotatab.c +LoadModule mod_quotatab_file.c + +# Install proftpd-mod-ldap to use this +#LoadModule mod_quotatab_ldap.c + +# Install one of the previous SQL backends and decomment +# the previous mod_sql.c module to use this +#LoadModule mod_quotatab_sql.c +LoadModule mod_quotatab_radius.c +LoadModule mod_wrap.c +LoadModule mod_rewrite.c +LoadModule mod_load.c +LoadModule mod_ban.c +LoadModule mod_wrap2.c +LoadModule mod_wrap2_file.c +# Install one of the previous SQL backends and decomment +# the previous mod_sql.c module to use this +#LoadModule mod_wrap2_sql.c +LoadModule mod_dynmasq.c +LoadModule mod_exec.c +LoadModule mod_shaper.c +LoadModule mod_ratio.c +LoadModule mod_site_misc.c + +LoadModule mod_sftp.c +LoadModule mod_sftp_pam.c +# Install one of the previous SQL backends and decomment +# the previous mod_sql.c module to use this +#LoadModule mod_sftp_sql.c + +LoadModule mod_facl.c +LoadModule mod_unique_id.c +LoadModule mod_copy.c +LoadModule mod_deflate.c +LoadModule mod_ifversion.c +LoadModule mod_tls_memcache.c + +# Install proftpd-mod-geoip to use the GeoIP feature +#LoadModule mod_geoip.c + +# keep this module the last one +LoadModule mod_ifsession.c diff --git a/install/config-examples/debian/proftpd.conf b/install/config-examples/debian/proftpd.conf new file mode 100644 index 0000000..ca77fa9 --- /dev/null +++ b/install/config-examples/debian/proftpd.conf @@ -0,0 +1,201 @@ +# +# /etc/proftpd/proftpd.conf -- This is a basic ProFTPD configuration file. +# To really apply changes, reload proftpd after modifications, if +# it runs in daemon mode. It is not required in inetd/xinetd mode. +# based on original proftpd debian jessie +# +# Thanks to Robert Tulke +# https://github.com/rtulke/ + + +# Includes DSO modules + +Include /etc/proftpd/modules.conf + +# Set off to disable IPv6 support which is annoying on IPv4 only boxes. +UseIPv6 on +# If set on you can experience a longer connection delay in many cases. +IdentLookups off + + + +ServerName "debian" +ServerType standalone +DeferWelcome off + +MultilineRFC2228 on +DefaultServer on +ShowSymlinks on + +TimeoutNoTransfer 600 +TimeoutStalled 600 +TimeoutIdle 1200 + +DisplayLogin welcome.msg +DisplayChdir .message true +ListOptions "-l" + +DenyFilter \*.*/ + +# Use this to jail all users in their homes +DefaultRoot ~ + +# Users require a valid shell listed in /etc/shells to login. +# Use this directive to release that constrain. +RequireValidShell off + +# Port 21 is the standard FTP port. +Port 21 + +# In some cases you have to specify passive ports range to by-pass +# firewall limitations. Ephemeral ports can be used for that, but +# feel free to use a more narrow range. +# PassivePorts 49152 65534 + +# If your host was NATted, this option is useful in order to +# allow passive tranfers to work. You have to use your public +# address and opening the passive ports used on your firewall as well. +# MasqueradeAddress 1.2.3.4 + +# This is useful for masquerading address with dynamic IPs: +# refresh any configured MasqueradeAddress directives every 8 hours + +# DynMasqRefresh 28800 + + +# To prevent DoS attacks, set the maximum number of child processes +# to 30. If you need to allow more than 30 concurrent connections +# at once, simply increase this value. Note that this ONLY works +# in standalone mode, in inetd mode you should use an inetd server +# that allows you to limit maximum number of processes per service +# (such as xinetd) +MaxInstances 30 + +# Set the user and group that the server normally runs at. +User proftpd +Group nogroup + +# Umask 022 is a good standard umask to prevent new files and dirs +# (second parm) from being group and world writable. +Umask 022 022 +# Normally, we want files to be overwriteable. +AllowOverwrite on + +# Uncomment this if you are using NIS or LDAP via NSS to retrieve passwords: +# PersistentPasswd off + +# This is required to use both PAM-based authentication and local passwords +# AuthOrder mod_auth_pam.c* mod_auth_unix.c +AuthOrder mod_sql.c # mod_auth_pam.c* mod_auth_unix.c + + +CreateHome on 775 + + +# Be warned: use of this directive impacts CPU average load! +# Uncomment this if you like to see progress and transfer rate with ftpwho +# in downloads. That is not needed for uploads rates. +# +# UseSendFile off + +TransferLog /var/log/proftpd/xferlog +SystemLog /var/log/proftpd/proftpd.log + +# Logging onto /var/log/lastlog is enabled but set to off by default +#UseLastlog on + +# In order to keep log file dates consistent after chroot, use timezone info +# from /etc/localtime. If this is not set, and proftpd is configured to +# chroot (e.g. DefaultRoot or ), it will use the non-daylight +# savings timezone regardless of whether DST is in effect. +#SetEnv TZ :/etc/localtime + + +QuotaEngine off + + + +Ratios off + + + +# Delay engine reduces impact of the so-called Timing Attack described in +# http://www.securityfocus.com/bid/11430/discuss +# It is on by default. + +DelayEngine on + + + +ControlsEngine off +ControlsMaxClients 2 +ControlsLog /var/log/proftpd/controls.log +ControlsInterval 5 +ControlsSocket /var/run/proftpd/proftpd.sock + + + +AdminControlsEngine off + + +# +# Alternative authentication frameworks +# +#Include /etc/proftpd/ldap.conf +Include /etc/proftpd/sql.conf + +# +# This is used for FTPS connections +# +#Include /etc/proftpd/tls.conf + +# +# Useful to keep VirtualHost/VirtualRoot directives separated +# +#Include /etc/proftpd/virtuals.conf + +# A basic anonymous configuration, no upload directories. + +# +# User ftp +# Group nogroup +# # We want clients to be able to login with "anonymous" as well as "ftp" +# UserAlias anonymous ftp +# # Cosmetic changes, all files belongs to ftp user +# DirFakeUser on ftp +# DirFakeGroup on ftp +# +# RequireValidShell off +# +# # Limit the maximum number of anonymous logins +# MaxClients 10 +# +# # We want 'welcome.msg' displayed at login, and '.message' displayed +# # in each newly chdired directory. +# DisplayLogin welcome.msg +# DisplayChdir .message +# +# # Limit WRITE everywhere in the anonymous chroot +# +# +# DenyAll +# +# +# +# # Uncomment this if you're brave. +# # +# # # Umask 022 is a good standard umask to prevent new files and dirs +# # # (second parm) from being group and world writable. +# # Umask 022 022 +# # +# # DenyAll +# # +# # +# # AllowAll +# # +# # +# +# + +# Include other custom configuration files +Include /etc/proftpd/conf.d/ diff --git a/install/config-examples/debian/sql.conf b/install/config-examples/debian/sql.conf new file mode 100644 index 0000000..caecbc3 --- /dev/null +++ b/install/config-examples/debian/sql.conf @@ -0,0 +1,60 @@ +# +# Proftpd sample configuration for SQL-based authentication. +# (This is not to be used if you prefer a PAM-based SQL authentication) +# based on default proftpd config debian jessie, modify ^SQLConnectInfo +# +# Thanks to Robert Tulke +# https://github.com/rtulke/ + + +# Choose a SQL backend among MySQL or PostgreSQL. +# Both modules are loaded in default configuration, so you have to specify the backend +# or comment out the unused module in /etc/proftpd/modules.conf. +# Use 'mysql' or 'postgres' as possible values. +# +#SQLBackend mysql +# +#SQLEngine on +#SQLAuthenticate on +# +# Use both a crypted or plaintext password +#SQLAuthTypes Crypt Plaintext +# +# Use a backend-crypted or a crypted password +#SQLAuthTypes Backend Crypt +# +# Connection +#SQLConnectInfo proftpd@sql.example.com proftpd_user proftpd_password +# +# Describes both users/groups tables +# +#SQLUserInfo users userid passwd uid gid homedir shell +#SQLGroupInfo groups groupname gid members + +SQLLogFile /var/log/proftpd/proftpd-mysql.log +CreateHome on 775 +SQLBackend mysql +SQLEngine on +SQLPasswordEngine on +SQLAuthenticate on +SQLAuthTypes Crypt +SQLConnectInfo proftpd@localhost proftpd +SQLUserInfo users userid passwd uid gid homedir shell +SQLGroupInfo groups groupname gid members +SQLUserWhereClause "disabled != 1" +SQLLog PASS updatecount +SQLNamedQuery updatecount UPDATE "login_count=login_count+1, last_login=now() WHERE userid='%u'" users + + # Used to track xfer traffic per user (without invoking a quota) +SQLLog RETR bytes-out-count +SQLNamedQuery bytes-out-count UPDATE "bytes_out_used=bytes_out_used+%b WHERE userid='%u'" users +SQLLog RETR files-out-count +SQLNamedQuery files-out-count UPDATE "files_out_used=files_out_used+1 WHERE userid='%u'" users + +SQLLog STOR bytes-in-count +SQLNamedQuery bytes-in-count UPDATE "bytes_in_used=bytes_in_used+%b WHERE userid='%u'" users +SQLLog STOR files-in-count +SQLNamedQuery files-in-count UPDATE "files_in_used=files_in_used+1 WHERE userid='%u'" users + + + diff --git a/tables-sqlite3.sql b/install/tables-sqlite3.sql similarity index 100% rename from tables-sqlite3.sql rename to install/tables-sqlite3.sql diff --git a/tables.sql b/install/tables.sql similarity index 100% rename from tables.sql rename to install/tables.sql From cde089dd5ffe296c36b32cc6958b06262ff6a7a1 Mon Sep 17 00:00:00 2001 From: "mk.keck" Date: Thu, 16 Mar 2017 16:26:55 +0100 Subject: [PATCH 07/24] Version 2.2 Fork / Security: option to force SSL * Config parameter $cfg['force_ssl'] * If $cfg['force_ssl'] true, then redirect to https:// * Some typos fixed --- CHANGELOG | 11 ++++++-- README.md | 19 ++++++++++++-- configs/config_example.php | 12 +++++++-- includes/Session.php | 26 ++++++++++++++----- .../config-examples/debian/config-example.php | 10 ++++++- 5 files changed, 64 insertions(+), 14 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index ecb9194..308abb5 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -20,8 +20,15 @@ Changes: Michael Keck - `includes/` not accessible via browser * Moved `tables*.sql` to `install/tables*.sql` * Added `install/config-examples` for Linux Distributions -* Added `install/config-examples/debian` as example and info how to setup on Debian Jessie - +* Added `install/config-examples/debian` as example and info how to + setup on Debian Jessie +* Added config param `force_ssl` and check if secured connection is + used if `$cfg['force_ssl'] = true'` +* Fixed typos in follow files: + - `README.md` + - `includes/Session.php` + - `configs/config_sample.php` + - `install/config-example/debian/config-example.php` Release: 2.2 Changes: diff --git a/README.md b/README.md index b16749f..aea4868 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,9 @@ Graphical User Interface for ProFTPd with MySQL and sqlite3 support This GUI for ProFTPd was written to support a basic user management feature when using the SQL module. Originally written by Lex Brugmann in 2004, updated by [Christian Beer](https://github.com/ChristianBeer/ProFTPd-Admin) -in 2012 to support the latest PHP version. +in 2012 to support the latest PHP version. 2017 updated by [Michael Keck](https://github.com/mkkeck) with build-in login for -the admin user, secure the directories _`configs/`_ and _`includes` and moved +the admin user, secure the directories _`configs/`_ and _`includes`_ and moved _`tables*.sql`_ to _`install/tables*.sql`_. Added _`install/config-examples`_ for [OS specific configurations](install/config-examples). @@ -26,6 +26,21 @@ the tool you need. ## Installation +**Note:** +Please use, if available, a secured connection to your webserver via `https`. +You can do this by your webserver configurations or simple set in the +_`config.php`_: +```php +/** + * Force SSL usage + * + * Important: You should change this to true on live systems or configure + * your webserver to use SSL! + */ +$cfg['force_ssl'] = true; // default was false +``` +Please notice that you need a SSL-certificate to use secured connection. + #### (A) Using MySQL and SHA1 diff --git a/configs/config_example.php b/configs/config_example.php index ef4d180..41600a8 100644 --- a/configs/config_example.php +++ b/configs/config_example.php @@ -8,7 +8,7 @@ * @copyright Ricardo Padilha * @copyright Christian Beer * @copyright Lex Brugman - * @copyright Michael Leck + * @copyright Michael Keck */ $cfg = array(); @@ -16,7 +16,7 @@ /** * Login data * - * Important: Please change this values in + * Important: Please change this values on * live systems! */ $cfg['login'] = array( @@ -28,6 +28,14 @@ 'blowfish' => 'XBu5pjOTa8H7UIwYSzMZxD' ); +/** + * Force SSL usage + * + * Important: You should change this to true on live systems or configure + * your webserver to use SSL! + */ +$cfg['force_ssl'] = false; + $cfg['table_users'] = "users"; $cfg['field_userid'] = "userid"; $cfg['field_id'] = "id"; diff --git a/includes/Session.php b/includes/Session.php index a946094..0bf96cc 100644 --- a/includes/Session.php +++ b/includes/Session.php @@ -2,7 +2,7 @@ /* * @class: Session * @file: includes/Session.php - * @date: 2017-03-15 + * @date: 2017-03-16 * @author: Michael Keck */ @@ -189,13 +189,13 @@ public static function set($index, $value = null) { /** * User login session * - * @param array $conf - * @param null|string $action - * @param null|array $data + * @param array $conf; configuration from gloabl $cfg['login'] + * @param null|string [$action]; optional: 'login' or 'logout' + * @param null|array [$data]; optional: array('username' => $_POST['username'], 'password' => $_POST['password']), * @return bool */ public static function user($conf = array(), $action = null, $data = null) { - $action = ($action !== NULL ? ($action === 'login' ? 'login' : 'logout') : NULL); + $action = ($action !== null ? ($action === 'login' ? 'login' : 'logout') : null); foreach (array('username','password','blowfish') as $key) { if (!isset($conf[$key]) || empty($conf[$key]) && trim('' . $conf[$key]) === '') { return false; @@ -234,13 +234,14 @@ public static function user($conf = array(), $action = null, $data = null) { } // Logout action or uid invalid - if ($action === 'logout' || self::get('uid') != $hash) { + if ($action === 'logout' || self::get('uid') !== $hash) { self::delete(); self::close(); return false; } - if (self::get('uid') == $hash) { + // Only check uid is valid + if (self::get('uid') === $hash) { self::close(); return true; } @@ -249,6 +250,17 @@ public static function user($conf = array(), $action = null, $data = null) { } } + +/* Only accessible via SSL if required */ +if (isset($cfg) && isset($cfg['force_ssl']) && $cfg['force_ssl'] === true) { + if ($_SERVER['SERVER_PORT'] !== '443') { + header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); + exit(); + } +} + + +/* Login required */ if (isset($cfg) && isset($cfg['login']) && is_array($cfg['login'])) { $session_usage = true; $session_valid = false; diff --git a/install/config-examples/debian/config-example.php b/install/config-examples/debian/config-example.php index 1d86793..28cb575 100644 --- a/install/config-examples/debian/config-example.php +++ b/install/config-examples/debian/config-example.php @@ -9,7 +9,7 @@ * @copyright Christian Beer * @copyright Lex Brugman * @copyright Robert Tulke - * @copyright Michael Leck + * @copyright Michael Keck * * rename to config.php */ @@ -32,6 +32,14 @@ 'blowfish' => 'XBu5pjOTa8H7UIwYSzMZxD' ); +/** + * Force SSL usage + * + * Important: You should change this to true on live systems or configure + * your webserver to use SSL! + */ +$cfg['force_ssl'] = false; + $cfg['table_users'] = "users"; $cfg['field_userid'] = "userid"; $cfg['field_id'] = "id"; From 53ddcd5e9819f47eda555944f07c4d05dc8a19a2 Mon Sep 17 00:00:00 2001 From: "mk.keck" Date: Sat, 18 Mar 2017 17:08:36 +0100 Subject: [PATCH 08/24] Version 2.2 Fork / Example Configs for CentOS 7.3 --- .../centos-7.3/config-example.php | 100 +++++++++ .../config-examples/centos-7.3/proftpd.conf | 208 ++++++++++++++++++ .../proftpd/conf.d/directories.conf | 90 ++++++++ .../centos-7.3/proftpd/modules.conf | 98 +++++++++ .../centos-7.3/proftpd/sql.conf | 51 +++++ .../centos-7.3/proftpd/tls.conf | 38 ++++ 6 files changed, 585 insertions(+) create mode 100644 install/config-examples/centos-7.3/config-example.php create mode 100644 install/config-examples/centos-7.3/proftpd.conf create mode 100644 install/config-examples/centos-7.3/proftpd/conf.d/directories.conf create mode 100644 install/config-examples/centos-7.3/proftpd/modules.conf create mode 100644 install/config-examples/centos-7.3/proftpd/sql.conf create mode 100644 install/config-examples/centos-7.3/proftpd/tls.conf diff --git a/install/config-examples/centos-7.3/config-example.php b/install/config-examples/centos-7.3/config-example.php new file mode 100644 index 0000000..6f90f45 --- /dev/null +++ b/install/config-examples/centos-7.3/config-example.php @@ -0,0 +1,100 @@ + + * @copyright Christian Beer + * @copyright Lex Brugman + * @copyright Michael Keck + */ + +$cfg = array(); + + +/** + * Login data + * + * Important: Please change this values in + * live systems! + */ +$cfg['login'] = array( + /* Username. Please use any username you want */ + 'username' => 'admin', + /* Password. CHANGE IT and use secure password! */ + 'password' => 'password', + /* Blowfish secret key (22 chars). CHANGE IT! */ + 'blowfish' => 'XBu5pjOTa8H7UIwYSzMZxD' +); + +/** + * Force SSL usage + * + * Important: You should change this to true on live systems or configure + * your webserver to use SSL! + */ +$cfg['force_ssl'] = false; + +$cfg['table_users'] = "users"; +$cfg['field_userid'] = "userid"; +$cfg['field_id'] = "id"; +$cfg['field_uid'] = "uid"; +$cfg['field_ugid'] = "gid"; +$cfg['field_passwd'] = "passwd"; +$cfg['field_homedir'] = "homedir"; +$cfg['field_shell'] = "shell"; +$cfg['field_title'] = "title"; +$cfg['field_name'] = "name"; +$cfg['field_company'] = "company"; +$cfg['field_email'] = "email"; +$cfg['field_comment'] = "comment"; +$cfg['field_disabled'] = "disabled"; +$cfg['field_login_count'] = "login_count"; +$cfg['field_last_login'] = "last_login"; +$cfg['field_last_modified'] = "last_modified"; +$cfg['field_bytes_in_used'] = "bytes_in_used"; +$cfg['field_bytes_out_used'] = "bytes_out_used"; +$cfg['field_files_in_used'] = "files_in_used"; +$cfg['field_files_out_used'] = "files_out_used"; + +$cfg['table_groups'] = "groups"; +$cfg['field_groupname'] = "groupname"; +$cfg['field_gid'] = "gid"; +$cfg['field_members'] = "members"; + +$cfg['default_uid'] = "1000"; //if empty next incremental will be default +$cfg['default_homedir'] = "/var/www/ftp/"; +// Use either SHA1 or MD5 or any other supported by your MySQL-Server and ProFTPd +// "pbkdf2" is supported if you are using ProFTPd 1.3.5. +// "crypt" uses the unix crypt() function. +$cfg['passwd_encryption'] = "SHA1"; +$cfg['min_passwd_length'] = "6"; +$cfg['max_userid_length'] = "20"; +$cfg['max_groupname_length'] = "20"; +$cfg['userid_regex'] = "/^([a-z][a-z0-9_\-\.\@]{0,20})$/i"; //every username must comply with this regex +$cfg['groupname_regex'] = "/^([a-z][a-z0-9_\-\.]{0,20})$/i"; //every username must comply with this regex +// Set any of these to -1 to remove the constraint +$cfg['min_uid'] = 1000; +$cfg['max_uid'] = 4000; +$cfg['min_gid'] = 1000; +$cfg['max_gid'] = 4000; +// Uncomment this to read crypt() settings from login.defs. +// $cfg['read_login_defs'] = true; + +// next option activates a userid filter on users.php. Usefull if you want to manage a lot of users +// that have a prefix like "pre-username", the first occurence of separator is recognized only! +$cfg['userid_filter_separator'] = ""; // try "-" or "_" as separators + +// use this block for a mysql backend +$cfg['db_type'] = "mysqli"; // if unset, 'db_type' defaults to mysqli +$cfg['db_host'] = "localhost"; +$cfg['db_name'] = "system_ftpd"; +$cfg['db_user'] = "system_ftpd"; +$cfg['db_pass'] = "system_ftpd"; + +// use this block for an sqlite3 backend +// $cfg['db_type'] = "sqlite3"; +// $cfg['db_path'] = "configs/"; +// $cfg['db_name'] = "auth.sqlite3"; diff --git a/install/config-examples/centos-7.3/proftpd.conf b/install/config-examples/centos-7.3/proftpd.conf new file mode 100644 index 0000000..2c90900 --- /dev/null +++ b/install/config-examples/centos-7.3/proftpd.conf @@ -0,0 +1,208 @@ +# +# /etc/proftpd.conf -- This is a basic ProFTPD configuration file. +# To really apply changes, reload proftpd after modifications, if +# it runs in daemon mode. +# +# Modified: by Michael Keck +# for Cenots 7.3 +# + + +# Includes DSO modules +Include /etc/proftpd/modules.conf + +# Set off to disable IPv6 support which is annoying on IPv4 only boxes. +UseIPv6 on + +# If set on you can experience a longer connection delay in many cases. +IdentLookups off +UseReverseDns off + +DefaultAddress your.server.tld +ServerName "your.server.tld" +ServerType standalone +DeferWelcome off + +MultilineRFC2228 on +DefaultServer on +ShowSymlinks on + +TimeoutNoTransfer 600 +TimeoutStalled 600 +TimeoutIdle 1200 + +DisplayLogin welcome.msg +DisplayChdir .message true +#ListOptions "-l" + + +#DenyFilter \*.*/ + +# Use this to jail all users in their homes +DefaultRoot ~ +AllowChrootSymlinks On + +# Users require a valid shell listed in /etc/shells to login. +# Use this directive to release that constrain. +RequireValidShell off + +# Port 21 is the standard FTP port. +Port 21 + +# In some cases you have to specify passive ports range to by-pass +# firewall limitations. Ephemeral ports can be used for that, but +# feel free to use a more narrow range. +# Enable in firewall: +# shell> firewall-cmd --add-port=49152-65534/tcp --zone=public --permanent +# shell> firewall-cmd --complete-reload +PassivePorts 49152 65534 + +# If your host was NATted, this option is useful in order to +# allow passive tranfers to work. You have to use your public +# address and opening the passive ports used on your firewall as well. +#MasqueradeAddress 1.2.3.4 + +# This is useful for masquerading address with dynamic IPs: +# refresh any configured MasqueradeAddress directives every 8 hours + +# DynMasqRefresh 28800 + + +# To prevent DoS attacks, set the maximum number of child processes +# to 30. If you need to allow more than 30 concurrent connections +# at once, simply increase this value. Note that this ONLY works +# in standalone mode, in inetd mode you should use an inetd server +# that allows you to limit maximum number of processes per service +# (such as xinetd) +MaxInstances 30 + +# Set the user and group that the server normally runs at. +User ftp +Group ftp + +# Umask 022 is a good standard umask to prevent new files and dirs +# (second parm) from being group and world writable. +Umask 022 022 + +# Normally, we want files to be overwriteable. +AllowOverwrite on + +# Uncomment this if you are using NIS or LDAP via NSS to retrieve passwords: +#PersistentPasswd off + +# This is required to use both PAM-based authentication and local passwords +#AuthOrder mod_auth_pam.c* mod_auth_unix.c +AuthOrder mod_sql.c + + +CreateHome on 775 + + +# Be warned: use of this directive impacts CPU average load! +# Uncomment this if you like to see progress and transfer rate with ftpwho +# in downloads. That is not needed for uploads rates. +#UseSendFile off + +TransferLog /var/log/proftpd/xfer.log + +SyslogLevel debug +SystemLog /var/log/proftpd/proftpd.log + +# Logging onto /var/log/lastlog is enabled but set to off by default +#UseLastlog on + +# In order to keep log file dates consistent after chroot, use timezone info +# from /etc/localtime. If this is not set, and proftpd is configured to +# chroot (e.g. DefaultRoot or ), it will use the non-daylight +# savings timezone regardless of whether DST is in effect. +#SetEnv TZ :/etc/localtime + + + QuotaEngine off + + + + Ratios off + + + +# Delay engine reduces impact of the so-called Timing Attack described in +# http://www.securityfocus.com/bid/11430/discuss +# It is on by default. + + DelayEngine on + + + + ControlsEngine off + ControlsMaxClients 2 + ControlsLog /var/log/proftpd/controls.log + ControlsInterval 5 + ControlsSocket /var/run/proftpd/proftpd.sock + + + + AdminControlsEngine off + + +# +# Alternative authentication frameworks +# +#Include /etc/proftpd/ldap.conf +Include /etc/proftpd/sql.conf + +# +# This is used for FTPS connections +# +Include /etc/proftpd/tls.conf + +# +# Useful to keep VirtualHost/VirtualRoot directives separated +# +#Include /etc/proftpd/virtuals.conf + +# A basic anonymous configuration, no upload directories. + +# +# User ftp +# Group ftp +# # We want clients to be able to login with "anonymous" as well as "ftp" +# UserAlias anonymous ftp +# # Cosmetic changes, all files belongs to ftp user +# DirFakeUse on ftp +# DirFakeGroup on ftp +# +# RequireValidShell off +# +# # Limit the maximum number of anonymous logins +# MaxClients 10 +# +# # We want 'welcome.msg' displayed at login, and '.message' displayed +# # in each newly chdired directory. +# DisplayLogin welcome.msg +# DisplayChdir .message +# +# # Limit WRITE everywhere in the anonymous chroot +# +# +# DenyAll +# +# +# +# # Uncomment this if you're brave. +# # +# # # Umask 022 is a good standard umask to prevent new files and dirs +# # # (second parm) from being group and world writable. +# # Umask 022 022 +# # +# # DenyAll +# # +# # +# # AllowAll +# # +# # +# +# + +# Include other custom configuration files +Include /etc/proftpd/conf.d/ diff --git a/install/config-examples/centos-7.3/proftpd/conf.d/directories.conf b/install/config-examples/centos-7.3/proftpd/conf.d/directories.conf new file mode 100644 index 0000000..a008904 --- /dev/null +++ b/install/config-examples/centos-7.3/proftpd/conf.d/directories.conf @@ -0,0 +1,90 @@ +# +# Proftpd sample configuration used to manage directory features. +# +# Modified: by Michael Keck +# for Cenots 7.3 +# + + + Umask 022 + DirFakeGroup On %u + DirFakeUser On %u + + + + # Dissalow renaming/removing main dir '~/cgi-bin' + + DenyAll + + + + # Allow all inner ~/cgi-bin/ + + AllowAll + + + + + # Dissalow renaming/removing main dir '~/logs' + + DenyAll + + + + # Allow all inner ~/logs/ + + AllowAll + + + + + # Dissalow renaming/removing main dir ~/public + + DenyAll + + + + # Allow all inner ~/public/ + + AllowAll + + + + + # Dissalow renaming/removing main dir ~/private + + DenyAll + + + + # Allow all inner ~/private/ + + AllowAll + + + + + # Dissalow renaming/removing main dir ~/stats + + DenyAll + + + + # Allow all inner ~/stats/ + + AllowAll + + + + + # Dissalow renaming/removing main dir ~/tmp + + DenyAll + + + + # Allow all inner ~/tmp/ + + AllowAll + + diff --git a/install/config-examples/centos-7.3/proftpd/modules.conf b/install/config-examples/centos-7.3/proftpd/modules.conf new file mode 100644 index 0000000..2aae198 --- /dev/null +++ b/install/config-examples/centos-7.3/proftpd/modules.conf @@ -0,0 +1,98 @@ +# +# Proftpd sample configuration used to manage DSO modules and features. +# +# Modified: by Michael Keck +# for Cenots 7.3 +# + +# This is the directory where DSO modules reside +# Note: Please check documentations and manuals of you OS! +ModulePath /usr/libexec/proftpd + +# Allow only user root to load and unload modules, but allow everyone +# to see which modules have been loaded +ModuleControlsACLs insmod,rmmod allow user root +ModuleControlsACLs lsmod allow user * + +LoadModule mod_ctrls_admin.c +#LoadModule mod_tls.c + +# Install one of proftpd-mod-mysql, proftpd-mod-pgsql or any other +# SQL backend engine to use this module and the required backend. +# This module must be mandatory loaded before anyone of +# the existent SQL backeds. +LoadModule mod_sql.c + +# Install proftpd-mod-ldap to use this +#LoadModule mod_ldap.c + + +# 'SQLBackend mysql' or 'SQLBackend postgres' (or any other valid backend) directives +# are required to have SQL authorization working. You can also comment out the +# unused module here, in alternative. +# + +# Install proftpd-mod-mysql and decomment the previous +# mod_sql.c module to use this. +LoadModule mod_sql_mysql.c + +# Install proftpd-mod-pgsql and decomment the previous +# mod_sql.c module to use this. +#LoadModule mod_sql_postgres.c + +# Install proftpd-mod-sqlite and decomment the previous +# mod_sql.c module to use this +#LoadModule mod_sql_sqlite.c + +# Install proftpd-mod-odbc and decomment the previous +# mod_sql.c module to use this +#LoadModule mod_sql_odbc.c + +# Install one of the previous SQL backends and decomment +# the previous mod_sql.c module to use this +LoadModule mod_sql_passwd.c + +LoadModule mod_radius.c +LoadModule mod_quotatab.c +LoadModule mod_quotatab_file.c + +# Install proftpd-mod-ldap to use this +#LoadModule mod_quotatab_ldap.c + +# Install one of the previous SQL backends and decomment +# the previous mod_sql.c module to use this +#LoadModule mod_quotatab_sql.c +LoadModule mod_quotatab_radius.c +LoadModule mod_wrap.c +LoadModule mod_rewrite.c +LoadModule mod_load.c +LoadModule mod_ban.c +LoadModule mod_wrap2.c +LoadModule mod_wrap2_file.c +# Install one of the previous SQL backends and decomment +# the previous mod_sql.c module to use this +#LoadModule mod_wrap2_sql.c +#LoadModule mod_dynmasq.c +LoadModule mod_exec.c +LoadModule mod_shaper.c +LoadModule mod_ratio.c +LoadModule mod_site_misc.c + +LoadModule mod_sftp.c +LoadModule mod_sftp_pam.c +# Install one of the previous SQL backends and decomment +# the previous mod_sql.c module to use this +#LoadModule mod_sftp_sql.c + +LoadModule mod_facl.c +#LoadModule mod_unique_id.c +LoadModule mod_copy.c +LoadModule mod_deflate.c +LoadModule mod_ifversion.c +LoadModule mod_tls_memcache.c + +# Install proftpd-mod-geoip to use the GeoIP feature +#LoadModule mod_geoip.c + +# keep this module the last one +LoadModule mod_ifsession.c diff --git a/install/config-examples/centos-7.3/proftpd/sql.conf b/install/config-examples/centos-7.3/proftpd/sql.conf new file mode 100644 index 0000000..27e62e8 --- /dev/null +++ b/install/config-examples/centos-7.3/proftpd/sql.conf @@ -0,0 +1,51 @@ +# +# Proftpd sample configuration for SQL-based authentication. +# (This is not to be used if you prefer a PAM-based SQL authentication) +# +# Modified: by Michael Keck +# for Cenots 7.3 +# + + + # Choose a SQL backend among MySQL or PostgreSQL. + # Both modules are loaded in default configuration, so you have to specify the backend + # or comment out the unused module in /etc/proftpd/modules.conf. + # Use 'mysql' or 'postgres' as possible values. + # + SQLBackend mysql + SQLEngine on + SQLPasswordEngine on + SQLAuthenticate users* groups* + + # Use both a crypted or plaintext password + # SQLAuthTypes Crypt Plaintext + # Use a backend-crypted or a crypted password + # SQLAuthTypes Backend Crypt + SQLAuthTypes SHA1 + + SQLLogFile /var/log/proftpd/proftpd-mysql.log + SQLDefaultHomedir /var/ftp/%u + + # Connection + SQLConnectInfo proftpd_db@sql.example.com proftpd_db_user proftpd_db_password + + # Describes both users/groups tables + SQLUserInfo users userid passwd uid gid homedir shell + SQLUserWhereClause "disabled != 1" + SQLGroupInfo groups groupname gid members + + SQLLog PASS updatecount + SQLNamedQuery updatecount UPDATE "login_count=login_count+1, last_login=now() WHERE userid='%u'" users + + # Used to track xfer traffic per user (without invoking a quota) + SQLLog RETR bytes-out-count + SQLNamedQuery bytes-out-count UPDATE "bytes_out_used=bytes_out_used+%b WHERE userid='%u'" users + SQLLog RETR files-out-count + SQLNamedQuery files-out-count UPDATE "files_out_used=files_out_used+1 WHERE userid='%u'" users + + SQLLog STOR bytes-in-count + SQLNamedQuery bytes-in-count UPDATE "bytes_in_used=bytes_in_used+%b WHERE userid='%u'" users + SQLLog STOR files-in-count + SQLNamedQuery files-in-count UPDATE "files_in_used=files_in_used+1 WHERE userid='%u'" users + + diff --git a/install/config-examples/centos-7.3/proftpd/tls.conf b/install/config-examples/centos-7.3/proftpd/tls.conf new file mode 100644 index 0000000..0cebc21 --- /dev/null +++ b/install/config-examples/centos-7.3/proftpd/tls.conf @@ -0,0 +1,38 @@ +# +# Proftpd sample configuration to configure the TLS module and TLS features. +# +# Modified: by Michael Keck +# for Cenots 7.3 +# + + + + + TLSEngine on + TLSLog /var/log/proftpd/tls.log + TLSRequired on + TLSProtocol SSLv3 TLSv1 + + # Server's RSA certificate + TLSRSACertificateFile /path/to/your/letsencyrpt/cert/fullchain.pem + TLSRSACertificateKeyFile /path/to/your/letsencyrpt/cert/privkey.pem + + TLSCipherSuite ALL:!ADH:!DES + TLSOptions NoCertRequest + + # Authenticate clients that want to use FTP over TLS? + TLSVerifyClient off + + # Allow SSL/TLS renegotiations when the client requests them, but + # do not force the renegotations. Some clients do not support + # SSL/TLS renegotiations; when mod_tls forces a renegotiation, these + # clients will close the data connection, or there will be a timeout + # on an idle data connection. + #TLSRenegotiate ctrl 3600 data 512000 required off timeout 300 + TLSRenegotiate none + + + TLSSessionCache shm:/file=/var/run/proftpd/sesscache + + + From e521a19e6c385088ded0bdc6c8136678cd3ab850 Mon Sep 17 00:00:00 2001 From: "mk.keck" Date: Sat, 18 Mar 2017 17:15:42 +0100 Subject: [PATCH 09/24] Version 2.2 Fork / Example Configs for CentOS 7.3 --- install/config-examples/centos-7.3/config-example.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/install/config-examples/centos-7.3/config-example.php b/install/config-examples/centos-7.3/config-example.php index 6f90f45..395326b 100644 --- a/install/config-examples/centos-7.3/config-example.php +++ b/install/config-examples/centos-7.3/config-example.php @@ -89,10 +89,10 @@ // use this block for a mysql backend $cfg['db_type'] = "mysqli"; // if unset, 'db_type' defaults to mysqli -$cfg['db_host'] = "localhost"; -$cfg['db_name'] = "system_ftpd"; -$cfg['db_user'] = "system_ftpd"; -$cfg['db_pass'] = "system_ftpd"; +$cfg['db_host'] = "sql.example.com"; +$cfg['db_name'] = "proftpd_db"; +$cfg['db_user'] = "proftpd_db_user"; +$cfg['db_pass'] = "proftpd_db_password"; // use this block for an sqlite3 backend // $cfg['db_type'] = "sqlite3"; From da19d7d66ad2b1601534409a5f2a5273bfe4d9b2 Mon Sep 17 00:00:00 2001 From: Michael Keck Date: Sat, 18 Mar 2017 22:08:16 +0100 Subject: [PATCH 10/24] Update config-example.php --- install/config-examples/centos-7.3/config-example.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/install/config-examples/centos-7.3/config-example.php b/install/config-examples/centos-7.3/config-example.php index 6f90f45..395326b 100644 --- a/install/config-examples/centos-7.3/config-example.php +++ b/install/config-examples/centos-7.3/config-example.php @@ -89,10 +89,10 @@ // use this block for a mysql backend $cfg['db_type'] = "mysqli"; // if unset, 'db_type' defaults to mysqli -$cfg['db_host'] = "localhost"; -$cfg['db_name'] = "system_ftpd"; -$cfg['db_user'] = "system_ftpd"; -$cfg['db_pass'] = "system_ftpd"; +$cfg['db_host'] = "sql.example.com"; +$cfg['db_name'] = "proftpd_db"; +$cfg['db_user'] = "proftpd_db_user"; +$cfg['db_pass'] = "proftpd_db_password"; // use this block for an sqlite3 backend // $cfg['db_type'] = "sqlite3"; From fc9be61f66c06044960ccc1044226d59f01799a9 Mon Sep 17 00:00:00 2001 From: "mk.keck" Date: Sun, 19 Mar 2017 19:23:40 +0100 Subject: [PATCH 11/24] Version 2.2 Fork / Example Configs for CentOS 7.3: DB Settings --- install/config-examples/centos-7.3/config-example.php | 2 +- install/config-examples/centos-7.3/proftpd/sql.conf | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/install/config-examples/centos-7.3/config-example.php b/install/config-examples/centos-7.3/config-example.php index 395326b..781b241 100644 --- a/install/config-examples/centos-7.3/config-example.php +++ b/install/config-examples/centos-7.3/config-example.php @@ -89,7 +89,7 @@ // use this block for a mysql backend $cfg['db_type'] = "mysqli"; // if unset, 'db_type' defaults to mysqli -$cfg['db_host'] = "sql.example.com"; +$cfg['db_host'] = "localhost"; $cfg['db_name'] = "proftpd_db"; $cfg['db_user'] = "proftpd_db_user"; $cfg['db_pass'] = "proftpd_db_password"; diff --git a/install/config-examples/centos-7.3/proftpd/sql.conf b/install/config-examples/centos-7.3/proftpd/sql.conf index 27e62e8..42881df 100644 --- a/install/config-examples/centos-7.3/proftpd/sql.conf +++ b/install/config-examples/centos-7.3/proftpd/sql.conf @@ -27,7 +27,7 @@ SQLDefaultHomedir /var/ftp/%u # Connection - SQLConnectInfo proftpd_db@sql.example.com proftpd_db_user proftpd_db_password + SQLConnectInfo proftpd_db@localhost proftpd_db_user proftpd_db_password # Describes both users/groups tables SQLUserInfo users userid passwd uid gid homedir shell From 21568a62eea4fae91e767929829f62f631dbcf66 Mon Sep 17 00:00:00 2001 From: APN Date: Mon, 20 Jan 2020 16:37:58 +0100 Subject: [PATCH 12/24] Change Password defaults to crypt + SAH512, Add User Expiry Date --- add_user.php | 13 + bootstrap/js/bootstrap-datetimepicker.js | 2485 ++++++ bootstrap/js/jquery.min.js | 8 +- bootstrap/js/moment-with-locales.js | 9792 ++++++++++++++++++++++ bootstrap/js/moment.min.js | 5 +- configs/config_example.php | 15 +- edit_user.php | 21 + includes/AdminClass.php | 11 +- includes/footer.php | 13 + includes/unix_crypt.php | 2 +- install/tables.sql | 5 +- users.php | 3 + 12 files changed, 12355 insertions(+), 18 deletions(-) create mode 100644 bootstrap/js/bootstrap-datetimepicker.js create mode 100644 bootstrap/js/moment-with-locales.js diff --git a/add_user.php b/add_user.php index 885d080..0049039 100644 --- a/add_user.php +++ b/add_user.php @@ -32,6 +32,7 @@ $field_email = $cfg['field_email']; $field_comment = $cfg['field_comment']; $field_disabled = $cfg['field_disabled']; +$field_expiration = $cfg['field_expiration']; $groups = $ac->get_groups(); @@ -99,6 +100,7 @@ $field_email => $_REQUEST[$field_email], $field_company => $_REQUEST[$field_company], $field_comment => $_REQUEST[$field_comment], + $field_expiration => $_REQUEST[$field_expiration], $field_disabled => $disabled); if ($ac->add_user($userdata)) { if (isset($_REQUEST[$field_ad_gid])) { @@ -128,6 +130,7 @@ $ugid = $_REQUEST[$field_ugid]; $ad_gid = $_REQUEST[$field_ad_gid]; $passwd = $_REQUEST[$field_passwd]; + $expiration = $_REQUEST[$field_expiration]; $homedir = $_REQUEST[$field_homedir]; $shell = $_REQUEST[$field_shell]; $title = $_REQUEST[$field_title]; @@ -154,6 +157,7 @@ $shell = $_REQUEST[$field_shell]; } $passwd = $ac->generate_random_string((int) $cfg['min_passwd_length']); + $expiration= "0000-00-00 00:00:00"; $homedir = $cfg['default_homedir']; $title = "m"; $name = ""; @@ -222,6 +226,15 @@

Minimum length characters.

+ + +
+ +
+ +
+
+
diff --git a/bootstrap/js/bootstrap-datetimepicker.js b/bootstrap/js/bootstrap-datetimepicker.js new file mode 100644 index 0000000..0e8e141 --- /dev/null +++ b/bootstrap/js/bootstrap-datetimepicker.js @@ -0,0 +1,2485 @@ +/*! version : 4.15.35 + ========================================================= + bootstrap-datetimejs + https://github.com/Eonasdan/bootstrap-datetimepicker + Copyright (c) 2015 Jonathan Peterson + ========================================================= + */ +/* + The MIT License (MIT) + + Copyright (c) 2015 Jonathan Peterson + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ +/*global define:false */ +/*global exports:false */ +/*global require:false */ +/*global jQuery:false */ +/*global moment:false */ +(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // AMD is used - Register as an anonymous module. + define(['jquery', 'moment'], factory); + } else if (typeof exports === 'object') { + factory(require('jquery'), require('moment')); + } else { + // Neither AMD nor CommonJS used. Use global variables. + if (typeof jQuery === 'undefined') { + throw 'bootstrap-datetimepicker requires jQuery to be loaded first'; + } + if (typeof moment === 'undefined') { + throw 'bootstrap-datetimepicker requires Moment.js to be loaded first'; + } + factory(jQuery, moment); + } +}(function ($, moment) { + 'use strict'; + if (!moment) { + throw new Error('bootstrap-datetimepicker requires Moment.js to be loaded first'); + } + + var dateTimePicker = function (element, options) { + var picker = {}, + date = moment().startOf('d'), + viewDate = date.clone(), + unset = true, + input, + component = false, + widget = false, + use24Hours, + minViewModeNumber = 0, + actualFormat, + parseFormats, + currentViewMode, + datePickerModes = [ + { + clsName: 'days', + navFnc: 'M', + navStep: 1 + }, + { + clsName: 'months', + navFnc: 'y', + navStep: 1 + }, + { + clsName: 'years', + navFnc: 'y', + navStep: 10 + }, + { + clsName: 'decades', + navFnc: 'y', + navStep: 100 + } + ], + viewModes = ['days', 'months', 'years', 'decades'], + verticalModes = ['top', 'bottom', 'auto'], + horizontalModes = ['left', 'right', 'auto'], + toolbarPlacements = ['default', 'top', 'bottom'], + keyMap = { + 'up': 38, + 38: 'up', + 'down': 40, + 40: 'down', + 'left': 37, + 37: 'left', + 'right': 39, + 39: 'right', + 'tab': 9, + 9: 'tab', + 'escape': 27, + 27: 'escape', + 'enter': 13, + 13: 'enter', + 'pageUp': 33, + 33: 'pageUp', + 'pageDown': 34, + 34: 'pageDown', + 'shift': 16, + 16: 'shift', + 'control': 17, + 17: 'control', + 'space': 32, + 32: 'space', + 't': 84, + 84: 't', + 'delete': 46, + 46: 'delete' + }, + keyState = {}, + + /******************************************************************************** + * + * Private functions + * + ********************************************************************************/ + isEnabled = function (granularity) { + if (typeof granularity !== 'string' || granularity.length > 1) { + throw new TypeError('isEnabled expects a single character string parameter'); + } + switch (granularity) { + case 'y': + return actualFormat.indexOf('Y') !== -1; + case 'M': + return actualFormat.indexOf('M') !== -1; + case 'd': + return actualFormat.toLowerCase().indexOf('d') !== -1; + case 'h': + case 'H': + return actualFormat.toLowerCase().indexOf('h') !== -1; + case 'm': + return actualFormat.indexOf('m') !== -1; + case 's': + return actualFormat.indexOf('s') !== -1; + default: + return false; + } + }, + hasTime = function () { + return (isEnabled('h') || isEnabled('m') || isEnabled('s')); + }, + + hasDate = function () { + return (isEnabled('y') || isEnabled('M') || isEnabled('d')); + }, + + getDatePickerTemplate = function () { + var headTemplate = $('') + .append($('') + .append($('').addClass('prev').attr('data-action', 'previous') + .append($('').addClass(options.icons.previous)) + ) + .append($('').addClass('picker-switch').attr('data-action', 'pickerSwitch').attr('colspan', (options.calendarWeeks ? '6' : '5'))) + .append($('').addClass('next').attr('data-action', 'next') + .append($('').addClass(options.icons.next)) + ) + ), + contTemplate = $('') + .append($('') + .append($('').attr('colspan', (options.calendarWeeks ? '8' : '7'))) + ); + + return [ + $('
').addClass('datepicker-days') + .append($('').addClass('table-condensed') + .append(headTemplate) + .append($('')) + ), + $('
').addClass('datepicker-months') + .append($('
').addClass('table-condensed') + .append(headTemplate.clone()) + .append(contTemplate.clone()) + ), + $('
').addClass('datepicker-years') + .append($('
').addClass('table-condensed') + .append(headTemplate.clone()) + .append(contTemplate.clone()) + ), + $('
').addClass('datepicker-decades') + .append($('
').addClass('table-condensed') + .append(headTemplate.clone()) + .append(contTemplate.clone()) + ) + ]; + }, + + getTimePickerMainTemplate = function () { + var topRow = $(''), + middleRow = $(''), + bottomRow = $(''); + + if (isEnabled('h')) { + topRow.append($('
') + .append($('').attr({href: '#', tabindex: '-1', 'title':'Increment Hour'}).addClass('btn').attr('data-action', 'incrementHours') + .append($('').addClass(options.icons.up)))); + middleRow.append($('') + .append($('').addClass('timepicker-hour').attr({'data-time-component':'hours', 'title':'Pick Hour'}).attr('data-action', 'showHours'))); + bottomRow.append($('') + .append($('').attr({href: '#', tabindex: '-1', 'title':'Decrement Hour'}).addClass('btn').attr('data-action', 'decrementHours') + .append($('').addClass(options.icons.down)))); + } + if (isEnabled('m')) { + if (isEnabled('h')) { + topRow.append($('').addClass('separator')); + middleRow.append($('').addClass('separator').html(':')); + bottomRow.append($('').addClass('separator')); + } + topRow.append($('') + .append($('').attr({href: '#', tabindex: '-1', 'title':'Increment Minute'}).addClass('btn').attr('data-action', 'incrementMinutes') + .append($('').addClass(options.icons.up)))); + middleRow.append($('') + .append($('').addClass('timepicker-minute').attr({'data-time-component': 'minutes', 'title':'Pick Minute'}).attr('data-action', 'showMinutes'))); + bottomRow.append($('') + .append($('').attr({href: '#', tabindex: '-1', 'title':'Decrement Minute'}).addClass('btn').attr('data-action', 'decrementMinutes') + .append($('').addClass(options.icons.down)))); + } + if (isEnabled('s')) { + if (isEnabled('m')) { + topRow.append($('').addClass('separator')); + middleRow.append($('').addClass('separator').html(':')); + bottomRow.append($('').addClass('separator')); + } + topRow.append($('') + .append($('').attr({href: '#', tabindex: '-1', 'title':'Increment Second'}).addClass('btn').attr('data-action', 'incrementSeconds') + .append($('').addClass(options.icons.up)))); + middleRow.append($('') + .append($('').addClass('timepicker-second').attr({'data-time-component': 'seconds', 'title':'Pick Second'}).attr('data-action', 'showSeconds'))); + bottomRow.append($('') + .append($('').attr({href: '#', tabindex: '-1', 'title':'Decrement Second'}).addClass('btn').attr('data-action', 'decrementSeconds') + .append($('').addClass(options.icons.down)))); + } + + if (!use24Hours) { + topRow.append($('').addClass('separator')); + middleRow.append($('') + .append($('').addClass('separator')); + } + + return $('
').addClass('timepicker-picker') + .append($('').addClass('table-condensed') + .append([topRow, middleRow, bottomRow])); + }, + + getTimePickerTemplate = function () { + var hoursView = $('
').addClass('timepicker-hours') + .append($('
').addClass('table-condensed')), + minutesView = $('
').addClass('timepicker-minutes') + .append($('
').addClass('table-condensed')), + secondsView = $('
').addClass('timepicker-seconds') + .append($('
').addClass('table-condensed')), + ret = [getTimePickerMainTemplate()]; + + if (isEnabled('h')) { + ret.push(hoursView); + } + if (isEnabled('m')) { + ret.push(minutesView); + } + if (isEnabled('s')) { + ret.push(secondsView); + } + + return ret; + }, + + getToolbar = function () { + var row = []; + if (options.showTodayButton) { + row.push($('\s*$/g,rb={option:[1,""],legend:[1,"
","
"],area:[1,"",""],param:[1,"",""],thead:[1,"
').append($('').attr({'data-action':'today', 'title': options.tooltips.today}).append($('').addClass(options.icons.today)))); + } + if (!options.sideBySide && hasDate() && hasTime()) { + row.push($('').append($('').attr({'data-action':'togglePicker', 'title':'Select Time'}).append($('').addClass(options.icons.time)))); + } + if (options.showClear) { + row.push($('').append($('').attr({'data-action':'clear', 'title': options.tooltips.clear}).append($('').addClass(options.icons.clear)))); + } + if (options.showClose) { + row.push($('').append($('').attr({'data-action':'close', 'title': options.tooltips.close}).append($('').addClass(options.icons.close)))); + } + return $('').addClass('table-condensed').append($('').append($('').append(row))); + }, + + getTemplate = function () { + var template = $('
').addClass('bootstrap-datetimepicker-widget dropdown-menu'), + dateView = $('
').addClass('datepicker').append(getDatePickerTemplate()), + timeView = $('
').addClass('timepicker').append(getTimePickerTemplate()), + content = $('
    ').addClass('list-unstyled'), + toolbar = $('
  • ').addClass('picker-switch' + (options.collapse ? ' accordion-toggle' : '')).append(getToolbar()); + + if (options.inline) { + template.removeClass('dropdown-menu'); + } + + if (use24Hours) { + template.addClass('usetwentyfour'); + } + if (isEnabled('s') && !use24Hours) { + template.addClass('wider'); + } + + if (options.sideBySide && hasDate() && hasTime()) { + template.addClass('timepicker-sbs'); + if (options.toolbarPlacement === 'top') { + template.append(toolbar); + } + template.append( + $('
    ').addClass('row') + .append(dateView.addClass('col-md-6')) + .append(timeView.addClass('col-md-6')) + ); + if (options.toolbarPlacement === 'bottom') { + template.append(toolbar); + } + return template; + } + + if (options.toolbarPlacement === 'top') { + content.append(toolbar); + } + if (hasDate()) { + content.append($('
  • ').addClass((options.collapse && hasTime() ? 'collapse in' : '')).append(dateView)); + } + if (options.toolbarPlacement === 'default') { + content.append(toolbar); + } + if (hasTime()) { + content.append($('
  • ').addClass((options.collapse && hasDate() ? 'collapse' : '')).append(timeView)); + } + if (options.toolbarPlacement === 'bottom') { + content.append(toolbar); + } + return template.append(content); + }, + + dataToOptions = function () { + var eData, + dataOptions = {}; + + if (element.is('input') || options.inline) { + eData = element.data(); + } else { + eData = element.find('input').data(); + } + + if (eData.dateOptions && eData.dateOptions instanceof Object) { + dataOptions = $.extend(true, dataOptions, eData.dateOptions); + } + + $.each(options, function (key) { + var attributeName = 'date' + key.charAt(0).toUpperCase() + key.slice(1); + if (eData[attributeName] !== undefined) { + dataOptions[key] = eData[attributeName]; + } + }); + return dataOptions; + }, + + place = function () { + var position = (component || element).position(), + offset = (component || element).offset(), + vertical = options.widgetPositioning.vertical, + horizontal = options.widgetPositioning.horizontal, + parent; + + if (options.widgetParent) { + parent = options.widgetParent.append(widget); + } else if (element.is('input')) { + parent = element.after(widget).parent(); + } else if (options.inline) { + parent = element.append(widget); + return; + } else { + parent = element; + element.children().first().after(widget); + } + + // Top and bottom logic + if (vertical === 'auto') { + if (offset.top + widget.height() * 1.5 >= $(window).height() + $(window).scrollTop() && + widget.height() + element.outerHeight() < offset.top) { + vertical = 'top'; + } else { + vertical = 'bottom'; + } + } + + // Left and right logic + if (horizontal === 'auto') { + if (parent.width() < offset.left + widget.outerWidth() / 2 && + offset.left + widget.outerWidth() > $(window).width()) { + horizontal = 'right'; + } else { + horizontal = 'left'; + } + } + + if (vertical === 'top') { + widget.addClass('top').removeClass('bottom'); + } else { + widget.addClass('bottom').removeClass('top'); + } + + if (horizontal === 'right') { + widget.addClass('pull-right'); + } else { + widget.removeClass('pull-right'); + } + + // find the first parent element that has a relative css positioning + if (parent.css('position') !== 'relative') { + parent = parent.parents().filter(function () { + return $(this).css('position') === 'relative'; + }).first(); + } + + if (parent.length === 0) { + throw new Error('datetimepicker component should be placed within a relative positioned container'); + } + + widget.css({ + top: vertical === 'top' ? 'auto' : position.top + element.outerHeight(), + bottom: vertical === 'top' ? position.top + element.outerHeight() : 'auto', + left: horizontal === 'left' ? (parent === element ? 0 : position.left) : 'auto', + right: horizontal === 'left' ? 'auto' : parent.outerWidth() - element.outerWidth() - (parent === element ? 0 : position.left) + }); + }, + + notifyEvent = function (e) { + if (e.type === 'dp.change' && ((e.date && e.date.isSame(e.oldDate)) || (!e.date && !e.oldDate))) { + return; + } + element.trigger(e); + }, + + viewUpdate = function (e) { + if (e === 'y') { + e = 'YYYY'; + } + notifyEvent({ + type: 'dp.update', + change: e, + viewDate: viewDate.clone() + }); + }, + + showMode = function (dir) { + if (!widget) { + return; + } + if (dir) { + currentViewMode = Math.max(minViewModeNumber, Math.min(3, currentViewMode + dir)); + } + widget.find('.datepicker > div').hide().filter('.datepicker-' + datePickerModes[currentViewMode].clsName).show(); + }, + + fillDow = function () { + var row = $('
'), + currentDate = viewDate.clone().startOf('w').startOf('d'); + + if (options.calendarWeeks === true) { + row.append($(''); + if (options.calendarWeeks) { + row.append(''); + } + html.push(row); + } + clsName = ''; + if (currentDate.isBefore(viewDate, 'M')) { + clsName += ' old'; + } + if (currentDate.isAfter(viewDate, 'M')) { + clsName += ' new'; + } + if (currentDate.isSame(date, 'd') && !unset) { + clsName += ' active'; + } + if (!isValid(currentDate, 'd')) { + clsName += ' disabled'; + } + if (currentDate.isSame(moment(), 'd')) { + clsName += ' today'; + } + if (currentDate.day() === 0 || currentDate.day() === 6) { + clsName += ' weekend'; + } + row.append(''); + currentDate.add(1, 'd'); + } + + daysView.find('tbody').empty().append(html); + + updateMonths(); + + updateYears(); + + updateDecades(); + }, + + fillHours = function () { + var table = widget.find('.timepicker-hours table'), + currentHour = viewDate.clone().startOf('d'), + html = [], + row = $(''); + + if (viewDate.hour() > 11 && !use24Hours) { + currentHour.hour(12); + } + while (currentHour.isSame(viewDate, 'd') && (use24Hours || (viewDate.hour() < 12 && currentHour.hour() < 12) || viewDate.hour() > 11)) { + if (currentHour.hour() % 4 === 0) { + row = $(''); + html.push(row); + } + row.append(''); + currentHour.add(1, 'h'); + } + table.empty().append(html); + }, + + fillMinutes = function () { + var table = widget.find('.timepicker-minutes table'), + currentMinute = viewDate.clone().startOf('h'), + html = [], + row = $(''), + step = options.stepping === 1 ? 5 : options.stepping; + + while (viewDate.isSame(currentMinute, 'h')) { + if (currentMinute.minute() % (step * 4) === 0) { + row = $(''); + html.push(row); + } + row.append(''); + currentMinute.add(step, 'm'); + } + table.empty().append(html); + }, + + fillSeconds = function () { + var table = widget.find('.timepicker-seconds table'), + currentSecond = viewDate.clone().startOf('m'), + html = [], + row = $(''); + + while (viewDate.isSame(currentSecond, 'm')) { + if (currentSecond.second() % 20 === 0) { + row = $(''); + html.push(row); + } + row.append(''); + currentSecond.add(5, 's'); + } + + table.empty().append(html); + }, + + fillTime = function () { + var toggle, newDate, timeComponents = widget.find('.timepicker span[data-time-component]'); + + if (!use24Hours) { + toggle = widget.find('.timepicker [data-action=togglePeriod]'); + newDate = date.clone().add((date.hours() >= 12) ? -12 : 12, 'h'); + + toggle.text(date.format('A')); + + if (isValid(newDate, 'h')) { + toggle.removeClass('disabled'); + } else { + toggle.addClass('disabled'); + } + } + timeComponents.filter('[data-time-component=hours]').text(date.format(use24Hours ? 'HH' : 'hh')); + timeComponents.filter('[data-time-component=minutes]').text(date.format('mm')); + timeComponents.filter('[data-time-component=seconds]').text(date.format('ss')); + + fillHours(); + fillMinutes(); + fillSeconds(); + }, + + update = function () { + if (!widget) { + return; + } + fillDate(); + fillTime(); + }, + + setValue = function (targetMoment) { + var oldDate = unset ? null : date; + + // case of calling setValue(null or false) + if (!targetMoment) { + unset = true; + input.val(''); + element.data('date', ''); + notifyEvent({ + type: 'dp.change', + date: false, + oldDate: oldDate + }); + update(); + return; + } + + targetMoment = targetMoment.clone().locale(options.locale); + + if (options.stepping !== 1) { + targetMoment.minutes((Math.round(targetMoment.minutes() / options.stepping) * options.stepping) % 60).seconds(0); + } + + if (isValid(targetMoment)) { + date = targetMoment; + viewDate = date.clone(); + input.val(date.format(actualFormat)); + element.data('date', date.format(actualFormat)); + unset = false; + update(); + notifyEvent({ + type: 'dp.change', + date: date.clone(), + oldDate: oldDate + }); + } else { + if (!options.keepInvalid) { + input.val(unset ? '' : date.format(actualFormat)); + } + notifyEvent({ + type: 'dp.error', + date: targetMoment + }); + } + }, + + hide = function () { + ///Hides the widget. Possibly will emit dp.hide + var transitioning = false; + if (!widget) { + return picker; + } + // Ignore event if in the middle of a picker transition + widget.find('.collapse').each(function () { + var collapseData = $(this).data('collapse'); + if (collapseData && collapseData.transitioning) { + transitioning = true; + return false; + } + return true; + }); + if (transitioning) { + return picker; + } + if (component && component.hasClass('btn')) { + component.toggleClass('active'); + } + widget.hide(); + + $(window).off('resize', place); + widget.off('click', '[data-action]'); + widget.off('mousedown', false); + + widget.remove(); + widget = false; + + notifyEvent({ + type: 'dp.hide', + date: date.clone() + }); + + input.blur(); + + return picker; + }, + + clear = function () { + setValue(null); + }, + + /******************************************************************************** + * + * Widget UI interaction functions + * + ********************************************************************************/ + actions = { + next: function () { + var navFnc = datePickerModes[currentViewMode].navFnc; + viewDate.add(datePickerModes[currentViewMode].navStep, navFnc); + fillDate(); + viewUpdate(navFnc); + }, + + previous: function () { + var navFnc = datePickerModes[currentViewMode].navFnc; + viewDate.subtract(datePickerModes[currentViewMode].navStep, navFnc); + fillDate(); + viewUpdate(navFnc); + }, + + pickerSwitch: function () { + showMode(1); + }, + + selectMonth: function (e) { + var month = $(e.target).closest('tbody').find('span').index($(e.target)); + viewDate.month(month); + if (currentViewMode === minViewModeNumber) { + setValue(date.clone().year(viewDate.year()).month(viewDate.month())); + if (!options.inline) { + hide(); + } + } else { + showMode(-1); + fillDate(); + } + viewUpdate('M'); + }, + + selectYear: function (e) { + var year = parseInt($(e.target).text(), 10) || 0; + viewDate.year(year); + if (currentViewMode === minViewModeNumber) { + setValue(date.clone().year(viewDate.year())); + if (!options.inline) { + hide(); + } + } else { + showMode(-1); + fillDate(); + } + viewUpdate('YYYY'); + }, + + selectDecade: function (e) { + var year = parseInt($(e.target).data('selection'), 10) || 0; + viewDate.year(year); + if (currentViewMode === minViewModeNumber) { + setValue(date.clone().year(viewDate.year())); + if (!options.inline) { + hide(); + } + } else { + showMode(-1); + fillDate(); + } + viewUpdate('YYYY'); + }, + + selectDay: function (e) { + var day = viewDate.clone(); + if ($(e.target).is('.old')) { + day.subtract(1, 'M'); + } + if ($(e.target).is('.new')) { + day.add(1, 'M'); + } + setValue(day.date(parseInt($(e.target).text(), 10))); + if (!hasTime() && !options.keepOpen && !options.inline) { + hide(); + } + }, + + incrementHours: function () { + var newDate = date.clone().add(1, 'h'); + if (isValid(newDate, 'h')) { + setValue(newDate); + } + }, + + incrementMinutes: function () { + var newDate = date.clone().add(options.stepping, 'm'); + if (isValid(newDate, 'm')) { + setValue(newDate); + } + }, + + incrementSeconds: function () { + var newDate = date.clone().add(1, 's'); + if (isValid(newDate, 's')) { + setValue(newDate); + } + }, + + decrementHours: function () { + var newDate = date.clone().subtract(1, 'h'); + if (isValid(newDate, 'h')) { + setValue(newDate); + } + }, + + decrementMinutes: function () { + var newDate = date.clone().subtract(options.stepping, 'm'); + if (isValid(newDate, 'm')) { + setValue(newDate); + } + }, + + decrementSeconds: function () { + var newDate = date.clone().subtract(1, 's'); + if (isValid(newDate, 's')) { + setValue(newDate); + } + }, + + togglePeriod: function () { + setValue(date.clone().add((date.hours() >= 12) ? -12 : 12, 'h')); + }, + + togglePicker: function (e) { + var $this = $(e.target), + $parent = $this.closest('ul'), + expanded = $parent.find('.in'), + closed = $parent.find('.collapse:not(.in)'), + collapseData; + + if (expanded && expanded.length) { + collapseData = expanded.data('collapse'); + if (collapseData && collapseData.transitioning) { + return; + } + if (expanded.collapse) { // if collapse plugin is available through bootstrap.js then use it + expanded.collapse('hide'); + closed.collapse('show'); + } else { // otherwise just toggle in class on the two views + expanded.removeClass('in'); + closed.addClass('in'); + } + if ($this.is('span')) { + $this.toggleClass(options.icons.time + ' ' + options.icons.date); + } else { + $this.find('span').toggleClass(options.icons.time + ' ' + options.icons.date); + } + + // NOTE: uncomment if toggled state will be restored in show() + //if (component) { + // component.find('span').toggleClass(options.icons.time + ' ' + options.icons.date); + //} + } + }, + + showPicker: function () { + widget.find('.timepicker > div:not(.timepicker-picker)').hide(); + widget.find('.timepicker .timepicker-picker').show(); + }, + + showHours: function () { + widget.find('.timepicker .timepicker-picker').hide(); + widget.find('.timepicker .timepicker-hours').show(); + }, + + showMinutes: function () { + widget.find('.timepicker .timepicker-picker').hide(); + widget.find('.timepicker .timepicker-minutes').show(); + }, + + showSeconds: function () { + widget.find('.timepicker .timepicker-picker').hide(); + widget.find('.timepicker .timepicker-seconds').show(); + }, + + selectHour: function (e) { + var hour = parseInt($(e.target).text(), 10); + + if (!use24Hours) { + if (date.hours() >= 12) { + if (hour !== 12) { + hour += 12; + } + } else { + if (hour === 12) { + hour = 0; + } + } + } + setValue(date.clone().hours(hour)); + actions.showPicker.call(picker); + }, + + selectMinute: function (e) { + setValue(date.clone().minutes(parseInt($(e.target).text(), 10))); + actions.showPicker.call(picker); + }, + + selectSecond: function (e) { + setValue(date.clone().seconds(parseInt($(e.target).text(), 10))); + actions.showPicker.call(picker); + }, + + clear: clear, + + today: function () { + if (isValid(moment(), 'd')) { + setValue(moment()); + } + }, + + close: hide + }, + + doAction = function (e) { + if ($(e.currentTarget).is('.disabled')) { + return false; + } + actions[$(e.currentTarget).data('action')].apply(picker, arguments); + return false; + }, + + show = function () { + ///Shows the widget. Possibly will emit dp.show and dp.change + var currentMoment, + useCurrentGranularity = { + 'year': function (m) { + return m.month(0).date(1).hours(0).seconds(0).minutes(0); + }, + 'month': function (m) { + return m.date(1).hours(0).seconds(0).minutes(0); + }, + 'day': function (m) { + return m.hours(0).seconds(0).minutes(0); + }, + 'hour': function (m) { + return m.seconds(0).minutes(0); + }, + 'minute': function (m) { + return m.seconds(0); + } + }; + + if (input.prop('disabled') || (!options.ignoreReadonly && input.prop('readonly')) || widget) { + return picker; + } + if (input.val() !== undefined && input.val().trim().length !== 0) { + setValue(parseInputDate(input.val().trim())); + } else if (options.useCurrent && unset && ((input.is('input') && input.val().trim().length === 0) || options.inline)) { + currentMoment = moment(); + if (typeof options.useCurrent === 'string') { + currentMoment = useCurrentGranularity[options.useCurrent](currentMoment); + } + setValue(currentMoment); + } + + widget = getTemplate(); + + fillDow(); + fillMonths(); + + widget.find('.timepicker-hours').hide(); + widget.find('.timepicker-minutes').hide(); + widget.find('.timepicker-seconds').hide(); + + update(); + showMode(); + + $(window).on('resize', place); + widget.on('click', '[data-action]', doAction); // this handles clicks on the widget + widget.on('mousedown', false); + + if (component && component.hasClass('btn')) { + component.toggleClass('active'); + } + widget.show(); + place(); + + if (options.focusOnShow && !input.is(':focus')) { + input.focus(); + } + + notifyEvent({ + type: 'dp.show' + }); + return picker; + }, + + toggle = function () { + /// Shows or hides the widget + return (widget ? hide() : show()); + }, + + parseInputDate = function (inputDate) { + if (options.parseInputDate === undefined) { + if (moment.isMoment(inputDate) || inputDate instanceof Date) { + inputDate = moment(inputDate); + } else { + inputDate = moment(inputDate, parseFormats, options.useStrict); + } + } else { + inputDate = options.parseInputDate(inputDate); + } + inputDate.locale(options.locale); + return inputDate; + }, + + keydown = function (e) { + var handler = null, + index, + index2, + pressedKeys = [], + pressedModifiers = {}, + currentKey = e.which, + keyBindKeys, + allModifiersPressed, + pressed = 'p'; + + keyState[currentKey] = pressed; + + for (index in keyState) { + if (keyState.hasOwnProperty(index) && keyState[index] === pressed) { + pressedKeys.push(index); + if (parseInt(index, 10) !== currentKey) { + pressedModifiers[index] = true; + } + } + } + + for (index in options.keyBinds) { + if (options.keyBinds.hasOwnProperty(index) && typeof (options.keyBinds[index]) === 'function') { + keyBindKeys = index.split(' '); + if (keyBindKeys.length === pressedKeys.length && keyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) { + allModifiersPressed = true; + for (index2 = keyBindKeys.length - 2; index2 >= 0; index2--) { + if (!(keyMap[keyBindKeys[index2]] in pressedModifiers)) { + allModifiersPressed = false; + break; + } + } + if (allModifiersPressed) { + handler = options.keyBinds[index]; + break; + } + } + } + } + + if (handler) { + handler.call(picker, widget); + e.stopPropagation(); + e.preventDefault(); + } + }, + + keyup = function (e) { + keyState[e.which] = 'r'; + e.stopPropagation(); + e.preventDefault(); + }, + + change = function (e) { + var val = $(e.target).val().trim(), + parsedDate = val ? parseInputDate(val) : null; + setValue(parsedDate); + e.stopImmediatePropagation(); + return false; + }, + + attachDatePickerElementEvents = function () { + input.on({ + 'change': change, + 'blur': options.debug ? '' : hide, + 'keydown': keydown, + 'keyup': keyup, + 'focus': options.allowInputToggle ? show : '' + }); + + if (element.is('input')) { + input.on({ + 'focus': show + }); + } else if (component) { + component.on('click', toggle); + component.on('mousedown', false); + } + }, + + detachDatePickerElementEvents = function () { + input.off({ + 'change': change, + 'blur': blur, + 'keydown': keydown, + 'keyup': keyup, + 'focus': options.allowInputToggle ? hide : '' + }); + + if (element.is('input')) { + input.off({ + 'focus': show + }); + } else if (component) { + component.off('click', toggle); + component.off('mousedown', false); + } + }, + + indexGivenDates = function (givenDatesArray) { + // Store given enabledDates and disabledDates as keys. + // This way we can check their existence in O(1) time instead of looping through whole array. + // (for example: options.enabledDates['2014-02-27'] === true) + var givenDatesIndexed = {}; + $.each(givenDatesArray, function () { + var dDate = parseInputDate(this); + if (dDate.isValid()) { + givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true; + } + }); + return (Object.keys(givenDatesIndexed).length) ? givenDatesIndexed : false; + }, + + indexGivenHours = function (givenHoursArray) { + // Store given enabledHours and disabledHours as keys. + // This way we can check their existence in O(1) time instead of looping through whole array. + // (for example: options.enabledHours['2014-02-27'] === true) + var givenHoursIndexed = {}; + $.each(givenHoursArray, function () { + givenHoursIndexed[this] = true; + }); + return (Object.keys(givenHoursIndexed).length) ? givenHoursIndexed : false; + }, + + initFormatting = function () { + var format = options.format || 'L LT'; + + actualFormat = format.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) { + var newinput = date.localeData().longDateFormat(formatInput) || formatInput; + return newinput.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput2) { //temp fix for #740 + return date.localeData().longDateFormat(formatInput2) || formatInput2; + }); + }); + + + parseFormats = options.extraFormats ? options.extraFormats.slice() : []; + if (parseFormats.indexOf(format) < 0 && parseFormats.indexOf(actualFormat) < 0) { + parseFormats.push(actualFormat); + } + + use24Hours = (actualFormat.toLowerCase().indexOf('a') < 1 && actualFormat.replace(/\[.*?\]/g, '').indexOf('h') < 1); + + if (isEnabled('y')) { + minViewModeNumber = 2; + } + if (isEnabled('M')) { + minViewModeNumber = 1; + } + if (isEnabled('d')) { + minViewModeNumber = 0; + } + + currentViewMode = Math.max(minViewModeNumber, currentViewMode); + + if (!unset) { + setValue(date); + } + }; + + /******************************************************************************** + * + * Public API functions + * ===================== + * + * Important: Do not expose direct references to private objects or the options + * object to the outer world. Always return a clone when returning values or make + * a clone when setting a private variable. + * + ********************************************************************************/ + picker.destroy = function () { + ///Destroys the widget and removes all attached event listeners + hide(); + detachDatePickerElementEvents(); + element.removeData('DateTimePicker'); + element.removeData('date'); + }; + + picker.toggle = toggle; + + picker.show = show; + + picker.hide = hide; + + picker.disable = function () { + ///Disables the input element, the component is attached to, by adding a disabled="true" attribute to it. + ///If the widget was visible before that call it is hidden. Possibly emits dp.hide + hide(); + if (component && component.hasClass('btn')) { + component.addClass('disabled'); + } + input.prop('disabled', true); + return picker; + }; + + picker.enable = function () { + ///Enables the input element, the component is attached to, by removing disabled attribute from it. + if (component && component.hasClass('btn')) { + component.removeClass('disabled'); + } + input.prop('disabled', false); + return picker; + }; + + picker.ignoreReadonly = function (ignoreReadonly) { + if (arguments.length === 0) { + return options.ignoreReadonly; + } + if (typeof ignoreReadonly !== 'boolean') { + throw new TypeError('ignoreReadonly () expects a boolean parameter'); + } + options.ignoreReadonly = ignoreReadonly; + return picker; + }; + + picker.options = function (newOptions) { + if (arguments.length === 0) { + return $.extend(true, {}, options); + } + + if (!(newOptions instanceof Object)) { + throw new TypeError('options() options parameter should be an object'); + } + $.extend(true, options, newOptions); + $.each(options, function (key, value) { + if (picker[key] !== undefined) { + picker[key](value); + } else { + throw new TypeError('option ' + key + ' is not recognized!'); + } + }); + return picker; + }; + + picker.date = function (newDate) { + /// + ///Returns the component's model current date, a moment object or null if not set. + ///date.clone() + /// + /// + ///Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration. + ///Takes string, Date, moment, null parameter. + /// + if (arguments.length === 0) { + if (unset) { + return null; + } + return date.clone(); + } + + if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { + throw new TypeError('date() parameter must be one of [null, string, moment or Date]'); + } + + setValue(newDate === null ? null : parseInputDate(newDate)); + return picker; + }; + + picker.format = function (newFormat) { + ///test su + ///info about para + ///returns foo + if (arguments.length === 0) { + return options.format; + } + + if ((typeof newFormat !== 'string') && ((typeof newFormat !== 'boolean') || (newFormat !== false))) { + throw new TypeError('format() expects a sting or boolean:false parameter ' + newFormat); + } + + options.format = newFormat; + if (actualFormat) { + initFormatting(); // reinit formatting + } + return picker; + }; + + picker.dayViewHeaderFormat = function (newFormat) { + if (arguments.length === 0) { + return options.dayViewHeaderFormat; + } + + if (typeof newFormat !== 'string') { + throw new TypeError('dayViewHeaderFormat() expects a string parameter'); + } + + options.dayViewHeaderFormat = newFormat; + return picker; + }; + + picker.extraFormats = function (formats) { + if (arguments.length === 0) { + return options.extraFormats; + } + + if (formats !== false && !(formats instanceof Array)) { + throw new TypeError('extraFormats() expects an array or false parameter'); + } + + options.extraFormats = formats; + if (parseFormats) { + initFormatting(); // reinit formatting + } + return picker; + }; + + picker.disabledDates = function (dates) { + /// + ///Returns an array with the currently set disabled dates on the component. + ///options.disabledDates + /// + /// + ///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of + ///options.enabledDates if such exist. + ///Takes an [ string or Date or moment ] of values and allows the user to select only from those days. + /// + if (arguments.length === 0) { + return (options.disabledDates ? $.extend({}, options.disabledDates) : options.disabledDates); + } + + if (!dates) { + options.disabledDates = false; + update(); + return picker; + } + if (!(dates instanceof Array)) { + throw new TypeError('disabledDates() expects an array parameter'); + } + options.disabledDates = indexGivenDates(dates); + options.enabledDates = false; + update(); + return picker; + }; + + picker.enabledDates = function (dates) { + /// + ///Returns an array with the currently set enabled dates on the component. + ///options.enabledDates + /// + /// + ///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledDates if such exist. + ///Takes an [ string or Date or moment ] of values and allows the user to select only from those days. + /// + if (arguments.length === 0) { + return (options.enabledDates ? $.extend({}, options.enabledDates) : options.enabledDates); + } + + if (!dates) { + options.enabledDates = false; + update(); + return picker; + } + if (!(dates instanceof Array)) { + throw new TypeError('enabledDates() expects an array parameter'); + } + options.enabledDates = indexGivenDates(dates); + options.disabledDates = false; + update(); + return picker; + }; + + picker.daysOfWeekDisabled = function (daysOfWeekDisabled) { + if (arguments.length === 0) { + return options.daysOfWeekDisabled.splice(0); + } + + if ((typeof daysOfWeekDisabled === 'boolean') && !daysOfWeekDisabled) { + options.daysOfWeekDisabled = false; + update(); + return picker; + } + + if (!(daysOfWeekDisabled instanceof Array)) { + throw new TypeError('daysOfWeekDisabled() expects an array parameter'); + } + options.daysOfWeekDisabled = daysOfWeekDisabled.reduce(function (previousValue, currentValue) { + currentValue = parseInt(currentValue, 10); + if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) { + return previousValue; + } + if (previousValue.indexOf(currentValue) === -1) { + previousValue.push(currentValue); + } + return previousValue; + }, []).sort(); + if (options.useCurrent && !options.keepInvalid) { + var tries = 0; + while (!isValid(date, 'd')) { + date.add(1, 'd'); + if (tries === 7) { + throw 'Tried 7 times to find a valid date'; + } + tries++; + } + setValue(date); + } + update(); + return picker; + }; + + picker.maxDate = function (maxDate) { + if (arguments.length === 0) { + return options.maxDate ? options.maxDate.clone() : options.maxDate; + } + + if ((typeof maxDate === 'boolean') && maxDate === false) { + options.maxDate = false; + update(); + return picker; + } + + if (typeof maxDate === 'string') { + if (maxDate === 'now' || maxDate === 'moment') { + maxDate = moment(); + } + } + + var parsedDate = parseInputDate(maxDate); + + if (!parsedDate.isValid()) { + throw new TypeError('maxDate() Could not parse date parameter: ' + maxDate); + } + if (options.minDate && parsedDate.isBefore(options.minDate)) { + throw new TypeError('maxDate() date parameter is before options.minDate: ' + parsedDate.format(actualFormat)); + } + options.maxDate = parsedDate; + if (options.useCurrent && !options.keepInvalid && date.isAfter(maxDate)) { + setValue(options.maxDate); + } + if (viewDate.isAfter(parsedDate)) { + viewDate = parsedDate.clone().subtract(options.stepping, 'm'); + } + update(); + return picker; + }; + + picker.minDate = function (minDate) { + if (arguments.length === 0) { + return options.minDate ? options.minDate.clone() : options.minDate; + } + + if ((typeof minDate === 'boolean') && minDate === false) { + options.minDate = false; + update(); + return picker; + } + + if (typeof minDate === 'string') { + if (minDate === 'now' || minDate === 'moment') { + minDate = moment(); + } + } + + var parsedDate = parseInputDate(minDate); + + if (!parsedDate.isValid()) { + throw new TypeError('minDate() Could not parse date parameter: ' + minDate); + } + if (options.maxDate && parsedDate.isAfter(options.maxDate)) { + throw new TypeError('minDate() date parameter is after options.maxDate: ' + parsedDate.format(actualFormat)); + } + options.minDate = parsedDate; + if (options.useCurrent && !options.keepInvalid && date.isBefore(minDate)) { + setValue(options.minDate); + } + if (viewDate.isBefore(parsedDate)) { + viewDate = parsedDate.clone().add(options.stepping, 'm'); + } + update(); + return picker; + }; + + picker.defaultDate = function (defaultDate) { + /// + ///Returns a moment with the options.defaultDate option configuration or false if not set + ///date.clone() + /// + /// + ///Will set the picker's inital date. If a boolean:false value is passed the options.defaultDate parameter is cleared. + ///Takes a string, Date, moment, boolean:false + /// + if (arguments.length === 0) { + return options.defaultDate ? options.defaultDate.clone() : options.defaultDate; + } + if (!defaultDate) { + options.defaultDate = false; + return picker; + } + + if (typeof defaultDate === 'string') { + if (defaultDate === 'now' || defaultDate === 'moment') { + defaultDate = moment(); + } + } + + var parsedDate = parseInputDate(defaultDate); + if (!parsedDate.isValid()) { + throw new TypeError('defaultDate() Could not parse date parameter: ' + defaultDate); + } + if (!isValid(parsedDate)) { + throw new TypeError('defaultDate() date passed is invalid according to component setup validations'); + } + + options.defaultDate = parsedDate; + + if (options.defaultDate && options.inline || (input.val().trim() === '' && input.attr('placeholder') === undefined)) { + setValue(options.defaultDate); + } + return picker; + }; + + picker.locale = function (locale) { + if (arguments.length === 0) { + return options.locale; + } + + if (!moment.localeData(locale)) { + throw new TypeError('locale() locale ' + locale + ' is not loaded from moment locales!'); + } + + options.locale = locale; + date.locale(options.locale); + viewDate.locale(options.locale); + + if (actualFormat) { + initFormatting(); // reinit formatting + } + if (widget) { + hide(); + show(); + } + return picker; + }; + + picker.stepping = function (stepping) { + if (arguments.length === 0) { + return options.stepping; + } + + stepping = parseInt(stepping, 10); + if (isNaN(stepping) || stepping < 1) { + stepping = 1; + } + options.stepping = stepping; + return picker; + }; + + picker.useCurrent = function (useCurrent) { + var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute']; + if (arguments.length === 0) { + return options.useCurrent; + } + + if ((typeof useCurrent !== 'boolean') && (typeof useCurrent !== 'string')) { + throw new TypeError('useCurrent() expects a boolean or string parameter'); + } + if (typeof useCurrent === 'string' && useCurrentOptions.indexOf(useCurrent.toLowerCase()) === -1) { + throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', ')); + } + options.useCurrent = useCurrent; + return picker; + }; + + picker.collapse = function (collapse) { + if (arguments.length === 0) { + return options.collapse; + } + + if (typeof collapse !== 'boolean') { + throw new TypeError('collapse() expects a boolean parameter'); + } + if (options.collapse === collapse) { + return picker; + } + options.collapse = collapse; + if (widget) { + hide(); + show(); + } + return picker; + }; + + picker.icons = function (icons) { + if (arguments.length === 0) { + return $.extend({}, options.icons); + } + + if (!(icons instanceof Object)) { + throw new TypeError('icons() expects parameter to be an Object'); + } + $.extend(options.icons, icons); + if (widget) { + hide(); + show(); + } + return picker; + }; + + picker.tooltips = function (tooltips) { + if (arguments.length === 0) { + return $.extend({}, options.tooltips); + } + + if (!(tooltips instanceof Object)) { + throw new TypeError('tooltips() expects parameter to be an Object'); + } + $.extend(options.tooltips, tooltips); + if (widget) { + hide(); + show(); + } + return picker; + }; + + picker.useStrict = function (useStrict) { + if (arguments.length === 0) { + return options.useStrict; + } + + if (typeof useStrict !== 'boolean') { + throw new TypeError('useStrict() expects a boolean parameter'); + } + options.useStrict = useStrict; + return picker; + }; + + picker.sideBySide = function (sideBySide) { + if (arguments.length === 0) { + return options.sideBySide; + } + + if (typeof sideBySide !== 'boolean') { + throw new TypeError('sideBySide() expects a boolean parameter'); + } + options.sideBySide = sideBySide; + if (widget) { + hide(); + show(); + } + return picker; + }; + + picker.viewMode = function (viewMode) { + if (arguments.length === 0) { + return options.viewMode; + } + + if (typeof viewMode !== 'string') { + throw new TypeError('viewMode() expects a string parameter'); + } + + if (viewModes.indexOf(viewMode) === -1) { + throw new TypeError('viewMode() parameter must be one of (' + viewModes.join(', ') + ') value'); + } + + options.viewMode = viewMode; + currentViewMode = Math.max(viewModes.indexOf(viewMode), minViewModeNumber); + + showMode(); + return picker; + }; + + picker.toolbarPlacement = function (toolbarPlacement) { + if (arguments.length === 0) { + return options.toolbarPlacement; + } + + if (typeof toolbarPlacement !== 'string') { + throw new TypeError('toolbarPlacement() expects a string parameter'); + } + if (toolbarPlacements.indexOf(toolbarPlacement) === -1) { + throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value'); + } + options.toolbarPlacement = toolbarPlacement; + + if (widget) { + hide(); + show(); + } + return picker; + }; + + picker.widgetPositioning = function (widgetPositioning) { + if (arguments.length === 0) { + return $.extend({}, options.widgetPositioning); + } + + if (({}).toString.call(widgetPositioning) !== '[object Object]') { + throw new TypeError('widgetPositioning() expects an object variable'); + } + if (widgetPositioning.horizontal) { + if (typeof widgetPositioning.horizontal !== 'string') { + throw new TypeError('widgetPositioning() horizontal variable must be a string'); + } + widgetPositioning.horizontal = widgetPositioning.horizontal.toLowerCase(); + if (horizontalModes.indexOf(widgetPositioning.horizontal) === -1) { + throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')'); + } + options.widgetPositioning.horizontal = widgetPositioning.horizontal; + } + if (widgetPositioning.vertical) { + if (typeof widgetPositioning.vertical !== 'string') { + throw new TypeError('widgetPositioning() vertical variable must be a string'); + } + widgetPositioning.vertical = widgetPositioning.vertical.toLowerCase(); + if (verticalModes.indexOf(widgetPositioning.vertical) === -1) { + throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')'); + } + options.widgetPositioning.vertical = widgetPositioning.vertical; + } + update(); + return picker; + }; + + picker.calendarWeeks = function (calendarWeeks) { + if (arguments.length === 0) { + return options.calendarWeeks; + } + + if (typeof calendarWeeks !== 'boolean') { + throw new TypeError('calendarWeeks() expects parameter to be a boolean value'); + } + + options.calendarWeeks = calendarWeeks; + update(); + return picker; + }; + + picker.showTodayButton = function (showTodayButton) { + if (arguments.length === 0) { + return options.showTodayButton; + } + + if (typeof showTodayButton !== 'boolean') { + throw new TypeError('showTodayButton() expects a boolean parameter'); + } + + options.showTodayButton = showTodayButton; + if (widget) { + hide(); + show(); + } + return picker; + }; + + picker.showClear = function (showClear) { + if (arguments.length === 0) { + return options.showClear; + } + + if (typeof showClear !== 'boolean') { + throw new TypeError('showClear() expects a boolean parameter'); + } + + options.showClear = showClear; + if (widget) { + hide(); + show(); + } + return picker; + }; + + picker.widgetParent = function (widgetParent) { + if (arguments.length === 0) { + return options.widgetParent; + } + + if (typeof widgetParent === 'string') { + widgetParent = $(widgetParent); + } + + if (widgetParent !== null && (typeof widgetParent !== 'string' && !(widgetParent instanceof $))) { + throw new TypeError('widgetParent() expects a string or a jQuery object parameter'); + } + + options.widgetParent = widgetParent; + if (widget) { + hide(); + show(); + } + return picker; + }; + + picker.keepOpen = function (keepOpen) { + if (arguments.length === 0) { + return options.keepOpen; + } + + if (typeof keepOpen !== 'boolean') { + throw new TypeError('keepOpen() expects a boolean parameter'); + } + + options.keepOpen = keepOpen; + return picker; + }; + + picker.focusOnShow = function (focusOnShow) { + if (arguments.length === 0) { + return options.focusOnShow; + } + + if (typeof focusOnShow !== 'boolean') { + throw new TypeError('focusOnShow() expects a boolean parameter'); + } + + options.focusOnShow = focusOnShow; + return picker; + }; + + picker.inline = function (inline) { + if (arguments.length === 0) { + return options.inline; + } + + if (typeof inline !== 'boolean') { + throw new TypeError('inline() expects a boolean parameter'); + } + + options.inline = inline; + return picker; + }; + + picker.clear = function () { + clear(); + return picker; + }; + + picker.keyBinds = function (keyBinds) { + options.keyBinds = keyBinds; + return picker; + }; + + picker.debug = function (debug) { + if (typeof debug !== 'boolean') { + throw new TypeError('debug() expects a boolean parameter'); + } + + options.debug = debug; + return picker; + }; + + picker.allowInputToggle = function (allowInputToggle) { + if (arguments.length === 0) { + return options.allowInputToggle; + } + + if (typeof allowInputToggle !== 'boolean') { + throw new TypeError('allowInputToggle() expects a boolean parameter'); + } + + options.allowInputToggle = allowInputToggle; + return picker; + }; + + picker.showClose = function (showClose) { + if (arguments.length === 0) { + return options.showClose; + } + + if (typeof showClose !== 'boolean') { + throw new TypeError('showClose() expects a boolean parameter'); + } + + options.showClose = showClose; + return picker; + }; + + picker.keepInvalid = function (keepInvalid) { + if (arguments.length === 0) { + return options.keepInvalid; + } + + if (typeof keepInvalid !== 'boolean') { + throw new TypeError('keepInvalid() expects a boolean parameter'); + } + options.keepInvalid = keepInvalid; + return picker; + }; + + picker.datepickerInput = function (datepickerInput) { + if (arguments.length === 0) { + return options.datepickerInput; + } + + if (typeof datepickerInput !== 'string') { + throw new TypeError('datepickerInput() expects a string parameter'); + } + + options.datepickerInput = datepickerInput; + return picker; + }; + + picker.parseInputDate = function (parseInputDate) { + if (arguments.length === 0) { + return options.parseInputDate; + } + + if (typeof parseInputDate !== 'function') { + throw new TypeError('parseInputDate() sholud be as function'); + } + + options.parseInputDate = parseInputDate; + + return picker; + }; + + picker.disabledTimeIntervals = function (disabledTimeIntervals) { + /// + ///Returns an array with the currently set disabled dates on the component. + ///options.disabledTimeIntervals + /// + /// + ///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of + ///options.enabledDates if such exist. + ///Takes an [ string or Date or moment ] of values and allows the user to select only from those days. + /// + if (arguments.length === 0) { + return (options.disabledTimeIntervals ? $.extend({}, options.disabledTimeIntervals) : options.disabledTimeIntervals); + } + + if (!disabledTimeIntervals) { + options.disabledTimeIntervals = false; + update(); + return picker; + } + if (!(disabledTimeIntervals instanceof Array)) { + throw new TypeError('disabledTimeIntervals() expects an array parameter'); + } + options.disabledTimeIntervals = disabledTimeIntervals; + update(); + return picker; + }; + + picker.disabledHours = function (hours) { + /// + ///Returns an array with the currently set disabled hours on the component. + ///options.disabledHours + /// + /// + ///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of + ///options.enabledHours if such exist. + ///Takes an [ int ] of values and disallows the user to select only from those hours. + /// + if (arguments.length === 0) { + return (options.disabledHours ? $.extend({}, options.disabledHours) : options.disabledHours); + } + + if (!hours) { + options.disabledHours = false; + update(); + return picker; + } + if (!(hours instanceof Array)) { + throw new TypeError('disabledHours() expects an array parameter'); + } + options.disabledHours = indexGivenHours(hours); + options.enabledHours = false; + if (options.useCurrent && !options.keepInvalid) { + var tries = 0; + while (!isValid(date, 'h')) { + date.add(1, 'h'); + if (tries === 24) { + throw 'Tried 24 times to find a valid date'; + } + tries++; + } + setValue(date); + } + update(); + return picker; + }; + + picker.enabledHours = function (hours) { + /// + ///Returns an array with the currently set enabled hours on the component. + ///options.enabledHours + /// + /// + ///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledHours if such exist. + ///Takes an [ int ] of values and allows the user to select only from those hours. + /// + if (arguments.length === 0) { + return (options.enabledHours ? $.extend({}, options.enabledHours) : options.enabledHours); + } + + if (!hours) { + options.enabledHours = false; + update(); + return picker; + } + if (!(hours instanceof Array)) { + throw new TypeError('enabledHours() expects an array parameter'); + } + options.enabledHours = indexGivenHours(hours); + options.disabledHours = false; + if (options.useCurrent && !options.keepInvalid) { + var tries = 0; + while (!isValid(date, 'h')) { + date.add(1, 'h'); + if (tries === 24) { + throw 'Tried 24 times to find a valid date'; + } + tries++; + } + setValue(date); + } + update(); + return picker; + }; + + picker.viewDate = function (newDate) { + /// + ///Returns the component's model current viewDate, a moment object or null if not set. + ///viewDate.clone() + /// + /// + ///Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration. + ///Takes string, viewDate, moment, null parameter. + /// + if (arguments.length === 0) { + return viewDate.clone(); + } + + if (!newDate) { + viewDate = date.clone(); + return picker; + } + + if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { + throw new TypeError('viewDate() parameter must be one of [string, moment or Date]'); + } + + viewDate = parseInputDate(newDate); + viewUpdate(); + return picker; + }; + + // initializing element and component attributes + if (element.is('input')) { + input = element; + } else { + input = element.find(options.datepickerInput); + if (input.size() === 0) { + input = element.find('input'); + } else if (!input.is('input')) { + throw new Error('CSS class "' + options.datepickerInput + '" cannot be applied to non input element'); + } + } + + if (element.hasClass('input-group')) { + // in case there is more then one 'input-group-addon' Issue #48 + if (element.find('.datepickerbutton').size() === 0) { + component = element.find('.input-group-addon'); + } else { + component = element.find('.datepickerbutton'); + } + } + + if (!options.inline && !input.is('input')) { + throw new Error('Could not initialize DateTimePicker without an input element'); + } + + $.extend(true, options, dataToOptions()); + + picker.options(options); + + initFormatting(); + + attachDatePickerElementEvents(); + + if (input.prop('disabled')) { + picker.disable(); + } + if (input.is('input') && input.val().trim().length !== 0) { + setValue(parseInputDate(input.val().trim())); + } + else if (options.defaultDate && input.attr('placeholder') === undefined) { + setValue(options.defaultDate); + } + if (options.inline) { + show(); + } + return picker; + }; + + /******************************************************************************** + * + * jQuery plugin constructor and defaults object + * + ********************************************************************************/ + + $.fn.datetimepicker = function (options) { + return this.each(function () { + var $this = $(this); + if (!$this.data('DateTimePicker')) { + // create a private copy of the defaults object + options = $.extend(true, {}, $.fn.datetimepicker.defaults, options); + $this.data('DateTimePicker', dateTimePicker($this, options)); + } + }); + }; + + $.fn.datetimepicker.defaults = { + format: false, + dayViewHeaderFormat: 'MMMM YYYY', + extraFormats: false, + stepping: 1, + minDate: false, + maxDate: false, + useCurrent: true, + collapse: true, + locale: moment.locale(), + defaultDate: false, + disabledDates: false, + enabledDates: false, + icons: { + time: 'glyphicon glyphicon-time', + date: 'glyphicon glyphicon-calendar', + up: 'glyphicon glyphicon-chevron-up', + down: 'glyphicon glyphicon-chevron-down', + previous: 'glyphicon glyphicon-chevron-left', + next: 'glyphicon glyphicon-chevron-right', + today: 'glyphicon glyphicon-screenshot', + clear: 'glyphicon glyphicon-trash', + close: 'glyphicon glyphicon-remove' + }, + tooltips: { + today: 'Go to today', + clear: 'Clear selection', + close: 'Close the picker', + selectMonth: 'Select Month', + prevMonth: 'Previous Month', + nextMonth: 'Next Month', + selectYear: 'Select Year', + prevYear: 'Previous Year', + nextYear: 'Next Year', + selectDecade: 'Select Decade', + prevDecade: 'Previous Decade', + nextDecade: 'Next Decade', + prevCentury: 'Previous Century', + nextCentury: 'Next Century' + }, + useStrict: false, + sideBySide: false, + daysOfWeekDisabled: false, + calendarWeeks: false, + viewMode: 'days', + toolbarPlacement: 'default', + showTodayButton: false, + showClear: false, + showClose: false, + widgetPositioning: { + horizontal: 'auto', + vertical: 'auto' + }, + widgetParent: null, + ignoreReadonly: false, + keepOpen: false, + focusOnShow: true, + inline: false, + keepInvalid: false, + datepickerInput: '.datepickerinput', + keyBinds: { + up: function (widget) { + if (!widget) { + return; + } + var d = this.date() || moment(); + if (widget.find('.datepicker').is(':visible')) { + this.date(d.clone().subtract(7, 'd')); + } else { + this.date(d.clone().add(this.stepping(), 'm')); + } + }, + down: function (widget) { + if (!widget) { + this.show(); + return; + } + var d = this.date() || moment(); + if (widget.find('.datepicker').is(':visible')) { + this.date(d.clone().add(7, 'd')); + } else { + this.date(d.clone().subtract(this.stepping(), 'm')); + } + }, + 'control up': function (widget) { + if (!widget) { + return; + } + var d = this.date() || moment(); + if (widget.find('.datepicker').is(':visible')) { + this.date(d.clone().subtract(1, 'y')); + } else { + this.date(d.clone().add(1, 'h')); + } + }, + 'control down': function (widget) { + if (!widget) { + return; + } + var d = this.date() || moment(); + if (widget.find('.datepicker').is(':visible')) { + this.date(d.clone().add(1, 'y')); + } else { + this.date(d.clone().subtract(1, 'h')); + } + }, + left: function (widget) { + if (!widget) { + return; + } + var d = this.date() || moment(); + if (widget.find('.datepicker').is(':visible')) { + this.date(d.clone().subtract(1, 'd')); + } + }, + right: function (widget) { + if (!widget) { + return; + } + var d = this.date() || moment(); + if (widget.find('.datepicker').is(':visible')) { + this.date(d.clone().add(1, 'd')); + } + }, + pageUp: function (widget) { + if (!widget) { + return; + } + var d = this.date() || moment(); + if (widget.find('.datepicker').is(':visible')) { + this.date(d.clone().subtract(1, 'M')); + } + }, + pageDown: function (widget) { + if (!widget) { + return; + } + var d = this.date() || moment(); + if (widget.find('.datepicker').is(':visible')) { + this.date(d.clone().add(1, 'M')); + } + }, + enter: function () { + this.hide(); + }, + escape: function () { + this.hide(); + }, + //tab: function (widget) { //this break the flow of the form. disabling for now + // var toggle = widget.find('.picker-switch a[data-action="togglePicker"]'); + // if(toggle.length > 0) toggle.click(); + //}, + 'control space': function (widget) { + if (widget.find('.timepicker').is(':visible')) { + widget.find('.btn[data-action="togglePeriod"]').click(); + } + }, + t: function () { + this.date(moment()); + }, + 'delete': function () { + this.clear(); + } + }, + debug: false, + allowInputToggle: false, + disabledTimeIntervals: false, + disabledHours: false, + enabledHours: false, + viewDate: false + }; +})); diff --git a/bootstrap/js/jquery.min.js b/bootstrap/js/jquery.min.js index ab28a24..e5ace11 100644 --- a/bootstrap/js/jquery.min.js +++ b/bootstrap/js/jquery.min.js @@ -1,4 +1,4 @@ -/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ -!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="
",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; -if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="
').addClass('cw').text('#')); + } + + while (currentDate.isBefore(viewDate.clone().endOf('w'))) { + row.append($('').addClass('dow').text(currentDate.format('dd'))); + currentDate.add(1, 'd'); + } + widget.find('.datepicker-days thead').append(row); + }, + + isInDisabledDates = function (testDate) { + return options.disabledDates[testDate.format('YYYY-MM-DD')] === true; + }, + + isInEnabledDates = function (testDate) { + return options.enabledDates[testDate.format('YYYY-MM-DD')] === true; + }, + + isInDisabledHours = function (testDate) { + return options.disabledHours[testDate.format('H')] === true; + }, + + isInEnabledHours = function (testDate) { + return options.enabledHours[testDate.format('H')] === true; + }, + + isValid = function (targetMoment, granularity) { + if (!targetMoment.isValid()) { + return false; + } + if (options.disabledDates && granularity === 'd' && isInDisabledDates(targetMoment)) { + return false; + } + if (options.enabledDates && granularity === 'd' && !isInEnabledDates(targetMoment)) { + return false; + } + if (options.minDate && targetMoment.isBefore(options.minDate, granularity)) { + return false; + } + if (options.maxDate && targetMoment.isAfter(options.maxDate, granularity)) { + return false; + } + if (options.daysOfWeekDisabled && granularity === 'd' && options.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) { + return false; + } + if (options.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && isInDisabledHours(targetMoment)) { + return false; + } + if (options.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && !isInEnabledHours(targetMoment)) { + return false; + } + if (options.disabledTimeIntervals && (granularity === 'h' || granularity === 'm' || granularity === 's')) { + var found = false; + $.each(options.disabledTimeIntervals, function () { + if (targetMoment.isBetween(this[0], this[1])) { + found = true; + return false; + } + }); + if (found) { + return false; + } + } + return true; + }, + + fillMonths = function () { + var spans = [], + monthsShort = viewDate.clone().startOf('y').startOf('d'); + while (monthsShort.isSame(viewDate, 'y')) { + spans.push($('').attr('data-action', 'selectMonth').addClass('month').text(monthsShort.format('MMM'))); + monthsShort.add(1, 'M'); + } + widget.find('.datepicker-months td').empty().append(spans); + }, + + updateMonths = function () { + var monthsView = widget.find('.datepicker-months'), + monthsViewHeader = monthsView.find('th'), + months = monthsView.find('tbody').find('span'); + + monthsViewHeader.eq(0).find('span').attr('title', options.tooltips.prevYear); + monthsViewHeader.eq(1).attr('title', options.tooltips.selectYear); + monthsViewHeader.eq(2).find('span').attr('title', options.tooltips.nextYear); + + monthsView.find('.disabled').removeClass('disabled'); + + if (!isValid(viewDate.clone().subtract(1, 'y'), 'y')) { + monthsViewHeader.eq(0).addClass('disabled'); + } + + monthsViewHeader.eq(1).text(viewDate.year()); + + if (!isValid(viewDate.clone().add(1, 'y'), 'y')) { + monthsViewHeader.eq(2).addClass('disabled'); + } + + months.removeClass('active'); + if (date.isSame(viewDate, 'y') && !unset) { + months.eq(date.month()).addClass('active'); + } + + months.each(function (index) { + if (!isValid(viewDate.clone().month(index), 'M')) { + $(this).addClass('disabled'); + } + }); + }, + + updateYears = function () { + var yearsView = widget.find('.datepicker-years'), + yearsViewHeader = yearsView.find('th'), + startYear = viewDate.clone().subtract(5, 'y'), + endYear = viewDate.clone().add(6, 'y'), + html = ''; + + yearsViewHeader.eq(0).find('span').attr('title', options.tooltips.nextDecade); + yearsViewHeader.eq(1).attr('title', options.tooltips.selectDecade); + yearsViewHeader.eq(2).find('span').attr('title', options.tooltips.prevDecade); + + yearsView.find('.disabled').removeClass('disabled'); + + if (options.minDate && options.minDate.isAfter(startYear, 'y')) { + yearsViewHeader.eq(0).addClass('disabled'); + } + + yearsViewHeader.eq(1).text(startYear.year() + '-' + endYear.year()); + + if (options.maxDate && options.maxDate.isBefore(endYear, 'y')) { + yearsViewHeader.eq(2).addClass('disabled'); + } + + while (!startYear.isAfter(endYear, 'y')) { + html += '' + startYear.year() + ''; + startYear.add(1, 'y'); + } + + yearsView.find('td').html(html); + }, + + updateDecades = function () { + var decadesView = widget.find('.datepicker-decades'), + decadesViewHeader = decadesView.find('th'), + startDecade = viewDate.isBefore(moment({y: 1999})) ? moment({y: 1899}) : moment({y: 1999}), + endDecade = startDecade.clone().add(100, 'y'), + html = ''; + + decadesViewHeader.eq(0).find('span').attr('title', options.tooltips.prevCentury); + decadesViewHeader.eq(2).find('span').attr('title', options.tooltips.nextCentury); + + decadesView.find('.disabled').removeClass('disabled'); + + if (startDecade.isSame(moment({y: 1900})) || (options.minDate && options.minDate.isAfter(startDecade, 'y'))) { + decadesViewHeader.eq(0).addClass('disabled'); + } + + decadesViewHeader.eq(1).text(startDecade.year() + '-' + endDecade.year()); + + if (startDecade.isSame(moment({y: 2000})) || (options.maxDate && options.maxDate.isBefore(endDecade, 'y'))) { + decadesViewHeader.eq(2).addClass('disabled'); + } + + while (!startDecade.isAfter(endDecade, 'y')) { + html += '' + (startDecade.year() + 1) + ' - ' + (startDecade.year() + 12) + ''; + startDecade.add(12, 'y'); + } + html += ''; //push the dangling block over, at least this way it's even + + decadesView.find('td').html(html); + }, + + fillDate = function () { + var daysView = widget.find('.datepicker-days'), + daysViewHeader = daysView.find('th'), + currentDate, + html = [], + row, + clsName, + i; + + if (!hasDate()) { + return; + } + + daysViewHeader.eq(0).find('span').attr('title', options.tooltips.prevMonth); + daysViewHeader.eq(1).attr('title', options.tooltips.selectMonth); + daysViewHeader.eq(2).find('span').attr('title', options.tooltips.nextMonth); + + daysView.find('.disabled').removeClass('disabled'); + daysViewHeader.eq(1).text(viewDate.format(options.dayViewHeaderFormat)); + + if (!isValid(viewDate.clone().subtract(1, 'M'), 'M')) { + daysViewHeader.eq(0).addClass('disabled'); + } + if (!isValid(viewDate.clone().add(1, 'M'), 'M')) { + daysViewHeader.eq(2).addClass('disabled'); + } + + currentDate = viewDate.clone().startOf('M').startOf('w').startOf('d'); + + for (i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks) + if (currentDate.weekday() === 0) { + row = $('
' + currentDate.week() + '' + currentDate.date() + '
' + currentHour.format(use24Hours ? 'HH' : 'hh') + '
' + currentMinute.format('mm') + '
' + currentSecond.format('ss') + '
a",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/
","
"],tr:[2,"","
"],col:[2,"","
"],td:[3,"","
"],_default:k.htmlSerialize?[0,"",""]:[1,"X
","
"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?""!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("