From 788db0318b159a180e87c2caf43e4a7c44b9dc0f Mon Sep 17 00:00:00 2001 From: esanchezm Date: Thu, 19 Jun 2008 09:01:12 +0000 Subject: [PATCH] 2008-06-18 Esteban Sanchez * functions.php: Added documentation to all the functions in JavaDoc format, which is an facto-standard. Deleted unused functions. Improved the code of some functions. Tab and blankspaces style correction. Replaced old lang_label with lang_string(). Some functions to print selects were replaced with a functio to get an array with all the possible values so the caller will use print_select() with them. * godmode/agentes/agent_manager.php: Use print_select() instead of deleted function. * godmode/agentes/alert_manager_editor.php: Use print_select() instead of deleted function. Use print_checkbox(). Style correction * godmode/reporting/map_builder.php, operation/agentes/ver_agente.php, operation/messages/message.php, operation/reporting/reporting_viewer_pdf.php: Replaced deleted functions with their equivalents. * include/functions_db.php: Documented some functions, some work is still required. Added get_reports() to get all the reports a user can see. Deleted unused functions. Replaced deleted functions with their equivalents. Added get_db_row_sql(), get_previous_data(). Fixed errors when calculating average, max, min and sum values of an agent module. * include/functions_reporting.php: Fixed errors when calculating SLA. * operation/events/events.php: Tab and blankspaces correction. Replaced form_priority with print_select(). Style correction. * operation/reporting/custom_reporting.php: Show all the reports a user can see. Use Pandora functions. * operation/reporting/reporting_viewer.php: Show unknown label if SLA can not be calculated. * operation/snmpconsole/snmp_alert.php: Avoid an extra indentation level by using check_login() properly. Tab and blankspaces correction. * index.php, operation/users/user_edit.php: Adopted to renamed function. * godmode/db/db_sanity.php, reporting/fgraph.php: Style correction. git-svn-id: https://svn.code.sf.net/p/pandora/code/trunk@881 c3f86ba8-e40f-0410-aaad-9ba5e7f4b01f --- pandora_console/ChangeLog | 90 +- .../godmode/agentes/agent_manager.php | 21 +- .../godmode/agentes/alert_manager_editor.php | 326 +++--- pandora_console/godmode/db/db_sanity.php | 39 +- .../godmode/reporting/map_builder.php | 44 +- pandora_console/include/functions.php | 959 +++++++++--------- pandora_console/include/functions_db.php | 728 +++++++------ .../include/functions_reporting.php | 55 +- pandora_console/index.php | 8 +- .../operation/agentes/ver_agente.php | 2 +- pandora_console/operation/events/events.php | 341 +++---- .../operation/messages/message.php | 14 +- .../operation/reporting/custom_reporting.php | 68 +- .../operation/reporting/reporting_viewer.php | 38 +- .../reporting/reporting_viewer_pdf.php | 2 +- .../operation/snmpconsole/snmp_alert.php | 629 ++++++------ pandora_console/operation/users/user_edit.php | 4 +- pandora_console/reporting/fgraph.php | 1 - 18 files changed, 1788 insertions(+), 1581 deletions(-) diff --git a/pandora_console/ChangeLog b/pandora_console/ChangeLog index 65a1e633bc..c48fce3d3a 100644 --- a/pandora_console/ChangeLog +++ b/pandora_console/ChangeLog @@ -1,38 +1,82 @@ +2008-06-18 Esteban Sanchez + + * functions.php: Added documentation to all the functions in JavaDoc + format, which is an facto-standard. Deleted unused functions. Improved + the code of some functions. Tab and blankspaces style correction. + Replaced old lang_label with lang_string(). Some functions to print + selects were replaced with a functio to get an array with all the + possible values so the caller will use print_select() with them. + + * godmode/agentes/agent_manager.php: Use print_select() instead of + deleted function. + + * godmode/agentes/alert_manager_editor.php: Use print_select() instead + of deleted function. Use print_checkbox(). Style correction + + * godmode/reporting/map_builder.php, operation/agentes/ver_agente.php, + operation/messages/message.php, + operation/reporting/reporting_viewer_pdf.php: + Replaced deleted functions with their equivalents. + + * include/functions_db.php: Documented some functions, some work is + still required. Added get_reports() to get all the reports a user can + see. Deleted unused functions. Replaced deleted functions with their + equivalents. Added get_db_row_sql(), get_previous_data(). Fixed errors + when calculating average, max, min and sum values of an agent module. + + * include/functions_reporting.php: Fixed errors when calculating SLA. + + * operation/events/events.php: Tab and blankspaces correction. + Replaced form_priority with print_select(). Style correction. + + * operation/reporting/custom_reporting.php: Show all the reports a + user can see. Use Pandora functions. + + * operation/reporting/reporting_viewer.php: Show unknown label if SLA + can not be calculated. + + * operation/snmpconsole/snmp_alert.php: Avoid an extra indentation + level by using check_login() properly. Tab and blankspaces correction. + + * index.php, operation/users/user_edit.php: Adopted to renamed + function. + + * godmode/db/db_sanity.php, reporting/fgraph.php: Style correction. 2008-06-18 Sancho Lerena - - * pandoradbdata_13_to_20.sql: prototype. not functional. - * operation/events/export_csv.php: Event export to CSV. Support - passed filters. + * pandoradbdata_13_to_20.sql: prototype. not functional. - * images/networkmap/*.png: Updated icons for network map. + * operation/events/export_csv.php: Event export to CSV. Support passed + filters. - * godmode/menu.php, - * godmode/db/db_sanity.php: New sanity tool for database in interactive - mode using console (ported from pandora_db.pl). + * images/networkmap/*.png: Updated icons for network map. - * reporting/fgraph.php: Added graphs for string data types. Fixed - event by agent/module graph for system events. + * godmode/menu.php, godmode/db/db_sanity.php: New sanity tool for + database in interactive mode using console (ported from + pandora_db.pl). - * general/logon_ok.php, tactica.php: Fixed a div0. + * reporting/fgraph.php: Added graphs for string data types. Fixed + event by agent/module graph for system events. - * godmode/agentes/manage_config.php: Several fixes, and added a new - option to mass-deletion of agents. + * general/logon_ok.php, tactica.php: Fixed a div0. - * godmode/agentes/agent_manager.php, - godmode/agentes/modificar_agente.php: Delete of remote configuration - when delete an agent and manually, by user. + * godmode/agentes/manage_config.php: Several fixes, and added a new + option to mass-deletion of agents. - * operation/servers/view_server_detail.php: Added refresh option and - fixed layout. + * godmode/agentes/agent_manager.php, + godmode/agentes/modificar_agente.php: Delete of remote configuration + when delete an agent and manually, by user.. - * status_monitor.php: Added new filter by state, most code rewritten. - Added pagination fixes, and corrected labels and legends. + * operation/servers/view_server_detail.php: Added refresh option and + fixed layout. - * operation/agentes/networkmap.php: Several fixes and modification to - render small maps and huge (>200 agents) maps. This should be fine by - now. Need "Group/Section" drawing /by click into section line/. + * status_monitor.php: Added new filter by state, most code rewritten. + Added pagination fixes, and corrected labels and legends. + + * operation/agentes/networkmap.php: Several fixes and modification to + render small maps and huge (>200 agents) maps. This should be fine by + now. Need "Group/Section" drawing /by click into section line/. 2008-06-18 Esteban Sanchez diff --git a/pandora_console/godmode/agentes/agent_manager.php b/pandora_console/godmode/agentes/agent_manager.php index a4ad17d6c4..3ebc9fb6ad 100644 --- a/pandora_console/godmode/agentes/agent_manager.php +++ b/pandora_console/godmode/agentes/agent_manager.php @@ -70,14 +70,14 @@ echo ''.$lang_label["agent_name"].' '; -if ((isset($id_agente)) && ($id_agente != "")){ +if (isset ($id_agente) && $id_agente != "") { echo " "; } // Remote configuration available -if (file_exists($config["remote_config"] . "/" . $agent_md5 . ".md5")) { +if (file_exists ($config["remote_config"] . "/" . $agent_md5 . ".md5")) { echo " "; @@ -88,7 +88,7 @@ echo ''.$lang_label["ip_address"].''; echo ''; echo ''; -if ($create_agent != 1){ +if ($create_agent != 1) { echo "    "; echo ''; @@ -242,11 +243,11 @@ echo ''.lang_string("Remote configuration").''; echo ''; $filename = $config["remote_config"] . "/" . $agent_md5 . ".md5"; if (file_exists($filename)){ - echo date("F d Y H:i:s.", fileatime($filename)); + echo date("F d Y H:i:s.", fileatime($filename)); // Delete remote configuration echo ""; } else { - echo ''.lang_string("Not available").''; + echo ''.lang_string("Not available").''; } echo '
'; diff --git a/pandora_console/godmode/agentes/alert_manager_editor.php b/pandora_console/godmode/agentes/alert_manager_editor.php index 83c6c9c2e9..90abbd62f8 100644 --- a/pandora_console/godmode/agentes/alert_manager_editor.php +++ b/pandora_console/godmode/agentes/alert_manager_editor.php @@ -1,5 +1,4 @@ - -".$lang_label["alert_asociation_form"].""; echo '
'; if ($form_alerttype == "combined") - echo ""; + echo ""; else - echo ""; + echo ""; if (! isset($update_alert)) - $update_alert = -1; - + $update_alert = -1; + if ($update_alert != 1) { - echo ''; + echo ''; } else { - echo ''; - echo ''; + echo ''; + echo ''; } echo ''; @@ -46,48 +45,48 @@ echo '
'.lang_string("assigned_module"); echo ''; if ($form_alerttype != "combined"){ - if ($update_alert != 1) { - echo '"; - } else { - $agentmodule_name = get_db_sql ("SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = $alerta_id_agentemodulo"); - echo $agentmodule_name; - } + if ($update_alert != 1) { + echo '"; + } else { + $agentmodule_name = get_db_sql ("SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = $alerta_id_agentemodulo"); + echo $agentmodule_name; + } } else { - echo lang_string ("N/A"); + echo lang_string ("N/A"); } echo ''; echo lang_string ("Priority"); echo ''; -if (isset($alert_priority)){ - $alert_priority = 3; // Warning by default +if (! isset($alert_priority)) { + $alert_priority = 3; // Warning by default } -echo form_priority ($alert_priority, "alert_priority"); +print_select (get_priorities (), "alert_priority", $alert_priority, '', '', ''); // Alert type echo '
'; echo $lang_label["alert_type"]; echo '"; @@ -97,11 +96,11 @@ echo $lang_label["alert_status"]; echo ""; echo '"; @@ -111,22 +110,22 @@ echo ''.$lang_label["min_value"]; - echo " ";echo $lang_label["min_valid_value_help"].""; - echo ''; + echo '
'.$lang_label["min_value"]; + echo " ";echo $lang_label["min_valid_value_help"].""; + echo ''; - echo ""; - echo $lang_label["max_value"]; - echo " "; - echo $lang_label["max_valid_value_help"]; - echo ""; - echo ""; - echo ""; + echo ""; + echo $lang_label["max_value"]; + echo " "; + echo $lang_label["max_valid_value_help"]; + echo ""; + echo ""; + echo ""; - // + // - echo '
'.$lang_label["alert_text"]." NOTE: This field is for matching text on data. Regular Expression Supported "; - echo ''; + echo '
'.$lang_label["alert_text"]." NOTE: This field is for matching text on data. Regular Expression Supported "; + echo ''; } // Time Threshold (TT) @@ -135,7 +134,7 @@ echo " ".$lang_label["alert_time_threshold_he echo ''; echo '
".$lang_label["min_alerts"]; echo ''; echo ''; echo ''; @@ -172,9 +171,9 @@ echo $lang_label["max_alerts"]; echo ''; echo ''; // Field1 @@ -202,14 +201,14 @@ echo '_timestamp_
_data_
'; echo "
".$lang_label["time_from"]; echo ""; @@ -217,43 +216,41 @@ echo ""; echo "".$lang_label["time_to"]; echo ""; - + // Days of week echo "
".lang_string ("Days of week"); echo ""; echo lang_string("Mon"); -echo form_render_check ("alert_d1", $alert_d1); +print_checkbox ("alert_d1", 1, $alert_d1); echo "  "; echo lang_string("Tue"); -echo form_render_check ("alert_d2", $alert_d2); +print_checkbox ("alert_d2", 1, $alert_d2); echo "  "; echo lang_string("Wed"); -echo form_render_check ("alert_d3", $alert_d3); +print_checkbox ("alert_d3", 1, $alert_d3); echo "  "; echo lang_string("Thu"); -echo form_render_check ("alert_d4", $alert_d4); +print_checkbox ("alert_d4", 1, $alert_d4); echo "  "; echo lang_string("Fri"); -echo form_render_check ("alert_d5", $alert_d5); +print_checkbox ("alert_d5", 1, $alert_d5); echo "  "; echo lang_string("Sat"); -echo form_render_check ("alert_d6", $alert_d6); +print_checkbox ("alert_d6", 1, $alert_d6); echo "  "; echo lang_string("Sun"); -echo form_render_check ("alert_d7", $alert_d7); - - +print_checkbox ("alert_d7", 1, $alert_d7); // Field2 Recovery echo '
'.lang_string ("Field #2 (Rec)"); @@ -266,11 +263,11 @@ echo lang_string ("Alert recovery"); echo ""; echo '"; @@ -285,56 +282,56 @@ echo '
"; echo ''; echo '
'; - if ($update_alert== "1"){ - echo ''; - } else { - echo ''; - } - echo ''; +if ($update_alert== "1"){ + echo ''; +} else { + echo ''; +} +echo ''; echo '
'; if (($form_alerttype == "combined") AND ($update_alert != -1)){ - echo "

".lang_string ("Combined alert components")."

"; - echo ''; - echo ''; - - if ($form_alerttype == "combined") - echo ""; - else - echo ""; - - echo ''; - echo ''; + echo "

".lang_string ("Combined alert components")."

"; + echo '
'; + echo ''; - echo "
"; - echo lang_string ("Source Agent/Alert"); - echo ""; - echo ""; + else + echo ""; + + echo ''; + echo ''; + + echo "
"; + echo lang_string ("Source Agent/Alert"); + echo ""; + echo ""; + echo ""; // there is any component already in this alert ? $result = mysql_query ("SELECT COUNT(*) FROM tcompound_alert, talerta_agente_modulo WHERE tcompound_alert.id = $id_aam AND talerta_agente_modulo.id_aam = tcompound_alert.id_aam"); - $row=mysql_fetch_array($result); + $row=mysql_fetch_array($result); if ($row[0] > 0){ echo ""; echo lang_string ("Operation"); @@ -351,60 +348,57 @@ if (($form_alerttype == "combined") AND ($update_alert != -1)){ echo ""; } echo ""; - echo ''; - echo ""; - echo "
"; + echo ''; + echo ""; + echo "
"; - echo ''; - echo ''; - echo ' - - - - - - - - "; + echo '
'.lang_string ("agent"); - echo ''.lang_string ("module"); - echo "".$lang_label["type"]."".lang_string ("Oper")."".$lang_label["threshold"]."".$lang_label["min."]."".$lang_label["max."]."".$lang_label["time"]."".$lang_label["description"]."".lang_string ("info")."".$lang_label["action"]."
'; + echo ''; + echo ' + + + + + + + + "; - $id_aam = $alerta_id_aam; - $sql2 = "SELECT * FROM tcompound_alert, talerta_agente_modulo WHERE tcompound_alert.id = $id_aam AND talerta_agente_modulo.id_aam = tcompound_alert.id_aam"; - $result2=mysql_query($sql2); - $string = ""; - $color = 1; + $id_aam = $alerta_id_aam; + $sql2 = "SELECT * FROM tcompound_alert, talerta_agente_modulo WHERE tcompound_alert.id = $id_aam AND talerta_agente_modulo.id_aam = tcompound_alert.id_aam"; + $result2=mysql_query($sql2); + $string = ""; + $color = 1; - while ($row2=mysql_fetch_array($result2)){ - // Show data for each component of this combined alert - if ($color == 1){ - $tdcolor="datos"; - $color =0; - } else { - $tdcolor="datos2"; - $color =1; - } - $module = get_db_row ("tagente_modulo", "id_agente_modulo", $row2["id_agente_modulo"]); - $description = $row2["descripcion"]; - $alert_mode = $row2["operation"]; - $id_agente_name = get_db_value ("nombre", "tagente", "id_agente", $module["id_agente"]); + while ($row2=mysql_fetch_array($result2)) { + // Show data for each component of this combined alert + if ($color == 1){ + $tdcolor="datos"; + $color =0; + } else { + $tdcolor="datos2"; + $color =1; + } + $module = get_db_row ("tagente_modulo", "id_agente_modulo", $row2["id_agente_modulo"]); + $description = $row2["descripcion"]; + $alert_mode = $row2["operation"]; + $id_agente_name = get_db_value ("nombre", "tagente", "id_agente", $module["id_agente"]); - echo ""; - echo ""; - } - echo "
'.lang_string ("agent"); + echo ''.lang_string ("module"); + echo "".$lang_label["type"]."".lang_string ("Oper")."".$lang_label["threshold"]."".$lang_label["min."]."".$lang_label["max."]."".$lang_label["time"]."".$lang_label["description"]."".lang_string ("info")."".$lang_label["action"]."
".$id_agente_name; - echo "".$module["nombre"]; - echo show_alert_row_edit ($row2, $tdcolor, $module["id_tipo_modulo"],1); - echo ""; - $id_grupo = dame_id_grupo($id_agente); - if (give_acl($id_user, $id_grupo, "LW")==1){ - echo " ".$lang_label["delete"]."   "; - echo " - ".$lang_label["update"].""; - } - echo "
"; + echo ""; + echo "".$id_agente_name; + echo "".$module["nombre"]; + echo show_alert_row_edit ($row2, $tdcolor, $module["id_tipo_modulo"],1); + echo ""; + $id_grupo = dame_id_grupo($id_agente); + if (give_acl($id_user, $id_grupo, "LW")==1){ + echo " ".$lang_label["delete"]."   "; + echo " + ".$lang_label["update"].""; + } + echo ""; + } + echo ""; } - - - -?> \ No newline at end of file +?> diff --git a/pandora_console/godmode/db/db_sanity.php b/pandora_console/godmode/db/db_sanity.php index 812103245e..0d7ec4c771 100644 --- a/pandora_console/godmode/db/db_sanity.php +++ b/pandora_console/godmode/db/db_sanity.php @@ -27,13 +27,13 @@ echo "

".lang_string("Database sanity tool")."

"; $sanity = get_parameter ("sanity", 0); -if ($sanity == 1){ +if ($sanity == 1) { // Create tagente estado when missing // ---------------------------------- - echo "

".lang_string("Checking tagente_estado table")."

"; + echo "

".lang_string ("Checking tagente_estado table")."

"; $sql = "SELECT * FROM tagente_modulo"; - $result=mysql_query($sql); - while ($row=mysql_fetch_array($result)){ + $result = mysql_query ($sql); + while ($row = mysql_fetch_array ($result)) { $id_agente_modulo = $row[0]; $id_agente = $row["id_agente"]; // check if exist in tagente_estado and create if not @@ -49,37 +49,36 @@ if ($sanity == 1){ echo "

".lang_string("Checking database consistency")."

"; $query1 = "SELECT * FROM tagente_estado"; - $result=mysql_query($query1); - while ($row=mysql_fetch_array($result)){ + $result = mysql_query($query1); + while ($row = mysql_fetch_array ($result)) { $id_agente_modulo = $row[1]; # check if exist in tagente_estado and create if not $query2 = "SELECT COUNT(*) FROM tagente_modulo WHERE id_agente_modulo = $id_agente_modulo"; - $result2=mysql_query($query2); - $row2=mysql_fetch_array($result2); - if ($row2[0] == 0){ + $result2 = mysql_query ($query2); + $row2 = mysql_fetch_array ($result2); + if ($row2[0] == 0) { $query3 = "DELETE FROM tagente_estado WHERE id_agente_modulo = $id_agente_modulo"; echo "Deleting non-existing module $id_agente_modulo in state table
"; mysql_query($query3); } } -} -elseif ($sanity == 2){ +} elseif ($sanity == 2) { echo "

".lang_string("Deleting non-init data")."

"; $query1 = "SELECT * FROM tagente_estado WHERE utimestamp = 0"; - $result=mysql_query($query1); - while ($row=mysql_fetch_array($result)){ + $result = mysql_query ($query1); + while ($row = mysql_fetch_array ($result)) { $id_agente_modulo = $row[1]; - $query0 = "DELETE FROM tagente_modulo WHERE id_agente_modulo = $id_agente_modulo"; - $query1 = "DELETE FROM tagente_estado WHERE id_agente_modulo = $id_agente_modulo"; echo "Deleting non init module $id_agente_modulo
"; - mysql_query($query0); - mysql_query($query1); + $sql = "DELETE FROM tagente_modulo WHERE id_agente_modulo = $id_agente_modulo"; + mysql_query ($sql); + $sql = "DELETE FROM tagente_estado WHERE id_agente_modulo = $id_agente_modulo"; + mysql_query ($sql); } } echo "
"; echo "
"; -echo lang_string("Pandora FMS Sanity tool is used to remove bad database structure data, created modules with missing status, or modules that cannot be initialized (and don't report any valid data) but retry each it's own interval to get data. This kind of bad modules could degrade performance of Pandora FMS. This database sanity tool is also implemented in the pandora_db.pl that you should be running each day or week. This console sanity DONT compact your database, only delete bad structured data."); +echo lang_string ("Pandora FMS Sanity tool is used to remove bad database structure data, created modules with missing status, or modules that cannot be initialized (and don't report any valid data) but retry each it's own interval to get data. This kind of bad modules could degrade performance of Pandora FMS. This database sanity tool is also implemented in the pandora_db.pl that you should be running each day or week. This console sanity DONT compact your database, only delete bad structured data."); echo "

"; echo ""; @@ -91,11 +90,11 @@ echo ""; echo "

"; echo ""; echo "  "; -echo lang_string("Delete non-initialized modules now"); +echo lang_string ("Delete non-initialized modules now"); echo ""; echo "
"; -?> \ No newline at end of file +?> diff --git a/pandora_console/godmode/reporting/map_builder.php b/pandora_console/godmode/reporting/map_builder.php index c327762cae..b8d432c526 100644 --- a/pandora_console/godmode/reporting/map_builder.php +++ b/pandora_console/godmode/reporting/map_builder.php @@ -1,4 +1,4 @@ -".$lang_label["create_ok"].""; diff --git a/pandora_console/include/functions.php b/pandora_console/include/functions.php index 74554ed8f2..21639e58f9 100644 --- a/pandora_console/include/functions.php +++ b/pandora_console/include/functions.php @@ -18,190 +18,138 @@ require ('functions_html.php'); -function pandora_help ($id, $return = false) { +/** + * Prints a help tip icon. + * + * @param id Help id + * @param return Flag to return or output the result + * + * @return The help tip if return flag was active. + */ +function pandora_help ($help_id, $return = false) { global $config; - $output = ''; + $output = ''; if ($return) return $return; echo $output; } -// --------------------------------------------------------------- -// safe_output() -// Write a string to screen, deleting all kind of problematic characters -// This should be safe for XSS. -// --------------------------------------------------------------- - -function safe_output ($string) { - return preg_replace('/[^\x09\x0A\x0D\x20-\x7F]/e', '"&#".ord($0).";"', $string); -} - -// --------------------------------------------------------------- -// safe_input() -// Get parameter, using UTF8 encoding, and cleaning bad codes -// --------------------------------------------------------------- +/** + * Cleans a string by decoding from UTF-8 and replacing the HTML + * entities. + * + * @param value String to be cleaned. + * + * @return The string cleaned. + */ function safe_input ($value) { if (is_numeric ($value)) return $value; return htmlentities (utf8_decode ($value), ENT_QUOTES); } -// --------------------------------------------------------------- -// salida_sql: Parse \' for replace to ' character, prearing -// SQL sentences to execute. -// --------------------------------------------------------------- - -function salida_sql ($string) { - return mysql_escape_string ($string); -} - - -// input: var, string. -// mesg, mesage to show, var content. -// --------------------------------------------------------------- - -function midebug($var, $mesg){ - echo "[DEBUG (".$var."]: (".$mesg.")"; - echo "
"; +/** + * Pandora debug functions. + * + * It prints a variable value and a message. + * + * @param var Variable to be displayed + * @param mesg Message to be displayed + */ +function pandora_debug ($var, $msg) { + echo "[Pandora DEBUG (".$var."]: (".$msg.")
"; } -// --------------------------------------------------------------- -// array_in -// Search "item" in a given array, return 1 if exists, 0 if not -// --------------------------------------------------------------- - -function array_in($exampleArray, $item){ - $result = 0; - foreach ($exampleArray as $key => $value){ - if ($value == $item){ - $result = 1; - } - } - return $result; -} - - -// --------------------------------------------------------------- -// parse and clear string -// --------------------------------------------------------------- - -function salida_limpia ($string){ - $quote_style=ENT_QUOTES; +/** + * Clean a string. + * + * @param string + * + * @return + */ +function salida_limpia ($string) { + $quote_style = ENT_QUOTES; static $trans; - if (!isset($trans)) { - $trans = get_html_translation_table(HTML_ENTITIES, $quote_style); + if (! isset ($trans)) { + $trans = get_html_translation_table (HTML_ENTITIES, $quote_style); foreach ($trans as $key => $value) $trans[$key] = '&#'.ord($key).';'; // dont translate the '&' in case it is part of &xxx; $trans[chr(38)] = '&'; } - // after the initial translation, _do_ map standalone '&' into '&' + // after the initial translation, _do_ map standalone "&" into "&" return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&" , strtr($string, $trans)); } +/** + * + * + * @param string + * + * @return + */ function clean_output_breaks ($string){ $myoutput = salida_limpia($string); return preg_replace ('/\n/',"
", $myoutput); } - -function output_clean_strict ($string){ - $string = preg_replace('/[\|\@\$\%\/\(\)\=\?\*\&\#]/','',$string); - return $string; +/** + * Cleans a string to be shown in a graphic. + * + * @param string String to be cleaned + * + * @return String with special characters cleaned. + */ +function output_clean_strict ($string) { + return preg_replace ('/[\|\@\$\%\/\(\)\=\?\*\&\#]/', '', $string); } -// --------------------------------------------------------------- -// This function reads a string and returns it "clean" -// for use in DB, againts string XSS and so on -// --------------------------------------------------------------- -function entrada_limpia ($texto){ - $filtro0 = utf8_decode($texto); - $filtro1 = htmlentities($filtro0, ENT_QUOTES); - return $filtro1; +/** + * WARNING: Deprecated function, use safe_input. Keep from compatibility. + */ +function entrada_limpia ($string) { + return safe_input ($string); } -// --------------------------------------------------------------- -// Esta funcion lee una cadena y la da "limpia", para su uso con -// parametros pasados a funcion de abrir fichero. Usados en sec y sec2 -// --------------------------------------------------------------- - -function parametro_limpio($texto){ - // Metemos comprobaciones de seguridad para los includes de paginas pasados por parametro - // Gracias Raul (http://seclists.org/lists/incidents/2004/Jul/0034.html) - // Consiste en purgar los http:// de las cadenas - $pos = strpos($texto,"://"); // quitamos la parte "fea" de http:// o ftp:// o telnet:// :-))) - if ($pos <> 0) - $texto = substr_replace($texto,"",$pos,+3); - // limitamos la entrada de datos por parametros a 125 caracteres - $texto = substr_replace($texto,"",125); - $safe = preg_replace('/[^a-z0-9_\/]/i','',$texto); - return $safe; +/** + * Performs an extra clean to a string. + * + * It's useful on sec and sec2 index parameters, to avoid the use of + * malicious parameters. The string is also stripped to 125 charactes. + * + * @param string String to clean + * + * @return + */ +function parameter_extra_clean ($string) { + /* Clean "://" from the strings + See: http://seclists.org/lists/incidents/2004/Jul/0034.html + */ + $pos = strpos ($string, "://"); + if ($pos != 0) + $string = substr_replace ($string, "", $pos, +3); + /* Strip the string to 125 characters */ + $string = substr_replace ($string, "", 125); + return preg_replace ('/[^a-z0-9_\/]/i', '', $string); } -// --------------------------------------------------------------- -// Esta funcion se supone que cierra todos los tags HTML abiertos y no cerrados -// --------------------------------------------------------------- - -// string closeOpenTags(string string [, string beginChar [, stringEndChar [, string CloseChar]]]); - -function closeOpenTags ($str, $open = "<", $close = ">", $end = "/", $tokens = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") -{ $chars = array(); - for ($i = 0; $i < strlen($tokens); $i++) - { $chars[] = substr($tokens, $i, 1); } - - $openedTags = array(); - $closedTags = array(); - $tag = FALSE; - $closeTag = FALSE; - $tagName = ""; - - for ($i = 0; $i < strlen($str); $i++) - { $char = substr($str, $i, 1); - if ($char == $open) - { $tag = TRUE; continue; } - if ($char == $end) - { $closeTag = TRUE; continue; } - if ($tag && in_array($char, $chars)) - { $tagName .= $char; } - else - {if ($closeTag) - {if (isset($closedTags[$tagName])) - { $closedTags[$tagName]++; } - else - { $closedTags[$tagName] = 1; } } - elseif ($tag) - {if (isset($openedTags[$tagName])) - { $openedTags[$tagName]++; } - else - { $openedTags[$tagName] = 1; } } - $tag = FALSE; $closeTag = FALSE; $tagName = ""; } - } - - while(list($tag, $count) = each($openedTags)) - { - $closedTags[$tag] = isset($closedTags[$tag]) ? $closedTags[$tag] : 0; - $count -= $closedTags[$tag]; - if ($count < 1) continue; - $str .= str_repeat($open.$end.$tag.$close, $count); - } - return $str; - - } - -// --------------------------------------------------------------- -// Return string with time-threshold in secs, mins, days or weeks -// --------------------------------------------------------------- - -function give_human_time ($int_seconds){ +/** + * Get a human readable string with a time threshold in seconds, + * minutes, days or weeks. + * + * @param int_seconds + * + * @return + */ +function give_human_time ($int_seconds) { $key_suffix = 's'; - $periods = array('year' => 31556926, - 'month' => 2629743, - 'day' => 86400, - 'hour' => 3600, - 'minute' => 60, - 'second' => 1 - ); + $periods = array('year' => 31556926, + 'month' => 2629743, + 'day' => 86400, + 'hour' => 3600, + 'minute' => 60, + 'second' => 1); // used to hide 0's in higher periods $flag_hide_zero = true; @@ -214,50 +162,54 @@ function give_human_time ($int_seconds){ // determine if temp qualifies to be passed to output if( !$flag_hide_zero || $temp > 0 ) { // store in an array - $build[] = $temp.' '.$key.($temp!=1?'s':null); + $build[] = $temp.' '.$key.($temp != 1 ? 's' : null); // set flag to false, to allow 0's in lower periods - $flag_hide_zero = true; + $flag_hide_zero = false; } // get the remainder of seconds - $int_seconds = fmod($int_seconds, $length); + $int_seconds = fmod ($int_seconds, $length); } // return output, if !empty, implode into string, else output $if_reached - return ( !empty($build)?implode(', ', $build):$if_reached ); + return (!empty ($build) ? implode (', ', $build) : $if_reached); } -// --------------------------------------------------------------- -// This function show a popup window using a help_id (unused) -// --------------------------------------------------------------- - -function popup_help ($help_id){ - echo "[H]"; +/** + * Add a help link to show help in a popup window. + * + * @param help_id Help id to be shown when clicking. + */ +function popup_help ($help_id, $return = false) { + $output = "[H]"; + if ($return) + return $output; + echo $output; } -// --------------------------------------------------------------- -// no_permission () - Display no perm. access -// --------------------------------------------------------------- - +/** + * Prints a no permission generic error message. + */ function no_permission () { require("config.php"); require ("include/languages/language_".$config["language"].".php"); - echo "

".$lang_label["no_permission_title"]."

"; + echo "

".lang_string ('no_permission_title')."

"; echo "No access

"; echo ""; echo "
"; - echo $lang_label["no_permission_text"]; + echo lang_string ('no_permission_text'); echo "
"; echo ""; include "general/footer.php"; exit; } -// --------------------------------------------------------------- -// unmanaged_error - Display generic error message and stop execution -// --------------------------------------------------------------- - +/** + * Prints a generic error message for some unhandled error. + * + * @param error Aditional error string to be shown. Blank by default + */ function unmanaged_error ($error = "") { require("config.php"); require ("include/languages/language_".$config["language"].".php"); @@ -274,7 +226,17 @@ function unmanaged_error ($error = "") { exit; } -function list_files($directory, $stringSearch, $searchHandler, $outputHandler) { +/** + * List files in a directory in the local path. + * + * @param directory Local path. + * @param stringSearch String to match the values. + * @param searchHandler Pattern of files to match. + * @param return Flag to print or return the list. + * + * @return The list if $return parameter is true. + */ +function list_files ($directory, $stringSearch, $searchHandler, $return) { $errorHandler = false; $result = array(); if (! $directoryHandler = @opendir ($directory)) { @@ -297,19 +259,25 @@ function list_files($directory, $stringSearch, $searchHandler, $outputHandler) { echo ("
\nerror: no filetype \"$fileExtension\" found!\n
\n"); } else { sort ($result); - if ($outputHandler == 0) { + if ($return == 0) { return $result; } - if ($outputHandler == 1) { - echo ("
\n");
-			print_r ($result);
-			echo ("
\n"); - } + echo ("
\n");
+		print_r ($result);
+		echo ("
\n"); } } - -function pagination ($count, $url, $offset ) { +/** + * Prints a pagination menu to browse into a collection of data. + * + * @param count Number of elements in the collection. + * @param url URL of the pagination links. It must include all form values as GET form. + * @param offset Current offset for the pagination + * + * @return It returns nothing, it prints the pagination. + */ +function pagination ($count, $url, $offset) { global $config; require ("include/languages/language_".$config["language"].".php"); @@ -321,234 +289,261 @@ function pagination ($count, $url, $offset ) { */ $block_limit = 15; // Visualize only $block_limit blocks - if ($count > $config["block_size"]){ - // If exists more registers than I can put in a page, calculate index markers - $index_counter = ceil($count/$config["block_size"]); // Number of blocks of block_size with data - $index_page = ceil($offset/$config["block_size"])-(ceil($block_limit/2)); // block to begin to show data; - if ($index_page < 0) - $index_page = 0; + if ($count <= $config["block_size"]) { + return; + } + // If exists more registers than I can put in a page, calculate index markers + $index_counter = ceil($count/$config["block_size"]); // Number of blocks of block_size with data + $index_page = ceil($offset/$config["block_size"])-(ceil($block_limit/2)); // block to begin to show data; + if ($index_page < 0) + $index_page = 0; - // This calculate index_limit, block limit for this search. - if (($index_page + $block_limit) > $index_counter) - $index_limit = $index_counter; - else - $index_limit = $index_page + $block_limit; + // This calculate index_limit, block limit for this search. + if (($index_page + $block_limit) > $index_counter) + $index_limit = $index_counter; + else + $index_limit = $index_page + $block_limit; - // This calculate if there are more blocks than visible (more than $block_limit blocks) - if ($index_counter > $block_limit ) - $paginacion_maxima = 1; // If maximum blocks ($block_limit), show only 10 and "...." - else - $paginacion_maxima = 0; + // This calculate if there are more blocks than visible (more than $block_limit blocks) + if ($index_counter > $block_limit ) + $paginacion_maxima = 1; // If maximum blocks ($block_limit), show only 10 and "...." + else + $paginacion_maxima = 0; - // This setup first block of query - if ( $paginacion_maxima == 1) - if ($index_page == 0) - $inicio_pag = 0; - else - $inicio_pag = $index_page; - else + // This setup first block of query + if ( $paginacion_maxima == 1) + if ($index_page == 0) $inicio_pag = 0; + else + $inicio_pag = $index_page; + else + $inicio_pag = 0; - echo "
"; - // Show GOTO FIRST button - echo ''; - echo ""; - echo ""; - echo " "; - // Show PREVIOUS button - if ($index_page > 0){ - $index_page_prev= ($index_page-(floor($block_limit/2)))*$config["block_size"]; - if ($index_page_prev < 0) - $index_page_prev = 0; - echo ''; + echo "
"; + // Show GOTO FIRST button + echo ''; + echo ""; + echo ""; + echo " "; + // Show PREVIOUS button + if ($index_page > 0){ + $index_page_prev= ($index_page-(floor($block_limit/2)))*$config["block_size"]; + if ($index_page_prev < 0) + $index_page_prev = 0; + echo ''; + } + echo " ";echo " "; + // Draw blocks markers + // $i stores number of page + for ($i = $inicio_pag; $i < $index_limit; $i++) { + $inicio_bloque = ($i * $config["block_size"]); + $final_bloque = $inicio_bloque + $config["block_size"]; + if ($final_bloque > $count){ // if upper limit is beyond max, this shouldnt be possible ! + $final_bloque = ($i-1)*$config["block_size"] + $count-(($i-1) * $config["block_size"]); } - echo " ";echo " "; - // Draw blocks markers - // $i stores number of page - for ($i = $inicio_pag; $i < $index_limit; $i++) { - $inicio_bloque = ($i * $config["block_size"]); - $final_bloque = $inicio_bloque + $config["block_size"]; - if ($final_bloque > $count){ // if upper limit is beyond max, this shouldnt be possible ! - $final_bloque = ($i-1)*$config["block_size"] + $count-(($i-1) * $config["block_size"]); - } - echo ""; + echo ""; - $inicio_bloque_fake = $inicio_bloque + 1; - // To Calculate last block (doesnt end with round data, - // it must be shown if not round to block limit) - echo ''; - if ($inicio_bloque == $offset) - echo "[ $i ]"; - else - echo "[ $i ]"; - echo ' '; - echo ""; - } - echo " ";echo " "; - // Show NEXT PAGE (fast forward) - // Index_counter stores max of blocks - if (($paginacion_maxima == 1) AND (($index_counter - $i) > 0)) { - $prox_bloque = ($i+ceil($block_limit/2))*$config["block_size"]; - if ($prox_bloque > $count) - $prox_bloque = ($count -1) - $config["block_size"]; - echo ''; - echo " "; - $i = $index_counter; - } - // if exists more registers than i can put in a page (defined by $block_size config parameter) - // get offset for index calculation - // Draw "last" block link, ajust for last block will be the same - // as painted in last block (last integer block). - if (($count - $config["block_size"]) > 0){ - $myoffset = floor(($count-1)/ $config["block_size"])* $config["block_size"]; - echo ''; - echo ""; - echo ""; - } + $inicio_bloque_fake = $inicio_bloque + 1; + // To Calculate last block (doesnt end with round data, + // it must be shown if not round to block limit) + echo ''; + if ($inicio_bloque == $offset) + echo "[ $i ]"; + else + echo "[ $i ]"; + echo ' '; + echo ""; + } + echo " ";echo " "; + // Show NEXT PAGE (fast forward) + // Index_counter stores max of blocks + if (($paginacion_maxima == 1) AND (($index_counter - $i) > 0)) { + $prox_bloque = ($i+ceil($block_limit/2))*$config["block_size"]; + if ($prox_bloque > $count) + $prox_bloque = ($count -1) - $config["block_size"]; + echo ''; + echo " "; + $i = $index_counter; + } + // if exists more registers than i can put in a page (defined by $block_size config parameter) + // get offset for index calculation + // Draw "last" block link, ajust for last block will be the same + // as painted in last block (last integer block). + if (($count - $config["block_size"]) > 0){ + $myoffset = floor(($count-1)/ $config["block_size"])* $config["block_size"]; + echo ''; + echo ""; + echo ""; + } // End div and layout echo "
"; - } } - -// --------------------------------------------------------------- -// Render data in a fashion way :-) -// --------------------------------------------------------------- +/** + * Format a number with decimals and thousands separator. + * + * If the number is zero or it's integer value, no decimals are + * shown. Otherwise, the number of decimals are given in the call. + * + * @param number Number to be rendered + * @param decimals Number of decimals to be shown. Default value: 2 + * @param dec_point Decimal separator string. Default value: . + * @param thousands_sep Thousands separator string. Default value: , + * + * @return + */ function format_numeric ($number, $decimals = 2, $dec_point = ".", $thousands_sep = ",") { if ($number == 0) return 0; - // If has decimals - if (fmod($number , 1) > 0) - return number_format ($number, $decimals, $dec_point, $thousands_sep); - else - return number_format ($number, 0, $dec_point, $thousands_sep); -} - -// --------------------------------------------------------------- -// Render numeric data in a easy way to the user -// --------------------------------------------------------------- -function format_for_graph ( $number , $decimals=2, $dec_point=".", $thousands_sep=",") { - if ($number > "1000000") - if (fmod ($number, 1000000) > 0) - return number_format ($number/1000000, $decimals, $dec_point, $thousands_sep)." M"; - else - return number_format ($number/1000000, 0, $dec_point, $thousands_sep)." M"; - - if ($number > "1000") - if (fmod ($number, 1000) > 0) - return number_format ($number/1000, $decimals, $dec_point, $thousands_sep )." K"; - else - return number_format ($number/1000, 0, $dec_point, $thousands_sep )." K"; - // If has decimals - if (fmod ($number , 1)> 0) + + /* If has decimals */ + if (fmod ($number , 1) > 0) return number_format ($number, $decimals, $dec_point, $thousands_sep); return number_format ($number, 0, $dec_point, $thousands_sep); } -function give_parameter_get ( $name, $default = "" ){ - $output = $default; - if (isset ($_GET[$name])){ - $output = $_GET[$name]; +/** + * Render numeric data for a graph. + * + * It adds magnitude suffix to the number (M for millions, K for thousands...) + * + * @param number Number to be rendered + * @param decimals Number of decimals to display + * @param dec_point Decimal separator character. Default value: . + * @param thousands_sep Thousands separator character. Default value: , + * + * @return A number rendered to be displayed gently on a graph. + */ +function format_for_graph ($number , $decimals = 2, $dec_point = ".", $thousands_sep = ",") { + if ($number > "1000000") { + if (fmod ($number, 1000000) > 0) + return number_format ($number / 1000000, $decimals, $dec_point, $thousands_sep)." M"; + return number_format ($number / 1000000, 0, $dec_point, $thousands_sep)." M"; } - return $output; + + if ($number > "1000") { + if (fmod ($number, 1000) > 0) + return number_format ($number / 1000, $decimals, $dec_point, $thousands_sep )." K"; + return number_format ($number/1000, 0, $dec_point, $thousands_sep )." K"; + } + /* If it has decimals */ + if (fmod ($number , 1)) + return number_format ($number, $decimals, $dec_point, $thousands_sep); + return number_format ($number, 0, $dec_point, $thousands_sep); } -function give_parameter_post ( $name, $default = "" ){ - $output = $default; - if (isset ($_POST[$name])){ - $output = $_POST[$name]; +/** + * Get a human readable string of the difference between current time + * and given timestamp. + * + * @param timestamp Timestamp to compare with current time. + * + * @return A human readable string of the diference between current + * time and given timestamp. + */ +function human_time_comparation ($timestamp) { + if ($timestamp == "") { + return "0 ".lang_string ('minutes'); } - return $output; -} - -function give_parameter_get_numeric ( $name, $default = "-1" ){ - $output = $default; - if (isset ($_GET[$name])){ - $output = $_GET[$name]; - } - if (is_numeric($output)) - return $output; - else - return -1; -} - -function give_parameter_post_numeric ( $name, $default = "" ){ - $output = $default; - if (isset ($_POST[$name])){ - $output = $_POST[$name]; - } - if (is_numeric($output)) - return $output; - else - return -1; -} - -function human_time_comparation ( $timestamp ){ - global $lang_label; - if ($timestamp != ""){ - $ahora=date("Y/m/d H:i:s"); - $seconds = strtotime($ahora) - strtotime($timestamp); - } else - $seconds = 0; - + + $ahora = date ("Y/m/d H:i:s"); + $seconds = strtotime ($ahora) - strtotime ($timestamp); + if ($seconds < 3600) - $render = format_numeric($seconds/60,1)." ".$lang_label["minutes"]; - elseif (($seconds >= 3600) and ($seconds < 86400)) - $render = format_numeric ($seconds/3600,1)." ".$lang_label["hours"]; - elseif (($seconds >= 86400) and ($seconds < 2592000)) - $render = format_numeric ($seconds/86400,1)." ".$lang_label["days"]; - elseif (($seconds >= 2592000) and ($seconds < 15552000)) - $render = format_numeric ($seconds/2592000,1)." ".$lang_label["months"]; - elseif ($seconds >= 15552000) - $render = " +6 ".$lang_label["months"]; - return $render; + return format_numeric ($seconds / 60, 1)." ".lang_string ('minutes'); + + if ($seconds >= 3600 && $seconds < 86400) + return format_numeric ($seconds / 3600, 1)." ".lang_string ('hours'); + + if ($seconds >= 86400 && $seconds < 2592000) + return format_numeric ($seconds / 86400, 1)." ".lang_string ('days'); + + if ($seconds >= 2592000 && $seconds < 15552000) + return format_numeric ($seconds / 2592000, 1)." ".lang_string ('months'); + return " +6 ".lang_string ('months'); } -function human_time_description_raw ($seconds){ +/** + * Transform an amount of time in seconds into a human readable + * strings of minutes, hours or days. + * + * @param seconds Seconds elapsed time + * + * @return A human readable translation of minutes. + */ +function human_time_description_raw ($seconds) { global $lang_label; if ($seconds < 3600) - $render = format_numeric($seconds/60,2)." ".$lang_label["minutes"]; - elseif (($seconds >= 3600) and ($seconds < 86400)) - $render = format_numeric ($seconds/3600,2)." ".$lang_label["hours"]; - elseif ($seconds >= 86400) - $render = format_numeric ($seconds/86400,2)." ".$lang_label["days"]; - return $render; + return format_numeric($seconds/60,2)." ".lang_string ('minutes'); + + if ($seconds >= 3600 && $seconds < 86400) + return format_numeric ($seconds/3600,2)." ".lang_string ('hours'); + + return format_numeric ($seconds/86400,2)." ".lang_string ('days'); } -function human_time_description ($period){ +/** + * Get a human readable label for a period of time. + * + * It only works with rounded period of times (one hour, two hours, six hours...) + * + * @param period Period of time in seconds + * + * @return A human readable label for a period of time. + */ +function human_time_description ($period) { global $lang_label; + switch ($period) { - case 3600: $period_label = $lang_label["hour"]; - break; - case 7200: $period_label = $lang_label["2_hours"]; - break; - case 21600: $period_label = $lang_label["6_hours"]; - break; - case 43200: $period_label = $lang_label["12_hours"]; - break; - case 86400: $period_label = $lang_label["last_day"]; - break; - case 172800: $period_label = $lang_label["two_days"]; - break; - case 432000: $period_label = $lang_label["five_days"]; - break; - case 604800: $period_label = $lang_label["last_week"]; - break; - case 1296000: $period_label = $lang_label["15_days"]; - break; - case 2592000: $period_label = $lang_label["last_month"]; - break; - case 5184000: $period_label = $lang_label["two_month"]; - break; - case 15552000: $period_label = $lang_label["six_months"]; - break; - default: $period_label = human_time_description_raw ($period); + case 3600: + return lang_string ('hour'); + break; + case 7200: + return lang_string ('2_hours'); + break; + case 21600: + return lang_string ('6_hours'); + break; + case 43200: + return lang_string ('12_hours'); + break; + case 86400: + return lang_string ('last_day'); + break; + case 172800: + return lang_string ('two_days'); + break; + case 432000: + return lang_string ('five_days'); + break; + case 604800: + return lang_string ('last_week'); + break; + case 1296000: + return lang_string ('15_days'); + break; + case 2592000: + return lang_string ('last_month'); + break; + case 5184000: + return lang_string ('two_month'); + break; + case 15552000: + return lang_string ('six_months'); + break; + default: + return human_time_description_raw ($period); } return $period_label; } -// This function returns MYSQL Date from now - seconds passed as parameter - +/** + * Get current time minus some seconds. + * + * @param seconds Seconds to substract from current time. + * + * @return The current time minus the seconds given. + */ function human_date_relative ( $seconds ) { $ahora=date("Y/m/d H:i:s"); $ahora_s = date("U"); @@ -556,14 +551,21 @@ function human_date_relative ( $seconds ) { return $ayer; } +/** + * + * + * @param lapse + * + * @return + */ function render_time ($lapse) { - $myhour = intval(($lapse*30)/60); + $myhour = intval (($lapse*30) / 60); if ($myhour == 0) $output = "00"; else $output = $myhour; - $output .=":"; - $mymin = fmod(($lapse*30),60); + $output .= ":"; + $mymin = fmod ($lapse * 30, 60); if ($mymin == 0) $output .= "00"; else @@ -571,6 +573,17 @@ function render_time ($lapse) { return $output; } +/** + * Get a paramter from a request. + * + * It checks first on post request, if there were nothing defined, it + * would return get request + * + * @param name + * @param default + * + * @return + */ function get_parameter ($name, $default = '') { // POST has precedence if (isset($_POST[$name])) @@ -582,6 +595,14 @@ function get_parameter ($name, $default = '') { return $default; } +/** + * Get a parameter from get request array. + * + * @param name Name of the parameter + * @param default Value returned if there were no parameter. + * + * @return Parameter value. + */ function get_parameter_get ($name, $default = "") { if ((isset ($_GET[$name])) && ($_GET[$name] != "")) return safe_input ($_GET[$name]); @@ -589,13 +610,28 @@ function get_parameter_get ($name, $default = "") { return $default; } -function get_parameter_post ( $name, $default = "" ){ +/** + * Get a parameter from post request array. + * + * @param name Name of the parameter + * @param default Value returned if there were no parameter. + * + * @return Parameter value. + */ +function get_parameter_post ($name, $default = "") { if ((isset ($_POST[$name])) && ($_POST[$name] != "")) return safe_input ($_POST[$name]); return $default; } +/** + * Get name of a priority value. + * + * @param priority Priority value + * + * @return Name of given priority + */ function get_alert_priority ($priority = 0) { global $config; switch ($priority) { @@ -618,7 +654,14 @@ function get_alert_priority ($priority = 0) { return ''; } -function get_alert_days ( $row ){ +/** + * + * + * @param row + * + * @return + */ +function get_alert_days ($row) { global $config; global $lang_label; $days_output = ""; @@ -645,35 +688,52 @@ function get_alert_days ( $row ){ return lang_string ("none"); } -function get_alert_times ($row2){ +/** + * + * + * @param row2 + * + * @return + */ +function get_alert_times ($row2) { global $config; global $lang_label; if ($row2["time_from"]){ $time_from_table = $row2["time_from"]; } else { - $time_from_table = lang_string("N/A"); + $time_from_table = lang_string ("N/A"); } if ($row2["time_to"]){ $time_to_table = $row2["time_to"]; } else { - $time_to_table = lang_string("N/A"); + $time_to_table = lang_string ("N/A"); } $string = ""; if ($time_to_table == $time_from_table) - $string .= $lang_label["N/A"]; + $string .= lang_string ('N/A'); else - $string .= substr($time_from_table,0,5)." - ".substr($time_to_table,0,5); + $string .= substr ($time_from_table, 0, 5)." - ".substr ($time_to_table, 0, 5); return $string; } +/** + * + * + * @param row2 + * @param tdcolor + * @param id_tipo_modulo + * @param combined + * + * @return + */ function show_alert_row_edit ($row2, $tdcolor = "datos", $id_tipo_modulo = 1, $combined = 0){ global $config; global $lang_label; $string = ""; if ($row2["disable"] == 1){ - $string .= "".$lang_label["disabled"].""; + $string .= "".lang_string ('disabled').""; } elseif ($id_tipo_modulo != 0) { $string .= ""; } else { @@ -713,7 +773,7 @@ function show_alert_row_edit ($row2, $tdcolor = "datos", $id_tipo_modulo = 1, $c // We have alert text ? if ($row2["alert_text"]!= "") { - $string = $string."".$lang_label["text"].""; + $string = $string."".lang_string ('text').""; } else { $string = $string."".$mymin.""; $string = $string."".$mymax.""; @@ -771,6 +831,15 @@ function show_alert_row_edit ($row2, $tdcolor = "datos", $id_tipo_modulo = 1, $c return $string; } +/** + * + * + * @param data + * @param tdcolor + * @param combined + * + * @return + */ function show_alert_show_view ($data, $tdcolor = "datos", $combined = 0) { global $config; global $lang_label; @@ -858,20 +927,20 @@ function show_alert_show_view ($data, $tdcolor = "datos", $combined = 0) { $mymax = format_for_graph($mymax ); // Text alert ? if ($data["alert_text"] != "") - echo "".$lang_label["text"].""; + echo "".lang_string ('text').""; else { echo "".$mymin.""; echo "".$mymax.""; } echo "".human_time_description($data["time_threshold"]); if ($data["last_fired"] == "0000-00-00 00:00:00") { - echo "".$lang_label["never"].""; + echo "".lang_string ('never').""; } else { echo "".human_time_comparation ($data["last_fired"]).""; } echo "".$data["times_fired"].""; if ($data["times_fired"] <> 0){ - echo ""; + echo ""; echo ""; $id_grupo_alerta = get_db_value ("id_grupo", "tagente", "id_agente", $id_agente); if (give_acl($config["id_user"], $id_grupo_alerta, "AW") == 1) { @@ -882,18 +951,10 @@ function show_alert_show_view ($data, $tdcolor = "datos", $combined = 0) { } } else { echo " - "; + "; } } -function form_render_check ($name_form, $value_form = 1){ - echo ""; -} - /** * Get report types in an array. * @@ -921,7 +982,7 @@ function get_report_types () { /** * Get report type name from type id. * - * @param $type Type id of the report. + * @param type Type id of the report. * * @return Report type name. */ @@ -935,7 +996,7 @@ function get_report_name ($type) { /** * Get report type name from type id. * - * @param $type Type id of the report. + * @param type Type id of the report. * * @return Report type name. */ @@ -977,7 +1038,7 @@ function get_report_type_data_source ($type) { /** * Checks if a module is of type "data" * - * @param $module_name Module name to check. + * @param module_name Module name to check. * * @return true if the module is of type "data" */ @@ -991,7 +1052,7 @@ function is_module_data ($module_name) { /** * Checks if a module is of type "proc" * - * @param $module_name Module name to check. + * @param module_name Module name to check. * * @return true if the module is of type "proc" */ @@ -1005,7 +1066,7 @@ function is_module_proc ($module_name) { /** * Checks if a module is of type "inc" * - * @param $module_name Module name to check. + * @param module_name Module name to check. * * @return true if the module is of type "inc" */ @@ -1019,7 +1080,7 @@ function is_module_inc ($module_name) { /** * Checks if a module is of type "string" * - * @param $module_name Module name to check. + * @param module_name Module name to check. * * @return true if the module is of type "string" */ @@ -1030,6 +1091,11 @@ function is_module_data_string ($module_name) { return true; } +/** + * Checks if a module is of type "string" + * + * @return module_name Module name to check. + */ function get_event_types () { $types = array (); $types['unknown'] = lang_string ('unknown'); @@ -1040,68 +1106,34 @@ function get_event_types () { $types['alert_ceased'] = lang_string ('alert_ceased'); $types['alert_manual_validation'] = lang_string ('alert_manual_validation'); $types['recon_host_detected'] = lang_string ('recon_host_detected'); - $types['new_agent'] = lang_string ('new_agent'); $types['system'] = lang_string ('sytem'); $types['error'] = lang_string ('error'); + return $types; } -function form_priority ($priority = 0, $form_name = "priority", $show_all = 0) { - global $config; - - echo '"; +/** + * Get an array with all the priorities. + * + * @return An array with all the priorities. + */ +function get_priorities () { + $priorities = array (); + $priorities[0] = lang_string ("Maintenance"); + $priorities[1] = lang_string ("Informational"); + $priorities[2] = lang_string ("Normal"); + $priorities[3] = lang_string ("Warning"); + $priorities[4] = lang_string ("Critical"); + + return $priorities; } - -function return_priority ($priority){ +/** + * Get priority value from priority name. + * + * @param priority Priority name. + */ +function return_priority ($priority) { global $config; switch ($priority) { @@ -1119,21 +1151,4 @@ function return_priority ($priority){ return lang_string ("All"); } } - -// Show combo with agents -function form_agent_combo ($id_agent = 0, $form_name = "id_agent") { - global $config; - echo '"; -} ?> diff --git a/pandora_console/include/functions_db.php b/pandora_console/include/functions_db.php index 7079baada1..964a93bd04 100644 --- a/pandora_console/include/functions_db.php +++ b/pandora_console/include/functions_db.php @@ -14,7 +14,14 @@ // GNU General Public License for more details. -function check_login() { +/** + * Check if login session variables are set. + * + * It will stop the execution if those variables were not set + * + * @return 0 on success + */ +function check_login () { global $config; if (!isset($config["homedir"])){ // No exists $config. Exit inmediatly @@ -28,7 +35,7 @@ function check_login() { $rowdup = mysql_fetch_array($resq1); $nombre = $rowdup[0]; if ( $id == $nombre ){ - return 0 ; + return 0; } } audit_db("N/A", getenv("REMOTE_ADDR"), "No session", "Trying to access without a valid session"); @@ -36,13 +43,28 @@ function check_login() { exit; } -// --------------------------------------------------------------- -// give_acl () -// Main Function to get access to resources -// Return 0 if no access, > 0 if access -// --------------------------------------------------------------- - -function give_acl($id_user, $id_group, $access){ +/** + * Check access privileges to resources + * + * Access can be: + * IR - Incident Read + * IW - Incident Write + * IM - Incident Management + * AR - Agent Read + * AW - Agent Write + * LW - Alert Write + * UM - User Management + * DM - DB Management + * LM - Alert Management + * PM - Pandora Management + * + * @param id_user User id to check + * @param id_group Agents group id to check access + * @param access Access privilege to check + * + * @return 1 if the user has privileges, 0 if not. + */ +function give_acl ($id_user, $id_group, $access) { // IF user is level = 1 then always return 1 // Access can be: /* @@ -64,44 +86,76 @@ function give_acl($id_user, $id_group, $access){ $res=mysql_query($query1); $row=mysql_fetch_array($res); if ($row["nivel"] == 1) - $result = 1; - else { - if ($id_group == 0) // Group doesnt matter, any group, for check permission to do at least an action in a group - $query1="SELECT * FROM tusuario_perfil WHERE id_usuario = '".$id_user."'"; // GroupID = 0, group doesnt matter (use with caution!) - else - $query1="SELECT * FROM tusuario_perfil WHERE id_usuario = '".$id_user."' and ( id_grupo =".$id_group." OR id_grupo = 1)"; // GroupID = 1 ALL groups - $resq1=mysql_query($query1); - $result = 0; - while ($rowdup=mysql_fetch_array($resq1)){ - $id_perfil=$rowdup["id_perfil"]; - // For each profile for this pair of group and user do... - $query2="SELECT * FROM tperfil WHERE id_perfil = ".$id_perfil; - $resq2=mysql_query($query2); - if ($rowq2=mysql_fetch_array($resq2)){ - switch ($access) { - case "IR": $result = $result + $rowq2["incident_view"]; break; - case "IW": $result = $result + $rowq2["incident_edit"]; break; - case "IM": $result = $result + $rowq2["incident_management"]; break; - case "AR": $result = $result + $rowq2["agent_view"]; break; - case "AW": $result = $result + $rowq2["agent_edit"]; break; - case "LW": $result = $result + $rowq2["alert_edit"]; break; - case "LM": $result = $result + $rowq2["alert_management"]; break; - case "PM": $result = $result + $rowq2["pandora_management"]; break; - case "DM": $result = $result + $rowq2["db_management"]; break; - case "UM": $result = $result + $rowq2["user_management"]; break; - } - } - } - } // else + return 1; + if ($id_group == 0) // Group doesnt matter, any group, for check permission to do at least an action in a group + $query1="SELECT * FROM tusuario_perfil WHERE id_usuario = '".$id_user."'"; // GroupID = 0, group doesnt matter (use with caution!) + else + $query1="SELECT * FROM tusuario_perfil WHERE id_usuario = '".$id_user."' and ( id_grupo =".$id_group." OR id_grupo = 1)"; // GroupID = 1 ALL groups + $resq1=mysql_query($query1); + $result = 0; + while ($rowdup=mysql_fetch_array($resq1)){ + $id_perfil=$rowdup["id_perfil"]; + // For each profile for this pair of group and user do... + $query2="SELECT * FROM tperfil WHERE id_perfil = ".$id_perfil; + $resq2=mysql_query($query2); + if ($rowq2=mysql_fetch_array($resq2)){ + switch ($access) { + case "IR": + $result = $result + $rowq2["incident_view"]; + + break; + case "IW": + $result = $result + $rowq2["incident_edit"]; + + break; + case "IM": + $result = $result + $rowq2["incident_management"]; + + break; + case "AR": + $result = $result + $rowq2["agent_view"]; + + break; + case "AW": + $result = $result + $rowq2["agent_edit"]; + + break; + case "LW": + $result = $result + $rowq2["alert_edit"]; + + break; + case "LM": + $result = $result + $rowq2["alert_management"]; + + break; + case "PM": + $result = $result + $rowq2["pandora_management"]; + + break; + case "DM": + $result = $result + $rowq2["db_management"]; + + break; + case "UM": + $result = $result + $rowq2["user_management"]; + + break; + } + } + } if ($result > 1) $result = 1; return $result; } -// --------------------------------------------------------------- -// audit_db, update audit log -// --------------------------------------------------------------- - +/** + * Adds an audit log entry. + * + * @param id User id that makes the incident + * @param ip Client IP who makes the incident + * @param accion Action description + * @param descripcion Long action description + */ function audit_db ($id, $ip, $accion, $descripcion){ require("config.php"); $today=date('Y-m-d H:i:s'); @@ -110,32 +164,38 @@ function audit_db ($id, $ip, $accion, $descripcion){ $result=mysql_query($sql1); } - -// --------------------------------------------------------------- -// logon_db, update entry in logon audit -// --------------------------------------------------------------- - -function logon_db($id,$ip){ - require("config.php"); - audit_db($id,$ip,"Logon","Logged in"); +/** + * Log in a user into Pandora. + * + * @param id_user User id + * @param ip Client user IP address. + */ +function logon_db ($id_user, $ip) { + require ("config.php"); + audit_db ($id_user, $ip, "Logon", "Logged in"); // Update last registry of user to get last logon - $sql2='UPDATE tusuario fecha_registro = $today WHERE id_usuario = "$id"'; - $result=mysql_query($sql2); + $sql = 'UPDATE tusuario fecha_registro = $today WHERE id_usuario = "$id_user"'; + $result = mysql_query ($sql); } -// --------------------------------------------------------------- -// logoff_db, also adds audit log -// --------------------------------------------------------------- - -function logoff_db($id,$ip){ - require("config.php"); - audit_db($id,$ip,"Logoff","Logged out"); +/** + * Log out a user into Pandora. + * + * @param id_user User id + * @param ip Client user IP address. + */ +function logoff_db ($id_user, $ip) { + require ("config.php"); + audit_db ($id_user, $ip, "Logoff", "Logged out"); } -// --------------------------------------------------------------- -// Returns profile given ID -// --------------------------------------------------------------- - +/** + * Get profile name from id. + * + * @param id_profile Id profile in tperfil + * + * @return Profile name of the given id + */ function dame_perfil ($id_profile) { return (string) get_db_value ('name', 'tperfil', 'id_perfil', (int) $id_profile); } @@ -210,107 +270,142 @@ function get_alerts_in_agent ($id_agent) { return array_merge ($simple_alerts, $combined_alerts); } -// --------------------------------------------------------------- -// Returns group given ID -// --------------------------------------------------------------- +/** + * Get a list of the reports the user can view. + * + * A user can view a report by two ways: + * - The user created the report (id_user field in treport) + * - The report is not private and the user has reading privileges on + * the group associated to the report + * + * @param $id_user User id to get the reports. + * + * @return An array with all the reports the user can view. + */ +function get_reports ($id_user) { + $user_reports = array (); + $all_reports = get_db_all_rows_in_table ('treport'); + if (sizeof ($all_reports) == 0) { + return $user_reports; + } + foreach ($all_reports as $report) { + /* The report is private and it does not belong to the user */ + if ($report['private'] && $report['id_user'] != $id_user) + continue; + /* Check ACL privileges on report group */ + if (! give_acl ($id_user, $report['id_group'], 'AR')) + continue; + array_push ($user_reports, $report); + } + return $user_reports; +} +/** + * Get group name from group. + * + * @param id_group Id group to get the name. + * + * @return The name of the given group + */ function dame_grupo ($id_group) { return (string) get_db_value ('nombre', 'tgrupo', 'id_grupo', (int) $id_group); } -// --------------------------------------------------------------- -// Returns icon name given group ID -// --------------------------------------------------------------- - +/** + * Get group icon from group. + * + * @param id_group Id group to get the icon + * + * @return Icon path of the given group + */ function dame_grupo_icono ($id_group) { return (string) get_db_value ('icon', 'tgrupo', 'id_grupo', (int) $id_group); } -// --------------------------------------------------------------- -// Return agent id given name of agent -// --------------------------------------------------------------- - +/** + * Get agent id from an agent name. + * + * @param agent_name Agent name to get its id. + * + * @return Id from the agent of the given name. + */ function dame_agente_id ($agent_name) { return (int) get_db_value ('id_agente', 'tagente', 'nombre', $agent_name); } - -// --------------------------------------------------------------- -// Returns userid given name an note id -// --------------------------------------------------------------- - +/** + * Get user id of a note. + * + * @param id_note Note id. + * + * @return User id of the given note. + */ function give_note_author ($id_note) { return (int) get_db_value ('id_usuario', 'tnota', 'id_nota', (int) $id_note); } - -// --------------------------------------------------------------- -// Returns agent id given name of agent -// --------------------------------------------------------------- - -function dame_agente_modulo_id ($id_agente, $id_tipomodulo, $nombre) { - $sql = sprintf ('SELECT id_agente_modulo FROM tagente_modulo - WHERE id_agente = %d - AND id_tipo_modulo = %d AND nombre = "%s"', - $id_agent, $id_tipomodulo, $nombre); - return get_db_sql ($sql); -} - - -// --------------------------------------------------------------- -// Returns event description given it's id -// --------------------------------------------------------------- - +/** + * Get description of an event. + * + * @param id_event Event id. + * + * @return Description of the given event. + */ 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 -// --------------------------------------------------------------- - +/** + * Get group id of an event. + * + * @param id_event Event id + * + * @return Group id of the given event. + */ function gime_idgroup_from_idevent ($id_event) { return (int) get_db_value ('id_grupo', 'tevento', 'id_evento', (int) $id_event); } - -// --------------------------------------------------------------- -// Return module id given name of module type -// --------------------------------------------------------------- - -function dame_module_id ($nombre){ - return (int) get_db_value ('id_tipo', 'ttipo_modulo', 'nombre', $nombre); -} - - -// --------------------------------------------------------------- -// Returns agent name when given its ID -// --------------------------------------------------------------- - +/** + * Get name of an agent. + * + * @param id_agente Agent id. + * + * @return Name of the given agent. + */ 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) { +/** + * Get password of an user. + * + * @param id_usuario User id. + * + * @return Password of an user. + */ +function get_user_password ($id_usuario) { return (string) get_db_value ('password', 'tusuario', 'id_usuario', (int) $id_usuario); } -// --------------------------------------------------------------- -// Returns name of an alert given ID -// --------------------------------------------------------------- - +/** + * Get name of an alert + * + * @param id_alert Alert id. + * + * @return Name of the alert. + */ function dame_nombre_alerta ($id_alert) { return (string) get_db_value ('nombre', 'talerta', 'id_alerta', (int) $id_alert); } -// --------------------------------------------------------------- -// Returns name of a modules group -// --------------------------------------------------------------- - +/** + * Get name of a module group. + * + * @param id_module_group Module group id. + * + * @return Name of the given module group. + */ function dame_nombre_grupomodulo ($id_module_group) { return (string) get_db_value ('name', 'tmodule_group', 'id_mg', (int) $id_module_group); } @@ -920,13 +1015,9 @@ function agent_belong_group($id_agent, $id_group){ // Conexion con la base Datos $child[] = ""; $child[] = $id_group; - give_groupchild($id_group,$child); - $id_agent_group = give_group_id($id_agent); - if (array_in($child,$id_agent_group)==1){ - return 1; - } else { - return 0; - } + give_groupchild ($id_group, $child); + $id_agent_group = give_group_id ($id_agent); + return in_array ($child, $id_agent_group); } // --------------------------------------------------------------- @@ -944,10 +1035,7 @@ function group_belong_group($id_group_a, $id_groupset){ (group_belong_group($id_group_a, $value) == 1)) return 1; } - if (array_in ($childgroup, $id_group_a) == 1) - return 1; - else - return 0; + return in_array ($childgroup, $id_group_a); } // --------------------------------------------------------------- @@ -1161,6 +1249,18 @@ function give_db_value ($field, $table, $field_search, $condition) { return get_db_value ($field, $table, $field_search, $condition); } +function get_db_row_sql ($sql) { + $result = mysql_query ($sql); + if (! $result) { + echo 'Error: get_db_row("'.$sql.'") :'. mysql_error ().'
'; + return NULL; + } + if ($row = mysql_fetch_array ($result)) + return $row; + + return NULL; +} + function get_db_row ($table, $field_search, $condition) { global $config; @@ -1173,15 +1273,7 @@ function get_db_row ($table, $field_search, $condition) { $sql = sprintf ('SELECT * FROM %s WHERE %s = "%s"', $table, $field_search, $condition); } - $result = mysql_query ($sql); - if (! $result) { - echo 'Error: get_db_row("'.$sql.'") :'. mysql_error ().'
'; - return NULL; - } - if ($row = mysql_fetch_array ($result)) - return $row; - - return NULL; + return get_db_row_sql ($sql); } // --------------------------------------------------------------- @@ -1314,15 +1406,15 @@ function return_status_layout ($id_layout = 0){ $sql="SELECT * FROM tlayout_data WHERE id_layout = $id_layout"; $res=mysql_query($sql); while ($row = mysql_fetch_array($res)){ - $id_agentmodule = $row["id_agente_modulo"]; - $type = $row["type"]; - $parent_item = $row["parent_item"]; - $link_layout = $row["id_layout_linked"]; + $id_agentmodule = $row["id_agente_modulo"]; + $type = $row["type"]; + $parent_item = $row["parent_item"]; + $link_layout = $row["id_layout_linked"]; if (($link_layout != 0) && ($id_agentmodule == 0)) { - $temp_status += return_status_layout ($link_layout); + $temp_status += return_status_layout ($link_layout); $temp_total++; - } else { - $temp_status += return_status_agent_module ($id_agentmodule); + } else { + $temp_status += return_status_agent_module ($id_agentmodule); $temp_total++; } } @@ -1376,48 +1468,91 @@ function return_coordinate_y_layoutdata ($id_layoutdata){ return (0); } +/** + * Get the previous data to the timestamp provided. + * + * It's useful to know the first value of a module in an interval, + * since it will be the last value in the + * + * @param $id_agent_module Agent module id to look. + * @param $utimestamp The timestamp to look backwards from and get the data. + * + * @return The row of tagente_datos of the last period. NULL if there were no data. + */ +function get_previous_data ($id_agent_module, $utimestamp) { + $sql = sprintf ('SELECT * FROM tagente_datos + WHERE id_agente_modulo = %d + AND utimestamp <= %d + ORDER by utimestamp DESC LIMIT 1', + $id_agent_module, $utimestamp); + return get_db_row_sql ($sql); +} + function return_moduledata_avg_value ($id_agent_module, $period, $date = 0) { if (! $date) $date = time (); - $datelimit = $date - $period; // limit date - $id_agent = get_db_value ("id_agente", "tagente_modulo", "id_agente_modulo", $id_agent_module); - $sql = sprintf ("SELECT AVG(datos) 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); - return (float) get_db_sql ($sql); + $datelimit = $date - $period; + + $sql = sprintf ("SELECT SUM(datos), COUNT(*) FROM tagente_datos + WHERE id_agente_modulo = %d + AND utimestamp > %d AND utimestamp <= %d + ORDER BY utimestamp ASC", + $id_agent_module, $datelimit, $date); + $values = get_db_row_sql ($sql); + $sum = (float) $values[0]; + $total = (int) $values[1]; + + /* Get also the previous data before the selected interval. */ + $previous_data = get_previous_data ($id_agent_module, $datelimit); + if ($previous_data) + return ($previous_data['datos'] + $sum) / ($total + 1); + return $sum / $total; } function return_moduledata_max_value ($id_agent_module, $period, $date = 0) { if (! $date) $date = time (); - $datelimit = $date - $period; // limit date - $id_agent = get_db_value ("id_agente", "tagente_modulo", "id_agente_modulo", $id_agent_module); + $datelimit = $date - $period; + $sql = sprintf ("SELECT MAX(datos) 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); - return (float) get_db_sql ($sql); + WHERE id_agente_modulo = %d + AND utimestamp > %d AND utimestamp <= %d + ORDER BY utimestamp ASC", + $id_agent_module, $datelimit, $date); + $max = (float) get_db_sql ($sql); + + /* Get also the previous report before the selected interval. */ + $previous_data = get_previous_data ($id_agent_module, $datelimit); + if ($previous_data) + return max ($previous_data['datos'], $max); + + return max ($previous_data, $max); } function return_moduledata_min_value ($id_agent_module, $period, $date = 0) { if (! $date) $date = time (); - $datelimit = $date - $period; // limit date - $id_agent = get_db_value ("id_agente", "tagente_modulo", "id_agente_modulo", $id_agent_module); + $datelimit = $date - $period; + $sql = sprintf ("SELECT MIN(datos) 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); - return (float) get_db_sql ($sql); + WHERE id_agente_modulo = %d + AND utimestamp > %d AND utimestamp <= %d + ORDER BY utimestamp ASC", + $id_agent_module, $datelimit, $date); + $min = (float) get_db_sql ($sql); + + /* Get also the previous data before the selected interval. */ + $previous_data = get_previous_data ($id_agent_module, $datelimit); + if ($previous_data) + return min ($previous_data['datos'], $min); + return $min; } function return_moduledata_sum_value ($id_agent_module, $period, $date = 0) { if (! $date) $date = time (); $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']); if (is_module_data_string ($module_name)) { @@ -1427,10 +1562,17 @@ function return_moduledata_sum_value ($id_agent_module, $period, $date = 0) { // Get the whole interval of data $sql = sprintf ('SELECT * FROM tagente_datos - WHERE id_agente = %d AND id_agente_modulo = %d + WHERE id_agente_modulo = %d AND utimestamp > %d AND utimestamp <= %d', - $agent_module['id_agente'], $id_agent_module, $datelimit, $date); + $id_agent_module, $datelimit, $date); $datas = get_db_all_rows_sqlfree ($sql); + + /* Get also the previous data before the selected interval. */ + $previous_data = get_previous_data ($id_agent_module, $datelimit); + if ($previous_data) { + /* Add data to the beginning */ + array_unshift ($datas, $previous_data); + } $last_data = ""; $total_badtime = 0; $interval_begin = 0; @@ -1491,13 +1633,13 @@ function check_server_status () { return $res; } -function show_alert_row_mini ($id_combined_alert){ +function show_alert_row_mini ($id_combined_alert) { global $config; global $lang_label; $color=1; - $sql_com = "SELECT talerta_agente_modulo.*, tcompound_alert.operation FROM talerta_agente_modulo, tcompound_alert WHERE tcompound_alert.id_aam = talerta_agente_modulo.id_aam AND tcompound_alert.id = ".$id_combined_alert; - $result_com = mysql_query ($sql_com); + $sql = "SELECT talerta_agente_modulo.*, tcompound_alert.operation FROM talerta_agente_modulo, tcompound_alert WHERE tcompound_alert.id_aam = talerta_agente_modulo.id_aam AND tcompound_alert.id = ".$id_combined_alert; + $result = mysql_query ($sql); echo ""; echo "
".lang_string("Name"); echo "".lang_string("Oper"); @@ -1509,9 +1651,9 @@ function show_alert_row_mini ($id_combined_alert){ echo "".lang_string("MinMax.Al"); echo "".lang_string("Days"); echo "".lang_string("Fired"); - while ($row2=mysql_fetch_array($result_com)){ + while ($row2 = mysql_fetch_array ($result)) { - if ($color == 1){ + if ($color == 1) { $tdcolor = "datos"; $color = 0; } @@ -1599,118 +1741,116 @@ function show_alert_row_mini ($id_combined_alert){ } echo "
"; } -function smal_event_table ($filter = "", $limit = 10, $width=440){ - global $config; - global $lang_label; - $sql2 = "SELECT * FROM tevento $filter ORDER BY timestamp DESC LIMIT $limit"; - echo ""; - echo ""; - echo ""; - echo "
".lang_string("Latest events"); - echo "
".lang_string ("St").""; - echo "".lang_string ("Type").""; - echo "".$lang_label["event_name"].""; - echo "".$lang_label["agent_name"].""; - echo "".$lang_label["id_user"].""; - echo "".$lang_label["timestamp"].""; - $result2=mysql_query($sql2); - while ($row2=mysql_fetch_array($result2)){ - $id_grupo = $row2["id_grupo"]; - if (give_acl($config["id_user"], $id_grupo, "AR") == 1){ // Only incident read access to view data ! - switch ($row2["criticity"]) { - case 0: - $tdclass = "datos_blue"; - break; - case 1: - $tdclass = "datos_grey"; - break; - case 2: - $tdclass = "datos_green"; - break; - case 3: - $tdclass = "datos_yellow"; - break; - case 4: - $tdclass = "datos_red"; - break; - default: - $tdclass = "datos_grey"; - } - $criticity_label = return_priority ($row2["criticity"]); - // Colored box - echo "
"; - if ($row2["estado"] == 0) - echo ""; - else - echo ""; - - // Event type - echo ""; - switch ($row2["event_type"]){ - case "unknown": - echo ""; - break; - case "alert_recovered": - echo ""; - break; - case "alert_manual_validation": - echo ""; - break; - case "monitor_up": - echo ""; - break; - case "monitor_down": - echo ""; - break; - case "alert_fired": - echo ""; - break; - case "system"; - echo ""; - break; - case "recon_host_detected"; - echo ""; - break; - case "new_agent": - echo ""; - break; - } - - // Event description - echo ""; - echo substr($row2["evento"],0,45); - if (strlen($row2["evento"]) > 45) - echo ".."; - if ($row2["id_agente"] > 0){ - // Agent name - $agent_name = dame_nombre_agente($row2["id_agente"]); - echo ""; - echo substr($agent_name, 0, 14); - if (strlen($agent_name) > 14) - echo ".."; - echo ""; - - // for System or SNMP generated alerts - } else { - if ($row2["event_type"] == "system"){ - echo "".lang_string("System"); - } else { - echo "".$lang_label["alert"]."SNMP"; - } - } - - // User who validated event - echo ""; - if ($row2["estado"] <> 0) - echo "".substr($row2["id_usuario"],0,8)." ".dame_nombre_real($row2["id_usuario"]).""; - - // Timestamp - echo ""; - echo human_time_comparation($row2["timestamp"]); - - } - } - echo "
"; +function smal_event_table ($filter = "", $limit = 10, $width = 440) { + global $config; + global $lang_label; + + $sql2 = "SELECT * FROM tevento $filter ORDER BY timestamp DESC LIMIT $limit"; + echo ""; + echo ""; + echo ""; + echo ""; + echo ""; + echo ""; + echo ""; + echo ""; + echo ""; + $result2=mysql_query($sql2); + while ($row2=mysql_fetch_array($result2)){ + $id_grupo = $row2["id_grupo"]; + if (give_acl($config["id_user"], $id_grupo, "AR") == 1){ // Only incident read access to view data ! + switch ($row2["criticity"]) { + case 0: + $tdclass = "datos_blue"; + break; + case 1: + $tdclass = "datos_grey"; + break; + case 2: + $tdclass = "datos_green"; + break; + case 3: + $tdclass = "datos_yellow"; + break; + case 4: + $tdclass = "datos_red"; + break; + default: + $tdclass = "datos_grey"; + } + $criticity_label = return_priority ($row2["criticity"]); + // Colored box + echo "
".lang_string("Latest events"); + echo "
".lang_string ("St")."".lang_string ("Type")."".$lang_label["event_name"]."".$lang_label["agent_name"]."".$lang_label["id_user"]."".$lang_label["timestamp"]."
"; + if ($row2["estado"] == 0) + echo ""; + else + echo ""; + + // Event type + echo ""; + switch ($row2["event_type"]){ + case "unknown": + echo ""; + break; + case "alert_recovered": + echo ""; + break; + case "alert_manual_validation": + echo ""; + break; + case "monitor_up": + echo ""; + break; + case "monitor_down": + echo ""; + break; + case "alert_fired": + echo ""; + break; + case "system"; + echo ""; + break; + case "recon_host_detected"; + echo ""; + break; + } + + // Event description + echo ""; + echo substr($row2["evento"],0,45); + if (strlen($row2["evento"]) > 45) + echo ".."; + if ($row2["id_agente"] > 0){ + // Agent name + $agent_name = dame_nombre_agente($row2["id_agente"]); + echo ""; + echo substr($agent_name, 0, 14); + if (strlen($agent_name) > 14) + echo ".."; + echo ""; + + // for System or SNMP generated alerts + } else { + if ($row2["event_type"] == "system"){ + echo "".lang_string("System"); + } else { + echo "".$lang_label["alert"]."SNMP"; + } + } + + // User who validated event + echo ""; + if ($row2["estado"] <> 0) + echo "".substr($row2["id_usuario"],0,8)." ".dame_nombre_real($row2["id_usuario"]).""; + + // Timestamp + echo ""; + echo human_time_comparation($row2["timestamp"]); + + } + } + echo "
"; } ?> diff --git a/pandora_console/include/functions_reporting.php b/pandora_console/include/functions_reporting.php index 60988ab636..2b81ecebfb 100644 --- a/pandora_console/include/functions_reporting.php +++ b/pandora_console/include/functions_reporting.php @@ -22,37 +22,58 @@ function return_module_SLA ($id_agent_module, $period, $min_value, $max_value, $ $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 + /* Get all the data in the interval */ $sql = sprintf ('SELECT * FROM tagente_datos WHERE id_agente = %d AND id_agente_modulo = %d - AND utimestamp > %d AND utimestamp <= %d', + AND utimestamp > %d AND utimestamp <= %d + ORDER BY utimestamp ASC', $id_agent, $id_agent_module, $datelimit, $date); - $result = mysql_query ($sql); + $datas = get_db_all_rows_sqlfree ($sql); $last_data = ""; $total_badtime = 0; $interval_begin = 0; - $interval_last = 0; - - if (! $result) { - return 100; + $interval_last = $date; + $previous_data_timestamp = 0; + + /* Get also the previous data before the selected interval. */ + $previous_data = get_previous_data ($id_agent_module, $datelimit); + if ($previous_data) { + /* Add data to the beginning */ + array_unshift ($datas, $previous_data); + $previous_data_timestamp = $previous_data['utimestamp']; } - while ($row = mysql_fetch_array ($result)) { - if ( ($row["datos"] > $max_value) || ($row["datos"] < $min_value)) { + if (sizeof ($datas) == 0) { + return false; + } + + foreach ($datas as $data) { + if ($data["datos"] > $max_value || $data["datos"] < $min_value) { if ($interval_begin == 0) { - $interval_begin = $row["utimestamp"]; + $interval_begin = $data["utimestamp"]; } - } elseif ($interval_begin != 0){ + } elseif ($interval_begin != 0) { // Here ends interval with data outside valid values, // Need to add this time to counter - $interval_last = $row["utimestamp"]; + $interval_last = $data["utimestamp"]; $temp_time = $interval_last - $interval_begin; - $total_badtime = $total_badtime + $temp_time; + $total_badtime += $temp_time; $interval_begin = 0; $interval_last = 0; } } + + /* Check the last interval, if any */ + if ($interval_begin != 0) { + /* The last time was the time of the previous data in the + interval. That means that in all the interval, the data was + not between the expected values, so the SLA is zero. */ + if ($interval_begin = $previous_data_timestamp) + return 0; + $total_badtime += $interval_last - $interval_begin; + } + $result = 100 - ($total_badtime / $period) * 100; - return $result; + return max ($result, 0); } function general_stats ( $id_user, $id_group = 0) { @@ -192,10 +213,10 @@ function event_reporting ($id_agent, $period, $date = 0, $return = false) { $sql2="SELECT * FROM tevento WHERE id_agente = $id_agent AND utimestamp > '$mytimestamp'"; // Make query for data (all data, not only distinct). - $result2=mysql_query($sql2); - while ($row2=mysql_fetch_array($result2)){ + $result2 = mysql_query($sql2); + while ($row2 = mysql_fetch_array($result2)) { $id_grupo = $row2["id_grupo"]; - if (give_acl($id_user, $id_grupo, "IR") == 1){ // Only incident read access to view data ! + if (give_acl($id_user, $id_grupo, "IR") == 1) { // Only incident read access to view data ! $id_group = $row2["id_grupo"]; if ($color == 1){ $tdcolor = "datos"; diff --git a/pandora_console/index.php b/pandora_console/index.php index 77302b7b47..f400df9e33 100644 --- a/pandora_console/index.php +++ b/pandora_console/index.php @@ -193,13 +193,15 @@ require "include/functions_db.php"; } $pagina = ""; if (isset ($_GET["sec2"])){ - $sec2 = parametro_limpio ($_GET["sec2"]); + $sec2 = get_parameter_get ('sec2'); + $sec2 = parameter_extra_clean ($sec2); $pagina = $sec2; } else $sec2 = ""; if (isset ($_GET["sec"])){ - $sec = parametro_limpio ($_GET["sec"]); + $sec = get_parameter_get ('sec'); + $sec = parameter_extra_clean ($sec); $pagina = $sec2; } else @@ -254,4 +256,4 @@ require "include/functions_db.php"; echo ''; -?> \ No newline at end of file +?> diff --git a/pandora_console/operation/agentes/ver_agente.php b/pandora_console/operation/agentes/ver_agente.php index 96f62bf9ee..f3954d187b 100644 --- a/pandora_console/operation/agentes/ver_agente.php +++ b/pandora_console/operation/agentes/ver_agente.php @@ -53,7 +53,7 @@ if (comprueba_login() == 0) { if (give_acl($id_usuario, $id_grupo, "AR")==1){ // Check for validate alert request - $validate_alert = give_parameter_get ("validate_alert"); + $validate_alert = get_parameter ("validate_alert"); if ($validate_alert != ""){ if (give_acl($id_usuario, $id_grupo, "AW")==1){ $alert_row = get_db_row ("talerta_agente_modulo", "id_aam", $validate_alert); diff --git a/pandora_console/operation/events/events.php b/pandora_console/operation/events/events.php index 1e5e5868d4..8f354342ed 100644 --- a/pandora_console/operation/events/events.php +++ b/pandora_console/operation/events/events.php @@ -18,40 +18,36 @@ @@ -164,36 +160,36 @@ $id_agent = get_parameter ("id_agent", -1); $sql_post = ""; if ($ev_group > 1) - $sql_post .= " AND id_grupo = $ev_group"; + $sql_post .= " AND id_grupo = $ev_group"; if ($status == 1) - $sql_post .= " AND estado = 1"; + $sql_post .= " AND estado = 1"; if ($status == 0) - $sql_post .= " AND estado = 0"; + $sql_post .= " AND estado = 0"; if ($search != "") - $sql_post .= " AND evento LIKE '%$search%'"; + $sql_post .= " AND evento LIKE '%$search%'"; if ($event_type != "") - $sql_post .= " AND event_type = '$event_type'"; + $sql_post .= " AND event_type = '$event_type'"; if ($severity != -1) - $sql_post .= " AND criticity >= $severity"; + $sql_post .= " AND criticity >= $severity"; if ($id_agent != -1) - $sql_post .= " AND id_agente = $id_agent"; + $sql_post .= " AND id_agente = $id_agent"; $url = "index.php?sec=eventos&sec2=operation/events/events&search=$search&event_type=$event_type&severity=$severity&status=$status&ev_group=$ev_group&refr=60&id_agent=$id_agent"; echo "

".$lang_label["events"]." > ".lang_string ("event_main_view"). " "; if ($config["pure"] == 1) - echo ""; + echo ""; else - echo ""; + echo ""; echo "

"; echo ""; echo "".lang_string("Event control filter")." ".''; if ($config["pure"] == 1) - echo "