From 00b5a1eaec1f6297533ef42236520a78526ac3ae Mon Sep 17 00:00:00 2001 From: Esteban Sanchez Date: Tue, 17 Jun 2008 14:30:44 +0000 Subject: [PATCH] 2008-06-17 Esteban Sanchez * ajax.php: Added to repository. AJAX interface for Pandora. A new time is coming... * pandoradb.sql: Added id_group to treport. A report is now assigned to a group of agents. Changes in treport_content to add an order field, drop sla fields and use an enum for the type. NOTE: This will break all your current defined reports, update under your responsabillity. Added table treport_content_sla_combined to define SLAs in the SLA types reports. * godmode/reporting/graph_builder.php: Use Pandora functions. Adde javascript code to display the module icon when changing from the dropdown menu. * godmode/reporting/reporting_builder.php: Almost complet rewritten to use Pandora HTML functions. Style correction. * include/functions.php: Added new report types. Style correction. * include/functions_db.php: Use Pandora database functions to get simple values. Added functions get_agents_in_group(), get_modules_in_agent(), get_simple_alerts_in_agent(), get_combined_alerts_in_agent(), get_alerts_in_agent(), get_monitor_downs_in_period(), get_monitor_last_down_timestamp_in_period(), get_alert_fires_in_period(), get_alert_last_fire_timestamp_in_period(). Deleted debug output and fixed calling to an inexistent function in return_moduledata_sum_value(). * include/functions_html.php: Tab style correction. Thanks to Ramon for the advice. Fixed some errors on print_table that was causing not to work fine if rowclass or colspan was defined. * include/functions_reporting.php: Adde date support to return_module_SLA(), event_reporting(). Added alert_reporting(), monitor_health_reporting(), general_group_reporting() and agents_detailed_reporting() to implement new report types. Style correction. * include/javascript/pandora.js: Added html_entity_decode() function to decode some AJAX results. * javascript/jquery.js: Added to repository. jQuery version 1.2.4a * include/javascript/jquery.timeentry.js: jQuery plugin to manage time inputs. * include/javascript/jquery.ui.datepicker.js: jQuery plugin to manage date inputs in a dropdown calendar. * include/languages/date_*.js, include/languages/time_*.js: Added to repository. Translation of date and time strings for the new calendar javascript support. * include/languages/language_en.php: Added new strings relatives to reports. * include/languages/language_de.php, include/languages/language_fr.php, include/languages/language_gl.php, include/languages/language_pt_br.php: Fixed a variable name. * godmode/groups/group_list.php: Avoid the use of an extra indentation by returning if no success on comprueba_login(). * include/styles/pandora.css: Add some classes. Tab style correction. * operation/agentes/ver_agente.php: Added AJAX support to agent operations. * operation/reporting/graph_viewer.php: Period dropdown selection improved and printed with Pandora functions. * operation/reporting/reporting_viewer.php: Massive rewritten. Implemented date and time support, added new report types, use Pandora functions... * reporting/fgraph.php: Documentation fix. Added a new graphic to show monitors health. * godmode/agentes/agent_manager.php, operation/reporting/custom_reporting.php: Style correction. git-svn-id: https://svn.code.sf.net/p/pandora/code/trunk@869 c3f86ba8-e40f-0410-aaad-9ba5e7f4b01f --- pandora_console/ChangeLog | 85 + pandora_console/ajax.php | 57 + .../godmode/agentes/agent_manager.php | 2 +- pandora_console/godmode/groups/group_list.php | 227 +-- .../godmode/reporting/graph_builder.php | 69 +- .../godmode/reporting/reporting_builder.php | 908 ++++++----- pandora_console/include/functions.php | 12 +- pandora_console/include/functions_db.php | 328 ++-- pandora_console/include/functions_html.php | 56 +- .../include/functions_reporting.php | 420 ++++- pandora_console/include/javascript/jquery.js | 13 + .../include/javascript/jquery.timeentry.js | 7 + .../javascript/jquery.ui.datepicker.js | 1450 +++++++++++++++++ pandora_console/include/javascript/pandora.js | 17 +- pandora_console/include/languages/date_ca.js | 22 + pandora_console/include/languages/date_de.js | 22 + pandora_console/include/languages/date_en.js | 1 + pandora_console/include/languages/date_es.js | 22 + pandora_console/include/languages/date_fr.js | 22 + pandora_console/include/languages/date_it.js | 22 + .../include/languages/date_pt_br.js | 22 + .../include/languages/language_de.php | 2 +- .../include/languages/language_en.php | 36 +- .../include/languages/language_fr.php | 4 +- .../include/languages/language_gl.php | 2 +- .../include/languages/language_pt_br.php | 4 +- pandora_console/include/languages/time_ca.js | 8 + pandora_console/include/languages/time_de.js | 9 + pandora_console/include/languages/time_es.js | 9 + pandora_console/include/languages/time_fr.js | 9 + pandora_console/include/languages/time_it.js | 9 + .../include/languages/time_pt_br.js | 9 + pandora_console/include/styles/pandora.css | 47 +- .../operation/agentes/ver_agente.php | 23 + .../operation/reporting/custom_reporting.php | 2 +- .../operation/reporting/graph_viewer.php | 70 +- .../operation/reporting/reporting_viewer.php | 535 +++--- pandora_console/pandoradb.sql | 45 +- pandora_console/reporting/fgraph.php | 17 +- 39 files changed, 3590 insertions(+), 1034 deletions(-) create mode 100644 pandora_console/ajax.php create mode 100644 pandora_console/include/javascript/jquery.js create mode 100644 pandora_console/include/javascript/jquery.timeentry.js create mode 100644 pandora_console/include/javascript/jquery.ui.datepicker.js create mode 100644 pandora_console/include/languages/date_ca.js create mode 100644 pandora_console/include/languages/date_de.js create mode 100644 pandora_console/include/languages/date_en.js create mode 100644 pandora_console/include/languages/date_es.js create mode 100644 pandora_console/include/languages/date_fr.js create mode 100644 pandora_console/include/languages/date_it.js create mode 100644 pandora_console/include/languages/date_pt_br.js create mode 100644 pandora_console/include/languages/time_ca.js create mode 100644 pandora_console/include/languages/time_de.js create mode 100644 pandora_console/include/languages/time_es.js create mode 100644 pandora_console/include/languages/time_fr.js create mode 100644 pandora_console/include/languages/time_it.js create mode 100644 pandora_console/include/languages/time_pt_br.js diff --git a/pandora_console/ChangeLog b/pandora_console/ChangeLog index 55f1d4e00c..b6d6627fbd 100644 --- a/pandora_console/ChangeLog +++ b/pandora_console/ChangeLog @@ -1,3 +1,88 @@ +2008-06-17 Esteban Sanchez + + * ajax.php: Added to repository. AJAX interface for Pandora. A new + time is coming... + + * pandoradb.sql: Added id_group to treport. A report is now assigned + to a group of agents. Changes in treport_content to add an order + field, drop sla fields and use an enum for the type. NOTE: This will + break all your current defined reports, update under your + responsabillity. Added table treport_content_sla_combined to define + SLAs in the SLA types reports. + + * godmode/reporting/graph_builder.php: Use Pandora functions. Adde + javascript code to display the module icon when changing from the + dropdown menu. + + * godmode/reporting/reporting_builder.php: Almost complet rewritten to + use Pandora HTML functions. Style correction. + + * include/functions.php: Added new report types. Style correction. + + * include/functions_db.php: Use Pandora database functions to get + simple values. Added functions get_agents_in_group(), + get_modules_in_agent(), get_simple_alerts_in_agent(), + get_combined_alerts_in_agent(), get_alerts_in_agent(), + get_monitor_downs_in_period(), + get_monitor_last_down_timestamp_in_period(), + get_alert_fires_in_period(), + get_alert_last_fire_timestamp_in_period(). Deleted debug output and + fixed calling to an inexistent function in + return_moduledata_sum_value(). + + * include/functions_html.php: Tab style correction. Thanks to Ramon + for the advice. Fixed some errors on print_table that was causing not + to work fine if rowclass or colspan was defined. + + * include/functions_reporting.php: Adde date support to + return_module_SLA(), event_reporting(). Added alert_reporting(), + monitor_health_reporting(), general_group_reporting() and + agents_detailed_reporting() to implement new report types. Style + correction. + + * include/javascript/pandora.js: Added html_entity_decode() function + to decode some AJAX results. + + * javascript/jquery.js: Added to repository. jQuery version 1.2.4a + + * include/javascript/jquery.timeentry.js: jQuery plugin to manage time + inputs. + + * include/javascript/jquery.ui.datepicker.js: jQuery plugin to manage + date inputs in a dropdown calendar. + + * include/languages/date_*.js, include/languages/time_*.js: Added to + repository. Translation of date and time strings for the new calendar + javascript support. + + * include/languages/language_en.php: Added new strings relatives to + reports. + + * include/languages/language_de.php, + include/languages/language_fr.php, include/languages/language_gl.php, + include/languages/language_pt_br.php: Fixed a variable name. + + * godmode/groups/group_list.php: Avoid the use of an extra indentation + by returning if no success on comprueba_login(). + + * include/styles/pandora.css: Add some classes. Tab style correction. + + * operation/agentes/ver_agente.php: Added AJAX support to agent + operations. + + * operation/reporting/graph_viewer.php: Period dropdown selection + improved and printed with Pandora functions. + + * operation/reporting/reporting_viewer.php: Massive rewritten. + Implemented date and time support, added new report types, use Pandora + functions... + + * reporting/fgraph.php: Documentation fix. Added a new graphic to show + monitors health. + + * godmode/agentes/agent_manager.php, + operation/reporting/custom_reporting.php: Style correction. + 2008-06-16 Sancho Lerena * pandoradb_data.sql: Updated some new config tokens (graph colors), diff --git a/pandora_console/ajax.php b/pandora_console/ajax.php new file mode 100644 index 0000000000..38f4075a98 --- /dev/null +++ b/pandora_console/ajax.php @@ -0,0 +1,57 @@ +Sorry! I can't find the page $page!"; +} +?> diff --git a/pandora_console/godmode/agentes/agent_manager.php b/pandora_console/godmode/agentes/agent_manager.php index 734baad789..a66d4d05e5 100644 --- a/pandora_console/godmode/agentes/agent_manager.php +++ b/pandora_console/godmode/agentes/agent_manager.php @@ -28,7 +28,7 @@ if (give_acl($id_user, 0, "AW")!=1) { audit_db($id_usuario,$REMOTE_ADDR, "ACL Violation","Trying to access agent manager"); require ("general/noaccess.php"); exit; -}; +} echo "

".$lang_label["agent_conf"]; if (isset($_GET["create_agent"])){ diff --git a/pandora_console/godmode/groups/group_list.php b/pandora_console/godmode/groups/group_list.php index 69f25d2e15..e26b7177f1 100644 --- a/pandora_console/godmode/groups/group_list.php +++ b/pandora_console/godmode/groups/group_list.php @@ -24,111 +24,128 @@ // Load global vars require("include/config.php"); -if (comprueba_login() == 0) - $id_user = $_SESSION["id_usuario"]; - if (give_acl($id_user, 0, "PM")==1) { - - if (isset($_POST["create_g"])){ // Create group - $nombre = entrada_limpia($_POST["nombre"]); - $icon = entrada_limpia($_POST["icon"]); - $parent = entrada_limpia($_POST["parent"]); - $disabled = entrada_limpia($_POST["disabled"]); - $sql_insert="INSERT INTO tgrupo (nombre, icon, parent, disabled) - VALUES ('$nombre', '$icon', '$parent', $disabled) "; - $result=mysql_query($sql_insert); - if (! $result) - echo "

".$lang_label["create_group_no"]."

"; - else { - echo "

".$lang_label["create_group_ok"]."

"; - $id_grupo = mysql_insert_id(); - } - } - - if (isset($_POST["update_g"])){ // if modified any parameter - $nombre = entrada_limpia($_POST["nombre"]); - $id_grupo = entrada_limpia($_POST["id_grupo"]); - $icon = entrada_limpia($_POST["icon"]); - $disabled = entrada_limpia($_POST["disabled"]); - $parent = entrada_limpia($_POST["parent"]); - $sql_update ="UPDATE tgrupo - SET nombre = '$nombre', icon = '$icon', disabled = $disabled, parent = '$parent' - WHERE id_grupo = '$id_grupo'"; - $result=mysql_query($sql_update); - if (! $result) - echo "

".$lang_label["modify_group_no"]."

"; - else - echo "

".$lang_label["modify_group_ok"]."

"; - } - - if (isset($_GET["delete_g"])){ // if delete - $id_borrar_modulo = entrada_limpia($_GET["id_grupo"]); - - // First delete from tagente_modulo - $sql_delete= "DELETE FROM tgrupo WHERE id_grupo = ".$id_borrar_modulo; - $result=mysql_query($sql_delete); - if (! $result) - echo "

".$lang_label["delete_group_no"]."

"; - else - echo "

".$lang_label["delete_group_ok"]."

"; - } - echo "

".$lang_label["group_management"]." > "; - echo $lang_label["definedgroups"]."

"; - - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - $sql1='SELECT * FROM tgrupo ORDER BY nombre'; - $result=mysql_query($sql1); - $color=0; - while ($row=mysql_fetch_array($result)){ - if ($color == 1){ - $tdcolor = "datos"; - $color = 0; - } - else { - $tdcolor = "datos2"; - $color = 1; - } - if ($row["id_grupo"] != 1){ - echo ""; - echo ""; - echo ""; - - // Disabled? - echo ""; - - echo ""; - } - } - echo "
".$lang_label["icon"]."".$lang_label["group_name"]."".$lang_label["parent"]."".$lang_label["alerts"]."".$lang_label["delete"]."
"; - echo ""; - echo ""; - echo "".$row["nombre"].""; - echo ""; - echo dame_nombre_grupo ($row["parent"]); - echo ""; - if ($row["disabled"]==1) - echo " ".$lang_label["disabled"]; - else - echo " ".$lang_label["enabled"]; - echo ""; - echo "'; - echo "
"; - echo ""; - echo "
"; - echo "
"; - echo ""; - echo "
"; - - } // Fin pagina - else { - audit_db($id_user,$REMOTE_ADDR, "ACL Violation","Trying to access Group Management"); +if (comprueba_login()) { + audit_db ($id_user,$REMOTE_ADDR, "ACL Violation", "Trying to access Group Management"); require ("general/noaccess.php"); - } + return; +} +$id_user = $_SESSION["id_usuario"]; +if (! give_acl($id_user, 0, "PM")) { + audit_db ($id_user, $REMOTE_ADDR, "ACL Violation", "Trying to access Group Management"); + require ("general/noaccess.php"); + return; +} + +if (defined ('AJAX')) { + $get_group_json = (bool) get_parameter ('get_group_json'); + + if ($get_group_json) { + $id_group = (int) get_parameter ('id_group'); + + $group = get_db_row ('tgrupo', 'id_grupo', $id_group); + + echo json_encode ($group); + exit (); + } + + exit (); +} + +if (isset($_POST["create_g"])) { // Create group + $nombre = entrada_limpia($_POST["nombre"]); + $icon = entrada_limpia($_POST["icon"]); + $parent = entrada_limpia($_POST["parent"]); + $disabled = entrada_limpia($_POST["disabled"]); + $sql_insert="INSERT INTO tgrupo (nombre, icon, parent, disabled) + VALUES ('$nombre', '$icon', '$parent', $disabled) "; + $result=mysql_query($sql_insert); + if (! $result) + echo "

".$lang_label["create_group_no"]."

"; + else { + echo "

".$lang_label["create_group_ok"]."

"; + $id_grupo = mysql_insert_id(); + } +} + +if (isset($_POST["update_g"])){ // if modified any parameter + $nombre = entrada_limpia($_POST["nombre"]); + $id_grupo = entrada_limpia($_POST["id_grupo"]); + $icon = entrada_limpia($_POST["icon"]); + $disabled = entrada_limpia($_POST["disabled"]); + $parent = entrada_limpia($_POST["parent"]); + $sql_update ="UPDATE tgrupo + SET nombre = '$nombre', icon = '$icon', disabled = $disabled, parent = '$parent' + WHERE id_grupo = '$id_grupo'"; + $result=mysql_query($sql_update); + if (! $result) + echo "

".$lang_label["modify_group_no"]."

"; + else + echo "

".$lang_label["modify_group_ok"]."

"; +} + +if (isset($_GET["delete_g"])){ // if delete + $id_borrar_modulo = entrada_limpia($_GET["id_grupo"]); + + // First delete from tagente_modulo + $sql_delete= "DELETE FROM tgrupo WHERE id_grupo = ".$id_borrar_modulo; + $result=mysql_query($sql_delete); + if (! $result) + echo "

".$lang_label["delete_group_no"]."

"; + else + echo "

".$lang_label["delete_group_ok"]."

"; +} +echo "

".$lang_label["group_management"]." > "; +echo $lang_label["definedgroups"]."

"; + +echo ""; +echo ""; +echo ""; +echo ""; +echo ""; +echo ""; +$sql1='SELECT * FROM tgrupo ORDER BY nombre'; +$result=mysql_query($sql1); +$color=0; +while ($row=mysql_fetch_array($result)){ + if ($color == 1){ + $tdcolor = "datos"; + $color = 0; + } + else { + $tdcolor = "datos2"; + $color = 1; + } + if ($row["id_grupo"] != 1){ + echo ""; + echo ""; + echo ""; + + // Disabled? + echo ""; + + echo ""; + } +} +echo "
".$lang_label["icon"]."".$lang_label["group_name"]."".$lang_label["parent"]."".$lang_label["alerts"]."".$lang_label["delete"]."
"; + echo ""; + echo ""; + echo "".$row["nombre"].""; + echo ""; + echo dame_nombre_grupo ($row["parent"]); + echo ""; + if ($row["disabled"]==1) + echo " ".$lang_label["disabled"]; + else + echo " ".$lang_label["enabled"]; + echo ""; + echo "'; + echo "
"; +echo ""; +echo "
"; +echo "
"; +echo ""; +echo "
"; ?> diff --git a/pandora_console/godmode/reporting/graph_builder.php b/pandora_console/godmode/reporting/graph_builder.php index 9bcc99b5b5..c97057ca40 100644 --- a/pandora_console/godmode/reporting/graph_builder.php +++ b/pandora_console/godmode/reporting/graph_builder.php @@ -28,6 +28,8 @@ $factor = 1; $render=1; // by default $stacked = 0; +$add_module = (bool) get_parameter ('add_module'); + // Login check $id_usuario=$_SESSION["id_usuario"]; global $REMOTE_ADDR; @@ -141,7 +143,7 @@ if (isset($_GET["delete_module"] )) { } } -if ( (isset($_GET["add_module"]))){ +if ($add_module) { $id_agent = $_POST["id_agent"]; $id_module = $_POST["id_module"]; if (isset($_POST["factor"])) @@ -262,14 +264,14 @@ if (($render == 1) && (isset($modules))) { // SOURCE AGENT TABLE/FORM // ----------------------- -if ( (!isset($_GET["add_module"]))){ +if ($add_module) { echo $lang_label["graph_builder"].""; } else { echo "

