Both are similars:
$modules = get_agent_modules ($id_agent, false, array ('disabled' => 0));
$modules = get_agent_modules ($id_agent, false, 'disabled = 0');
Both are similars:
$modules = get_agent_modules ($id_agent, '*', array ('disabled' => 0, 'history_data' => 0));
$modules = get_agent_modules ($id_agent, '*', 'disabled = 0 AND history_data = 0');
*
* @return array An array with all modules in the agent.
* If multiple rows are selected, they will be in an array
*/
function get_agent_modules ($id_agent, $details = false, $filter = false, $indexed = true) {
$id_agent = safe_int ($id_agent, 1);
$where = '';
if (! empty ($id_agent)) {
$where = sprintf (' WHERE id_agente IN (%s)', implode (",", (array) $id_agent));
}
if (! empty ($filter)) {
if ($where != '') {
$where .= ' AND ';
} else {
$where .= ' WHERE ';
}
if (is_array ($filter)) {
$fields = array ();
foreach ($filter as $field => $value) {
array_push ($fields, $field.'="'.$value.'"');
}
$where .= implode (' AND ', $fields);
} else {
$where .= $filter;
}
}
if (empty ($details)) {
$details = "nombre";
} else {
$details = safe_input ($details);
}
$sql = sprintf ('SELECT %s%s
FROM tagente_modulo
%s
ORDER BY nombre',
($details != '*' && $indexed) ? 'id_agente_modulo,' : '',
implode (",", (array) $details),
$where);
$result = get_db_all_rows_sql ($sql);
if (empty ($result)) {
return array ();
}
if (! $indexed)
return $result;
$modules = array ();
foreach ($result as $module) {
if (is_array ($details) || $details == '*') {
//Just stack the information in array by ID
$modules[$module['id_agente_modulo']] = $module;
} else {
$modules[$module['id_agente_modulo']] = $module[$details];
}
}
return $modules;
}
/**
* Get the number of all agent modules in the database
*
* @param mixed Array of integers with agent(s) id or a single agent id. Default
* value will select all.
*
* @return int The number of agent modules
*/
function get_agent_modules_count ($id_agent = 0) {
//Make sure we're all int's and filter out bad stuff
$id_agent = safe_int ($id_agent, 1);
if (empty ($id_agent)) {
//If the array proved empty or the agent is less than 1 (eg. -1)
$filter = '';
} else {
$filter = sprintf (" WHERE id_agente IN (%s)", implode (",", (array) $id_agent));
}
return (int) get_db_sql ("SELECT COUNT(*) FROM tagente_modulo".$filter);
}
/**
* Get group icon from group.
*
* @param int id_group Id group to get the icon
*
* @return string Icon path of the given group
*/
function get_group_icon ($id_group) {
return (string) get_db_value ('icon', 'tgrupo', 'id_grupo', (int) $id_group);
}
/**
* DEPRECATED in favor of get_group_icon
*/
function dame_grupo_icono ($id_group) {
return get_group_icon ($id_group);
}
/**
* Get agent id from an agent name.
*
* @param string $agent_name Agent name to get its id.
*
* @return int Id from the agent of the given name.
*/
function get_agent_id ($agent_name) {
return (int) get_db_value ('id_agente', 'tagente', 'nombre', $agent_name);
}
/**
* Get name of an agent.
*
* @param int $id_agent Agent id.
* @param string $case Case (upper, lower, none)
*
* @return string Name of the given agent.
*/
function get_agent_name ($id_agent, $case = "upper") {
$agent = (string) get_db_value ('nombre', 'tagente', 'id_agente', (int) $id_agent);
switch ($case) {
case "upper":
return mb_strtoupper ($agent,"UTF-8");
break;
case "lower":
return mb_strtolower ($agent,"UTF-8");
break;
case "none":
default:
return ($agent);
}
}
/**
* Get type name for alerts (e-mail, text, internal, ...) based on type number
*
* @param int id_alert Alert type id.
*
* @return string Type name of the alert.
*/
function get_alert_type ($id_type) {
return (string) get_db_value ('name', 'talert_templates', 'id', (int) $id_type);
}
/**
* Get the name of an exporting server
*
* @param int $id_server Server id
*
* @return string The name of given server.
*/
function dame_nombre_servidorexportacion ($id_server) {
return (string) get_db_value ('name', 'tserver_export', 'id', (int) $id_server);
}
/**
* Get the name of a plugin
*
* @param int id_plugin Plugin id.
*
* @return string The name of the given plugin
*/
function dame_nombre_pluginid ($id_plugin) {
return (string) get_db_value ('name', 'tplugin', 'id', (int) $id_plugin);
}
/**
* Get the name of a module type
*
* @param int $id_type Type id
*
* @return string The name of the given type.
*/
function get_module_type_name ($id_type) {
return (string) get_db_value ('nombre', 'ttipo_modulo', 'id_tipo', (int) $id_type);
}
/**
* Get agent id of an agent module.
*
* @param int $id_agentmodule Agent module id.
*
* @return int The id of the agent of given agent module
*/
function get_agentmodule_agent ($id_agentmodule) {
return (int) get_db_value ('id_agente', 'tagente_modulo', 'id_agente_modulo', (int) $id_agentmodule);
}
/**
* Get agent name of an agent module.
*
* @param int $id_agente_modulo Agent module id.
*
* @return string The name of the given agent module.
*/
function get_agentmodule_agent_name ($id_agentmodule) {
// Since this is a helper function we don't need to do casting
return (string) get_agent_name (get_agentmodule_agent ($id_agentmodule));
}
/**
* Get the module name of an agent module.
*
* @param int $id_agente_modulo Agent module id.
*
* @return string Name of the given agent module.
*/
function get_agentmodule_name ($id_agente_modulo) {
return (string) get_db_value ('nombre', 'tagente_modulo', 'id_agente_modulo', (int) $id_agente_modulo);
}
/**
* Get the module type of an agent module.
*
* @param int $id_agentmodule Agent module id.
*
* @return string Module type of the given agent module.
*/
function get_agentmodule_type ($id_agentmodule) {
return (int) get_db_value ('id_tipo_modulo', 'tagente_modulo', 'id_agente_modulo', (int) $id_agentmodule);
}
/**
* DEPRECATED: User get_user_fullname
*/
function dame_nombre_real ($id_user) {
return get_user_fullname ($id_user);
}
/**
* Get all the times a monitor went down during a period.
*
* @param int $id_agent_module Agent module of the monitor.
* @param int $period Period timed to check from date
* @param int $date Date to check (now by default)
*
* @return int The number of times a monitor went down.
*/
function get_monitor_downs_in_period ($id_agent_module, $period, $date = 0) {
if ($date == 0) {
$date = get_system_time ();
}
$datelimit = $date - $period;
$sql = sprintf ("SELECT COUNT(`id_agentmodule`) FROM `tevento` WHERE
`event_type` = 'monitor_down'
AND `id_agentmodule` = %d
AND `utimestamp` > %d
AND `utimestamp` <= %d",
$id_agent_module, $datelimit, $date);
return get_db_sql ($sql);
}
/**
* Get the last time a monitor went down during a period.
*
* @param int $id_agent_module Agent module of the monitor.
* @param int $period Period timed to check from date
* @param int $date Date to check (now by default)
*
* @return int The last time a monitor went down.
*/
function get_monitor_last_down_timestamp_in_period ($id_agent_module, $period, $date = 0) {
if ($date == 0) {
$date = get_system_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);
return get_db_sql ($sql);
}
/**
* Get all the monitors defined in an group.
*
* @param int $id_group Group id to get all the monitors.
*
* @return array An array with all the monitors defined in the group (tagente_modulo).
*/
function get_monitors_in_group ($id_group) {
if ($id_group <= 1) {
//We select all groups the user has access to if it's 0, -1 or 1
global $config;
$id_group = array_keys (get_user_groups ($config['id_user']));
}
if (is_array ($id_group)) {
$id_group = implode (",",$id_group);
}
$sql = sprintf ("SELECT `tagente_modulo`.* 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` IN (%s) ORDER BY `tagente`.`nombre`", $id_group);
return get_db_all_rows_sql ($sql);
}
/**
* Get all the events happened in a group during a period of time.
*
* The returned events will be in the time interval ($date - $period, $date]
*
* @param mixed $id_group Group id to get events for.
* @param int $period Period of time in seconds to get events.
* @param int $date Beginning date to get events.
*
* @return array An array with all the events happened.
*/
function get_group_events ($id_group, $period, $date) {
global $config;
$id_group = safe_acl_group ($config["id_user"], $id_group, "AR");
if (empty ($id_group)) {
//An empty array means the user doesn't have access
return false;
}
$datelimit = $date - $period;
$sql = sprintf ('SELECT * FROM tevento
WHERE utimestamp > %d AND utimestamp <= %d
AND id_grupo IN (%s)
ORDER BY utimestamp ASC',
$datelimit, $date, implode (",", $id_group));
return get_db_all_rows_sql ($sql);
}
/**
* Get all the events happened in an Agent during a period of time.
*
* The returned events will be in the time interval ($date - $period, $date]
*
* @param int $id_agent Agent id to get events.
* @param int $period Period of time in seconds to get events.
* @param int $date Beginning date to get events.
*
* @return array An array with all the events happened.
*/
function get_agent_events ($id_agent, $period, $date = 0) {
if (!is_numeric ($date)) {
$date = strtotime ($date);
}
if (empty ($date)) {
$date = get_system_time ();
}
$datelimit = $date - $period;
$sql = sprintf ('SELECT evento, event_type, criticity, count(*) as count_rep, max(timestamp) AS time2
FROM tevento WHERE id_agente = %d AND utimestamp > %d AND utimestamp <= %d
GROUP BY id_agentmodule, evento ORDER BY time2 DESC', $id_agent, $datelimit, $date);
return get_db_all_rows_sql ($sql);
}
/**
* Get all the monitors defined in an agent.
*
* @param int $id_agent Agent id to get all the monitors.
*
* @return array An array with all the monitors defined (tagente_modulo).
*/
function get_monitors_in_agent ($id_agent) {
$sql = sprintf ("SELECT `tagente_modulo`.*
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_agente` = %d", $id_agent);
return get_db_all_rows_sql ($sql);
}
/**
* Get all the monitors down during a period of time.
*
* @param array $monitors An array with all the monitors to check. Each
* element of the array must be a dictionary.
* @param int $period Period of time to check the monitors.
* @param int $date Beginning date to check the monitors.
*
* @return array An array with all the monitors that went down in that
* period of time.
*/
function get_monitors_down ($monitors, $period = 0, $date = 0) {
$monitors_down = array ();
if (empty ($monitors))
return $monitors_down;
foreach ($monitors as $monitor) {
$down = get_monitor_downs_in_period ($monitor['id_agente_modulo'], $period, $date);
if ($down > 0)
array_push ($monitors_down, $monitor);
}
return $monitors_down;
}
/**
* Get all the times an alerts fired during a period.
*
* @param int Alert module id.
* @param int Period timed to check from date
* @param int Date to check (current time by default)
*
* @return int The number of times an alert fired.
*/
function get_alert_fires_in_period ($id_alert_module, $period, $date = 0) {
if (!$date)
$date = get_system_time ();
$datelimit = $date - $period;
$sql = sprintf ("SELECT COUNT(`id_agentmodule`) FROM `tevento` WHERE
`event_type` = 'alert_fired'
AND `id_alert_am` = %d
AND `utimestamp` > %d
AND `utimestamp` <= %d",
$id_alert_module, $datelimit, $date);
return (int) get_db_sql ($sql);
}
/**
* Get all the alerts defined in a group.
*
* It gets all the alerts of all the agents on a given group.
*
* @param int $id_group Group id to check.
*
* @return array An array with alerts dictionaries defined in a group.
*/
function get_group_alerts ($id_group) {
global $config;
require_once ($config["homedir"].'/include/functions_agents.php');
$alerts = array ();
$agents = get_group_agents ($id_group, false, "none");
foreach ($agents as $agent_id => $agent_name) {
$agent_alerts = get_agent_alerts ($agent_id);
$alerts = array_merge ($alerts, $agent_alerts);
}
return $alerts;
}
/**
* Get all the alerts fired during a period, given a list of alerts.
*
* @param array A list of alert modules to check. See get_alerts_in_group()
* @param int Period of time to check fired alerts.
* @param int Beginning date to check fired alerts in UNIX format (current date by default)
*
* @return array An array with the alert id as key and the number of times
* the alert was fired (only included if it was fired).
*/
function get_alerts_fired ($alerts, $period = 0, $date = 0) {
if (! $date)
$date = get_system_time ();
$datelimit = $date - $period;
$alerts_fired = array ();
$agents = array ();
foreach ($alerts as $alert) {
if (isset($alert['id'])){
$fires = get_alert_fires_in_period ($alert['id'], $period, $date);
if (! $fires) {
continue;
}
$alerts_fired[$alert['id']] = $fires;
}
}
return $alerts_fired;
}
/**
* Get the last time an alert fired during a period.
*
* @param int Alert agent module id.
* @param int Period timed to check from date
* @param int Date to check (current date by default)
*
* @return int The last time an alert fired. It's an UNIX timestamp.
*/
function get_alert_last_fire_timestamp_in_period ($id_alert_module, $period, $date = 0) {
if ($date == 0) {
$date = get_system_time ();
}
$datelimit = $date - $period;
$sql = sprintf ("SELECT MAX(`utimestamp`) FROM `tevento` WHERE
`event_type` = 'alert_fired'
AND `id_alert_am` = %d
AND `utimestamp` > %d
AND `utimestamp` <= %d",
$id_alert_module, $datelimit, $date);
return get_db_sql ($sql);
}
/**
* Get the server name.
*
* @param int Server id.
*
* @return string Name of the given server
*/
function get_server_name ($id_server) {
return (string) get_db_value ('name', 'tserver', 'id_server', (int) $id_server);
}
/**
* Get the module type name (type = generic_data, remote_snmp, ...)
*
* @param int $id_type Type id
*
* @return string Name of the given type.
*/
function get_moduletype_name ($id_type) {
return (string) get_db_value ('nombre', 'ttipo_modulo', 'id_tipo', (int) $id_type);
}
/**
* Get the module type description
*
* @param int $id_type Type id
*
* @return string Description of the given type.
*/
function get_moduletype_description ($id_type) {
return (string) get_db_value ('descripcion', 'ttipo_modulo', 'id_tipo', (int) $id_type);
}
/**
* Returns an array with all module types (default) or if "remote" or "agent"
* is passed it will return only remote (ICMP, SNMP, TCP...) module types
* otherwise the full list + the column you specify
*
* @param string Specifies which type to return (will return an array with id's)
* @param string Which rows to select (defaults to nombre)
*
* @return array Either the full table or if a type is specified, an array with id's
*/
function get_moduletypes ($type = "all", $rows = "nombre") {
$return = array ();
$rows = (array) $rows; //Cast as array
$row_cnt = count ($rows);
if ($type == "remote") {
return array_merge (range (6,18), (array) 100);
} elseif ($type == "agent") {
return array_merge (range (1,4), range (19,24));
}
$sql = sprintf ("SELECT id_tipo,%s FROM ttipo_modulo", implode (",", $rows));
$result = get_db_all_rows_sql ($sql);
if ($result === false) {
return $return;
}
foreach ($result as $type) {
if ($row_cnt > 1) {
$return[$type["id_tipo"]] = $type;
} else {
$return[$type["id_tipo"]] = $type[reset ($rows)];
}
}
return $return;
}
/**
* @deprecated Use get_agent_group ($id) now (fully compatible)
*/
function dame_id_grupo ($id_agent) {
return get_agent_group ($id_agent);
}
/**
* Get the number of pandora data packets in the database.
*
* In case an array is passed, it will have a value for every agent passed
* incl. a total otherwise it will just return the total
*
* @param mixed Agent id or array of agent id's, 0 for all
*
* @return mixed The number of data in the database
*/
function get_agent_modules_data_count ($id_agent = 0) {
$id_agent = safe_int ($id_agent, 1);
if (empty ($id_agent)) {
$id_agent = array ();
} else {
$id_agent = (array) $id_agent;
}
$count = array ();
$count["total"] = 0;
$query[0] = "SELECT COUNT(*) FROM tagente_datos";
//$query[1] = "SELECT COUNT(*) FROM tagente_datos_inc";
//$query[2] = "SELECT COUNT(*) FROM tagente_datos_string";
foreach ($id_agent as $agent_id) {
//Init value
$count[$agent_id] = 0;
$modules = array_keys (get_agent_modules ($agent_id));
foreach ($query as $sql) {
//Add up each table's data
$count[$agent_id] += (int) get_db_sql ($sql." WHERE id_agente_modulo IN (".implode (",", $modules).")");
}
//Add total agent count to total count
$count["total"] += $count[$agent_id];
}
if ($count["total"] == 0) {
foreach ($query as $sql) {
$count["total"] += (int) get_db_sql ($sql);
}
}
if (!isset ($agent_id)) {
//If agent_id is not set, it didn't loop through any agents
return $count["total"];
}
return $count; //Return the array
}
/**
* Get the operating system name.
*
* @param int Operating system id.
*
* @return string Name of the given operating system.
*/
function get_os_name ($id_os) {
return (string) get_db_value ('name', 'tconfig_os', 'id_os', (int) $id_os);
}
/**
* @deprecated Use is_user_admin
*/
function dame_admin ($id_user) {
return is_user_admin ($id_user);
}
/**
* @deprecated Use check_login () instead
*/
function comprueba_login () {
return check_login ();
}
/**
* Check if an agent has alerts fired.
*
* @param int Agent id.
*
* @return bool True if the agent has fired alerts.
*/
function check_alert_fired ($id_agent) {
$sql = sprintf ("SELECT COUNT(*)
FROM talert_template_modules, tagente_modulo
WHERE talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo
AND times_fired > 0 AND id_agente = %d",
$id_agent);
$value = get_db_sql ($sql);
if ($value > 0)
return true;
return false;
}
/**
* Get the interval value of an agent module.
*
* If the module interval is not set, the agent interval is returned
*
* @param int Id agent module to get the interval value.
*
* @return int Module interval or agent interval if no module interval
*/
function get_module_interval ($id_agent_module) {
$interval = (int) get_db_value ('module_interval', 'tagente_modulo', 'id_agente_modulo', (int) $id_agent_module);
if ($interval > 0)
return $interval;
$id_agent = give_agent_id_from_module_id ($id_agent_module);
return (int) get_agent_interval ($id_agent);
}
/**
* Get the interval of an agent.
*
* @param int Agent id.
*
* @return int The interval value of a given agent
*/
function get_agent_interval ($id_agent) {
return (int) get_db_value ('intervalo', 'tagente', 'id_agente', $id_agent);
}
/**
* Get the flag value of an agent module.
*
* @param int Agent module id.
*
* @return bool The flag value of an agent module.
*/
function give_agentmodule_flag ($id_agent_module) {
return get_db_value ('flag', 'tagente_modulo', 'id_agente_modulo', $id_agent_module);
}
/**
* Prints a list of
get_db_value_filter ('name', 'talert_templates',
array ('value' => 2, 'type' => 'equal'));
// Equivalent to:
// SELECT name FROM talert_templates WHERE value = 2 AND type = 'equal' LIMIT 1
get_db_value_filter ('description', 'talert_templates',
array ('name' => 'My alert', 'type' => 'regex'), 'OR');
// Equivalent to:
// SELECT description FROM talert_templates WHERE name = 'My alert' OR type = 'equal' LIMIT 1
*
* @param string Field name to get
* @param string Table to retrieve the data
* @param array Conditions to filter the element. See format_array_to_where_clause_sql()
* for the format
* @param string Join operator for the elements in the filter.
*
* @return mixed Value of first column of the first row. False if there were no row.
*/
function get_db_value_filter ($field, $table, $filter, $where_join = 'AND') {
if (! is_array ($filter) || empty ($filter))
return false;
/* Avoid limit and offset if given */
unset ($filter['limit']);
unset ($filter['offset']);
$sql = sprintf ("SELECT %s FROM %s WHERE %s LIMIT 1",
$field, $table,
format_array_to_where_clause_sql ($filter, $where_join));
$result = get_db_all_rows_sql ($sql);
if ($result === false)
return false;
return $result[0][$field];
}
/**
* Get the first row of an SQL database query.
*
* @param string SQL select statement to execute.
*
* @return mixed The first row of the result or false
*/
function get_db_row_sql ($sql) {
$sql .= " LIMIT 1";
$result = get_db_all_rows_sql ($sql);
if($result === false)
return false;
return $result[0];
}
/**
* Get the first row of a database query into a table.
*
* The SQL statement executed would be something like:
* "SELECT (*||$fields) FROM $table WHERE $field_search = $condition"
*
* @param string Table to get the row
* @param string Field to filter elements
* @param string Condition the field must have.
* @param mixed Fields to select (array or string or false/empty for *)
*
* @return mixed The first row of a database query or false.
*/
function get_db_row ($table, $field_search, $condition, $fields = false) {
if (empty ($fields)) {
$fields = '*';
} else {
if (is_array ($fields))
$fields = implode (',', $fields);
else if (! is_string ($fields))
return false;
}
if (is_int ($condition)) {
$sql = sprintf ("SELECT %s FROM `%s` WHERE `%s` = %d LIMIT 1",
$fields, $table, $field_search, $condition);
} else if (is_float ($condition) || is_double ($condition)) {
$sql = sprintf ("SELECT %s FROM `%s` WHERE `%s` = %f LIMIT 1",
$fields, $table, $field_search, $condition);
} else {
$sql = sprintf ("SELECT %s FROM `%s` WHERE `%s` = '%s' LIMIT 1",
$fields, $table, $field_search, $condition);
}
$result = get_db_all_rows_sql ($sql);
if ($result === false)
return false;
return $result[0];
}
/**
* Get the row of a table in the database using a complex filter.
*
* @param string Table to retrieve the data (warning: not cleaned)
* @param mixed Filters elements. It can be an indexed array
* (keys would be the field name and value the expected value, and would be
* joined with an AND operator) or a string, including any SQL clause (without
* the WHERE keyword). Example:
Both are similars:
get_db_row_filter ('table', array ('disabled', 0));
get_db_row_filter ('table', 'disabled = 0');
Both are similars:
get_db_row_filter ('table', array ('disabled' => 0, 'history_data' => 0), 'name, description', 'OR');
get_db_row_filter ('table', 'disabled = 0 OR history_data = 0', 'name, description');
get_db_row_filter ('table', array ('disabled' => 0, 'history_data' => 0), array ('name', 'description'), 'OR');
* @param mixed Fields of the table to retrieve. Can be an array or a coma
* separated string. All fields are retrieved by default
* @param string Condition to join the filters (AND, OR).
*
* @return mixed Array of the row or false in case of error.
*/
function get_db_row_filter ($table, $filter, $fields = false, $where_join = 'AND') {
if (empty ($fields)) {
$fields = '*';
} else {
if (is_array ($fields))
$fields = implode (',', $fields);
else if (! is_string ($fields))
return false;
}
if (is_array ($filter))
$filter = format_array_to_where_clause_sql ($filter, $where_join, ' WHERE ');
else if (is_string ($filter))
$filter = 'WHERE '.$filter;
else
$filter = '';
$sql = sprintf ('SELECT %s FROM %s %s',
$fields, $table, $filter);
return get_db_row_sql ($sql);
}
/**
* Get a single field in the databse from a SQL query.
*
* @param string SQL statement to execute
* @param mixed Field number or row to get, beggining by 0. Default: 0
*
* @return mixed The selected field of the first row in a select statement.
*/
function get_db_sql ($sql, $field = 0) {
$result = get_db_all_rows_sql ($sql);
if($result === false)
return false;
return $result[0][$field];
}
/**
* Get all the result rows using an SQL statement.
*
* @param string SQL statement to execute.
*
* @return mixed A matrix with all the values returned from the SQL statement or
* false in case of empty result
*/
function get_db_all_rows_sql ($sql) {
$return = process_sql ($sql);
if (! empty ($return))
return $return;
//Return false, check with === or !==
return false;
}
/**
* Get all the rows of a table in the database that matches a filter.
*
* @param string Table to retrieve the data (warning: not cleaned)
* @param mixed Filters elements. It can be an indexed array
* (keys would be the field name and value the expected value, and would be
* joined with an AND operator) or a string, including any SQL clause (without
* the WHERE keyword). Example:
Both are similars:
get_db_all_rows_filter ('table', array ('disabled', 0));
get_db_all_rows_filter ('table', 'disabled = 0');
Both are similars:
get_db_all_rows_filter ('table', array ('disabled' => 0, 'history_data' => 0), 'name', 'OR');
get_db_all_rows_filter ('table', 'disabled = 0 OR history_data = 0', 'name');
* @param mixed Fields of the table to retrieve. Can be an array or a coma
* separated string. All fields are retrieved by default
* @param string Condition of the filter (AND, OR).
*
* @return mixed Array of the row or false in case of error.
*/
function get_db_all_rows_filter ($table, $filter, $fields = false, $where_join = 'AND') {
//TODO: Validate and clean fields
if (empty ($fields)) {
$fields = '*';
} elseif (is_array ($fields)) {
$fields = implode (',', $fields);
} elseif (! is_string ($fields)) {
return false;
}
//TODO: Validate and clean filter options
if (is_array ($filter)) {
$filter = format_array_to_where_clause_sql ($filter, $where_join, ' WHERE ');
} elseif (is_string ($filter)) {
$filter = 'WHERE '.$filter;
} else {
$filter = '';
}
$sql = sprintf ('SELECT %s FROM %s %s', $fields, $table, $filter);
return get_db_all_rows_sql ($sql);
}
/**
* Error handler function when an SQL error is triggered.
*
* @param int Level of the error raised (not used, but required by set_error_handler()).
* @param string Contains the error message.
*
* @return bool True if error level is lower or equal than errno.
*/
function sql_error_handler ($errno, $errstr) {
global $config;
/* If debug is activated, this will also show the backtrace */
if (debug ($errstr))
return false;
if (error_reporting () <= $errno)
return false;
echo "SQL error: ".$errstr."
$values = array ();
$values['name'] = "Name";
$values['description'] = "Long description";
$sql = 'UPDATE table SET '.format_array_to_update_sql ($values).' WHERE id=1';
echo $sql;
* Will return:
UPDATE table SET `name` = "Name", `description` = "Long description" WHERE id=1
*
* @param array Values to be formatted in an array indexed by the field name.
*
* @return string Values joined into an SQL string that can fits into an UPDATE
* sentence.
*/
function format_array_to_update_sql ($values) {
$fields = array ();
foreach ($values as $field => $value) {
if (is_numeric ($field)) {
array_push ($fields, $value);
continue;
}
if ($value === NULL) {
$sql = sprintf ("`%s` = NULL", $field);
} elseif (is_int ($value) || is_bool ($value)) {
$sql = sprintf ("`%s` = %d", $field, $value);
} elseif (is_float ($value) || is_double ($value)) {
$sql = sprintf ("`%s` = %f", $field, $value);
} else {
/* String */
if (isset ($value[0]) && $value[0] == '`')
/* Don't round with quotes if it references a field */
$sql = sprintf ("`%s` = %s", $field, $value);
else
$sql = sprintf ("`%s` = '%s'", $field, $value);
}
array_push ($fields, $sql);
}
return implode (", ", $fields);
}
/**
* Formats an array of values into a SQL where clause string.
*
* This function is useful to generate a WHERE clause for a SQL sentence from
* a list of values. Example code:
$values = array ();
$values['name'] = "Name";
$values['description'] = "Long description";
$values['limit'] = $config['block_size']; // Assume it's 20
$sql = 'SELECT * FROM table WHERE '.format_array_to_where_clause_sql ($values);
echo $sql;
* Will return:
*
* SELECT * FROM table WHERE `name` = "Name" AND `description` = "Long description" LIMIT 20
*
*
* @param array Values to be formatted in an array indexed by the field name.
* There are special parameters such as 'limit' and 'offset' that will be used
* as ORDER, LIMIT and OFFSET clauses respectively. Since LIMIT and OFFSET are
* numerics, ORDER can receive a field name or a SQL function and a the ASC or
* DESC clause. Examples:
$values = array ();
$values['value'] = 10;
$sql = 'SELECT * FROM table WHERE '.format_array_to_where_clause_sql ($values);
// SELECT * FROM table WHERE VALUE = 10
$values = array ();
$values['value'] = 10;
$values['order'] = 'name DESC';
$sql = 'SELECT * FROM table WHERE '.format_array_to_where_clause_sql ($values);
// SELECT * FROM table WHERE VALUE = 10 ORDER BY name DESC
* @param string Join operator. AND by default.
* @param string A prefix to be added to the string. It's useful when limit and
* offset could be given to avoid this cases:
$values = array ();
$values['limit'] = 10;
$values['offset'] = 20;
$sql = 'SELECT * FROM table WHERE '.format_array_to_where_clause_sql ($values);
// Wrong SQL: SELECT * FROM table WHERE LIMIT 10 OFFSET 20
$values = array ();
$values['limit'] = 10;
$values['offset'] = 20;
$sql = 'SELECT * FROM table WHERE '.format_array_to_where_clause_sql ($values, 'AND', 'WHERE');
// Good SQL: SELECT * FROM table LIMIT 10 OFFSET 20
$values = array ();
$values['value'] = 5;
$values['limit'] = 10;
$values['offset'] = 20;
$sql = 'SELECT * FROM table WHERE '.format_array_to_where_clause_sql ($values, 'AND', 'WHERE');
// Good SQL: SELECT * FROM table WHERE value = 5 LIMIT 10 OFFSET 20
*
* @return string Values joined into an SQL string that can fits into the WHERE
* clause of an SQL sentence.
*/
function format_array_to_where_clause_sql ($values, $join = 'AND', $prefix = false) {
$fields = array ();
if (! is_array ($values)) {
return '';
}
$query = '';
$limit = '';
$offset = '';
$order = '';
$group = '';
if (isset ($values['limit'])) {
$limit = sprintf (' LIMIT %d', $values['limit']);
unset ($values['limit']);
}
if (isset ($values['offset'])) {
$offset = sprintf (' OFFSET %d', $values['offset']);
unset ($values['offset']);
}
if (isset ($values['order'])) {
$order = sprintf (' ORDER BY %s', $values['order']);
unset ($values['order']);
}
if (isset ($values['group'])) {
$group = sprintf (' GROUP BY %s', $values['group']);
unset ($values['group']);
}
$i = 1;
$max = count ($values);
foreach ($values as $field => $value) {
if (is_numeric ($field)) {
/* User provide the exact operation to do */
$query .= $value;
if ($i < $max) {
$query .= ' '.$join.' ';
}
$i++;
continue;
}
if ($field[0] != "`") {
$field = "`".$field."`";
}
if (is_null ($value)) {
$query .= sprintf ("%s IS NULL", $field);
} elseif (is_int ($value) || is_bool ($value)) {
$query .= sprintf ("%s = %d", $field, $value);
} else if (is_float ($value) || is_double ($value)) {
$query .= sprintf ("%s = %f", $field, $value);
} elseif (is_array ($value)) {
$query .= sprintf ('%s IN ("%s")', $field, implode ('", "', $value));
} else {
$query .= sprintf ("%s = '%s'", $field, $value);
}
if ($i < $max) {
$query .= ' '.$join.' ';
}
$i++;
}
return (! empty ($query) ? $prefix: '').$query.$group.$order.$limit.$offset;
}
/**
* Get the status of an agent module.
*
* @param int Id agent module to check.
*
* @return int Module status. Value 4 means that some alerts assigned to the
* module were fired.
*/
function get_agentmodule_status ($id_agentmodule = 0) {
$times_fired = get_db_value ('SUM(times_fired)', 'talert_template_modules', 'id_agent_module', $id_agentmodule);
if ($times_fired > 0) {
return 4; // Alert
}
$status = get_db_value ('estado', 'tagente_estado', 'id_agente_modulo', $id_agentmodule);
return $status;
}
/**
* Get the worst status of all modules of a given agent.
*
* @param int Id agent to check.
*
* @return int Worst status of an agent for all of its modules.
* The value -1 is returned in case the agent has exceed its interval.
*/
function get_agent_status ($id_agent = 0) {
$time = get_system_time ();
$status = get_db_value_filter ('COUNT(*)',
'tagente',
array ('id_agente' => (int) $id_agent,
'UNIX_TIMESTAMP(ultimo_contacto) + intervalo * 2 > '.$time,
'UNIX_TIMESTAMP(ultimo_contacto_remoto) + intervalo * 2 > '.$time));
if (! $status)
return -1;
$status = get_db_sql ("SELECT MAX(estado)
FROM tagente_estado, tagente_modulo
WHERE tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo
AND tagente_modulo.disabled = 0
AND tagente_modulo.delete_pending = 0
AND tagente_modulo.id_agente = $id_agent");
// TODO: Check any alert for that agent who has recept alerts fired
return $status;
}
/**
* Get the current value of an agent module.
*
* @param int Agent module id.
*
* @return int a numerically formatted value
*/
function get_agent_module_last_value ($id_agentmodule) {
return get_db_value ('datos', 'tagente_estado',
'id_agente_modulo', $id_agentmodule);
}
/**
* Get the X axis coordinate of a layout item
*
* @param int Id of the layout to get.
*
* @return int The X axis coordinate value.
*/
function get_layoutdata_x ($id_layoutdata) {
return (float) get_db_value ('pos_x', 'tlayout_data', 'id', (int) $id_layoutdata);
}
/**
* Get the Y axis coordinate of a layout item
*
* @param int Id of the layout to get.
*
* @return int The Y axis coordinate value.
*/
function get_layoutdata_y ($id_layoutdata){
return (float) get_db_value ('pos_y', 'tlayout_data', 'id', (int) $id_layoutdata);
}
/**
* 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 table which has a timestamp
* before the beginning of the interval. All this calculation is due
* to the data compression algorithm.
*
* @param int Agent module id
* @param int The timestamp to look backwards from and get the data.
*
* @return mixed The row of tagente_datos of the last period. False if there were no data.
*/
function get_previous_data ($id_agent_module, $utimestamp = 0) {
if (empty ($utimestamp))
$utimestamp = time ();
$interval = get_module_interval ($id_agent_module);
$sql = sprintf ('SELECT * FROM tagente_datos
WHERE id_agente_modulo = %d
AND utimestamp <= %d
AND utimestamp > %d
ORDER BY utimestamp DESC',
$id_agent_module, $utimestamp, $utimestamp - $interval);
return get_db_row_sql ($sql);
}
/**
* Get all the values of an agent module in a period of time.
*
* @param int Agent module id
* @param int Period of time to check (in seconds)
* @param int Top date to check the values. Default current time.
*
* @return array The module value and the timestamp
*/
function get_agentmodule_data ($id_agent_module, $period, $date = 0) {
if ($date < 1) {
$date = get_system_time ();
}
$datelimit = $date - $period;
$sql = sprintf ("SELECT datos AS data, utimestamp 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_all_rows_sql ($sql);
if ($values === false) {
return array ();
}
$module_name = get_agentmodule_name ($id_agent_module);
$agent_id = get_agentmodule_agent ($id_agent_module);
$agent_name = get_agentmodule_agent_name ($id_agent_module);
foreach ($values as $key => $data) {
$values[$key]["module_name"] = $module_name;
$values[$key]["agent_id"] = $agent_id;
$values[$key]["agent_name"] = $agent_name;
}
return $values;
}
/**
* Get the average value of an agent module in a period of time.
*
* @param int Agent module id
* @param int Period of time to check (in seconds)
* @param int Top date to check the values. Default current time.
*
* @return float The average module value in the interval.
*/
function get_agentmodule_data_average ($id_agent_module, $period, $date = 0) {
if ($date < 1) {
$date = get_system_time ();
}
$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);
} elseif ($total > 0) {
return $sum / $total;
}
return 0;
}
/**
* Get the maximum value of an agent module in a period of time.
*
* @param int Agent module id to get the maximum value.
* @param int Period of time to check (in seconds)
* @param int Top date to check the values. Default current time.
*
* @return float The maximum module value in the interval.
*/
function get_agentmodule_data_max ($id_agent_module, $period, $date = 0) {
if (! $date)
$date = get_system_time ();
$datelimit = $date - $period;
$sql = sprintf ("SELECT MAX(datos) FROM tagente_datos
WHERE id_agente_modulo = %d
AND utimestamp > %d AND utimestamp <= %d",
$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 !== false)
return max ($previous_data['datos'], $max);
return max ((float) $previous_data, $max);
}
/**
* Get the minimum value of an agent module in a period of time.
*
* @param int Agent module id to get the minimum value.
* @param int Period of time to check (in seconds)
* @param int Top date to check the values in Unix time. Default current time.
*
* @return float The minimum module value of the module
*/
function get_agentmodule_data_min ($id_agent_module, $period, $date = 0) {
if (! $date)
$date = get_system_time ();
$datelimit = $date - $period;
$sql = sprintf ("SELECT MIN(datos) FROM tagente_datos
WHERE id_agente_modulo = %d
AND utimestamp > %d AND utimestamp <= %d",
$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;
}
/**
* Get the sum of values of an agent module in a period of time.
*
* @param int Agent module id to get the sumatory.
* @param int Period of time to check (in seconds)
* @param int Top date to check the values. Default current time.
*
* @return float The sumatory of the module values in the interval.
*/
function get_agentmodule_data_sum ($id_agent_module, $period, $date = 0) {
if (! $date)
$date = get_system_time ();
$datelimit = $date - $period; // limit date
$id_module_type = get_db_value ('id_tipo_modulo', 'tagente_modulo','id_agente_modulo', $id_agent_module);
$module_name = get_db_value ('nombre', 'ttipo_modulo', 'id_tipo', $id_module_type);
if (is_module_data_string ($module_name)) {
return __('Wrong module type');
}
// Get the whole interval of data
$sql = sprintf ('SELECT utimestamp, datos FROM tagente_datos
WHERE id_agente_modulo = %d
AND utimestamp > %d AND utimestamp <= %d
ORDER BY utimestamp ASC',
$id_agent_module, $datelimit, $date);
$datas = get_db_all_rows_sql ($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);
}
if ($datas === false) {
return 0;
}
$last_data = "";
$total_badtime = 0;
$module_interval = get_module_interval ($id_agent_module);
$timestamp_begin = $datelimit + $module_interval;
$timestamp_end = 0;
$sum = 0;
$data_value = 0;
foreach ($datas as $data) {
$timestamp_end = $data["utimestamp"];
$elapsed = $timestamp_end - $timestamp_begin;
$times = intval ($elapsed / $module_interval);
if (is_module_inc ($module_name)) {
$data_value = $data['datos'] * $module_interval;
} else {
$data_value = $data['datos'];
}
$sum += $times * $data_value;
$timestamp_begin = $data["utimestamp"];
}
/* The last value must be get from tagente_estado, but
it will count only if it's not older than date demanded
*/
$timestamp_end = get_db_value ('utimestamp', 'tagente_estado', 'id_agente_modulo', $id_agent_module);
if ($timestamp_end <= $datelimit) {
$elapsed = $timestamp_end - $timestamp_begin;
$times = intval ($elapsed / $module_interval);
if (is_module_inc ($module_name)) {
$data_value = $data['datos'] * $module_interval;
} else {
$data_value = $data['datos'];
}
$sum += $times * $data_value;
}
return (float) $sum;
}
/**
* Get a translated string
*
* @param string String to translate. It can have special format characters like
* a printf
* @param mixed Optional parameters to be replaced in string. Example:
echo __('Hello!');
echo __('Hello, %s!', $user);
*
* @return string The translated string. If not defined, the same string will be returned
*/
function __ ($string /*, variable arguments */) {
global $l10n;
if (func_num_args () == 1) {
if (is_null ($l10n))
return $string;
return $l10n->translate ($string);
}
$args = func_get_args ();
$string = array_shift ($args);
if (is_null ($l10n))
return vsprintf ($string, $args);
return vsprintf ($l10n->translate ($string), $args);
}
/**
* Get the numbers of servers up.
*
* This check assumes that server_keepalive should be at least 15 minutes.
*
* @return int The number of servers alive.
*/
function check_server_status () {
$sql = "SELECT COUNT(id_server) FROM tserver WHERE status = 1 AND keepalive > NOW() - INTERVAL 15 MINUTE";
$status = (int) get_db_sql ($sql); //Cast as int will assure a number value
// Set servers to down
if ($status == 0){
process_sql ("UPDATE tserver SET status = 0");
}
return $status;
}
/**
* @deprecated Will show a small HTML table with some compound alert information
*/
function show_alert_row_mini ($id_combined_alert) {
$color=1;
$sql = sprintf ("SELECT talert_template_modules.*,tcompound_alert.operation
FROM talert_template_modules, tcompound_alert
WHERE tcompound_alert.id_aam = talert_template_modules.id
AND tcompound_alert.id = %d", $id_combined_alert);
$result = get_db_all_rows_sql ($sql);
if ($result === false)
return;
echo "".__('Name')." | "; echo "".__('Oper')." | "; /* Translators: Abbrevation for Time threshold */ echo "".__('Tt')." | "; echo "".__('Firing')." | "; echo "".__('Time')." | "; /* Translators: Abbrevation for Description */ echo "".__('Desc')." | "; echo "".__('Recovery')." | "; echo "".__('MinMax.Al')." | "; echo "".__('Days')." | "; echo "".__('Fired')." | "; foreach ($result as $row2) { if ($color == 1) { $tdcolor = "datos"; $color = 0; } else { $tdcolor = "datos2"; $color = 1; } echo "||
---|---|---|---|---|---|---|---|---|---|---|---|
".get_db_sql ("SELECT nombre FROM tagente_modulo WHERE id_agente_modulo =".$row2["id_agente_modulo"])." | "; echo "".$row2["operation"]." | "; echo "".human_time_description ($row2["time_threshold"])." | "; if ($row2["dis_min"]!=0) { $mytempdata = fmod ($row2["dis_min"], 1); if ($mytempdata == 0) { $mymin = intval ($row2["dis_min"]); } else { $mymin = format_for_graph ($row2["dis_min"]); } } else { $mymin = 0; } if ($row2["dis_max"]!=0) { $mytempdata = fmod ($row2["dis_max"], 1); if ($mytempdata == 0) { $mymax = intval ($row2["dis_max"]); } else { $mymax = format_for_graph ($row2["dis_max"]); } } else { $mymax = 0; } if (($mymin == 0) && ($mymax == 0)) { $mymin = __('N/A'); $mymax = $mymin; } // We have alert text ? if ($row2["alert_text"]!= "") { echo "".__('Text')." | "; } else { echo "".$mymin."/".$mymax." | "; } // Alert times echo ""; echo get_alert_times ($row2); // Description echo " | ".substr ($row2["descripcion"],0,20); // Has recovery notify activated ? if ($row2["recovery_notify"] > 0) { $recovery_notify = __('Yes'); } else { $recovery_notify = __('No'); } echo " | ".$recovery_notify; // calculare firing conditions if ($row2["alert_text"] != ""){ $firing_cond = __('Text')."(".substr ($row2["alert_text"],0,8).")"; } else { $firing_cond = $row2["min_alerts"]." / ".$row2["max_alerts"]; } echo " | ".$firing_cond; // calculate days $firing_days = get_alert_days ( $row2 ); echo " | ".$firing_days; // Fired ? if ($row2["times_fired"]>0) { echo " | "; } else { echo " | "; } } echo " |
process_sql_update ('table', array ('field' => 1), array ('id' => $id));
process_sql_update ('table', array ('field' => 1), array ('id' => $id, 'name' => $name));
process_sql_update ('table', array ('field' => 1), array ('id' => $id, 'name' => $name), 'OR');
process_sql_update ('table', array ('field' => 2), 'id in (1, 2, 3) OR id > 10');
*
*
* @param string Table to insert into
* @param array An associative array of values to update
* @param mixed An associative array of field and value matches. Will be joined
* with operator specified by $where_join. A custom string can also be provided.
* If nothing is provided, the update will affect all rows.
* @param string When a $where parameter is given, this will work as the glue
* between the fields. "AND" operator will be use by default. Other values might
* be "OR", "AND NOT", "XOR"
*
* @return mixed False in case of error or invalid values passed. Affected rows otherwise
*/
function process_sql_update ($table, $values, $where = false, $where_join = 'AND') {
$query = sprintf ("UPDATE `%s` SET %s",
$table,
format_array_to_update_sql ($values));
if ($where) {
if (is_string ($where)) {
// No clean, the caller should make sure all input is clean, this is a raw function
$query .= " WHERE ".$where;
} else if (is_array ($where)) {
$query .= format_array_to_where_clause_sql ($where, $where_join, ' WHERE ');
}
}
return process_sql ($query);
}
/**
* Delete database records.
*
* All values should be cleaned before passing. Quoting isn't necessary.
* Examples:
*
*
process_sql_delete ('table', array ('id' => 1));
// DELETE FROM table WHERE id = 1
process_sql_delete ('table', array ('id' => 1, 'name' => 'example'));
// DELETE FROM table WHERE id = 1 AND name = 'example'
process_sql_delete ('table', array ('id' => 1, 'name' => 'example'), 'OR');
// DELETE FROM table WHERE id = 1 OR name = 'example'
process_sql_delete ('table', 'id in (1, 2, 3) OR id > 10');
// DELETE FROM table WHERE id in (1, 2, 3) OR id > 10
*
*
* @param string Table to insert into
* @param array An associative array of values to update
* @param mixed An associative array of field and value matches. Will be joined
* with operator specified by $where_join. A custom string can also be provided.
* If nothing is provided, the update will affect all rows.
* @param string When a $where parameter is given, this will work as the glue
* between the fields. "AND" operator will be use by default. Other values might
* be "OR", "AND NOT", "XOR"
*
* @return mixed False in case of error or invalid values passed. Affected rows otherwise
*/
function process_sql_delete ($table, $where, $where_join = 'AND') {
if (empty ($where))
/* Should avoid any mistake that lead to deleting all data */
return false;
$query = sprintf ("DELETE FROM `%s` WHERE ", $table);
if ($where) {
if (is_string ($where)) {
/* FIXME: Should we clean the string for sanity?
Who cares if this is deleting data... */
$query .= $where;
} else if (is_array ($where)) {
$query .= format_array_to_where_clause_sql ($where, $where_join);
}
}
return process_sql ($query);
}
/**
* Starts a database transaction.
*/
function process_sql_begin () {
mysql_query ('SET AUTOCOMMIT = 0');
mysql_query ('START TRANSACTION');
}
/**
* Commits a database transaction.
*/
function process_sql_commit () {
mysql_query ('COMMIT');
mysql_query ('SET AUTOCOMMIT = 0');
}
/**
* Rollbacks a database transaction.
*/
function process_sql_rollback () {
mysql_query ('ROLLBACK');
mysql_query ('SET AUTOCOMMIT = 0');
}
/**
* Get all the users belonging to a group.
*
* @param int $id_group The group id to look for
*
* @return array An array with all the users or an empty array
*/
function get_group_users ($id_group, $filter = false) {
if (! is_array ($filter))
$filter = array ();
$filter['id_grupo'] = (int) $id_group;
$result = get_db_all_rows_filter ("tusuario_perfil", $filter);
if ($result === false)
return array ();
//This removes stale users from the list. This can happen if switched to another auth scheme
//(internal users still exist) or external auth has users removed/inactivated from the list (eg. LDAP)
$retval = array ();
foreach ($result as $key => $user) {
if (!is_user ($user)) {
unset ($result[$key]);
} else {
array_push ($retval, get_user_info ($user));
}
}
return $retval;
}
/**
* Prints a database debug table with all the queries done in the page loading.
*
* This functions does nothing if the config['debug'] flag is not set.
*/
function print_database_debug () {
global $config;
if (! isset ($config['debug']))
return '';
echo ''.__('Database debug').'';
$table->id = 'database_debug';
$table->cellpadding = '0';
$table->width = '95%';
$table->align = array ();
$table->align[1] = 'left';
$table->size = array ();
$table->size[0] = '40px';
$table->size[2] = '30%';
$table->size[3] = '40px';
$table->size[4] = '40px';
$table->size[5] = '40px';
$table->data = array ();
$table->head = array ();
$table->head[0] = '#';
$table->head[1] = __('SQL sentence');
$table->head[2] = __('Result');
$table->head[3] = __('Rows');
$table->head[4] = __('Saved');
$table->head[5] = __('Time (ms)');
if (! isset ($config['db_debug']))
$config['db_debug'] = array ();
$i = 1;
foreach ($config['db_debug'] as $debug) {
$data = array ();
$data[0] = $i++;
$data[1] = $debug['sql'];
$data[2] = (empty ($debug['result']) ? __('OK') : $debug['result']);
$data[3] = $debug['affected'];
$data[4] = $debug['saved'];
$data[5] = (isset ($debug['extra']['time']) ? format_numeric ($debug['extra']['time'] * 1000, 0) : '');
array_push ($table->data, $data);
if (($i % 100) == 0) {
print_table ($table);
$table->data = array ();
}
}
print_table ($table);
}
/**
* Return access to a specific agent by a specific user
*
* @param int Agent id.
* @param string Access mode to be checked. Default AR (Agent reading)
* @param string User id. Current user by default
*
* @return bool Access to that agent (false not, true yes)
*/
function user_access_to_agent ($id_agent, $mode = "AR", $id_user = false) {
if (empty ($id_agent))
return false;
if ($id_user == false) {
global $config;
$id_user = $config['id_user'];
}
$id_group = (int) get_db_value ('id_grupo', 'tagente', 'id_agente', (int) $id_agent);
return (bool) give_acl ($id_user, $id_group, $mode);
}
?>