".$lang_label["graph_builder"]."

"; } echo ""; -echo ""; - +echo ""; +print_input_hidden ('add_module', 1); if (isset($period)) echo ""; @@ -278,26 +280,15 @@ echo ""; echo ""; // Show combo with agents -echo "'."\n"; + $output .= ''."\n"; } $output .= ''."\n"; } diff --git a/pandora_console/include/functions_reporting.php b/pandora_console/include/functions_reporting.php index 4aaf67465e..60988ab636 100644 --- a/pandora_console/include/functions_reporting.php +++ b/pandora_console/include/functions_reporting.php @@ -16,38 +16,42 @@ // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -function return_module_SLA ($id_agent_module, $period, $min_value, $max_value){ +function return_module_SLA ($id_agent_module, $period, $min_value, $max_value, $date = 0) { require("config.php"); - $datelimit = time() - $period; // limit date - $id_agent = give_db_value ("id_agente", "tagente_modulo", "id_agente_modulo", $id_agent_module); + if (! $date) + $date = time (); + $datelimit = $date - $period; // limit date + $id_agent = give_db_value ('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_agent_module); // Get the whole interval of data - $query1="SELECT * FROM tagente_datos WHERE id_agente = $id_agent AND id_agente_modulo = $id_agent_module AND utimestamp > $datelimit"; - $resq1=mysql_query($query1); + $sql = sprintf ('SELECT * FROM tagente_datos + WHERE id_agente = %d AND id_agente_modulo = %d + AND utimestamp > %d AND utimestamp <= %d', + $id_agent, $id_agent_module, $datelimit, $date); + $result = mysql_query ($sql); $last_data = ""; - $total_badtime = 0; $interval_begin = 0; $interval_last = 0; - - if ($resq1 != 0){ - while ($row=mysql_fetch_array($resq1)){ - if ( ($row["datos"] > $max_value) OR ($row["datos"] < $min_value)){ - if ($interval_begin == 0){ - $interval_begin = $row["utimestamp"]; - } - } elseif ($interval_begin != 0){ - // Here ends interval with data outside valid values, - // Need to add this time to counter - $interval_last = $row["utimestamp"]; - $temp_time = $interval_last - $interval_begin; - $total_badtime = $total_badtime + $temp_time; - $interval_begin = 0; - $interval_last = 0; - } - } - } else + + if (! $result) { return 100; - $result = 100 - ($total_badtime / $period ) * 100; + } + while ($row = mysql_fetch_array ($result)) { + if ( ($row["datos"] > $max_value) || ($row["datos"] < $min_value)) { + if ($interval_begin == 0) { + $interval_begin = $row["utimestamp"]; + } + } elseif ($interval_begin != 0){ + // Here ends interval with data outside valid values, + // Need to add this time to counter + $interval_last = $row["utimestamp"]; + $temp_time = $interval_last - $interval_begin; + $total_badtime = $total_badtime + $temp_time; + $interval_begin = 0; + $interval_last = 0; + } + } + $result = 100 - ($total_badtime / $period) * 100; return $result; } @@ -165,20 +169,23 @@ function general_stats ( $id_user, $id_group = 0) { return $data; } -function event_reporting ($id_agent, $period){ +function event_reporting ($id_agent, $period, $date = 0, $return = false) { require("config.php"); require ("include/languages/language_".$config["language"].".php"); - $id_user=$_SESSION["id_usuario"]; + + $output = ''; + $id_user = $_SESSION["id_usuario"]; global $REMOTE_ADDR; - $ahora = date("U"); - $mytimestamp = $ahora - $period; + if (! $date) + $date = time (); + $mytimestamp = $date - $period; - echo "
".$lang_label["source_agent"]."'; +echo ""; + +print_select_from_sql ('SELECT id_agente, nombre FROM tagente ORDER BY nombre', 'id_agent', $id_agent, '', '--', 0); if (isset($chunkdata)) echo ""; -echo ""; -echo ""; - // ----------------------- // SOURCE MODULE FORM // ----------------------- -echo "
"; if (isset($chunkdata)) echo ""; @@ -307,7 +298,7 @@ if (isset($id_agent)) echo "
"; echo "".$lang_label["modules"].""; echo ""; -echo ""; echo ""; if ($id_agent != 0){ // Populate Module/Agent combo @@ -506,3 +497,43 @@ if (isset($module_array)){ } ?> + + + + + diff --git a/pandora_console/godmode/reporting/reporting_builder.php b/pandora_console/godmode/reporting/reporting_builder.php index 1f5b8137d6..cb4092ba21 100644 --- a/pandora_console/godmode/reporting/reporting_builder.php +++ b/pandora_console/godmode/reporting/reporting_builder.php @@ -1,4 +1,4 @@ -".$lang_label["delete_ok"].""; +if ($delete_report_content) { + $id_report_content = (int) get_parameter ('id_report_content'); + $sql = sprintf ('DELETE FROM treport_content WHERE id_rc = %d', $id_report_content); + $result = mysql_query ($sql); + if ($result) + echo "

".lang_string ('delete_ok')."

"; else - $result = "

".$lang_label["delete_no"]."

"; - echo $result; + echo "

".lang_string ('delete_no')."

"; } -// Delete module SQL code -if (isset($_GET["delete_report"])){ - $id = $_GET["delete_report"]; - $sql = "DELETE FROM treport_content WHERE id_report = $id"; - $sql2 = "DELETE FROM treport WHERE id_report = $id"; - $res=mysql_query($sql); - $res2=mysql_query($sql2); +// Move content up +if ($content_up) { + $id_report_content = (int) get_parameter ('id_report_content'); + $order = get_db_value ('`order`', 'treport_content', 'id_rc', $id_report_content); + /* Set the previous element order to the current of the content we want to change */ + $sql = sprintf ('UPDATE treport_content SET `order` = `order` + 1 WHERE id_report = %d AND `order` = %d', + $id_report, $order - 1); + $result = mysql_query ($sql); + $sql = sprintf ('UPDATE treport_content SET `order` = `order` - 1 WHERE id_rc = %d', $id_report_content); + $result = mysql_query ($sql); +} + +// Move content down +if ($content_down) { + $id_report_content = (int) get_parameter ('id_report_content'); + $order = get_db_value ('`order`', 'treport_content', 'id_rc', $id_report_content); + /* Set the previous element order to the current of the content we want to change */ + $sql = sprintf ('UPDATE treport_content SET `order` = `order` - 1 WHERE id_report = %d AND `order` = %d', + $id_report, $order + 1); + $result = mysql_query ($sql); + $sql = sprintf ('UPDATE treport_content SET `order` = `order` + 1 WHERE id_rc = %d', $id_report_content); + $result = mysql_query ($sql); +} + +// Delete report SQL code +if ($delete_report) { + $sql = sprintf ('DELETE FROM treport_content WHERE id_report = %d', $id_report); + $sql2 = sprintf ('DELETE FROM treport WHERE id_report = %d', $id_report); + $res = mysql_query ($sql); + $res2 = mysql_query ($sql2); if ($res AND $res2) - $result = "

".$lang_label["delete_reporting_ok"]."

"; + echo "

".lang_string ('delete_reporting_ok')."

"; else - $result = "

".$lang_label["delete_reporting_no"]."

"; - echo $result; -} - -// Create new report. First step -if (isset($_GET["create_report"])){ - $createmode = 2; + echo "

".lang_string ('delete_reporting_no')."

"; + $id_report = 0; } // Add module SQL code -if (isset($_GET["add_module"])){ - if (isset($_POST["id_report"])) - $id_report = $_POST["id_report"]; - else { +if ($add_content) { + if (! $id_report) { audit_db($id_user,$REMOTE_ADDR, "Hack attempt","Parameter trash in report builder"); include ("general/noaccess.php"); - exit; + exit (); } - $my_id_agent = entrada_limpia($_POST["id_agent"]); - $my_id_module = entrada_limpia($_POST["id_module"]); - $my_period = entrada_limpia($_POST["period"]); - $my_type = entrada_limpia($_POST["type"]); - - // event reporting (use agent not module) - if ($my_type == 3){ - $my_id_module = $my_id_agent; - } - - $my_cg = entrada_limpia($_POST["id_custom_graph"]); - $my_slamax = entrada_limpia($_POST["sla_max"]); - $my_slamin = entrada_limpia($_POST["sla_min"]); - $my_slalimit = entrada_limpia($_POST["sla_limit"]); + $id_agent = (int) get_parameter ('id_agent'); + $id_agent_module = (int) get_parameter ('id_module'); + $period = (int) get_parameter ('period'); + $type = (string) get_parameter ('type'); + $id_custom_graph = (int) get_parameter ('id_custom_graph'); - $sql = "INSERT INTO treport_content (id_report, id_gs, id_agent_module, type, sla_max, sla_min, sla_limit, period) VALUES ('$id_report', '$my_cg', '$my_id_module', '$my_type', '$my_slamax', '$my_slamin', '$my_slalimit', '$my_period')"; - if ($res=mysql_query($sql)) - $result = "

".$lang_label["create_reporting_ok"]."

"; - else - $result = "

".$lang_label["create_reporting_no"]."

"; - echo $result; -} + $order = (int) get_db_value ('COUNT(*)', 'treport_content', 'id_report', $id_report); -// Create item SQL code -if (isset($_POST["createmode"])){ - $createmode = $_POST["createmode"]; - $form_report_name = entrada_limpia($_POST["report_name"]); - $form_report_description = entrada_limpia($_POST["report_description"]); - if (isset($_POST["report_private"])) - $form_report_private = entrada_limpia($_POST["report_private"]); - else - $form_report_private = 0; - - // INSERT REPORT DATA - if ($createmode == 1){ - $form_id_user = $id_user; - $sql = "INSERT INTO treport (name, description, id_user, private) VALUES ('$form_report_name', '$form_report_description', '$form_id_user', '$form_report_private')"; - if ($res=mysql_query($sql)) - $result = "

".$lang_label["create_reporting_ok"]."

"; - else - $result = "

".$lang_label["create_reporting_no"]."

"; - $id_report = mysql_insert_id(); - // UPDATE REPORT DATA + $sql = sprintf ('INSERT INTO treport_content (id_report, id_gs, id_agent_module, + `order`, id_agent, type, period) + VALUES (%d, %s, %s, %d, %s, "%s", %d)', + $id_report, $id_custom_graph ? $id_custom_graph : "NULL", + $id_agent_module ? $id_agent_module : "NULL", + $order, $id_agent ? $id_agent : "NULL", + $type, $period * 3600); + if ($result = mysql_query($sql)) { + echo "

".lang_string ('create_reporting_ok')."

"; + $id_agent = 0; + $id_agent_module = 0; + $report_id_group = 0; + $period = 0; + $type = 0; + $id_custom_graph = 0; + $sla_max = 0; + $sla_min = 0; + $sla_limit = 0; } else { - $form_id_report = entrada_limpia($_POST["id_report"]); - $id_report = $form_id_report; - $sql = "UPDATE treport SET name = '$form_report_name', description = '$form_report_description', private = '$form_report_private' WHERE id_report = $form_id_report"; - if ($res=mysql_query($sql)) - $result = "

".$lang_label["modify_ok"]."

"; - else - $result = "

".$lang_label["modify_no"]."

"; - } - echo $result; - if ($id_report != ""){ - $_GET["id"]=$id_report; - $createmode=0; + echo "

".lang_string ('create_reporting_no')."

"; + /* Do not unset so the values are kept in the form */ } } -// GET DATA OF REPORT -// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -if ($createmode==2 OR isset($_GET["id"]) OR (isset($_POST["id_report"]))) { - if (isset($_GET["id"])) - $id_report = $_GET["id"]; - elseif (isset($_POST["id_report"])) - $id_report = $_POST["id_report"]; +// Create report +if ($create_report) { + $form_id_user = $id_user; + $sql = sprintf ('INSERT INTO treport (name, description, id_user, private, id_group) + VALUES ("%s", "%s", %d, %d, %d)', + $report_name, $report_description, $form_id_user, $report_private, $report_id_group); + $result = mysql_query ($sql); + if ($result) + echo "

".lang_string ('create_reporting_ok')."

"; else - $id_report = -1; + echo "

".lang_string ('create_reporting_no')."

"; + $id_report = mysql_insert_id (); +} + +// Update report +if ($update_report) { + $sql = sprintf ('UPDATE treport SET name = "%s", + description = "%s", private = %d, id_group = %d + WHERE id_report = %d', + $report_name, $report_description, + $report_private, $report_id_group, $id_report); + $result = mysql_query ($sql); + if ($result) + echo "

".lang_string ('modify_ok')."

"; + else + echo "

".lang_string ('modify_no')."

"; +} + +if ($id_report) { + $report = get_db_row ('treport', 'id_report', (int) $id_report); + $report_name = $report["name"]; + $report_description = $report["description"]; + $report_private = $report["private"]; + $report_id_user = $report["id_user"]; + $report_id_group = $report['id_group']; +} + +if ($edit_sla_report_content) { + /* Edit SLA report form */ + $add_sla = (bool) get_parameter ('add_sla'); + $delete_sla = (bool) get_parameter ('delete_sla'); + $id_report_content = (int) get_parameter ('id_report_content'); + $id_module = (int) get_parameter ('id_module'); + + $sla_max = ''; + $sla_min = ''; + $sla_limit = ''; + if ($add_sla) { + $sla_max = (int) get_parameter ('sla_max'); + $sla_min = (int) get_parameter ('sla_min'); + $sla_limit = (int) get_parameter ('sla_limit'); + $sql = sprintf ('INSERT INTO treport_content_sla_combined (id_report_content, + id_agent_module, sla_max, sla_min, sla_limit) VALUES (%d, %d, %d, %d, %d)', + $id_report_content, $id_module, $sla_max, $sla_min, $sla_limit); + + if ($id_module) { + $result = mysql_query ($sql); + if ($result) + echo "

".lang_string ('add_sla_ok')."

"; + else + echo "

".lang_string ('add_sla_no')."

"; + } else { + echo "

".lang_string ('sla_module_is_null')."

"; + } + } + if ($delete_sla) { + $id_sla = (int) get_parameter ('id_sla'); + $sql = sprintf ('DELETE FROM treport_content_sla_combined WHERE id = %d', $id_sla); + echo $sql; + $result = mysql_query ($sql); + if ($result) + echo "

".lang_string ('delete_sla_ok')."

"; + else + echo "

".lang_string ('delete_sla_no')."

"; + } + $report_content = get_db_row ('treport_content', 'id_rc', $id_report_content); + + /* Show all SLAs defined in the report content */ + echo '

'.lang_string ('reporting')." > "; + echo lang_string ('custom_reporting_builder')." > "; + echo ''.$report['name'].'

'; + echo '

'.lang_string ('defined_slas')."

"; + + $table->id = 'table-sla-list'; + $table->width = '500px'; + $table->align = array (); + $table->align[5] = 'center'; + $table->data = array (); + $table->head = array (); + $table->head[0] = lang_string ('agent'); + $table->head[1] = lang_string ('module'); + $table->head[2] = lang_string ('sla_min'); + $table->head[3] = lang_string ('sla_max'); + $table->head[4] = lang_string ('sla_limit'); + $table->head[5] = lang_string ('delete'); + + $slas = get_db_all_rows_field_filter ('treport_content_sla_combined', 'id_report_content', $id_report_content); + foreach ($slas as $sla) { + $data = array (); + + $data[0] = dame_nombre_agente_agentemodulo ($sla['id_agent_module']); + $data[1] = dame_nombre_modulo_agentemodulo ($sla['id_agent_module']); + $data[2] = $sla['sla_min']; + $data[3] = $sla['sla_max']; + $data[4] = $sla['sla_limit'].'%'; + $data[5] = ''; + + array_push ($table->data, $data); + } + + if (sizeof ($slas)) { + print_table ($table); + } + + echo "

".lang_string ('sla_construction')."

"; + $table->id = 'table-add-sla'; + $table->width = '500px'; + $table->data = array (); + $table->style = array (); + $table->size = array (); + $table->size[0] = '150px'; + $table->head = array (); + $table->style[0] = 'font-weight: bold'; + $sql = sprintf ('SELECT id_agente, nombre FROM tagente WHERE id_grupo = %d ORDER BY nombre', $report_id_group); + $table->data[0][0] = lang_string ('agent'); + $table->data[0][1] = print_select_from_sql ($sql, 'id_agent', 0, '', '--', 0, true); + $table->data[1][0] = lang_string ('module'); + $table->data[1][1] = print_select (array (), 'id_module', 0, '', '--', 0, true); + $table->data[2][0] = lang_string ('sla_min'); + $table->data[2][1] = print_input_text ('sla_min', $sla_min, '', 5, 10, true); + $table->data[3][0] = lang_string ('sla_max'); + $table->data[3][1] = print_input_text ('sla_max', $sla_max, '', 5, 10, true); + $table->data[4][0] = lang_string ('sla_limit'); + $table->data[4][1] = print_input_text ('sla_limit', $sla_limit, '', 5, 10, true); + + echo ''; + print_table ($table); + print_input_hidden ('add_sla', 1); + print_input_hidden ('edit_sla_report_content', 1); + print_input_hidden ('id_report_content', $id_report_content); + echo '
'; + print_submit_button (lang_string ('create'), 'add', false, 'class="sub wand"'); + echo '
'; + echo ''; + +} else if ($edit_report || $id_report) { + /* Edit and creation report form */ if (isset($_POST["id_agent"])) $id_agent = $_POST["id_agent"]; else $id_agent = 0; - if ($createmode != 2){ - $createmode = 0; - $sql = "SELECT * FROM treport WHERE id_report = $id_report"; - $res=mysql_query($sql); - if ($row = mysql_fetch_array($res)){ - $form_report_name = $row["name"]; - $form_report_description = $row["description"]; - $form_report_private = $row["private"]; - $form_id_user = $row["id_user"]; - } - } else { - $form_report_name = ""; - $form_report_description = ""; - $form_report_private = 0; - $form_id_user = $id_user; - $createmode = 1; - } - echo "

".$lang_label["reporting"]." > "; - echo $lang_label["custom_reporting_builder"]."

"; - echo "
"; - echo ""; - if ($createmode == 0){ - echo ""; - } - echo ""; - - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo "
"; - echo $lang_label["report_name"].""; - echo ""; - - echo "
"; - echo $lang_label["private"].""; - if ($form_report_private == 1) - echo ""; - else - echo ""; - echo "
"; - echo $lang_label["description"].""; - echo ""; - echo "
"; + echo "

".lang_string ('reporting')." > "; + echo lang_string ('custom_reporting_builder')."

"; + $table->id = 'table-edit-report'; + $table->width = '500px'; + $table->data = array (); + $table->style = array (); + $table->style[0] = 'font-weight: bold'; + $table->data[0][0] = lang_string ('report_name'); + $table->data[0][1] = print_input_text ('report_name', $report_name, '', 35, 150, true); + $table->data[1][0] = lang_string ('group'); + $table->data[1][1] = print_select_from_sql ('SELECT id_grupo, nombre FROM tgrupo ORDER BY nombre', + 'report_id_group', $report_id_group, '', '--', 0, true); + $table->data[1][1] .= ''; + if ($report_id_group) { + $table->data[1][1] .= ''; + } + $table->data[1][1] .= ''; + $table->data[2][0] = lang_string ('private'); + $table->data[2][1] = print_checkbox ('report_private', 1, $report_private, true); + $table->data[3][0] = lang_string ('description'); + $table->data[3][1] = print_textarea ('report_description', 3, 40, $report_description, '', true); + + echo ""; + print_table ($table); // Button - echo ""; - echo ""; - echo "
"; - if ($createmode == 0) - echo ""; - else - echo ""; - echo "
"; + echo '
'; + print_input_hidden ('edit_report', 1); + if ($id_report) { + print_input_hidden ('id_report', $id_report); + print_input_hidden ('update_report', 1); + print_submit_button (lang_string ('update'), 'submit', false, 'class="sub next"'); + } else { + print_input_hidden ('create_report', 1); + print_submit_button (lang_string ('create'), 'submit', false, 'class="sub wand"'); + } + echo "
"; echo "
"; - - if ($createmode == 0){ + + if ($id_report) { // Part 2 - Add new items to report - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - echo "

".$lang_label["reporting_item_add"]."

"; - - // Show combo with agents - // ---------------------- + echo "

".lang_string ('reporting_item_add')."

"; - echo ""; - echo ""; - echo ""; + /* We're reusing some $table attributes */ + $table->id = 'table-add-item'; + $table->rowstyle = array (); + $table->rowstyle[2] = 'display: none'; + $table->rowstyle[3] = 'display: none'; + $table->rowstyle[4] = 'display: none'; + $table->size = array (); + $table->size[0] = '200px'; + $table->data = array (); + + $table->data[0][0] = lang_string ('reporting_type'); + $types = get_report_types (); + asort ($types); + $table->data[0][1] = print_select ($types, 'type', -1, '', '--', -1, true); + $table->data[1][0] = lang_string ('period'); + $periods = array (); + $periods[1] = lang_string ('hour'); + $periods[2] = '2 '.lang_string ('hours'); + $periods[3] = '3 '.lang_string ('hours'); + $periods[6] = '6 '.lang_string ('hours'); + $periods[12] = '12 '.lang_string ('hours'); + $periods[24] = lang_string ('last_day'); + $periods[48] = lang_string ('two_days'); + $periods[360] = lang_string ('last_week'); + $periods[720] = lang_string ('last_month'); + $periods[4320] = lang_string ('six_months'); + $table->data[1][1] = print_select ($periods, 'period', 0, '', '--', 0, true); + + $table->data[2][0] = lang_string ('source_agent'); + $sql = sprintf ('SELECT id_agente, nombre FROM tagente WHERE id_grupo = %d ORDER BY nombre', $report_id_group); + $table->data[2][1] = print_select_from_sql ($sql, 'id_agent', $id_agent, '', '--', 0, true); - echo ""; - echo ""; - echo "'; - - echo ""; - - // Modules combo - // ----------------------- - echo ""; - echo ""; - if (isset($id_agent)) - echo ""; - - echo ""; - echo ""; - - // Component type - echo ""; - echo ""; - - // Custom graph - // ----------------------- - echo ""; - echo ""; - echo ""; - - // SLA Max - echo ""; - echo ""; - // SLA Min - echo ""; - echo ""; + $table->data[3][1] = print_select ($modules, 'id_module', 0, '', '--', 0, true); - // SLA limit - echo ""; - echo ""; - echo "
".$lang_label["source_agent"]." - "; - echo "
"; - echo "".$lang_label["modules"].""; - echo ""; - echo "
"; - echo "".$lang_label["reporting_type"].""; - echo "
"; - echo "".$lang_name["custom_graph_name"].""; - echo ""; - - // Period - echo "
"; - echo "".$lang_label["period"].""; - echo "
"; - echo "".$lang_label["sla_max"].""; - echo ""; - echo "".$lang_label["sla_min"].""; - echo "
"; - echo "".$lang_label["sla_limit"].""; - echo "
"; + $table->data[4][0] = lang_string ('custom_graph_name'); + $table->data[4][1] = print_select_from_sql ('SELECT id_graph, name FROM tgraph', + 'id_custom_graph', 0, '', '--', 0, true); - echo ""; - echo ""; - echo "
"; - echo ""; - echo "
"; + echo ""; + print_table ($table); + echo '
'; + print_input_hidden ('add_content', 1); + print_input_hidden ('id_report', $id_report); + print_submit_button (lang_string ('add'), 'add', false, 'class="sub wand"'); + echo "
"; echo ""; - // Part 3 - List of already assigned report items - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - echo "

".$lang_label["report_items"]."

"; - echo ""; - echo " - - - - - "; - $sql = "SELECT * FROM treport_content WHERE id_report = $id_report"; - $res=mysql_query($sql); - $color = 0; - while ($row = mysql_fetch_array($res)){ - // Calculate table line color - if ($color == 1){ - $tdcolor = "datos"; - $color = 0; - } - else { - $tdcolor = "datos2"; - $color = 1; - } - $id_rc = $row["id_rc"]; - $type = $row["type"]; - switch ($type){ - case "0": $type_desc = "Graph"; break; - case "1": $type_desc = "User graph"; break; - case "2": $type_desc = "SLA"; break; - case "3": $type_desc = "Event report"; break; - case "4": $type_desc = "Alert report"; break; - case "5": $type_desc = "Monitor report"; break; - case "6": $type_desc = "Avg.Value"; break; - case "7": $type_desc = "Max.Value"; break; - case "8": $type_desc = "Min.Value"; break; - } - $period = $row["period"]; - $id_am = $row["id_agent_module"]; - $name = "N/A"; - $agent_name = "N/A"; - if ($id_am != ""){ - $agent_name = dame_nombre_agente_agentemodulo ($id_am); - $module_name = dame_nombre_modulo_agentemodulo ($id_am); - } - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; + echo "

".lang_string ('report_items')."

"; + $table->id = 'table-assigned-reports'; + $table->data = array (); + $table->head = array (); + $table->size = array (); + $table->rowstyle = array (); + $table->head[0] = lang_string ('order'); + $table->head[1] = lang_string ('type'); + $table->head[2] = lang_string ('period'); + $table->head[3] = lang_string ('Options'); + $table->align = array (); + $table->align[0] = 'center'; + $table->align[3] = 'center'; + if ($report_id_user == $config['id_user']) { + $table->align[4] = 'center'; + $table->head[4] = lang_string ('delete'); } - echo "
".$lang_label["type"]."".$lang_label["agent_name"]."".$lang_label["module_name"]."".$lang_label["period"]."".$lang_label["delete"]."
".$type_desc."".$agent_name."".$module_name."".$period.""; - if ($form_id_user == $id_user){ - echo ""; - } - echo "
"; + + + $sql = sprintf ('SELECT * FROM treport_content WHERE id_report = %d ORDER BY `order`', $id_report); + $report_contents = get_db_all_rows_sqlfree ($sql); + if (sizeof ($report_contents)) { + $first_id = $report_contents[0]['id_rc']; + $last_id = $report_contents[sizeof ($report_contents) - 1]['id_rc']; + } + foreach ($report_contents as $report_content) { + $data = array (); + $data[0] = ''; + if ($first_id != $report_content['id_rc']) { + $data[0] .= ''; + } + if ($last_id != $report_content['id_rc']) { + $data[0] .= ''; + } + $data[1] = get_report_name ($report_content['type']); + $data[2] = human_time_description ($report_content['period']); + $data[3] = ''; + if ($report_content['type'] == 'SLA') { + $data[3] = ''; + } + if ($report_id_user == $config['id_user']) { + $data[4] = ''; + } + + array_push ($table->data, $data); + } + print_table ($table); } } else { - // Report item editor / add - // Report LIST - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - echo "

".$lang_label["reporting"]." > "; - echo $lang_label["custom_reporting"]."

"; + echo "

".lang_string ('reporting')." > "; + echo lang_string ('custom_reporting')."

"; - $sql="SELECT * FROM treport"; - $res=mysql_query($sql); - if (mysql_num_rows($res)) { - echo ""; - echo " - - - - "; - $color=1; - while ($row = mysql_fetch_array($res)){ - if (($row["private"]==0) || ($row["id_user"] == $id_user)){ - // Calculate table line color - if ($color == 1){ - $tdcolor = "datos"; - $color = 0; - } - else { - $tdcolor = "datos2"; - $color = 1; - } - echo ""; - echo ""; - echo ""; + $reports = get_db_all_rows_in_table ('treport'); + $sql = "SELECT * FROM treport"; + $res = mysql_query($sql); + $table->width = '0px'; + if (sizeof ($reports)) { + + $table->id = 'report_list'; + $table->width = '600px'; + $table->head = array (); + $table->align = array (); + $table->align[2] = 'center'; + $table->data = array (); + $table->head[0] = lang_string ('report_name'); + $table->head[1] = lang_string ('description'); + $table->head[2] = lang_string ('delete'); + + foreach ($reports as $report) { + if ($report["private"] || $report["id_user"] != $id_user) + continue; + $data = array (); + $data[0] = ''.$report['name'].''; + $data[1] = $report['description']; + $data[2] = ''; + + array_push ($table->data, $data); + } + print_table ($table); + } else { + echo "
".lang_string ('no_reporting_def')."
"; } - echo "
".$lang_label["report_name"]."".$lang_label["description"]."".$lang_label["Manage"]."".$lang_label["delete"]."
".$row["name"]; - echo "".$row["description"]; - $id_report = $row["id_report"]; - echo " - - - -
"; - echo ""; -} else { - echo "
".$lang_label["no_reporting_def"]."
"; - echo "
"; -} - echo ""; - echo "
"; - echo ""; + + echo ''; + echo '
'; + print_input_hidden ('edit_report', 1); + print_submit_button (lang_string ('add'), 'create', false, 'class="sub next"'); + echo "
"; echo ""; - echo "
"; } ?> + + + + + diff --git a/pandora_console/include/functions.php b/pandora_console/include/functions.php index 66c2c252a0..085f5de1a9 100644 --- a/pandora_console/include/functions.php +++ b/pandora_console/include/functions.php @@ -771,11 +771,11 @@ function show_alert_row_edit ($row2, $tdcolor = "datos", $id_tipo_modulo = 1, $c return $string; } -function show_alert_show_view ($data, $tdcolor = "datos", $combined = 0){ +function show_alert_show_view ($data, $tdcolor = "datos", $combined = 0) { global $config; global $lang_label; - if ($combined == 0){ + if ($combined == 0) { $module_name = get_db_sql ("SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = ".$data["id_agente_modulo"]); $agent_name = get_db_sql ("SELECT tagente.nombre FROM tagente_modulo, tagente WHERE tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.id_agente_modulo = ".$data["id_agente_modulo"]); $id_agente = get_db_sql ("SELECT id_agente FROM tagente_modulo WHERE id_agente_modulo = ".$data["id_agente_modulo"]); @@ -912,6 +912,8 @@ function get_report_types () { $types['min_value'] = lang_string ('min_value'); $types['sumatory'] = lang_string ('sumatory'); $types['general_group_report'] = lang_string ('general_group_report'); + $types['monitor_health'] = lang_string ('monitor_health'); + $types['agents_detailed'] = lang_string ('agents_detailed'); return $types; } @@ -963,6 +965,10 @@ function get_report_type_data_source ($type) { case 'monitor_report': case 11: case 'general_group_report': + case 12: + case 'monitor_health': + case 13: + case 'agents_detailed': return 'agent-group'; } return 'unknown'; @@ -973,7 +979,7 @@ function get_report_type_data_source ($type) { * * @param $module_name Module name to check. * - * @return true if the module is of type "date" + * @return true if the module is of type "data" */ function is_module_data ($module_name) { $result = ereg ("^(.*_data)$", $module_name); diff --git a/pandora_console/include/functions_db.php b/pandora_console/include/functions_db.php index 80057efa16..03775a2b3e 100644 --- a/pandora_console/include/functions_db.php +++ b/pandora_console/include/functions_db.php @@ -148,7 +148,67 @@ function give_disabled_group ($id_group) { return (bool) get_db_value ('disabled', 'tgrupo', 'id_grupo', (int) $id_group); } +/** + * Get all the agents in a group. + * + * @param $id_group Group id to get all agents. + * + * @return An array with all agents in the group. + */ +function get_agents_in_group ($id_group) { + return get_db_all_rows_field_filter ('tagente', 'id_grupo', (int) $id_group); +} +/** + * Get all the modules in an agent. + * + * @param $id_agent Agent id to get all modules. + * + * @return An array with all modules in the agent. + */ +function get_modules_in_agent ($id_agent) { + return get_db_all_rows_field_filter ('tagente_modulo', 'id_agente', (int) $id_agent); +} + +/** + * Get all the simple alerts of an agent. + * + * @param $id_agent Agent id to get all simple alerts. + * + * @return An array with all simple alerts defined for an agent. + */ +function get_simple_alerts_in_agent ($id_agent) { + $sql = sprintf ('SELECT talerta_agente_modulo.* + FROM talerta_agente_modulo, tagente_modulo + WHERE talerta_agente_modulo.id_agente_modulo = tagente_modulo.id_agente_modulo + AND tagente_modulo.id_agente = %d', $id_agent); + return get_db_all_rows_sqlfree ($sql); +} + +/** + * Get all the combined alerts of an agent. + * + * @param $id_agent Agent id to get all combined alerts. + * + * @return An array with all combined alerts defined for an agent. + */ +function get_combined_alerts_in_agent ($id_agent) { + return get_db_all_rows_field_filter ('talerta_agente_modulo', 'id_agent', (int) $id_agent); +} + +/** + * Get all the alerts of an agent, simple and combined. + * + * @param $id_agent Agent id to get all alerts. + * + * @return An array with all alerts defined for an agent. + */ +function get_alerts_in_agent ($id_agent) { + $simple_alerts = get_simple_alerts_in_agent ($id_agent); + $combined_alerts = get_combined_alerts_in_agent ($id_agent); + + return array_merge ($simple_alerts, $combined_alerts); +} // --------------------------------------------------------------- // Returns group given ID @@ -201,29 +261,16 @@ function dame_agente_modulo_id ($id_agente, $id_tipomodulo, $nombre) { // Returns event description given it's id // --------------------------------------------------------------- -function return_event_description ($id_event){ - require("config.php"); - $query1="SELECT evento FROM tevento WHERE id_evento = $id_event"; - $resq1=mysql_query($query1); - if ($rowdup=mysql_fetch_array($resq1)) - $pro=$rowdup[0]; - else - $pro = ""; - return $pro; +function return_event_description ($id_event) { + return (string) get_db_value ('evento', 'tevento', 'id_evento', (int) $id_event); } // --------------------------------------------------------------- // Return ID_Group from an event given as id_event // --------------------------------------------------------------- -function gime_idgroup_from_idevent($id_event){ - require("config.php"); - $query1="SELECT * FROM tevento WHERE id_evento = ".$id_event; - $pro = -1; - if ($resq1=mysql_query($query1)) - if ($rowdup=mysql_fetch_array($resq1)) - $pro=$rowdup["id_grupo"]; - return $pro; +function gime_idgroup_from_idevent ($id_event) { + return (int) get_db_value ('id_grupo', 'tevento', 'id_evento', (int) $id_event); } @@ -231,15 +278,8 @@ function gime_idgroup_from_idevent($id_event){ // Return module id given name of module type // --------------------------------------------------------------- -function dame_module_id($nombre){ - require("config.php"); - $query1="SELECT * FROM ttipo_modulo WHERE nombre = '".$nombre."'"; - $resq1=mysql_query($query1); - if ($rowdup=mysql_fetch_array($resq1)) - $pro=$rowdup["id_tipo"]; - else - $pro = ""; - return $pro; +function dame_module_id ($nombre){ + return (int) get_db_value ('id_tipo', 'ttipo_modulo', 'nombre', $nombre); } @@ -247,106 +287,56 @@ function dame_module_id($nombre){ // Returns agent name when given its ID // --------------------------------------------------------------- -function dame_nombre_agente ($id){ - require("config.php"); - $query1="SELECT * FROM tagente WHERE id_agente = ".$id; - $resq1=mysql_query($query1); - if ($rowdup=mysql_fetch_array($resq1)) - $pro=$rowdup["nombre"]; - else - $pro = ""; - return $pro; +function dame_nombre_agente ($id_agente) { + return (string) get_db_value ('nombre', 'tagente', 'id_agente', (int) $id_agente); } // --------------------------------------------------------------- // Returns password (HASH) given user_id // --------------------------------------------------------------- -function dame_password($id_usuario){ - require("config.php"); - $query1="SELECT * FROM tusuario WHERE id_usuario= '".$id_usuario."'"; - $resq1=mysql_query($query1); - if ($rowdup=mysql_fetch_array($resq1)) - $pro=$rowdup["password"]; - else - $pro = ""; - return $pro; +function dame_password ($id_usuario) { + return (string) get_db_value ('password', 'tusuario', 'id_usuario', (int) $id_usuario); } - // --------------------------------------------------------------- // Returns name of an alert given ID // --------------------------------------------------------------- -function dame_nombre_alerta($id){ - require("config.php"); - $query1="SELECT * FROM talerta WHERE id_alerta = ".$id; - $resq1=mysql_query($query1); - if ($rowdup=mysql_fetch_array($resq1)) - $pro=$rowdup["nombre"]; - else - $pro = ""; - return $pro; +function dame_nombre_alerta ($id_alert) { + return (string) get_db_value ('nombre', 'talerta', 'id_alerta', (int) $id_alert); } // --------------------------------------------------------------- // Returns name of a modules group // --------------------------------------------------------------- -function dame_nombre_grupomodulo($id){ - require("config.php"); - $query1="SELECT * FROM tmodule_group WHERE id_mg = ".$id; - $resq1=mysql_query($query1); - if ($rowdup=mysql_fetch_array($resq1)) - $pro=$rowdup["name"]; - else - $pro = ""; - return $pro; +function dame_nombre_grupomodulo ($id_module_group) { + return (string) get_db_value ('name', 'tmodule_group', 'id_mg', (int) $id_module_group); } // --------------------------------------------------------------- // Returns name of a export server // --------------------------------------------------------------- -function dame_nombre_servidorexportacion($id){ - require("config.php"); - $query1="SELECT id, name FROM tserver_export WHERE id = ".$id; - $resq1=mysql_query($query1); - if ($rowdup=mysql_fetch_array($resq1)) - $pro=$rowdup["name"]; - else - $pro = ""; - return $pro; +function dame_nombre_servidorexportacion ($id_server) { + return (string) get_db_value ('name', 'tserver_export', 'id', (int) $id_server); } // --------------------------------------------------------------- // Returns name of a plugin module // --------------------------------------------------------------- -function dame_nombre_pluginid($id){ - require("config.php"); - $query1="SELECT id, name FROM tplugin WHERE id = ".$id; - $resq1=mysql_query($query1); - if ($rowdup=mysql_fetch_array($resq1)) - $pro=$rowdup["name"]; - else - $pro = ""; - return $pro; +function dame_nombre_pluginid ($id_plugin) { + return (string) get_db_value ('name', 'tplugin', 'id', (int) $id_plugin); } // --------------------------------------------------------------- // Returns id of a moduletype // --------------------------------------------------------------- -function giveme_module_type($id){ - require("config.php"); - $query1="SELECT id_tipo, nombre FROM ttipo_modulo WHERE id_tipo = ".$id; - $resq1=mysql_query($query1); - if ($rowdup=mysql_fetch_array($resq1)) - $pro=$rowdup["nombre"]; - else - $pro = ""; - return $pro; +function giveme_module_type ($id_type) { + return (string) get_db_value ('nombre', 'ttipo_modulo', 'id_tipo', (int) $id_type); } // --------------------------------------------------------------- @@ -364,7 +354,7 @@ function dame_nombre_agente_agentemodulo ($id_agente_modulo) { // Return agent module name, given a ID of agente_module table // --------------------------------------------------------------- function dame_nombre_modulo_agentemodulo ($id_agente_modulo) { - return get_db_value ('nombre', 'tagente_modulo', 'id_agente_modulo', $id_agente_modulo); + return (string) get_db_value ('nombre', 'tagente_modulo', 'id_agente_modulo', (int) $id_agente_modulo); } @@ -372,46 +362,112 @@ function dame_nombre_modulo_agentemodulo ($id_agente_modulo) { // Return agent module, given a ID of agente_module table // --------------------------------------------------------------- -function dame_id_tipo_modulo_agentemodulo($id_agente_modulo){ - require("config.php"); - $query1="SELECT * FROM tagente_modulo WHERE id_agente_modulo = ".$id_agente_modulo; - $resq1=mysql_query($query1); - if ($rowdup=mysql_fetch_array($resq1)) - $pro = $rowdup["id_tipo_modulo"]; - else - $pro = ""; - return $pro; +function dame_id_tipo_modulo_agentemodulo ($id_agente_modulo) { + return (int) get_db_value ('id_tipo_modulo', 'tagente_modulo', 'id_agente_modulo', (int) $id_agente_modulo); } // --------------------------------------------------------------- // Returns name of the user when given ID // --------------------------------------------------------------- -function dame_nombre_real($id){ - require("config.php"); - $query1="SELECT * FROM tusuario WHERE id_usuario = '".$id."'"; - $resq1=mysql_query($query1); - if ($rowdup=mysql_fetch_array($resq1)) - $pro=$rowdup["nombre_real"]; - else - $pro = ""; - return $pro; +function dame_nombre_real ($id_user) { + return (string) get_db_value ('nombre_real', 'tusuario', 'id_usuario', (int) $id_user); } +/** + * Get all the times a monitor went down during a period. + * + * @param $id_agent_module Agent module of the monitor. + * @param $period Period timed to check from date + * @param $date Date to check (now by default) + * + * @return The number of times a monitor went down. + */ +function get_monitor_downs_in_period ($id_agent_module, $period, $date = 0) { + if (!$date) + $date = time (); + $datelimit = $date - $period; + $sql = sprintf ('SELECT COUNT(*) FROM tevento WHERE + event_type = "monitor_down" + AND id_agentmodule = %d + AND utimestamp > %d AND utimestamp <= %d', + $id_agent_module, $datelimit, $date); + $down = get_db_sql ($sql); + return $down; +} + +/** + * Get the last time a monitor went down during a period. + * + * @param $id_agent_module Agent module of the monitor. + * @param $period Period timed to check from date + * @param $date Date to check (now by default) + * + * @return The last time a monitor went down. + */ +function get_monitor_last_down_timestamp_in_period ($id_agent_module, $period, $date = 0) { + if (!$date) + $date = time (); + $datelimit = $date - $period; + $sql = sprintf ('SELECT MAX(timestamp) FROM tevento WHERE + event_type = "monitor_down" + AND id_agentmodule = %d + AND utimestamp > %d AND utimestamp <= %d', + $id_agent_module, $datelimit, $date); + $timestamp = get_db_sql ($sql); + return $timestamp; +} + +/** + * Get all the times an alerts fired during a period. + * + * @param $id_agent_module Agent module of the alert. + * @param $period Period timed to check from date + * @param $date Date to check (now by default) + * + * @return The number of times an alert fired. + */ +function get_alert_fires_in_period ($id_agent_module, $period, $date = 0) { + if (!$date) + $date = time (); + $datelimit = $date - $period; + $sql = sprintf ('SELECT COUNT(*) FROM tevento WHERE + event_type = "alert_fired" + AND id_agentmodule = %d + AND utimestamp > %d AND utimestamp <= %d', + $id_agent_module, $datelimit, $date); + $down = get_db_sql ($sql); + return (int) $down; +} + +/** + * Get the last time an alert fired during a period. + * + * @param $id_agent_module Agent module of the monitor. + * @param $period Period timed to check from date + * @param $date Date to check (now by default) + * + * @return The last time an alert fired. + */ +function get_alert_last_fire_timestamp_in_period ($id_agent_module, $period, $date = 0) { + if (!$date) + $date = time (); + $datelimit = $date - $period; + $sql = sprintf ('SELECT MAX(timestamp) FROM tevento WHERE + event_type = "alert_fired" + AND id_agentmodule = %d + AND utimestamp > %d AND utimestamp <= %d', + $id_agent_module, $datelimit, $date); + $timestamp = get_db_sql ($sql); + return $timestamp; +} // --------------------------------------------------------------- // This function returns ID of user who has created incident // --------------------------------------------------------------- -function give_incident_author($id){ - require("include/config.php"); - $query1="SELECT * FROM tincidencia WHERE id_incidencia = '".$id."'"; - $resq1=mysql_query($query1); - if ($rowdup=mysql_fetch_array($resq1)) - $pro=$rowdup["id_usuario"]; - else - $pro = ""; - return $pro; +function give_incident_author ($id_incident) { + return (string) get_db_value ('id_usuario', 'tincidencia', 'id_incidencia', (int) $id_incident); } // --------------------------------------------------------------- @@ -1146,6 +1202,13 @@ function get_db_sql ($sql, $field = 0){ return NULL; } +/** + * Get all the result rows using an SQL statement. + * + * @param $sql SQL statement to execute. + * + * @return A matrix with all the values returned from the SQL statement + */ function get_db_all_rows_sqlfree ($sql) { global $config; $retval = array (); @@ -1161,10 +1224,26 @@ function get_db_all_rows_sqlfree ($sql) { return $retval; } +/** + * Get all the rows in a table of the database. + * + * @param $table Database table name. + * + * @return A matrix with all the values in the table + */ function get_db_all_rows_in_table ($table) { return get_db_all_rows_sqlfree ('SELECT * FROM '.$table); } +/** + * Get all the rows in a table of the databes filtering from a field. + * + * @param $table Database table name. + * @param $field Field of the table. + * @param $condition Condition the field must have to be selected. + * + * @return A matrix with all the values in the table that matches the condition in the field + */ function get_db_all_rows_field_filter ($table, $field, $condition) { if (is_int ($condition)) { $sql = sprintf ('SELECT * FROM %s WHERE %s = %d', $table, $field, $condition); @@ -1177,6 +1256,15 @@ function get_db_all_rows_field_filter ($table, $field, $condition) { return get_db_all_rows_sqlfree ($sql); } +/** + * Get all the rows in a table of the databes filtering from a field. + * + * @param $table Database table name. + * @param $field Field of the table. + * @param $condition Condition the field must have to be selected. + * + * @return A matrix with all the values in the table that matches the condition in the field + */ function get_db_all_fields_in_table ($table, $field) { return get_db_all_rows_sqlfree ('SELECT '.$field.' FROM '. $table); } @@ -1331,7 +1419,7 @@ function return_moduledata_sum_value ($id_agent_module, $period, $date = 0) { $datelimit = $date - $period; // limit date $agent_module = get_db_row ('tagente_modulo', 'id_agente_modulo', $id_agent_module); $module_name = get_db_value ('nombre', 'ttipo_modulo', 'id_tipo', $agent_module['id_tipo_modulo']); - echo $module_name; + if (is_module_data_string ($module_name)) { return lang_string ('wrong_module_type'); } @@ -1361,7 +1449,7 @@ function return_moduledata_sum_value ($id_agent_module, $period, $date = 0) { } else { $times = 1; } - if (is_module_data_proc ($module_name)) { + if (is_module_proc ($module_name)) { $previous_data = $data['datos'] * $interval; } else { $previous_data = $data['datos']; diff --git a/pandora_console/include/functions_html.php b/pandora_console/include/functions_html.php index 4f5ef42f2a..0bcb4890db 100644 --- a/pandora_console/include/functions_html.php +++ b/pandora_console/include/functions_html.php @@ -31,32 +31,32 @@ function print_select ($fields, $name, $selected = '', $script = '', $nothing = 'select', $nothing_value = '0', $return = false) { $output = "\n"; - $attributes = ($script) ? 'onchange="'. $script .'"' : ''; - $output .= '\n"; - if ($nothing != '') { - $output .= ' \n"; - } - } - } + if (!empty ($fields)) { + foreach ($fields as $value => $label) { + $output .= ' \n"; + } + } + } - $output .= "\n"; + $output .= "\n"; if ($return) return $output; @@ -287,12 +287,12 @@ function print_table ($table, $return = false) { } if (isset ($table->rowclass)) { foreach ($table->rowclass as $key => $class) { - $rowclass[$key] = $st; + $rowclass[$key] = $class; } } if (isset ($table->colspan)) { - foreach ($table->colspan as $keyrow => $colspan) { - foreach ($colspan as $key => $span) { + foreach ($table->colspan as $keyrow => $cspan) { + foreach ($cspan as $key => $span) { $colspan[$keyrow][$key] = ' colspan="'.$span.'"'; } } @@ -366,7 +366,7 @@ function print_table ($table, $return = false) { if (!isset ($size[$key])) { $size[$key] = ''; } - if (!isset ($colspan[$key])) { + if (!isset ($colspan[$keyrow][$key])) { $colspan[$keyrow][$key] = ''; } if (!isset ($align[$key])) { @@ -382,7 +382,7 @@ function print_table ($table, $return = false) { $style[$key] = ''; } - $output .= '
'. $item .''. $item .'
"; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; + $output .= "
".$lang_label["status"]."".$lang_label["event_name"]."".$lang_label["id_user"]."".$lang_label["timestamp"]."
"; + $output .= ""; + $output .= ""; + $output .= ""; + $output .= ""; + $output .= ""; $color = 1; $id_evento = 0; @@ -198,65 +205,312 @@ function event_reporting ($id_agent, $period){ $tdcolor = "datos2"; $color = 1; } - echo ""; + $output .= substr($row2["id_usuario"],0,8)." ".dame_nombre_real($row2["id_usuario"]).""; + $output .= ""; } } - echo "
".$lang_label["status"]."".$lang_label["event_name"]."".$lang_label["id_user"]."".$lang_label["timestamp"]."
"; + $output .= "
"; if ($row2["estado"] == 0) - echo ""; + $output .= ""; else - echo ""; - echo "".$row2["evento"]; - echo ""; + $output .= ""; + $output .= "".$row2["evento"]; + $output .= ""; if ($row2["estado"] <> 0) - echo substr($row2["id_usuario"],0,8)." ".dame_nombre_real($row2["id_usuario"]).""; - echo "".$row2["timestamp"]; - echo "
".$row2["timestamp"]; + $output .= "
"; + $output .= ""; + + if (!$return) + echo $output; + return $output; } -function alert_reporting ($id_agent_module){ - global $config; - require ("include/languages/language_".$config["language"].".php"); +/** + * Get a report for alerts in a group of agents. + * + * It prints the numbers of alerts defined, fired and not fired in a group. + * It also prints all the alerts that were fired grouped by agents. + * + * @param $id_group Group to get info of the alerts. + * @param $period Period of time of the desired alert report. + * @param $date Beggining date of the report (current date by default). + * @param $return Flag to return or echo the report (by default). + */ +function alert_reporting ($id_group, $period = 0, $date = 0, $return = false) { + if (! $date) + $date = time (); + $datelimit = $date - $period; + $output = ''; + $alerts = array (); + + $agents = get_agents_in_group ($id_group); + foreach ($agents as $agent) { + $agent_alerts = get_alerts_in_agent ($agent['id_agente']); + $alerts = array_merge ($alerts, $agent_alerts); + } + if (sizeof ($alerts) == 0) + return; - $query_gen='SELECT talerta_agente_modulo.alert_text, talerta_agente_modulo.id_alerta, talerta_agente_modulo.descripcion, talerta_agente_modulo.last_fired, talerta_agente_modulo.times_fired, tagente_modulo.nombre, talerta_agente_modulo.dis_max, talerta_agente_modulo.dis_min, talerta_agente_modulo.max_alerts, talerta_agente_modulo.time_threshold, talerta_agente_modulo.min_alerts, talerta_agente_modulo.id_agente_modulo, tagente_modulo.id_agente_modulo FROM tagente_modulo, talerta_agente_modulo WHERE tagente_modulo.id_agente_modulo = talerta_agente_modulo.id_agente_modulo and talerta_agente_modulo.id_agente_modulo = '.$id_agent_module.' ORDER BY tagente_modulo.nombre'; - $result_gen=mysql_query($query_gen); - if (mysql_num_rows ($result_gen)) { - echo ""; - echo " - - - - - "; + $alerts_fired = array (); + $agents = array (); + foreach ($alerts as $alert) { + $fires = get_alert_fires_in_period ($alert['id_agente_modulo'], $period, $date); + if (! $fires) { + continue; + } + $alerts_fired[$alert['id_aam']] = $fires; + $data = array (); - $color=1; - while ($data=mysql_fetch_array($result_gen)){ - if ($color == 1){ - $tdcolor = "datos"; - $color = 0; - } - else { - $tdcolor = "datos2"; - $color = 1; - } - echo ""; - if ($data["times_fired"] <> 0) - echo ""; - else - echo ""; - echo ""; - echo ""; - } - else { - echo ""; - } - echo ""; - + /* Add alerts fired to $agents_fired_alerts indexed by id_agent */ + $id_agent = $alert['id_agent']; + if (!isset ($agents[$id_agent])) { + $agents[$id_agent] = array (); } - echo '
".$lang_label["status"]."".$lang_label["description"]."".$lang_label["time_threshold"]."".$lang_label["last_fired"]."".$lang_label["times_fired"]."
".$data["descripcion"]."".human_time_description($data["time_threshold"]); - if ($data["last_fired"] == "0000-00-00 00:00:00") { - echo "".$lang_label["never"]."".human_time_comparation ($data["last_fired"])."".$data["times_fired"]."
'; + array_push ($agents[$id_agent], $alert); } + $fired_percentage = round (sizeof ($alerts_fired) / sizeof ($alerts) * 100, 2); + $not_fired_percentage = 100 - $fired_percentage; + $output .= ''; + + $output .= ''.lang_string ('agents_with_fired_alerts').': '.sizeof ($agents).'
'; + $output .= ''.lang_string ('fired_alerts').': '.sizeof ($alerts_fired).'
'; + $output .= ''.lang_string ('total_alerts_monitored').': '.sizeof ($alerts).'
'; + + $table->width = '100%'; + $table->class = 'databox'; + $table->size = array (); + $table->size[0] = '100px'; + $table->data = array (); + $table->head = array (); + $table->head[0] = lang_string ('agent'); + $table->head[1] = lang_string ('alert_description'); + $table->head[2] = lang_string ('times_fired'); + $table->head[3] = lang_string ('priority'); + + foreach ($agents as $alerts) { + $data = array (); + foreach ($alerts as $alert) { + if (! isset ($data[0])) + $data[0] = ''.dame_nombre_agente_agentemodulo ($alert['id_agente_modulo']).''; + else + $data[0] = ''; + $data[1] = $alert['descripcion']; + $data[2] = $alerts_fired[$alert['id_aam']]; + $data[3] = $alert['priority']; + array_push ($table->data, $data); + } + } + $output .= print_table ($table, true); + + if (!$return) + echo $output; + return $output; } +/** + * Get a report for monitors modules in a group of agents. + * + * It prints the numbers of monitors defined, showing those which went up and down, in a group. + * It also prints all the down monitors in the group. + * + * @param $id_group Group to get info of the monitors. + * @param $period Period of time of the desired monitor report. + * @param $date Beggining date of the report (current date by default). + * @param $return Flag to return or echo the report (by default). + */ +function monitor_health_reporting ($id_group, $period = 0, $date = 0, $return = false) { + if (! $date) + $date = time (); + $datelimit = $date - $period; + $output = ''; + + $sql = sprintf ('SELECT * FROM tagente_modulo, ttipo_modulo, tagente + WHERE id_tipo_modulo = id_tipo + AND tagente.id_agente = tagente_modulo.id_agente + AND ttipo_modulo.nombre like "%%_proc" + AND tagente.id_grupo = %d', $id_group); + $monitors = get_db_all_rows_sqlfree ($sql); + if (sizeof ($monitors) == 0) + return; + + $monitors_down = 0; + $agents = array (); + foreach ($monitors as $monitor) { + $down = get_monitor_downs_in_period ($monitor['id_agente_modulo'], $period, $date); + if (! $down) { + continue; + } + $data = array (); + + /* Add monitors fired to $agents_fired_alerts indexed by id_agent */ + $id_agent = $monitor['id_agente']; + if (!isset ($agents[$id_agent])) { + $agents[$id_agent] = array (); + } + array_push ($agents[$id_agent], $monitor); + + $monitors_down++; + } + $down_percentage = round ($monitors_down / sizeof ($monitors) * 100, 2); + $not_down_percentage = 100 - $down_percentage; + $output .= ''; + + $output .= ''.lang_string ('total_monitors').': '.sizeof ($monitors).'
'; + $output .= ''.lang_string ('monitors_down_on_period').': '.$monitors_down.'
'; + + $table->width = '100%'; + $table->class = 'databox'; + $table->size = array (); + $table->size[0] = '100px'; + $table->data = array (); + $table->head = array (); + $table->head[0] = lang_string ('agent'); + $table->head[1] = lang_string ('alert_description'); + + foreach ($agents as $monitors) { + $data = array (); + foreach ($monitors as $monitor) { + if (! isset ($data[0])) + $data[0] = ''.$monitor['nombre'].''; + else + $data[0] = ''; + $data[1] = $monitor['descripcion']; + array_push ($table->data, $data); + } + } + $output .= print_table ($table, true); + + if (!$return) + echo $output; + return $output; +} + +/** + * Get a general report of a group of agents. + * + * It shows the number of agents and no more things right now. + * + * @param $id_group Group to get the report + * @param $return Flag to return or echo the report (by default). + */ +function general_group_reporting ($id_group, $return = false) { + $output = ''; + $agents = give_db_value ('COUNT(*)', 'tagente', 'id_grupo', $id_group); + $output .= ''.lang_string ('agents_in_group').': '.$agents.'
'; + + if (!$return) + echo $output; + return $output; +} + +/** + * Get a detailed report of agents in a group. + * + * It + * + * @param $id_group Group to get the report + * @param $return Flag to return or echo the report (by default). + */ +function agents_detailed_reporting ($id_group, $period = 0, $date = 0, $return = false) { + $output = ''; + $agents = give_db_value ('COUNT(*)', 'tagente', 'id_grupo', $id_group); + + $table_modules->width = '750px'; + $table_alerts->width = '750px'; + $table_monitors->width = '750px'; + $table_monitors->align = array (); + $table_monitors->align[1] = 'right'; + $table_monitors->head = array (); + $table_monitors->head[0] = lang_string ('monitor'); + $table_monitors->head[1] = lang_string ('last_failure'); + $table_alerts->head = array (); + $table_alerts->head[0] = lang_string ('type'); + $table_alerts->head[1] = lang_string ('description'); + $table_alerts->head[2] = lang_string ('min'); + $table_alerts->head[3] = lang_string ('max'); + $table_alerts->head[4] = lang_string ('threshold'); + $table_alerts->head[5] = lang_string ('last_fired'); + $table_alerts->head[6] = lang_string ('times_fired'); + + $agents = get_agents_in_group ($id_group); + $n_a_string = lang_string ('N/A').'(*)'; + foreach ($agents as $agent) { + $monitors = array (); + $table_modules->data = array (); + $table_modules->head = array (); + $table_alerts->data = array (); + + $modules = get_modules_in_agent ($agent['id_agente']); + + /* Show modules in agent */ + $output .= '

'.lang_string ('agent').' - '.$agent['nombre'].'

'; + $output .= '

'.lang_string ('modules').'

'; + $data = array (); + foreach ($modules as $module) { + if ($module['descripcion'] != $n_a_string && $module['descripcion'] != '') + $data[0] = $module['descripcion']; + else + $data[0] = $module['nombre']; + $module_name = giveme_module_type ($module['id_tipo_modulo']); + if (is_module_proc ($module_name)) { + array_push ($monitors, $module); + } + array_push ($table_modules->data, $data); + } + $output .= print_table ($table_modules, true); + + /* Show alerts in agent */ + $alerts = get_alerts_in_agent ($agent['id_agente']); + foreach ($alerts as $alert) { + $fires = get_alert_fires_in_period ($alert['id_agente_modulo'], $period, $date); + if (! $fires) { + continue; + } + $alert_type = get_db_row ('talerta', 'id_alerta', $alert['id_alerta']); + $data = array (); + $data[0] = $alert_type['nombre']; + $data[1] = $alert['descripcion']; + $data[2] = $alert['dis_min']; + $data[3] = $alert['dis_max']; + $data[4] = $alert['time_threshold']; + $data[5] = get_alert_last_fire_timestamp_in_period ($alert['id_agente_modulo'], $period, $date); + $data[6] = $fires; + + array_push ($table_alerts->data, $data); + } + if (sizeof ($table_alerts->data)) { + $output .= '

'.lang_string ('alerts').'

'; + $output .= print_table ($table_alerts, true); + } + + /* Show monitor status in agent (if any) */ + if (sizeof ($monitors) == 0) { + continue; + } + $table_monitors->data = array (); + foreach ($monitors as $monitor) { + $downs = get_monitor_downs_in_period ($monitor['id_agente_modulo'], $period, $date); + if (! $downs) { + continue; + } + $data = array (); + if ($monitor['descripcion'] != $n_a_string && $monitor['descripcion'] != '') + $data[0] = $monitor['descripcion']; + else + $data[0] = $monitor['nombre']; + $data[1] = get_monitor_last_down_timestamp_in_period ($monitor['id_agente_modulo'], $period, $date); + array_push ($table_monitors->data, $data); + } + if (sizeof ($table_monitors->data)) { + $output .= '

'.lang_string ('monitors').'

'; + $output .= print_table ($table_monitors, true); + } + } + + if (!$return) + echo $output; + return $output; +} ?> diff --git a/pandora_console/include/javascript/jquery.js b/pandora_console/include/javascript/jquery.js new file mode 100644 index 0000000000..2453ec6266 --- /dev/null +++ b/pandora_console/include/javascript/jquery.js @@ -0,0 +1,13 @@ +/* + * jQuery 1.2.4a - New Wave Javascript + * + * Copyright (c) 2008 John Resig (jquery.com) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * Compressed using Dean Edwards' Packer (http://dean.edwards.name/packer/) + * + * $Date: 2008-04-09 21:17:07 -0400 (Wed, 09 Apr 2008) $ + * $Rev: 5225 $ + */ +(function(){if(window.jQuery)var u=window.jQuery;var v=window.jQuery=function(a,b){return new v.prototype.init(a,b)};if(window.$)var w=window.$;window.$=v;var x=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;var y=/^.[^:#\[\.]*$/;v.fn=v.prototype={init:function(a,b){a=a||document;if(a.nodeType){this[0]=a;this.length=1;return this}else if(typeof a=="string"){var c=x.exec(a);if(c&&(c[1]||!b)){if(c[1])a=v.clean([c[1]],b);else{var d=document.getElementById(c[3]);if(d)if(d.id!=c[3])return v().find(a);else{this[0]=d;this.length=1;return this}else a=[]}}else return new v(b).find(a)}else if(v.isFunction(a))return new v(document)[v.fn.ready?"ready":"load"](a);return this.setArray(a.constructor==Array&&a||(a.jquery||a.length&&a!=window&&!a.nodeType&&a[0]!=undefined&&a[0].nodeType)&&v.makeArray(a)||[a])},jquery:"1.2.4a",size:function(){return this.length},length:0,get:function(a){return a==undefined?v.makeArray(this):this[a]},pushStack:function(a){var b=v(a);b.prevObject=this;return b},setArray:function(a){this.length=0;Array.prototype.push.apply(this,a);return this},each:function(a,b){return v.each(this,a,b)},index:function(a){var b=-1;this.each(function(i){if(this==a)b=i});return b},attr:function(a,b,c){var d=a;if(a.constructor==String)if(b==undefined)return this.length&&v[c||"attr"](this[0],a)||undefined;else{d={};d[a]=b}return this.each(function(i){for(a in d)v.attr(c?this.style:this,a,v.prop(this,d[a],c,i,a))})},css:function(a,b){if((a=='width'||a=='height')&&parseFloat(b)<0)b=undefined;return this.attr(a,b,"curCSS")},text:function(a){if(typeof a!="object"&&a!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(a));var b="";v.each(a||this,function(){v.each(this.childNodes,function(){if(this.nodeType!=8)b+=this.nodeType!=1?this.nodeValue:v.fn.text([this])})});return b},wrapAll:function(b){if(this[0])v(b,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var a=this;while(a.firstChild)a=a.firstChild;return a}).append(this);return this},wrapInner:function(a){return this.each(function(){v(this).contents().wrapAll(a)})},wrap:function(a){return this.each(function(){v(this).wrapAll(a)})},append:function(){return this.domManip(arguments,true,false,function(a){if(this.nodeType==1)this.appendChild(a)})},prepend:function(){return this.domManip(arguments,true,true,function(a){if(this.nodeType==1)this.insertBefore(a,this.firstChild)})},before:function(){return this.domManip(arguments,false,false,function(a){this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,false,true,function(a){this.parentNode.insertBefore(a,this.nextSibling)})},end:function(){return this.prevObject||v([])},find:function(b){var c=v.map(this,function(a){return v.find(b,a)});return this.pushStack(/[^+>] [^+>]/.test(b)||b.indexOf("..")>-1?v.unique(c):c)},clone:function(d){var e=this.map(function(){if(v.browser.msie&&!v.isXMLDoc(this)){var a=this.cloneNode(true),container=document.createElement("div");container.appendChild(a);return v.clean([container.innerHTML])[0]}else return this.cloneNode(true)});var f=e.find("*").andSelf().each(function(){if(this[A]!=undefined)this[A]=null});if(d===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var a=v.data(this,"events");for(var b in a)for(var c in a[b])v.event.add(f[i],b,a[b][c],a[b][c].data)});return e},filter:function(b){return this.pushStack(v.isFunction(b)&&v.grep(this,function(a,i){return b.call(a,i)})||v.multiFilter(b,this))},not:function(a){if(a.constructor==String)if(y.test(a))return this.pushStack(v.multiFilter(a,this,true));else a=v.multiFilter(a,this);var b=a.length&&a[a.length-1]!==undefined&&!a.nodeType;return this.filter(function(){return b?v.inArray(this,a)<0:this!=a})},add:function(a){return!a?this:this.pushStack(v.merge(this.get(),a.constructor==String?v(a).get():a.length!=undefined&&(!a.nodeName||v.nodeName(a,"form"))?a:[a]))},is:function(a){return a?v.multiFilter(a,this).length>0:false},hasClass:function(a){return this.is("."+a)},val:function(b){if(b==undefined){if(this.length){var c=this[0];if(v.nodeName(c,"select")){var d=c.selectedIndex,values=[],options=c.options,one=c.type=="select-one";if(d<0)return null;for(var i=one?d:0,max=one?d+1:options.length;i=0||v.inArray(this.name,b)>=0);else if(v.nodeName(this,"select")){var a=b.constructor==Array?b:[b];v("option",this).each(function(){this.selected=(v.inArray(this.value,a)>=0||v.inArray(this.text,a)>=0)});if(!a.length)this.selectedIndex=-1}else this.value=b})},html:function(a){return a==undefined?(this.length?this[0].innerHTML:null):this.empty().append(a)},replaceWith:function(a){return this.after(a).remove()},eq:function(i){return this.slice(i,i+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments))},map:function(b){return this.pushStack(v.map(this,function(a,i){return b.call(a,i,a)}))},andSelf:function(){return this.add(this.prevObject)},data:function(a,b){var c=a.split(".");c[1]=c[1]?"."+c[1]:"";if(b==null){var d=this.triggerHandler("getData"+c[1]+"!",[c[0]]);if(d==undefined&&this.length)d=v.data(this[0],a);return d==null&&c[1]?this.data(c[0]):d}else return this.trigger("setData"+c[1]+"!",[c[0],b]).each(function(){v.data(this,a,b)})},removeData:function(a){return this.each(function(){v.removeData(this,a)})},domManip:function(d,e,f,g){var h=this.length>1,elems;return this.each(function(){if(!elems){elems=v.clean(d,this.ownerDocument);if(f)elems.reverse()}var b=this;if(e&&v.nodeName(this,"table")&&v.nodeName(elems[0],"tr"))b=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var c=v([]);v.each(elems,function(){var a=h?v(this).clone(true)[0]:this;if(v.nodeName(a,"script")){c=c.add(a)}else{if(a.nodeType==1)c=c.add(v("script",a).remove());g.call(b,a)}});c.each(evalScript)})}};v.prototype.init.prototype=v.prototype;function evalScript(i,a){if(a.src)v.ajax({url:a.src,async:false,dataType:"script"});else v.globalEval(a.text||a.textContent||a.innerHTML||"");if(a.parentNode)a.parentNode.removeChild(a)}v.extend=v.fn.extend=function(){var a=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(a.constructor==Boolean){deep=a;a=arguments[1]||{};i=2}if(typeof a!="object"&&typeof a!="function")a={};if(length==1){a=this;i=0}for(;i-1}},swap:function(a,b,c){var d={};for(var e in b){d[e]=a.style[e];a.style[e]=b[e]}c.call(a);for(var e in b)a.style[e]=d[e]},css:function(b,c,d){if(c=="width"||c=="height"){var e,props={position:"absolute",visibility:"hidden",display:"block"},which=c=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){e=c=="width"?b.offsetWidth:b.offsetHeight;var a=0,border=0;v.each(which,function(){a+=parseFloat(v.curCSS(b,"padding"+this,true))||0;border+=parseFloat(v.curCSS(b,"border"+this+"Width",true))||0});e-=Math.round(a+border)}if(v(b).is(":visible"))getWH();else v.swap(b,props,getWH);return Math.max(0,e)}return v.curCSS(b,c,d)},curCSS:function(c,d,e){var f;function color(a){if(!v.browser.safari)return false;var b=document.defaultView.getComputedStyle(a,null);return!b||b.getPropertyValue("color")==""}if(d=="opacity"&&v.browser.msie){f=v.attr(c.style,"opacity");return f==""?"1":f}if(v.browser.opera&&d=="display"){var g=c.style.outline;c.style.outline="0 solid black";c.style.outline=g}if(d.match(/float/i))d=D;if(!e&&c.style&&c.style[d])f=c.style[d];else if(document.defaultView&&document.defaultView.getComputedStyle){if(d.match(/float/i))d="float";d=d.replace(/([A-Z])/g,"-$1").toLowerCase();var h=document.defaultView.getComputedStyle(c,null);if(h&&!color(c))f=h.getPropertyValue(d);else{var j=[],stack=[];for(var a=c;a&&color(a);a=a.parentNode)stack.unshift(a);for(var i=0;i]*?)\/>/g,function(a,b,c){return c.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?a:b+">"});var e=v.trim(d).toLowerCase(),div=k.createElement("div");var f=!e.indexOf("",""]||!e.indexOf("",""]||e.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
"]||!e.indexOf("",""]||(!e.indexOf("",""]||!e.indexOf("",""]||v.browser.msie&&[1,"div
","
"]||[0,"",""];div.innerHTML=f[1]+d+f[2];while(f[0]--)div=div.lastChild;if(v.browser.msie){var g=!e.indexOf(""&&e.indexOf("=0;--j)if(v.nodeName(g[j],"tbody")&&!g[j].childNodes.length)g[j].parentNode.removeChild(g[j]);if(/^\s/.test(d))div.insertBefore(k.createTextNode(d.match(/^\s*/)[0]),div.firstChild)}d=v.makeArray(div.childNodes)}if(d.length===0&&(!v.nodeName(d,"form")&&!v.nodeName(d,"select")))return;if(d[0]==undefined||v.nodeName(d,"form")||d.options)l.push(d);else l=v.merge(l,d)});return l},attr:function(c,d,e){if(!c||c.nodeType==3||c.nodeType==8)return undefined;var f=v.isXMLDoc(c)?{}:v.props;if(d=="selected"&&v.browser.safari)c.parentNode.selectedIndex;if(f[d]){if(e!=undefined)c[f[d]]=e;return c[f[d]]}else if(v.browser.msie&&d=="style")return v.attr(c.style,"cssText",e);else if(e==undefined&&v.browser.msie&&v.nodeName(c,"form")&&(d=="action"||d=="method"))return c.getAttributeNode(d).nodeValue;else if(c.tagName){if(e!=undefined){if(d=="type"&&v.nodeName(c,"input")&&c.parentNode)throw"type property can't be changed";c.setAttribute(d,""+e)}if(v.browser.msie&&/href|src/.test(d)&&!v.isXMLDoc(c))return c.getAttribute(d,2);return c.getAttribute(d)}else{if(d=="opacity"&&v.browser.msie){if(e!=undefined){c.zoom=1;c.filter=(c.filter||"").replace(/alpha\([^)]*\)/,"")+(parseFloat(e).toString()=="NaN"?"":"alpha(opacity="+e*100+")")}return c.filter&&c.filter.indexOf("opacity=")>=0?(parseFloat(c.filter.match(/opacity=([^)]*)/)[1])/100).toString():""}d=d.replace(/-([a-z])/ig,function(a,b){return b.toUpperCase()});if(e!=undefined)c[d]=e;return c[d]}},trim:function(a){return(a||"").replace(/^\s+|\s+$/g,"")},makeArray:function(a){var b=[];if(a.constructor!=Array)for(var i=0,length=a.length;i*",this).remove();while(this.firstChild)this.removeChild(this.firstChild)}},function(a,b){v.fn[a]=function(){return this.each(b,arguments)}});v.each(["Height","Width"],function(i,b){var c=b.toLowerCase();v.fn[c]=function(a){return this[0]==window?v.browser.opera&&document.body["client"+b]||v.browser.safari&&window["inner"+b]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+b]||document.body["client"+b]:this[0]==document?Math.max(Math.max(document.body["scroll"+b],document.documentElement["scroll"+b]),Math.max(document.body["offset"+b],document.documentElement["offset"+b])):a==undefined?(this.length?v.css(this[0],c):null):this.css(c,a.constructor==String?a:a+"px")}});var E=v.browser.safari&&parseInt(v.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+E+"+)"),quickID=new RegExp("^("+E+"+)(#)("+E+"+)"),quickClass=new RegExp("^([#.]?)("+E+"*)");v.extend({expr:{"":function(a,i,m){return m[2]=="*"||v.nodeName(a,m[2])},"#":function(a,i,m){return a.getAttribute("id")==m[2]},":":{lt:function(a,i,m){return im[3]-0},nth:function(a,i,m){return m[3]-0==i},eq:function(a,i,m){return m[3]-0==i},first:function(a,i){return i==0},last:function(a,i,m,r){return i==r.length-1},even:function(a,i){return i%2==0},odd:function(a,i){return i%2},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a},"last-child":function(a){return v.nth(a.parentNode.lastChild,1,"previousSibling")==a},"only-child":function(a){return!v.nth(a.parentNode.lastChild,2,"previousSibling")},parent:function(a){return a.firstChild},empty:function(a){return!a.firstChild},contains:function(a,i,m){return(a.textContent||a.innerText||v(a).text()||"").indexOf(m[3])>=0},visible:function(a){return"hidden"!=a.type&&v.css(a,"display")!="none"&&v.css(a,"visibility")!="hidden"},hidden:function(a){return"hidden"==a.type||v.css(a,"display")=="none"||v.css(a,"visibility")=="hidden"},enabled:function(a){return!a.disabled},disabled:function(a){return a.disabled},checked:function(a){return a.checked},selected:function(a){return a.selected||v.attr(a,"selected")},text:function(a){return"text"==a.type},radio:function(a){return"radio"==a.type},checkbox:function(a){return"checkbox"==a.type},file:function(a){return"file"==a.type},password:function(a){return"password"==a.type},submit:function(a){return"submit"==a.type},image:function(a){return"image"==a.type},reset:function(a){return"reset"==a.type},button:function(a){return"button"==a.type||v.nodeName(a,"button")},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},has:function(a,i,m){return v.find(m[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},animated:function(a){return v.grep(v.timers,function(b){return a==b.elem}).length}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+E+"+)")],multiFilter:function(a,b,c){var d,cur=[];while(a&&a!=d){d=a;var f=v.filter(a,b,c);a=f.t.replace(/^\s*,\s*/,"");cur=c?b=f.r:v.merge(cur,f.r)}return cur},find:function(t,a){if(typeof t!="string")return[t];if(a&&a.nodeType!=1&&a.nodeType!=9)return[];a=a||document;var b=[a],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=v.trim(t);var d=false;var e=quickChild;var m=e.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;b[i];i++)for(var c=b[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);b=r;t=t.replace(e,"");if(t.indexOf(" ")==0)continue;d=true}else{e=/^([>+~])\s*(\w*)/i;if((m=e.exec(t))!=null){r=[];var f={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=b.length;j=0;if(!a&&c||a&&!c)b.push(r[i])}return b},filter:function(t,r,b){var d;while(t&&t!=d){d=t;var p=v.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=y.test(m[3])?v.filter(m[3],r,true).r:v(r).not(m[3]);else if(m[1]==".")r=v.classFilter(r,m[2],b);else if(m[1]=="["){var e=[],type=m[3];for(var i=0,rl=r.length;i=0)^b)e.push(a)}r=e}else if(m[1]==":"&&m[2]=="nth-child"){var f={},e=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,d=test[3]-0;for(var i=0,rl=r.length;i=0)h=true;if(h^b)e.push(g)}r=e}else{var j=v.expr[m[1]];if(typeof j=="object")j=j[m[2]];if(typeof j=="string")j=eval("false||function(a,i){return "+j+";}");r=v.grep(r,function(a,i){return j(a,i,m,r)},b)}}return{r:r,t:t}},dir:function(a,b){var c=[];var d=a[b];while(d&&d!=document){if(d.nodeType==1)c.push(d);d=d[b]}return c},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType==1&&++e==b)break;return a},sibling:function(n,a){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&(!a||n!=a))r.push(n)}return r}});v.event={add:function(e,f,g,h){if(e.nodeType==3||e.nodeType==8)return;if(v.browser.msie&&e.setInterval!=undefined)e=window;if(!g.guid)g.guid=this.guid++;if(h!=undefined){var i=g;g=function(){return i.apply(this,arguments)};g.data=h;g.guid=i.guid}var j=v.data(e,"events")||v.data(e,"events",{}),handle=v.data(e,"handle")||v.data(e,"handle",function(){var a;if(typeof v=="undefined"||v.event.triggered)return a;a=v.event.handle.apply(arguments.callee.elem,arguments);return a});handle.elem=e;v.each(f.split(/\s+/),function(a,b){var c=b.split(".");b=c[0];g.type=c[1];var d=j[b];if(!d){d=j[b]={};if(!v.event.special[b]||v.event.special[b].setup.call(e)===false){if(e.addEventListener)e.addEventListener(b,handle,false);else if(e.attachEvent)e.attachEvent("on"+b,handle)}}d[g.guid]=g;v.event.global[b]=true});e=null},guid:1,global:{},remove:function(d,e,f){if(d.nodeType==3||d.nodeType==8)return;var g=v.data(d,"events"),ret,index;if(g){if(e==undefined||(typeof e=="string"&&e.charAt(0)=="."))for(var h in g)this.remove(d,h+(e||""));else{if(e.type){f=e.handler;e=e.type}v.each(e.split(/\s+/),function(a,b){var c=b.split(".");b=c[0];if(g[b]){if(f)delete g[b][f.guid];else for(f in g[b])if(!c[1]||g[b][f].type==c[1])delete g[b][f];for(ret in g[b])break;if(!ret){if(!v.event.special[b]||v.event.special[b].teardown.call(d)===false){if(d.removeEventListener)d.removeEventListener(b,v.data(d,"handle"),false);else if(d.detachEvent)d.detachEvent("on"+b,v.data(d,"handle"))}ret=null;delete g[b]}}})}for(ret in g)break;if(!ret){var i=v.data(d,"handle");if(i)i.elem=null;v.removeData(d,"events");v.removeData(d,"handle")}}},trigger:function(a,b,c,d,f){b=v.makeArray(b||[]);if(a.indexOf("!")>=0){a=a.slice(0,-1);var g=true}if(!c){if(this.global[a])v("*").add([window,document]).trigger(a,b)}else{if(c.nodeType==3||c.nodeType==8)return undefined;var h,ret,fn=v.isFunction(c[a]||null),event=!b[0]||!b[0].preventDefault;if(event)b.unshift(this.fix({type:a,target:c}));b[0].type=a;if(g)b[0].exclusive=true;if(v.isFunction(v.data(c,"handle")))h=v.data(c,"handle").apply(c,b);if(!fn&&c["on"+a]&&c["on"+a].apply(c,b)===false)h=false;if(event)b.shift();if(f&&v.isFunction(f)){ret=f.apply(c,h==null?b:b.concat(h));if(ret!==undefined)h=ret}if(fn&&d!==false&&h!==false&&!(v.nodeName(c,'a')&&a=="click")){this.triggered=true;try{c[a]()}catch(e){}}this.triggered=false}return h},handle:function(a){var b;a=v.event.fix(a||window.event||{});var c=a.type.split(".");a.type=c[0];var d=v.data(this,"events")&&v.data(this,"events")[a.type],args=Array.prototype.slice.call(arguments,1);args.unshift(a);for(var j in d){var e=d[j];args[0].handler=e;args[0].data=e.data;if(!c[1]&&!a.exclusive||e.type==c[1]){var f=e.apply(this,args);if(b!==false)b=f;if(f===false){a.preventDefault();a.stopPropagation()}}}if(v.browser.msie)a.target=a.preventDefault=a.stopPropagation=a.handler=a.data=null;return b},fix:function(a){var b=a;a=v.extend({},b);a.preventDefault=function(){if(b.preventDefault)b.preventDefault();b.returnValue=false};a.stopPropagation=function(){if(b.stopPropagation)b.stopPropagation();b.cancelBubble=true};if(!a.target)a.target=a.srcElement||document;if(a.target.nodeType==3)a.target=b.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement==a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){var c=document.documentElement,body=document.body;a.pageX=a.clientX+(c&&c.scrollLeft||body&&body.scrollLeft||0)-(c.clientLeft||0);a.pageY=a.clientY+(c&&c.scrollTop||body&&body.scrollTop||0)-(c.clientTop||0)}if(!a.which&&((a.charCode||a.charCode===0)?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button)a.which=(a.button&1?1:(a.button&2?3:(a.button&4?2:0)));return a},special:{ready:{setup:function(){bindReady();return},teardown:function(){return}},mouseenter:{setup:function(){if(v.browser.msie)return false;v(this).bind("mouseover",v.event.special.mouseenter.handler);return true},teardown:function(){if(v.browser.msie)return false;v(this).unbind("mouseover",v.event.special.mouseenter.handler);return true},handler:function(a){if(G(a,this))return true;arguments[0].type="mouseenter";return v.event.handle.apply(this,arguments)}},mouseleave:{setup:function(){if(v.browser.msie)return false;v(this).bind("mouseout",v.event.special.mouseleave.handler);return true},teardown:function(){if(v.browser.msie)return false;v(this).unbind("mouseout",v.event.special.mouseleave.handler);return true},handler:function(a){if(G(a,this))return true;arguments[0].type="mouseleave";return v.event.handle.apply(this,arguments)}}}};v.fn.extend({bind:function(a,b,c){return a=="unload"?this.one(a,b,c):this.each(function(){v.event.add(this,a,c||b,c&&b)})},one:function(b,c,d){return this.each(function(){v.event.add(this,b,function(a){v(this).unbind(a);return(d||c).apply(this,arguments)},d&&c)})},unbind:function(a,b){return this.each(function(){v.event.remove(this,a,b)})},trigger:function(a,b,c){return this.each(function(){v.event.trigger(a,b,this,true,c)})},triggerHandler:function(a,b,c){if(this[0])return v.event.trigger(a,b,this[0],false,c);return undefined},toggle:function(){var b=arguments;return this.click(function(a){this.lastToggle=0==this.lastToggle?1:0;a.preventDefault();return b[this.lastToggle].apply(this,arguments)||false})},hover:function(a,b){return this.bind('mouseenter',a).bind('mouseleave',b)},ready:function(a){bindReady();if(v.isReady)a.call(document,v);else v.readyList.push(function(){return a.call(this,v)});return this}});v.extend({isReady:false,readyList:[],ready:function(){if(!v.isReady){v.isReady=true;if(v.readyList){v.each(v.readyList,function(){this.apply(document)});v.readyList=null}v(document).triggerHandler("ready")}}});var F=false;function bindReady(){if(F)return;F=true;if(document.addEventListener&&!v.browser.opera)document.addEventListener("DOMContentLoaded",v.ready,false);if(v.browser.msie&&window==top)(function(){if(v.isReady)return;try{document.documentElement.doScroll("left")}catch(error){setTimeout(arguments.callee,0);return}v.ready()})();if(v.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(v.isReady)return;for(var i=0;i=0){var g=c.slice(f,c.length);c=c.slice(0,f)}e=e||function(){};var h="GET";if(d)if(v.isFunction(d)){e=d;d=null}else{d=v.param(d);h="POST"}var i=this;v.ajax({url:c,type:h,dataType:"html",data:d,complete:function(a,b){if(b=="success"||b=="notmodified")i.html(g?v("
").append(a.responseText.replace(//g,"")).find(g):a.responseText);i.each(e,[a.responseText,b,a])}});return this},serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return v.nodeName(this,"form")?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type))}).map(function(i,b){var c=v(this).val();return c==null?null:c.constructor==Array?v.map(c,function(a,i){return{name:b.name,value:a}}):{name:b.name,value:c}}).get()}});v.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){v.fn[o]=function(f){return this.bind(o,f)}});var H=(new Date).getTime();v.extend({get:function(a,b,c,d){if(v.isFunction(b)){c=b;b=null}return v.ajax({type:"GET",url:a,data:b,success:c,dataType:d})},getScript:function(a,b){return v.get(a,null,b,"script")},getJSON:function(a,b,c){return v.get(a,b,c,"json")},post:function(a,b,c,d){if(v.isFunction(b)){c=b;b={}}return v.ajax({type:"POST",url:a,data:b,success:c,dataType:d})},ajaxSetup:function(a){v.extend(v.ajaxSettings,a)},ajaxSettings:{global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){var c,jsre=/=\?(&|$)/g,status,data;s=v.extend(true,s,v.extend(true,{},v.ajaxSettings,s));if(s.data&&s.processData&&typeof s.data!="string")s.data=v.param(s.data);if(s.dataType=="jsonp"){if(s.type.toLowerCase()=="get"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?"}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json"}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){c="jsonp"+H++;if(s.data)s.data=(s.data+"").replace(jsre,"="+c+"$1");s.url=s.url.replace(jsre,"="+c+"$1");s.dataType="script";window[c]=function(a){data=a;success();complete();window[c]=undefined;try{delete window[c]}catch(e){}if(g)g.removeChild(h)}}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&s.type.toLowerCase()=="get"){var d=(new Date()).getTime();var f=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+d+"$2");s.url=f+((f==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+d:"")}if(s.data&&s.type.toLowerCase()=="get"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null}if(s.global&&!v.active++)v.event.trigger("ajaxStart");if((!s.url.indexOf("http")||!s.url.indexOf("//"))&&s.dataType=="script"&&s.type.toLowerCase()=="get"){var g=document.getElementsByTagName("head")[0];var h=document.createElement("script");h.src=s.url;if(s.scriptCharset)h.charset=s.scriptCharset;if(!c){var i=false;h.onload=h.onreadystatechange=function(){if(!i&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){i=true;success();complete();g.removeChild(h)}}}g.appendChild(h);return undefined}var j=false;var k=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();k.open(s.type,s.url,s.async,s.username,s.password);try{if(s.data)k.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)k.setRequestHeader("If-Modified-Since",v.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");k.setRequestHeader("X-Requested-With","XMLHttpRequest");k.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default)}catch(e){}if(s.beforeSend)s.beforeSend(k);if(s.global)v.event.trigger("ajaxSend",[k,s]);var l=function(a){if(!j&&k&&(k.readyState==4||a=="timeout")){j=true;if(m){clearInterval(m);m=null}status=a=="timeout"&&"timeout"||!v.httpSuccess(k)&&"error"||s.ifModified&&v.httpNotModified(k,s.url)&&"notmodified"||"success";if(status=="success"){try{data=v.httpData(k,s.dataType)}catch(e){status="parsererror"}}if(status=="success"){var b;try{b=k.getResponseHeader("Last-Modified")}catch(e){}if(s.ifModified&&b)v.lastModified[s.url]=b;if(!c)success()}else v.handleError(s,k,status);complete();if(s.async)k=null}};if(s.async){var m=setInterval(l,13);if(s.timeout>0)setTimeout(function(){if(k){k.abort();if(!j)l("timeout")}},s.timeout)}try{k.send(s.data)}catch(e){v.handleError(s,k,null,e)}if(!s.async)l();function success(){if(s.success)s.success(data,status);if(s.global)v.event.trigger("ajaxSuccess",[k,s])}function complete(){if(s.complete)s.complete(k,status);if(s.global)v.event.trigger("ajaxComplete",[k,s]);if(s.global&&!--v.active)v.event.trigger("ajaxStop")}return k},handleError:function(s,a,b,e){if(s.error)s.error(a,b,e);if(s.global)v.event.trigger("ajaxError",[a,s,e])},active:0,httpSuccess:function(r){try{return!r.status&&location.protocol=="file:"||(r.status>=200&&r.status<300)||r.status==304||r.status==1223||v.browser.safari&&r.status==undefined}catch(e){}return false},httpNotModified:function(a,b){try{var c=a.getResponseHeader("Last-Modified");return a.status==304||c==v.lastModified[b]||v.browser.safari&&a.status==undefined}catch(e){}return false},httpData:function(r,a){var b=r.getResponseHeader("content-type");var c=a=="xml"||!a&&b&&b.indexOf("xml")>=0;var d=c?r.responseXML:r.responseText;if(c&&d.documentElement.tagName=="parsererror")throw"parsererror";if(a=="script")v.globalEval(d);if(a=="json")d=eval("("+d+")");return d},param:function(a){var s=[];if(a.constructor==Array||a.jquery)v.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value))});else for(var j in a)if(a[j]&&a[j].constructor==Array)v.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this))});else s.push(encodeURIComponent(j)+"="+encodeURIComponent(a[j]));return s.join("&").replace(/%20/g,"+")}});v.fn.extend({show:function(b,c){return b?this.animate({height:"show",width:"show",opacity:"show"},b,c):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(v.css(this,"display")=="none"){var a=v("<"+this.tagName+" />").appendTo("body");this.style.display=a.css("display");if(this.style.display=="none")this.style.display="block";a.remove()}}).end()},hide:function(a,b){return a?this.animate({height:"hide",width:"hide",opacity:"hide"},a,b):this.filter(":visible").each(function(){this.oldblock=this.oldblock||v.css(this,"display");this.style.display="none"}).end()},_toggle:v.fn.toggle,toggle:function(a,b){return v.isFunction(a)&&v.isFunction(b)?this._toggle(a,b):a?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},a,b):this.each(function(){v(this)[v(this).is(":hidden")?"show":"hide"]()})},slideDown:function(a,b){return this.animate({height:"show"},a,b)},slideUp:function(a,b){return this.animate({height:"hide"},a,b)},slideToggle:function(a,b){return this.animate({height:"toggle"},a,b)},fadeIn:function(a,b){return this.animate({opacity:"show"},a,b)},fadeOut:function(a,b){return this.animate({opacity:"hide"},a,b)},fadeTo:function(a,b,c){return this.animate({opacity:b},a,c)},animate:function(h,i,j,k){var l=v.speed(i,j,k);return this[l.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var f=v.extend({},l);var g=v(this).is(":hidden"),self=this;for(var p in h){if(h[p]=="hide"&&g||h[p]=="show"&&!g)return v.isFunction(f.complete)&&f.complete.apply(this);if(p=="height"||p=="width"){f.display=v.css(this,"display");f.overflow=this.style.overflow}}if(f.overflow!=null)this.style.overflow="hidden";f.curAnim=v.extend({},h);v.each(h,function(a,b){var e=new v.fx(self,f,a);if(/toggle|show|hide/.test(b))e[b=="toggle"?g?"show":"hide":b](h);else{var c=b.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(c){var d=parseFloat(c[2]),unit=c[3]||"px";if(unit!="px"){self.style[a]=(d||1)+unit;start=((d||1)/e.cur(true))*start;self.style[a]=start+unit}if(c[1])d=((c[1]=="-="?-1:1)*d)+start;e.custom(start,d,unit)}else e.custom(start,b,"")}});return true})},queue:function(a,b){if(v.isFunction(a)||(a&&a.constructor==Array)){b=a;a="fx"}if(!a||(typeof a=="string"&&!b))return I(this[0],a);return this.each(function(){if(b.constructor==Array)I(this,a,b);else{I(this,a).push(b);if(I(this,a).length==1)b.apply(this)}})},stop:function(a,b){var c=v.timers;if(a)this.queue([]);this.each(function(){for(var i=c.length-1;i>=0;i--)if(c[i].elem==this){if(b)c[i](true);c.splice(i,1)}});if(!b)this.dequeue();return this}});var I=function(a,b,c){if(!a)return undefined;b=b||"fx";var q=v.data(a,b+"queue");if(!q||c)q=v.data(a,b+"queue",c?v.makeArray(c):[]);return q};v.fn.dequeue=function(a){a=a||"fx";return this.each(function(){var q=I(this,a);q.shift();if(q.length)q[0].apply(this)})};v.extend({speed:function(a,b,c){var d=a&&a.constructor==Object?a:{complete:c||!c&&b||v.isFunction(a)&&a,duration:a,easing:c&&b||b&&b.constructor!=Function&&b};d.duration=(d.duration&&d.duration.constructor==Number?d.duration:{slow:600,fast:200}[d.duration])||400;d.old=d.complete;d.complete=function(){if(d.queue!==false)v(this).dequeue();if(v.isFunction(d.old))d.old.apply(this)};return d},easing:{linear:function(p,n,a,b){return a+b*p},swing:function(p,n,a,b){return((-Math.cos(p*Math.PI)/2)+0.5)*b+a}},timers:[],timerId:null,fx:function(a,b,c){this.options=b;this.elem=a;this.prop=c;if(!b.orig)b.orig={}}});v.fx.prototype={update:function(){if(this.options.step)this.options.step.apply(this.elem,[this.now,this]);(v.fx.step[this.prop]||v.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(v.css(this.elem,this.prop,a));return r&&r>-10000?r:parseFloat(v.curCSS(this.elem,this.prop))||0},custom:function(b,c,d){this.startTime=(new Date()).getTime();this.start=b;this.end=c;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var e=this;function t(a){return e.step(a)}t.elem=this.elem;v.timers.push(t);if(v.timerId==null){v.timerId=setInterval(function(){var a=v.timers;for(var i=0;ithis.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var b=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)b=false;if(b){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(v.css(this.elem,"display")=="none")this.elem.style.display="block"}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)v.attr(this.elem.style,p,this.options.orig[p])}if(b&&v.isFunction(this.options.complete))this.options.complete.apply(this.elem);return false}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=v.easing[this.options.easing||(v.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};v.fx.step={scrollLeft:function(a){a.elem.scrollLeft=a.now},scrollTop:function(a){a.elem.scrollTop=a.now},opacity:function(a){v.attr(a.elem.style,"opacity",a.now)},_default:function(a){a.elem.style[a.prop]=a.now+a.unit}};v.fn.offset=function(){var b=0,top=0,elem=this[0],results;if(elem)with(v.browser){var c=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(C),fixed=v.css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var d=elem.getBoundingClientRect();add(d.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),d.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop)}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&v.css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent}while(c&&c.tagName&&!/^body|html$/i.test(c.tagName)){if(!/^inline|table.*$/i.test(v.css(c,"display")))add(-c.scrollLeft,-c.scrollTop);if(mozilla&&v.css(c,"overflow")!="visible")border(c);c=c.parentNode}if((safari2&&(fixed||v.css(offsetChild,"position")=="absolute"))||(mozilla&&v.css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop))}results={top:top,left:b}}function border(a){add(v.curCSS(a,"borderLeftWidth",true),v.curCSS(a,"borderTopWidth",true))}function add(l,t){b+=parseInt(l)||0;top+=parseInt(t)||0}return results};v.each(["Height","Width"],function(i,b){var c=b=="Height"?"Top":"Left",br=b=="Height"?"Bottom":"Right";v.fn["inner"+b]=function(){return this[b.toLowerCase()]()+num(this,"padding"+c)+num(this,"padding"+br)};v.fn["outer"+b]=function(a){return this["inner"+b]()+num(this,"border"+c+"Width")+num(this,"border"+br+"Width")+(!!a?num(this,"margin"+c)+num(this,"margin"+br):0)}});function num(a,b){a=a.jquery?a[0]:a;return a&&parseInt(v.curCSS(a,b,true))||0}})(); diff --git a/pandora_console/include/javascript/jquery.timeentry.js b/pandora_console/include/javascript/jquery.timeentry.js new file mode 100644 index 0000000000..4da617a404 --- /dev/null +++ b/pandora_console/include/javascript/jquery.timeentry.js @@ -0,0 +1,7 @@ +/* http://keith-wood.name/timeEntry.html + Time entry for jQuery v1.3.1. + Written by Keith Wood (kbwood@virginbroadband.com.au) June 2007. + Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and + MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. + Please attribute the author if you use it. */ +(function($){function TimeEntry(){this._nextId=0;this._inst=[];this._disabledInputs=[];this.regional=[];this.regional['']={show24Hours:false,separator:':',ampmPrefix:'',ampmNames:['AM','PM'],spinnerTexts:['Now','Previous field','Next field','Increment','Decrement']};this._defaults={appendText:'',showSeconds:false,timeSteps:[1,1,1],initialField:0,useMouseWheel:true,defaultTime:null,minTime:null,maxTime:null,spinnerImage:'timeEntry.png',spinnerSize:[20,20,8],spinnerIncDecOnly:false,spinnerRepeat:[500,250],beforeShow:null};$.extend(this._defaults,this.regional[''])}$.extend(TimeEntry.prototype,{markerClassName:'hasTimeEntry',_register:function(a){var b=this._nextId++;this._inst[b]=a;return b},_getInst:function(a){return this._inst[a]||a},setDefaults:function(a){extendRemove(this._defaults,a||{})},_doFocus:function(a){var b=(a.nodeName&&a.nodeName.toLowerCase()=='input'?a:this);if($.timeEntry._lastInput==b){return}if($.timeEntry._isDisabledTimeEntry(b)){return}var c=$.timeEntry._getInst(b._timeId);c._input=$(b);$.timeEntry._focussed=true;$.timeEntry._lastInput=b;$.timeEntry._blurredInput=null;var d=c._get('beforeShow');extendRemove(c._settings,(d?d(b):{}));c._parseTime()},_doBlur:function(a){$.timeEntry._blurredInput=$.timeEntry._lastInput;$.timeEntry._lastInput=null},_doClick:function(a){var b=a.target;var c=$.timeEntry._getInst(b._timeId);if(!$.timeEntry._focussed){var d=c._get('separator').length+2;c._field=0;if($.browser.msie){var e=b.value;var f=a.clientX+$.timeEntry._findScroll(a.srcElement)[0]-$.timeEntry._findPos(a.srcElement)[0];for(var g=0;g<=Math.max(1,c._secondField,c._ampmField);g++){var h=(g!=c._ampmField?(g*d)+2:(c._ampmField*d)+c._get('ampmPrefix').length+c._get('ampmNames')[0].length);b.value=e.substring(0,h);var i=b.createTextRange();if(f=48){return true}var b=$.timeEntry._getInst(this._timeId);switch(a.keyCode){case 9:return(a.shiftKey?b._previousField(true):b._nextField(true));case 35:if(a.ctrlKey){b._setValue('')}else{b._field=Math.max(1,b._secondField,b._ampmField);b._adjustField(0)}break;case 36:if(a.ctrlKey){b._setTime()}else{b._field=0;b._adjustField(0)}break;case 37:b._previousField(false);break;case 38:b._adjustField(+1);break;case 39:b._nextField(false);break;case 40:b._adjustField(-1);break;case 46:b._setValue('');break}return false},_doKeyPress:function(a){var b=String.fromCharCode(a.charCode==undefined?a.keyCode:a.charCode);if(b<' '){return true}var c=$.timeEntry._getInst(this._timeId);c._handleKeyPress(b);return false},_doMouseWheel:function(a,b){b=($.browser.opera?-b/Math.abs(b):b);var c=$.timeEntry._getInst(this._timeId);c._adjustField(b);a.preventDefault()},_connectTimeEntry:function(b,c){var d=$(b);if(d.is('.'+this.markerClassName)){return}var e=c._get('spinnerImage');var f=c._get('spinnerText');var g=c._get('spinnerSize');var h=c._get('appendText');var i=(!e?null:$(''));d.wrap('').after(h?''+h+'':'').after(i||'');d.addClass(this.markerClassName).bind('focus.timeEntry',this._doFocus).bind('blur.timeEntry',this._doBlur).bind('click.timeEntry',this._doClick).bind('keydown.timeEntry',this._doKeyDown).bind('keypress.timeEntry',this._doKeyPress);if($.browser.mozilla){d.bind('input.timeEntry',function(a){c._parseTime()})}if($.browser.msie){d.bind('paste.timeEntry',function(a){setTimeout(function(){c._parseTime()},1)})}if(c._get('useMouseWheel')&&$.fn.mousewheel){d.mousewheel(this._doMouseWheel)}d[0]._timeId=c._id;if(i){i.mousedown(this._handleSpinner).mouseup(this._endSpinner).mouseout(this._endSpinner).mousemove(this._describeSpinner);i[0]._timeId=c._id}},_enableTimeEntry:function(a){this._enableDisable(a,false)},_disableTimeEntry:function(a){this._enableDisable(a,true)},_enableDisable:function(b,c){var d=$.timeEntry._getInst(b._timeId);if(!d){return}b.disabled=c;if(b.nextSibling&&b.nextSibling.nodeName.toLowerCase()=='span'){$.timeEntry._changeSpinner(d,b.nextSibling,(c?5:-1))}$.timeEntry._disabledInputs=$.map($.timeEntry._disabledInputs,function(a){return(a==b?null:a)});if(c){$.timeEntry._disabledInputs[$.timeEntry._disabledInputs.length]=b}},_isDisabledTimeEntry:function(a){for(var i=0;i=3&&f[0]){$.timeEntry._timer=setTimeout(function(){$.timeEntry._repeatSpinner(d,e)},f[0]);$(b).one('mouseout',$.timeEntry._releaseSpinner).one('mouseup',$.timeEntry._releaseSpinner)}},_actionSpinner:function(a,b){switch(b){case 0:a._setTime();break;case 1:a._previousField(false);break;case 2:a._nextField(false);break;case 3:a._adjustField(+1);break;case 4:a._adjustField(-1);break}},_repeatSpinner:function(a,b){$.timeEntry._lastInput=$.timeEntry._blurredInput;this._actionSpinner(a,b);this._timer=setTimeout(function(){$.timeEntry._repeatSpinner(a,b)},a._get('spinnerRepeat')[1])},_releaseSpinner:function(a){clearTimeout($.timeEntry._timer)},_endSpinner:function(a){var b=$.timeEntry._getSpinnerTarget(a);var c=$.timeEntry._getInst(b._timeId);if(!$.timeEntry._isDisabledTimeEntry(b.previousSibling)){$.timeEntry._changeSpinner(c,b,-1)}if(!$.browser.opera){$.timeEntry._lastInput=$.timeEntry._blurredInput}if($.timeEntry._lastInput){c._showField()}},_getSpinnerTarget:function(a){return(a.target?a.target:a.srcElement)},_getSpinnerRegion:function(a,b){var c=this._getSpinnerTarget(b);var d=this._findPos(c);var e=this._findScroll(c);var f=a._get('spinnerIncDecOnly');var g=(f?99:b.clientX+e[0]-d[0]-($.browser.msie?1:0));var h=b.clientY+e[1]-d[1]-($.browser.msie?1:0);var i=a._get('spinnerSize');var j=(f?99:i[0]-g);var k=i[1]-h;if(i[2]>0&&Math.abs(g-j)<=i[2]&&Math.abs(h-k)<=i[2]){return 0}var l=Math.min(g,h,j,k);return(l==g?1:(l==j?2:(l==h?3:4)))},_changeSpinner:function(a,b,c){$(b).css('background-position','-'+((c+1)*a._get('spinnerSize')[0])+'px 0px')},_findPos:function(a){var b=curTop=0;if(a.offsetParent){b=a.offsetLeft;curTop=a.offsetTop;while(a=a.offsetParent){var c=b;b+=a.offsetLeft;if(b<0){b=c}curTop+=a.offsetTop}}return[b,curTop]},_findScroll:function(a){var b=false;$(a).parents().each(function(){b|=$(this).css('position')=='fixed'});if(b&&!$.browser.opera){return[0,0]}var c=($.browser.opera?document.body.scrollLeft:a.scrollLeft);var d=($.browser.opera?document.body.scrollTop:a.scrollTop);if(!$.browser.opera){while(a=a.parentNode){c+=a.scrollLeft||0;d+=a.scrollTop||0}}return[c,d]}});function TimeEntryInstance(a){this._id=$.timeEntry._register(this);this._selectedHour=0;this._selectedMinute=0;this._selectedSecond=0;this._field=0;this._input=null;this._settings=extendRemove({},a||{})}$.extend(TimeEntryInstance.prototype,{_get:function(a){return(this._settings[a]!=null?this._settings[a]:$.timeEntry._defaults[a])},_parseTime:function(){var a=this._extractTime();var b=this._get('showSeconds');if(a){this._selectedHour=a[0];this._selectedMinute=a[1];this._selectedSecond=a[2]}else{var c=this._constrainTime();this._selectedHour=c[0];this._selectedMinute=c[1];this._selectedSecond=(b?c[2]:0)}this._secondField=(b?2:-1);this._ampmField=(this._get('show24Hours')?-1:(b?3:2));this._lastChr='';this._field=Math.max(0,Math.min(Math.max(1,this._secondField,this._ampmField),this._get('initialField')));if(this._input.val()!=''){this._showTime()}},_extractTime:function(){var a=(this._input?this._input.val():'');var b=this._get('separator');var c=a.split(b);if(b==''&&a!=''){c[0]=a.substring(0,2);c[1]=a.substring(2,4);c[2]=a.substring(4,6)}var d=this._get('ampmNames');var e=this._get('show24Hours');if(c.length>=2){var f=!e&&(a.indexOf(d[0])>-1);var g=!e&&(a.indexOf(d[1])>-1);var h=parseInt(c[0],10);h=(isNaN(h)?0:h);h=((f||g)&&h==12?0:h)+(g?12:0);var i=parseInt(c[1],10);i=(isNaN(i)?0:i);var j=(c.length>=3?parseInt(c[2],10):0);j=(isNaN(j)||!this._get('showSeconds')?0:j);return this._constrainTime([h,i,j])}return null},_constrainTime:function(a){var b=(a!=null);if(!b){var c=this._determineTime(this._get('defaultTime'))||new Date();a=[c.getHours(),c.getMinutes(),c.getSeconds()]}var d=false;var e=this._get('timeSteps');for(var i=0;i1){a[i]=Math.round(a[i]/e[i])*e[i];d=true}}return a},_showTime:function(){var a=this._get('show24Hours');var b=this._get('separator');var c=(this._formatNumber(a?this._selectedHour:((this._selectedHour+11)%12)+1)+b+this._formatNumber(this._selectedMinute)+(this._get('showSeconds')?b+this._formatNumber(this._selectedSecond):'')+(a?'':this._get('ampmPrefix')+this._get('ampmNames')[(this._selectedHour<12?0:1)]));this._setValue(c);this._showField()},_showField:function(){if(!this._input){return}var a=this._input[0];var b=this._get('separator');var c=b.length+2;var d=(this._field!=this._ampmField?(this._field*c):(this._ampmField*c)-b.length+this._get('ampmPrefix').length);var e=d+(this._field!=this._ampmField?2:this._get('ampmNames')[0].length);if(a.setSelectionRange){a.setSelectionRange(d,e)}else if(a.createTextRange){var f=a.createTextRange();f.moveStart('character',d);f.moveEnd('character',e-this._input.val().length);f.select()}if(!a.disabled){a.focus()}},_formatNumber:function(a){return(a<10?'0':'')+a},_setValue:function(a){this._input.val(a);this._input.trigger('change')},_previousField:function(a){var b=(this._input.val()==''||this._field==0);if(!b){this._field--}this._showField();this._lastChr='';return(b&&a)},_nextField:function(a){var b=(this._input.val()==''||this._field==Math.max(1,this._secondField,this._ampmField));if(!b){this._field++}this._showField();this._lastChr='';return(b&&a)},_adjustField:function(a){if(this._input&&this._input.val()==''){a=0}var b=this._get('timeSteps');this._setTime(new Date(0,0,0,this._selectedHour+(this._field==0?a*b[0]:0)+(this._field==this._ampmField?a*12:0),this._selectedMinute+(this._field==1?a*b[1]:0),this._selectedSecond+(this._field==this._secondField?a*b[2]:0)))},_setTime:function(a){a=this._determineTime(a);var b=this._constrainTime(a?[a.getHours(),a.getMinutes(),a.getSeconds()]:null);a=new Date(0,0,0,b[0],b[1],b[2]);var a=this._normaliseTime(a);var c=this._normaliseTime(this._determineTime(this._get('minTime')));var d=this._normaliseTime(this._determineTime(this._get('maxTime')));a=(c&&ad?d:a));this._selectedHour=a.getHours();this._selectedMinute=a.getMinutes();this._selectedSecond=a.getSeconds();this._showTime()},_determineTime:function(h){var i=function(a){var b=new Date();b.setTime(b.getTime()+a*1000);return b};var j=function(a){var b=new Date();var c=b.getHours();var d=b.getMinutes();var e=b.getSeconds();var f=/([+-]?[0-9]+)\s*(s|S|m|M|h|H)?/g;var g=f.exec(a);while(g){switch(g[2]||'s'){case's':case'S':e+=parseInt(g[1]);break;case'm':case'M':d+=parseInt(g[1]);break;case'h':case'H':c+=parseInt(g[1]);break}g=f.exec(a)}b=new Date(0,0,10,c,d,e,0);if(/^!/.test(a)){if(b.getDate()>10){b=new Date(0,0,10,23,59,59)}else if(b.getDate()<10){b=new Date(0,0,10,0,0,0)}}return b};return(h?(typeof h=='string'?j(h):(typeof h=='number'?i(h):h)):null)},_normaliseTime:function(a){if(!a){return null}a.setFullYear(2001);a.setMonth(1-1);a.setDate(26);return a},_handleKeyPress:function(a){if(a==this._get('separator')){this._nextField(false)}else if(a>='0'&&a<='9'){var b=(this._lastChr+a)*1;var c=this._get('show24Hours');var d=(this._field==0&&((c&&b<24)||(b>=1&&b<=12))?b+(!c&&this._selectedHour>=12?12:0):this._selectedHour);var e=(this._field==1&&b<60?b:this._selectedMinute);var f=(this._field==this._secondField&&b<60?b:this._selectedSecond);var g=this._constrainTime([d,e,f]);this._setTime(new Date(0,0,0,g[0],g[1],g[2]));this._lastChr=a}else if(!this._get('show24Hours')){var h=this._get('ampmNames');if((a==h[0].substring(0,1).toLowerCase()&&this._selectedHour>=12)||(a==h[1].substring(0,1).toLowerCase()&&this._selectedHour<12)){var i=this._field;this._field=this._ampmField;this._adjustField(+1);this._field=i;this._showField()}}}});function extendRemove(a,b){$.extend(a,b);for(var c in b){if(b[c]==null){a[c]=null}}return a}$.fn.timeEntry=function(e){var f=Array.prototype.slice.call(arguments,1);if(typeof e=='string'&&(e=='isDisabled'||e=='getTime')){return $.timeEntry['_'+e+'TimeEntry'].apply($.timeEntry,[this[0]].concat(f))}return this.each(function(){var a=this.nodeName.toLowerCase();if(a=='input'){if(typeof e=='string'){$.timeEntry['_'+e+'TimeEntry'].apply($.timeEntry,[this].concat(f))}else{var b=null;for(attrName in $.timeEntry._defaults){var c=this.getAttribute('time:'+attrName);if(c){b=b||{};try{b[attrName]=eval(c)}catch(err){b[attrName]=c}}}var d=(d&&!b?d:new TimeEntryInstance(!b?e:$.extend(b,e)));$.timeEntry._connectTimeEntry(this,d)}}})};$(document).ready(function(){$.timeEntry=new TimeEntry()})})(jQuery); \ No newline at end of file diff --git a/pandora_console/include/javascript/jquery.ui.datepicker.js b/pandora_console/include/javascript/jquery.ui.datepicker.js new file mode 100644 index 0000000000..c1f1b3c4d5 --- /dev/null +++ b/pandora_console/include/javascript/jquery.ui.datepicker.js @@ -0,0 +1,1450 @@ +/* + * jQuery UI Datepicker + * + * Copyright (c) 2006, 2007, 2008 Marc Grabanski + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI/Datepicker + * + * Depends: + * ui.core.js + * + * Marc Grabanski (m@marcgrabanski.com) and Keith Wood (kbwood@virginbroadband.com.au). + */ + +(function($) { // hide the namespace + +/* Date picker manager. + Use the singleton instance of this class, $.datepicker, to interact with the date picker. + Settings for (groups of) date pickers are maintained in an instance object + (DatepickerInstance), allowing multiple different settings on the same page. */ + +function Datepicker() { + this.debug = false; // Change this to true to start debugging + this._nextId = 0; // Next ID for a date picker instance + this._inst = []; // List of instances indexed by ID + this._curInst = null; // The current instance in use + this._disabledInputs = []; // List of date picker inputs that have been disabled + this._datepickerShowing = false; // True if the popup picker is showing , false if not + this._inDialog = false; // True if showing within a "dialog", false if not + this.regional = []; // Available regional settings, indexed by language code + this.regional[''] = { // Default regional settings + clearText: 'Clear', // Display text for clear link + clearStatus: 'Erase the current date', // Status text for clear link + closeText: 'Close', // Display text for close link + closeStatus: 'Close without change', // Status text for close link + prevText: '<Prev', // Display text for previous month link + prevStatus: 'Show the previous month', // Status text for previous month link + nextText: 'Next>', // Display text for next month link + nextStatus: 'Show the next month', // Status text for next month link + currentText: 'Today', // Display text for current month link + currentStatus: 'Show the current month', // Status text for current month link + monthNames: ['January','February','March','April','May','June', + 'July','August','September','October','November','December'], // Names of months for drop-down and formatting + monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting + monthStatus: 'Show a different month', // Status text for selecting a month + yearStatus: 'Show a different year', // Status text for selecting a year + weekHeader: 'Wk', // Header for the week of the year column + weekStatus: 'Week of the year', // Status text for the week of the year column + dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting + dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting + dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday + dayStatus: 'Set DD as first week day', // Status text for the day of the week selection + dateStatus: 'Select DD, M d', // Status text for the date selection + dateFormat: 'mm/dd/yy', // See format options on parseDate + firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... + initStatus: 'Select a date', // Initial Status text on opening + isRTL: false // True if right-to-left language, false if left-to-right + }; + this._defaults = { // Global defaults for all the date picker instances + showOn: 'focus', // 'focus' for popup on focus, + // 'button' for trigger button, or 'both' for either + showAnim: 'show', // Name of jQuery animation for popup + defaultDate: null, // Used when field is blank: actual date, + // +/-number for offset from today, null for today + appendText: '', // Display text following the input box, e.g. showing the format + buttonText: '...', // Text for trigger button + buttonImage: '', // URL for trigger button image + buttonImageOnly: false, // True if the image appears alone, false if it appears on a button + closeAtTop: true, // True to have the clear/close at the top, + // false to have them at the bottom + mandatory: false, // True to hide the Clear link, false to include it + hideIfNoPrevNext: false, // True to hide next/previous month links + // if not applicable, false to just disable them + changeMonth: true, // True if month can be selected directly, false if only prev/next + changeYear: true, // True if year can be selected directly, false if only prev/next + yearRange: '-10:+10', // Range of years to display in drop-down, + // either relative to current year (-nn:+nn) or absolute (nnnn:nnnn) + changeFirstDay: true, // True to click on day name to change, false to remain as set + showOtherMonths: false, // True to show dates in other months, false to leave blank + showWeeks: false, // True to show week of the year, false to omit + calculateWeek: this.iso8601Week, // How to calculate the week of the year, + // takes a Date and returns the number of the week for it + shortYearCutoff: '+10', // Short year values < this are in the current century, + // > this are in the previous century, + // string value starting with '+' for current year + value + showStatus: false, // True to show status bar at bottom, false to not show it + statusForDate: this.dateStatus, // Function to provide status text for a date - + // takes date and instance as parameters, returns display text + minDate: null, // The earliest selectable date, or null for no limit + maxDate: null, // The latest selectable date, or null for no limit + speed: 'normal', // Speed of display/closure + beforeShowDay: null, // Function that takes a date and returns an array with + // [0] = true if selectable, false if not, + // [1] = custom CSS class name(s) or '', e.g. $.datepicker.noWeekends + beforeShow: null, // Function that takes an input field and + // returns a set of custom settings for the date picker + onSelect: null, // Define a callback function when a date is selected + onClose: null, // Define a callback function when the datepicker is closed + numberOfMonths: 1, // Number of months to show at a time + stepMonths: 1, // Number of months to step back/forward + rangeSelect: false, // Allows for selecting a date range on one date picker + rangeSeparator: ' - ' // Text between two dates in a range + }; + $.extend(this._defaults, this.regional['']); + this._datepickerDiv = $('
'); +} + +$.extend(Datepicker.prototype, { + /* Class name added to elements to indicate already configured with a date picker. */ + markerClassName: 'hasDatepicker', + + /* Debug logging (if enabled). */ + log: function () { + if (this.debug) + console.log.apply('', arguments); + }, + + /* Register a new date picker instance - with custom settings. */ + _register: function(inst) { + var id = this._nextId++; + this._inst[id] = inst; + return id; + }, + + /* Retrieve a particular date picker instance based on its ID. */ + _getInst: function(id) { + return this._inst[id] || id; + }, + + /* Override the default settings for all instances of the date picker. + @param settings object - the new settings to use as defaults (anonymous object) + @return the manager object */ + setDefaults: function(settings) { + extendRemove(this._defaults, settings || {}); + return this; + }, + + /* Attach the date picker to a jQuery selection. + @param target element - the target input field or division or span + @param settings object - the new settings to use for this date picker instance (anonymous) */ + _attachDatepicker: function(target, settings) { + // check for settings on the control itself - in namespace 'date:' + var inlineSettings = null; + for (attrName in this._defaults) { + var attrValue = target.getAttribute('date:' + attrName); + if (attrValue) { + inlineSettings = inlineSettings || {}; + try { + inlineSettings[attrName] = eval(attrValue); + } catch (err) { + inlineSettings[attrName] = attrValue; + } + } + } + var nodeName = target.nodeName.toLowerCase(); + var instSettings = (inlineSettings ? + $.extend(settings || {}, inlineSettings || {}) : settings); + if (nodeName == 'input') { + var inst = (inst && !inlineSettings ? inst : + new DatepickerInstance(instSettings, false)); + this._connectDatepicker(target, inst); + } else if (nodeName == 'div' || nodeName == 'span') { + var inst = new DatepickerInstance(instSettings, true); + this._inlineDatepicker(target, inst); + } + }, + + /* Detach a datepicker from its control. + @param target element - the target input field or division or span */ + _destroyDatepicker: function(target) { + var nodeName = target.nodeName.toLowerCase(); + var calId = target._calId; + target._calId = null; + var $target = $(target); + if (nodeName == 'input') { + $target.siblings('.ui-datepicker-append').replaceWith('').end() + .siblings('.ui-datepicker-trigger').replaceWith('').end() + .removeClass(this.markerClassName) + .unbind('focus', this._showDatepicker) + .unbind('keydown', this._doKeyDown) + .unbind('keypress', this._doKeyPress); + var wrapper = $target.parents('.ui-datepicker-wrap'); + if (wrapper) + wrapper.replaceWith(wrapper.html()); + } else if (nodeName == 'div' || nodeName == 'span') + $target.removeClass(this.markerClassName).empty(); + if ($('input[_calId=' + calId + ']').length == 0) + // clean up if last for this ID + this._inst[calId] = null; + }, + + /* Enable the date picker to a jQuery selection. + @param target element - the target input field or division or span */ + _enableDatepicker: function(target) { + target.disabled = false; + $(target).siblings('button.ui-datepicker-trigger').each(function() { this.disabled = false; }).end() + .siblings('img.ui-datepicker-trigger').css({opacity: '1.0', cursor: ''}); + this._disabledInputs = $.map(this._disabledInputs, + function(value) { return (value == target ? null : value); }); // delete entry + }, + + /* Disable the date picker to a jQuery selection. + @param target element - the target input field or division or span */ + _disableDatepicker: function(target) { + target.disabled = true; + $(target).siblings('button.ui-datepicker-trigger').each(function() { this.disabled = true; }).end() + .siblings('img.ui-datepicker-trigger').css({opacity: '0.5', cursor: 'default'}); + this._disabledInputs = $.map($.datepicker._disabledInputs, + function(value) { return (value == target ? null : value); }); // delete entry + this._disabledInputs[$.datepicker._disabledInputs.length] = target; + }, + + /* Is the first field in a jQuery collection disabled as a datepicker? + @param target element - the target input field or division or span + @return boolean - true if disabled, false if enabled */ + _isDisabledDatepicker: function(target) { + if (!target) + return false; + for (var i = 0; i < this._disabledInputs.length; i++) { + if (this._disabledInputs[i] == target) + return true; + } + return false; + }, + + /* Update the settings for a date picker attached to an input field or division. + @param target element - the target input field or division or span + @param name string - the name of the setting to change or + object - the new settings to update + @param value any - the new value for the setting (omit if above is an object) */ + _changeDatepicker: function(target, name, value) { + var settings = name || {}; + if (typeof name == 'string') { + settings = {}; + settings[name] = value; + } + if (inst = this._getInst(target._calId)) { + extendRemove(inst._settings, settings); + this._updateDatepicker(inst); + } + }, + + /* Set the dates for a jQuery selection. + @param target element - the target input field or division or span + @param date Date - the new date + @param endDate Date - the new end date for a range (optional) */ + _setDateDatepicker: function(target, date, endDate) { + if (inst = this._getInst(target._calId)) { + inst._setDate(date, endDate); + this._updateDatepicker(inst); + } + }, + + /* Get the date(s) for the first entry in a jQuery selection. + @param target element - the target input field or division or span + @return Date - the current date or + Date[2] - the current dates for a range */ + _getDateDatepicker: function(target) { + var inst = this._getInst(target._calId); + if (inst) { + inst._setDateFromField($(target)); + } + return (inst ? inst._getDate() : null); + }, + + /* Handle keystrokes. */ + _doKeyDown: function(e) { + var inst = $.datepicker._getInst(this._calId); + if ($.datepicker._datepickerShowing) + switch (e.keyCode) { + case 9: $.datepicker._hideDatepicker(null, ''); + break; // hide on tab out + case 13: $.datepicker._selectDay(inst, inst._selectedMonth, inst._selectedYear, + $('td.ui-datepicker-days-cell-over', inst._datepickerDiv)[0]); + return false; // don't submit the form + break; // select the value on enter + case 27: $.datepicker._hideDatepicker(null, inst._get('speed')); + break; // hide on escape + case 33: $.datepicker._adjustDate(inst, + (e.ctrlKey ? -1 : -inst._get('stepMonths')), (e.ctrlKey ? 'Y' : 'M')); + break; // previous month/year on page up/+ ctrl + case 34: $.datepicker._adjustDate(inst, + (e.ctrlKey ? +1 : +inst._get('stepMonths')), (e.ctrlKey ? 'Y' : 'M')); + break; // next month/year on page down/+ ctrl + case 35: if (e.ctrlKey) $.datepicker._clearDate(inst); + break; // clear on ctrl+end + case 36: if (e.ctrlKey) $.datepicker._gotoToday(inst); + break; // current on ctrl+home + case 37: if (e.ctrlKey) $.datepicker._adjustDate(inst, -1, 'D'); + break; // -1 day on ctrl+left + case 38: if (e.ctrlKey) $.datepicker._adjustDate(inst, -7, 'D'); + break; // -1 week on ctrl+up + case 39: if (e.ctrlKey) $.datepicker._adjustDate(inst, +1, 'D'); + break; // +1 day on ctrl+right + case 40: if (e.ctrlKey) $.datepicker._adjustDate(inst, +7, 'D'); + break; // +1 week on ctrl+down + } + else if (e.keyCode == 36 && e.ctrlKey) // display the date picker on ctrl+home + $.datepicker._showDatepicker(this); + }, + + /* Filter entered characters - based on date format. */ + _doKeyPress: function(e) { + var inst = $.datepicker._getInst(this._calId); + var chars = $.datepicker._possibleChars(inst._get('dateFormat')); + var chr = String.fromCharCode(e.charCode == undefined ? e.keyCode : e.charCode); + return e.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1); + }, + + /* Attach the date picker to an input field. */ + _connectDatepicker: function(target, inst) { + var input = $(target); + if (input.is('.' + this.markerClassName)) + return; + var appendText = inst._get('appendText'); + var isRTL = inst._get('isRTL'); + if (appendText) { + if (isRTL) + input.before('' + appendText); + else + input.after('' + appendText); + } + var showOn = inst._get('showOn'); + if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field + input.focus(this._showDatepicker); + if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked + input.wrap(''); + var buttonText = inst._get('buttonText'); + var buttonImage = inst._get('buttonImage'); + var trigger = $(inst._get('buttonImageOnly') ? + $('').addClass('ui-datepicker-trigger').attr({ src: buttonImage, alt: buttonText, title: buttonText }) : + $('