Merge branch '1827-Graficas_TIP_eje_x_no_mantiene_ratio' into 'develop'

1827 graficas tip eje x no mantiene ratio

See merge request artica/pandorafms!1268
This commit is contained in:
vgilc 2018-06-11 14:01:48 +02:00
commit 00f3d091f0
71 changed files with 23666 additions and 8669 deletions

View File

@ -39,14 +39,40 @@ function pandora_realtime_graphs () {
$legend = '';
$long_index = array();
$no_data_image = '';
$canvas = '<div id="graph_container">';
$canvas .= '<div id="chartLegend"></div>';
$canvas .= area_graph($interactive_graph, $chart, 800, 300, $color, $legend, $long_index, $no_data_image, "", "", "",
"", '', '', '', 1, array(), array(), 0, 0, '', false, '', false);
$width = 800;
$height = 300;
$data_array['realtime']['data'][0][0] = time() - 10;
$data_array['realtime']['data'][0][1] = 0;
$data_array['realtime']['data'][1][0] = time();
$data_array['realtime']['data'][1][1] = 0;
$data_array['realtime']['color'] = 'green';
$params =array(
'agent_module_id' => false,
'period' => 300,
'width' => $width,
'height' => $height,
'unit' => $unit,
'only_image' => $only_image,
'homeurl' => $homeurl,
'type_graph' => 'area',
'font' => $config['fontpath'],
'font-size' => $config['font_size'],
'array_data_create' => $data_array,
'show_legend' => false,
'show_menu' => false
);
$canvas .= grafico_modulo_sparse($params);
$canvas .= '</div>';
echo $canvas;
$table->width = '100%';
$table->id = 'table-form';
$table->class = 'databox filters';
@ -62,7 +88,7 @@ function pandora_realtime_graphs () {
$table->style['snmp_oid'] = 'font-weight: bold;';
$table->style['snmp_oid'] = 'font-weight: bold;';
$table->data = array ();
$graph_fields['cpu_load'] = __('%s Server CPU', get_product_name());
$graph_fields['pending_packets'] = __('Pending packages from %s Server', get_product_name());
$graph_fields['disk_io_wait'] = __('%s Server Disk IO Wait', get_product_name());
@ -70,19 +96,19 @@ function pandora_realtime_graphs () {
$graph_fields['mysql_load'] = __('%s Server MySQL load', get_product_name());
$graph_fields['server_load'] = __('%s Server load', get_product_name());
$graph_fields['snmp_interface'] = __('SNMP Interface throughput');
$graph = get_parameter('graph', 'cpu_load');
$refresh = get_parameter('refresh', '1000');
if ($graph != 'snmp_module') {
$data['graph'] = __('Graph') . '&nbsp;&nbsp;' . html_print_select ($graph_fields, 'graph', $graph, '', '', 0, true);
}
$refresh_fields[1000] = human_time_description_raw(1, true, 'large');
$refresh_fields[5000] = human_time_description_raw(5, true, 'large');
$refresh_fields[1000] = human_time_description_raw(1, true, 'large');
$refresh_fields[5000] = human_time_description_raw(5, true, 'large');
$refresh_fields[10000] = human_time_description_raw(10, true, 'large');
$refresh_fields[30000] = human_time_description_raw(30, true, 'large');
if ($graph == 'snmp_module') {
$agent_alias = get_parameter('agent_alias', '');
$module_name = get_parameter('module_name', '');
@ -109,7 +135,7 @@ function pandora_realtime_graphs () {
$snmp_ver = get_parameter('snmp_ver', '');
$data = array();
$data['snmp_address'] = __('Target IP') . '&nbsp;&nbsp;' . html_print_input_text ('ip_target', $snmp_address, '', 50, 255, true);
$table->colspan[1]['snmp_address'] = 2;
@ -122,7 +148,7 @@ function pandora_realtime_graphs () {
$snmp_versions['1'] = '1';
$snmp_versions['2'] = '2';
$snmp_versions['2c'] = '2c';
$data = array();
$data['snmp_oid'] = __('OID') . '&nbsp;&nbsp;' . html_print_input_text ('snmp_oid', $snmp_oid, '', 100, 255, true);
$table->colspan[2]['snmp_oid'] = 2;
@ -140,7 +166,7 @@ function pandora_realtime_graphs () {
}
snmp_browser_print_container (false, '100%', '60%', 'none');
}
// Print the relative path to AJAX calls:
html_print_input_hidden('rel_path', get_parameter('rel_path', ''));
@ -148,7 +174,7 @@ function pandora_realtime_graphs () {
echo '<form id="realgraph" method="post">';
html_print_table($table);
echo '</form>';
// Define a custom action to save the OID selected in the SNMP browser to the form
html_print_input_hidden ('custom_action', urlencode (base64_encode('&nbsp;<a href="javascript:setOID()"><img src="' . ui_get_full_url("images") . '/input_filter.disabled.png" title="' . __("Use this OID") . '" style="vertical-align: middle;"></img></a>')), false);
html_print_input_hidden ('incremental_base', '0');
@ -156,7 +182,7 @@ function pandora_realtime_graphs () {
echo '<script type="text/javascript" src="'.ui_get_full_url("extensions/realtime_graphs/realtime_graphs.js").'"></script>';
echo '<script type="text/javascript" src="'.ui_get_full_url("include/javascript/pandora_snmp_browser.js").'"></script>';
echo '<link rel="stylesheet" type="text/css" href="'.ui_get_full_url("extensions/realtime_graphs/realtime_graphs.css").'"></style>';
// Store servers timezone offset to be retrieved from js
set_js_value('timezone_offset', date('Z', time()));
}

View File

@ -2919,7 +2919,7 @@ function chooseType() {
case 'simple_graph':
$("#row_time_compare_overlapped").show();
$("#row_only_avg").show();
// $("#row_only_avg").show();
$("#row_fullscale").show();
if ($("#checkbox-percentil").prop("checked"))
$("#row_percentil").show();
@ -2930,7 +2930,6 @@ function chooseType() {
$("#row_agent").show();
$("#row_module").show();
$("#row_period").show();
$("#row_show_in_two_columns").show();
$("#row_show_in_landscape").show();
$("#row_time_compare_overlapped").show();
$("#row_historical_db_check").hide();

View File

@ -22,7 +22,7 @@ $get_graphs = (bool)get_parameter('get_graphs_container');
if ($save_custom_graph) {
$return = array();
$id_modules = (array)get_parameter('id_modules', array());
$name = get_parameter('name', '');
$description = get_parameter('description', '');
@ -32,87 +32,90 @@ if ($save_custom_graph) {
$events = get_parameter('events', 0);
$period = get_parameter('period', 0);
$fullscale = get_parameter('fullscale', 0);
$result = (bool)custom_graphs_create($id_modules, $name,
$description, $stacked, $width, $height, $events, $period, 0, 0, false, $fullscale);
$return['correct'] = $result;
echo json_encode($return);
return;
}
if ($print_custom_graph) {
ob_clean();
$id_graph = (int) get_parameter('id_graph');
$height = (int) get_parameter('height', CHART_DEFAULT_HEIGHT);
$width = (int) get_parameter('width', CHART_DEFAULT_WIDTH);
$period = (int) get_parameter('period', SECONDS_5MINUTES);
$stacked = (int) get_parameter('stacked', CUSTOM_GRAPH_LINE);
$date = (int) get_parameter('date', time());
$only_image = (bool) get_parameter('only_image');
$background_color = (string) get_parameter('background_color', 'white');
$modules_param = get_parameter('modules_param', array());
$homeurl = (string) get_parameter('homeurl');
$name_list = get_parameter('name_list', array());
$unit_list = get_parameter('unit_list', array());
$show_last = (bool) get_parameter('show_last', true);
$show_max = (bool) get_parameter('show_max', true);
$show_min = (bool) get_parameter('show_min', true);
$show_avg = (bool) get_parameter('show_avg', true);
$ttl = (int) get_parameter('ttl', 1);
$dashboard = (bool) get_parameter('dashboard');
$vconsole = (bool) get_parameter('vconsole');
$fullscale = (bool) get_parameter('fullscale');
echo custom_graphs_print($id_graph, $height, $width, $period, $stacked,
true, $date, $only_image, $background_color, $modules_param,
$homeurl, $name_list, $unit_list, $show_last, $show_max,
$show_min, $show_avg, $ttl, $dashboard, $vconsole);
$params =array(
'period' => (int) get_parameter('period', SECONDS_5MINUTES),
'width' => (int) get_parameter('width', CHART_DEFAULT_WIDTH),
'height' => (int) get_parameter('height', CHART_DEFAULT_HEIGHT),
'unit_name' => get_parameter('unit_list', array()),
'date' => (int) get_parameter('date', time()),
'only_image' => (bool) get_parameter('only_image', false),
'homeurl' => (string) get_parameter('homeurl', ''),
'ttl' => (int) get_parameter('ttl', 1),
'dashboard' => (bool) get_parameter('dashboard', false),
'vconsole' => (bool) get_parameter('vconsole', false),
'fullscale' => (bool) get_parameter('fullscale', false),
'backgroundColor' => (string) get_parameter('background_color', 'white'),
'show_alerts' => (bool) get_parameter('show_alerts'),
'show_events' => (bool) get_parameter('show_events'),
'type_graph' => get_parameter('type_g', $config['type_module_charts']),
);
$params_combined = array(
'stacked' => (int) get_parameter('stacked', CUSTOM_GRAPH_LINE),
'labels' => get_parameter('name_list', array()),
'modules_series' => get_parameter('modules_param', array()),
'id_graph' => (int) get_parameter('id_graph', 0),
'return' => 1
);
echo graphic_combined_module(
get_parameter('modules_param', array()),
$params,
$params_combined
);
return;
}
if ($print_sparse_graph) {
ob_clean();
$agent_module_id = (int) get_parameter('agent_module_id');
$period = (int) get_parameter('period', SECONDS_5MINUTES);
$show_events = (bool) get_parameter('show_events');
$width = (int) get_parameter('width', CHART_DEFAULT_WIDTH);
$height = (int) get_parameter('height', CHART_DEFAULT_HEIGHT);
$title = (string) get_parameter('title');
$unit_name = (string) get_parameter('unit_name');
$show_alerts = (bool) get_parameter('show_alerts');
$avg_only = (int) get_parameter('avg_only');
$pure = (bool) get_parameter('pure');
$date = (int) get_parameter('date', time());
$unit = (string) get_parameter('unit');
$baseline = (int) get_parameter('baseline');
$return_data = (int) get_parameter('return_data');
$show_title = (bool) get_parameter('show_title', true);
$only_image = (bool) get_parameter('only_image');
$homeurl = (string) get_parameter('homeurl');
$ttl = (int) get_parameter('ttl', 1);
$projection = (bool) get_parameter('projection');
$adapt_key = (string) get_parameter('adapt_key');
$compare = (bool) get_parameter('compare');
$show_unknown = (bool) get_parameter('show_unknown');
$menu = (bool) get_parameter('menu', true);
$background_color = (string) get_parameter('background_color', 'white');
$percentil = get_parameter('percentil', null);
$dashboard = (bool) get_parameter('dashboard');
$vconsole = (bool) get_parameter('vconsole');
$type_g = get_parameter('type_g', $config['type_module_charts']);
$fullscale = get_parameter('fullscale', 0);
echo grafico_modulo_sparse($agent_module_id, $period, $show_events,
$width, $height , $title, $unit_name, $show_alerts, $avg_only,
$pure, $date, $unit, $baseline, $return_data, $show_title,
$only_image, $homeurl, $ttl, $projection, $adapt_key, $compare,
$show_unknown, $menu, $backgroundColor, $percentil,
$dashboard, $vconsole, $type_g, $fullscale);
$params =array(
'agent_module_id' => (int)get_parameter('agent_module_id'),
'period' => (int) get_parameter('period', SECONDS_5MINUTES),
'show_events' => (bool) get_parameter('show_events'),
'title' => (string) get_parameter('title'),
'unit_name' => (string) get_parameter('unit_name'),
'show_alerts' => (bool) get_parameter('show_alerts'),
'avg_only' => (int) get_parameter('avg_only'),
'pure' => (bool) get_parameter('pure'),
'date' => (int) get_parameter('date', time()),
'unit' => (string) get_parameter('unit'),
'baseline' => (int) get_parameter('baseline'),
'return_data' => (int) get_parameter('return_data'),
'show_title' => (bool) get_parameter('show_title', true),
'only_image' => (bool) get_parameter('only_image'),
'homeurl' => (string) get_parameter('homeurl'),
'ttl' => (int) get_parameter('ttl', 1),
'projection' => (bool) get_parameter('projection'),
'adapt_key' => (string) get_parameter('adapt_key'),
'compare' => (bool) get_parameter('compare'),
'show_unknown' => (bool) get_parameter('show_unknown'),
'menu' => (bool) get_parameter('menu', true),
'backgroundColor' => (string) get_parameter('background_color', 'white'),
'percentil' => get_parameter('percentil', null),
'dashboard' => (bool) get_parameter('dashboard'),
'vconsole' => (bool) get_parameter('vconsole'),
'type_graph' => get_parameter('type_g', $config['type_module_charts']),
'fullscale' => get_parameter('fullscale', 0),
'id_widget_dashboard' => false,
'force_interval' => '',
'time_interval' => 300,
'array_data_create' => 0
);
echo grafico_modulo_sparse($params);
return;
}
@ -124,7 +127,7 @@ if ($get_graphs){
if (!empty($result_items)){
$hash = get_parameter('hash',0);
$period = get_parameter('time',0);
$periods = array ();
$periods[1] = __('none');
$periods[SECONDS_1HOUR] = __('1 hour');
@ -137,7 +140,7 @@ if ($get_graphs){
$periods[SECONDS_1WEEK] = __('1 week');
$periods[SECONDS_15DAYS] = __('15 days');
$periods[SECONDS_1MONTH] = __('1 month');
$table = '';
$single_table = "<table width='100%' cellpadding=4 cellspacing=4>";
$single_table .= "<tr id='row_time_lapse' style='' class='datos'>";
@ -151,7 +154,7 @@ if ($get_graphs){
$single_table .= "</td>";
$single_table .= "</tr>";
$single_table .= "</table>";
$table .= $single_table;
$contador = $config['max_graph_container'];
foreach ($result_items as $key => $value) {
@ -159,9 +162,9 @@ if ($get_graphs){
if($period > 1){
$value['time_lapse'] = $period;
}
$type_graph = ($value['type_graph'])? "line" : "area";
switch ($value['type']) {
case 'simple_graph':
if ($contador > 0) {
@ -170,60 +173,23 @@ if ($get_graphs){
$sql_alias = db_get_all_rows_sql("SELECT alias from tagente
WHERE id_agente = ". $sql_modulo[0]['id_agente']);
$table .= "<div style='width: 90%'><h4>AGENT " .$sql_alias[0]['alias']." MODULE ".$sql_modulo[0]['nombre']."</h4><hr></div>";
$table .= grafico_modulo_sparse(
$value['id_agent_module'],
$value['time_lapse'],
0,
1000,
300,
'',
'',
false,
$value['only_average'],
false,
0,
'',
0,
0,
1,
false,
ui_get_full_url(false, false, false, false),
1,
false,
0,
false,
false,
1,
'white',
null,
false,
false,
$type_graph,
$value['fullscale']);
$params =array(
'agent_module_id' => $value['id_agent_module'],
'period' => $value['time_lapse'],
'avg_only' => $value['only_average'],
'homeurl' => ui_get_full_url(false, false, false, false),
'type_graph' => $type_graph,
'fullscale' => $value['fullscale']
);
$table .= grafico_modulo_sparse($params);
$contador --;
}
// $table .= "</br>";
break;
case 'custom_graph':
if ($contador > 0) {
$graph = db_get_all_rows_field_filter('tgraph', 'id_graph',$value['id_graph']);
$sources = db_get_all_rows_field_filter('tgraph_source', 'id_graph',$value['id_graph']);
$modules = array ();
$weights = array ();
$labels = array ();
foreach ($sources as $source) {
array_push ($modules, $source['id_agent_module']);
array_push ($weights, $source['weight']);
if ($source['label'] != ''){
$item['type'] = 'custom_graph';
$item['id_agent'] = agents_get_module_id($source['id_agent_module']);
$item['id_agent_module'] = $source['id_agent_module'];
$labels[$source['id_agent_module']] = reporting_label_macro($item, $source['label']);
}
}
$homeurl = ui_get_full_url(false, false, false, false);
$graph_conf = db_get_row('tgraph', 'id_graph', $value['id_graph']);
if($graph_conf['stacked'] == 4 || $graph_conf['stacked'] == 9){
@ -233,40 +199,28 @@ if ($get_graphs){
} else {
$height = 300;
}
$table .= "<div style='width: 90%'><h4>".$graph[0]['name']."</h4><hr></div>";
$table .= graphic_combined_module(
$modules,
$weights,
$value['time_lapse'],
1000,
$height,
'',
'',
0,
0,
0,
$graph_conf['stacked'],
0,
false,
$homeurl,
1,
false,
false,
'white',
array(),
array(),
1,
1,
1,
1,
$labels,
false,
false,
$graph_conf['percentil'] == 1,
false,
false,
$value['fullscale']
$params =array(
'period' => $value['time_lapse'],
'width' => 1000,
'height' => $height,
'percentil' => $graph_conf['percentil'] == 1,
'fullscale' => $value['fullscale']
);
$params_combined = array(
'stacked' => $graph_conf['stacked'],
'id_graph' => $value['id_graph']
);
$table .= graphic_combined_module(
false,
$params,
$params_combined
);
$contador --;
}
break;
@ -280,13 +234,13 @@ if ($get_graphs){
} else {
$id_group = " AND id_grupo = ".$value['id_group'];
}
if($value['id_module_group'] === '0'){
$id_module_group = "";
} else {
$id_module_group = " AND id_module_group = ".$value['id_module_group'];
}
if($value['id_tag'] === '0'){
$tag = "";
$id_tag = "";
@ -294,7 +248,7 @@ if ($get_graphs){
$tag = " INNER JOIN ttag_module ON ttag_module.id_agente_modulo = tagente_modulo.id_agente_modulo ";
$id_tag = " AND ttag_module.id_tag = ".$value['id_tag'];
}
if($value['module'] != ''){
$module_name = " AND nombre REGEXP '".$value['module']."'";
}
@ -303,47 +257,27 @@ if ($get_graphs){
". $tag . "WHERE 1=1" . $id_module_group . $module_name .
" AND id_agente IN (SELECT id_agente FROM tagente WHERE 1=1" .$alias.$id_group.")"
. $id_tag);
foreach ($id_agent_module as $key2 => $value2) {
if ($contador > 0) {
$sql_modulo2 = db_get_all_rows_sql("SELECT nombre, id_agente FROM
tagente_modulo WHERE id_agente_modulo = ". $value2['id_agente_modulo']);
$sql_alias2 = db_get_all_rows_sql("SELECT alias from tagente
WHERE id_agente = ". $sql_modulo2[0]['id_agente']);
$table .= "<div style='width: 90%'><h4>AGENT " .$sql_alias2[0]['alias']." MODULE ".$sql_modulo2[0]['nombre']."</h4><hr></div>";
$table .= grafico_modulo_sparse(
$value2['id_agente_modulo'],
$value['time_lapse'],
0,
1000,
300,
'',
'',
false,
$value['only_average'],
false,
0,
'',
0,
0,
1,
false,
ui_get_full_url(false, false, false, false),
1,
false,
0,
false,
false,
1,
'white',
null,
false,
false,
$type_graph,
$value['fullscale']);
$params =array(
'agent_module_id' => $value2['id_agente_modulo'],
'period' => $value['time_lapse'],
'avg_only' => $value['only_average'],
'homeurl' => ui_get_full_url(false, false, false, false),
'type_graph' => $type_graph,
'fullscale' => $value['fullscale']
);
$table .= grafico_modulo_sparse($params);
$contador --;
}
}
@ -353,7 +287,6 @@ if ($get_graphs){
$table .= "</br>";
echo $table;
return;
}
}

View File

@ -251,20 +251,41 @@ switch ($action) {
continue;
}
}
$params =array(
'period' => $period,
'width' => $width,
'height' => $height,
'vconsole' => true,
'backgroundColor'=> $background_color
);
$params_combined = array(
'id_graph' => $id_custom_graph
);
if ($id_custom_graph != 0) {
$img = custom_graphs_print(
$id_custom_graph, $height, $width, $period,
null, true, 0, true, $background_color);
$img = graphic_combined_module(
false,
$params,
$params_combined
);
}
else {
$img = grafico_modulo_sparse($id_agent_module,
$period, 0, $width, $height, '', null, false, 1,
0, 0, '', 0, 0, true, true, '', 1, false, '',
false, false, true, $background_color,
false, false, false, $config['type_module_charts']);
$params =array(
'agent_module_id' => $id_agent_module,
'period' => $period,
'show_events' => false,
'width' => $width,
'height' => $height,
'menu' => false,
'backgroundColor' => $background_color,
'vconsole' => true,
'type_graph' => $config['type_module_charts']
);
$img = grafico_modulo_sparse($params);
}
//Restore db connection
if (!empty($id_metaconsole)) {
metaconsole_restore_db();

View File

@ -0,0 +1,120 @@
<?php
// Pandora FMS - http://pandorafms.com
// ==================================================
// Copyright (c) 2005-2018 Artica Soluciones Tecnologicas
// Please see http://pandorafms.org for full contribution list
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation for version 2.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Global & session manageme
session_id($_GET["session_id"]);
session_start();
session_write_close();
require_once ('config.php');
require_once ($config['homedir'] . '/include/auth/mysql.php');
require_once ($config['homedir'] . '/include/functions.php');
require_once ($config['homedir'] . '/include/functions_db.php');
require_once ($config['homedir'] . '/include/functions_reporting.php');
require_once ($config['homedir'] . '/include/functions_graph.php');
require_once ($config['homedir'] . '/include/functions_custom_graphs.php');
require_once ($config['homedir'] . '/include/functions_modules.php');
require_once ($config['homedir'] . '/include/functions_agents.php');
require_once ($config['homedir'] . '/include/functions_tags.php');
check_login();
global $config;
/*
$params_json = base64_decode((string) get_parameter('params'));
$params = json_decode($params_json, true);
// Metaconsole connection to the node
$server_id = (int) (isset($params['server']) ? $params['server'] : 0);
if ($config["metaconsole"] && !empty($server_id)) {
$server = metaconsole_get_connection_by_id($server_id);
// Error connecting
if (metaconsole_connect($server) !== NOERR) {
echo "<html>";
echo "<body>";
ui_print_error_message(__('There was a problem connecting with the node'));
echo "</body>";
echo "</html>";
exit;
}
}
*/
$user_language = get_user_language($config['id_user']);
if (file_exists ('languages/'.$user_language.'.mo')) {
$l10n = new gettext_reader (new CachedFileReader ('languages/'.$user_language.'.mo'));
$l10n->load_tables();
}
?>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pandora FMS Graph (<?php echo agents_get_alias($agent_id) . ' - ' . $interface_name; ?>)</title>
<link rel="stylesheet" href="styles/pandora.css" type="text/css" />
<link rel="stylesheet" href="styles/pandora_minimal.css" type="text/css" />
<link rel="stylesheet" href="styles/jquery-ui-1.10.0.custom.css" type="text/css" />
<script language="javascript" type='text/javascript' src='javascript/pandora.js'></script>
<script language="javascript" type='text/javascript' src='javascript/jquery-1.9.0.js'></script>
<script language="javascript" type='text/javascript' src='javascript/jquery.pandora.js'></script>
<script language="javascript" type='text/javascript' src='javascript/jquery.jquery-ui-1.10.0.custom.js'></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.min.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.time.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.pie.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.crosshair.min.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.stack.min.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.selection.min.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.resize.min.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.threshold.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.threshold.multiple.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.symbol.min.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.exportdata.pandora.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/jquery.flot.axislabels.js"></script>
<script language="javascript" type="text/javascript" src="graphs/flot/pandora.flot.js"></script>
</head>
<body bgcolor="#ffffff" style='background:#ffffff;'>
<?php
$params = json_decode($_GET['data'], true);
$params['only_image'] = false;
$params['width'] = '1048';
$params['menu'] = false;
$params_combined = json_decode($_GET['data_combined'], true);
$module_list = json_decode($_GET['data_module_list'], true);
$type_graph_pdf = $_GET['type_graph_pdf'];
if($type_graph_pdf == 'combined'){
echo '<div>';
echo graphic_combined_module(
$module_list,
$params,
$params_combined
);
echo '</div>';
}
elseif($type_graph_pdf == 'sparse'){
echo '<div>';
echo grafico_modulo_sparse($params);
echo '</div>';
}
?>
</body>
</html>

View File

@ -2798,12 +2798,12 @@ function register_pass_change_try ($id_user, $success) {
}
function isJson($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
/**
* returns true or false if it is a valid ip
* returns true or false if it is a valid ip
* checking ipv4 and ipv6 or resolves the name dns
* @param string address
*
@ -2824,6 +2824,372 @@ function validate_address($address){
return true;
}
function color_graph_array(){
global $config;
$color_series = array();
$color_series[0] = array(
'border' => '#000000',
'color' => $config['graph_color1'],
'alpha' => CHART_DEFAULT_ALPHA
);
//XXX Hablar con Sancho del tema de los slices
/*
$color_series[1] = array(
'border' => '#000000',
'color' => $config['graph_color2'],
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series[2] = array(
'border' => '#000000',
'color' => $config['graph_color3'],
'alpha' => CHART_DEFAULT_ALPHA
);
*/
$color_series[1] = array(
'border' => '#000000',
'color' => $config['graph_color4'],
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series[2] = array(
'border' => '#000000',
'color' => $config['graph_color5'],
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series[3] = array(
'border' => '#000000',
'color' => $config['graph_color6'],
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series[4] = array(
'border' => '#000000',
'color' => $config['graph_color7'],
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series[5] = array(
'border' => '#000000',
'color' => $config['graph_color8'],
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series[6] = array(
'border' => '#000000',
'color' => $config['graph_color9'],
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series[7] = array(
'border' => '#000000',
'color' => $config['graph_color10'],
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series[8] = array(
'border' => '#000000',
'color' => COL_GRAPH9,
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series[9] = array(
'border' => '#000000',
'color' => COL_GRAPH10,
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series[10] = array(
'border' => '#000000',
'color' => COL_GRAPH11,
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series[11] = array(
'border' => '#000000',
'color' => COL_GRAPH12,
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series[12] = array(
'border' => '#000000',
'color' => COL_GRAPH13,
'alpha' => CHART_DEFAULT_ALPHA
);
//XXX Colores fijos para eventos, alertas, desconocidos, percentil, overlapped, summatory, average, projection
$color_series['event'] = array(
'border' => '#ff0000',
'color' => '#FF5733',
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series['alert'] = array(
'border' => '#ffff00',
'color' => '#ffff00',
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series['unknown'] = array(
'border' => '#999999',
'color' => '#E1E1E1',
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series['percentil'] = array(
'border' => '#000000',
'color' => '#003333',
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series['projection'] = array(
'border' => '#000000',
'color' => $config['graph_color8'],
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series['overlapped'] = array(
'border' => '#000000',
'color' => $config['graph_color9'],
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series['summatory'] = array(
'border' => '#000000',
'color' => $config['graph_color7'],
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series['average'] = array(
'border' => '#000000',
'color' => $config['graph_color10'],
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series['no_data'] = array(
'border' => '#000000',
'color' => '#f2c40e',
'alpha' => CHART_DEFAULT_ALPHA
);
$color_series['unit'] = array(
'border' => null,
'color' => '#0097BC',
'alpha' => 10
);
//XXXXXXXX
/*
if($id_widget_dashboard){
$opcion = unserialize(db_get_value_filter('options','twidget_dashboard',array('id' => $id_widget_dashboard)));
foreach ($module_list as $key => $value) {
if(!empty($opcion[$value])){
$color[$key]['color'] = $opcion[$value];
}
}
}
*/
return $color_series;
}
function series_type_graph_array($data, $show_elements_graph){
global $config;
if(isset($show_elements_graph['stacked'])){
switch ($show_elements_graph['stacked']) {
case 2:
case 4:
$type_graph = 'line';
break;
default:
$type_graph = 'area';
break;
}
}
else{
$type_graph = $show_elements_graph['type_graph'];
}
$color_series = color_graph_array();
$i = 0;
if(isset($data) && is_array($data)){
foreach ($data as $key => $value) {
if($show_elements_graph['compare'] == 'overlapped'){
if($key == 'sum2'){
$str = ' (' . __('Previous') . ')';
}
}
if(strpos($key, 'summatory') !== false){
$data_return['series_type'][$key] = $type_graph;
$data_return['legend'][$key] = __('Summatory series') . ' ' . $str;
$data_return['color'][$key] = $color_series['summatory'];
}
elseif(strpos($key, 'average') !== false){
$data_return['series_type'][$key] = $type_graph;
$data_return['legend'][$key] = __('Average series') . ' ' . $str;
$data_return['color'][$key] = $color_series['average'];
}
elseif(strpos($key, 'sum') !== false || strpos($key, 'baseline') !== false){
switch ($value['id_module_type']) {
case 21: case 2: case 6:
case 18: case 9: case 31:
$data_return['series_type'][$key] = 'boolean';
break;
default:
$data_return['series_type'][$key] = $type_graph;
break;
}
if (isset($show_elements_graph['labels']) &&
is_array($show_elements_graph['labels']) &&
(count($show_elements_graph['labels']) > 0)){
$data_return['legend'][$key] = $show_elements_graph['labels'][$value['agent_module_id']] . ' ' ;
}
else{
if(strpos($key, 'baseline') !== false){
$data_return['legend'][$key] = $value['agent_alias'] . ' / ' .
$value['module_name'] . ' Baseline ';
}
else{
$data_return['legend'][$key] = $value['agent_alias'] . ' / ' .
$value['module_name'] . ': ';
}
}
if(strpos($key, 'baseline') === false){
$data_return['legend'][$key] .=
__('Min:') . remove_right_zeros(
number_format(
$value['min'],
$config['graph_precision']
)
) . ' ' .
__('Max:') . remove_right_zeros(
number_format(
$value['max'],
$config['graph_precision']
)
) . ' ' .
_('Avg:') . remove_right_zeros(
number_format(
$value['avg'],
$config['graph_precision']
)
) . ' ' . $str;
}
if($show_elements_graph['compare'] == 'overlapped'){
$data_return['color'][$key] = $color_series['overlapped'];
}
else{
$data_return['color'][$key] = $color_series[$i];
$i++;
}
}
elseif(strpos($key, 'event') !== false){
$data_return['series_type'][$key] = 'points';
if($show_elements_graph['show_events']){
$data_return['legend'][$key] = __('Events') . ' ' . $str;
}
$data_return['color'][$key] = $color_series['event'];
}
elseif(strpos($key, 'alert') !== false){
$data_return['series_type'][$key] = 'points';
if($show_elements_graph['show_alerts']){
$data_return['legend'][$key] = __('Alert') . ' ' . $str;
}
$data_return['color'][$key] = $color_series['alert'];
}
elseif(strpos($key, 'unknown') !== false){
$data_return['series_type'][$key] = 'unknown';
if($show_elements_graph['show_unknown']){
$data_return['legend'][$key] = __('Unknown') . ' ' . $str;
}
$data_return['color'][$key] =$color_series['unknown'];
}
elseif(strpos($key, 'percentil') !== false){
$data_return['series_type'][$key] = 'percentil';
if($show_elements_graph['percentil']){
$data_return['legend'][$key] =
__('Percentil') . ' ' .
$config['percentil'] .
'º ' . __('of module') . ' ';
if (isset($show_elements_graph['labels']) && is_array($show_elements_graph['labels'])){
$data_return['legend'][$key] .= $show_elements_graph['labels'][$value['agent_module_id']] . ' ' ;
}
else{
$data_return['legend'][$key] .= $value['agent_alias'] . ' / ' .
$value['module_name'] . ': ' . ' Value: ';
}
$data_return['legend'][$key] .= remove_right_zeros(
number_format(
$value['data'][0][1],
$config['graph_precision']
)
) . ' ' . $str;
}
$data_return['color'][$key] =$color_series['percentil'];
}
elseif(strpos($key, 'projection') !== false){
$data_return['series_type'][$key] = $type_graph;
$data_return['legend'][$key] = __('Projection') . ' ' . $str;
$data_return['color'][$key] = $color_series['projection'];
}
else{
$data_return['series_type'][$key] = $type_graph;
$data_return['legend'][$key] = $key;
$data_return['color'][$key] = $color_series[$i];
$i++;
}
}
return $data_return;
}
return false;
}
function generator_chart_to_pdf($type_graph_pdf, $params, $params_combined = false, $module_list = false){
global $config;
$file_js = $config["homedir"] . "/include/web2image.js";
$url = $config["homeurl"] . "/include/chart_generator.php";
$img_file = "img_". uniqid() .".png";
$img_path = $config["homedir"] . "/attachment/" . $img_file;
$img_url = $config["homeurl"] . "attachment/" . $img_file;
$width_img = 500;
$height_img = 450;
$params_encode_json = urlencode(json_encode($params));
if($params_combined){
$params_combined = urlencode(json_encode($params_combined));
}
if($module_list){
$module_list = urlencode(json_encode($module_list));
}
$session_id = session_id();
$result = exec(
"phantomjs " . $file_js . " " .
$url . " '" .
$type_graph_pdf . "' '" .
$params_encode_json . "' '" .
$params_combined . "' '" .
$module_list . "' " .
$img_path . " " .
$width_img . " " .
$height_img . " '" .
$session_id . "' " .
$params['return_img_base_64']
);
if($params['return_img_base_64']){
return $result;
}
else{
$config["temp_images"][] = $img_path;
return '<img src="' . $img_url . '" />';
}
}
/**
* Get the product name.
*

View File

@ -6655,7 +6655,7 @@ function api_get_graph_module_data($id, $thrash1, $other, $thrash2) {
if (defined ('METACONSOLE')) {
return;
}
$period = $other['data'][0];
$width = $other['data'][1];
$height = $other['data'][2];
@ -6667,38 +6667,40 @@ function api_get_graph_module_data($id, $thrash1, $other, $thrash2) {
$avg_only = 0;
$start_date = $other['data'][4];
$date = strtotime($start_date);
$homeurl = '../';
$ttl = 1;
global $config;
$config['flash_charts'] = 0;
$image = grafico_modulo_sparse ($id, $period, $draw_events,
$width, $height , $label, null,
$draw_alerts, $avg_only, false,
$date, '', 0, 0,true,
false, $homeurl, $ttl);
preg_match("/<div class=\"nodata_text\">/",
$image, $match);
if (!empty($match[0])) {
echo "Error no data";
}
else {
// Extract url of the image from img tag
preg_match("/src='([^']*)'/i", $image, $match);
if (empty($match[1])) {
echo "Error getting graph";
}
else {
header('Content-type: image/png');
header('Location: ' . $match[1]);
}
}
$params =array(
'agent_module_id' => $id,
'period' => $period,
'show_events' => $draw_events,
'width' => $width,
'height' => $height,
'show_alerts' => $draw_alerts,
'date' => $date,
'unit' => '',
'baseline' => 0,
'return_data' => 0,
'show_title' => true,
'only_image' => true,
'homeurl' => $homeurl,
'compare' => false,
'show_unknown' => true,
'backgroundColor' => 'white',
'percentil' => null,
'type_graph' => $config['type_module_charts'],
'fullscale' => false,
'return_img_base_64' => true
);
$image = grafico_modulo_sparse($params);
header('Content-type: text/html');
returnData('string', array('type' => 'string', 'data' => '<img src="data:image/jpeg;base64,' . $image . '">'));
}
/**
@ -10039,25 +10041,24 @@ function api_set_delete_special_day($id_special_day, $thrash2, $thrash3, $thrash
*
*/
function api_get_module_graph($id_module, $thrash2, $other, $thrash4) {
global $config;
if (defined ('METACONSOLE')) {
return;
}
if (is_nan($id_module) || $id_module <= 0) {
returnError('error_module_graph', __(''));
return;
}
$id_exist = (bool) db_get_value ('id_agente_modulo', 'tagente_modulo', 'id_agente_modulo', $id_module);
if (!$id_exist) {
// returnError('id_not_found');
return;
}
$graph_seconds =
(!empty($other) && isset($other['data'][0]))
?
@ -10066,7 +10067,7 @@ function api_get_module_graph($id_module, $thrash2, $other, $thrash4) {
SECONDS_1HOUR; // 1 hour by default
$graph_threshold =
(!empty($other) && isset($other['data'][2]))
(!empty($other) && isset($other['data'][2]) && $other['data'][2])
?
$other['data'][2]
:
@ -10076,80 +10077,38 @@ function api_get_module_graph($id_module, $thrash2, $other, $thrash4) {
// returnError('error_module_graph', __(''));
return;
}
$id_module_type = modules_get_agentmodule_type ($id_module);
$module_type = modules_get_moduletype_name ($id_module_type);
$string_type = strpos($module_type,'string');
// Get the html item
if ($string_type === false) {
$graph_html = grafico_modulo_sparse(
$id_module, $graph_seconds, false, 600, 300, '',
'', false, false, true, time(), '', 0, 0, true, true,
ui_get_full_url(false) . '/', 1, false, '', false, true,
true, 'white', null, false, false, $config['type_module_charts'],
false, false);
$params =array(
'agent_module_id' => $id_module,
'period' => $graph_seconds,
'show_events' => false,
'width' => $width,
'height' => $height,
'show_alerts' => false,
'date' => time(),
'unit' => '',
'baseline' => 0,
'return_data' => 0,
'show_title' => true,
'only_image' => true,
'homeurl' => ui_get_full_url(false) . '/',
'compare' => false,
'show_unknown' => true,
'backgroundColor' => 'white',
'percentil' => null,
'type_graph' => $config['type_module_charts'],
'fullscale' => false,
'return_img_base_64' => true,
'image_treshold' => $graph_threshold
);
$graph_html = grafico_modulo_sparse($params);
if($other['data'][1]){
header('Content-type: text/html');
returnData('string', array('type' => 'string', 'data' => '<img src="data:image/jpeg;base64,' . $graph_html . '">'));
} else {
$graph_html = grafico_modulo_string(
$id_module, $graph_seconds, false, 600, 300, '',
'', false, false, true, time(), true, ui_get_full_url(false) . '/',
'', 1, true);
}
$graph_image_file_encoded = false;
if (preg_match("/<img src='(.+)'./", $graph_html, $matches)) {
$file_url = $matches[1];
if (preg_match("/\?(.+)&(.+)&(.+)&(.+)/", $file_url,$parameters)) {
array_shift ($parameters);
foreach ($parameters as $parameter){
$value = explode ("=",$parameter);
if (strcmp($value[0], "static_graph") == 0){
$static_graph = $value[1];
}
elseif (strcmp($value[0], "graph_type") == 0){
$graph_type = $value[1];
}
elseif (strcmp($value[0], "ttl") == 0){
$ttl = $value[1];
}
elseif (strcmp($value[0], "id_graph") == 0){
$id_graph = $value[1];
}
}
}
}
// Check values are OK
if ( (isset ($graph_type))
&& (isset ($ttl))
&& (isset ($id_graph))) {
$_GET["ttl"] = $ttl;
$_GET["id_graph"] = $id_graph;
$_GET["graph_type"] = $graph_type;
$_GET["static_graph"] = $static_graph;
$_GET["graph_threshold"] = $graph_threshold;
$_GET["id_module"] = $id_module;
}
ob_start();
include (__DIR__ . "/graphs/functions_pchart.php");
$output = ob_get_clean();
$graph_image_file_encoded = base64_encode($output);
if (empty($graph_image_file_encoded)) {
// returnError('error_module_graph', __(''));
}
else {
if($other['data'][1]){
header('Content-type: text/html');
returnData('string', array('type' => 'string', 'data' => '<img src="data:image/jpeg;base64,' . $graph_image_file_encoded . '">'));
} else {
returnData('string', array('type' => 'string', 'data' => $graph_image_file_encoded));
}
// To show only the base64 code, call returnData as:
// returnData('string', array('type' => 'string', 'data' => $graph_image_file_encoded));
returnData('string', array('type' => 'string', 'data' => $graph_html));
}
}

View File

@ -21,7 +21,7 @@
/**
* @global array Contents all var configs for the local instalation.
* @global array Contents all var configs for the local instalation.
*/
global $config;
@ -32,13 +32,13 @@ function custom_graphs_create($id_modules = array(), $name = "",
$description = "", $stacked = CUSTOM_GRAPH_AREA, $width = 0,
$height = 0, $events = 0 , $period = 0, $private = 0, $id_group = 0,
$user = false, $fullscale = 0) {
global $config;
if ($user === false) {
$user = $config['id_user'];
}
$id_graph = db_process_sql_insert('tgraph',
array(
'id_user' => $user,
@ -54,7 +54,7 @@ function custom_graphs_create($id_modules = array(), $name = "",
'id_graph_template' => 0,
'fullscale' => $fullscale,
));
if (empty($id_graph)) {
return false;
}
@ -67,22 +67,22 @@ function custom_graphs_create($id_modules = array(), $name = "",
'id_agent_module' => $id_module,
'weight' => 1
));
if (empty($result))
break;
}
if (empty($result)) {
//Not it is a complete insert the modules. Delete all
db_process_sql_delete('tgraph_source',
array('id_graph' => $id_graph));
db_process_sql_delete('tgraph',
array('id_graph' => $id_graph));
return false;
}
return $id_graph;
}
}
@ -100,30 +100,30 @@ function custom_graphs_create($id_modules = array(), $name = "",
*/
function custom_graphs_get_user ($id_user = 0, $only_names = false, $returnAllGroup = true, $privileges = 'RR') {
global $config;
if (!$id_user) {
$id_user = $config['id_user'];
}
$groups = users_get_groups ($id_user, $privileges, $returnAllGroup);
$all_graphs = db_get_all_rows_in_table ('tgraph', 'name');
if ($all_graphs === false)
return array ();
$graphs = array ();
foreach ($all_graphs as $graph) {
if (!in_array($graph['id_group'], array_keys($groups)))
continue;
if ($graph["id_user"] != $id_user && $graph['private'])
continue;
if ($graph["id_group"] > 0)
if (!isset($groups[$graph["id_group"]])) {
continue;
}
if ($only_names) {
$graphs[$graph['id_graph']] = $graph['name'];
}
@ -135,148 +135,7 @@ function custom_graphs_get_user ($id_user = 0, $only_names = false, $returnAllGr
$graphs[$graph['id_graph']]['graphs_count'] = $graphsCount;
}
}
return $graphs;
}
/**
* Print a custom graph image.
*
* @param $id_graph Graph id to print.
* @param $height Height of the returning image.
* @param $width Width of the returning image.
* @param $period Period of time to get data in seconds.
* @param $stacked Whether the graph is stacked or not.
* @param $return Whether to return an output string or echo now (optional, echo by default).
* @param $date Date to start printing the graph
* @param bool Wether to show an image instead a interactive chart or not
* @param string Background color
* @param array List of names for the items. Should have the same size as the module list.
* @param bool Show the last value of the item on the list.
* @param bool Show the max value of the item on the list.
* @param bool Show the min value of the item on the list.
* @param bool Show the average value of the item on the list.
*
* @return Mixed
*/
function custom_graphs_print($id_graph, $height, $width, $period,
$stacked = null, $return = false, $date = 0, $only_image = false,
$background_color = 'white', $modules_param = array(), $homeurl = '',
$name_list = array(), $unit_list = array(), $show_last = true,
$show_max = true, $show_min = true, $show_avg = true, $ttl = 1,
$dashboard = false, $vconsole = false, $percentil = null,
$from_interface = false,$id_widget_dashboard=false, $fullscale = false) {
global $config;
if ($from_interface) {
if ($config["type_interface_charts"] == 'line') {
$graph_conf['stacked'] = CUSTOM_GRAPH_LINE;
}
else {
$graph_conf['stacked'] = CUSTOM_GRAPH_AREA;
}
}
else {
if ($id_graph == 0) {
$graph_conf['stacked'] = CUSTOM_GRAPH_LINE;
}
else {
$graph_conf = db_get_row('tgraph', 'id_graph', $id_graph);
}
}
if ($stacked === null) {
$stacked = $graph_conf['stacked'];
}
$sources = false;
if ($id_graph == 0) {
$modules = $modules_param;
$count_modules = count($modules);
$weights = array_fill(0, $count_modules, 1);
if ($count_modules > 0)
$sources = true;
}
else {
$sources = db_get_all_rows_field_filter('tgraph_source', 'id_graph',
$id_graph);
$series = db_get_all_rows_sql('SELECT summatory_series,average_series,modules_series FROM tgraph WHERE id_graph = '.$id_graph);
$summatory = $series[0]['summatory_series'];
$average = $series[0]['average_series'];
$modules_series = $series[0]['modules_series'];
$modules = array ();
$weights = array ();
$labels = array ();
foreach ($sources as $source) {
array_push ($modules, $source['id_agent_module']);
array_push ($weights, $source['weight']);
if ($source['label'] != ''){
$item['type'] = 'custom_graph';
$item['id_agent'] = agents_get_module_id($source['id_agent_module']);
$item['id_agent_module'] = $source['id_agent_module'];
$labels[$source['id_agent_module']] = reporting_label_macro($item, $source['label']);
}
}
}
if ($sources === false) {
if ($return){
return false;
}
else{
ui_print_info_message ( array ( 'no_close' => true, 'message' => __('No items.') ) );
return;
}
}
if (empty($homeurl)) {
$homeurl = ui_get_full_url(false, false, false, false);
}
$output = graphic_combined_module($modules,
$weights,
$period,
$width,
$height,
'',
'',
0,
0,
0,
$stacked,
$date,
$only_image,
$homeurl,
$ttl,
false,
false,
$background_color,
$name_list,
array(),
$show_last,
$show_max,
$show_min,
$show_avg,
$labels,
$dashboard,
$vconsole,
$percentil,
$from_interface,
$id_widget_dashboard,
$fullscale,
$summatory,
$average,
$modules_series);
if ($return)
return $output;
echo $output;
}
?>

View File

@ -418,7 +418,7 @@ function db_get_row ($table, $field_search, $condition, $fields = false) {
*/
function db_get_row_filter($table, $filter, $fields = false, $where_join = 'AND', $historydb = false) {
global $config;
switch ($config["dbtype"]) {
case "mysql":
return mysql_db_get_row_filter($table, $filter, $fields, $where_join, $historydb);
@ -443,10 +443,10 @@ function db_get_row_filter($table, $filter, $fields = false, $where_join = 'AND'
function db_get_sql ($sql, $field = 0, $search_history_db = false) {
$result = db_get_all_rows_sql ($sql, $search_history_db);
if ($result === false)
return false;
$ax = 0;
foreach ($result[0] as $f) {
if ($field == $ax)
@ -467,7 +467,7 @@ function db_get_sql ($sql, $field = 0, $search_history_db = false) {
*/
function db_get_all_rows_sql($sql, $search_history_db = false, $cache = true, $dbconnection = false) {
global $config;
switch ($config["dbtype"]) {
case "mysql":
return mysql_db_get_all_rows_sql($sql, $search_history_db, $cache, $dbconnection);
@ -482,15 +482,12 @@ function db_get_all_rows_sql($sql, $search_history_db = false, $cache = true, $d
}
/**
*
* Returns the time the module is in unknown status (by events)
*
* @param int $id_agente_modulo module to check
* @param int $tstart begin of search
* @param int $tend end of search
*
*/
function db_get_module_ranges_unknown($id_agente_modulo, $tstart = false, $tend = false, $historydb = false) {
function db_get_module_ranges_unknown($id_agente_modulo, $tstart = false, $tend = false, $historydb = false, $fix_to_range = 0) {
global $config;
if (!isset($id_agente_modulo)) {
@ -512,18 +509,39 @@ function db_get_module_ranges_unknown($id_agente_modulo, $tstart = false, $tend
}
// Retrieve going unknown events in range
$query = "SELECT utimestamp,event_type FROM tevento WHERE id_agentmodule = " . $id_agente_modulo;
$query .= " AND event_type like 'going_%' ";
$query .= " AND utimestamp >= $tstart AND utimestamp <= $tend ";
$query .= " ORDER BY utimestamp ASC";
$query = "SELECT * FROM tevento WHERE id_agentmodule = " . $id_agente_modulo
. " AND event_type like 'going_%' "
. " AND utimestamp >= $tstart AND utimestamp <= $tend "
. " ORDER BY utimestamp ASC";
$events = db_get_all_rows_sql($query, $historydb);
if (! is_array($events)){
$query = "SELECT * FROM tevento WHERE id_agentmodule = " . $id_agente_modulo
. " AND event_type like 'going_%' "
. " AND utimestamp < $tstart "
. " ORDER BY utimestamp DESC LIMIT 1;";
$previous_event = db_get_all_rows_sql($query, $historydb);
if ($previous_event !== false) {
$last_status = $previous_event[0]["event_type"] == "going_unknown" ? 1:0;
}
else {
$last_status = 0;
}
if ((! is_array($events)) && (! is_array($previous_event))) {
return false;
}
$last_status = $events[0]["event_type"] != "going_unknown" ? 1:0;
if (! is_array($events)) {
if ($previous_event[0]["event_type"] == "going_unknown") {
return array(
array(
"time_from" => (($fix_to_range == 1)?$tstart:$previous_event[0]["utimestamp"]),
)
);
}
}
$return = array();
$i=0;
foreach ($events as $event) {
@ -558,23 +576,22 @@ function db_get_module_ranges_unknown($id_agente_modulo, $tstart = false, $tend
return $return;
}
/**
* Uncompresses and returns the data of a given id_agent_module
*
*
* @param int $id_agente_modulo id_agente_modulo
* @param utimestamp $tstart Begin of the catch
* @param utimestamp $tend End of the catch
* @param int $interval Size of slice (default-> module_interval)
*
*
* @return hash with the data uncompressed in blocks of module_interval
* false in case of empty result
*
*
* Note: All "unknown" data are marked as NULL
* Warning: Be careful with the amount of data, check your RAM size available
* We'll return a bidimensional array
* Structure returned: schema:
*
*
* uncompressed_data =>
* pool_id (int)
* utimestamp (start of current slice)
@ -582,7 +599,7 @@ function db_get_module_ranges_unknown($id_agente_modulo, $tstart = false, $tend
* array
* datos
* utimestamp
*
*
*/
function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = false) {
global $config;
@ -602,7 +619,7 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
$search_historydb = false;
$table = "tagente_datos";
$module = modules_get_agentmodule($id_agente_modulo);
if ($module === false){
// module not exists
@ -610,11 +627,11 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
}
$module_type = $module['id_tipo_modulo'];
$module_type_str = modules_get_type_name ($module_type);
if (strstr ($module_type_str, 'string') !== false) {
$table = "tagente_datos_string";
}
$flag_async = false;
if(strstr ($module_type_str, 'async_data') !== false) {
$flag_async = true;
@ -634,7 +651,7 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
else {
$query = "SELECT datos,utimestamp FROM $table ";
$query .= " WHERE id_agente_modulo=$id_agente_modulo ";
$query .= " AND utimestamp=" . $first_utimestamp;
$query .= " AND utimestamp = " . $first_utimestamp;
$data = db_get_all_rows_sql($query,$search_historydb);
@ -652,7 +669,6 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
else {
$first_data["utimestamp"] = $data[0]["utimestamp"];
$first_data["datos"] = $data[0]["datos"];
}
}
@ -670,27 +686,11 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
}
// Retrieve going unknown events in range
$unknown_events = db_get_module_ranges_unknown($id_agente_modulo, $tstart, $tend, $search_historydb);
// Get the last event after inverval to know if graph start on unknown
$previous_unknown_events = db_get_row_filter (
'tevento',
array ('id_agentmodule' => $id_agente_modulo,
"utimestamp <= $tstart",
'order' => 'utimestamp DESC'
),
false,
'AND',
$search_historydb
$unknown_events = db_get_module_ranges_unknown(
$id_agente_modulo, $tstart,
$tend, $search_historydb, 1
);
//show graph if graph is inside unknown
if( $previous_unknown_events && $previous_unknown_events['event_type'] == 'going_unknown' &&
$unknown_events === false){
$last_inserted_value = $first_data["datos"];
$unknown_events[0]['time_from'] = $tstart;
}
//if time to is missing in last event force time to outside range time
if( $unknown_events && !isset($unknown_events[count($unknown_events) -1]['time_to']) ){
$unknown_events[count($unknown_events) -1]['time_to'] = $tend;
@ -699,8 +699,7 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
//if time to is missing in first event force time to outside range time
if ($first_data["datos"] === false && !$flag_async) {
$last_inserted_value = false;
}elseif(($unknown_events && !isset($unknown_events[0]['time_from']) &&
$previous_unknown_events && $previous_unknown_events['event_type'] == 'going_unknown' && !$flag_async) ||
}elseif(($unknown_events && !isset($unknown_events[0]['time_from']) && !$flag_async) ||
($first_utimestamp < $tstart - (SECONDS_1DAY + 2*$module_interval) && !$flag_async) ){
$last_inserted_value = $first_data["datos"];
$unknown_events[0]['time_from'] = $tstart;
@ -734,7 +733,7 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
else{
$current_unknown = null;
}
if(is_array($raw_data)) {
$current_raw_data = array_pop($raw_data);
}
@ -751,15 +750,15 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
|| (($current_timestamp - $last_timestamp) > (SECONDS_1DAY + 2 * $module_interval)) ) {
$tmp_data["utimestamp"] = $current_timestamp;
//check not init
$tmp_data["datos"] = $last_value === false ? false : null;
//async not unknown
if($flag_async && $tmp_data["datos"] === null){
$tmp_data["datos"] = $last_inserted_value;
}
// debug purpose
//$tmp_data["obs"] = "unknown extra";
array_push($return[$pool_id]["data"], $tmp_data);
@ -767,9 +766,9 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
//insert raw data
while ( ($current_raw_data != null) &&
( ($current_timestamp_end > $current_raw_data['utimestamp']) &&
( ($current_timestamp_end > $current_raw_data['utimestamp']) &&
($current_timestamp <= $current_raw_data['utimestamp']) ) ) {
// Add real data detected
if (count($return[$pool_id]['data']) == 0) {
//insert first slice data
@ -777,6 +776,7 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
$tmp_data["datos"] = $last_inserted_value;
// debug purpose
//$tmp_data["obs"] = "virtual data (raw)";
$tmp_data["type"] = ($current_timestamp == $tstart || ($current_timestamp == $tend)?0:1); // virtual data
//Add order to avoid usort missorder in same utimestamp data cells
$tmp_data["order"] = 1;
@ -785,6 +785,7 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
$tmp_data["utimestamp"] = $current_raw_data["utimestamp"];
$tmp_data["datos"] = $current_raw_data["datos"];
$tmp_data["type"] = 0; // real data
// debug purpose
//$tmp_data["obs"] = "real data";
//Add order to avoid usort missorder in same utimestamp data cells
@ -800,16 +801,16 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
$current_raw_data = null;
}
}
//unknown
$data_slices = $return[$pool_id]["data"];
if(!$flag_async){
while ( ($current_unknown != null) &&
( ( ($current_unknown['time_from'] != null) &&
($current_timestamp_end >= $current_unknown['time_from']) ) ||
($current_timestamp_end >= $current_unknown['time_from']) ) ||
($current_timestamp_end >= $current_unknown['time_to']) ) ) {
if( ( $current_timestamp <= $current_unknown['time_from']) &&
if( ( $current_timestamp <= $current_unknown['time_from']) &&
( $current_timestamp_end >= $current_unknown['time_from'] ) ){
if (count($return[$pool_id]['data']) == 0) {
//insert first slice data
@ -833,7 +834,7 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
array_push($return[$pool_id]["data"], $tmp_data);
$current_unknown["time_from"] = null;
}
elseif( ($current_timestamp <= $current_unknown['time_to']) &&
elseif( ($current_timestamp <= $current_unknown['time_to']) &&
($current_timestamp_end > $current_unknown['time_to'] ) ){
if (count($return[$pool_id]['data']) == 0) {
@ -862,7 +863,7 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
}
$i--;
}
// debug purpose
//$tmp_data["obs"] = "event data unknown to";
array_push($return[$pool_id]["data"], $tmp_data);
@ -883,7 +884,7 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
if (count($return[$pool_id]['data']) == 0) {
//insert first slice data
$tmp_data["utimestamp"] = $current_timestamp;
$tmp_data["datos"] = $last_inserted_value;
$tmp_data["datos"] = $last_inserted_value;
// debug purpose
//$tmp_data["obs"] = "virtual data (empty)";
array_push($return[$pool_id]["data"], $tmp_data);
@ -902,7 +903,7 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
//put the last slice data like first element of next slice
$last_inserted_value = end($return[$pool_id]['data']);
$last_inserted_value = $last_inserted_value['datos'];
//increment
$pool_id++;
$current_timestamp = $current_timestamp_end;
@ -917,8 +918,6 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
array_push($return, $end_array);
}
// html_debug_print($return);
return $return;
}
@ -948,7 +947,7 @@ function db_uncompress_module_data($id_agente_modulo, $tstart = false, $tend = f
*/
function db_get_all_rows_filter($table, $filter = array(), $fields = false, $where_join = 'AND', $search_history_db = false, $returnSQL = false) {
global $config;
switch ($config["dbtype"]) {
case "mysql":
return mysql_db_get_all_rows_filter($table, $filter, $fields, $where_join, $search_history_db, $returnSQL);

View File

@ -46,12 +46,15 @@ function forecast_projection_graph($module_id,
}
$begin_time = time();
$module_data=grafico_modulo_sparse ($module_id, $period, 0,
300, 300 , '', null,
false, 0, false,
0, '', 0, 1, false,
true, '', 1, true);
$params =array(
'agent_module_id' => $module_id,
'period' => $period,
'return_data' => 1,
'projection' => true
);
$module_data = grafico_modulo_sparse ($params);
if (empty($module_data)) {
return array();
@ -62,55 +65,57 @@ function forecast_projection_graph($module_id,
}
// Data initialization
$sum_obs = 0;
$sum_xi = 0;
$sum_yi = 0;
$sum_xi_yi = 0;
$sum_xi2 = 0;
$sum_yi2 = 0;
$sum_obs = 0;
$sum_xi = 0;
$sum_yi = 0;
$sum_xi_yi = 0;
$sum_xi2 = 0;
$sum_yi2 = 0;
$sum_diff_dates = 0;
$last_timestamp = get_system_time();
$agent_interval = SECONDS_5MINUTES;
$cont = 1;
$data = array();
$cont = 1;
$data = array();
//$table->data = array();
// Creates data for calculation
if (is_array($module_data) || is_object($module_data)) {
foreach ($module_data as $utimestamp => $row) {
if ($utimestamp == '') {
foreach ($module_data['sum1']['data'] as $key => $row) {
if ($row[0] == '') {
continue;
}
$row[0] = $row[0] / 1000;
$data[0] = '';
$data[1] = $cont;
$data[2] = date($config["date_format"], $utimestamp);
$data[3] = $utimestamp;
$data[4] = $row['sum'];
$data[5] = $utimestamp * $row['sum'];
$data[6] = $utimestamp * $utimestamp;
$data[7] = $row['sum'] * $row['sum'];
$data[2] = date($config["date_format"], $row[0]);
$data[3] = $row[0];
$data[4] = $row[1];
$data[5] = $row[0] * $row[1];
$data[6] = $row[0] * $row[0];
$data[7] = $row[1] * $row[1];
if ($cont == 1) {
$data[8] = 0;
}
else {
$data[8] = $utimestamp - $last_timestamp;
$data[8] = $row[0] - $last_timestamp;
}
$sum_obs = $sum_obs + $cont;
$sum_xi = $sum_xi + $utimestamp;
$sum_yi = $sum_yi + $row['sum'];
$sum_xi_yi = $sum_xi_yi + $data[5];
$sum_xi2 = $sum_xi2 + $data[6];
$sum_yi2 = $sum_yi2 + $data[7];
$sum_obs = $sum_obs + $cont;
$sum_xi = $sum_xi + $row[0];
$sum_yi = $sum_yi + $row[1];
$sum_xi_yi = $sum_xi_yi + $data[5];
$sum_xi2 = $sum_xi2 + $data[6];
$sum_yi2 = $sum_yi2 + $data[7];
$sum_diff_dates = $sum_diff_dates + $data[8];
$last_timestamp = $utimestamp;
$last_timestamp = $row[0];
$cont++;
}
}
$cont--;
// Calculation over data above:
// 1. Calculation of linear correlation coefficient...
@ -121,15 +126,6 @@ function forecast_projection_graph($module_id,
// 3.2 Standard deviation for Y: sqrt((Sum(Yi²)/Obs) - (avg Y)²)
// Linear correlation coefficient:
if ($sum_xi != 0) {
$avg_x = $cont/$sum_xi;
} else {
$avg_x = 0;
}
if ($sum_yi != 0)
$avg_y = $cont/$sum_yi;
else
$avg_y = 0;
/*
if ($cont != 0) {
@ -229,18 +225,17 @@ function forecast_projection_graph($module_id,
}
}
$timestamp_f = date($time_format, $current_ts);
//$timestamp_f = date($time_format, $current_ts);
$timestamp_f = graph_get_formatted_date($current_ts, $time_format, $time_format_2);
$timestamp_f = $current_ts * 1000;
if ($csv) {
$output_data[$idx]['date'] = $current_ts;
$output_data[$idx]['data'] = ($a + ($b * $current_ts));
}
else {
$output_data[$timestamp_f] = ($a + ($b * $current_ts));
$output_data[$idx][0] = $timestamp_f;
$output_data[$idx][1] = ($a + ($b * $current_ts));
}
// Using this function for prediction_date
if ($prediction_period == false) {
// These statements stop the prediction when interval is greater than 2 years
@ -249,7 +244,7 @@ function forecast_projection_graph($module_id,
}
// Found it
if ($max_value >= $output_data[$timestamp_f] and $min_value <= $output_data[$timestamp_f]) {
if ($max_value >= $output_data[$idx][0] and $min_value <= $output_data[$idx][0]) {
return $current_ts;
}
}
@ -259,7 +254,7 @@ function forecast_projection_graph($module_id,
$current_ts = $current_ts + $agent_interval;
$idx++;
}
return $output_data;
}

File diff suppressed because it is too large Load Diff

View File

@ -1674,26 +1674,27 @@ function modules_get_last_value ($id_agentmodule) {
* @return mixed The row of tagente_datos of the last period. False if there were no data.
*/
function modules_get_previous_data ($id_agent_module, $utimestamp = 0, $string = 0) {
if (empty ($utimestamp))
if (empty ($utimestamp)){
$utimestamp = time ();
}
if ($string == 1) {
$table = 'tagente_datos_string';
}
else {
$table = 'tagente_datos';
}
$sql = sprintf ('SELECT *
FROM ' . $table . '
WHERE id_agente_modulo = %d
AND utimestamp <= %d
AND utimestamp >= %d
AND utimestamp <= %d
ORDER BY utimestamp DESC',
$id_agent_module, $utimestamp, $utimestamp - SECONDS_2DAY);
$search_in_history_db = db_search_in_history_db($utimestamp);
$id_agent_module, $utimestamp,
$utimestamp - SECONDS_2DAY
);
$search_in_history_db = db_search_in_history_db($utimestamp);
return db_get_row_sql ($sql, $search_in_history_db);
}
@ -2327,14 +2328,12 @@ function modules_get_first_date($id_agent_module, $datelimit = 0) {
$query = " SELECT max(utimestamp) as utimestamp FROM $table ";
$query .= " WHERE id_agente_modulo=$id_agent_module ";
$query .= " AND utimestamp < $datelimit ";
}
else {
// get first utimestamp
$query = " SELECT min(utimestamp) as utimestamp FROM $table ";
$query .= " WHERE id_agente_modulo=$id_agent_module ";
}
// SEARCH ACTIVE DB
$data = db_get_all_rows_sql($query,$search_historydb);

File diff suppressed because it is too large Load Diff

View File

@ -727,11 +727,10 @@ function treeview_printTable($id_agente, $server_data = array(), $no_head = fals
//echo '<div id="id_div" style="height: 10px">&nbsp;</div>';
if ($config["agentaccess"]) {
$access_graph = '<div style="margin-left: 10px;">';
$access_graph .= graphic_agentaccess($id_agente, 290, 110,
SECONDS_1DAY, true);
$access_graph .= '</div><br>';
$access_graph = '<div>hjhhjhhj</div>';
$access_graph = '<div style="width:100%; heigth:200px;">';
$access_graph .= graphic_agentaccess($id_agente, 380, 180, SECONDS_1DAY, true, true);
$access_graph .= '</div><br><br>';
ui_toggle($access_graph, __('Agent access rate (24h)'));
}

View File

@ -944,9 +944,9 @@ function visual_map_print_item($mode = "read", $layoutData,
continue;
}
}
$only_image = !$graph_javascript && $isExternalLink;
if ($layoutData['id_custom_graph'] != 0) {
// Show only avg on the visual console
if (get_parameter('action') == 'edit') {
@ -955,59 +955,54 @@ function visual_map_print_item($mode = "read", $layoutData,
}
else {
$img = '<img src="images/console/signes/custom_graph.png" style="width:'.$width.'px;height:'.$height.'px;'.$imgpos.'">';
}
}
}
}
else {
if ($width == 0 || $height == 0) {
if ($layoutData['label_position']=='left') {
$img = '<div style="z-index:'.$show_on_top_index.';float:right;height:'.$himg.'px;">'.custom_graphs_print(
$layoutData['id_custom_graph'], 180, 480,
$period, null, true, 0, $only_image, $layoutData['image'],
array(), '', array(), array(), true,
false, false, true, 1, false, true).'</div>';
}
elseif ($layoutData['label_position']=='right') {
$img = '<div style="z-index:'.$show_on_top_index.';float:left;height:'.$himg.'px;">'.custom_graphs_print(
$layoutData['id_custom_graph'], 180, 480,
$period, null, true, 0, $only_image, $layoutData['image'],
array(), '', array(), array(), true,
false, false, true, 1, false, true).'</div>';
}
else {
$img = custom_graphs_print(
$layoutData['id_custom_graph'], 180, 480,
$period, null, true, 0, $only_image, $layoutData['image'],
array(), '', array(), array(), true,
false, false, true, 1, false, true);
}
if ($width == 0 ) {
$width = 180;
}
if($height == 0) {
$height = 480;
}
$params =array(
'period' => $period,
'width' => $width,
'height' => $height,
'title' => '',
'unit_name' => null,
'show_alerts' => false,
'only_image' => $only_image,
'vconsole' => true,
'backgroundColor' => $layoutData['image']
);
$params_combined = array(
'id_graph' => $layoutData['id_custom_graph']
);
if ($layoutData['label_position']=='left') {
$img = '<div style="z-index:'.$show_on_top_index.';float:right;height:'.$himg.'px;">'.
graphic_combined_module(
false,
$params,
$params_combined
).'</div>';
}
elseif ($layoutData['label_position']=='right') {
$img = '<div style="z-index:'.$show_on_top_index.';float:left;height:'.$himg.'px;">'.
graphic_combined_module(
false,
$params,
$params_combined
).'</div>';
}
else {
if ($width < 480){
$img = '<div class="error">'._("Could not draw pie with labels contained inside canvas. Resize widget to 500px width minimum").'</div>';
}
else {
if ($layoutData['label_position']=='left') {
$img = '<div style="z-index:'.$show_on_top_index.';float:right;height:'.$himg.'px;">'.custom_graphs_print(
$layoutData['id_custom_graph'], $height, $width,
$period, null, true, 0, $only_image, $layoutData['image'],
array(), '', array(), array(), true,
false, false, true, 1, false, true).'</div>';
}
elseif($layoutData['label_position']=='right') {
$img = '<div style="z-index:'.$show_on_top_index.';float:left;height:'.$himg.'px;">'.custom_graphs_print(
$layoutData['id_custom_graph'], $height, $width,
$period, null, true, 0, $only_image, $layoutData['image'],
array(), '', array(), array(), true,
false, false, true, 1, false, true).'</div>';
}
else {
$img = custom_graphs_print(
$layoutData['id_custom_graph'], $height, $width,
$period, null, true, 0, $only_image, $layoutData['image'],
array(), '', array(), array(), true,
false, false, true, 1, false, true);
}
}
$img = graphic_combined_module(
false,
$params,
$params_combined
);
}
}
}
@ -1016,7 +1011,7 @@ function visual_map_print_item($mode = "read", $layoutData,
$homeurl = $config['homeurl'];
else
$homeurl = '';
if ( (get_parameter('action') == 'edit') || (get_parameter('operation') == 'edit_visualmap') ) {
if($width == 0 || $height == 0){
if ($layoutData['id_metaconsole'] != 0) {
@ -1034,85 +1029,62 @@ function visual_map_print_item($mode = "read", $layoutData,
else{
$img = '<img src="images/console/signes/module_graph.png" style="width:'.$width.'px;height:'. $height.'px;'.$imgpos.'">';
}
}
}
else {
if ($width == 0 || $height == 0) {
if ($layoutData['label_position']=='left') {
$img = '<div style="z-index:'.$show_on_top_index.';float:right;height:'.$himg.'px;">'.
grafico_modulo_sparse($id_module, $period,
0, 300, 180, modules_get_agentmodule_name($id_module),null, false, 1, false, 0,
modules_get_unit($id_module), 0, 0, true, $only_image, '', 1, false, '',
false, false, false, $layoutData['image'],
null, true, false, $type_graph) . '</div>';
}
elseif($layoutData['label_position']=='right') {
$img = '<div style="z-index:'.$show_on_top_index.';float:left;height:'.$himg.'px;">' .
grafico_modulo_sparse($id_module,
$period, 0, 300, 180, modules_get_agentmodule_name($id_module),null, false,
1, false, 0, modules_get_unit($id_module), 0, 0, true, $only_image, '',
1, false, '', false, false, false,
$layoutData['image'], null, true,
false, $type_graph) . '</div>';
}
else {
$img = grafico_modulo_sparse($id_module,
$period, 0, 300, 180, modules_get_agentmodule_name($id_module),null, false, 1,
false, 0, modules_get_unit($id_module), 0, 0, true, $only_image, '',
1, false, '', false, false, false,
$layoutData['image'], null, true, false, $type_graph);
}
}
else{
if ($layoutData['label_position']=='left') {
$img = '<div style="z-index:'.$show_on_top_index.';float:right;height:'.$himg.'px;">' .
grafico_modulo_sparse($id_module, $period,
0, $width, $height, modules_get_agentmodule_name($id_module), null, false, 1,
false, 0, modules_get_unit($id_module), 0, 0, true, $only_image, '',
1, false, '', false, false, false,
$layoutData['image'], null, true,
false, $type_graph) . '</div>';
}
elseif ($layoutData['label_position']=='right') {
$img = '<div style="z-index:'.$show_on_top_index.';float:left;height:'.$himg.'px;">' .
grafico_modulo_sparse($id_module, $period,
0, $width, $height, modules_get_agentmodule_name($id_module), null, false, 1,
false, 0, modules_get_unit($id_module), 0, 0, true, $only_image,
'', 1, false, modules_get_unit($id_module), false, false, false,
$layoutData['image'], null, true,
false, $type_graph) . '</div>';
}
else {
$img = grafico_modulo_sparse($id_module,
$period, 0, $width, $height, modules_get_agentmodule_name($id_module), null,
false, 1, false, 0, modules_get_unit($id_module), 0, 0, true,
$only_image, '', 1, false, '', false,
false, false, $layoutData['image'],
null, false, true, $type_graph);
}
}
}
}
else {
if ($width == 0 || $height == 0) {
$width = 300;
$height = 180;
}
$params =array(
'agent_module_id' => $id_module,
'period' => $period,
'show_events' => false,
'width' => $width,
'height' => $height,
'title' => modules_get_agentmodule_name($id_module),
'unit' => modules_get_unit($id_module),
'only_image' => $only_image,
'menu' => false,
'backgroundColor' => $layoutData['image'],
'type_graph' => $type_graph,
'vconsole' => true
);
if ($layoutData['label_position']=='left') {
$img = '<div style="z-index:'.$show_on_top_index.';float:right;height:'.$himg.'px;">'.
grafico_modulo_sparse($params) . '</div>';
}
elseif($layoutData['label_position']=='right') {
$img = '<div style="z-index:'.$show_on_top_index.';float:left;height:'.$himg.'px;">' .
grafico_modulo_sparse($params) . '</div>';
}
else {
$img = grafico_modulo_sparse($params);
}
}
}
//Restore db connection
if ($layoutData['id_metaconsole'] != 0) {
metaconsole_restore_db();
}
break;
case BARS_GRAPH:
$imgpos = '';
if($layoutData['label_position']=='left'){
$imgpos = 'float:right';
}
else if($layoutData['label_position']=='right'){
$imgpos = 'float:left';
}
if (!empty($proportion)) {
$width =
((integer)($proportion['proportion_width'] * $width));

View File

@ -39,11 +39,11 @@ if (!empty($graph_type)) {
ob_end_clean ();
switch($graph_type) {
case 'histogram':
case 'histogram':
$width = get_parameter('width');
$height = get_parameter('height');
$data = json_decode(io_safe_output(get_parameter('data')), true);
$max = get_parameter('max');
$title = get_parameter('title');
$mode = get_parameter ('mode', 1);
@ -53,19 +53,19 @@ switch($graph_type) {
$width = get_parameter('width');
$height = get_parameter('height');
$progress = get_parameter('progress');
$out_of_lim_str = io_safe_output(get_parameter('out_of_lim_str', false));
$out_of_lim_image = get_parameter('out_of_lim_image', false);
$title = get_parameter('title');
$mode = get_parameter('mode', 1);
$fontsize = get_parameter('fontsize', 10);
$value_text = get_parameter('value_text', '');
$colorRGB = get_parameter('colorRGB', '');
gd_progress_bar ($width, $height, $progress, $title, $config['fontpath'],
$out_of_lim_str, $out_of_lim_image, $mode, $fontsize,
$value_text, $colorRGB);
@ -74,19 +74,19 @@ switch($graph_type) {
$width = get_parameter('width');
$height = get_parameter('height');
$progress = get_parameter('progress');
$out_of_lim_str = io_safe_output(get_parameter('out_of_lim_str', false));
$out_of_lim_image = get_parameter('out_of_lim_image', false);
$title = get_parameter('title');
$mode = get_parameter('mode', 1);
$fontsize = get_parameter('fontsize', 7);
$value_text = get_parameter('value_text', '');
$colorRGB = get_parameter('colorRGB', '');
gd_progress_bubble ($width, $height, $progress, $title, $config['fontpath'],
$out_of_lim_str, $out_of_lim_image, $mode, $fontsize,
$value_text, $colorRGB);
@ -95,7 +95,7 @@ switch($graph_type) {
function histogram($chart_data, $width, $height, $font, $max, $title,
$mode, $ttl = 1) {
$graph = array();
$graph['data'] = $chart_data;
$graph['width'] = $width;
@ -104,18 +104,18 @@ function histogram($chart_data, $width, $height, $font, $max, $title,
$graph['max'] = $max;
$graph['title'] = $title;
$graph['mode'] = $mode;
$id_graph = serialize_in_temp($graph, null, $ttl);
return "<img src='include/graphs/functions_gd.php?static_graph=1&graph_type=histogram&ttl=".$ttl."&id_graph=".$id_graph."'>";
}
function progressbar($progress, $width, $height, $title, $font,
$mode = 1, $out_of_lim_str = false, $out_of_lim_image = false,
$ttl = 1) {
$graph = array();
$graph['progress'] = $progress;
$graph['width'] = $width;
$graph['height'] = $height;
@ -124,7 +124,7 @@ function progressbar($progress, $width, $height, $title, $font,
$graph['title'] = $title;
$graph['font'] = $font;
$graph['mode'] = $mode;
$id_graph = serialize_in_temp($graph, null, $ttl);
if (is_metaconsole()) {
return "<img src='../../include/graphs/functions_gd.php?static_graph=1&graph_type=progressbar&ttl=".$ttl."&id_graph=".$id_graph."'>";
@ -137,7 +137,7 @@ function progressbar($progress, $width, $height, $title, $font,
function slicesbar_graph($chart_data, $period, $width, $height, $colors,
$font, $round_corner, $home_url = '', $ttl = 1) {
$graph = array();
$graph['data'] = $chart_data;
$graph['period'] = $period;
@ -146,9 +146,9 @@ function slicesbar_graph($chart_data, $period, $width, $height, $colors,
$graph['font'] = $font;
$graph['round_corner'] = $round_corner;
$graph['color'] = $colors;
$id_graph = serialize_in_temp($graph, null, $ttl);
return "<img src='".$home_url."include/graphs/functions_pchart.php?static_graph=1&graph_type=slicebar&ttl=".$ttl."&id_graph=".$id_graph."' style='width:100%;'>";
}
@ -172,15 +172,14 @@ function vbar_graph(
$backgroundColor = 'white',
$from_ux = false,
$from_wux = false,
$tick_color = 'white'
) {
$tick_color = 'white') {
setup_watermark($water_mark, $water_mark_file, $water_mark_url);
if (empty($chart_data)) {
return '<img src="' . $no_data_image . '" />';
}
if ($flash_chart) {
return flot_vcolumn_chart ($chart_data, $width, $height, $color,
$legend, $long_index, $homeurl, $unit, $water_mark_url,
@ -213,337 +212,78 @@ function vbar_graph(
$graph['water_mark'] = $water_mark_file;
$graph['font'] = $font;
$graph['font_size'] = $font_size;
$id_graph = serialize_in_temp($graph, null, $ttl);
return "<img src='" . $homeurl . "include/graphs/functions_pchart.php?static_graph=1&graph_type=vbar&ttl=".$ttl."&id_graph=".$id_graph."'>";
}
}
// NOT USED ACTUALLY
function threshold_graph($flash_chart, $chart_data, $width, $height,
$ttl = 1) {
if ($flash_chart) {
return flot_area_simple_graph($chart_data, $width, $height);
}
else {
echo "<img src='include/graphs/functions_pchart.php?static_graph=1&graph_type=threshold&ttl=".$ttl."&data=".json_encode($chart_data)."&width=".$width."&height=".$height."'>";
}
}
function area_graph(
$agent_module_id, $array_data,
$legend, $series_type, $color, $date_array,
$data_module_graph, $params, $water_mark,
$array_events_alerts) {
global $config;
function area_graph($flash_chart, $chart_data, $width, $height, $color,
$legend, $long_index, $no_data_image, $xaxisname = "",
$yaxisname = "", $homeurl="", $water_mark = "", $font = '',
$font_size = '', $unit = '', $ttl = 1, $series_type = array(),
$chart_extra_data = array(), $yellow_threshold = 0,
$red_threshold = 0, $adapt_key = '', $force_integer = false,
$series_suffix_str = '', $menu = true, $backgroundColor = 'white',
$dashboard = false, $vconsole = false, $agent_module_id = 0, $percentil_values = array(),
$threshold_data = array()) {
include_once('functions_flot.php');
setup_watermark($water_mark, $water_mark_file, $water_mark_url);
// ATTENTION: The min size is in constants.php
// It's not the same minsize for all graphs, but we are choosed a prudent minsize for all
if ($height <= CHART_DEFAULT_HEIGHT) {
$height = CHART_DEFAULT_HEIGHT;
}
if ($width < CHART_DEFAULT_WIDTH) {
$width = CHART_DEFAULT_WIDTH;
}
if (empty($chart_data)) {
return graph_nodata_image($width, $height);
return '<img src="' . $no_data_image . '" />';
}
if ($vconsole) $menu = false;
if ($flash_chart) {
return flot_area_simple_graph(
$chart_data,
$width,
$height,
$color,
$legend,
$long_index,
$homeurl,
$unit,
$water_mark_url,
$series_type,
$chart_extra_data,
$yellow_threshold,
$red_threshold,
$adapt_key,
$force_integer,
$series_suffix_str,
$menu,
$backgroundColor,
$dashboard,
$vconsole,
$agent_module_id,
$font,
$font_size,
$xaxisname,
$percentil_values,
$threshold_data
);
}
else {
$graph = array();
$graph['data'] = $chart_data;
$graph['width'] = $width;
$graph['height'] = $height;
$graph['color'] = $color;
$graph['legend'] = $legend;
$graph['xaxisname'] = $xaxisname;
$graph['yaxisname'] = $yaxisname;
$graph['water_mark'] = $water_mark_file;
$graph['font'] = $font;
$graph['font_size'] = $font_size;
$graph['backgroundColor'] = $backgroundColor;
$graph['unit'] = $unit;
$graph['series_type'] = $series_type;
$graph['percentil'] = $percentil_values;
$id_graph = serialize_in_temp($graph, null, $ttl);
// Warning: This string is used in the function "api_get_module_graph" from 'functions_api.php' with the regec patern "/<img src='(.+)'>/"
return "<img src='" .
ui_get_full_url (false, false, false, false) .
"include/graphs/functions_pchart.php?" .
"static_graph=1&" .
"graph_type=area&" .
"ttl=" . $ttl . "&" .
"id_graph=" . $id_graph . "'>";
}
setup_watermark($water_mark, $water_mark_file, $water_mark_url);
return flot_area_graph(
$agent_module_id,
$array_data,
$legend,
$series_type,
$color,
$date_array,
$data_module_graph,
$params,
$water_mark,
$array_events_alerts
);
}
function stacked_area_graph($flash_chart, $chart_data, $width, $height,
$color, $legend, $long_index, $no_data_image, $xaxisname = "",
$yaxisname = "", $water_mark = "", $font = '', $font_size = '',
$unit = '', $ttl = 1, $homeurl = '', $backgroundColor = 'white',
$dashboard = false, $vconsole = false, $agent_module_id) {
setup_watermark($water_mark, $water_mark_file, $water_mark_url);
if (empty($chart_data)) {
return '<img src="' . $no_data_image . '" />';
}
$menu = (!$dashboard && !$vconsole);
if ($flash_chart) {
return flot_area_stacked_graph(
$chart_data,
$width,
$height,
$color,
$legend,
$long_index,
$homeurl,
$font,
$font_size,
$unit,
$water_mark_url,
array(),
array(),
0,
0,
'',
false,
'',
$menu,
$backgroundColor,
$dashboard,
$vconsole,
$agent_module_id);
}
else {
//Stack the data
stack_data($chart_data, $legend, $color);
$graph = array();
$graph['data'] = $chart_data;
$graph['width'] = $width;
$graph['height'] = $height;
$graph['color'] = $color;
$graph['legend'] = $legend;
$graph['xaxisname'] = $xaxisname;
$graph['yaxisname'] = $yaxisname;
$graph['water_mark'] = $water_mark_file;
$graph['font'] = $font;
$graph['font_size'] = $font_size;
$graph['backgroundColor'] = $backgroundColor;
$id_graph = serialize_in_temp($graph, null, $ttl);
return "<img src='" . ui_get_full_url (false, false, false, false) .
"include/graphs/functions_pchart.php?static_graph=1&graph_type=stacked_area&ttl=".$ttl."&id_graph=" . $id_graph . "' />";
}
}
function stacked_line_graph($flash_chart, $chart_data, $width, $height,
$color, $legend, $long_index, $no_data_image, $xaxisname = "",
$yaxisname = "", $water_mark = "", $font = '', $font_size = '',
$unit = '', $ttl = 1, $homeurl = '', $backgroundColor = 'white',
$dashboard = false, $vconsole = false) {
setup_watermark($water_mark, $water_mark_file, $water_mark_url);
if (empty($chart_data)) {
return '<img src="' . $no_data_image . '" />';
}
$menu = (!$dashboard && !$vconsole);
if ($flash_chart) {
return flot_line_stacked_graph(
$chart_data,
$width,
$height,
$color,
$legend,
$long_index,
$homeurl,
$font,
$font_size,
$unit,
$water_mark_url,
array(),
array(),
0,
0,
'',
false,
'',
$menu,
$backgroundColor,
$dashboard,
$vconsole);
}
else {
//Stack the data
stack_data($chart_data, $legend, $color);
$graph = array();
$graph['data'] = $chart_data;
$graph['width'] = $width;
$graph['height'] = $height;
$graph['color'] = $color;
$graph['legend'] = $legend;
$graph['xaxisname'] = $xaxisname;
$graph['yaxisname'] = $yaxisname;
$graph['water_mark'] = $water_mark_file;
$graph['font'] = $font;
$graph['font_size'] = $font_size;
$graph['backgroundColor'] = $backgroundColor;
$id_graph = serialize_in_temp($graph, null, $ttl);
return "<img src='" . $homeurl . "include/graphs/functions_pchart.php?static_graph=1&graph_type=line&ttl=".$ttl."&id_graph=" . $id_graph . "' />";
}
}
function stacked_bullet_chart($flash_chart, $chart_data, $width, $height,
function stacked_bullet_chart($chart_data, $width, $height,
$color, $legend, $long_index, $no_data_image, $xaxisname = "",
$yaxisname = "", $water_mark = "", $font = '', $font_size = '',
$unit = '', $ttl = 1, $homeurl = '', $backgroundColor = 'white') {
include_once('functions_d3.php');
setup_watermark($water_mark, $water_mark_file, $water_mark_url);
if (empty($chart_data)) {
return '<img src="' . $no_data_image . '" />';
}
if ($flash_chart) {
return d3_bullet_chart(
$chart_data,
$width,
$height,
$color,
$legend,
$homeurl,
$unit,
$font,
$font_size
);
}
else {
$legend = array();
$new_data = array();
foreach($chart_data as $key => $data) {
$temp[] = ($data['min'] != false) ? $data['min'] : 0;
$temp[] = ($data['value'] != false) ? $data['value'] : 0;
$temp[] = ($data['max'] != false) ? $data['max'] : 0;
$legend[] = $data['label'];
array_push($new_data, $temp);
$temp = array();
}
$graph = array();
$graph['data'] = $new_data;
$graph['width'] = $width;
$graph['height'] = $height;
$graph['color'] = $color;
$graph['legend'] = $legend;
$graph['xaxisname'] = $xaxisname;
$graph['yaxisname'] = $yaxisname;
$graph['water_mark'] = $water_mark_file;
$graph['font'] = $font;
$graph['font_size'] = $font_size;
$graph['backgroundColor'] = $backgroundColor;
$id_graph = serialize_in_temp($graph, null, $ttl);
return "<img src='" . $homeurl . "include/graphs/functions_pchart.php?static_graph=1&graph_type=bullet_chart&ttl=".$ttl."&id_graph=" . $id_graph . "' />";
}
}
function stacked_gauge($flash_chart, $chart_data, $width, $height,
$color, $legend, $long_index, $no_data_image, $xaxisname = "",
$yaxisname = "", $water_mark = "", $font = '', $font_size = '',
$unit = '', $ttl = 1, $homeurl = '', $backgroundColor = 'white') {
include_once('functions_d3.php');
setup_watermark($water_mark, $water_mark_file, $water_mark_url);
if (empty($chart_data)) {
return '<img src="' . $no_data_image . '" />';
}
return d3_gauges(
$chart_data,
$width,
$height,
$color,
$legend,
$homeurl,
$unit,
$font,
$font_size + 2,
$no_data_image
);
return d3_bullet_chart(
$chart_data,
$width,
$height,
$color,
$legend,
$homeurl,
$unit,
$font,
$font_size
);
}
function stacked_thermometers($flash_chart, $chart_data, $width, $height,
$color, $legend, $long_index, $no_data_image, $xaxisname = "",
$yaxisname = "", $water_mark = "", $font = '', $font_size = '',
$unit = '', $ttl = 1, $homeurl = '', $backgroundColor = 'white') {
include_once('functions_d3.php');
setup_watermark($water_mark, $water_mark_file, $water_mark_url);
if (empty($chart_data)) {
return '<img src="' . $no_data_image . '" />';
}
return d3_thermometers(
$chart_data,
$width,
@ -558,127 +298,47 @@ function stacked_thermometers($flash_chart, $chart_data, $width, $height,
);
}
function line_graph($flash_chart, $chart_data, $width, $height, $color,
$legend, $long_index, $no_data_image, $xaxisname = "",
$yaxisname = "", $water_mark = "", $font = '', $font_size = '',
$unit = '', $ttl = 1, $homeurl = '', $backgroundColor = 'white',
$dashboard = false, $vconsole = false, $series_type = array(),
$percentil_values = array(), $yellow_threshold = 0, $red_threshold = 0,
$threshold_data = array()) {
include_once("functions_flot.php");
setup_watermark($water_mark, $water_mark_file, $water_mark_url);
function stacked_gauge($chart_data, $width, $height,
$color, $legend, $no_data_image, $font = '', $font_size = '',
$unit = '', $homeurl = '') {
include_once('functions_d3.php');
if (empty($chart_data)) {
return '<img src="' . $no_data_image . '" />';
}
$menu = (!$dashboard && !$vconsole);
if ($flash_chart) {
return flot_line_simple_graph(
$chart_data,
$width,
$height,
$color,
$legend,
$long_index,
$homeurl,
$font,
$font_size,
$unit,
$water_mark_url,
$series_type,
array(),
$yellow_threshold,
$red_threshold,
'',
false,
'',
$menu,
$backgroundColor,
$dashboard,
$vconsole,
false,
$percentil_values,
$threshold_data,
$xaxisname);
}
else {
$graph = array();
$graph['data'] = $chart_data;
$graph['width'] = $width;
$graph['height'] = $height;
$graph['color'] = $color;
$graph['legend'] = $legend;
$graph['xaxisname'] = $xaxisname;
$graph['yaxisname'] = $yaxisname;
$graph['water_mark'] = $water_mark_file;
$graph['font'] = $font;
$graph['font_size'] = $font_size;
$graph['backgroundColor'] = $backgroundColor;
$graph['percentil'] = $percentil_values;
$id_graph = serialize_in_temp($graph, null, $ttl);
if(empty($homeurl)){
return "<img src='" . ui_get_full_url (false, false, false, false) . "include/graphs/functions_pchart.php?static_graph=1&graph_type=line&ttl=".$ttl."&id_graph=" . $id_graph . "' />";
}else{
return "<img src='" . $homeurl . "include/graphs/functions_pchart.php?static_graph=1&graph_type=line&ttl=".$ttl."&id_graph=" . $id_graph . "' />";
}
}
return d3_gauges(
$chart_data,
$width,
$height,
$color,
$legend,
$homeurl,
$unit,
$font,
$font_size + 2,
$no_data_image
);
}
function kiviat_graph($graph_type, $flash_chart, $chart_data, $width,
$height, $no_data_image, $ttl = 1, $homedir="") {
if (empty($chart_data)) {
return '<img src="' . $no_data_image . '" />';
}
$graph = array();
$graph['data'] = $chart_data;
$graph['width'] = $width;
$graph['height'] = $height;
$id_graph = serialize_in_temp($graph, null, $ttl);
return "<img src='".$homedir."include/graphs/functions_pchart.php?static_graph=1&graph_type=".$graph_type."&ttl=".$ttl."&id_graph=" . $id_graph . "' />";
}
function radar_graph($flash_chart, $chart_data, $width, $height,
$no_data_image, $ttl = 1, $homedir="") {
return kiviat_graph('radar', $flash_chart, $chart_data, $width,
$height, $no_data_image, $ttl, $homedir);
}
function polar_graph($flash_chart, $chart_data, $width, $height,
$no_data_image, $ttl = 1, $homedir="") {
return kiviat_graph('polar', $flash_chart, $chart_data, $width,
$height, $no_data_image, $ttl, $homedir="");
}
function hbar_graph($flash_chart, $chart_data, $width, $height,
$color, $legend, $long_index, $no_data_image, $xaxisname = "",
$yaxisname = "", $water_mark = "", $font = '', $font_size = '',
$unit = '', $ttl = 1, $homeurl = '', $backgroundColor = 'white',
$tick_color = "white", $val_min=null, $val_max=null) {
setup_watermark($water_mark, $water_mark_file, $water_mark_url);
if (empty($chart_data)) {
return '<img src="' . $no_data_image . '" />';
}
if ($flash_chart) {
return flot_hcolumn_chart(
$chart_data, $width, $height, $water_mark_url, $font, $font_size, $backgroundColor, $tick_color, $val_min, $val_max);
}
else {
foreach ($chart_data as $key => $value) {
$str_key = io_safe_output($key);
if(strlen($str_key) > 40){
@ -692,8 +352,7 @@ function hbar_graph($flash_chart, $chart_data, $width, $height,
unset($chart_data[$key]);
}
}
$graph = array();
$graph['data'] = $chart_data;
$graph['width'] = $width;
@ -707,9 +366,9 @@ function hbar_graph($flash_chart, $chart_data, $width, $height,
$graph['font'] = $font;
$graph['font_size'] = $font_size;
$graph['force_steps'] = $force_steps;
$id_graph = serialize_in_temp($graph, null, $ttl);
return "<img src='" . $homeurl . "include/graphs/functions_pchart.php?static_graph=1&graph_type=hbar&ttl=".$ttl."&id_graph=".$id_graph."'>";
}
}
@ -718,7 +377,7 @@ function pie3d_graph($flash_chart, $chart_data, $width, $height,
$others_str = "other", $homedir = "", $water_mark = "", $font = '',
$font_size = '', $ttl = 1, $legend_position = false, $colors = '',
$hide_labels = false) {
return pie_graph('3d', $flash_chart, $chart_data, $width, $height,
$others_str, $homedir, $water_mark, $font, $font_size, $ttl,
$legend_position, $colors, $hide_labels);
@ -728,9 +387,9 @@ function pie2d_graph($flash_chart, $chart_data, $width, $height,
$others_str = "other", $homedir="", $water_mark = "", $font = '',
$font_size = '', $ttl = 1, $legend_position = false, $colors = '',
$hide_labels = false) {
return pie_graph('2d', $flash_chart, $chart_data, $width, $height,
$others_str, $homedir, $water_mark, $font, $font_size, $ttl,
$others_str, $homedir, $water_mark, $font, $font_size, $ttl,
$legend_position, $colors, $hide_labels);
}
@ -738,23 +397,23 @@ function pie_graph($graph_type, $flash_chart, $chart_data, $width,
$height, $others_str = "other", $homedir="", $water_mark = "",
$font = '', $font_size = '', $ttl = 1, $legend_position = false,
$colors = '', $hide_labels = false) {
if (empty($chart_data)) {
return graph_nodata_image($width, $height, 'pie');
}
setup_watermark($water_mark, $water_mark_file, $water_mark_url);
// This library allows only 8 colors
$max_values = 9;
//Remove the html_entities
$temp = array();
foreach ($chart_data as $key => $value) {
$temp[io_safe_output($key)] = $value;
}
$chart_data = $temp;
if (count($chart_data) > $max_values) {
$chart_data_trunc = array();
$n = 1;
@ -772,7 +431,7 @@ function pie_graph($graph_type, $flash_chart, $chart_data, $width,
}
$chart_data = $chart_data_trunc;
}
if ($flash_chart) {
return flot_pie_chart(array_values($chart_data),
array_keys($chart_data), $width, $height, $water_mark_url,
@ -780,7 +439,6 @@ function pie_graph($graph_type, $flash_chart, $chart_data, $width,
}
else {
//TODO SET THE LEGEND POSITION
$graph = array();
$graph['data'] = $chart_data;
$graph['width'] = $width;
@ -790,9 +448,9 @@ function pie_graph($graph_type, $flash_chart, $chart_data, $width,
$graph['font_size'] = $font_size;
$graph['legend_position'] = $legend_position;
$graph['color'] = $colors;
$id_graph = serialize_in_temp($graph, null, $ttl);
switch ($graph_type) {
case "2d":
return "<img src='" . $homedir . "include/graphs/functions_pchart.php?static_graph=1&graph_type=pie2d&ttl=".$ttl."&id_graph=".$id_graph."'>";
@ -808,17 +466,16 @@ function ring_graph($flash_chart, $chart_data, $width,
$height, $others_str = "other", $homedir="", $water_mark = "",
$font = '', $font_size = '', $ttl = 1, $legend_position = false,
$colors = '', $hide_labels = false,$background_color = 'white') {
if (empty($chart_data)) {
return graph_nodata_image($width, $height, 'pie');
}
setup_watermark($water_mark, $water_mark_file, $water_mark_url);
// This library allows only 8 colors
$max_values = 18;
if ($flash_chart) {
return flot_custom_pie_chart ($flash_chart, $chart_data,
$width, $height, $colors, $module_name_list, $long_index,
@ -828,7 +485,7 @@ function ring_graph($flash_chart, $chart_data, $width,
else {
$total_modules = $chart_data['total_modules'];
unset($chart_data['total_modules']);
$max_values = 9;
//Remove the html_entities
$n = 0;
@ -842,13 +499,13 @@ function ring_graph($flash_chart, $chart_data, $width,
$n++;
}
$chart_data = $temp;
$chart_data_trunc = array();
$coloretes = array();
$n = 1;
//~ foreach ($chart_data as $key => $value) {
//~ if ($n < $max_values) {
//~ $chart_data_trunc[$key] = $value;
//~ }
//~ else {
@ -860,9 +517,8 @@ function ring_graph($flash_chart, $chart_data, $width,
//~ $n++;
//~ }
//~ $chart_data = $chart_data_trunc;
//TODO SET THE LEGEND POSITION
$graph = array();
$graph['data'] = $chart_data;
$graph['width'] = $width;
@ -872,11 +528,11 @@ function ring_graph($flash_chart, $chart_data, $width,
$graph['font_size'] = $font_size;
$graph['legend_position'] = $legend_position;
$graph['legend'] = $legend;
$id_graph = serialize_in_temp($graph, null, $ttl);
return "<img src='" . $homedir . "include/graphs/functions_pchart.php?static_graph=1&graph_type=ring3d&ttl=".$ttl."&id_graph=".$id_graph."'>";
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,180 @@
/* Plugin for jQuery for working with colors.
*
* Version 1.1.
*
* Inspiration from jQuery color animation plugin by John Resig.
*
* Released under the MIT license by Ole Laursen, October 2009.
*
* Examples:
*
* $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
* var c = $.color.extract($("#mydiv"), 'background-color');
* console.log(c.r, c.g, c.b, c.a);
* $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
*
* Note that .scale() and .add() return the same modified object
* instead of making a new one.
*
* V. 1.1: Fix error handling so e.g. parsing an empty string does
* produce a color rather than just crashing.
*/
(function($) {
$.color = {};
// construct color object with some convenient chainable helpers
$.color.make = function (r, g, b, a) {
var o = {};
o.r = r || 0;
o.g = g || 0;
o.b = b || 0;
o.a = a != null ? a : 1;
o.add = function (c, d) {
for (var i = 0; i < c.length; ++i)
o[c.charAt(i)] += d;
return o.normalize();
};
o.scale = function (c, f) {
for (var i = 0; i < c.length; ++i)
o[c.charAt(i)] *= f;
return o.normalize();
};
o.toString = function () {
if (o.a >= 1.0) {
return "rgb("+[o.r, o.g, o.b].join(",")+")";
} else {
return "rgba("+[o.r, o.g, o.b, o.a].join(",")+")";
}
};
o.normalize = function () {
function clamp(min, value, max) {
return value < min ? min: (value > max ? max: value);
}
o.r = clamp(0, parseInt(o.r), 255);
o.g = clamp(0, parseInt(o.g), 255);
o.b = clamp(0, parseInt(o.b), 255);
o.a = clamp(0, o.a, 1);
return o;
};
o.clone = function () {
return $.color.make(o.r, o.b, o.g, o.a);
};
return o.normalize();
}
// extract CSS color property from element, going up in the DOM
// if it's "transparent"
$.color.extract = function (elem, css) {
var c;
do {
c = elem.css(css).toLowerCase();
// keep going until we find an element that has color, or
// we hit the body or root (have no parent)
if (c != '' && c != 'transparent')
break;
elem = elem.parent();
} while (elem.length && !$.nodeName(elem.get(0), "body"));
// catch Safari's way of signalling transparent
if (c == "rgba(0, 0, 0, 0)")
c = "transparent";
return $.color.parse(c);
}
// parse CSS color string (like "rgb(10, 32, 43)" or "#fff"),
// returns color object, if parsing failed, you get black (0, 0,
// 0) out
$.color.parse = function (str) {
var res, m = $.color.make;
// Look for rgb(num,num,num)
if (res = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))
return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10));
// Look for rgba(num,num,num,num)
if (res = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))
return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10), parseFloat(res[4]));
// Look for rgb(num%,num%,num%)
if (res = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))
return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55);
// Look for rgba(num%,num%,num%,num)
if (res = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))
return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55, parseFloat(res[4]));
// Look for #a0b1c2
if (res = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))
return m(parseInt(res[1], 16), parseInt(res[2], 16), parseInt(res[3], 16));
// Look for #fff
if (res = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))
return m(parseInt(res[1]+res[1], 16), parseInt(res[2]+res[2], 16), parseInt(res[3]+res[3], 16));
// Otherwise, we're most likely dealing with a named color
var name = $.trim(str).toLowerCase();
if (name == "transparent")
return m(255, 255, 255, 0);
else {
// default to black
res = lookupColors[name] || [0, 0, 0];
return m(res[0], res[1], res[2]);
}
}
var lookupColors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]
};
})(jQuery);

View File

@ -0,0 +1 @@
(function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i<c.length;++i)o[c.charAt(i)]+=d;return o.normalize()};o.scale=function(c,f){for(var i=0;i<c.length;++i)o[c.charAt(i)]*=f;return o.normalize()};o.toString=function(){if(o.a>=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return value<min?min:value>max?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);

View File

@ -1,6 +1,11 @@
/*
CAxis Labels Plugin for flot. :P
Copyright (c) 2010 Xuan Luo
Axis Labels Plugin for flot.
http://github.com/markrcote/flot-axislabels
Original code is Copyright (c) 2010 Xuan Luo.
Original code was released under the GPLv3 license by Xuan Luo, September 2010.
Original code was rereleased under the MIT license by Xuan Luo, April 2012.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
@ -8,8 +13,10 @@ without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
@ -18,120 +25,441 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function ($) {
var options = { };
var options = {
axisLabels: {
show: true
}
};
function init(plot) {
// This is kind of a hack. There are no hooks in Flot between
// the creation and measuring of the ticks (setTicks, measureTickLabels
// in setupGrid() ) and the drawing of the ticks and plot box
// (insertAxisLabels in setupGrid() ).
//
// Therefore, we use a trick where we run the draw routine twice:
// the first time to get the tick measurements, so that we can change
// them, and then have it draw it again.
var secondPass = false;
plot.hooks.draw.push(function (plot, ctx) {
if (!secondPass) {
// MEASURE AND SET OPTIONS
$.each(plot.getAxes(), function(axisName, axis) {
var opts = axis.options // Flot 0.7
|| plot.getOptions()[axisName]; // Flot 0.6
if (!opts || !opts.axisLabel)
return;
function canvasSupported() {
return !!document.createElement('canvas').getContext;
}
var w, h;
if (opts.axisLabelUseCanvas != false)
opts.axisLabelUseCanvas = true;
function canvasTextSupported() {
if (!canvasSupported()) {
return false;
}
var dummy_canvas = document.createElement('canvas');
var context = dummy_canvas.getContext('2d');
return typeof context.fillText == 'function';
}
if (opts.axisLabelUseCanvas) {
// canvas text
if (!opts.axisLabelFontSizePixels)
opts.axisLabelFontSizePixels = 14;
if (!opts.axisLabelFontFamily)
opts.axisLabelFontFamily = 'sans-serif';
// since we currently always display x as horiz.
// and y as vertical, we only care about the height
w = opts.axisLabelFontSizePixels;
h = opts.axisLabelFontSizePixels;
} else {
// HTML text
var elem = $('<div class="axisLabels" style="position:absolute;">' + opts.axisLabel + '</div>');
plot.getPlaceholder().append(elem);
w = elem.outerWidth(true);
h = elem.outerHeight(true);
elem.remove();
}
if (axisName.charAt(0) == 'x')
axis.labelHeight += h;
else
axis.labelWidth += w;
opts.labelHeight = axis.labelHeight;
opts.labelWidth = axis.labelWidth;
});
// re-draw with new label widths and heights
secondPass = true;
plot.setupGrid();
plot.draw();
} else {
// DRAW
$.each(plot.getAxes(), function(axisName, axis) {
var opts = axis.options // Flot 0.7
|| plot.getOptions()[axisName]; // Flot 0.6
if (!opts || !opts.axisLabel)
return;
if (opts.axisLabelUseCanvas) {
// canvas text
var ctx = plot.getCanvas().getContext('2d');
ctx.save();
ctx.font = opts.axisLabelFontSizePixels + 'px ' +
opts.axisLabelFontFamily;
var width = ctx.measureText(opts.axisLabel).width;
var height = opts.axisLabelFontSizePixels;
var x, y;
if (axisName.charAt(0) == 'x') {
x = plot.getPlotOffset().left + plot.width()/2 - width/2;
y = plot.getCanvas().height;
} else {
x = height * 0.72;
y = plot.getPlotOffset().top + plot.height()/2 - width/2;
}
ctx.translate(x, y);
ctx.rotate((axisName.charAt(0) == 'x') ? 0 : -Math.PI/2);
ctx.fillText(opts.axisLabel, 0, 0);
ctx.restore();
} else {
// HTML text
plot.getPlaceholder().find('#' + axisName + 'Label').remove();
var elem = $('<div id="' + axisName + 'Label" class="axisLabels" style="position:absolute;">' + opts.axisLabel + '</div>');
if (axisName.charAt(0) == 'x') {
//~ elem.css('left', plot.getPlotOffset().left + plot.width()/4 - elem.outerWidth()/2 + 'px');
elem.css('bottom', '0px');
elem.css('width', '100%');
} else {
elem.css('top', plot.getPlotOffset().top + plot.height()/2 - elem.outerHeight()/2 + 'px');
elem.css('left', '0px');
}
plot.getPlaceholder().append(elem);
}
});
secondPass = false;
}
});
function css3TransitionSupported() {
var div = document.createElement('div');
return typeof div.style.MozTransition != 'undefined' // Gecko
|| typeof div.style.OTransition != 'undefined' // Opera
|| typeof div.style.webkitTransition != 'undefined' // WebKit
|| typeof div.style.transition != 'undefined';
}
function AxisLabel(axisName, position, padding, plot, opts) {
this.axisName = axisName;
this.position = position;
this.padding = padding;
this.plot = plot;
this.opts = opts;
this.width = 0;
this.height = 0;
}
AxisLabel.prototype.cleanup = function() {
};
CanvasAxisLabel.prototype = new AxisLabel();
CanvasAxisLabel.prototype.constructor = CanvasAxisLabel;
function CanvasAxisLabel(axisName, position, padding, plot, opts) {
AxisLabel.prototype.constructor.call(this, axisName, position, padding,
plot, opts);
}
CanvasAxisLabel.prototype.calculateSize = function() {
if (!this.opts.axisLabelFontSizePixels)
this.opts.axisLabelFontSizePixels = 14;
if (!this.opts.axisLabelFontFamily)
this.opts.axisLabelFontFamily = 'sans-serif';
var textWidth = this.opts.axisLabelFontSizePixels + this.padding;
var textHeight = this.opts.axisLabelFontSizePixels + this.padding;
if (this.position == 'left' || this.position == 'right') {
this.width = this.opts.axisLabelFontSizePixels + this.padding;
this.height = 0;
} else {
this.width = 0;
this.height = this.opts.axisLabelFontSizePixels + this.padding;
}
};
CanvasAxisLabel.prototype.draw = function(box) {
if (!this.opts.axisLabelColour)
this.opts.axisLabelColour = 'black';
var ctx = this.plot.getCanvas().getContext('2d');
ctx.save();
ctx.font = this.opts.axisLabelFontSizePixels + 'px ' +
this.opts.axisLabelFontFamily;
ctx.fillStyle = this.opts.axisLabelColour;
var width = ctx.measureText(this.opts.axisLabel).width;
var height = this.opts.axisLabelFontSizePixels;
var x, y, angle = 0;
if (this.position == 'top') {
x = box.left + box.width/2 - width/2;
y = box.top + height*0.72;
} else if (this.position == 'bottom') {
x = box.left + box.width/2 - width/2;
y = box.top + box.height - height*0.72;
} else if (this.position == 'left') {
x = box.left + height*0.72;
y = box.height/2 + box.top + width/2;
angle = -Math.PI/2;
} else if (this.position == 'right') {
x = box.left + box.width - height*0.72;
y = box.height/2 + box.top - width/2;
angle = Math.PI/2;
}
ctx.translate(x, y);
ctx.rotate(angle);
ctx.fillText(this.opts.axisLabel, 0, 0);
ctx.restore();
};
HtmlAxisLabel.prototype = new AxisLabel();
HtmlAxisLabel.prototype.constructor = HtmlAxisLabel;
function HtmlAxisLabel(axisName, position, padding, plot, opts) {
AxisLabel.prototype.constructor.call(this, axisName, position,
padding, plot, opts);
this.elem = null;
}
HtmlAxisLabel.prototype.calculateSize = function() {
var elem = $('<div class="axisLabels" style="position:absolute;">' +
this.opts.axisLabel + '</div>');
this.plot.getPlaceholder().append(elem);
// store height and width of label itself, for use in draw()
this.labelWidth = elem.outerWidth(true);
this.labelHeight = elem.outerHeight(true);
elem.remove();
this.width = this.height = 0;
if (this.position == 'left' || this.position == 'right') {
this.width = this.labelWidth + this.padding;
} else {
this.height = this.labelHeight + this.padding;
}
};
HtmlAxisLabel.prototype.cleanup = function() {
if (this.elem) {
this.elem.remove();
}
};
HtmlAxisLabel.prototype.draw = function(box) {
this.plot.getPlaceholder().find('#' + this.axisName + 'Label').remove();
this.elem = $('<div id="' + this.axisName +
'Label" " class="axisLabels" style="position:absolute;">'
+ this.opts.axisLabel + '</div>');
this.plot.getPlaceholder().append(this.elem);
if (this.position == 'top') {
this.elem.css('left', box.left + box.width/2 - this.labelWidth/2 +
'px');
this.elem.css('top', box.top + 'px');
} else if (this.position == 'bottom') {
this.elem.css('left', box.left + box.width/2 - this.labelWidth/2 +
'px');
this.elem.css('top', box.top + box.height - this.labelHeight +
'px');
} else if (this.position == 'left') {
this.elem.css('top', box.top + box.height/2 - this.labelHeight/2 +
'px');
this.elem.css('left', box.left + 'px');
} else if (this.position == 'right') {
this.elem.css('top', box.top + box.height/2 - this.labelHeight/2 +
'px');
this.elem.css('left', box.left + box.width - this.labelWidth +
'px');
}
};
CssTransformAxisLabel.prototype = new HtmlAxisLabel();
CssTransformAxisLabel.prototype.constructor = CssTransformAxisLabel;
function CssTransformAxisLabel(axisName, position, padding, plot, opts) {
HtmlAxisLabel.prototype.constructor.call(this, axisName, position,
padding, plot, opts);
}
CssTransformAxisLabel.prototype.calculateSize = function() {
HtmlAxisLabel.prototype.calculateSize.call(this);
this.width = this.height = 0;
if (this.position == 'left' || this.position == 'right') {
this.width = this.labelHeight + this.padding;
} else {
this.height = this.labelHeight + this.padding;
}
};
CssTransformAxisLabel.prototype.transforms = function(degrees, x, y) {
var stransforms = {
'-moz-transform': '',
'-webkit-transform': '',
'-o-transform': '',
'-ms-transform': ''
};
if (x != 0 || y != 0) {
var stdTranslate = ' translate(' + x + 'px, ' + y + 'px)';
stransforms['-moz-transform'] += stdTranslate;
stransforms['-webkit-transform'] += stdTranslate;
stransforms['-o-transform'] += stdTranslate;
stransforms['-ms-transform'] += stdTranslate;
}
if (degrees != 0) {
var rotation = degrees / 90;
var stdRotate = ' rotate(' + degrees + 'deg)';
stransforms['-moz-transform'] += stdRotate;
stransforms['-webkit-transform'] += stdRotate;
stransforms['-o-transform'] += stdRotate;
stransforms['-ms-transform'] += stdRotate;
}
var s = 'top: 0; left: 0; ';
for (var prop in stransforms) {
if (stransforms[prop]) {
s += prop + ':' + stransforms[prop] + ';';
}
}
s += ';';
return s;
};
CssTransformAxisLabel.prototype.calculateOffsets = function(box) {
var offsets = { x: 0, y: 0, degrees: 0 };
if (this.position == 'bottom') {
offsets.x = box.left + box.width/2 - this.labelWidth/2;
offsets.y = box.top + box.height - this.labelHeight;
} else if (this.position == 'top') {
offsets.x = box.left + box.width/2 - this.labelWidth/2;
offsets.y = box.top;
} else if (this.position == 'left') {
offsets.degrees = -90;
offsets.x = box.left - this.labelWidth/2 + this.labelHeight/2;
offsets.y = box.height/2 + box.top;
} else if (this.position == 'right') {
offsets.degrees = 90;
offsets.x = box.left + box.width - this.labelWidth/2
- this.labelHeight/2;
offsets.y = box.height/2 + box.top;
}
offsets.x = Math.round(offsets.x);
offsets.y = Math.round(offsets.y);
return offsets;
};
CssTransformAxisLabel.prototype.draw = function(box) {
this.plot.getPlaceholder().find("." + this.axisName + "Label").remove();
var offsets = this.calculateOffsets(box);
this.elem = $('<div class="axisLabels ' + this.axisName +
'Label" style="position:absolute; ' +
this.transforms(offsets.degrees, offsets.x, offsets.y) +
'">' + this.opts.axisLabel + '</div>');
this.plot.getPlaceholder().append(this.elem);
};
IeTransformAxisLabel.prototype = new CssTransformAxisLabel();
IeTransformAxisLabel.prototype.constructor = IeTransformAxisLabel;
function IeTransformAxisLabel(axisName, position, padding, plot, opts) {
CssTransformAxisLabel.prototype.constructor.call(this, axisName,
position, padding,
plot, opts);
this.requiresResize = false;
}
IeTransformAxisLabel.prototype.transforms = function(degrees, x, y) {
// I didn't feel like learning the crazy Matrix stuff, so this uses
// a combination of the rotation transform and CSS positioning.
var s = '';
if (degrees != 0) {
var rotation = degrees/90;
while (rotation < 0) {
rotation += 4;
}
s += ' filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=' + rotation + '); ';
// see below
this.requiresResize = (this.position == 'right');
}
if (x != 0) {
s += 'left: ' + x + 'px; ';
}
if (y != 0) {
s += 'top: ' + y + 'px; ';
}
return s;
};
IeTransformAxisLabel.prototype.calculateOffsets = function(box) {
var offsets = CssTransformAxisLabel.prototype.calculateOffsets.call(
this, box);
// adjust some values to take into account differences between
// CSS and IE rotations.
if (this.position == 'top') {
// FIXME: not sure why, but placing this exactly at the top causes
// the top axis label to flip to the bottom...
offsets.y = box.top + 1;
} else if (this.position == 'left') {
offsets.x = box.left;
offsets.y = box.height/2 + box.top - this.labelWidth/2;
} else if (this.position == 'right') {
offsets.x = box.left + box.width - this.labelHeight;
offsets.y = box.height/2 + box.top - this.labelWidth/2;
}
return offsets;
};
IeTransformAxisLabel.prototype.draw = function(box) {
CssTransformAxisLabel.prototype.draw.call(this, box);
if (this.requiresResize) {
this.elem = this.plot.getPlaceholder().find("." + this.axisName +
"Label");
// Since we used CSS positioning instead of transforms for
// translating the element, and since the positioning is done
// before any rotations, we have to reset the width and height
// in case the browser wrapped the text (specifically for the
// y2axis).
this.elem.css('width', this.labelWidth);
this.elem.css('height', this.labelHeight);
}
};
function init(plot) {
plot.hooks.processOptions.push(function (plot, options) {
if (!options.axisLabels.show)
return;
// This is kind of a hack. There are no hooks in Flot between
// the creation and measuring of the ticks (setTicks, measureTickLabels
// in setupGrid() ) and the drawing of the ticks and plot box
// (insertAxisLabels in setupGrid() ).
//
// Therefore, we use a trick where we run the draw routine twice:
// the first time to get the tick measurements, so that we can change
// them, and then have it draw it again.
var secondPass = false;
var axisLabels = {};
var axisOffsetCounts = { left: 0, right: 0, top: 0, bottom: 0 };
var defaultPadding = 2; // padding between axis and tick labels
plot.hooks.draw.push(function (plot, ctx) {
var hasAxisLabels = false;
if (!secondPass) {
// MEASURE AND SET OPTIONS
$.each(plot.getAxes(), function(axisName, axis) {
var opts = axis.options // Flot 0.7
|| plot.getOptions()[axisName]; // Flot 0.6
// Handle redraws initiated outside of this plug-in.
if (axisName in axisLabels) {
axis.labelHeight = axis.labelHeight -
axisLabels[axisName].height;
axis.labelWidth = axis.labelWidth -
axisLabels[axisName].width;
opts.labelHeight = axis.labelHeight;
opts.labelWidth = axis.labelWidth;
axisLabels[axisName].cleanup();
delete axisLabels[axisName];
}
if (!opts || !opts.axisLabel || !axis.show)
return;
hasAxisLabels = true;
var renderer = null;
if (!opts.axisLabelUseHtml &&
navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
rv = parseFloat(RegExp.$1);
}
if (rv >= 9 && !opts.axisLabelUseCanvas && !opts.axisLabelUseHtml) {
renderer = CssTransformAxisLabel;
} else if (!opts.axisLabelUseCanvas && !opts.axisLabelUseHtml) {
renderer = IeTransformAxisLabel;
} else if (opts.axisLabelUseCanvas) {
renderer = CanvasAxisLabel;
} else {
renderer = HtmlAxisLabel;
}
} else {
if (opts.axisLabelUseHtml || (!css3TransitionSupported() && !canvasTextSupported()) && !opts.axisLabelUseCanvas) {
renderer = HtmlAxisLabel;
} else if (opts.axisLabelUseCanvas || !css3TransitionSupported()) {
renderer = CanvasAxisLabel;
} else {
renderer = CssTransformAxisLabel;
}
}
var padding = opts.axisLabelPadding === undefined ?
defaultPadding : opts.axisLabelPadding;
axisLabels[axisName] = new renderer(axisName,
axis.position, padding,
plot, opts);
// flot interprets axis.labelHeight and .labelWidth as
// the height and width of the tick labels. We increase
// these values to make room for the axis label and
// padding.
axisLabels[axisName].calculateSize();
// AxisLabel.height and .width are the size of the
// axis label and padding.
// Just set opts here because axis will be sorted out on
// the redraw.
opts.labelHeight = axis.labelHeight +
axisLabels[axisName].height;
opts.labelWidth = axis.labelWidth +
axisLabels[axisName].width;
});
// If there are axis labels, re-draw with new label widths and
// heights.
if (hasAxisLabels) {
secondPass = true;
plot.setupGrid();
plot.draw();
}
} else {
secondPass = false;
// DRAW
$.each(plot.getAxes(), function(axisName, axis) {
var opts = axis.options // Flot 0.7
|| plot.getOptions()[axisName]; // Flot 0.6
if (!opts || !opts.axisLabel || !axis.show)
return;
axisLabels[axisName].draw(axis.box);
});
}
});
});
}
$.plot.plugins.push({
init: init,
options: options,
name: 'axisLabels',
version: '1.0'
version: '2.0'
});
})(jQuery);

View File

@ -0,0 +1,345 @@
/* Flot plugin for drawing all elements of a plot on the canvas.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
Flot normally produces certain elements, like axis labels and the legend, using
HTML elements. This permits greater interactivity and customization, and often
looks better, due to cross-browser canvas text inconsistencies and limitations.
It can also be desirable to render the plot entirely in canvas, particularly
if the goal is to save it as an image, or if Flot is being used in a context
where the HTML DOM does not exist, as is the case within Node.js. This plugin
switches out Flot's standard drawing operations for canvas-only replacements.
Currently the plugin supports only axis labels, but it will eventually allow
every element of the plot to be rendered directly to canvas.
The plugin supports these options:
{
canvas: boolean
}
The "canvas" option controls whether full canvas drawing is enabled, making it
possible to toggle on and off. This is useful when a plot uses HTML text in the
browser, but needs to redraw with canvas text when exporting as an image.
*/
(function($) {
var options = {
canvas: true
};
var render, getTextInfo, addText;
// Cache the prototype hasOwnProperty for faster access
var hasOwnProperty = Object.prototype.hasOwnProperty;
function init(plot, classes) {
var Canvas = classes.Canvas;
// We only want to replace the functions once; the second time around
// we would just get our new function back. This whole replacing of
// prototype functions is a disaster, and needs to be changed ASAP.
if (render == null) {
getTextInfo = Canvas.prototype.getTextInfo,
addText = Canvas.prototype.addText,
render = Canvas.prototype.render;
}
// Finishes rendering the canvas, including overlaid text
Canvas.prototype.render = function() {
if (!plot.getOptions().canvas) {
return render.call(this);
}
var context = this.context,
cache = this._textCache;
// For each text layer, render elements marked as active
context.save();
context.textBaseline = "middle";
for (var layerKey in cache) {
if (hasOwnProperty.call(cache, layerKey)) {
var layerCache = cache[layerKey];
for (var styleKey in layerCache) {
if (hasOwnProperty.call(layerCache, styleKey)) {
var styleCache = layerCache[styleKey],
updateStyles = true;
for (var key in styleCache) {
if (hasOwnProperty.call(styleCache, key)) {
var info = styleCache[key],
positions = info.positions,
lines = info.lines;
// Since every element at this level of the cache have the
// same font and fill styles, we can just change them once
// using the values from the first element.
if (updateStyles) {
context.fillStyle = info.font.color;
context.font = info.font.definition;
updateStyles = false;
}
for (var i = 0, position; position = positions[i]; i++) {
if (position.active) {
for (var j = 0, line; line = position.lines[j]; j++) {
context.fillText(lines[j].text, line[0], line[1]);
}
} else {
positions.splice(i--, 1);
}
}
if (positions.length == 0) {
delete styleCache[key];
}
}
}
}
}
}
}
context.restore();
};
// Creates (if necessary) and returns a text info object.
//
// When the canvas option is set, the object looks like this:
//
// {
// width: Width of the text's bounding box.
// height: Height of the text's bounding box.
// positions: Array of positions at which this text is drawn.
// lines: [{
// height: Height of this line.
// widths: Width of this line.
// text: Text on this line.
// }],
// font: {
// definition: Canvas font property string.
// color: Color of the text.
// },
// }
//
// The positions array contains objects that look like this:
//
// {
// active: Flag indicating whether the text should be visible.
// lines: Array of [x, y] coordinates at which to draw the line.
// x: X coordinate at which to draw the text.
// y: Y coordinate at which to draw the text.
// }
Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) {
if (!plot.getOptions().canvas) {
return getTextInfo.call(this, layer, text, font, angle, width);
}
var textStyle, layerCache, styleCache, info;
// Cast the value to a string, in case we were given a number
text = "" + text;
// If the font is a font-spec object, generate a CSS definition
if (typeof font === "object") {
textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px " + font.family;
} else {
textStyle = font;
}
// Retrieve (or create) the cache for the text's layer and styles
layerCache = this._textCache[layer];
if (layerCache == null) {
layerCache = this._textCache[layer] = {};
}
styleCache = layerCache[textStyle];
if (styleCache == null) {
styleCache = layerCache[textStyle] = {};
}
info = styleCache[text];
if (info == null) {
var context = this.context;
// If the font was provided as CSS, create a div with those
// classes and examine it to generate a canvas font spec.
if (typeof font !== "object") {
var element = $("<div>&nbsp;</div>")
.css("position", "absolute")
.addClass(typeof font === "string" ? font : null)
.appendTo(this.getTextLayer(layer));
font = {
lineHeight: element.height(),
style: element.css("font-style"),
variant: element.css("font-variant"),
weight: element.css("font-weight"),
family: element.css("font-family"),
color: element.css("color")
};
// Setting line-height to 1, without units, sets it equal
// to the font-size, even if the font-size is abstract,
// like 'smaller'. This enables us to read the real size
// via the element's height, working around browsers that
// return the literal 'smaller' value.
font.size = element.css("line-height", 1).height();
element.remove();
}
textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px " + font.family;
// Create a new info object, initializing the dimensions to
// zero so we can count them up line-by-line.
info = styleCache[text] = {
width: 0,
height: 0,
positions: [],
lines: [],
font: {
definition: textStyle,
color: font.color
}
};
context.save();
context.font = textStyle;
// Canvas can't handle multi-line strings; break on various
// newlines, including HTML brs, to build a list of lines.
// Note that we could split directly on regexps, but IE < 9 is
// broken; revisit when we drop IE 7/8 support.
var lines = (text + "").replace(/<br ?\/?>|\r\n|\r/g, "\n").split("\n");
for (var i = 0; i < lines.length; ++i) {
var lineText = lines[i],
measured = context.measureText(lineText);
info.width = Math.max(measured.width, info.width);
info.height += font.lineHeight;
info.lines.push({
text: lineText,
width: measured.width,
height: font.lineHeight
});
}
context.restore();
}
return info;
};
// Adds a text string to the canvas text overlay.
Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) {
if (!plot.getOptions().canvas) {
return addText.call(this, layer, x, y, text, font, angle, width, halign, valign);
}
var info = this.getTextInfo(layer, text, font, angle, width),
positions = info.positions,
lines = info.lines;
// Text is drawn with baseline 'middle', which we need to account
// for by adding half a line's height to the y position.
y += info.height / lines.length / 2;
// Tweak the initial y-position to match vertical alignment
if (valign == "middle") {
y = Math.round(y - info.height / 2);
} else if (valign == "bottom") {
y = Math.round(y - info.height);
} else {
y = Math.round(y);
}
// FIXME: LEGACY BROWSER FIX
// AFFECTS: Opera < 12.00
// Offset the y coordinate, since Opera is off pretty
// consistently compared to the other browsers.
if (!!(window.opera && window.opera.version().split(".")[0] < 12)) {
y -= 2;
}
// Determine whether this text already exists at this position.
// If so, mark it for inclusion in the next render pass.
for (var i = 0, position; position = positions[i]; i++) {
if (position.x == x && position.y == y) {
position.active = true;
return;
}
}
// If the text doesn't exist at this position, create a new entry
position = {
active: true,
lines: [],
x: x,
y: y
};
positions.push(position);
// Fill in the x & y positions of each line, adjusting them
// individually for horizontal alignment.
for (var i = 0, line; line = lines[i]; i++) {
if (halign == "center") {
position.lines.push([Math.round(x - line.width / 2), y]);
} else if (halign == "right") {
position.lines.push([Math.round(x - line.width), y]);
} else {
position.lines.push([Math.round(x), y]);
}
y += line.height;
}
};
}
$.plot.plugins.push({
init: init,
options: options,
name: "canvas",
version: "1.0"
});
})(jQuery);

View File

@ -0,0 +1,7 @@
/* Javascript plotting library for jQuery, version 0.8.3.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
*/
(function($){var options={canvas:true};var render,getTextInfo,addText;var hasOwnProperty=Object.prototype.hasOwnProperty;function init(plot,classes){var Canvas=classes.Canvas;if(render==null){getTextInfo=Canvas.prototype.getTextInfo,addText=Canvas.prototype.addText,render=Canvas.prototype.render}Canvas.prototype.render=function(){if(!plot.getOptions().canvas){return render.call(this)}var context=this.context,cache=this._textCache;context.save();context.textBaseline="middle";for(var layerKey in cache){if(hasOwnProperty.call(cache,layerKey)){var layerCache=cache[layerKey];for(var styleKey in layerCache){if(hasOwnProperty.call(layerCache,styleKey)){var styleCache=layerCache[styleKey],updateStyles=true;for(var key in styleCache){if(hasOwnProperty.call(styleCache,key)){var info=styleCache[key],positions=info.positions,lines=info.lines;if(updateStyles){context.fillStyle=info.font.color;context.font=info.font.definition;updateStyles=false}for(var i=0,position;position=positions[i];i++){if(position.active){for(var j=0,line;line=position.lines[j];j++){context.fillText(lines[j].text,line[0],line[1])}}else{positions.splice(i--,1)}}if(positions.length==0){delete styleCache[key]}}}}}}}context.restore()};Canvas.prototype.getTextInfo=function(layer,text,font,angle,width){if(!plot.getOptions().canvas){return getTextInfo.call(this,layer,text,font,angle,width)}var textStyle,layerCache,styleCache,info;text=""+text;if(typeof font==="object"){textStyle=font.style+" "+font.variant+" "+font.weight+" "+font.size+"px "+font.family}else{textStyle=font}layerCache=this._textCache[layer];if(layerCache==null){layerCache=this._textCache[layer]={}}styleCache=layerCache[textStyle];if(styleCache==null){styleCache=layerCache[textStyle]={}}info=styleCache[text];if(info==null){var context=this.context;if(typeof font!=="object"){var element=$("<div>&nbsp;</div>").css("position","absolute").addClass(typeof font==="string"?font:null).appendTo(this.getTextLayer(layer));font={lineHeight:element.height(),style:element.css("font-style"),variant:element.css("font-variant"),weight:element.css("font-weight"),family:element.css("font-family"),color:element.css("color")};font.size=element.css("line-height",1).height();element.remove()}textStyle=font.style+" "+font.variant+" "+font.weight+" "+font.size+"px "+font.family;info=styleCache[text]={width:0,height:0,positions:[],lines:[],font:{definition:textStyle,color:font.color}};context.save();context.font=textStyle;var lines=(text+"").replace(/<br ?\/?>|\r\n|\r/g,"\n").split("\n");for(var i=0;i<lines.length;++i){var lineText=lines[i],measured=context.measureText(lineText);info.width=Math.max(measured.width,info.width);info.height+=font.lineHeight;info.lines.push({text:lineText,width:measured.width,height:font.lineHeight})}context.restore()}return info};Canvas.prototype.addText=function(layer,x,y,text,font,angle,width,halign,valign){if(!plot.getOptions().canvas){return addText.call(this,layer,x,y,text,font,angle,width,halign,valign)}var info=this.getTextInfo(layer,text,font,angle,width),positions=info.positions,lines=info.lines;y+=info.height/lines.length/2;if(valign=="middle"){y=Math.round(y-info.height/2)}else if(valign=="bottom"){y=Math.round(y-info.height)}else{y=Math.round(y)}if(!!(window.opera&&window.opera.version().split(".")[0]<12)){y-=2}for(var i=0,position;position=positions[i];i++){if(position.x==x&&position.y==y){position.active=true;return}}position={active:true,lines:[],x:x,y:y};positions.push(position);for(var i=0,line;line=lines[i];i++){if(halign=="center"){position.lines.push([Math.round(x-line.width/2),y])}else if(halign=="right"){position.lines.push([Math.round(x-line.width),y])}else{position.lines.push([Math.round(x),y])}y+=line.height}}}$.plot.plugins.push({init:init,options:options,name:"canvas",version:"1.0"})})(jQuery);

View File

@ -0,0 +1,190 @@
/* Flot plugin for plotting textual data or categories.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
Consider a dataset like [["February", 34], ["March", 20], ...]. This plugin
allows you to plot such a dataset directly.
To enable it, you must specify mode: "categories" on the axis with the textual
labels, e.g.
$.plot("#placeholder", data, { xaxis: { mode: "categories" } });
By default, the labels are ordered as they are met in the data series. If you
need a different ordering, you can specify "categories" on the axis options
and list the categories there:
xaxis: {
mode: "categories",
categories: ["February", "March", "April"]
}
If you need to customize the distances between the categories, you can specify
"categories" as an object mapping labels to values
xaxis: {
mode: "categories",
categories: { "February": 1, "March": 3, "April": 4 }
}
If you don't specify all categories, the remaining categories will be numbered
from the max value plus 1 (with a spacing of 1 between each).
Internally, the plugin works by transforming the input data through an auto-
generated mapping where the first category becomes 0, the second 1, etc.
Hence, a point like ["February", 34] becomes [0, 34] internally in Flot (this
is visible in hover and click events that return numbers rather than the
category labels). The plugin also overrides the tick generator to spit out the
categories as ticks instead of the values.
If you need to map a value back to its label, the mapping is always accessible
as "categories" on the axis object, e.g. plot.getAxes().xaxis.categories.
*/
(function ($) {
var options = {
xaxis: {
categories: null
},
yaxis: {
categories: null
}
};
function processRawData(plot, series, data, datapoints) {
// if categories are enabled, we need to disable
// auto-transformation to numbers so the strings are intact
// for later processing
var xCategories = series.xaxis.options.mode == "categories",
yCategories = series.yaxis.options.mode == "categories";
if (!(xCategories || yCategories))
return;
var format = datapoints.format;
if (!format) {
// FIXME: auto-detection should really not be defined here
var s = series;
format = [];
format.push({ x: true, number: true, required: true });
format.push({ y: true, number: true, required: true });
if (s.bars.show || (s.lines.show && s.lines.fill)) {
var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero));
format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale });
if (s.bars.horizontal) {
delete format[format.length - 1].y;
format[format.length - 1].x = true;
}
}
datapoints.format = format;
}
for (var m = 0; m < format.length; ++m) {
if (format[m].x && xCategories)
format[m].number = false;
if (format[m].y && yCategories)
format[m].number = false;
}
}
function getNextIndex(categories) {
var index = -1;
for (var v in categories)
if (categories[v] > index)
index = categories[v];
return index + 1;
}
function categoriesTickGenerator(axis) {
var res = [];
for (var label in axis.categories) {
var v = axis.categories[label];
if (v >= axis.min && v <= axis.max)
res.push([v, label]);
}
res.sort(function (a, b) { return a[0] - b[0]; });
return res;
}
function setupCategoriesForAxis(series, axis, datapoints) {
if (series[axis].options.mode != "categories")
return;
if (!series[axis].categories) {
// parse options
var c = {}, o = series[axis].options.categories || {};
if ($.isArray(o)) {
for (var i = 0; i < o.length; ++i)
c[o[i]] = i;
}
else {
for (var v in o)
c[v] = o[v];
}
series[axis].categories = c;
}
// fix ticks
if (!series[axis].options.ticks)
series[axis].options.ticks = categoriesTickGenerator;
transformPointsOnAxis(datapoints, axis, series[axis].categories);
}
function transformPointsOnAxis(datapoints, axis, categories) {
// go through the points, transforming them
var points = datapoints.points,
ps = datapoints.pointsize,
format = datapoints.format,
formatColumn = axis.charAt(0),
index = getNextIndex(categories);
for (var i = 0; i < points.length; i += ps) {
if (points[i] == null)
continue;
for (var m = 0; m < ps; ++m) {
var val = points[i + m];
if (val == null || !format[m][formatColumn])
continue;
if (!(val in categories)) {
categories[val] = index;
++index;
}
points[i + m] = categories[val];
}
}
}
function processDatapoints(plot, series, datapoints) {
setupCategoriesForAxis(series, "xaxis", datapoints);
setupCategoriesForAxis(series, "yaxis", datapoints);
}
function init(plot) {
plot.hooks.processRawData.push(processRawData);
plot.hooks.processDatapoints.push(processDatapoints);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'categories',
version: '1.0'
});
})(jQuery);

View File

@ -0,0 +1,7 @@
/* Javascript plotting library for jQuery, version 0.8.3.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
*/
(function($){var options={xaxis:{categories:null},yaxis:{categories:null}};function processRawData(plot,series,data,datapoints){var xCategories=series.xaxis.options.mode=="categories",yCategories=series.yaxis.options.mode=="categories";if(!(xCategories||yCategories))return;var format=datapoints.format;if(!format){var s=series;format=[];format.push({x:true,number:true,required:true});format.push({y:true,number:true,required:true});if(s.bars.show||s.lines.show&&s.lines.fill){var autoscale=!!(s.bars.show&&s.bars.zero||s.lines.show&&s.lines.zero);format.push({y:true,number:true,required:false,defaultValue:0,autoscale:autoscale});if(s.bars.horizontal){delete format[format.length-1].y;format[format.length-1].x=true}}datapoints.format=format}for(var m=0;m<format.length;++m){if(format[m].x&&xCategories)format[m].number=false;if(format[m].y&&yCategories)format[m].number=false}}function getNextIndex(categories){var index=-1;for(var v in categories)if(categories[v]>index)index=categories[v];return index+1}function categoriesTickGenerator(axis){var res=[];for(var label in axis.categories){var v=axis.categories[label];if(v>=axis.min&&v<=axis.max)res.push([v,label])}res.sort(function(a,b){return a[0]-b[0]});return res}function setupCategoriesForAxis(series,axis,datapoints){if(series[axis].options.mode!="categories")return;if(!series[axis].categories){var c={},o=series[axis].options.categories||{};if($.isArray(o)){for(var i=0;i<o.length;++i)c[o[i]]=i}else{for(var v in o)c[v]=o[v]}series[axis].categories=c}if(!series[axis].options.ticks)series[axis].options.ticks=categoriesTickGenerator;transformPointsOnAxis(datapoints,axis,series[axis].categories)}function transformPointsOnAxis(datapoints,axis,categories){var points=datapoints.points,ps=datapoints.pointsize,format=datapoints.format,formatColumn=axis.charAt(0),index=getNextIndex(categories);for(var i=0;i<points.length;i+=ps){if(points[i]==null)continue;for(var m=0;m<ps;++m){var val=points[i+m];if(val==null||!format[m][formatColumn])continue;if(!(val in categories)){categories[val]=index;++index}points[i+m]=categories[val]}}}function processDatapoints(plot,series,datapoints){setupCategoriesForAxis(series,"xaxis",datapoints);setupCategoriesForAxis(series,"yaxis",datapoints)}function init(plot){plot.hooks.processRawData.push(processRawData);plot.hooks.processDatapoints.push(processDatapoints)}$.plot.plugins.push({init:init,options:options,name:"categories",version:"1.0"})})(jQuery);

View File

@ -0,0 +1,176 @@
/* Flot plugin for showing crosshairs when the mouse hovers over the plot.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
The plugin supports these options:
crosshair: {
mode: null or "x" or "y" or "xy"
color: color
lineWidth: number
}
Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical
crosshair that lets you trace the values on the x axis, "y" enables a
horizontal crosshair and "xy" enables them both. "color" is the color of the
crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of
the drawn lines (default is 1).
The plugin also adds four public methods:
- setCrosshair( pos )
Set the position of the crosshair. Note that this is cleared if the user
moves the mouse. "pos" is in coordinates of the plot and should be on the
form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple
axes), which is coincidentally the same format as what you get from a
"plothover" event. If "pos" is null, the crosshair is cleared.
- clearCrosshair()
Clear the crosshair.
- lockCrosshair(pos)
Cause the crosshair to lock to the current location, no longer updating if
the user moves the mouse. Optionally supply a position (passed on to
setCrosshair()) to move it to.
Example usage:
var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } };
$("#graph").bind( "plothover", function ( evt, position, item ) {
if ( item ) {
// Lock the crosshair to the data point being hovered
myFlot.lockCrosshair({
x: item.datapoint[ 0 ],
y: item.datapoint[ 1 ]
});
} else {
// Return normal crosshair operation
myFlot.unlockCrosshair();
}
});
- unlockCrosshair()
Free the crosshair to move again after locking it.
*/
(function ($) {
var options = {
crosshair: {
mode: null, // one of null, "x", "y" or "xy",
color: "rgba(170, 0, 0, 0.80)",
lineWidth: 1
}
};
function init(plot) {
// position of crosshair in pixels
var crosshair = { x: -1, y: -1, locked: false };
plot.setCrosshair = function setCrosshair(pos) {
if (!pos)
crosshair.x = -1;
else {
var o = plot.p2c(pos);
crosshair.x = Math.max(0, Math.min(o.left, plot.width()));
crosshair.y = Math.max(0, Math.min(o.top, plot.height()));
}
plot.triggerRedrawOverlay();
};
plot.clearCrosshair = plot.setCrosshair; // passes null for pos
plot.lockCrosshair = function lockCrosshair(pos) {
if (pos)
plot.setCrosshair(pos);
crosshair.locked = true;
};
plot.unlockCrosshair = function unlockCrosshair() {
crosshair.locked = false;
};
function onMouseOut(e) {
if (crosshair.locked)
return;
if (crosshair.x != -1) {
crosshair.x = -1;
plot.triggerRedrawOverlay();
}
}
function onMouseMove(e) {
if (crosshair.locked)
return;
if (plot.getSelection && plot.getSelection()) {
crosshair.x = -1; // hide the crosshair while selecting
return;
}
var offset = plot.offset();
crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width()));
crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height()));
plot.triggerRedrawOverlay();
}
plot.hooks.bindEvents.push(function (plot, eventHolder) {
if (!plot.getOptions().crosshair.mode)
return;
eventHolder.mouseout(onMouseOut);
eventHolder.mousemove(onMouseMove);
});
plot.hooks.drawOverlay.push(function (plot, ctx) {
var c = plot.getOptions().crosshair;
if (!c.mode)
return;
var plotOffset = plot.getPlotOffset();
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
if (crosshair.x != -1) {
var adj = plot.getOptions().crosshair.lineWidth % 2 ? 0.5 : 0;
ctx.strokeStyle = c.color;
ctx.lineWidth = c.lineWidth;
ctx.lineJoin = "round";
ctx.beginPath();
if (c.mode.indexOf("x") != -1) {
var drawX = Math.floor(crosshair.x) + adj;
ctx.moveTo(drawX, 0);
ctx.lineTo(drawX, plot.height());
}
if (c.mode.indexOf("y") != -1) {
var drawY = Math.floor(crosshair.y) + adj;
ctx.moveTo(0, drawY);
ctx.lineTo(plot.width(), drawY);
}
ctx.stroke();
}
ctx.restore();
});
plot.hooks.shutdown.push(function (plot, eventHolder) {
eventHolder.unbind("mouseout", onMouseOut);
eventHolder.unbind("mousemove", onMouseMove);
});
}
$.plot.plugins.push({
init: init,
options: options,
name: 'crosshair',
version: '1.0'
});
})(jQuery);

View File

@ -1 +1,7 @@
(function(b){var a={crosshair:{mode:null,color:"rgba(170, 0, 0, 0.80)",lineWidth:1}};function c(h){var j={x:-1,y:-1,locked:false};h.setCrosshair=function e(l){if(!l){j.x=-1}else{var k=h.p2c(l);j.x=Math.max(0,Math.min(k.left,h.width()));j.y=Math.max(0,Math.min(k.top,h.height()))}h.triggerRedrawOverlay()};h.clearCrosshair=h.setCrosshair;h.lockCrosshair=function f(k){if(k){h.setCrosshair(k)}j.locked=true};h.unlockCrosshair=function g(){j.locked=false};function d(k){if(j.locked){return}if(j.x!=-1){j.x=-1;h.triggerRedrawOverlay()}}function i(k){if(j.locked){return}if(h.getSelection&&h.getSelection()){j.x=-1;return}var l=h.offset();j.x=Math.max(0,Math.min(k.pageX-l.left,h.width()));j.y=Math.max(0,Math.min(k.pageY-l.top,h.height()));h.triggerRedrawOverlay()}h.hooks.bindEvents.push(function(l,k){if(!l.getOptions().crosshair.mode){return}k.mouseout(d);k.mousemove(i)});h.hooks.drawOverlay.push(function(m,k){var n=m.getOptions().crosshair;if(!n.mode){return}var l=m.getPlotOffset();k.save();k.translate(l.left,l.top);if(j.x!=-1){k.strokeStyle=n.color;k.lineWidth=n.lineWidth;k.lineJoin="round";k.beginPath();if(n.mode.indexOf("x")!=-1){k.moveTo(j.x,0);k.lineTo(j.x,m.height())}if(n.mode.indexOf("y")!=-1){k.moveTo(0,j.y);k.lineTo(m.width(),j.y)}k.stroke()}k.restore()});h.hooks.shutdown.push(function(l,k){k.unbind("mouseout",d);k.unbind("mousemove",i)})}b.plot.plugins.push({init:c,options:a,name:"crosshair",version:"1.0"})})(jQuery);
/* Javascript plotting library for jQuery, version 0.8.3.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
*/
(function($){var options={crosshair:{mode:null,color:"rgba(170, 0, 0, 0.80)",lineWidth:1}};function init(plot){var crosshair={x:-1,y:-1,locked:false};plot.setCrosshair=function setCrosshair(pos){if(!pos)crosshair.x=-1;else{var o=plot.p2c(pos);crosshair.x=Math.max(0,Math.min(o.left,plot.width()));crosshair.y=Math.max(0,Math.min(o.top,plot.height()))}plot.triggerRedrawOverlay()};plot.clearCrosshair=plot.setCrosshair;plot.lockCrosshair=function lockCrosshair(pos){if(pos)plot.setCrosshair(pos);crosshair.locked=true};plot.unlockCrosshair=function unlockCrosshair(){crosshair.locked=false};function onMouseOut(e){if(crosshair.locked)return;if(crosshair.x!=-1){crosshair.x=-1;plot.triggerRedrawOverlay()}}function onMouseMove(e){if(crosshair.locked)return;if(plot.getSelection&&plot.getSelection()){crosshair.x=-1;return}var offset=plot.offset();crosshair.x=Math.max(0,Math.min(e.pageX-offset.left,plot.width()));crosshair.y=Math.max(0,Math.min(e.pageY-offset.top,plot.height()));plot.triggerRedrawOverlay()}plot.hooks.bindEvents.push(function(plot,eventHolder){if(!plot.getOptions().crosshair.mode)return;eventHolder.mouseout(onMouseOut);eventHolder.mousemove(onMouseMove)});plot.hooks.drawOverlay.push(function(plot,ctx){var c=plot.getOptions().crosshair;if(!c.mode)return;var plotOffset=plot.getPlotOffset();ctx.save();ctx.translate(plotOffset.left,plotOffset.top);if(crosshair.x!=-1){var adj=plot.getOptions().crosshair.lineWidth%2?.5:0;ctx.strokeStyle=c.color;ctx.lineWidth=c.lineWidth;ctx.lineJoin="round";ctx.beginPath();if(c.mode.indexOf("x")!=-1){var drawX=Math.floor(crosshair.x)+adj;ctx.moveTo(drawX,0);ctx.lineTo(drawX,plot.height())}if(c.mode.indexOf("y")!=-1){var drawY=Math.floor(crosshair.y)+adj;ctx.moveTo(0,drawY);ctx.lineTo(plot.width(),drawY)}ctx.stroke()}ctx.restore()});plot.hooks.shutdown.push(function(plot,eventHolder){eventHolder.unbind("mouseout",onMouseOut);eventHolder.unbind("mousemove",onMouseMove)})}$.plot.plugins.push({init:init,options:options,name:"crosshair",version:"1.0"})})(jQuery);

View File

@ -0,0 +1,353 @@
/* Flot plugin for plotting error bars.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
Error bars are used to show standard deviation and other statistical
properties in a plot.
* Created by Rui Pereira - rui (dot) pereira (at) gmail (dot) com
This plugin allows you to plot error-bars over points. Set "errorbars" inside
the points series to the axis name over which there will be error values in
your data array (*even* if you do not intend to plot them later, by setting
"show: null" on xerr/yerr).
The plugin supports these options:
series: {
points: {
errorbars: "x" or "y" or "xy",
xerr: {
show: null/false or true,
asymmetric: null/false or true,
upperCap: null or "-" or function,
lowerCap: null or "-" or function,
color: null or color,
radius: null or number
},
yerr: { same options as xerr }
}
}
Each data point array is expected to be of the type:
"x" [ x, y, xerr ]
"y" [ x, y, yerr ]
"xy" [ x, y, xerr, yerr ]
Where xerr becomes xerr_lower,xerr_upper for the asymmetric error case, and
equivalently for yerr. Eg., a datapoint for the "xy" case with symmetric
error-bars on X and asymmetric on Y would be:
[ x, y, xerr, yerr_lower, yerr_upper ]
By default no end caps are drawn. Setting upperCap and/or lowerCap to "-" will
draw a small cap perpendicular to the error bar. They can also be set to a
user-defined drawing function, with (ctx, x, y, radius) as parameters, as eg.
function drawSemiCircle( ctx, x, y, radius ) {
ctx.beginPath();
ctx.arc( x, y, radius, 0, Math.PI, false );
ctx.moveTo( x - radius, y );
ctx.lineTo( x + radius, y );
ctx.stroke();
}
Color and radius both default to the same ones of the points series if not
set. The independent radius parameter on xerr/yerr is useful for the case when
we may want to add error-bars to a line, without showing the interconnecting
points (with radius: 0), and still showing end caps on the error-bars.
shadowSize and lineWidth are derived as well from the points series.
*/
(function ($) {
var options = {
series: {
points: {
errorbars: null, //should be 'x', 'y' or 'xy'
xerr: { err: 'x', show: null, asymmetric: null, upperCap: null, lowerCap: null, color: null, radius: null},
yerr: { err: 'y', show: null, asymmetric: null, upperCap: null, lowerCap: null, color: null, radius: null}
}
}
};
function processRawData(plot, series, data, datapoints){
if (!series.points.errorbars)
return;
// x,y values
var format = [
{ x: true, number: true, required: true },
{ y: true, number: true, required: true }
];
var errors = series.points.errorbars;
// error bars - first X then Y
if (errors == 'x' || errors == 'xy') {
// lower / upper error
if (series.points.xerr.asymmetric) {
format.push({ x: true, number: true, required: true });
format.push({ x: true, number: true, required: true });
} else
format.push({ x: true, number: true, required: true });
}
if (errors == 'y' || errors == 'xy') {
// lower / upper error
if (series.points.yerr.asymmetric) {
format.push({ y: true, number: true, required: true });
format.push({ y: true, number: true, required: true });
} else
format.push({ y: true, number: true, required: true });
}
datapoints.format = format;
}
function parseErrors(series, i){
var points = series.datapoints.points;
// read errors from points array
var exl = null,
exu = null,
eyl = null,
eyu = null;
var xerr = series.points.xerr,
yerr = series.points.yerr;
var eb = series.points.errorbars;
// error bars - first X
if (eb == 'x' || eb == 'xy') {
if (xerr.asymmetric) {
exl = points[i + 2];
exu = points[i + 3];
if (eb == 'xy')
if (yerr.asymmetric){
eyl = points[i + 4];
eyu = points[i + 5];
} else eyl = points[i + 4];
} else {
exl = points[i + 2];
if (eb == 'xy')
if (yerr.asymmetric) {
eyl = points[i + 3];
eyu = points[i + 4];
} else eyl = points[i + 3];
}
// only Y
} else if (eb == 'y')
if (yerr.asymmetric) {
eyl = points[i + 2];
eyu = points[i + 3];
} else eyl = points[i + 2];
// symmetric errors?
if (exu == null) exu = exl;
if (eyu == null) eyu = eyl;
var errRanges = [exl, exu, eyl, eyu];
// nullify if not showing
if (!xerr.show){
errRanges[0] = null;
errRanges[1] = null;
}
if (!yerr.show){
errRanges[2] = null;
errRanges[3] = null;
}
return errRanges;
}
function drawSeriesErrors(plot, ctx, s){
var points = s.datapoints.points,
ps = s.datapoints.pointsize,
ax = [s.xaxis, s.yaxis],
radius = s.points.radius,
err = [s.points.xerr, s.points.yerr];
//sanity check, in case some inverted axis hack is applied to flot
var invertX = false;
if (ax[0].p2c(ax[0].max) < ax[0].p2c(ax[0].min)) {
invertX = true;
var tmp = err[0].lowerCap;
err[0].lowerCap = err[0].upperCap;
err[0].upperCap = tmp;
}
var invertY = false;
if (ax[1].p2c(ax[1].min) < ax[1].p2c(ax[1].max)) {
invertY = true;
var tmp = err[1].lowerCap;
err[1].lowerCap = err[1].upperCap;
err[1].upperCap = tmp;
}
for (var i = 0; i < s.datapoints.points.length; i += ps) {
//parse
var errRanges = parseErrors(s, i);
//cycle xerr & yerr
for (var e = 0; e < err.length; e++){
var minmax = [ax[e].min, ax[e].max];
//draw this error?
if (errRanges[e * err.length]){
//data coordinates
var x = points[i],
y = points[i + 1];
//errorbar ranges
var upper = [x, y][e] + errRanges[e * err.length + 1],
lower = [x, y][e] - errRanges[e * err.length];
//points outside of the canvas
if (err[e].err == 'x')
if (y > ax[1].max || y < ax[1].min || upper < ax[0].min || lower > ax[0].max)
continue;
if (err[e].err == 'y')
if (x > ax[0].max || x < ax[0].min || upper < ax[1].min || lower > ax[1].max)
continue;
// prevent errorbars getting out of the canvas
var drawUpper = true,
drawLower = true;
if (upper > minmax[1]) {
drawUpper = false;
upper = minmax[1];
}
if (lower < minmax[0]) {
drawLower = false;
lower = minmax[0];
}
//sanity check, in case some inverted axis hack is applied to flot
if ((err[e].err == 'x' && invertX) || (err[e].err == 'y' && invertY)) {
//swap coordinates
var tmp = lower;
lower = upper;
upper = tmp;
tmp = drawLower;
drawLower = drawUpper;
drawUpper = tmp;
tmp = minmax[0];
minmax[0] = minmax[1];
minmax[1] = tmp;
}
// convert to pixels
x = ax[0].p2c(x),
y = ax[1].p2c(y),
upper = ax[e].p2c(upper);
lower = ax[e].p2c(lower);
minmax[0] = ax[e].p2c(minmax[0]);
minmax[1] = ax[e].p2c(minmax[1]);
//same style as points by default
var lw = err[e].lineWidth ? err[e].lineWidth : s.points.lineWidth,
sw = s.points.shadowSize != null ? s.points.shadowSize : s.shadowSize;
//shadow as for points
if (lw > 0 && sw > 0) {
var w = sw / 2;
ctx.lineWidth = w;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, w + w/2, minmax);
ctx.strokeStyle = "rgba(0,0,0,0.2)";
drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, w/2, minmax);
}
ctx.strokeStyle = err[e].color? err[e].color: s.color;
ctx.lineWidth = lw;
//draw it
drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, 0, minmax);
}
}
}
}
function drawError(ctx,err,x,y,upper,lower,drawUpper,drawLower,radius,offset,minmax){
//shadow offset
y += offset;
upper += offset;
lower += offset;
// error bar - avoid plotting over circles
if (err.err == 'x'){
if (upper > x + radius) drawPath(ctx, [[upper,y],[Math.max(x + radius,minmax[0]),y]]);
else drawUpper = false;
if (lower < x - radius) drawPath(ctx, [[Math.min(x - radius,minmax[1]),y],[lower,y]] );
else drawLower = false;
}
else {
if (upper < y - radius) drawPath(ctx, [[x,upper],[x,Math.min(y - radius,minmax[0])]] );
else drawUpper = false;
if (lower > y + radius) drawPath(ctx, [[x,Math.max(y + radius,minmax[1])],[x,lower]] );
else drawLower = false;
}
//internal radius value in errorbar, allows to plot radius 0 points and still keep proper sized caps
//this is a way to get errorbars on lines without visible connecting dots
radius = err.radius != null? err.radius: radius;
// upper cap
if (drawUpper) {
if (err.upperCap == '-'){
if (err.err=='x') drawPath(ctx, [[upper,y - radius],[upper,y + radius]] );
else drawPath(ctx, [[x - radius,upper],[x + radius,upper]] );
} else if ($.isFunction(err.upperCap)){
if (err.err=='x') err.upperCap(ctx, upper, y, radius);
else err.upperCap(ctx, x, upper, radius);
}
}
// lower cap
if (drawLower) {
if (err.lowerCap == '-'){
if (err.err=='x') drawPath(ctx, [[lower,y - radius],[lower,y + radius]] );
else drawPath(ctx, [[x - radius,lower],[x + radius,lower]] );
} else if ($.isFunction(err.lowerCap)){
if (err.err=='x') err.lowerCap(ctx, lower, y, radius);
else err.lowerCap(ctx, x, lower, radius);
}
}
}
function drawPath(ctx, pts){
ctx.beginPath();
ctx.moveTo(pts[0][0], pts[0][1]);
for (var p=1; p < pts.length; p++)
ctx.lineTo(pts[p][0], pts[p][1]);
ctx.stroke();
}
function draw(plot, ctx){
var plotOffset = plot.getPlotOffset();
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
$.each(plot.getData(), function (i, s) {
if (s.points.errorbars && (s.points.xerr.show || s.points.yerr.show))
drawSeriesErrors(plot, ctx, s);
});
ctx.restore();
}
function init(plot) {
plot.hooks.processRawData.push(processRawData);
plot.hooks.draw.push(draw);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'errorbars',
version: '1.0'
});
})(jQuery);

File diff suppressed because one or more lines are too long

View File

@ -24,7 +24,6 @@
// Throw errors
var retrieveDataOject = function (dataObjects, custom) {
var result;
if (typeof dataObjects === 'undefined')
throw new Error('Empty parameter');
@ -76,25 +75,36 @@
* }
*/
if (type === 'csv') {
result = {
head: ['date', 'value','label'],
head: ['timestap', 'date', 'value', 'label'],
data: []
};
dataObject.data.forEach(function (item, index) {
var date = '', value = item[1];
var timestap = item[0];
// Long labels are preferred
if (typeof plot.getOptions().export.labels_long[index] !== 'undefined')
date = plot.getOptions().export.labels_long[index];
else if (typeof labels[index] !== 'undefined')
date = labels[index];
var d = new Date(item[0]);
var monthNames = [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun",
"Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"
];
var clean_label = dataObject.label;
clean_label = clean_label.replace( new RegExp("<.*?>", "g"), "");
clean_label = clean_label.replace( new RegExp(";", "g"), "");
result.data.push([date, value, clean_label]);
date_format = (d.getDate() <10?'0':'') + d.getDate() + " " +
monthNames[d.getMonth()] + " " +
d.getFullYear() + " " +
(d.getHours()<10?'0':'') + d.getHours() + ":" +
(d.getMinutes()<10?'0':'') + d.getMinutes() + ":" +
(d.getSeconds()<10?'0':'') + d.getSeconds();
var date = date_format;
var value = item[1];
var clean_label = plot.getOptions().export.labels_long[dataObject.label];
clean_label = clean_label.replace( new RegExp("&#x20;", "g"), " ");
result.data.push([timestap, date, value, clean_label]);
});
}
/* [
@ -203,10 +213,9 @@
}
catch (e) {
alert('There was an error exporting the data');
console.log(e);
}
}
plot.exportDataJSON = function (args) {
//amount = plot.getOptions().export.type,
//options = options || {};
@ -394,11 +403,10 @@
}
catch (e) {
alert('There was an error exporting the data');
console.log(e);
}
}
}
$.plot.plugins.push({
init: init,
options: options,

View File

@ -0,0 +1,226 @@
/* Flot plugin for computing bottoms for filled line and bar charts.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
The case: you've got two series that you want to fill the area between. In Flot
terms, you need to use one as the fill bottom of the other. You can specify the
bottom of each data point as the third coordinate manually, or you can use this
plugin to compute it for you.
In order to name the other series, you need to give it an id, like this:
var dataset = [
{ data: [ ... ], id: "foo" } , // use default bottom
{ data: [ ... ], fillBetween: "foo" }, // use first dataset as bottom
];
$.plot($("#placeholder"), dataset, { lines: { show: true, fill: true }});
As a convenience, if the id given is a number that doesn't appear as an id in
the series, it is interpreted as the index in the array instead (so fillBetween:
0 can also mean the first series).
Internally, the plugin modifies the datapoints in each series. For line series,
extra data points might be inserted through interpolation. Note that at points
where the bottom line is not defined (due to a null point or start/end of line),
the current line will show a gap too. The algorithm comes from the
jquery.flot.stack.js plugin, possibly some code could be shared.
*/
(function ( $ ) {
var options = {
series: {
fillBetween: null // or number
}
};
function init( plot ) {
function findBottomSeries( s, allseries ) {
var i;
for ( i = 0; i < allseries.length; ++i ) {
if ( allseries[ i ].id === s.fillBetween ) {
return allseries[ i ];
}
}
if ( typeof s.fillBetween === "number" ) {
if ( s.fillBetween < 0 || s.fillBetween >= allseries.length ) {
return null;
}
return allseries[ s.fillBetween ];
}
return null;
}
function computeFillBottoms( plot, s, datapoints ) {
if ( s.fillBetween == null ) {
return;
}
var other = findBottomSeries( s, plot.getData() );
if ( !other ) {
return;
}
var ps = datapoints.pointsize,
points = datapoints.points,
otherps = other.datapoints.pointsize,
otherpoints = other.datapoints.points,
newpoints = [],
px, py, intery, qx, qy, bottom,
withlines = s.lines.show,
withbottom = ps > 2 && datapoints.format[2].y,
withsteps = withlines && s.lines.steps,
fromgap = true,
i = 0,
j = 0,
l, m;
while ( true ) {
if ( i >= points.length ) {
break;
}
l = newpoints.length;
if ( points[ i ] == null ) {
// copy gaps
for ( m = 0; m < ps; ++m ) {
newpoints.push( points[ i + m ] );
}
i += ps;
} else if ( j >= otherpoints.length ) {
// for lines, we can't use the rest of the points
if ( !withlines ) {
for ( m = 0; m < ps; ++m ) {
newpoints.push( points[ i + m ] );
}
}
i += ps;
} else if ( otherpoints[ j ] == null ) {
// oops, got a gap
for ( m = 0; m < ps; ++m ) {
newpoints.push( null );
}
fromgap = true;
j += otherps;
} else {
// cases where we actually got two points
px = points[ i ];
py = points[ i + 1 ];
qx = otherpoints[ j ];
qy = otherpoints[ j + 1 ];
bottom = 0;
if ( px === qx ) {
for ( m = 0; m < ps; ++m ) {
newpoints.push( points[ i + m ] );
}
//newpoints[ l + 1 ] += qy;
bottom = qy;
i += ps;
j += otherps;
} else if ( px > qx ) {
// we got past point below, might need to
// insert interpolated extra point
if ( withlines && i > 0 && points[ i - ps ] != null ) {
intery = py + ( points[ i - ps + 1 ] - py ) * ( qx - px ) / ( points[ i - ps ] - px );
newpoints.push( qx );
newpoints.push( intery );
for ( m = 2; m < ps; ++m ) {
newpoints.push( points[ i + m ] );
}
bottom = qy;
}
j += otherps;
} else { // px < qx
// if we come from a gap, we just skip this point
if ( fromgap && withlines ) {
i += ps;
continue;
}
for ( m = 0; m < ps; ++m ) {
newpoints.push( points[ i + m ] );
}
// we might be able to interpolate a point below,
// this can give us a better y
if ( withlines && j > 0 && otherpoints[ j - otherps ] != null ) {
bottom = qy + ( otherpoints[ j - otherps + 1 ] - qy ) * ( px - qx ) / ( otherpoints[ j - otherps ] - qx );
}
//newpoints[l + 1] += bottom;
i += ps;
}
fromgap = false;
if ( l !== newpoints.length && withbottom ) {
newpoints[ l + 2 ] = bottom;
}
}
// maintain the line steps invariant
if ( withsteps && l !== newpoints.length && l > 0 &&
newpoints[ l ] !== null &&
newpoints[ l ] !== newpoints[ l - ps ] &&
newpoints[ l + 1 ] !== newpoints[ l - ps + 1 ] ) {
for (m = 0; m < ps; ++m) {
newpoints[ l + ps + m ] = newpoints[ l + m ];
}
newpoints[ l + 1 ] = newpoints[ l - ps + 1 ];
}
}
datapoints.points = newpoints;
}
plot.hooks.processDatapoints.push( computeFillBottoms );
}
$.plot.plugins.push({
init: init,
options: options,
name: "fillbetween",
version: "1.0"
});
})(jQuery);

View File

@ -0,0 +1,7 @@
/* Javascript plotting library for jQuery, version 0.8.3.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
*/
(function($){var options={series:{fillBetween:null}};function init(plot){function findBottomSeries(s,allseries){var i;for(i=0;i<allseries.length;++i){if(allseries[i].id===s.fillBetween){return allseries[i]}}if(typeof s.fillBetween==="number"){if(s.fillBetween<0||s.fillBetween>=allseries.length){return null}return allseries[s.fillBetween]}return null}function computeFillBottoms(plot,s,datapoints){if(s.fillBetween==null){return}var other=findBottomSeries(s,plot.getData());if(!other){return}var ps=datapoints.pointsize,points=datapoints.points,otherps=other.datapoints.pointsize,otherpoints=other.datapoints.points,newpoints=[],px,py,intery,qx,qy,bottom,withlines=s.lines.show,withbottom=ps>2&&datapoints.format[2].y,withsteps=withlines&&s.lines.steps,fromgap=true,i=0,j=0,l,m;while(true){if(i>=points.length){break}l=newpoints.length;if(points[i]==null){for(m=0;m<ps;++m){newpoints.push(points[i+m])}i+=ps}else if(j>=otherpoints.length){if(!withlines){for(m=0;m<ps;++m){newpoints.push(points[i+m])}}i+=ps}else if(otherpoints[j]==null){for(m=0;m<ps;++m){newpoints.push(null)}fromgap=true;j+=otherps}else{px=points[i];py=points[i+1];qx=otherpoints[j];qy=otherpoints[j+1];bottom=0;if(px===qx){for(m=0;m<ps;++m){newpoints.push(points[i+m])}bottom=qy;i+=ps;j+=otherps}else if(px>qx){if(withlines&&i>0&&points[i-ps]!=null){intery=py+(points[i-ps+1]-py)*(qx-px)/(points[i-ps]-px);newpoints.push(qx);newpoints.push(intery);for(m=2;m<ps;++m){newpoints.push(points[i+m])}bottom=qy}j+=otherps}else{if(fromgap&&withlines){i+=ps;continue}for(m=0;m<ps;++m){newpoints.push(points[i+m])}if(withlines&&j>0&&otherpoints[j-otherps]!=null){bottom=qy+(otherpoints[j-otherps+1]-qy)*(px-qx)/(otherpoints[j-otherps]-qx)}i+=ps}fromgap=false;if(l!==newpoints.length&&withbottom){newpoints[l+2]=bottom}}if(withsteps&&l!==newpoints.length&&l>0&&newpoints[l]!==null&&newpoints[l]!==newpoints[l-ps]&&newpoints[l+1]!==newpoints[l-ps+1]){for(m=0;m<ps;++m){newpoints[l+ps+m]=newpoints[l+m]}newpoints[l+1]=newpoints[l-ps+1]}}datapoints.points=newpoints}plot.hooks.processDatapoints.push(computeFillBottoms)}$.plot.plugins.push({init:init,options:options,name:"fillbetween",version:"1.0"})})(jQuery);

View File

@ -0,0 +1,241 @@
/* Flot plugin for plotting images.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
The data syntax is [ [ image, x1, y1, x2, y2 ], ... ] where (x1, y1) and
(x2, y2) are where you intend the two opposite corners of the image to end up
in the plot. Image must be a fully loaded Javascript image (you can make one
with new Image()). If the image is not complete, it's skipped when plotting.
There are two helpers included for retrieving images. The easiest work the way
that you put in URLs instead of images in the data, like this:
[ "myimage.png", 0, 0, 10, 10 ]
Then call $.plot.image.loadData( data, options, callback ) where data and
options are the same as you pass in to $.plot. This loads the images, replaces
the URLs in the data with the corresponding images and calls "callback" when
all images are loaded (or failed loading). In the callback, you can then call
$.plot with the data set. See the included example.
A more low-level helper, $.plot.image.load(urls, callback) is also included.
Given a list of URLs, it calls callback with an object mapping from URL to
Image object when all images are loaded or have failed loading.
The plugin supports these options:
series: {
images: {
show: boolean
anchor: "corner" or "center"
alpha: [ 0, 1 ]
}
}
They can be specified for a specific series:
$.plot( $("#placeholder"), [{
data: [ ... ],
images: { ... }
])
Note that because the data format is different from usual data points, you
can't use images with anything else in a specific data series.
Setting "anchor" to "center" causes the pixels in the image to be anchored at
the corner pixel centers inside of at the pixel corners, effectively letting
half a pixel stick out to each side in the plot.
A possible future direction could be support for tiling for large images (like
Google Maps).
*/
(function ($) {
var options = {
series: {
images: {
show: false,
alpha: 1,
anchor: "corner" // or "center"
}
}
};
$.plot.image = {};
$.plot.image.loadDataImages = function (series, options, callback) {
var urls = [], points = [];
var defaultShow = options.series.images.show;
$.each(series, function (i, s) {
if (!(defaultShow || s.images.show))
return;
if (s.data)
s = s.data;
$.each(s, function (i, p) {
if (typeof p[0] == "string") {
urls.push(p[0]);
points.push(p);
}
});
});
$.plot.image.load(urls, function (loadedImages) {
$.each(points, function (i, p) {
var url = p[0];
if (loadedImages[url])
p[0] = loadedImages[url];
});
callback();
});
}
$.plot.image.load = function (urls, callback) {
var missing = urls.length, loaded = {};
if (missing == 0)
callback({});
$.each(urls, function (i, url) {
var handler = function () {
--missing;
loaded[url] = this;
if (missing == 0)
callback(loaded);
};
$('<img />').load(handler).error(handler).attr('src', url);
});
};
function drawSeries(plot, ctx, series) {
var plotOffset = plot.getPlotOffset();
if (!series.images || !series.images.show)
return;
var points = series.datapoints.points,
ps = series.datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
var img = points[i],
x1 = points[i + 1], y1 = points[i + 2],
x2 = points[i + 3], y2 = points[i + 4],
xaxis = series.xaxis, yaxis = series.yaxis,
tmp;
// actually we should check img.complete, but it
// appears to be a somewhat unreliable indicator in
// IE6 (false even after load event)
if (!img || img.width <= 0 || img.height <= 0)
continue;
if (x1 > x2) {
tmp = x2;
x2 = x1;
x1 = tmp;
}
if (y1 > y2) {
tmp = y2;
y2 = y1;
y1 = tmp;
}
// if the anchor is at the center of the pixel, expand the
// image by 1/2 pixel in each direction
if (series.images.anchor == "center") {
tmp = 0.5 * (x2-x1) / (img.width - 1);
x1 -= tmp;
x2 += tmp;
tmp = 0.5 * (y2-y1) / (img.height - 1);
y1 -= tmp;
y2 += tmp;
}
// clip
if (x1 == x2 || y1 == y2 ||
x1 >= xaxis.max || x2 <= xaxis.min ||
y1 >= yaxis.max || y2 <= yaxis.min)
continue;
var sx1 = 0, sy1 = 0, sx2 = img.width, sy2 = img.height;
if (x1 < xaxis.min) {
sx1 += (sx2 - sx1) * (xaxis.min - x1) / (x2 - x1);
x1 = xaxis.min;
}
if (x2 > xaxis.max) {
sx2 += (sx2 - sx1) * (xaxis.max - x2) / (x2 - x1);
x2 = xaxis.max;
}
if (y1 < yaxis.min) {
sy2 += (sy1 - sy2) * (yaxis.min - y1) / (y2 - y1);
y1 = yaxis.min;
}
if (y2 > yaxis.max) {
sy1 += (sy1 - sy2) * (yaxis.max - y2) / (y2 - y1);
y2 = yaxis.max;
}
x1 = xaxis.p2c(x1);
x2 = xaxis.p2c(x2);
y1 = yaxis.p2c(y1);
y2 = yaxis.p2c(y2);
// the transformation may have swapped us
if (x1 > x2) {
tmp = x2;
x2 = x1;
x1 = tmp;
}
if (y1 > y2) {
tmp = y2;
y2 = y1;
y1 = tmp;
}
tmp = ctx.globalAlpha;
ctx.globalAlpha *= series.images.alpha;
ctx.drawImage(img,
sx1, sy1, sx2 - sx1, sy2 - sy1,
x1 + plotOffset.left, y1 + plotOffset.top,
x2 - x1, y2 - y1);
ctx.globalAlpha = tmp;
}
}
function processRawData(plot, series, data, datapoints) {
if (!series.images.show)
return;
// format is Image, x1, y1, x2, y2 (opposite corners)
datapoints.format = [
{ required: true },
{ x: true, number: true, required: true },
{ y: true, number: true, required: true },
{ x: true, number: true, required: true },
{ y: true, number: true, required: true }
];
}
function init(plot) {
plot.hooks.processRawData.push(processRawData);
plot.hooks.drawSeries.push(drawSeries);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'image',
version: '1.1'
});
})(jQuery);

View File

@ -0,0 +1,7 @@
/* Javascript plotting library for jQuery, version 0.8.3.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
*/
(function($){var options={series:{images:{show:false,alpha:1,anchor:"corner"}}};$.plot.image={};$.plot.image.loadDataImages=function(series,options,callback){var urls=[],points=[];var defaultShow=options.series.images.show;$.each(series,function(i,s){if(!(defaultShow||s.images.show))return;if(s.data)s=s.data;$.each(s,function(i,p){if(typeof p[0]=="string"){urls.push(p[0]);points.push(p)}})});$.plot.image.load(urls,function(loadedImages){$.each(points,function(i,p){var url=p[0];if(loadedImages[url])p[0]=loadedImages[url]});callback()})};$.plot.image.load=function(urls,callback){var missing=urls.length,loaded={};if(missing==0)callback({});$.each(urls,function(i,url){var handler=function(){--missing;loaded[url]=this;if(missing==0)callback(loaded)};$("<img />").load(handler).error(handler).attr("src",url)})};function drawSeries(plot,ctx,series){var plotOffset=plot.getPlotOffset();if(!series.images||!series.images.show)return;var points=series.datapoints.points,ps=series.datapoints.pointsize;for(var i=0;i<points.length;i+=ps){var img=points[i],x1=points[i+1],y1=points[i+2],x2=points[i+3],y2=points[i+4],xaxis=series.xaxis,yaxis=series.yaxis,tmp;if(!img||img.width<=0||img.height<=0)continue;if(x1>x2){tmp=x2;x2=x1;x1=tmp}if(y1>y2){tmp=y2;y2=y1;y1=tmp}if(series.images.anchor=="center"){tmp=.5*(x2-x1)/(img.width-1);x1-=tmp;x2+=tmp;tmp=.5*(y2-y1)/(img.height-1);y1-=tmp;y2+=tmp}if(x1==x2||y1==y2||x1>=xaxis.max||x2<=xaxis.min||y1>=yaxis.max||y2<=yaxis.min)continue;var sx1=0,sy1=0,sx2=img.width,sy2=img.height;if(x1<xaxis.min){sx1+=(sx2-sx1)*(xaxis.min-x1)/(x2-x1);x1=xaxis.min}if(x2>xaxis.max){sx2+=(sx2-sx1)*(xaxis.max-x2)/(x2-x1);x2=xaxis.max}if(y1<yaxis.min){sy2+=(sy1-sy2)*(yaxis.min-y1)/(y2-y1);y1=yaxis.min}if(y2>yaxis.max){sy1+=(sy1-sy2)*(yaxis.max-y2)/(y2-y1);y2=yaxis.max}x1=xaxis.p2c(x1);x2=xaxis.p2c(x2);y1=yaxis.p2c(y1);y2=yaxis.p2c(y2);if(x1>x2){tmp=x2;x2=x1;x1=tmp}if(y1>y2){tmp=y2;y2=y1;y1=tmp}tmp=ctx.globalAlpha;ctx.globalAlpha*=series.images.alpha;ctx.drawImage(img,sx1,sy1,sx2-sx1,sy2-sy1,x1+plotOffset.left,y1+plotOffset.top,x2-x1,y2-y1);ctx.globalAlpha=tmp}}function processRawData(plot,series,data,datapoints){if(!series.images.show)return;datapoints.format=[{required:true},{x:true,number:true,required:true},{y:true,number:true,required:true},{x:true,number:true,required:true},{y:true,number:true,required:true}]}function init(plot){plot.hooks.processRawData.push(processRawData);plot.hooks.drawSeries.push(drawSeries)}$.plot.plugins.push({init:init,options:options,name:"image",version:"1.1"})})(jQuery);

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,346 @@
/* Flot plugin for adding the ability to pan and zoom the plot.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
The default behaviour is double click and scrollwheel up/down to zoom in, drag
to pan. The plugin defines plot.zoom({ center }), plot.zoomOut() and
plot.pan( offset ) so you easily can add custom controls. It also fires
"plotpan" and "plotzoom" events, useful for synchronizing plots.
The plugin supports these options:
zoom: {
interactive: false
trigger: "dblclick" // or "click" for single click
amount: 1.5 // 2 = 200% (zoom in), 0.5 = 50% (zoom out)
}
pan: {
interactive: false
cursor: "move" // CSS mouse cursor value used when dragging, e.g. "pointer"
frameRate: 20
}
xaxis, yaxis, x2axis, y2axis: {
zoomRange: null // or [ number, number ] (min range, max range) or false
panRange: null // or [ number, number ] (min, max) or false
}
"interactive" enables the built-in drag/click behaviour. If you enable
interactive for pan, then you'll have a basic plot that supports moving
around; the same for zoom.
"amount" specifies the default amount to zoom in (so 1.5 = 150%) relative to
the current viewport.
"cursor" is a standard CSS mouse cursor string used for visual feedback to the
user when dragging.
"frameRate" specifies the maximum number of times per second the plot will
update itself while the user is panning around on it (set to null to disable
intermediate pans, the plot will then not update until the mouse button is
released).
"zoomRange" is the interval in which zooming can happen, e.g. with zoomRange:
[1, 100] the zoom will never scale the axis so that the difference between min
and max is smaller than 1 or larger than 100. You can set either end to null
to ignore, e.g. [1, null]. If you set zoomRange to false, zooming on that axis
will be disabled.
"panRange" confines the panning to stay within a range, e.g. with panRange:
[-10, 20] panning stops at -10 in one end and at 20 in the other. Either can
be null, e.g. [-10, null]. If you set panRange to false, panning on that axis
will be disabled.
Example API usage:
plot = $.plot(...);
// zoom default amount in on the pixel ( 10, 20 )
plot.zoom({ center: { left: 10, top: 20 } });
// zoom out again
plot.zoomOut({ center: { left: 10, top: 20 } });
// zoom 200% in on the pixel (10, 20)
plot.zoom({ amount: 2, center: { left: 10, top: 20 } });
// pan 100 pixels to the left and 20 down
plot.pan({ left: -100, top: 20 })
Here, "center" specifies where the center of the zooming should happen. Note
that this is defined in pixel space, not the space of the data points (you can
use the p2c helpers on the axes in Flot to help you convert between these).
"amount" is the amount to zoom the viewport relative to the current range, so
1 is 100% (i.e. no change), 1.5 is 150% (zoom in), 0.7 is 70% (zoom out). You
can set the default in the options.
*/
// First two dependencies, jquery.event.drag.js and
// jquery.mousewheel.js, we put them inline here to save people the
// effort of downloading them.
/*
jquery.event.drag.js ~ v1.5 ~ Copyright (c) 2008, Three Dub Media (http://threedubmedia.com)
Licensed under the MIT License ~ http://threedubmedia.googlecode.com/files/MIT-LICENSE.txt
*/
(function(a){function e(h){var k,j=this,l=h.data||{};if(l.elem)j=h.dragTarget=l.elem,h.dragProxy=d.proxy||j,h.cursorOffsetX=l.pageX-l.left,h.cursorOffsetY=l.pageY-l.top,h.offsetX=h.pageX-h.cursorOffsetX,h.offsetY=h.pageY-h.cursorOffsetY;else if(d.dragging||l.which>0&&h.which!=l.which||a(h.target).is(l.not))return;switch(h.type){case"mousedown":return a.extend(l,a(j).offset(),{elem:j,target:h.target,pageX:h.pageX,pageY:h.pageY}),b.add(document,"mousemove mouseup",e,l),i(j,!1),d.dragging=null,!1;case!d.dragging&&"mousemove":if(g(h.pageX-l.pageX)+g(h.pageY-l.pageY)<l.distance)break;h.target=l.target,k=f(h,"dragstart",j),k!==!1&&(d.dragging=j,d.proxy=h.dragProxy=a(k||j)[0]);case"mousemove":if(d.dragging){if(k=f(h,"drag",j),c.drop&&(c.drop.allowed=k!==!1,c.drop.handler(h)),k!==!1)break;h.type="mouseup"}case"mouseup":b.remove(document,"mousemove mouseup",e),d.dragging&&(c.drop&&c.drop.handler(h),f(h,"dragend",j)),i(j,!0),d.dragging=d.proxy=l.elem=!1}return!0}function f(b,c,d){b.type=c;var e=a.event.dispatch.call(d,b);return e===!1?!1:e||b.result}function g(a){return Math.pow(a,2)}function h(){return d.dragging===!1}function i(a,b){a&&(a.unselectable=b?"off":"on",a.onselectstart=function(){return b},a.style&&(a.style.MozUserSelect=b?"":"none"))}a.fn.drag=function(a,b,c){return b&&this.bind("dragstart",a),c&&this.bind("dragend",c),a?this.bind("drag",b?b:a):this.trigger("drag")};var b=a.event,c=b.special,d=c.drag={not:":input",distance:0,which:1,dragging:!1,setup:function(c){c=a.extend({distance:d.distance,which:d.which,not:d.not},c||{}),c.distance=g(c.distance),b.add(this,"mousedown",e,c),this.attachEvent&&this.attachEvent("ondragstart",h)},teardown:function(){b.remove(this,"mousedown",e),this===d.dragging&&(d.dragging=d.proxy=!1),i(this,!0),this.detachEvent&&this.detachEvent("ondragstart",h)}};c.dragstart=c.dragend={setup:function(){},teardown:function(){}}})(jQuery);
/* jquery.mousewheel.min.js
* Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.6
*
* Requires: 1.2.2+
*/
(function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;void 0!==b.axis&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);void 0!==b.wheelDeltaY&&(g=b.wheelDeltaY/120);void 0!==b.wheelDeltaX&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]=d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,!1);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,!1);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);
(function ($) {
var options = {
xaxis: {
zoomRange: null, // or [number, number] (min range, max range)
panRange: null // or [number, number] (min, max)
},
zoom: {
interactive: false,
trigger: "dblclick", // or "click" for single click
amount: 1.5 // how much to zoom relative to current position, 2 = 200% (zoom in), 0.5 = 50% (zoom out)
},
pan: {
interactive: false,
cursor: "move",
frameRate: 20
}
};
function init(plot) {
function onZoomClick(e, zoomOut) {
var c = plot.offset();
c.left = e.pageX - c.left;
c.top = e.pageY - c.top;
if (zoomOut)
plot.zoomOut({ center: c });
else
plot.zoom({ center: c });
}
function onMouseWheel(e, delta) {
e.preventDefault();
onZoomClick(e, delta < 0);
return false;
}
var prevCursor = 'default', prevPageX = 0, prevPageY = 0,
panTimeout = null;
function onDragStart(e) {
if (e.which != 1) // only accept left-click
return false;
var c = plot.getPlaceholder().css('cursor');
if (c)
prevCursor = c;
plot.getPlaceholder().css('cursor', plot.getOptions().pan.cursor);
prevPageX = e.pageX;
prevPageY = e.pageY;
}
function onDrag(e) {
var frameRate = plot.getOptions().pan.frameRate;
if (panTimeout || !frameRate)
return;
panTimeout = setTimeout(function () {
plot.pan({ left: prevPageX - e.pageX,
top: prevPageY - e.pageY });
prevPageX = e.pageX;
prevPageY = e.pageY;
panTimeout = null;
}, 1 / frameRate * 1000);
}
function onDragEnd(e) {
if (panTimeout) {
clearTimeout(panTimeout);
panTimeout = null;
}
plot.getPlaceholder().css('cursor', prevCursor);
plot.pan({ left: prevPageX - e.pageX,
top: prevPageY - e.pageY });
}
function bindEvents(plot, eventHolder) {
var o = plot.getOptions();
if (o.zoom.interactive) {
eventHolder[o.zoom.trigger](onZoomClick);
eventHolder.mousewheel(onMouseWheel);
}
if (o.pan.interactive) {
eventHolder.bind("dragstart", { distance: 10 }, onDragStart);
eventHolder.bind("drag", onDrag);
eventHolder.bind("dragend", onDragEnd);
}
}
plot.zoomOut = function (args) {
if (!args)
args = {};
if (!args.amount)
args.amount = plot.getOptions().zoom.amount;
args.amount = 1 / args.amount;
plot.zoom(args);
};
plot.zoom = function (args) {
if (!args)
args = {};
var c = args.center,
amount = args.amount || plot.getOptions().zoom.amount,
w = plot.width(), h = plot.height();
if (!c)
c = { left: w / 2, top: h / 2 };
var xf = c.left / w,
yf = c.top / h,
minmax = {
x: {
min: c.left - xf * w / amount,
max: c.left + (1 - xf) * w / amount
},
y: {
min: c.top - yf * h / amount,
max: c.top + (1 - yf) * h / amount
}
};
$.each(plot.getAxes(), function(_, axis) {
var opts = axis.options,
min = minmax[axis.direction].min,
max = minmax[axis.direction].max,
zr = opts.zoomRange,
pr = opts.panRange;
if (zr === false) // no zooming on this axis
return;
min = axis.c2p(min);
max = axis.c2p(max);
if (min > max) {
// make sure min < max
var tmp = min;
min = max;
max = tmp;
}
//Check that we are in panRange
if (pr) {
if (pr[0] != null && min < pr[0]) {
min = pr[0];
}
if (pr[1] != null && max > pr[1]) {
max = pr[1];
}
}
var range = max - min;
if (zr &&
((zr[0] != null && range < zr[0] && amount >1) ||
(zr[1] != null && range > zr[1] && amount <1)))
return;
opts.min = min;
opts.max = max;
});
plot.setupGrid();
plot.draw();
if (!args.preventEvent)
plot.getPlaceholder().trigger("plotzoom", [ plot, args ]);
};
plot.pan = function (args) {
var delta = {
x: +args.left,
y: +args.top
};
if (isNaN(delta.x))
delta.x = 0;
if (isNaN(delta.y))
delta.y = 0;
$.each(plot.getAxes(), function (_, axis) {
var opts = axis.options,
min, max, d = delta[axis.direction];
min = axis.c2p(axis.p2c(axis.min) + d),
max = axis.c2p(axis.p2c(axis.max) + d);
var pr = opts.panRange;
if (pr === false) // no panning on this axis
return;
if (pr) {
// check whether we hit the wall
if (pr[0] != null && pr[0] > min) {
d = pr[0] - min;
min += d;
max += d;
}
if (pr[1] != null && pr[1] < max) {
d = pr[1] - max;
min += d;
max += d;
}
}
opts.min = min;
opts.max = max;
});
plot.setupGrid();
plot.draw();
if (!args.preventEvent)
plot.getPlaceholder().trigger("plotpan", [ plot, args ]);
};
function shutdown(plot, eventHolder) {
eventHolder.unbind(plot.getOptions().zoom.trigger, onZoomClick);
eventHolder.unbind("mousewheel", onMouseWheel);
eventHolder.unbind("dragstart", onDragStart);
eventHolder.unbind("drag", onDrag);
eventHolder.unbind("dragend", onDragEnd);
if (panTimeout)
clearTimeout(panTimeout);
}
plot.hooks.bindEvents.push(bindEvents);
plot.hooks.shutdown.push(shutdown);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'navigate',
version: '1.3'
});
})(jQuery);

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,59 @@
/* Flot plugin for automatically redrawing plots as the placeholder resizes.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
It works by listening for changes on the placeholder div (through the jQuery
resize event plugin) - if the size changes, it will redraw the plot.
There are no options. If you need to disable the plugin for some plots, you
can just fix the size of their placeholders.
*/
/* Inline dependency:
* jQuery resize event - v1.1 - 3/14/2010
* http://benalman.com/projects/jquery-resize-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($,e,t){"$:nomunge";var i=[],n=$.resize=$.extend($.resize,{}),a,r=false,s="setTimeout",u="resize",m=u+"-special-event",o="pendingDelay",l="activeDelay",f="throttleWindow";n[o]=200;n[l]=20;n[f]=true;$.event.special[u]={setup:function(){if(!n[f]&&this[s]){return false}var e=$(this);i.push(this);e.data(m,{w:e.width(),h:e.height()});if(i.length===1){a=t;h()}},teardown:function(){if(!n[f]&&this[s]){return false}var e=$(this);for(var t=i.length-1;t>=0;t--){if(i[t]==this){i.splice(t,1);break}}e.removeData(m);if(!i.length){if(r){cancelAnimationFrame(a)}else{clearTimeout(a)}a=null}},add:function(e){if(!n[f]&&this[s]){return false}var i;function a(e,n,a){var r=$(this),s=r.data(m)||{};s.w=n!==t?n:r.width();s.h=a!==t?a:r.height();i.apply(this,arguments)}if($.isFunction(e)){i=e;return a}else{i=e.handler;e.handler=a}}};function h(t){if(r===true){r=t||1}for(var s=i.length-1;s>=0;s--){var l=$(i[s]);if(l[0]==e||l.is(":visible")){var f=l.width(),c=l.height(),d=l.data(m);if(d&&(f!==d.w||c!==d.h)){l.trigger(u,[d.w=f,d.h=c]);r=t||true}}else{d=l.data(m);d.w=0;d.h=0}}if(a!==null){if(r&&(t==null||t-r<1e3)){a=e.requestAnimationFrame(h)}else{a=setTimeout(h,n[o]);r=false}}}if(!e.requestAnimationFrame){e.requestAnimationFrame=function(){return e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(t,i){return e.setTimeout(function(){t((new Date).getTime())},n[l])}}()}if(!e.cancelAnimationFrame){e.cancelAnimationFrame=function(){return e.webkitCancelRequestAnimationFrame||e.mozCancelRequestAnimationFrame||e.oCancelRequestAnimationFrame||e.msCancelRequestAnimationFrame||clearTimeout}()}})(jQuery,this);
(function ($) {
var options = { }; // no options
function init(plot) {
function onResize() {
var placeholder = plot.getPlaceholder();
// somebody might have hidden us and we can't plot
// when we don't have the dimensions
if (placeholder.width() == 0 || placeholder.height() == 0)
return;
plot.resize();
plot.setupGrid();
plot.draw();
}
function bindEvents(plot, eventHolder) {
plot.getPlaceholder().resize(onResize);
}
function shutdown(plot, eventHolder) {
plot.getPlaceholder().unbind("resize", onResize);
}
plot.hooks.bindEvents.push(bindEvents);
plot.hooks.shutdown.push(shutdown);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'resize',
version: '1.0'
});
})(jQuery);

View File

@ -1 +1,7 @@
(function(n,p,u){var w=n([]),s=n.resize=n.extend(n.resize,{}),o,l="setTimeout",m="resize",t=m+"-special-event",v="delay",r="throttleWindow";s[v]=250;s[r]=true;n.event.special[m]={setup:function(){if(!s[r]&&this[l]){return false}var a=n(this);w=w.add(a);n.data(this,t,{w:a.width(),h:a.height()});if(w.length===1){q()}},teardown:function(){if(!s[r]&&this[l]){return false}var a=n(this);w=w.not(a);a.removeData(t);if(!w.length){clearTimeout(o)}},add:function(b){if(!s[r]&&this[l]){return false}var c;function a(d,h,g){var f=n(this),e=n.data(this,t);e.w=h!==u?h:f.width();e.h=g!==u?g:f.height();c.apply(this,arguments)}if(n.isFunction(b)){c=b;return a}else{c=b.handler;b.handler=a}}};function q(){o=p[l](function(){w.each(function(){var d=n(this),a=d.width(),b=d.height(),c=n.data(this,t);if(a!==c.w||b!==c.h){d.trigger(m,[c.w=a,c.h=b])}});q()},s[v])}})(jQuery,this);(function(b){var a={};function c(f){function e(){var h=f.getPlaceholder();if(h.width()==0||h.height()==0){return}f.resize();f.setupGrid();f.draw()}function g(i,h){i.getPlaceholder().resize(e)}function d(i,h){i.getPlaceholder().unbind("resize",e)}f.hooks.bindEvents.push(g);f.hooks.shutdown.push(d)}b.plot.plugins.push({init:c,options:a,name:"resize",version:"1.0"})})(jQuery);
/* Javascript plotting library for jQuery, version 0.8.3.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
*/
(function($,e,t){"$:nomunge";var i=[],n=$.resize=$.extend($.resize,{}),a,r=false,s="setTimeout",u="resize",m=u+"-special-event",o="pendingDelay",l="activeDelay",f="throttleWindow";n[o]=200;n[l]=20;n[f]=true;$.event.special[u]={setup:function(){if(!n[f]&&this[s]){return false}var e=$(this);i.push(this);e.data(m,{w:e.width(),h:e.height()});if(i.length===1){a=t;h()}},teardown:function(){if(!n[f]&&this[s]){return false}var e=$(this);for(var t=i.length-1;t>=0;t--){if(i[t]==this){i.splice(t,1);break}}e.removeData(m);if(!i.length){if(r){cancelAnimationFrame(a)}else{clearTimeout(a)}a=null}},add:function(e){if(!n[f]&&this[s]){return false}var i;function a(e,n,a){var r=$(this),s=r.data(m)||{};s.w=n!==t?n:r.width();s.h=a!==t?a:r.height();i.apply(this,arguments)}if($.isFunction(e)){i=e;return a}else{i=e.handler;e.handler=a}}};function h(t){if(r===true){r=t||1}for(var s=i.length-1;s>=0;s--){var l=$(i[s]);if(l[0]==e||l.is(":visible")){var f=l.width(),c=l.height(),d=l.data(m);if(d&&(f!==d.w||c!==d.h)){l.trigger(u,[d.w=f,d.h=c]);r=t||true}}else{d=l.data(m);d.w=0;d.h=0}}if(a!==null){if(r&&(t==null||t-r<1e3)){a=e.requestAnimationFrame(h)}else{a=setTimeout(h,n[o]);r=false}}}if(!e.requestAnimationFrame){e.requestAnimationFrame=function(){return e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(t,i){return e.setTimeout(function(){t((new Date).getTime())},n[l])}}()}if(!e.cancelAnimationFrame){e.cancelAnimationFrame=function(){return e.webkitCancelRequestAnimationFrame||e.mozCancelRequestAnimationFrame||e.oCancelRequestAnimationFrame||e.msCancelRequestAnimationFrame||clearTimeout}()}})(jQuery,this);(function($){var options={};function init(plot){function onResize(){var placeholder=plot.getPlaceholder();if(placeholder.width()==0||placeholder.height()==0)return;plot.resize();plot.setupGrid();plot.draw()}function bindEvents(plot,eventHolder){plot.getPlaceholder().resize(onResize)}function shutdown(plot,eventHolder){plot.getPlaceholder().unbind("resize",onResize)}plot.hooks.bindEvents.push(bindEvents);plot.hooks.shutdown.push(shutdown)}$.plot.plugins.push({init:init,options:options,name:"resize",version:"1.0"})})(jQuery);

View File

@ -0,0 +1,360 @@
/* Flot plugin for selecting regions of a plot.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
The plugin supports these options:
selection: {
mode: null or "x" or "y" or "xy",
color: color,
shape: "round" or "miter" or "bevel",
minSize: number of pixels
}
Selection support is enabled by setting the mode to one of "x", "y" or "xy".
In "x" mode, the user will only be able to specify the x range, similarly for
"y" mode. For "xy", the selection becomes a rectangle where both ranges can be
specified. "color" is color of the selection (if you need to change the color
later on, you can get to it with plot.getOptions().selection.color). "shape"
is the shape of the corners of the selection.
"minSize" is the minimum size a selection can be in pixels. This value can
be customized to determine the smallest size a selection can be and still
have the selection rectangle be displayed. When customizing this value, the
fact that it refers to pixels, not axis units must be taken into account.
Thus, for example, if there is a bar graph in time mode with BarWidth set to 1
minute, setting "minSize" to 1 will not make the minimum selection size 1
minute, but rather 1 pixel. Note also that setting "minSize" to 0 will prevent
"plotunselected" events from being fired when the user clicks the mouse without
dragging.
When selection support is enabled, a "plotselected" event will be emitted on
the DOM element you passed into the plot function. The event handler gets a
parameter with the ranges selected on the axes, like this:
placeholder.bind( "plotselected", function( event, ranges ) {
alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to)
// similar for yaxis - with multiple axes, the extra ones are in
// x2axis, x3axis, ...
});
The "plotselected" event is only fired when the user has finished making the
selection. A "plotselecting" event is fired during the process with the same
parameters as the "plotselected" event, in case you want to know what's
happening while it's happening,
A "plotunselected" event with no arguments is emitted when the user clicks the
mouse to remove the selection. As stated above, setting "minSize" to 0 will
destroy this behavior.
The plugin allso adds the following methods to the plot object:
- setSelection( ranges, preventEvent )
Set the selection rectangle. The passed in ranges is on the same form as
returned in the "plotselected" event. If the selection mode is "x", you
should put in either an xaxis range, if the mode is "y" you need to put in
an yaxis range and both xaxis and yaxis if the selection mode is "xy", like
this:
setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } });
setSelection will trigger the "plotselected" event when called. If you don't
want that to happen, e.g. if you're inside a "plotselected" handler, pass
true as the second parameter. If you are using multiple axes, you can
specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of
xaxis, the plugin picks the first one it sees.
- clearSelection( preventEvent )
Clear the selection rectangle. Pass in true to avoid getting a
"plotunselected" event.
- getSelection()
Returns the current selection in the same format as the "plotselected"
event. If there's currently no selection, the function returns null.
*/
(function ($) {
function init(plot) {
var selection = {
first: { x: -1, y: -1}, second: { x: -1, y: -1},
show: false,
active: false
};
// FIXME: The drag handling implemented here should be
// abstracted out, there's some similar code from a library in
// the navigation plugin, this should be massaged a bit to fit
// the Flot cases here better and reused. Doing this would
// make this plugin much slimmer.
var savedhandlers = {};
var mouseUpHandler = null;
function onMouseMove(e) {
if (selection.active) {
updateSelection(e);
plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]);
}
}
function onMouseDown(e) {
if (e.which != 1) // only accept left-click
return;
// cancel out any text selections
document.body.focus();
// prevent text selection and drag in old-school browsers
if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) {
savedhandlers.onselectstart = document.onselectstart;
document.onselectstart = function () { return false; };
}
if (document.ondrag !== undefined && savedhandlers.ondrag == null) {
savedhandlers.ondrag = document.ondrag;
document.ondrag = function () { return false; };
}
setSelectionPos(selection.first, e);
selection.active = true;
// this is a bit silly, but we have to use a closure to be
// able to whack the same handler again
mouseUpHandler = function (e) { onMouseUp(e); };
$(document).one("mouseup", mouseUpHandler);
}
function onMouseUp(e) {
mouseUpHandler = null;
// revert drag stuff for old-school browsers
if (document.onselectstart !== undefined)
document.onselectstart = savedhandlers.onselectstart;
if (document.ondrag !== undefined)
document.ondrag = savedhandlers.ondrag;
// no more dragging
selection.active = false;
updateSelection(e);
if (selectionIsSane())
triggerSelectedEvent();
else {
// this counts as a clear
plot.getPlaceholder().trigger("plotunselected", [ ]);
plot.getPlaceholder().trigger("plotselecting", [ null ]);
}
return false;
}
function getSelection() {
if (!selectionIsSane())
return null;
if (!selection.show) return null;
var r = {}, c1 = selection.first, c2 = selection.second;
$.each(plot.getAxes(), function (name, axis) {
if (axis.used) {
var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]);
r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) };
}
});
return r;
}
function triggerSelectedEvent() {
var r = getSelection();
plot.getPlaceholder().trigger("plotselected", [ r ]);
// backwards-compat stuff, to be removed in future
if (r.xaxis && r.yaxis)
plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]);
}
function clamp(min, value, max) {
return value < min ? min: (value > max ? max: value);
}
function setSelectionPos(pos, e) {
var o = plot.getOptions();
var offset = plot.getPlaceholder().offset();
var plotOffset = plot.getPlotOffset();
pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width());
pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height());
if (o.selection.mode == "y")
pos.x = pos == selection.first ? 0 : plot.width();
if (o.selection.mode == "x")
pos.y = pos == selection.first ? 0 : plot.height();
}
function updateSelection(pos) {
if (pos.pageX == null)
return;
setSelectionPos(selection.second, pos);
if (selectionIsSane()) {
selection.show = true;
plot.triggerRedrawOverlay();
}
else
clearSelection(true);
}
function clearSelection(preventEvent) {
if (selection.show) {
selection.show = false;
plot.triggerRedrawOverlay();
if (!preventEvent)
plot.getPlaceholder().trigger("plotunselected", [ ]);
}
}
// function taken from markings support in Flot
function extractRange(ranges, coord) {
var axis, from, to, key, axes = plot.getAxes();
for (var k in axes) {
axis = axes[k];
if (axis.direction == coord) {
key = coord + axis.n + "axis";
if (!ranges[key] && axis.n == 1)
key = coord + "axis"; // support x1axis as xaxis
if (ranges[key]) {
from = ranges[key].from;
to = ranges[key].to;
break;
}
}
}
// backwards-compat stuff - to be removed in future
if (!ranges[key]) {
axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0];
from = ranges[coord + "1"];
to = ranges[coord + "2"];
}
// auto-reverse as an added bonus
if (from != null && to != null && from > to) {
var tmp = from;
from = to;
to = tmp;
}
return { from: from, to: to, axis: axis };
}
function setSelection(ranges, preventEvent) {
var axis, range, o = plot.getOptions();
if (o.selection.mode == "y") {
selection.first.x = 0;
selection.second.x = plot.width();
}
else {
range = extractRange(ranges, "x");
selection.first.x = range.axis.p2c(range.from);
selection.second.x = range.axis.p2c(range.to);
}
if (o.selection.mode == "x") {
selection.first.y = 0;
selection.second.y = plot.height();
}
else {
range = extractRange(ranges, "y");
selection.first.y = range.axis.p2c(range.from);
selection.second.y = range.axis.p2c(range.to);
}
selection.show = true;
plot.triggerRedrawOverlay();
if (!preventEvent && selectionIsSane())
triggerSelectedEvent();
}
function selectionIsSane() {
var minSize = plot.getOptions().selection.minSize;
return Math.abs(selection.second.x - selection.first.x) >= minSize &&
Math.abs(selection.second.y - selection.first.y) >= minSize;
}
plot.clearSelection = clearSelection;
plot.setSelection = setSelection;
plot.getSelection = getSelection;
plot.hooks.bindEvents.push(function(plot, eventHolder) {
var o = plot.getOptions();
if (o.selection.mode != null) {
eventHolder.mousemove(onMouseMove);
eventHolder.mousedown(onMouseDown);
}
});
plot.hooks.drawOverlay.push(function (plot, ctx) {
// draw selection
if (selection.show && selectionIsSane()) {
var plotOffset = plot.getPlotOffset();
var o = plot.getOptions();
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
var c = $.color.parse(o.selection.color);
ctx.strokeStyle = c.scale('a', 0.8).toString();
ctx.lineWidth = 1;
ctx.lineJoin = o.selection.shape;
ctx.fillStyle = c.scale('a', 0.4).toString();
var x = Math.min(selection.first.x, selection.second.x) + 0.5,
y = Math.min(selection.first.y, selection.second.y) + 0.5,
w = Math.abs(selection.second.x - selection.first.x) - 1,
h = Math.abs(selection.second.y - selection.first.y) - 1;
ctx.fillRect(x, y, w, h);
ctx.strokeRect(x, y, w, h);
ctx.restore();
}
});
plot.hooks.shutdown.push(function (plot, eventHolder) {
eventHolder.unbind("mousemove", onMouseMove);
eventHolder.unbind("mousedown", onMouseDown);
if (mouseUpHandler)
$(document).unbind("mouseup", mouseUpHandler);
});
}
$.plot.plugins.push({
init: init,
options: {
selection: {
mode: null, // one of null, "x", "y" or "xy"
color: "#e8cfac",
shape: "round", // one of "round", "miter", or "bevel"
minSize: 5 // minimum number of pixels
}
},
name: 'selection',
version: '1.1'
});
})(jQuery);

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,188 @@
/* Flot plugin for stacking data sets rather than overlyaing them.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
The plugin assumes the data is sorted on x (or y if stacking horizontally).
For line charts, it is assumed that if a line has an undefined gap (from a
null point), then the line above it should have the same gap - insert zeros
instead of "null" if you want another behaviour. This also holds for the start
and end of the chart. Note that stacking a mix of positive and negative values
in most instances doesn't make sense (so it looks weird).
Two or more series are stacked when their "stack" attribute is set to the same
key (which can be any number or string or just "true"). To specify the default
stack, you can set the stack option like this:
series: {
stack: null/false, true, or a key (number/string)
}
You can also specify it for a single series, like this:
$.plot( $("#placeholder"), [{
data: [ ... ],
stack: true
}])
The stacking order is determined by the order of the data series in the array
(later series end up on top of the previous).
Internally, the plugin modifies the datapoints in each series, adding an
offset to the y value. For line series, extra data points are inserted through
interpolation. If there's a second y value, it's also adjusted (e.g for bar
charts or filled areas).
*/
(function ($) {
var options = {
series: { stack: null } // or number/string
};
function init(plot) {
function findMatchingSeries(s, allseries) {
var res = null;
for (var i = 0; i < allseries.length; ++i) {
if (s == allseries[i])
break;
if (allseries[i].stack == s.stack)
res = allseries[i];
}
return res;
}
function stackData(plot, s, datapoints) {
if (s.stack == null || s.stack === false)
return;
var other = findMatchingSeries(s, plot.getData());
if (!other)
return;
var ps = datapoints.pointsize,
points = datapoints.points,
otherps = other.datapoints.pointsize,
otherpoints = other.datapoints.points,
newpoints = [],
px, py, intery, qx, qy, bottom,
withlines = s.lines.show,
horizontal = s.bars.horizontal,
withbottom = ps > 2 && (horizontal ? datapoints.format[2].x : datapoints.format[2].y),
withsteps = withlines && s.lines.steps,
fromgap = true,
keyOffset = horizontal ? 1 : 0,
accumulateOffset = horizontal ? 0 : 1,
i = 0, j = 0, l, m;
while (true) {
if (i >= points.length)
break;
l = newpoints.length;
if (points[i] == null) {
// copy gaps
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
i += ps;
}
else if (j >= otherpoints.length) {
// for lines, we can't use the rest of the points
if (!withlines) {
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
}
i += ps;
}
else if (otherpoints[j] == null) {
// oops, got a gap
for (m = 0; m < ps; ++m)
newpoints.push(null);
fromgap = true;
j += otherps;
}
else {
// cases where we actually got two points
px = points[i + keyOffset];
py = points[i + accumulateOffset];
qx = otherpoints[j + keyOffset];
qy = otherpoints[j + accumulateOffset];
bottom = 0;
if (px == qx) {
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
newpoints[l + accumulateOffset] += qy;
bottom = qy;
i += ps;
j += otherps;
}
else if (px > qx) {
// we got past point below, might need to
// insert interpolated extra point
if (withlines && i > 0 && points[i - ps] != null) {
intery = py + (points[i - ps + accumulateOffset] - py) * (qx - px) / (points[i - ps + keyOffset] - px);
newpoints.push(qx);
newpoints.push(intery + qy);
for (m = 2; m < ps; ++m)
newpoints.push(points[i + m]);
bottom = qy;
}
j += otherps;
}
else { // px < qx
if (fromgap && withlines) {
// if we come from a gap, we just skip this point
i += ps;
continue;
}
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
// we might be able to interpolate a point below,
// this can give us a better y
if (withlines && j > 0 && otherpoints[j - otherps] != null)
bottom = qy + (otherpoints[j - otherps + accumulateOffset] - qy) * (px - qx) / (otherpoints[j - otherps + keyOffset] - qx);
newpoints[l + accumulateOffset] += bottom;
i += ps;
}
fromgap = false;
if (l != newpoints.length && withbottom)
newpoints[l + 2] += bottom;
}
// maintain the line steps invariant
if (withsteps && l != newpoints.length && l > 0
&& newpoints[l] != null
&& newpoints[l] != newpoints[l - ps]
&& newpoints[l + 1] != newpoints[l - ps + 1]) {
for (m = 0; m < ps; ++m)
newpoints[l + ps + m] = newpoints[l + m];
newpoints[l + 1] = newpoints[l - ps + 1];
}
}
datapoints.points = newpoints;
}
plot.hooks.processDatapoints.push(stackData);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'stack',
version: '1.2'
});
})(jQuery);

View File

@ -1 +1,7 @@
(function(b){var a={series:{stack:null}};function c(f){function d(k,j){var h=null;for(var g=0;g<j.length;++g){if(k==j[g]){break}if(j[g].stack==k.stack){h=j[g]}}return h}function e(C,v,g){if(v.stack==null){return}var p=d(v,C.getData());if(!p){return}var z=g.pointsize,F=g.points,h=p.datapoints.pointsize,y=p.datapoints.points,t=[],x,w,k,J,I,r,u=v.lines.show,G=v.bars.horizontal,o=z>2&&(G?g.format[2].x:g.format[2].y),n=u&&v.lines.steps,E=true,q=G?1:0,H=G?0:1,D=0,B=0,A;while(true){if(D>=F.length){break}A=t.length;if(F[D]==null){for(m=0;m<z;++m){t.push(F[D+m])}D+=z}else{if(B>=y.length){if(!u){for(m=0;m<z;++m){t.push(F[D+m])}}D+=z}else{if(y[B]==null){for(m=0;m<z;++m){t.push(null)}E=true;B+=h}else{x=F[D+q];w=F[D+H];J=y[B+q];I=y[B+H];r=0;if(x==J){for(m=0;m<z;++m){t.push(F[D+m])}t[A+H]+=I;r=I;D+=z;B+=h}else{if(x>J){if(u&&D>0&&F[D-z]!=null){k=w+(F[D-z+H]-w)*(J-x)/(F[D-z+q]-x);t.push(J);t.push(k+I);for(m=2;m<z;++m){t.push(F[D+m])}r=I}B+=h}else{if(E&&u){D+=z;continue}for(m=0;m<z;++m){t.push(F[D+m])}if(u&&B>0&&y[B-h]!=null){r=I+(y[B-h+H]-I)*(x-J)/(y[B-h+q]-J)}t[A+H]+=r;D+=z}}E=false;if(A!=t.length&&o){t[A+2]+=r}}}}if(n&&A!=t.length&&A>0&&t[A]!=null&&t[A]!=t[A-z]&&t[A+1]!=t[A-z+1]){for(m=0;m<z;++m){t[A+z+m]=t[A+m]}t[A+1]=t[A-z+1]}}g.points=t}f.hooks.processDatapoints.push(e)}b.plot.plugins.push({init:c,options:a,name:"stack",version:"1.2"})})(jQuery);
/* Javascript plotting library for jQuery, version 0.8.3.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
*/
(function($){var options={series:{stack:null}};function init(plot){function findMatchingSeries(s,allseries){var res=null;for(var i=0;i<allseries.length;++i){if(s==allseries[i])break;if(allseries[i].stack==s.stack)res=allseries[i]}return res}function stackData(plot,s,datapoints){if(s.stack==null||s.stack===false)return;var other=findMatchingSeries(s,plot.getData());if(!other)return;var ps=datapoints.pointsize,points=datapoints.points,otherps=other.datapoints.pointsize,otherpoints=other.datapoints.points,newpoints=[],px,py,intery,qx,qy,bottom,withlines=s.lines.show,horizontal=s.bars.horizontal,withbottom=ps>2&&(horizontal?datapoints.format[2].x:datapoints.format[2].y),withsteps=withlines&&s.lines.steps,fromgap=true,keyOffset=horizontal?1:0,accumulateOffset=horizontal?0:1,i=0,j=0,l,m;while(true){if(i>=points.length)break;l=newpoints.length;if(points[i]==null){for(m=0;m<ps;++m)newpoints.push(points[i+m]);i+=ps}else if(j>=otherpoints.length){if(!withlines){for(m=0;m<ps;++m)newpoints.push(points[i+m])}i+=ps}else if(otherpoints[j]==null){for(m=0;m<ps;++m)newpoints.push(null);fromgap=true;j+=otherps}else{px=points[i+keyOffset];py=points[i+accumulateOffset];qx=otherpoints[j+keyOffset];qy=otherpoints[j+accumulateOffset];bottom=0;if(px==qx){for(m=0;m<ps;++m)newpoints.push(points[i+m]);newpoints[l+accumulateOffset]+=qy;bottom=qy;i+=ps;j+=otherps}else if(px>qx){if(withlines&&i>0&&points[i-ps]!=null){intery=py+(points[i-ps+accumulateOffset]-py)*(qx-px)/(points[i-ps+keyOffset]-px);newpoints.push(qx);newpoints.push(intery+qy);for(m=2;m<ps;++m)newpoints.push(points[i+m]);bottom=qy}j+=otherps}else{if(fromgap&&withlines){i+=ps;continue}for(m=0;m<ps;++m)newpoints.push(points[i+m]);if(withlines&&j>0&&otherpoints[j-otherps]!=null)bottom=qy+(otherpoints[j-otherps+accumulateOffset]-qy)*(px-qx)/(otherpoints[j-otherps+keyOffset]-qx);newpoints[l+accumulateOffset]+=bottom;i+=ps}fromgap=false;if(l!=newpoints.length&&withbottom)newpoints[l+2]+=bottom}if(withsteps&&l!=newpoints.length&&l>0&&newpoints[l]!=null&&newpoints[l]!=newpoints[l-ps]&&newpoints[l+1]!=newpoints[l-ps+1]){for(m=0;m<ps;++m)newpoints[l+ps+m]=newpoints[l+m];newpoints[l+1]=newpoints[l-ps+1]}}datapoints.points=newpoints}plot.hooks.processDatapoints.push(stackData)}$.plot.plugins.push({init:init,options:options,name:"stack",version:"1.2"})})(jQuery);

View File

@ -0,0 +1,71 @@
/* Flot plugin that adds some extra symbols for plotting points.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
The symbols are accessed as strings through the standard symbol options:
series: {
points: {
symbol: "square" // or "diamond", "triangle", "cross"
}
}
*/
(function ($) {
function processRawData(plot, series, datapoints) {
// we normalize the area of each symbol so it is approximately the
// same as a circle of the given radius
var handlers = {
square: function (ctx, x, y, radius, shadow) {
// pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2
var size = radius * Math.sqrt(Math.PI) / 2;
ctx.rect(x - size, y - size, size + size, size + size);
},
diamond: function (ctx, x, y, radius, shadow) {
// pi * r^2 = 2s^2 => s = r * sqrt(pi/2)
var size = radius * Math.sqrt(Math.PI / 2);
ctx.moveTo(x - size, y);
ctx.lineTo(x, y - size);
ctx.lineTo(x + size, y);
ctx.lineTo(x, y + size);
ctx.lineTo(x - size, y);
},
triangle: function (ctx, x, y, radius, shadow) {
// pi * r^2 = 1/2 * s^2 * sin (pi / 3) => s = r * sqrt(2 * pi / sin(pi / 3))
var size = radius * Math.sqrt(2 * Math.PI / Math.sin(Math.PI / 3));
var height = size * Math.sin(Math.PI / 3);
ctx.moveTo(x - size/2, y + height/2);
ctx.lineTo(x + size/2, y + height/2);
if (!shadow) {
ctx.lineTo(x, y - height/2);
ctx.lineTo(x - size/2, y + height/2);
}
},
cross: function (ctx, x, y, radius, shadow) {
// pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2
var size = radius * Math.sqrt(Math.PI) / 2;
ctx.moveTo(x - size, y - size);
ctx.lineTo(x + size, y + size);
ctx.moveTo(x - size, y + size);
ctx.lineTo(x + size, y - size);
}
};
var s = series.points.symbol;
if (handlers[s])
series.points.symbol = handlers[s];
}
function init(plot) {
plot.hooks.processDatapoints.push(processRawData);
}
$.plot.plugins.push({
init: init,
name: 'symbols',
version: '1.0'
});
})(jQuery);

View File

@ -1 +1,7 @@
(function(b){function a(h,e,g){var d={square:function(k,j,n,i,m){var l=i*Math.sqrt(Math.PI)/2;k.rect(j-l,n-l,l+l,l+l)},diamond:function(k,j,n,i,m){var l=i*Math.sqrt(Math.PI/2);k.moveTo(j-l,n);k.lineTo(j,n-l);k.lineTo(j+l,n);k.lineTo(j,n+l);k.lineTo(j-l,n)},triangle:function(l,k,o,j,n){var m=j*Math.sqrt(2*Math.PI/Math.sin(Math.PI/3));var i=m*Math.sin(Math.PI/3);l.moveTo(k-m/2,o+i/2);l.lineTo(k+m/2,o+i/2);if(!n){l.lineTo(k,o-i/2);l.lineTo(k-m/2,o+i/2)}},cross:function(k,j,n,i,m){var l=i*Math.sqrt(Math.PI)/2;k.moveTo(j-l,n-l);k.lineTo(j+l,n+l);k.moveTo(j-l,n+l);k.lineTo(j+l,n-l)}};var f=e.points.symbol;if(d[f]){e.points.symbol=d[f]}}function c(d){d.hooks.processDatapoints.push(a)}b.plot.plugins.push({init:c,name:"symbols",version:"1.0"})})(jQuery);
/* Javascript plotting library for jQuery, version 0.8.3.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
*/
(function($){function processRawData(plot,series,datapoints){var handlers={square:function(ctx,x,y,radius,shadow){var size=radius*Math.sqrt(Math.PI)/2;ctx.rect(x-size,y-size,size+size,size+size)},diamond:function(ctx,x,y,radius,shadow){var size=radius*Math.sqrt(Math.PI/2);ctx.moveTo(x-size,y);ctx.lineTo(x,y-size);ctx.lineTo(x+size,y);ctx.lineTo(x,y+size);ctx.lineTo(x-size,y)},triangle:function(ctx,x,y,radius,shadow){var size=radius*Math.sqrt(2*Math.PI/Math.sin(Math.PI/3));var height=size*Math.sin(Math.PI/3);ctx.moveTo(x-size/2,y+height/2);ctx.lineTo(x+size/2,y+height/2);if(!shadow){ctx.lineTo(x,y-height/2);ctx.lineTo(x-size/2,y+height/2)}},cross:function(ctx,x,y,radius,shadow){var size=radius*Math.sqrt(Math.PI)/2;ctx.moveTo(x-size,y-size);ctx.lineTo(x+size,y+size);ctx.moveTo(x-size,y+size);ctx.lineTo(x+size,y-size)}};var s=series.points.symbol;if(handlers[s])series.points.symbol=handlers[s]}function init(plot){plot.hooks.processDatapoints.push(processRawData)}$.plot.plugins.push({init:init,name:"symbols",version:"1.0"})})(jQuery);

View File

@ -1,132 +1,154 @@
/*
Flot plugin for thresholding data. Controlled through the option
"threshold" in either the global series options
series: {
threshold: {
below: number
color: colorspec
/* Flot plugin for thresholding data.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
The plugin supports these options:
series: {
threshold: {
below: number,
above: mumber,
color: colorspec
}
}
}
or in a specific series
$.plot($("#placeholder"), [{ data: [ ... ], threshold: { ... }}])
An array can be passed for multiple thresholding
threshold: [{
below: number1
color: color1
},{
below: number2
color: color2
}]
These multiple threshold objects can be passed in any order since they
are sorted by the processing function.
The data points below "below" are drawn with the specified color. This
makes it easy to mark points below 0, e.g. for budget data.
Internally, the plugin works by splitting the data into two series,
above and below the threshold. The extra series below the threshold
will have its label cleared and the special "originSeries" attribute
set to the original series. You may need to check for this in hover
events.
It can also be applied to a single series, like this:
$.plot( $("#placeholder"), [{
data: [ ... ],
threshold: { ... }
}])
An array can be passed for multiple thresholding, like this:
threshold: [{
below: number1,
color: color1
},{
above: number2,
color: color2
}]
These multiple threshold objects can be passed in any order since they are
sorted by the processing function.
The data points below "below" are drawn with the specified color. This makes
it easy to mark points below 0, e.g. for budget data.
Internally, the plugin works by splitting the data into two series, above and
below the threshold. The extra series below the threshold will have its label
cleared and the special "originSeries" attribute set to the original series.
You may need to check for this in hover events.
*/
(function ($) {
(function($) {
var options = {
series: { threshold: null } // or { below: number, color: color spec}
};
function init(plot) {
function thresholdData(plot, s, datapoints, below, color) {
var ps = datapoints.pointsize, i, x, y, p, prevp,
thresholded = $.extend({}, s); // note: shallow copy
thresholded.datapoints = { points: [], pointsize: ps };
function init(plot) {
function thresholdData(plot, s, datapoints, below, above, color) {
var origpoints = datapoints.points,
ps = datapoints.pointsize,
addCrossingPoints = s.lines.show,
thresholded = $.extend({}, s), // note: shallow copy
threspoints = [],
newpoints = [],
prevp, i, x, y, p, m;
thresholded.datapoints = { points: [], pointsize: ps, format: datapoints.format };
thresholded.label = null;
thresholded.color = color;
thresholded.threshold = null;
thresholded.originSeries = s;
thresholded.data = [];
var origpoints = datapoints.points,
addCrossingPoints = s.lines.show;
threspoints = [];
newpoints = [];
for (i = 0; i < origpoints.length; i += ps) {
x = origpoints[i]
x = origpoints[i];
y = origpoints[i + 1];
prevp = p;
if (y < below)
if (y < below || y > above) {
p = threspoints;
else
} else {
p = newpoints;
}
if (addCrossingPoints && prevp != p && x != null
&& i > 0 && origpoints[i - ps] != null) {
var interx = (x - origpoints[i - ps]) / (y - origpoints[i - ps + 1]) * (below - y) + x;
if (addCrossingPoints && prevp !== p && x != null && i > 0 && origpoints[i - ps] != null) {
var interx = x + (below - y) * (x - origpoints[i - ps]) / (y - origpoints[i - ps + 1]);
prevp.push(interx);
prevp.push(below);
for (m = 2; m < ps; ++m)
for (m = 2; m < ps; ++m) {
prevp.push(origpoints[i + m]);
}
p.push(null); // start new segment
p.push(null);
for (m = 2; m < ps; ++m)
for (m = 2; m < ps; ++m) {
p.push(origpoints[i + m]);
}
p.push(interx);
p.push(below);
for (m = 2; m < ps; ++m)
for (m = 2; m < ps; ++m) {
p.push(origpoints[i + m]);
}
}
p.push(x);
p.push(y);
if (thresholded.lines.fill) {
p.push(0)
}
for (m = 2; m < ps; ++m) {
p.push(origpoints[i + m]);
}
}
datapoints.points = newpoints;
thresholded.datapoints.points = threspoints;
if (thresholded.datapoints.points.length > 0)
plot.getData().push(thresholded);
if (thresholded.datapoints.points.length > 0) {
var origIndex = $.inArray(s, plot.getData());
// Insert newly-generated series right after original one (to prevent it from becoming top-most)
plot.getData().splice(origIndex + 1, 0, thresholded);
}
// FIXME: there are probably some edge cases left in bars
}
function iterateThresholds(plot, s, datapoints) {
if(!s.threshold)
function processThresholds(plot, s, datapoints) {
if (!s.threshold) {
return;
if(s.threshold instanceof Array) {
}
if (s.threshold instanceof Array) {
s.threshold.sort(function(a, b) {
return a.below - b.below;
});
$(s.threshold).each(function(i, th) {
thresholdData(plot, s, datapoints, th.below, th.color);
thresholdData(plot, s, datapoints, th.below, th.above, th.color);
});
} else {
thresholdData(plot, s, datapoints, s.threshold.below, s.threshold.color);
thresholdData(plot, s, datapoints, s.threshold.below, s.threshold.above, s.threshold.color);
}
}
plot.hooks.processDatapoints.push(iterateThresholds);
plot.hooks.processDatapoints.push(processThresholds);
function processThresholdsLegend(ctx, canvas, s) {
if (!s.threshold) {
return;
}
var color = s.threshold.color ? s.threshold.color : "black";
$(".legendLabel").each(function() {
if ($(this).text() === s.label)
{
var legend = $(this).prev().find("div > div");
legend.css("border-right-color", color);
legend.css("border-bottom-color", color);
}
});
}
plot.hooks.drawSeries.push(processThresholdsLegend);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'threshold',
version: '1.0'
name: "threshold",
version: "1.3"
});
})(jQuery);
})(jQuery);

View File

@ -0,0 +1,7 @@
/* Javascript plotting library for jQuery, version 0.8.3.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
*/
(function($){var options={series:{threshold:null}};function init(plot){function thresholdData(plot,s,datapoints,below,color){var ps=datapoints.pointsize,i,x,y,p,prevp,thresholded=$.extend({},s);thresholded.datapoints={points:[],pointsize:ps,format:datapoints.format};thresholded.label=null;thresholded.color=color;thresholded.threshold=null;thresholded.originSeries=s;thresholded.data=[];var origpoints=datapoints.points,addCrossingPoints=s.lines.show;var threspoints=[];var newpoints=[];var m;for(i=0;i<origpoints.length;i+=ps){x=origpoints[i];y=origpoints[i+1];prevp=p;if(y<below)p=threspoints;else p=newpoints;if(addCrossingPoints&&prevp!=p&&x!=null&&i>0&&origpoints[i-ps]!=null){var interx=x+(below-y)*(x-origpoints[i-ps])/(y-origpoints[i-ps+1]);prevp.push(interx);prevp.push(below);for(m=2;m<ps;++m)prevp.push(origpoints[i+m]);p.push(null);p.push(null);for(m=2;m<ps;++m)p.push(origpoints[i+m]);p.push(interx);p.push(below);for(m=2;m<ps;++m)p.push(origpoints[i+m])}p.push(x);p.push(y);for(m=2;m<ps;++m)p.push(origpoints[i+m])}datapoints.points=newpoints;thresholded.datapoints.points=threspoints;if(thresholded.datapoints.points.length>0){var origIndex=$.inArray(s,plot.getData());plot.getData().splice(origIndex+1,0,thresholded)}}function processThresholds(plot,s,datapoints){if(!s.threshold)return;if(s.threshold instanceof Array){s.threshold.sort(function(a,b){return a.below-b.below});$(s.threshold).each(function(i,th){thresholdData(plot,s,datapoints,th.below,th.color)})}else{thresholdData(plot,s,datapoints,s.threshold.below,s.threshold.color)}}plot.hooks.processDatapoints.push(processThresholds)}$.plot.plugins.push({init:init,options:options,name:"threshold",version:"1.2"})})(jQuery);

View File

@ -0,0 +1,189 @@
/*
Flot plugin for specifying range of thresolds on data.
Controlled through the option "constraints" in a specific series
usage -
$.plot($("#placeholder"), [{ data: [ ... ], constraints: [constraint1, constraint2]},{data:[...],constraints:[...]}])
where constraint1 = {
threshold: 2,
color: "rgb(0,0,0)",
evaluate : function(y,threshold){ return y < threshold; }
}
threshold -> y-limit on the plot.
evaluate -> the function which defines the limit.This function defines wheteher y < threshold or y > threshold.
color -> the color with which to plot portion of the graph which satisfies the limit condition.
Internally, the plugin works by splitting the data into different series, one for each constraint.
*/
(function($){
function init(plot){
function plotWithMultipleThresholds(plot,s,datapoints){
if(s.data && s.data.length > 0 && s.constraints && s.constraints.length>0){
var series = new Graph(s.data,s.constraints).getPlotData();
for(var i=0;i<series.length;i++){
var ss = $.extend({},s);
ss.constraints = [];
ss.data = series[i].data;
ss.color = series[i].color;
plot.getData().push(ss);
}
}
}
function Graph(dataset, constraints) {
this._constraints = _getSortedConstraints(dataset,constraints);
this._dataset = dataset;
this._plotData = [];
this.getPlotData = function() {
if(this._constraints.length == 0)return [];
for ( var i = this._constraints.length - 1; i >= 0 ; i--) {
var constraint = this._constraints[i];
if(null != constraint.threshold){
var set = new Resolve(this._dataset).using(constraint.threshold, constraint.evaluate);
this._plotData.push( {
data : set,
color : constraint.color
});
}
}
return this._plotData;
};
function Resolve(originalPonits) {
this._originalPoints = originalPonits;
this._data = [];
this._getPointOnThreshold = _getPointOnThreshold;
this.using = using ;
function using(threshold, evaluate) {
var count = 0;
for ( var i = 0; i < this._originalPoints.length; i++) {
var currentPoint = this._originalPoints[i];
if (evaluate(currentPoint[1],threshold)) {
if (i > 0
&& (this._data.length == 0 || this._data[count - 1] == null)) {
this._data[count++] = this._getPointOnThreshold(threshold,this._originalPoints[i - 1], currentPoint);
}
this._data[count++] = currentPoint;
} else {
if (this._data.length > 0 && this._data[count - 1] != null) {
this._data[count++] = this._getPointOnThreshold(threshold,this._originalPoints[i - 1], currentPoint);
this._data[count++] = null;
this._data[count++] = null;
}
}
}
return this._data;
}
function _getPointOnThreshold(threshold, prevP, currP) {
var currentX = currP[0];
var currentY = currP[1];
var prevX = prevP[0];
var prevY = prevP[1];
var slope = (threshold - currentY)
/ (prevY - currentY);
var xOnConstraintLine = slope * (prevX - currentX) + currentX;
return [ xOnConstraintLine, threshold ];
}
}
function _getSortedConstraints(originalpoints,constraints){
var dataRange = _findMaxAndMin(originalpoints);
if(undefined == dataRange)return [];
var max = dataRange.max;
var min = dataRange.min;
var thresholdRanges = [];
var sortedConstraints = [];
for(var i = 0; i < constraints.length ; i++){
var constraint = constraints[i];
var range = 0;
if(constraint.evaluate(min,constraint.threshold)){
range = Math.abs(constraint.threshold - min);
}else{
range = Math.abs(max - constraint.threshold);
}
thresholdRanges.push({constraint:constraint,range:range});
}
QuickSort(thresholdRanges,function(obj1,obj2){ return obj1.range < obj2.range;});
for(var i=thresholdRanges.length-1;i>=0;i--){
sortedConstraints[i] = thresholdRanges[i].constraint;
}
return sortedConstraints;
}
function _findMaxAndMin(dataset){
if(undefined == dataset)return undefined;
var arr = [];
for( var i=0;i<dataset.length;i++){
arr[i] = dataset[i][1];
}
QuickSort(arr,function(p1,p2){return p1 < p2;});
return { min:arr[0],max:arr[arr.length-1]};
}
}
function QuickSort(dataset,comparator){
sort(dataset, 0, dataset.length-1, comparator);
function sort(array, left, right,comparator){
if(right > left){
var pivotIndex = Math.floor(( left + right )/2);
var pivotNewIndex = partition(array,left,right,pivotIndex,comparator);
sort(array, left, pivotNewIndex - 1,comparator);
sort(array, pivotNewIndex + 1, right,comparator);
}
}
function partition(array,left,right,pivotIndex,comparator){
var pivot = array[pivotIndex];
swap(array,pivotIndex,right);
var storeIndex = left;
for( var i= left ; i < right ; i++){
if(comparator(array[i] , pivot)){
swap(array,i,storeIndex);
storeIndex = storeIndex + 1;
}
}
swap(array,storeIndex,right);
return storeIndex;
}
function swap(array,index1,index2){
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
}
plot.hooks.processRawData.push(plotWithMultipleThresholds);
}
$.plot.plugins.push({
init: init,
name: 'multiple.threshold',
version: '1.0'
});
})(jQuery);

View File

@ -0,0 +1,432 @@
/* Pretty handling of time axes.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
Set axis.mode to "time" to enable. See the section "Time series data" in
API.txt for details.
*/
(function($) {
var options = {
xaxis: {
timezone: null, // "browser" for local to the client or timezone for timezone-js
timeformat: null, // format string to use
twelveHourClock: false, // 12 or 24 time in time mode
monthNames: null // list of names of months
}
};
// round to nearby lower multiple of base
function floorInBase(n, base) {
return base * Math.floor(n / base);
}
// Returns a string with the date d formatted according to fmt.
// A subset of the Open Group's strftime format is supported.
function formatDate(d, fmt, monthNames, dayNames) {
if (typeof d.strftime == "function") {
return d.strftime(fmt);
}
var leftPad = function(n, pad) {
n = "" + n;
pad = "" + (pad == null ? "0" : pad);
return n.length == 1 ? pad + n : n;
};
var r = [];
var escape = false;
var hours = d.getHours();
var isAM = hours < 12;
if (monthNames == null) {
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
}
if (dayNames == null) {
dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
}
var hours12;
if (hours > 12) {
hours12 = hours - 12;
} else if (hours == 0) {
hours12 = 12;
} else {
hours12 = hours;
}
for (var i = 0; i < fmt.length; ++i) {
var c = fmt.charAt(i);
if (escape) {
switch (c) {
case 'a': c = "" + dayNames[d.getDay()]; break;
case 'b': c = "" + monthNames[d.getMonth()]; break;
case 'd': c = leftPad(d.getDate()); break;
case 'e': c = leftPad(d.getDate(), " "); break;
case 'h': // For back-compat with 0.7; remove in 1.0
case 'H': c = leftPad(hours); break;
case 'I': c = leftPad(hours12); break;
case 'l': c = leftPad(hours12, " "); break;
case 'm': c = leftPad(d.getMonth() + 1); break;
case 'M': c = leftPad(d.getMinutes()); break;
// quarters not in Open Group's strftime specification
case 'q':
c = "" + (Math.floor(d.getMonth() / 3) + 1); break;
case 'S': c = leftPad(d.getSeconds()); break;
case 'y': c = leftPad(d.getFullYear() % 100); break;
case 'Y': c = "" + d.getFullYear(); break;
case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
case 'w': c = "" + d.getDay(); break;
}
r.push(c);
escape = false;
} else {
if (c == "%") {
escape = true;
} else {
r.push(c);
}
}
}
return r.join("");
}
// To have a consistent view of time-based data independent of which time
// zone the client happens to be in we need a date-like object independent
// of time zones. This is done through a wrapper that only calls the UTC
// versions of the accessor methods.
function makeUtcWrapper(d) {
function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
sourceObj[sourceMethod] = function() {
return targetObj[targetMethod].apply(targetObj, arguments);
};
};
var utc = {
date: d
};
// support strftime, if found
if (d.strftime != undefined) {
addProxyMethod(utc, "strftime", d, "strftime");
}
addProxyMethod(utc, "getTime", d, "getTime");
addProxyMethod(utc, "setTime", d, "setTime");
var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
for (var p = 0; p < props.length; p++) {
addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
}
return utc;
};
// select time zone strategy. This returns a date-like object tied to the
// desired timezone
function dateGenerator(ts, opts) {
if (opts.timezone == "browser") {
return new Date(ts);
} else if (!opts.timezone || opts.timezone == "utc") {
return makeUtcWrapper(new Date(ts));
} else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
var d = new timezoneJS.Date();
// timezone-js is fickle, so be sure to set the time zone before
// setting the time.
d.setTimezone(opts.timezone);
d.setTime(ts);
return d;
} else {
return makeUtcWrapper(new Date(ts));
}
}
// map of app. size of time units in milliseconds
var timeUnitSize = {
"second": 1000,
"minute": 60 * 1000,
"hour": 60 * 60 * 1000,
"day": 24 * 60 * 60 * 1000,
"month": 30 * 24 * 60 * 60 * 1000,
"quarter": 3 * 30 * 24 * 60 * 60 * 1000,
"year": 365.2425 * 24 * 60 * 60 * 1000
};
// the allowed tick sizes, after 1 year we use
// an integer algorithm
var baseSpec = [
[1, "second"], [2, "second"], [5, "second"], [10, "second"],
[30, "second"],
[1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
[30, "minute"],
[1, "hour"], [2, "hour"], [4, "hour"],
[8, "hour"], [12, "hour"],
[1, "day"], [2, "day"], [3, "day"],
[0.25, "month"], [0.5, "month"], [1, "month"],
[2, "month"]
];
// we don't know which variant(s) we'll need yet, but generating both is
// cheap
var specMonths = baseSpec.concat([[3, "month"], [6, "month"],
[1, "year"]]);
var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"],
[1, "year"]]);
function init(plot) {
plot.hooks.processOptions.push(function (plot, options) {
$.each(plot.getAxes(), function(axisName, axis) {
var opts = axis.options;
if (opts.mode == "time") {
axis.tickGenerator = function(axis) {
var ticks = [];
var d = dateGenerator(axis.min, opts);
var minSize = 0;
// make quarter use a possibility if quarters are
// mentioned in either of these options
var spec = (opts.tickSize && opts.tickSize[1] ===
"quarter") ||
(opts.minTickSize && opts.minTickSize[1] ===
"quarter") ? specQuarters : specMonths;
if (opts.minTickSize != null) {
if (typeof opts.tickSize == "number") {
minSize = opts.tickSize;
} else {
minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
}
}
for (var i = 0; i < spec.length - 1; ++i) {
if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]]
+ spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
&& spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) {
break;
}
}
var size = spec[i][0];
var unit = spec[i][1];
// special-case the possibility of several years
if (unit == "year") {
// if given a minTickSize in years, just use it,
// ensuring that it's an integer
if (opts.minTickSize != null && opts.minTickSize[1] == "year") {
size = Math.floor(opts.minTickSize[0]);
} else {
var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10));
var norm = (axis.delta / timeUnitSize.year) / magn;
if (norm < 1.5) {
size = 1;
} else if (norm < 3) {
size = 2;
} else if (norm < 7.5) {
size = 5;
} else {
size = 10;
}
size *= magn;
}
// minimum size for years is 1
if (size < 1) {
size = 1;
}
}
axis.tickSize = opts.tickSize || [size, unit];
var tickSize = axis.tickSize[0];
unit = axis.tickSize[1];
var step = tickSize * timeUnitSize[unit];
if (unit == "second") {
d.setSeconds(floorInBase(d.getSeconds(), tickSize));
} else if (unit == "minute") {
d.setMinutes(floorInBase(d.getMinutes(), tickSize));
} else if (unit == "hour") {
d.setHours(floorInBase(d.getHours(), tickSize));
} else if (unit == "month") {
d.setMonth(floorInBase(d.getMonth(), tickSize));
} else if (unit == "quarter") {
d.setMonth(3 * floorInBase(d.getMonth() / 3,
tickSize));
} else if (unit == "year") {
d.setFullYear(floorInBase(d.getFullYear(), tickSize));
}
// reset smaller components
d.setMilliseconds(0);
if (step >= timeUnitSize.minute) {
d.setSeconds(0);
}
if (step >= timeUnitSize.hour) {
d.setMinutes(0);
}
if (step >= timeUnitSize.day) {
d.setHours(0);
}
if (step >= timeUnitSize.day * 4) {
d.setDate(1);
}
if (step >= timeUnitSize.month * 2) {
d.setMonth(floorInBase(d.getMonth(), 3));
}
if (step >= timeUnitSize.quarter * 2) {
d.setMonth(floorInBase(d.getMonth(), 6));
}
if (step >= timeUnitSize.year) {
d.setMonth(0);
}
var carry = 0;
var v = Number.NaN;
var prev;
do {
prev = v;
v = d.getTime();
ticks.push(v);
if (unit == "month" || unit == "quarter") {
if (tickSize < 1) {
// a bit complicated - we'll divide the
// month/quarter up but we need to take
// care of fractions so we don't end up in
// the middle of a day
d.setDate(1);
var start = d.getTime();
d.setMonth(d.getMonth() +
(unit == "quarter" ? 3 : 1));
var end = d.getTime();
d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
carry = d.getHours();
d.setHours(0);
} else {
d.setMonth(d.getMonth() +
tickSize * (unit == "quarter" ? 3 : 1));
}
} else if (unit == "year") {
d.setFullYear(d.getFullYear() + tickSize);
} else {
d.setTime(v + step);
}
} while (v < axis.max && v != prev);
return ticks;
};
axis.tickFormatter = function (v, axis) {
var d = dateGenerator(v, axis.options);
// first check global format
if (opts.timeformat != null) {
return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames);
}
// possibly use quarters if quarters are mentioned in
// any of these places
var useQuarters = (axis.options.tickSize &&
axis.options.tickSize[1] == "quarter") ||
(axis.options.minTickSize &&
axis.options.minTickSize[1] == "quarter");
var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
var span = axis.max - axis.min;
var suffix = (opts.twelveHourClock) ? " %p" : "";
var hourCode = (opts.twelveHourClock) ? "%I" : "%H";
var fmt;
if (t < timeUnitSize.minute) {
fmt = hourCode + ":%M:%S" + suffix;
} else if (t < timeUnitSize.day) {
if (span < 2 * timeUnitSize.day) {
fmt = hourCode + ":%M" + suffix;
} else {
fmt = "%b %d " + hourCode + ":%M" + suffix;
}
} else if (t < timeUnitSize.month) {
fmt = "%b %d";
} else if ((useQuarters && t < timeUnitSize.quarter) ||
(!useQuarters && t < timeUnitSize.year)) {
if (span < timeUnitSize.year) {
fmt = "%b";
} else {
fmt = "%b %Y";
}
} else if (useQuarters && t < timeUnitSize.year) {
if (span < timeUnitSize.year) {
fmt = "Q%q";
} else {
fmt = "Q%q %Y";
}
} else {
fmt = "%Y";
}
var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames);
return rt;
};
}
});
});
}
$.plot.plugins.push({
init: init,
options: options,
name: 'time',
version: '1.0'
});
// Time-axis support used to be in Flot core, which exposed the
// formatDate function on the plot object. Various plugins depend
// on the function, so we need to re-expose it here.
$.plot.formatDate = formatDate;
$.plot.dateGenerator = dateGenerator;
})(jQuery);

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -20,22 +20,26 @@ global $config;
function include_javascript_dependencies_flot_graph($return = false) {
global $config;
static $is_include_javascript = false;
if (!$is_include_javascript) {
$is_include_javascript = true;
$metaconsole_hack = '';
if (defined('METACONSOLE')) {
$metaconsole_hack = '../../';
}
// NOTE: jquery.flot.threshold is not te original file. Is patched to allow multiple thresholds and filled area
$output = '
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="' . ui_get_full_url($metaconsole_hack . '/include/graphs/flot/excanvas.js') . '"></script><![endif]-->
<script language="javascript" type="text/javascript" src="'.
ui_get_full_url($metaconsole_hack . '/include/graphs/flot/jquery.flot.js') .'"></script>
<script language="javascript" type="text/javascript" src="'.
ui_get_full_url($metaconsole_hack . '/include/graphs/flot/jquery.flot.min.js') .'"></script>
<script language="javascript" type="text/javascript" src="'.
ui_get_full_url($metaconsole_hack . '/include/graphs/flot/jquery.flot.time.js') .'"></script>
<script language="javascript" type="text/javascript" src="'.
ui_get_full_url($metaconsole_hack . '/include/graphs/flot/jquery.flot.pie.js') .'"></script>
<script language="javascript" type="text/javascript" src="'.
@ -48,18 +52,20 @@ function include_javascript_dependencies_flot_graph($return = false) {
ui_get_full_url($metaconsole_hack . '/include/graphs/flot/jquery.flot.resize.min.js') .'"></script>
<script language="javascript" type="text/javascript" src="'.
ui_get_full_url($metaconsole_hack . '/include/graphs/flot/jquery.flot.threshold.js') .'"></script>
<script language="javascript" type="text/javascript" src="'.
ui_get_full_url($metaconsole_hack . '/include/graphs/flot/jquery.flot.threshold.multiple.js') .'"></script>
<script language="javascript" type="text/javascript" src="'.
ui_get_full_url($metaconsole_hack . '/include/graphs/flot/jquery.flot.symbol.min.js') .'"></script>
<script language="javascript" type="text/javascript" src="'.
ui_get_full_url($metaconsole_hack . '/include/graphs/flot/jquery.flot.exportdata.pandora.js') .'"></script>
<script language="javascript" type="text/javascript" src="'.
ui_get_full_url($metaconsole_hack . '/include/graphs/flot/jquery.flot.axislabels.js') .'"></script>
<script language="javascript" type="text/javascript" src="'.
<script language="javascript" type="text/javascript" src="'.
ui_get_full_url($metaconsole_hack . '/include/graphs/flot/pandora.flot.js') .'"></script>';
$output .= "
<script type='text/javascript'>
var precision_graph = " . $config['graph_precision'] . ";
function pieHover(event, pos, obj)
function pieHover(event, pos, obj)
{
if (!obj)
return;
@ -74,8 +80,8 @@ function include_javascript_dependencies_flot_graph($return = false) {
}
});
}
function pieClick(event, pos, obj)
function pieClick(event, pos, obj)
{
if (!obj)
return;
@ -83,10 +89,10 @@ function include_javascript_dependencies_flot_graph($return = false) {
alert(''+obj.series.label+': '+obj.series.data[0][1]+' ('+percent+'%)');
}
</script>";
if (!$return)
echo $output;
return $output;
}
}
@ -94,103 +100,21 @@ function include_javascript_dependencies_flot_graph($return = false) {
///////////////////////////////
////////// AREA GRAPHS ////////
///////////////////////////////
function flot_area_stacked_graph($chart_data, $width, $height, $color,
$legend, $long_index, $homeurl = '', $font = '', $font_size = 7,
$unit = '', $water_mark = '', $serie_types = array(),
$chart_extra_data = array(), $yellow_threshold = 0,
$red_threshold = 0, $adapt_key= '', $force_integer = false,
$series_suffix_str = '', $menu = true, $background_color = 'white',
$dashboard = false, $vconsole = false, $agent_module_id = 0) {
global $config;
return flot_area_graph($chart_data, $width, $height, $color,
$legend, $long_index, $homeurl, $unit, 'area_stacked',
$water_mark, $serie_types, $chart_extra_data, $yellow_threshold,
$red_threshold, $adapt_key, $force_integer, $series_suffix_str,
$menu, $background_color, $dashboard, $vconsole,
$agent_module_id, $font, $font_size);
}
function flot_area_graph (
$agent_module_id, $array_data,
$legend, $series_type, $color, $date_array,
$data_module_graph, $params, $water_mark,
$array_events_alerts ) {
function flot_area_simple_graph($chart_data, $width, $height, $color,
$legend, $long_index, $homeurl = '', $unit = '', $water_mark = '',
$serie_types = array(), $chart_extra_data = array(),
$yellow_threshold = 0, $red_threshold = 0, $adapt_key= '',
$force_integer = false, $series_suffix_str = '', $menu = true,
$background_color = 'white', $dashboard = false, $vconsole = false,
$agent_module_id = 0, $font = '', $font_size = 7, $xaxisname = '',
$percentil_values = array(), $threshold_data = array()) {
global $config;
return flot_area_graph($chart_data, $width, $height, $color,
$legend, $long_index, $homeurl, $unit, 'area_simple',
$water_mark, $serie_types, $chart_extra_data, $yellow_threshold,
$red_threshold, $adapt_key, $force_integer, $series_suffix_str,
$menu, $background_color, $dashboard, $vconsole,
$agent_module_id, $font, $font_size, $xaxisname, $percentil_values,
$threshold_data);
}
function flot_line_stacked_graph($chart_data, $width, $height, $color,
$legend, $long_index, $homeurl = '', $font = '', $font_size = 7,
$unit = '', $water_mark = '', $serie_types = array(),
$chart_extra_data = array(), $yellow_threshold = 0,
$red_threshold = 0, $adapt_key= '', $force_integer = false,
$series_suffix_str = '', $menu = true, $background_color = 'white',
$dashboard = false, $vconsole = false, $agent_module_id = 0,
$xaxisname = "") {
global $config;
return flot_area_graph($chart_data, $width, $height, $color,
$legend, $long_index, $homeurl, $unit, 'line_stacked',
$water_mark, $serie_types, $chart_extra_data, $yellow_threshold,
$red_threshold, $adapt_key, $force_integer, $series_suffix_str,
$menu, $background_color, $dashboard, $vconsole,
$agent_module_id, $font, $font_size, $xaxisname);
}
function flot_line_simple_graph($chart_data, $width, $height, $color,
$legend, $long_index, $homeurl = '', $font = '', $font_size = 7,
$unit = '', $water_mark = '', $serie_types = array(),
$chart_extra_data = array(), $yellow_threshold = 0,
$red_threshold = 0, $adapt_key= '', $force_integer = false,
$series_suffix_str = '', $menu = true, $background_color = 'white',
$dashboard = false, $vconsole = false, $agent_module_id = 0,
$percentil_values = array(), $threshold_data = array(),
$xaxisname = '') {
global $config;
return flot_area_graph($chart_data, $width, $height, $color,
$legend, $long_index, $homeurl, $unit, 'line_simple',
$water_mark, $serie_types, $chart_extra_data, $yellow_threshold,
$red_threshold, $adapt_key, $force_integer, $series_suffix_str,
$menu, $background_color, $dashboard, $vconsole,
$agent_module_id, $font, $font_size, $xaxisname, $percentil_values,
$threshold_data);
}
function flot_area_graph($chart_data, $width, $height, $color, $legend,
$long_index, $homeurl, $unit, $type, $water_mark, $serie_types,
$chart_extra_data, $yellow_threshold, $red_threshold, $adapt_key,
$force_integer, $series_suffix_str = '', $menu = true,
$background_color = 'white', $dashboard = false, $vconsole = false,
$agent_module_id = 0, $font = '', $font_size = 7, $xaxisname = '',
$percentil_values = array(), $threshold_data = array()) {
global $config;
// include_javascript_dependencies_flot_graph();
$menu = (int)$menu;
// Get a unique identifier to graph
$graph_id = uniqid('graph_');
$background_style = '';
switch ($background_color) {
default:
switch ($params['backgroundColor']) {
case 'white':
$background_style = ' background: #fff; ';
break;
@ -200,281 +124,128 @@ function flot_area_graph($chart_data, $width, $height, $color, $legend,
case 'transparent':
$background_style = '';
break;
default:
$background_style = 'background-color: ' . $params['backgroundColor'];
break;
}
// Parent layer
$return = "<div class='parent_graph' style='width: " . ($width) . "px; " . $background_style . "'>";
$return = "<div class='parent_graph' style='width: " . ($params['width']) . ";" . $background_style . "'>";
// Set some containers to legend, graph, timestamp tooltip, etc.
$return .= "<p id='legend_$graph_id' class='legend_graph' style='font-size:$font_size"."pt !important;'></p>";
if (!empty($threshold_data)) {
$yellow_up = $threshold_data['yellow_up'];
$red_up = $threshold_data['red_up'];
$yellow_inverse = $threshold_data['yellow_inverse'];
$red_inverse = $threshold_data['red_inverse'];
if($params['show_legend']){
$return .= "<p id='legend_$graph_id' class='legend_graph' style='font-size:" . $params['font_size'] ."pt !important;'></p>";
}
else {
if(isset($params['graph_combined']) && $params['graph_combined'] &&
(!isset($params['from_interface']) || !$params['from_interface']) ){
$yellow_up = 0;
$red_up = 0;
$yellow_inverse = false;
$red_inverse = false;
}
elseif(!isset($params['combined']) || !$params['combined']){
$yellow_threshold = $data_module_graph['w_min'];
$red_threshold = $data_module_graph['c_min'];
// Get other required module datas to draw warning and critical
if ($agent_module_id == 0) {
$yellow_up = 0;
$red_up = 0;
$yellow_up = 0;
$red_up = 0;
$yellow_inverse = false;
$red_inverse = false;
$red_inverse = false;
} else {
$module_data = db_get_row_sql ('SELECT * FROM tagente_modulo WHERE id_agente_modulo = ' . $agent_module_id);
$yellow_up = $module_data['max_warning'];
$red_up = $module_data['max_critical'];
$yellow_inverse = !($module_data['warning_inverse'] == 0);
$red_inverse = !($module_data['critical_inverse'] == 0);
$yellow_up = $data_module_graph['w_max'];
$red_up = $data_module_graph['c_max'];
$yellow_inverse = !($data_module_graph['w_inv'] == 0);
$red_inverse = !($data_module_graph['c_inv'] == 0);
}
}
if ($menu) {
$threshold = false;
if ($yellow_threshold != $yellow_up || $red_threshold != $red_up) {
$threshold = true;
elseif(isset($params['from_interface']) && $params['from_interface']){
if( isset($params['threshold_data']) && is_array($params['threshold_data'])){
$yellow_up = $params['threshold_data']['yellow_up'];
$red_up = $params['threshold_data']['red_up'];
$yellow_inverse = $params['threshold_data']['yellow_inverse'];
$red_inverse = $params['threshold_data']['red_inverse'];
}
$nbuttons = 3;
if ($threshold) {
$nbuttons++;
}
$menu_width = 25 * $nbuttons + 15;
if ( $dashboard == false AND $vconsole == false) {
$return .= "<div id='geneal_menu_$graph_id' class='menu_graph' style='
width: 30px;
height: 250px;
left: " . $width . "px;
position: absolute;
top: 0px;
background-color: white;'>";
$return .= "<div id='menu_$graph_id' " .
"style='display: none; " .
"text-align: center;" .
"position: relative;".
"border-bottom: 0px;'>
<a href='javascript:'><img id='menu_cancelzoom_$graph_id' src='".$homeurl."images/zoom_cross_grey.disabled.png' alt='".__('Cancel zoom')."' title='".__('Cancel zoom')."'></a>";
if ($threshold) {
$return .= " <a href='javascript:'><img id='menu_threshold_$graph_id' src='".$homeurl."images/chart_curve_threshold.png' alt='".__('Warning and Critical thresholds')."' title='".__('Warning and Critical thresholds')."'></a>";
}
$return .= " <a href='javascript:'>
<img id='menu_overview_$graph_id' class='menu_overview' src='" . $homeurl . "images/chart_curve_overview.png' alt='" . __('Overview graph') . "' title='".__('Overview graph')."'></a>";
// Export buttons
$return .= " <a href='javascript:'><img id='menu_export_csv_$graph_id' src='".$homeurl."images/csv_grey.png' alt='".__('Export to CSV')."' title='".__('Export to CSV')."'></a>";
// Button disabled. This feature works, but seems that is not useful enough to the final users.
//$return .= " <a href='javascript:'><img id='menu_export_json_$graph_id' src='".$homeurl."images/json.png' alt='".__('Export to JSON')."' title='".__('Export to JSON')."'></a>";
$return .= "</div>";
$return .= "</div>";
else{
$yellow_up = 0;
$red_up = 0;
$yellow_inverse = false;
$red_inverse = false;
}
}
else{
$yellow_up = 0;
$red_up = 0;
$yellow_inverse = false;
$red_inverse = false;
}
if ($dashboard) {
$return .= "<div id='geneal_menu_$graph_id' class='menu_graph' style='
width: 30px;
height: 250px;
left: " . $width . "px;
position: absolute;
top: 0px;
background-color: white;'>";
$return .= "<div id='menu_$graph_id' " .
"style='display: none; " .
"text-align: center;" .
"position: relative;".
"border-bottom: 0px;'>
<a href='javascript:'><img id='menu_cancelzoom_$graph_id' src='".$homeurl."images/zoom_cross_grey.disabled.png' alt='".__('Cancel zoom')."' title='".__('Cancel zoom')."'></a>";
$return .= "</div>";
$return .= "</div>";
}
if ($params['menu']) {
$return .= menu_graph(
$yellow_threshold,
$red_threshold,
$yellow_up,
$red_up,
$yellow_inverse,
$red_inverse,
$graph_id,
$params
);
}
$return .= html_print_input_hidden('line_width_graph', $config['custom_graph_width'], true);
$return .= "<div id='timestamp_$graph_id' class='timestamp_graph' style='font-size:".$font_size."pt;display:none; position:absolute; background:#fff; border: solid 1px #aaa; padding: 2px; z-index:1000;'></div>";
$return .= "<div id='timestamp_$graph_id'
class='timestamp_graph'
style=' font-size:".$params['font_size']."pt;
display:none; position:absolute;
background:#fff; border: solid 1px #aaa;
padding: 2px; z-index:1000;'></div>";
$return .= "<div id='$graph_id' class='";
if($type=='area_simple'){$return .= "noresizevc ";}
$return .= "graph $adapt_key' style='width: ".$width."px; height: ".$height."px;'></div>";
if ($menu) {
$height = 100;
if($params['type'] == 'area_simple'){
$return .= "noresizevc ";
}
$return .= "graph" .$params['adapt_key'] ."'
style=' width: ".$params['width']."px;
height: ".$params['height']."px;'></div>";
if ($params['menu']) {
$params['height'] = 100;
}
else {
$height = 1;
$params['height'] = 1;
}
if (!$vconsole)
$return .= "<div id='overview_$graph_id' class='overview_graph' style='display: none; margin-left:0px; margin-top:20px; margin-bottom:50px; width: ".$width."px; height: ".$height ."px;'></div>";
if (!$vconsole){
$return .= "<div id='overview_$graph_id' class='overview_graph'
style='margin:0px; margin-top:30px; margin-bottom:50px; display:none; width: ".$params['width']."; height: 200px;'></div>";
}
if ($water_mark != '') {
$return .= "<div id='watermark_$graph_id' style='display:none; position:absolute;'><img id='watermark_image_$graph_id' src='$water_mark'></div>";
$return .= "<div id='watermark_$graph_id' style='display:none; position:absolute;'><img id='watermark_image_$graph_id' src='" . $water_mark['url'] . "'></div>";
$watermark = 'true';
}
else {
$watermark = 'false';
}
// Set a weird separator to serialize and unserialize passing data from php to javascript
$separator = ';;::;;';
$separator2 = ':,:,,,:,:';
// Transform data from our format to library format
$legend2 = array();
$labels = array();
$a = array();
$vars = array();
$serie_types2 = array();
$colors = array();
$index = array_keys(reset($chart_data));
foreach ($index as $serie_key) {
if (isset($color[$serie_key])) {
$colors[] = $color[$serie_key]['color'];
}
else {
$colors[] = '';
}
}
foreach ($chart_data as $label => $values) {
$labels[] = $label;
foreach($values as $key => $value) {
$jsvar = "data_" . $graph_id . "_" . $key;
if (!isset($serie_types[$key])) {
switch ($type) {
case 'line_simple':
case 'line_stacked':
$serie_types2[$jsvar] = 'line';
break;
case 'area_simple':
case 'area_stacked':
default:
$serie_types2[$jsvar] = 'area';
break;
}
}
else {
$serie_types2[$jsvar] = $serie_types[$key];
}
if ($serie_types2[$jsvar] == 'points' && $value == 0) {
$data[$jsvar][] = 'null';
}
else {
$data[$jsvar][] = $value;
}
if (!isset($legend[$key])) {
$legend2[$jsvar] = 'null';
}
else {
$legend2[$jsvar] = $legend[$key];
}
}
foreach($series_type as $k => $v){
$series_type_unique["data_" . $graph_id . "_" . $k] = $v;
}
if (!empty($percentil_values)) {
foreach($percentil_values as $key => $value) {
$jsvar = "percentil_" . $graph_id . "_" . $key;
$serie_types2[$jsvar] = 'line';
$data[$jsvar] = $value;
}
}
// Store data series in javascript format
$jsvars = '';
$jsseries = array();
$values2 = array();
$i = 0;
$max_x = 0;
foreach ($data as $jsvar => $values) {
$n_values = count($values);
if ($n_values > $max_x) {
$max_x = $n_values;
}
$values2[] = implode($separator,$values);
$i ++;
}
$values = implode($separator2, $values2);
// Max is "n-1" because start with 0
$max_x--;
$extra_width = (int)($width / 3);
$return .= "<div id='extra_$graph_id' style='font-size: " . $font_size . "pt; display:none; position:absolute; overflow: auto; max-height: ".($height+50)."px; width: ".$extra_width."px; background:#fff; padding: 2px 2px 2px 2px; border: solid #000 1px;'></div>";
// Process extra data
$events = array();
$event_ids = array();
$alerts = array();
$alert_ids = array();
$legend_events = '';
$legend_alerts = '';
if (empty($chart_extra_data)) {
$chart_extra_data = array();
}
foreach ($chart_extra_data as $i => $data) {
switch ($i) {
case 'legend_alerts':
$legend_alerts = $data;
break;
case 'legend_events':
$legend_events = $data;
break;
default:
if (isset($data['events'])) {
$event_ids[] = $i;
$events[$i] = $data['events'];
}
if (isset($data['alerts'])) {
$alert_ids[] = $i;
$alerts[$i] = $data['alerts'];
}
break;
}
}
// Store serialized data to use it from javascript
$events = implode($separator,$events);
$event_ids = implode($separator,$event_ids);
$alerts = implode($separator,$alerts);
$alert_ids = implode($separator,$alert_ids);
$labels = implode($separator,$labels);
if (!empty($long_index)) {
$labels_long = implode($separator, $long_index);
}
else {
$labels_long = $labels;
}
if (!empty($legend)) {
$legend = io_safe_output(implode($separator, $legend));
}
$serie_types = implode($separator, $serie_types2);
$colors = implode($separator, $colors);
// transform into string to pass to javascript
if ($force_integer) {
$force_integer = 'true';
}
else {
$force_integer = 'false';
}
//modify internal grid lines and legend text color
$extra_width = (int)($params['width'] / 3);
$return .= "<div id='extra_$graph_id'
style='font-size: " . $params['font_size'] . "pt;
display:none; position:absolute; overflow: auto;
max-height: ".($params['height']+50)."px;
width: ".$extra_width."px;
background:#fff; padding: 2px 2px 2px 2px;
border: solid #000 1px;'></div>";
if(substr($background_style, -6, 4) == '#fff'){
$background_color = "#eee";
$legend_color = "#151515";
}
else if(substr($background_style, -6, 4) == '#000'){
$background_color = "#151515";
@ -484,68 +255,119 @@ function flot_area_graph($chart_data, $width, $height, $color, $legend,
$background_color = "#A4A4A4";
$legend_color = "#A4A4A4";
}
// Trick to get translated string from javascript
$return .= html_print_input_hidden('unknown_text', __('Unknown'),
true);
if (!isset($config["short_module_graph_data"]))
$force_integer = 0;
// Trick to get translated string from javascript
$return .= html_print_input_hidden('unknown_text', __('Unknown'), true);
if (!isset($config["short_module_graph_data"])){
$config["short_module_graph_data"] = '';
}
$short_data = $config["short_module_graph_data"];
$values = json_encode($array_data);
$legend = json_encode($legend);
$series_type = json_encode($series_type);
$color = json_encode($color);
$date_array = json_encode($date_array);
$data_module_graph = json_encode($data_module_graph);
$params = json_encode($params);
$array_events_alerts = json_encode($array_events_alerts);
// Javascript code
if ($font_size == '') $font_size = '\'\'';
$return .= "<script type='text/javascript'>";
$return .= "$(document).ready( function () {";
$return .= "pandoraFlotArea(" .
"'$graph_id', \n" .
"'$values', \n" .
"'$labels', \n" .
"'$labels_long', \n" .
"'$legend', \n" .
"'$colors', \n" .
"'$type', \n" .
"'$serie_types', \n" .
"$watermark, \n" .
"$width, \n" .
"$max_x, \n" .
"'$homeurl', \n" .
"'$unit', \n" .
"$font_size, \n" .
"'$font', \n" .
"$menu, \n" .
"'$events', \n" .
"'$event_ids', \n" .
"'$legend_events', \n" .
"'$alerts', \n" .
"'$alert_ids', \n" .
"'$legend_alerts', \n" .
"'$yellow_threshold', \n" .
"'$red_threshold', \n" .
"JSON.parse('$values'), \n" .
"JSON.parse('$legend'), \n" .
"'$agent_module_id', \n" .
"JSON.parse('$series_type'), \n" .
"JSON.parse('$color'), \n" .
"'$watermark', \n" .
"JSON.parse('$date_array'), \n" .
"JSON.parse('$data_module_graph'), \n" .
"JSON.parse('$params'), \n" .
"$force_integer, \n" .
"'$separator', \n" .
"'$separator2', \n" .
"'$yellow_up', \n" .
"'$red_up', \n" .
"'$yellow_inverse', \n" .
"'$red_inverse', \n" .
"'$series_suffix_str',
" . json_encode($dashboard) . ",\n
" . json_encode($vconsole) . ",\n" .
"'$xaxisname', \n" .
"'$background_color', \n" .
"'$legend_color', \n" .
"'$short_data'
);";
"'$short_data', \n" .
"JSON.parse('$array_events_alerts')".
");";
$return .= "});";
$return .= "</script>";
// Parent layer
$return .= "</div>";
return $return;
}
function menu_graph(
$yellow_threshold, $red_threshold,
$yellow_up, $red_up, $yellow_inverse,
$red_inverse, $graph_id, $params
){
$return = '';
$threshold = false;
if ($yellow_threshold != $yellow_up || $red_threshold != $red_up) {
$threshold = true;
}
if ( $params['dashboard'] == false AND $params['vconsole'] == false) {
$return .= "<div id='general_menu_$graph_id' class='menu_graph' style='
width: 20px;
height: 150px;
left:100%;
position: absolute;
top: 0px;
background-color: tranparent;'>";
$return .= "<div id='menu_$graph_id' " .
"style='display: none; " .
"text-align: center;" .
"position: relative;".
"border-bottom: 0px;'>
<a href='javascript:'><img id='menu_cancelzoom_$graph_id' src='".$params['homeurl']."images/zoom_cross_grey.disabled.png' alt='".__('Cancel zoom')."' title='".__('Cancel zoom')."'></a>";
if ($threshold) {
$return .= " <a href='javascript:'><img id='menu_threshold_$graph_id' src='".$params['homeurl']."images/chart_curve_threshold.png' alt='".__('Warning and Critical thresholds')."' title='".__('Warning and Critical thresholds')."'></a>";
}
if($params['show_overview']){
$return .= " <a href='javascript:'>
<img id='menu_overview_$graph_id' class='menu_overview' src='" . $params['homeurl'] . "images/chart_curve_overview.png' alt='" . __('Overview graph') . "' title='".__('Overview graph')."'></a>";
}
// Export buttons
if($params['show_export_csv']){
$return .= " <a href='javascript:'><img id='menu_export_csv_$graph_id' src='".$params['homeurl']."images/csv_grey.png' alt='".__('Export to CSV')."' title='".__('Export to CSV')."'></a>";
}
// Button disabled. This feature works, but seems that is not useful enough to the final users.
//$return .= " <a href='javascript:'><img id='menu_export_json_$graph_id' src='".$homeurl."images/json.png' alt='".__('Export to JSON')."' title='".__('Export to JSON')."'></a>";
$return .= "</div>";
$return .= "</div>";
}
if ($params['dashboard']) {
$return .= "<div id='general_menu_$graph_id' class='menu_graph' style='
width: 30px;
height: 250px;
left: " . $params['width'] . "px;
position: absolute;
top: 0px;
background-color: white;'>";
$return .= "<div id='menu_$graph_id' " .
"style='display: none; " .
"text-align: center;" .
"position: relative;".
"border-bottom: 0px;'>
<a href='javascript:'><img id='menu_cancelzoom_$graph_id' src='".$params['homeurl']."images/zoom_cross_grey.disabled.png' alt='".__('Cancel zoom')."' title='".__('Cancel zoom')."'></a>";
$return .= "</div>";
$return .= "</div>";
}
return $return;
}
@ -882,10 +704,10 @@ function flot_slicesbar_graph ($graph_data, $period, $width, $height, $legend, $
// Set some containers to legend, graph, timestamp tooltip, etc.
if ($stat_win) {
$return = "<div id='$graph_id' class='noresizevc graph $adapt_key' style='width: ".$width."px; height: ".$height."px; display: inline-block;'></div>";
$return = "<div id='$graph_id' class='noresizevc graph $adapt_key' style='width: ".$width."%; height: ".$height."px; display: inline-block;'></div>";
}
else {
$return = "<div id='$graph_id' class='noresizevc graph $adapt_key' style='width: ".$width."px; height: ".$height."px;'></div>";
$return = "<div id='$graph_id' class='noresizevc graph $adapt_key' style='width: ".$width."%; height: ".$height."px;'></div>";
}
$return .= "<div id='value_$graph_id' style='display:none; position:absolute; background:#fff; border: solid 1px #aaa; padding: 2px'></div>";

View File

@ -382,14 +382,7 @@ switch ($graph_type) {
$font, $antialiasing, $rgb_color, $xaxisname, $yaxisname, false,
$legend, $fine_colors, $water_mark, $font_size);
break;
case 'stacked_area':
case 'area':
case 'line':
pch_vertical_graph($graph_type, $data_keys, $data_values, $width,
$height, $rgb_color, $xaxisname, $yaxisname, false, $legend,
$font, $antialiasing, $water_mark, $font_size,
$backgroundColor, $unit, $series_type, $graph_threshold, $id_module);
break;
default:
case 'threshold':
pch_threshold_graph($graph_type, $data_keys, $data_values, $width,
$height, $font, $antialiasing, $xaxisname, $yaxisname, $title,
@ -875,540 +868,6 @@ function pch_bar_graph ($graph_type, $index, $data, $width, $height, $font,
$myPicture->stroke();
}
function pch_vertical_graph ($graph_type, $index, $data, $width, $height,
$rgb_color = false, $xaxisname = "", $yaxisname = "", $show_values = false,
$legend = array(), $font, $antialiasing, $water_mark = '', $font_size,
$backgroundColor = 'white', $unit = '', $series_type = array(),
$graph_threshold = false, $id_module) {
global $config;
/* CAT:Vertical Charts */
if (!is_array($legend) || empty($legend)) {
unset($legend);
}
if (is_array(reset($data))) {
$data2 = array();
foreach ($data as $i =>$values) {
$c = 0;
foreach ($values as $i2 => $value) {
$data2[$i2][$i] = $value;
$c++;
}
}
$data = $data2;
}
else {
$data = array($data);
}
/* Create and populate the pData object */
$MyData = new pData();
foreach ($data as $i => $values) {
if (isset($legend)) {
$point_id = $legend[$i];
// Translate the id of serie to legend of id
if (!empty($series_type)) {
if (!isset($series_type[$point_id])) {
$series_type[$point_id] = $series_type[$i];
unset($series_type[$i]);
}
}
}
else {
$point_id = $i;
}
$MyData->addPoints($values, $point_id);
if (!empty($rgb_color)) {
$MyData->setPalette($point_id,
array(
"R" => $rgb_color[$i]['color']["R"],
"G" => $rgb_color[$i]['color']["G"],
"B" => $rgb_color[$i]['color']["B"],
"BorderR" => $rgb_color[$i]['border']["R"],
"BorderG" => $rgb_color[$i]['border']["G"],
"BorderB" => $rgb_color[$i]['border']["B"],
"Alpha" => $rgb_color[$i]['alpha']));
$palette_color = array();
if (isset($rgb_color[$i]['color'])) {
$palette_color["R"] = $rgb_color[$i]['color']["R"];
$palette_color["G"] = $rgb_color[$i]['color']["G"];
$palette_color["B"] = $rgb_color[$i]['color']["B"];
}
if (isset($rgb_color[$i]['color'])) {
$palette_color["BorderR"] = $rgb_color[$i]['border']["R"];
$palette_color["BorderG"] = $rgb_color[$i]['border']["G"];
$palette_color["BorderB"] = $rgb_color[$i]['border']["B"];
}
if (isset($rgb_color[$i]['color'])) {
$palette_color["Alpha"] = $rgb_color[$i]['Alpha'];
}
$MyData->setPalette($point_id, $palette_color);
}
// The weight of the line is not calculated in pixels, so it needs to be transformed
$reduction_coefficient = 0.31;
$MyData->setSerieWeight($point_id, $config['custom_graph_width'] * $reduction_coefficient);
}
$MyData->setAxisName(0,$unit);
$MyData->addPoints($index,"Xaxis");
$MyData->setSerieDescription("Xaxis", $xaxisname);
$MyData->setAbscissa("Xaxis");
$MyData->setAxisDisplay(0, AXIS_FORMAT_TWO_SIGNIFICANT, 0);
switch ($backgroundColor) {
case 'white':
$transparent = false;
$fontColor = array('R' => 0, 'G' => 0, 'B' => 0);
break;
case 'black':
$transparent = false;
$fontColor = array('R' => 200, 'G' => 200, 'B' => 200);
break;
case 'transparent':
$transparent = true;
// $fontColor = array('R' => 0, 'G' => 0, 'B' => 0);
// Now the color of the text will be grey
$fontColor = array('R' => 200, 'G' => 200, 'B' => 200);
break;
}
/* Create the pChart object */
$myPicture = new pImage($width, $height + $font_size, $MyData, $transparent,
$backgroundColor, $fontColor);
/* Turn of Antialiasing */
$myPicture->Antialias = $antialiasing;
/* Add a border to the picture */
//$myPicture->drawRectangle(0,0,$width,$height,array("R"=>0,"G"=>0,"B"=>0));
/* Set the default font */
$myPicture->setFontProperties(
array("FontName" =>$font, "FontSize" => $font_size));
// By default, set a top margin of 5 px
$top_margin = 5;
if (isset($legend)) {
/* Set horizontal legend if is posible */
$legend_mode = LEGEND_HORIZONTAL;
$size = $myPicture->getLegendSize(
array("Style" => LEGEND_NOBORDER,"Mode" => $legend_mode));
if ($size['Width'] > ($width - 5)) {
$legend_mode = LEGEND_VERTICAL;
$size = $myPicture->getLegendSize(array("Style"=>LEGEND_NOBORDER,"Mode"=>$legend_mode));
}
// Update the top margin to add the legend Height
$top_margin = $size['Height'];
/* Write the chart legend */
$myPicture->drawLegend($width - $size['Width'], 8,
array("Style" => LEGEND_NOBORDER, "Mode" => $legend_mode));
}
//Calculate the bottom margin from the size of string in each index
$max_chars = graph_get_max_index($index);
$margin_bottom = $font_size * $max_chars;
$water_mark_height = 0;
$water_mark_width = 0;
if (!empty($water_mark)) {
$size_water_mark = getimagesize($water_mark);
$water_mark_height = $size_water_mark[1];
$water_mark_width = $size_water_mark[0];
$myPicture->drawFromPNG(
($width - $water_mark_width),
$top_margin,
$water_mark);
}
// Get the max number of scale
$max_all = 0;
$serie_ne_zero = false;
foreach ($data as $serie) {
$max_this_serie = max($serie);
if ($max_this_serie > $max_all) {
$max_all = $max_this_serie;
}
// Detect if all serie is equal to zero or not
if ($serie != 0)
$serie_ne_zero = true;
}
// Get the number of digits of the scale
$digits_left = 0;
while ($max_all > 1) {
$digits_left ++;
$max_all /= 10;
}
// If the number is less than 1 we count the decimals
// Also check if the serie is not all equal to zero (!$serie_ne_zero)
if ($digits_left == 0 and !$serie_ne_zero) {
while($max_all < 1) {
$digits_left ++;
$max_all *= 10;
}
}
$chart_size = ($digits_left * $font_size) + 20;
$min_data = 0;
$max_data = 0;
foreach ($data as $k => $v) {
if(min($v) < $min_data){
$min_data = min($v);
}
if(max($v) > $max_data){
$max_data = max($v);
}
}
$chart_margin = 36;
/* Area depends on yaxisname */
if ($yaxisname != '') {
$chart_margin += $chart_size;
}
$myPicture->setGraphArea($chart_margin, $top_margin,
$width,
($height - $margin_bottom));
if($graph_threshold){
$sql_treshold = 'select min_critical, max_critical, min_warning, max_warning, critical_inverse, warning_inverse from tagente_modulo where id_agente_modulo =' . $id_module;
$treshold_position = db_get_all_rows_sql($sql_treshold);
//min, max and inverse critical and warning
$p_min_crit = $treshold_position[0]['min_critical'];
$p_max_crit = $treshold_position[0]['max_critical'];
$p_inv_crit = $treshold_position[0]['critical_inverse'];
$p_min_warn = $treshold_position[0]['min_warning'];
$p_max_warn = $treshold_position[0]['max_warning'];
$p_inv_warn = $treshold_position[0]['warning_inverse'];
//interval warning
$print_rectangle_warning = 1;
if($p_min_warn == "0.00" && $p_max_warn == "0.00" && $p_inv_warn == 0){
$print_rectangle_warning = 0;
}
if($print_rectangle_warning){
if($p_inv_warn){
if($p_max_warn == 0){
$p_max_warn = $p_min_warn;
$p_min_warn = "none";
}
else{
$p_max_warn_inv = $p_min_warn;
$p_min_warn_inv = $min_data + 2;
$p_min_warn = $p_max_warn;
if($p_max_warn > $max_data){
$p_max_warn = $p_max_warn + 21;
}
else{
$p_max_warn = $max_data + 21;
}
}
}
else{
if($p_max_warn == 0){
if($max_data > $p_min_warn){
$p_max_warn = $max_data + 21;
}
else{
$p_max_warn = $p_min_warn + 21;
}
}
}
}
//interval critical
$print_rectangle_critical = 1;
if($p_min_crit == "0.00" && $p_max_crit == "0.00" && $p_inv_crit == 0){
$print_rectangle_critical = 0;
}
if($print_rectangle_critical){
if($p_inv_crit){
if($p_max_crit == 0){
$p_max_crit = $p_min_crit;
$p_min_crit = "none";
}
else{
$p_max_crit_inv = $p_min_crit;
$p_min_crit_inv = $min_data + 2;
$p_min_crit = $p_max_crit;
if($p_inv_warn){
if($p_max_crit < $p_max_warn){
$p_max_crit = $p_max_warn;
}
}
else{
if($p_max_crit > $max_data){
$p_max_crit = $p_max_crit + 21;
}
else{
$p_max_crit = $max_data + 21;
}
}
}
}
else{
if($p_max_crit == 0){
if($p_max_warn > $p_min_crit){
$p_max_crit = $p_max_warn;
}
else{
if($max_data > $p_min_crit){
$p_max_crit = $max_data + 21;
}
else{
$p_max_crit = $p_min_crit + 21;
}
}
}
}
}
//Check size scale
//Which of the thresholds is higher?
if($p_max_crit > $p_max_warn){
$check_scale = $p_max_crit;
}
else{
$check_scale = $p_max_warn;
}
if($p_min_crit < $p_min_warn){
$check_scale_min = $p_min_crit;
}
else{
$check_scale_min = $p_min_warn;
}
//Is the threshold higher than our maximum?
if($max_data > $check_scale){
$check_scale = $max_data;
}
if($min_data < $check_scale_min){
$check_scale_min = $min_data;
}
$ManualScale = array( 0 => array("Min" => $check_scale_min, "Max" => $check_scale) );
$mode = SCALE_MODE_MANUAL;
/* Draw the scale */
$scaleSettings = array(
"GridR" => 200,
"GridG" => 200,
"GridB" => 200,
"GridAlpha" => 30,
"DrawSubTicks" => true,
"CycleBackground" => true,
"BackgroundAlpha1" => 35,
"BackgroundAlpha2" => 35,
"Mode" => $mode,
"ManualScale" => $ManualScale,
"LabelRotation" => 40,
"XMargin" => 0,
"MinDivHeight" => 15,
"TicksFontSize" => $font_size - 1);
$scaleSettings['AxisR'] = '200';
$scaleSettings['AxisG'] = '200';
$scaleSettings['AxisB'] = '200';
$scaleSettings['TickR'] = '200';
$scaleSettings['TickG'] = '200';
$scaleSettings['TickB'] = '200';
$myPicture->drawScale($scaleSettings);
//values
$scale_max = $myPicture->DataSet->Data["Axis"][0]["ScaleMax"];
$scale_min = $myPicture->DataSet->Data["Axis"][0]["ScaleMin"];
$position_y1 = $myPicture->GraphAreaY1;
$position_y2 = $myPicture->GraphAreaY2;
$position1 = $myPicture->GraphAreaX1;
$position3 = $myPicture->GraphAreaX2;
$cte = ($position_y2 - $position_y1) / ($scale_max - $scale_min);
//warning
if($print_rectangle_warning){
$RectangleSettings = array("R"=>255,"G"=>255,"B"=>000,"Dash"=>TRUE,"DashR"=>170,"DashG"=>220,"DashB"=>190);
if($p_min_warn == "none"){
$p_min_warn = $scale_min;
}
$position2 = ($scale_max - $p_min_warn)*$cte + $position_y1;
$position4 = ($scale_max - $p_max_warn)*$cte + $position_y1;
$myPicture->drawFilledRectangle($position1, floor($position2),
$position3, floor($position4),
$RectangleSettings);
if($p_inv_warn){
$position2 = ($scale_max - $p_min_warn_inv)*$cte + $position_y1;
$position4 = ($scale_max - $p_max_warn_inv)*$cte + $position_y1;
$myPicture->drawFilledRectangle($position1, floor($position2),
$position3, floor($position4),
$RectangleSettings);
}
}
//critical
if($print_rectangle_critical){
$RectangleSettings = array("R"=>248,"G"=>000,"B"=>000,"Dash"=>TRUE,"DashR"=>170,"DashG"=>220,"DashB"=>190);
if($p_min_crit == "none"){
$p_min_crit = $scale_min;
}
$position2 = ($scale_max - $p_min_crit)*$cte + $position_y1;
$position4 = ($scale_max - $p_max_crit)*$cte + $position_y1;
$myPicture->drawFilledRectangle($position1, $position2,
$position3, $position4,
$RectangleSettings);
if($p_inv_crit){
$position2 = ($scale_max - $p_min_crit_inv)*$cte + $position_y1;
$position4 = ($scale_max - $p_max_crit_inv)*$cte + $position_y1;
$myPicture->drawFilledRectangle($position1, $position2,
$position3, $position4,
$RectangleSettings);
}
}
}
else{
$ManualScale = array( 0 => array(
"Min" => $min_data,
"Max" => $max_data
));
//html_debug("MAX: $max_data, ROUND: $max_round", true);
$mode = SCALE_MODE_MANUAL;
/* Draw the scale */
$scaleSettings = array(
"GridR" => 200,
"GridG" => 200,
"GridB" => 200,
"GridAlpha" => 30,
"DrawSubTicks" => true,
"CycleBackground" => true,
"BackgroundAlpha1" => 35,
"BackgroundAlpha2" => 35,
"Mode" => $mode,
"ManualScale" => $ManualScale,
"LabelRotation" => 40,
"XMargin" => 0,
"MinDivHeight" => 15,
"TicksFontSize" => $font_size - 1);
$scaleSettings['AxisR'] = '200';
$scaleSettings['AxisG'] = '200';
$scaleSettings['AxisB'] = '200';
$scaleSettings['TickR'] = '200';
$scaleSettings['TickG'] = '200';
$scaleSettings['TickB'] = '200';
$myPicture->drawScale($scaleSettings);
}
/* Turn on shadow computing */
//$myPicture->setShadow(TRUE,array("X"=>0,"Y"=>1,"R"=>0,"G"=>0,"B"=>0,"Alpha"=>10));
switch ($graph_type) {
case 'stacked_area':
$ForceTransparency = "-1";
break;
default:
$ForceTransparency = "100";
break;
}
/* Draw the chart */
$settings = array(
"ForceTransparency" => 20,
"Gradient" => TRUE,
"GradientMode" => GRADIENT_EFFECT_CAN,
"DisplayValues" => $show_values,
"DisplayZeroValues" => FALSE,
"DisplayR" => 100,
"DisplayZeros" => FALSE,
"DisplayG" => 100,
"DisplayB" => 100,
"DisplayShadow" => TRUE,
"Surrounding" => 5,
"AroundZero" => TRUE);
if (empty($series_type)) {
switch($graph_type) {
case "stacked_area":
case "area":
$myPicture->drawAreaChart($settings);
break;
case "line":
$myPicture->drawLineChart($settings);
break;
}
}
else {
// Hiden all series for to show each serie as type
foreach ($series_type as $id => $type) {
$MyData->setSerieDrawable($id, false);
}
foreach ($series_type as $id => $type) {
$MyData->setSerieDrawable($id, true); //Enable the serie to paint
switch ($type) {
default:
case 'area':
$myPicture->drawAreaChart($settings);
break;
//~ case "points":
//~ $myPicture->drawPlotChart($settings);
//~ break;
case "line":
$myPicture->drawLineChart($settings);
break;
case 'boolean':
switch($graph_type) {
case "stacked_area":
case "area":
$myPicture->drawFilledStepChart($settings);
break;
case "line":
$myPicture->drawStepChart($settings);
break;
}
break;
}
$MyData->setSerieDrawable($id, false); //Disable the serie to paint the rest
}
}
/* Render the picture */
$myPicture->stroke();
}
function pch_threshold_graph ($graph_type, $index, $data, $width, $height, $font,
$antialiasing, $xaxisname = "", $yaxisname = "", $title = "",
$show_values = false, $show_legend = false, $font_size) {

View File

@ -1758,6 +1758,12 @@
$SkippedTickAlpha = isset($Format["SkippedTickAlpha"]) ? $Format["SkippedTickAlpha"] : $TickAlpha-80;
$SkippedInnerTickWidth = isset($Format["SkippedInnerTickWidth"]) ? $Format["SkippedInnerTickWidth"] : 0;
$SkippedOuterTickWidth = isset($Format["SkippedOuterTickWidth"]) ? $Format["SkippedOuterTickWidth"] : 2;
$ScaleModeAuto = isset($Format["ScaleModeAuto"]) ? $Format["ScaleModeAuto"] : FALSE;
$LabelSkipOffset = isset($Format["LabelSkipOffset"]) ? $Format["LabelSkipOffset"] : 0;
$LabelShowBoundaries = isset($Format["LabelShowBoundaries"]) ? $Format["LabelShowBoundaries"] : FALSE;
$DrawXBoundaryLines = isset($Format["DrawXBoundaryLines"]) ? $Format["DrawXBoundaryLines"] : FALSE;
$ScaleModeAutoGridInterval = isset($Format["ScaleModeAutoGridInterval"]) ? $Format["ScaleModeAutoGridInterval"] : 0;
$ScaleModeAutoGridLabel = isset($Format["ScaleModeAutoGridLabel"]) ? $Format["ScaleModeAutoGridLabel"] : FALSE;
/* Floating scale require X & Y margins to be set manually */
if ( $Floating && ( $XMargin == AUTO || $YMargin == 0 ) ) { $Floating = FALSE; }
@ -1884,8 +1890,10 @@
{
$Points = 0;
$AxisName = isset($Data["XAxisName"]) ? $Data["XAxisName"] : NULL;
foreach($Data["Series"] as $SerieID => $SerieParameter)
{ if ( $SerieParameter["isDrawable"] ) { $Points = max($Points,count($SerieParameter["Data"])); } }
if (count($Data["Series"]) > 0) {
foreach($Data["Series"] as $SerieID => $SerieParameter)
{ if ( $SerieParameter["isDrawable"] ) { $Points = max($Points,count($SerieParameter["Data"])); } }
}
}
$AxisID = count($Data["Axis"]);
@ -1901,7 +1909,7 @@
if ( $Points == 1 )
$Data["Axis"][$AxisID]["Margin"] = $Height / 2;
else
else if ($Points > 1)
$Data["Axis"][$AxisID]["Margin"] = ($Height/$Points) / 2;
}
else
@ -1938,6 +1946,24 @@
{
if ( $Pos == SCALE_POS_LEFTRIGHT )
{
$Width = ($this->GraphAreaX2 - $this->GraphAreaX1) - $Parameters["Margin"]*2;
if ( $ScaleModeAuto && isset($Data["Series"][$Abscissa]["Data"][0]) ) {
$AbscissaScaleValueMin = $Data["Series"][$Abscissa]["Data"][0];
} else {
$AbscissaScaleValueMin = 0;
}
if ( $ScaleModeAuto && isset($Data["Series"][$Abscissa]["Data"][$Parameters["Rows"]]) ) {
$AbscissaScaleValueMax = $Data["Series"][$Abscissa]["Data"][$Parameters["Rows"]];
} else {
$AbscissaScaleValueMax = $Width;
}
$AbscissaScaleValueWidth = $AbscissaScaleValueMax - $AbscissaScaleValueMin;
if ($AbscissaScaleValueWidth > 0)
$AbscissaScaleFactor = $AbscissaScaleValueWidth / $Width;
else
$AbscissaScaleFactor = 1;
if ( $Parameters["Position"] == AXIS_POSITION_BOTTOM )
{
if ( $LabelRotation == 0 ) { $LabelAlign = TEXT_ALIGN_TOPMIDDLE; $YLabelOffset = 2; }
@ -1951,15 +1977,23 @@
{ $FloatingOffset = 0; $this->drawLine($this->GraphAreaX1,$AxisPos["B"],$this->GraphAreaX2,$AxisPos["B"],array("R"=>$AxisR,"G"=>$AxisG,"B"=>$AxisB,"Alpha"=>$AxisAlpha)); }
if ( $DrawArrows ) { $this->drawArrow($this->GraphAreaX2-$Parameters["Margin"],$AxisPos["B"],$this->GraphAreaX2+($ArrowSize*2),$AxisPos["B"],array("FillR"=>$AxisR,"FillG"=>$AxisG,"FillB"=>$AxisB,"Size"=>$ArrowSize)); }
$Width = ($this->GraphAreaX2 - $this->GraphAreaX1) - $Parameters["Margin"]*2;
if ($Parameters["Rows"] == 0 ) { $Step = $Width; } else { $Step = $Width / ($Parameters["Rows"]); }
$MaxBottom = $AxisPos["B"];
for($i=0;$i<=$Parameters["Rows"];$i++)
{
$XPos = $this->GraphAreaX1 + $Parameters["Margin"] + $Step*$i;
if ( $ScaleModeAuto && $Abscissa != NULL ) {
if ( isset($Data["Series"][$Abscissa]["Data"][$i]) ) {
$AbscissaScaleValue = $Data["Series"][$Abscissa]["Data"][$i] - $AbscissaScaleValueMin;
$XPos = $this->GraphAreaX1 + $Parameters["Margin"] + $AbscissaScaleValue / $AbscissaScaleFactor;
} else {
$XPos = $this->GraphAreaX1 + $Parameters["Margin"] + $Step*$i;
}
} else {
$XPos = $this->GraphAreaX1 + $Parameters["Margin"] + $Step*$i;
}
$YPos = $AxisPos["B"];
if ( $Abscissa != NULL )
@ -1973,7 +2007,7 @@
}
$ID++; $Skipped = TRUE;
if ( $this->isValidLabel($Value,$LastValue,$LabelingMethod,$ID,$LabelSkip) )
if ( ($LabelShowBoundaries && ($i==0 || $i==$Parameters["Rows"])) || $this->isValidLabel($Value,$LastValue,$LabelingMethod,$ID,$LabelSkip,$LabelSkipOffset) )
{
$Bounds = $this->drawText($XPos,$YPos+$OuterTickWidth+$YLabelOffset,$Value,array("FontSize"=>$TicksFontSize,"Angle"=>$LabelRotation,"Align"=>$LabelAlign));
$TxtBottom = $YPos+$OuterTickWidth+2+($Bounds[0]["Y"]-$Bounds[2]["Y"]);
@ -1981,7 +2015,12 @@
$LastValue = $Value;
$Skipped = FALSE;
}
if ( $DrawXBoundaryLines && ($i==0 || $i==$Parameters["Rows"]) )
{
$this->drawLine($XPos,$this->GraphAreaY1+$FloatingOffset,$XPos,$this->GraphAreaY2-$FloatingOffset,array("R"=>$GridR,"G"=>$GridG,"B"=>$GridB,"Alpha"=>$GridAlpha,"Ticks"=>$GridTicks));
}
if ( $Skipped )
{
if ( $DrawXLines ) { $this->drawLine($XPos,$this->GraphAreaY1+$FloatingOffset,$XPos,$this->GraphAreaY2-$FloatingOffset,$SkippedAxisColor); }
@ -2002,6 +2041,31 @@
}
}
if ( $ScaleModeAuto && ($ScaleModeAutoGridInterval > 0) )
{
$ScaleModeAutoGridIntervalDraw = true;
$ScaleModeAutoGridIntervalStep = 0;
while ($ScaleModeAutoGridIntervalDraw) {
$ScaleModeAutoGridIntervalStep++;
$ScaleModeAutoGridIntervalValue = $ScaleModeAutoGridIntervalStep*$ScaleModeAutoGridInterval;
if ($ScaleModeAutoGridIntervalValue < ($AbscissaScaleValueMax-$AbscissaScaleValueMin)) {
$ScaleModeAutoGridIntervalX = $this->GraphAreaX1 + $Parameters["Margin"] + $ScaleModeAutoGridIntervalValue / $AbscissaScaleFactor;
$this->drawLine($ScaleModeAutoGridIntervalX,$this->GraphAreaY1+$FloatingOffset,$ScaleModeAutoGridIntervalX,$this->GraphAreaY2-$FloatingOffset,array("R"=>$GridR,"G"=>$GridG,"B"=>$GridB,"Alpha"=>$GridAlpha,"Ticks"=>$GridTicks));
if ($ScaleModeAutoGridLabel) {
$ScaleModeAutoGridLabelDescription = $this->scaleFormat($AbscissaScaleValueMin+$ScaleModeAutoGridIntervalValue,$Data["XAxisDisplay"],$Data["XAxisFormat"],"");
$this->drawText($ScaleModeAutoGridIntervalX,$this->GraphAreaY1+$FloatingOffset+5,$ScaleModeAutoGridLabelDescription,array("Align"=>TEXT_ALIGN_MIDDLERIGHT,"Angle"=>90,"R"=>$GridR,"G"=>$GridG,"B"=>$GridB,"Alpha"=>floor($GridAlpha*2)));
}
} else {
$ScaleModeAutoGridIntervalDraw = false;
}
}
}
if ( isset($Parameters["Name"]) )
{
$YPos = $MaxBottom+2;
@ -2027,15 +2091,22 @@
{ $FloatingOffset = 0; $this->drawLine($this->GraphAreaX1,$AxisPos["T"],$this->GraphAreaX2,$AxisPos["T"],array("R"=>$AxisR,"G"=>$AxisG,"B"=>$AxisB,"Alpha"=>$AxisAlpha)); }
if ( $DrawArrows ) { $this->drawArrow($this->GraphAreaX2-$Parameters["Margin"],$AxisPos["T"],$this->GraphAreaX2+($ArrowSize*2),$AxisPos["T"],array("FillR"=>$AxisR,"FillG"=>$AxisG,"FillB"=>$AxisB,"Size"=>$ArrowSize)); }
$Width = ($this->GraphAreaX2 - $this->GraphAreaX1) - $Parameters["Margin"]*2;
if ($Parameters["Rows"] == 0 ) { $Step = $Width; } else { $Step = $Width / $Parameters["Rows"]; }
$MinTop = $AxisPos["T"];
for($i=0;$i<=$Parameters["Rows"];$i++)
{
$XPos = $this->GraphAreaX1 + $Parameters["Margin"] + $Step*$i;
if ( $ScaleModeAuto && $Abscissa != NULL ) {
if ( isset($Data["Series"][$Abscissa]["Data"][$i]) ) {
$AbscissaScaleValue = $Data["Series"][$Abscissa]["Data"][$i] - $AbscissaScaleValueMin;
$XPos = $this->GraphAreaX1 + $Parameters["Margin"] + $AbscissaScaleValue / $AbscissaScaleFactor;
} else {
$XPos = $this->GraphAreaX1 + $Parameters["Margin"] + $Step*$i;
}
} else {
$XPos = $this->GraphAreaX1 + $Parameters["Margin"] + $Step*$i;
}
$YPos = $AxisPos["T"];
if ( $Abscissa != NULL )
@ -2049,7 +2120,7 @@
}
$ID++; $Skipped = TRUE;
if ( $this->isValidLabel($Value,$LastValue,$LabelingMethod,$ID,$LabelSkip) )
if ( ($LabelShowBoundaries && ($i==0 || $i==$Parameters["Rows"])) || $this->isValidLabel($Value,$LastValue,$LabelingMethod,$ID,$LabelSkip,$LabelSkipOffset) )
{
$Bounds = $this->drawText($XPos,$YPos-$OuterTickWidth-$YLabelOffset,$Value,array("Angle"=>$LabelRotation,"Align"=>$LabelAlign));
$TxtBox = $YPos-$OuterTickWidth-2-($Bounds[0]["Y"]-$Bounds[2]["Y"]);
@ -2057,6 +2128,11 @@
$LastValue = $Value;
$Skipped = FALSE;
}
if ( $DrawXBoundaryLines && ($i==0 || $i==$Parameters["Rows"]) )
{
$this->drawLine($XPos,$this->GraphAreaY1+$FloatingOffset,$XPos,$this->GraphAreaY2-$FloatingOffset,array("R"=>$GridR,"G"=>$GridG,"B"=>$GridB,"Alpha"=>$GridAlpha,"Ticks"=>$GridTicks));
}
if ( $Skipped )
{
@ -2070,6 +2146,31 @@
}
}
if ( $ScaleModeAuto && ($ScaleModeAutoGridInterval > 0) )
{
$ScaleModeAutoGridIntervalDraw = true;
$ScaleModeAutoGridIntervalStep = 0;
while ($ScaleModeAutoGridIntervalDraw) {
$ScaleModeAutoGridIntervalStep++;
$ScaleModeAutoGridIntervalValue = $ScaleModeAutoGridIntervalStep*$ScaleModeAutoGridInterval;
if ($ScaleModeAutoGridIntervalValue < ($AbscissaScaleValueMax-$AbscissaScaleValueMin)) {
$ScaleModeAutoGridIntervalX = $this->GraphAreaX1 + $Parameters["Margin"] + $ScaleModeAutoGridIntervalValue / $AbscissaScaleFactor;
$this->drawLine($ScaleModeAutoGridIntervalX,$this->GraphAreaY1+$FloatingOffset,$ScaleModeAutoGridIntervalX,$this->GraphAreaY2-$FloatingOffset,array("R"=>$GridR,"G"=>$GridG,"B"=>$GridB,"Alpha"=>$GridAlpha,"Ticks"=>$GridTicks));
if ($ScaleModeAutoGridLabel) {
$ScaleModeAutoGridLabelDescription = $this->scaleFormat($AbscissaScaleValueMin+$ScaleModeAutoGridIntervalValue,$Data["XAxisDisplay"],$Data["XAxisFormat"],"");
$this->drawText($ScaleModeAutoGridIntervalX,$this->GraphAreaY1+$FloatingOffset+5,$ScaleModeAutoGridLabelDescription,array("Align"=>TEXT_ALIGN_MIDDLERIGHT,"Angle"=>90,"R"=>$GridR,"G"=>$GridG,"B"=>$GridB,"Alpha"=>floor($GridAlpha*2)));
}
} else {
$ScaleModeAutoGridIntervalDraw = false;
}
}
}
if ( isset($Parameters["Name"]) )
{
$YPos = $MinTop-2;
@ -2085,6 +2186,21 @@
}
elseif ( $Pos == SCALE_POS_TOPBOTTOM )
{
$Height = ($this->GraphAreaY2 - $this->GraphAreaY1) - $Parameters["Margin"]*2;
if ( $ScaleModeAuto && isset($Data["Series"][$Abscissa]["Data"][0]) ) {
$AbscissaScaleValueMin = $Data["Series"][$Abscissa]["Data"][0];
} else {
$AbscissaScaleValueMin = 0;
}
if ( $ScaleModeAuto && isset($Data["Series"][$Abscissa]["Data"][$Parameters["Rows"]]) ) {
$AbscissaScaleValueMax = $Data["Series"][$Abscissa]["Data"][$Parameters["Rows"]];
} else {
$AbscissaScaleValueMax = $Height;
}
$AbscissaScaleValueWidth = $AbscissaScaleValueMax - $AbscissaScaleValueMin;
$AbscissaScaleFactor = $AbscissaScaleValueWidth / $Height;
if ( $Parameters["Position"] == AXIS_POSITION_LEFT )
{
if ( $LabelRotation == 0 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $XLabelOffset = -2; }
@ -2098,15 +2214,22 @@
{ $FloatingOffset = 0; $this->drawLine($AxisPos["L"],$this->GraphAreaY1,$AxisPos["L"],$this->GraphAreaY2,array("R"=>$AxisR,"G"=>$AxisG,"B"=>$AxisB,"Alpha"=>$AxisAlpha)); }
if ( $DrawArrows ) { $this->drawArrow($AxisPos["L"],$this->GraphAreaY2-$Parameters["Margin"],$AxisPos["L"],$this->GraphAreaY2+($ArrowSize*2),array("FillR"=>$AxisR,"FillG"=>$AxisG,"FillB"=>$AxisB,"Size"=>$ArrowSize)); }
$Height = ($this->GraphAreaY2 - $this->GraphAreaY1) - $Parameters["Margin"]*2;
if ($Parameters["Rows"] == 0 ) { $Step = $Height; } else { $Step = $Height / $Parameters["Rows"]; }
$MinLeft = $AxisPos["L"];
for($i=0;$i<=$Parameters["Rows"];$i++)
{
$YPos = $this->GraphAreaY1 + $Parameters["Margin"] + $Step*$i;
if ( $ScaleModeAuto && $Abscissa != NULL ) {
if ( isset($Data["Series"][$Abscissa]["Data"][$i]) ) {
$AbscissaScaleValue = $Data["Series"][$Abscissa]["Data"][$i] - $AbscissaScaleValueMin;
$YPos = $this->GraphAreaY1 + $Parameters["Margin"] + $AbscissaScaleValue / $AbscissaScaleFactor;
} else {
$YPos = $this->GraphAreaY1 + $Parameters["Margin"] + $Step*$i;
}
} else {
$YPos = $this->GraphAreaY1 + $Parameters["Margin"] + $Step*$i;
}
$XPos = $AxisPos["L"];
if ( $Abscissa != NULL )
@ -2120,7 +2243,7 @@
}
$ID++; $Skipped = TRUE;
if ( $this->isValidLabel($Value,$LastValue,$LabelingMethod,$ID,$LabelSkip) )
if ( ($LabelShowBoundaries && ($i==0 || $i==$Parameters["Rows"])) || $this->isValidLabel($Value,$LastValue,$LabelingMethod,$ID,$LabelSkip,$LabelSkipOffset) )
{
$Bounds = $this->drawText($XPos-$OuterTickWidth+$XLabelOffset,$YPos,$Value,array("Angle"=>$LabelRotation,"Align"=>$LabelAlign));
$TxtBox = $XPos-$OuterTickWidth-2-($Bounds[1]["X"]-$Bounds[0]["X"]);
@ -2128,6 +2251,11 @@
$LastValue = $Value;
$Skipped = FALSE;
}
if ( $DrawXBoundaryLines && ($i==0 || $i==$Parameters["Rows"]) )
{
$this->drawLine($this->GraphAreaX1+$FloatingOffset,$YPos,$this->GraphAreaX2-$FloatingOffset,$YPos,array("R"=>$GridR,"G"=>$GridG,"B"=>$GridB,"Alpha"=>$GridAlpha,"Ticks"=>$GridTicks));
}
if ( $Skipped )
{
@ -2141,6 +2269,31 @@
}
}
if ( $ScaleModeAuto && ($ScaleModeAutoGridInterval > 0) )
{
$ScaleModeAutoGridIntervalDraw = true;
$ScaleModeAutoGridIntervalStep = 0;
while ($ScaleModeAutoGridIntervalDraw) {
$ScaleModeAutoGridIntervalStep++;
$ScaleModeAutoGridIntervalValue = $ScaleModeAutoGridIntervalStep*$ScaleModeAutoGridInterval;
if ($ScaleModeAutoGridIntervalValue < ($AbscissaScaleValueMax-$AbscissaScaleValueMin)) {
$ScaleModeAutoGridIntervalY = $this->GraphAreaY1 + $Parameters["Margin"] + $ScaleModeAutoGridIntervalValue / $AbscissaScaleFactor;
$this->drawLine($this->GraphAreaX1+$FloatingOffset,$ScaleModeAutoGridIntervalY,$this->GraphAreaX2-$FloatingOffset,$ScaleModeAutoGridIntervalY,array("R"=>$GridR,"G"=>$GridG,"B"=>$GridB,"Alpha"=>$GridAlpha,"Ticks"=>$GridTicks));
if ($ScaleModeAutoGridLabel) {
$ScaleModeAutoGridLabelDescription = $this->scaleFormat($AbscissaScaleValueMin+$ScaleModeAutoGridIntervalValue,$Data["XAxisDisplay"],$Data["XAxisFormat"],"");
$this->drawText($this->GraphAreaX2+$FloatingOffset-5,$ScaleModeAutoGridIntervalY,$ScaleModeAutoGridLabelDescription,array("Align"=>TEXT_ALIGN_MIDDLERIGHT,"Angle"=>0,"R"=>$GridR,"G"=>$GridG,"B"=>$GridB,"Alpha"=>floor($GridAlpha*2)));
}
} else {
$ScaleModeAutoGridIntervalDraw = false;
}
}
}
if ( isset($Parameters["Name"]) )
{
$XPos = $MinLeft-2;
@ -2167,14 +2320,21 @@
if ( $DrawArrows ) { $this->drawArrow($AxisPos["R"],$this->GraphAreaY2-$Parameters["Margin"],$AxisPos["R"],$this->GraphAreaY2+($ArrowSize*2),array("FillR"=>$AxisR,"FillG"=>$AxisG,"FillB"=>$AxisB,"Size"=>$ArrowSize)); }
$Height = ($this->GraphAreaY2 - $this->GraphAreaY1) - $Parameters["Margin"]*2;
if ($Parameters["Rows"] == 0 ) { $Step = $Height; } else { $Step = $Height / $Parameters["Rows"]; }
$MaxRight = $AxisPos["R"];
for($i=0;$i<=$Parameters["Rows"];$i++)
{
$YPos = $this->GraphAreaY1 + $Parameters["Margin"] + $Step*$i;
if ( $ScaleModeAuto && $Abscissa != NULL ) {
if ( isset($Data["Series"][$Abscissa]["Data"][$i]) ) {
$AbscissaScaleValue = $Data["Series"][$Abscissa]["Data"][$i] - $AbscissaScaleValueMin;
$YPos = $this->GraphAreaY1 + $Parameters["Margin"] + $AbscissaScaleValue / $AbscissaScaleFactor;
} else {
$YPos = $this->GraphAreaY1 + $Parameters["Margin"] + $Step*$i;
}
} else {
$YPos = $this->GraphAreaY1 + $Parameters["Margin"] + $Step*$i;
}
$XPos = $AxisPos["R"];
if ( $Abscissa != NULL )
@ -2188,7 +2348,7 @@
}
$ID++; $Skipped = TRUE;
if ( $this->isValidLabel($Value,$LastValue,$LabelingMethod,$ID,$LabelSkip) )
if ( ($LabelShowBoundaries && ($i==0 || $i==$Parameters["Rows"])) || $this->isValidLabel($Value,$LastValue,$LabelingMethod,$ID,$LabelSkip,$LabelSkipOffset) )
{
$Bounds = $this->drawText($XPos+$OuterTickWidth+$XLabelOffset,$YPos,$Value,array("Angle"=>$LabelRotation,"Align"=>$LabelAlign));
$TxtBox = $XPos+$OuterTickWidth+2+($Bounds[1]["X"]-$Bounds[0]["X"]);
@ -2196,6 +2356,11 @@
$LastValue = $Value;
$Skipped = FALSE;
}
if ( $DrawXBoundaryLines && ($i==0 || $i==$Parameters["Rows"]) )
{
$this->drawLine($this->GraphAreaX1+$FloatingOffset,$YPos,$this->GraphAreaX2-$FloatingOffset,$YPos,array("R"=>$GridR,"G"=>$GridG,"B"=>$GridB,"Alpha"=>$GridAlpha,"Ticks"=>$GridTicks));
}
if ( $Skipped )
{
@ -2209,6 +2374,31 @@
}
}
if ( $ScaleModeAuto && ($ScaleModeAutoGridInterval > 0) )
{
$ScaleModeAutoGridIntervalDraw = true;
$ScaleModeAutoGridIntervalStep = 0;
while ($ScaleModeAutoGridIntervalDraw) {
$ScaleModeAutoGridIntervalStep++;
$ScaleModeAutoGridIntervalValue = $ScaleModeAutoGridIntervalStep*$ScaleModeAutoGridInterval;
if ($ScaleModeAutoGridIntervalValue < ($AbscissaScaleValueMax-$AbscissaScaleValueMin)) {
$ScaleModeAutoGridIntervalY = $this->GraphAreaY1 + $Parameters["Margin"] + $ScaleModeAutoGridIntervalValue / $AbscissaScaleFactor;
$this->drawLine($this->GraphAreaX1+$FloatingOffset,$ScaleModeAutoGridIntervalY,$this->GraphAreaX2-$FloatingOffset,$ScaleModeAutoGridIntervalY,array("R"=>$GridR,"G"=>$GridG,"B"=>$GridB,"Alpha"=>$GridAlpha,"Ticks"=>$GridTicks));
if ($ScaleModeAutoGridLabel) {
$ScaleModeAutoGridLabelDescription = $this->scaleFormat($AbscissaScaleValueMin+$ScaleModeAutoGridIntervalValue,$Data["XAxisDisplay"],$Data["XAxisFormat"],"");
$this->drawText($this->GraphAreaX2+$FloatingOffset-5,$ScaleModeAutoGridIntervalY,$ScaleModeAutoGridLabelDescription,array("Align"=>TEXT_ALIGN_MIDDLERIGHT,"Angle"=>0,"R"=>$GridR,"G"=>$GridG,"B"=>$GridB,"Alpha"=>floor($GridAlpha*2)));
}
} else {
$ScaleModeAutoGridIntervalDraw = false;
}
}
}
if ( isset($Parameters["Name"]) )
{
$XPos = $MaxRight+4;
@ -2433,12 +2623,12 @@
}
}
function isValidLabel($Value,$LastValue,$LabelingMethod,$ID,$LabelSkip)
function isValidLabel($Value,$LastValue,$LabelingMethod,$ID,$LabelSkip,$LabelSkipOffset=0)
{
if ( $LabelingMethod == LABELING_DIFFERENT && $Value != $LastValue ) { return(TRUE); }
if ( $LabelingMethod == LABELING_DIFFERENT && $Value == $LastValue ) { return(FALSE); }
if ( $LabelingMethod == LABELING_ALL && $LabelSkip == 1 ) { return(TRUE); }
if ( $LabelingMethod == LABELING_ALL && ($ID+$LabelSkip) % ($LabelSkip+1) != 1 ) { return(FALSE); }
if ( $LabelingMethod == LABELING_ALL && $LabelSkip == 0 ) { return(TRUE); }
if ( $LabelingMethod == LABELING_ALL && ($ID+$LabelSkip+$LabelSkipOffset) % ($LabelSkip+1) != 1 ) { return(FALSE); }
return(TRUE);
}
@ -3456,6 +3646,7 @@
$DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
$DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
$DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
$ScaleModeAuto = isset($Format["ScaleModeAuto"]) ? $Format["ScaleModeAuto"] : FALSE;
$Data = $this->DataSet->getData();
list($XMargin,$XDivs) = $this->scaleGetXSettings();
@ -3481,7 +3672,32 @@
$PosArray = $this->scaleComputeY($Serie["Data"],array("AxisID"=>$Serie["Axis"]));
$this->DataSet->Data["Series"][$SerieName]["XOffset"] = 0;
$Width = $this->GraphAreaX2-$this->GraphAreaX1-$XMargin*2;
$Height = $this->GraphAreaY2-$this->GraphAreaY1-$XMargin*2;
if ( $ScaleModeAuto && isset($Data["Series"][$Data["Abscissa"]]["Data"][0]) ) {
$AbscissaScaleValueMin = $Data["Series"][$Data["Abscissa"]]["Data"][0];
} else {
$AbscissaScaleValueMin = 0;
}
if ( $ScaleModeAuto && isset($Data["Series"][$Data["Abscissa"]]["Data"][$XDivs]) ) {
$AbscissaScaleValueMax = $Data["Series"][$Data["Abscissa"]]["Data"][$XDivs];
} else {
$AbscissaScaleValueMax = $Width;
}
$AbscissaScaleValueWidth = $AbscissaScaleValueMax - $AbscissaScaleValueMin;
if ( $Data["Orientation"] == SCALE_POS_LEFTRIGHT ) {
if ($AbscissaScaleValueWidth > 0)
$AbscissaScaleFactor = $AbscissaScaleValueWidth / $Width;
else
$AbscissaScaleFactor = 1;
} else {
if ($AbscissaScaleValueWidth > 0)
$AbscissaScaleFactor = $AbscissaScaleValueWidth / $Height;
else
$AbscissaScaleFactor = 1;
}
if ( $Data["Orientation"] == SCALE_POS_LEFTRIGHT )
{
if ( $XDivs == 0 ) { $XStep = ($this->GraphAreaX2-$this->GraphAreaX1)/4; } else { $XStep = ($this->GraphAreaX2-$this->GraphAreaX1-$XMargin*2)/$XDivs; }
@ -3491,6 +3707,11 @@
$LastGoodY = NULL; $LastGoodX = NULL; $Init = FALSE;
foreach($PosArray as $Key => $Y)
{
if ($ScaleModeAuto) {
$AbscissaScaleValue = $Data["Series"][$Data["Abscissa"]]["Data"][$Key] - $AbscissaScaleValueMin;
$X = $this->GraphAreaX1 + $XMargin + $AbscissaScaleValue / $AbscissaScaleFactor;
}
if ( $DisplayValues && $Serie["Data"][$Key] != VOID )
{
if ( $Y <= $LastY ) { $Align = TEXT_ALIGN_BOTTOMMIDDLE; $Offset = $DisplayOffset; } else { $Align = TEXT_ALIGN_TOPMIDDLE; $Offset = -$DisplayOffset; }
@ -3523,7 +3744,10 @@
if ( !$Init && $ReCenter ) { $X = $X - $XStep/2; $Init = TRUE; }
$LastX = $X; $LastY = $Y;
if ( $LastX < $this->GraphAreaX1 + $XMargin ) { $LastX = $this->GraphAreaX1 + $XMargin; }
$X = $X + $XStep;
if (!$ScaleModeAuto) {
$X = $X + $XStep;
}
}
if ( $ReCenter ) { $this->drawLine($LastX,$LastY,$this->GraphAreaX2 - $XMargin,$LastY,$Color); }
}
@ -3536,6 +3760,11 @@
$LastGoodY = NULL; $LastGoodX = NULL; $Init = FALSE;
foreach($PosArray as $Key => $X)
{
if ($ScaleModeAuto) {
$AbscissaScaleValue = $Data["Series"][$Data["Abscissa"]]["Data"][$Key] - $AbscissaScaleValueMin;
$Y = $this->GraphAreaY1 + $XMargin + $AbscissaScaleValue / $AbscissaScaleFactor;
}
if ( $DisplayValues && $Serie["Data"][$Key] != VOID )
{
if ( $X >= $LastX ) { $Align = TEXT_ALIGN_MIDDLELEFT; $Offset = $DisplayOffset; } else { $Align = TEXT_ALIGN_MIDDLERIGHT; $Offset = -$DisplayOffset; }
@ -3565,7 +3794,10 @@
if ( !$Init && $ReCenter ) { $Y = $Y - $YStep/2; $Init = TRUE; }
$LastX = $X; $LastY = $Y;
if ( $LastY < $this->GraphAreaY1 + $XMargin ) { $LastY = $this->GraphAreaY1 + $XMargin; }
$Y = $Y + $YStep;
if (!$ScaleModeAuto) {
$Y = $Y + $YStep;
}
}
if ( $ReCenter ) { $this->drawLine($LastX,$LastY,$LastX,$this->GraphAreaY2 - $XMargin,$Color); }
}
@ -3585,6 +3817,7 @@
$DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
$DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
$AroundZero = isset($Format["AroundZero"]) ? $Format["AroundZero"] : TRUE;
$ScaleModeAuto = isset($Format["ScaleModeAuto"]) ? $Format["ScaleModeAuto"] : FALSE;
$Data = $this->DataSet->getData();
list($XMargin,$XDivs) = $this->scaleGetXSettings();
@ -3608,6 +3841,31 @@
$YZero = $this->scaleComputeY(0,array("AxisID"=>$Serie["Axis"]));
$this->DataSet->Data["Series"][$SerieName]["XOffset"] = 0;
$Width = $this->GraphAreaX2-$this->GraphAreaX1-$XMargin*2;
$Height = $this->GraphAreaY2-$this->GraphAreaY1-$XMargin*2;
if ( $ScaleModeAuto && isset($Data["Series"][$Data["Abscissa"]]["Data"][0]) ) {
$AbscissaScaleValueMin = $Data["Series"][$Data["Abscissa"]]["Data"][0];
} else {
$AbscissaScaleValueMin = 0;
}
if ( $ScaleModeAuto && isset($Data["Series"][$Data["Abscissa"]]["Data"][$XDivs]) ) {
$AbscissaScaleValueMax = $Data["Series"][$Data["Abscissa"]]["Data"][$XDivs];
} else {
$AbscissaScaleValueMax = $Width;
}
$AbscissaScaleValueWidth = $AbscissaScaleValueMax - $AbscissaScaleValueMin;
if ( $Data["Orientation"] == SCALE_POS_LEFTRIGHT ) {
if ($AbscissaScaleValueWidth > 0)
$AbscissaScaleFactor = $AbscissaScaleValueWidth / $Width;
else
$AbscissaScaleFactor = 1;
} else {
if ($AbscissaScaleValueWidth > 0)
$AbscissaScaleFactor = $AbscissaScaleValueWidth / $Height;
else
$AbscissaScaleFactor = 1;
}
if ( $Data["Orientation"] == SCALE_POS_LEFTRIGHT )
{
@ -3623,6 +3881,11 @@
$LastGoodY = NULL; $LastGoodX = NULL; $Points = ""; $Init = FALSE;
foreach($PosArray as $Key => $Y)
{
if ($ScaleModeAuto) {
$AbscissaScaleValue = $Data["Series"][$Data["Abscissa"]]["Data"][$Key] - $AbscissaScaleValueMin;
$X = $this->GraphAreaX1 + $XMargin + $AbscissaScaleValue / $AbscissaScaleFactor;
}
if ( $Y == VOID && $LastX != NULL && $LastY != NULL && $Points !="" )
{
$Points[] = $LastX; $Points[] = $LastY;
@ -3646,7 +3909,10 @@
if ( !$Init && $ReCenter ) { $X = $X - $XStep/2; $Init = TRUE; }
$LastX = $X; $LastY = $Y;
if ( $LastX < $this->GraphAreaX1 + $XMargin ) { $LastX = $this->GraphAreaX1 + $XMargin; }
$X = $X + $XStep;
if (!$ScaleModeAuto) {
$X = $X + $XStep;
}
}
if ( $ReCenter )
@ -3671,6 +3937,11 @@
$LastGoodY = NULL; $LastGoodX = NULL; $Points = "";
foreach($PosArray as $Key => $X)
{
if ($ScaleModeAuto) {
$AbscissaScaleValue = $Data["Series"][$Data["Abscissa"]]["Data"][$Key] - $AbscissaScaleValueMin;
$Y = $this->GraphAreaY1 + $XMargin + $AbscissaScaleValue / $AbscissaScaleFactor;
}
if ( $X == VOID && $LastX != NULL && $LastY != NULL && $Points !="" )
{
$Points[] = $LastX; $Points[] = $LastY;
@ -3694,7 +3965,10 @@
if ( $LastX == NULL && $ReCenter ) { $Y = $Y - $YStep/2; }
$LastX = $X; $LastY = $Y;
if ( $LastY < $this->GraphAreaY1 + $XMargin ) { $LastY = $this->GraphAreaY1 + $XMargin; }
$Y = $Y + $YStep;
if (!$ScaleModeAuto) {
$Y = $Y + $YStep;
}
}
if ( $ReCenter )

View File

@ -1024,41 +1024,40 @@ function createGauge(name, etiqueta, value, min, max, min_warning,max_warning,wa
function createGauges(data, width, height, font_size, no_data_image, font) {
var nombre,label,minimun_warning,maximun_warning,minimun_critical,maximun_critical,
mininum,maxinum,valor;
for (key in data) {
nombre = data[key].gauge;
label = data[key].label;
label = label.replace(/&#x20;/g,' ');
label = label.replace(/\(/g,'\(');
label = label.replace(/\)/g,'\)');
label = label.replace(/&#40;/g,'\(');
label = label.replace(/&#41;/g,'\)');
minimun_warning = round_with_decimals(parseFloat( data[key].min_warning ));
maximun_warning = round_with_decimals(parseFloat( data[key].max_warning ));
minimun_critical = round_with_decimals(parseFloat( data[key].min_critical ));
maximun_critical = round_with_decimals(parseFloat( data[key].max_critical ));
minimun_warning = round_with_decimals(parseFloat( data[key].min_warning ));
maximun_warning = round_with_decimals(parseFloat( data[key].max_warning ));
minimun_critical = round_with_decimals(parseFloat( data[key].min_critical ));
maximun_critical = round_with_decimals(parseFloat( data[key].max_critical ));
mininum = round_with_decimals(parseFloat(data[key].min));
maxinum = round_with_decimals(parseFloat(data[key].max));
critical_inverse = parseInt(data[key].critical_inverse);
warning_inverse = parseInt(data[key].warning_inverse);
valor = round_with_decimals(data[key].value);
if (isNaN(valor))
valor = null;
createGauge(nombre, label, valor, mininum, maxinum,
createGauge(nombre, label, valor, mininum, maxinum,
minimun_warning, maximun_warning, warning_inverse, minimun_critical,
maximun_critical, critical_inverse, font_size, height, font);
}
}
function createthermometers(data, width, height, font_size, no_data_image, font) {
@ -1487,8 +1486,10 @@ function Gauge(placeholderName, configuration, font)
this.drawBand = function(start, end, color)
{
if (start === undefined) return;
if (end === undefined) return;
if (0 >= end - start) return;
this.body.append("svg:path")
.style("fill", color)
.attr("d", d3.svg.arc()
@ -1498,13 +1499,13 @@ function Gauge(placeholderName, configuration, font)
.outerRadius(Math.round(0.85 * this.config.raduis)))
.attr("transform", function() { return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(270)" });
}
this.redraw = function(value, transitionDuration)
{
var pointerContainer = this.body.select(".pointerContainer");
pointerContainer.selectAll("text").text(round_with_decimals(value));
var pointer = pointerContainer.selectAll("path");
pointer.transition()
.duration(undefined != transitionDuration ? transitionDuration : this.config.transitionDuration)
@ -1519,7 +1520,7 @@ function Gauge(placeholderName, configuration, font)
var targetRotation = (self.valueToDegrees(pointerValue) - 90);
var currentRotation = self._currentRotation || targetRotation;
self._currentRotation = targetRotation;
return function(step)
{
var rotation = currentRotation + (targetRotation-currentRotation)*step;

View File

@ -637,7 +637,6 @@ function post_process_select_init_unit(name,selected) {
$('#' + name + '_select').change(function() {
var value = $('#' + name + '_select').val();
$('#' + name + '_select option[value='+ value +']').attr("selected",true);
console.log(value);
});
}
@ -1553,35 +1552,20 @@ function paint_graph_status(min_w, max_w, min_c, max_c, inverse_w, inverse_c, er
}
}
function round_with_decimals (value, multiplier = 1) {
function round_with_decimals(value, multiplier) {
// Default values
if (typeof(multiplier) === "undefined") multiplier = 1;
// Return non numeric types without modification
if (typeof(value) !== "number") return value;
if ((value * multiplier) == 0) return 0;
if ((value * multiplier) >= 1) {
if ((Math.abs(value) * multiplier) >= 1) {
return Math.round(value * multiplier) / multiplier;
}
return round_with_decimals (value, multiplier * 10);
}
/*
$("body").append('<div id="event_delete_confirm_dialog"><h4>' + '<?php echo __('Are you sure?'); ?>' + '</h4></div>');
$("#event_delete_confirm_dialog").dialog({
resizable: false,
draggable: false,
modal: true,
height: 280,
width: 330,
overlay: {
opacity: 0.5,
background: "black"
},
closeOnEscape: false,
open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); }
});
*/
/**
* Display a confirm dialog box
*
@ -1590,12 +1574,7 @@ function round_with_decimals (value, multiplier = 1) {
* @param string Cancel button text
* @param function Callback to action when ok button is pressed
*/
function display_confirm_dialog (
message = '',
ok_text = '',
cancel_text = '',
ok_function = function () {}
) {
function display_confirm_dialog (message, ok_text, cancel_text, ok_function) {
// Clean function to close the dialog
var clean_function = function () {
$("#pandora_confirm_dialog_text").hide();

View File

@ -4548,7 +4548,6 @@ form ul.form_flex li ul li{
width: 85%;
height:100%;
float:left;
}
.status_animation {
@ -4577,7 +4576,6 @@ form ul.form_flex li ul li{
width: 15%;
height:100%;
float:left;
}
#last_contact_date {
@ -4587,9 +4585,9 @@ form ul.form_flex li ul li{
margin-left:5%;
text-align:center;
display: flex;
justify-content: center;
align-content: center;
flex-direction: column;
justify-content: center;
align-content: center;
flex-direction: column;
}
#last_contact_date_text {
@ -4615,9 +4613,9 @@ form ul.form_flex li ul li{
width: 90%;
height:100%;
display: flex;
justify-content: center;
align-content: center;
flex-direction: column;
justify-content: center;
align-content: center;
flex-direction: column;
}
.events_bar {
@ -4631,11 +4629,13 @@ form ul.form_flex li ul li{
border: 0px;
}
/*
.yAxis.y1Axis > .tickLabel {
white-space: nowrap;
line-height: 1.05em!important;
width: auto!important;
}
*/
.pandora_confirm_dialog .ui-dialog-buttonset {
display: flex;
@ -4664,4 +4664,4 @@ form ul.form_flex li ul li{
.dialog-grayed .ui-dialog-buttonpane {
background: #373737 !important;
}
}

View File

@ -0,0 +1,26 @@
var webPage = require('webpage');
var page = webPage.create();
var url = "http://nova/pandora_console/operation/agentes/stat_win.php?type=sparse&period=86400&id=136574&label=QXJ0aWNhJiN4MjA7d2ViJiN4MjA7cGFnZSYjeDIwO2V4YW1wbGU%3D&refresh=600&draw_events=0";
var r = page.addCookie({
'name' : 'PHPSESSID', /* required property */
'value' : '23qu7l1sgb3iq3bkaedr724hp3', /* required property */
'path' : '/pandora_console',
'domain' : 'nova',
});
console.log(r);
page.viewportSize = { width: 750, height: 350 };
page.open(url, function start(status) {
page.render('output.jpeg', {format: 'jpeg', quality: '100'});
phantom.exit();
});

View File

@ -0,0 +1,60 @@
var system = require('system');
if (system.args.length < 3 || system.args.length > 11) {
phantom.exit(1);
}
var webPage = require('webpage');
var page = webPage.create();
var url = system.args[1];
var type_graph_pdf = system.args[2];
var url_params = system.args[3];
var url_params_comb = system.args[4];
var url_module_list = system.args[5];
var output_filename = system.args[6];
var _width = system.args[7];
var _height = system.args[8];
var session_id = system.args[9];
var base_64 = system.args[10];
if (!_width) {
_width = 750;
}
if (!_height) {
_height = 350;
}
if(type_graph_pdf == 'combined'){
finish_url = url + "?" + "data=" + url_params +
"&data_combined=" + url_params_comb +
"&data_module_list=" + url_module_list +
"&type_graph_pdf=" + type_graph_pdf +
"&session_id=" + session_id;
}
else{
finish_url = url + "?" + "data=" + url_params +
"&type_graph_pdf=" + type_graph_pdf +
"&session_id=" + session_id;
}
page.viewportSize = { width: _width, height: _height };
//page.zoomFactor = 1.75;
page.open(finish_url, function start(status) {
});
page.onLoadFinished = function (status) {
if(!base_64){
page.render(output_filename, {format: 'png'});
}
else{
var base64 = page.renderBase64('png');
console.log(base64);
}
phantom.exit();
}

View File

@ -316,10 +316,6 @@ div.graph {
margin: 0 auto;
}
.tickLabels * {
font-size: 10px !important;
}
table.alternate tr:nth-child(odd) td, table.alternate tr:nth-child(odd) th{
background-color: #ffffff;
}

View File

@ -15,7 +15,7 @@
class ModuleGraph {
private $correct_acl = false;
private $acl = "AR";
private $id = 0;
private $id_agent = 0;
private $graph_type = "sparse";
@ -31,14 +31,14 @@ class ModuleGraph {
private $unknown_graph = 1;
private $zoom = 1;
private $baseline = 0;
private $module = null;
function __construct() {
$system = System::getInstance();
$this->start_date = date("Y-m-d");
if ($system->checkACL($this->acl)) {
$this->correct_acl = true;
}
@ -46,17 +46,17 @@ class ModuleGraph {
$this->correct_acl = false;
}
}
private function getFilters() {
$system = System::getInstance();
$this->id = (int)$system->getRequest('id', 0);
$this->id_agent = (int)$system->getRequest('id_agent', 0);
$this->module = modules_get_agentmodule($this->id);
$this->graph_type = return_graphtype($this->module["id_tipo_modulo"]);
$period_hours = $system->getRequest('period_hours', false);
if ($period_hours == false) {
$this->period = SECONDS_1DAY;
}
@ -78,29 +78,29 @@ class ModuleGraph {
$this->unknown_graph = (int)$system->getRequest('unknown_graph', 0);
$this->zoom = (int)$system->getRequest('zoom', 1);
$this->baseline = (int)$system->getRequest('baseline', 0);
$this->width = (int)$system->getRequest('width', 0);
$this->width -= 20; //Correct the width
$this->height = (int)$system->getRequest('height', 0);
//Sancho says "put the height to 1/2 for to make more beautyful"
$this->height = $this->height / 1.5;
$this->height -= 80; //Correct the height
//For to avoid fucking IPHONES when they are in horizontal.
if ($this->height < 140) {
$this->height = 140;
}
}
public function ajax($parameter2 = false) {
global $config;
$system = System::getInstance();
if (!$this->correct_acl) {
return;
}
@ -110,23 +110,20 @@ class ModuleGraph {
$this->getFilters();
$correct = 0;
$graph = '';
$correct = 1;
$label = $this->module["nombre"];
$unit = db_get_value('unit', 'tagente_modulo',
'id_agente_modulo', $this->id);
$utime = get_system_time ();
$current = date("Y-m-d", $utime);
if ($this->start_date != $current)
$date = strtotime($this->start_date);
else
$date = $utime;
$urlImage = ui_get_full_url(false);
$time_compare = false;
if ($this->time_compare_separated) {
$time_compare = 'separated';
@ -134,61 +131,33 @@ class ModuleGraph {
else if ($this->time_compare_overlapped) {
$time_compare = 'overlapped';
}
ob_start();
switch ($this->graph_type) {
case 'boolean':
$graph = grafico_modulo_boolean (
$this->id,
$this->period,
$this->draw_events,
$this->width,
$this->height,
false,
$unit,
$this->draw_alerts,
$this->avg_only,
false,
$date,
false,
$urlImage,
'adapter_' . $this->graph_type,
$time_compare,
$this->unknown_graph, false);
if ($this->draw_events) {
$graph .= '<br>';
$graph .= graphic_module_events(
$this->id,
$this->width, $this->height,
$this->period, $config['homeurl'],
$this->zoom,
'adapted_' . $this->graph_type, $date);
}
break;
case 'sparse':
$graph = grafico_modulo_sparse(
$this->id,
$this->period,
$this->draw_events,
$this->width,
$this->height,
false,
null,
$this->draw_alerts,
$this->avg_only,
false,
$date,
$unit,
$this->baseline,
0,
true,
false,
$urlImage,
1,
false,
'adapter_' . $this->graph_type,
$time_compare, $this->unknown_graph, false,
'white', null, false, false, $config['type_module_charts']);
case 'string':
$params =array(
'agent_module_id' => $this->id,
'period' => $this->period,
'show_events' => $this->draw_events,
'width' => $this->width,
'height' => $this->height,
'show_alerts' => $this->draw_alerts,
'avg_only' => $this->avg_only,
'date' => $date,
'unit' => $unit,
'baseline' => $this->baseline,
'homeurl' => $urlImage,
'adapt_key' => 'adapter_' . $this->graph_type,
'compare' => $time_compare,
'show_unknown' => $this->unknown_graph,
'menu' => false,
'type_graph' => $config['type_module_charts'],
'vconsole' => true
);
$graph = grafico_modulo_sparse($params);
if ($this->draw_events) {
$graph .= '<br>';
$graph .= graphic_module_events($this->id,
@ -197,64 +166,18 @@ class ModuleGraph {
$this->zoom, 'adapted_'.$this->graph_type, $date);
}
break;
case 'string':
$graph = grafico_modulo_string(
$this->id,
$this->period,
$this->draw_events,
$this->width,
$this->height,
false,
null,
$this->draw_alerts,
1,
false,
$date,
false,
$urlImage,
'adapter_' . $this->graph_type,
1,
false);
if ($this->draw_events) {
$graph .= '<br>';
$graph .= graphic_module_events($this->id,
$this->width, $this->height,
$this->period, $config['homeurl'],
$this->zoom, 'adapted_' . $this->graph_type, $date);
}
break;
case 'log4x':
$graph = grafico_modulo_log4x(
$this->id,
$this->period,
$this->draw_events,
$this->width,
$this->height,
false,
$unit_name,
$this->draw_alerts,
1,
$pure,
$date);
if ($this->draw_events) {
$graph .= '<br>';
$graph .= graphic_module_events($this->id,
$this->width, $this->height,
$this->period, $config['homeurl'], $this->zoom, '', $date);
}
break;
default:
$graph .= fs_error_image ('../images');
break;
}
$graph = ob_get_clean() . $graph;
echo json_encode(array('correct' => $correct, 'graph' => $graph));
break;
}
}
}
public function show() {
if (!$this->correct_acl) {
$this->show_fail_acl();
@ -264,7 +187,7 @@ class ModuleGraph {
$this->showModuleGraph();
}
}
private function show_fail_acl() {
$error['type'] = 'onStart';
$error['title_text'] = __('You don\'t have access to this page');
@ -275,7 +198,7 @@ class ModuleGraph {
$home = new Home();
$home->show($error);
}
private function javascript_code() {
ob_start();
@ -291,24 +214,24 @@ class ModuleGraph {
$(document).ready(function() {
function load_graph() {
$("#loading_graph").show();
var heigth = $(document).height()
var heigth = $(document).height()
- $(".ui-header").height()
- $(".ui-collapsible").height()
- 55;
var width = $(document).width() - 25;
ajax_get_graph($("#id_module").val(), heigth, width);
}
load_graph();
// Detect orientation change to refresh dinamic content
window.addEventListener("resize", function() {
// Reload dinamic content
load_graph();
});
});
function ajax_get_graph(id, heigth_graph, width_graph) {
postvars = {};
postvars["action"] = "ajax";
@ -316,20 +239,20 @@ class ModuleGraph {
postvars["parameter2"] = "get_graph";
postvars["width"] = width_graph;
postvars["height"] = heigth_graph;
postvars["draw_alerts"] = ($("input[name = 'draw_alerts']").is(":checked"))?1:0;
postvars["draw_events"] = ($("input[name = 'draw_events']").is(":checked"))?1:0;
postvars["time_compare_separated"] = ($("input[name = 'time_compare_separated']").is(":checked"))?1:0;
postvars["time_compare_overlapped"] = ($("input[name = 'time_compare_overlapped']").is(":checked"))?1:0;
postvars["unknown_graph"] = ($("input[name = 'unknown_graph']").is(":checked"))?1:0;;
postvars["avg_only"] = ($("input[name = 'avg_only']").is(":checked"))?1:0;;
postvars["period_hours"] = $("input[name = 'period_hours']").val();
postvars["zoom"] = $("input[name = 'zoom']").val();
postvars["start_date"] = $("input[name = 'start_date']").val();
postvars["id"] = id;
$.ajax ({
type: "POST",
url: "index.php",
@ -356,17 +279,17 @@ class ModuleGraph {
</script>
<?php
$javascript_code = ob_get_clean();
return $javascript_code;
}
private function showModuleGraph() {
$agent_alias = agents_get_alias($this->module['id_agente']);
$ui = Ui::getInstance();
$ui->createPage();
if ($this->id_agent) {
$ui->createDefaultHeader(
sprintf(__("%s: %s"), get_product_name(), $this->module["nombre"]),
@ -402,7 +325,7 @@ class ModuleGraph {
'label' => __('Show Alerts')
);
$ui->formAddCheckbox($options);
$options = array(
'name' => 'draw_events',
'value' => 1,
@ -410,7 +333,7 @@ class ModuleGraph {
'label' => __('Show Events')
);
$ui->formAddCheckbox($options);
$options = array(
'name' => 'time_compare_separated',
'value' => 1,
@ -418,7 +341,7 @@ class ModuleGraph {
'label' => __('Time compare (Separated)')
);
$ui->formAddCheckbox($options);
$options = array(
'name' => 'time_compare_overlapped',
'value' => 1,
@ -426,7 +349,7 @@ class ModuleGraph {
'label' => __('Time compare (Overlapped)')
);
$ui->formAddCheckbox($options);
$options = array(
'name' => 'unknown_graph',
'value' => 1,
@ -434,7 +357,7 @@ class ModuleGraph {
'label' => __('Show unknown graph')
);
$ui->formAddCheckbox($options);
$options = array(
'name' => 'avg_only',
'value' => 1,
@ -442,7 +365,7 @@ class ModuleGraph {
'label' => __('Avg Only')
);
$ui->formAddCheckbox($options);
$options = array(
'label' => __('Time range (hours)'),
'name' => 'period_hours',
@ -452,22 +375,21 @@ class ModuleGraph {
'step' => 4
);
$ui->formAddSlider($options);
$options = array(
'name' => 'start_date',
'value' => $this->start_date,
'label' => __('Begin date')
);
$ui->formAddInpuDate($options);
$options = array(
'icon' => 'refresh',
'icon_pos' => 'right',
'text' => __('Update graph')
);
$ui->formAddSubmitButton($options);
$html = $ui->getEndForm();
$ui->contentCollapsibleAddItem($html);
$ui->contentEndCollapsible();

View File

@ -280,13 +280,15 @@ $access_agent = db_get_value_sql("SELECT COUNT(id_agent)
WHERE id_agent = " . $id_agente);
if ($config["agentaccess"] && $access_agent > 0) {
$data[2] =
'<fieldset width=90% class="databox agente" style="">
'<fieldset width=99% class="databox agente" style="">
<legend>' .
__('Agent access rate (24h)') .
'</legend>' .
graphic_agentaccess($id_agente, 300, 100, SECONDS_1DAY, true) .
graphic_agentaccess($id_agente, '90%', 150, SECONDS_1DAY, true) .
'</fieldset>';
$table_data->style[1] = 'width: 40%;';
$table_data->style[0] = 'width: 20%;';
$table_data->style[1] = 'width: 30%;';
$table_data->style[2] = 'width: 50%;';
$table_data->rowspan[0][2] = 5;
}
@ -298,8 +300,6 @@ if (!empty($addresses)) {
$data[1] = '<div style="max-height: 45px; overflow-y: scroll; height:45px;">' .
implode('<br>',$addresses) .
'</div>';
//~ $table_data->data[] = '<div style="max-height: 200px; overflow: hidden;>' .
//~ $data . '</div>';
$table_data->data[] = $data;
}

View File

@ -75,7 +75,7 @@ $interface_traffic_modules = array(
$refresh = (int) get_parameter('refresh', SECONDS_5MINUTES);
if ($refresh > 0) {
$query = ui_get_url_refresh(false);
echo '<meta http-equiv="refresh" content="'.$refresh.'; URL='.$query.'" />';
}
?>
@ -99,10 +99,10 @@ $interface_traffic_modules = array(
window.onload = function() {
// Hack to repeat the init process to period select
var periodSelectId = $('[name="period"]').attr('class');
period_select_init(periodSelectId);
};
function show_others() {
if (!$("#checkbox-avg_only").attr('checked')) {
$("#hidden-show_other").val(1);
@ -116,20 +116,18 @@ $interface_traffic_modules = array(
</head>
<body bgcolor="#ffffff" style='background:#ffffff;'>
<?php
// ACL
$permission = false;
$agent_group = (int) agents_get_agent_group($agent_id);
$strict_user = (bool) db_get_value("strict_acl", "tusuario", "id_user", $config['id_user']);
// The traffic modules should belong to the agent id
$in_agent_id = (int) db_get_value("id_agente", "tagente_modulo", "id_agente_modulo", $params['traffic_module_in']);
$out_agent_id = (int) db_get_value("id_agente", "tagente_modulo", "id_agente_modulo", $params['traffic_module_out']);
$traffic_modules_belong_to_agent = $agent_id == $in_agent_id && $agent_id == $out_agent_id;
if (!empty($agent_group) && !empty($params['traffic_module_in'])
&& !empty($params['traffic_module_out']) && $traffic_modules_belong_to_agent) {
if ($strict_user) {
if (tags_check_acl_by_module($params['traffic_module_in'], $config['id_user'], 'RR') === true
&& tags_check_acl_by_module($params['traffic_module_out'], $config['id_user'], 'RR') === true)
@ -139,12 +137,12 @@ $interface_traffic_modules = array(
$permission = check_acl($config['id_user'], $agent_group, "RR");
}
}
if (!$permission) {
require ($config['homedir'] . "/general/noaccess.php");
exit;
}
// Get input parameters
$period = get_parameter ("period", SECONDS_1DAY);
$width = (int) get_parameter("width", 555);
@ -155,10 +153,10 @@ $interface_traffic_modules = array(
$baseline = get_parameter ("baseline", 0);
$show_percentil = get_parameter ("show_percentil", 0);
$fullscale = get_parameter("fullscale");
if(!isset($_GET["fullscale_sent"]) ){
if(!isset($config['full_scale_option']) ||
$config['full_scale_option'] == 0 ||
if(!isset($config['full_scale_option']) ||
$config['full_scale_option'] == 0 ||
$config['full_scale_option'] == 2 ){
$fullscale = 0;
}
@ -170,12 +168,11 @@ $interface_traffic_modules = array(
if ($zoom > 1) {
$height = $height * ($zoom / 2.1);
$width = $width * ($zoom / 1.4);
echo "<script type='text/javascript'>window.resizeTo($width + 120, $height + 320);</script>";
}
/*$current = date("Y-m-d");
if ($start_date != $current)
$date = strtotime($start_date);
else
@ -183,45 +180,49 @@ $interface_traffic_modules = array(
*/
$date = strtotime("$start_date $start_time");
$now = time();
if ($date > $now){
$date = $now;
}
$urlImage = ui_get_full_url(false);
if ($config['flash_charts'] == 1)
echo '<div style="margin-left: 70px; padding-top: 10px;">';
else
echo '<div style="margin-left: 50px; padding-top: 10px;">';
custom_graphs_print(0,
$height,
$width,
$period,
null,
false,
$date,
false,
'white',
$height = 400;
$width = '90%';
$params =array(
'period' => $period,
'width' => $width,
'height' => $height,
'unit_name' => array_fill(0, count($interface_traffic_modules), $config["interface_unit"]),
'date' => $date,
'homeurl' => $config['homeurl'],
'percentil' => (($show_percentil)? $config['percentil'] : null),
'fullscale' => $fullscale
);
$params_combined = array(
'weight_list' => array(),
'projection' => false,
'labels' => array_keys($interface_traffic_modules),
'from_interface' => true,
'modules_series' => array_values($interface_traffic_modules),
'return' => 0
);
graphic_combined_module(
array_values($interface_traffic_modules),
$config['homeurl'],
array_keys($interface_traffic_modules),
array_fill(0, count($interface_traffic_modules), $config["interface_unit"]),
false,
true,
true,
true,
1,
false,
false,
(($show_percentil)? $config['percentil'] : null),
true,
false,
$fullscale);
$params,
$params_combined
);
echo '</div>';
///////////////////////////
// SIDE MENU
///////////////////////////
@ -231,13 +232,12 @@ $interface_traffic_modules = array(
$side_layer_params['top_text'] = "<div style='color: white; width: 100%; text-align: center; font-weight: bold; vertical-align: top;'>" . html_print_image('/images/config.disabled.png', true, array('width' => '16px'),false,false,false,true) . ' ' . __('Graph configuration menu') . "</div>";
$side_layer_params['body_text'] = "<div class='menu_sidebar_outer'>";
$side_layer_params['body_text'] .=__('Please, make your changes and apply with the <i>Reload</i> button');
// MENU
$side_layer_params['body_text'] .= '<form method="get" action="interface_traffic_graph_win.php">';
$side_layer_params['body_text'] .= html_print_input_hidden("params", base64_encode($params_json), true);
// FORM TABLE
$table = html_get_predefined_table('transparent', 2);
$table->width = '98%';
$table->id = 'stat_win_form_div';
@ -245,32 +245,32 @@ $interface_traffic_modules = array(
$table->style[1] = 'text-align:left;';
$table->styleTable = 'border-spacing: 4px;';
$table->class = 'alternate';
$data = array();
$data[0] = __('Refresh time');
$data[1] = html_print_extended_select_for_time("refresh", $refresh, '', '', 0, 7, true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = __('Begin date');
$data[1] = html_print_input_text ("start_date", substr ($start_date, 0, 10),'', 15, 255, true);
$data[1] .= html_print_image ("/images/calendar_view_day.png", true, array ("onclick" => "scwShow(scwID('text-start_date'),this);", "style" => 'vertical-align: bottom;'),false,false,false,true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = __('Begin time');
$data[1] = html_print_input_text ("start_time", $start_time,'', 10, 10, true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = __('Time range');
$data[1] = html_print_extended_select_for_time('period', $period, '', '', 0, 7, true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = __('Show percentil');
$data[1] = html_print_checkbox ("show_percentil", 1, (bool) $show_percentil, true);
@ -288,7 +288,7 @@ $interface_traffic_modules = array(
$data[1] = html_print_checkbox ("fullscale", 1, (bool) $fullscale, true);
$table->data[] = $data;
$table->rowclass[] ='';
$data = array();
$data[0] = __('Zoom factor');
$options = array();
@ -300,47 +300,47 @@ $interface_traffic_modules = array(
$data[1] = html_print_select($options, "zoom", $zoom, '', '', 0, true);
$table->data[] = $data;
$table->rowclass[] = '';
$form_table = html_print_table($table, true);
unset($table);
$table->id = 'stat_win_form';
$table->width = '100%';
$table->cellspacing = 2;
$table->cellpadding = 2;
$table->class = 'databox';
$data = array();
$data[0] = html_print_div(array('content' => $form_table, 'style' => 'overflow: auto; height: 220px'), true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = '<div style="width:100%; text-align:right;">' . html_print_submit_button (__('Reload'), "submit", false, 'class="sub upd"', true) . "</div>";
$table->data[] = $data;
$table->rowclass[] = '';
$side_layer_params['body_text'] .= html_print_table($table, true);
$side_layer_params['body_text'] .= '</form>';
$side_layer_params['body_text'] .= '</div>'; // outer
// ICONS
$side_layer_params['icon_closed'] = '/images/graphmenu_arrow_hide.png';
$side_layer_params['icon_open'] = '/images/graphmenu_arrow.png';
// SIZE
$side_layer_params['width'] = 500;
// POSITION
$side_layer_params['position'] = 'left';
html_print_side_layer($side_layer_params);
// Hidden div to forced title
html_print_div(array('id' => 'forced_title_layer', 'class' => 'forced_title_layer', 'hidden' => true));
?>
</body>
</html>
<?php
@ -351,7 +351,7 @@ ui_require_jquery_file("ui.datepicker-" . $custom_user_language, "include/javasc
ui_include_time_picker(true);
?>
<script>
<?php
//Resize window when show the overview graph.
if ($config['flash_charts']) {
@ -363,7 +363,7 @@ ui_include_time_picker(true);
height_window = $(window).height();
width_window = $(window).width();
});
$("*").filter(function() {
if (typeof(this.id) == "string")
return this.id.match(/menu_overview_graph.*/);
@ -375,12 +375,12 @@ ui_include_time_picker(true);
<?php
}
?>
// Add datepicker and timepicker
$("#text-start_date").datepicker({
dateFormat: "<?php echo DATE_FORMAT_JS; ?>"
});
$("#text-start_time").timepicker({
showSecond: true,
timeFormat: '<?php echo TIME_FORMAT_JS; ?>',
@ -392,8 +392,8 @@ ui_include_time_picker(true);
currentText: '<?php echo __('Now');?>',
closeText: '<?php echo __('Close');?>'
});
$.datepicker.setDefaults($.datepicker.regional["<?php echo $custom_user_language; ?>"]);
forced_title_callback();
</script>

View File

@ -36,7 +36,6 @@ check_login ();
$server_id = (int) get_parameter("server");
if (is_metaconsole() && !empty($server_id)) {
$server = metaconsole_get_connection_by_id($server_id);
// Error connecting
if (metaconsole_connect($server) !== NOERR) {
echo "<html>";
@ -56,11 +55,11 @@ if (file_exists ('../../include/languages/'.$user_language.'.mo')) {
echo '<link rel="stylesheet" href="../../include/styles/pandora.css" type="text/css"/>';
$label = get_parameter('label');
$label = base64_decode($label);
$id = get_parameter('id');
$label = get_parameter('label');
$label = base64_decode($label);
$id = get_parameter('id');
$id_agent = db_get_value ("id_agente","tagente_modulo","id_agente_modulo",$id);
$alias = db_get_value ("alias","tagente","id_agente",$id_agent);
$alias = db_get_value ("alias","tagente","id_agente",$id_agent);
//$agent = agents_get_agent_with_ip ("192.168.50.31");
//$label = rawurldecode(urldecode(base64_decode(get_parameter('label', ''))));
?>
@ -72,7 +71,6 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
$refresh = (int) get_parameter ("refresh", -1);
if ($refresh > 0) {
$query = ui_get_url_refresh (false);
echo '<meta http-equiv="refresh" content="'.$refresh.'; URL='.$query.'" />';
}
?>
@ -92,14 +90,13 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
}
?>
<script type='text/javascript'>
<!--
window.onload = function() {
// Hack to repeat the init process to period select
var periodSelectId = $('[name="period"]').attr('class');
period_select_init(periodSelectId);
};
function show_others() {
if ($('#checkbox-avg_only').is(":checked") == true) {
$("#hidden-show_other").val(1);
@ -107,15 +104,7 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
else {
$("#hidden-show_other").val(0);
}
//
// if ($('#hidden-avg_only_sent').is(":checked") == true) {
// $("#hidden-avg_only_sent").val(1);
// }
// else {
// $("#hidden-avg_only_sent").val(0);
// }
}
//-->
</script>
</head>
<body bgcolor="#ffffff" style='background:#ffffff;'>
@ -125,18 +114,18 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
$id = (int) get_parameter ("id", 0);
// Agent id
$agent_id = (int) modules_get_agentmodule_agent($id);
if (empty($id) || empty($agent_id)) {
ui_print_error_message(__('There was a problem locating the source of the graph'));
exit;
}
// ACL
$permission = false;
$permission = false;
$agent_group = (int) agents_get_agent_group($agent_id);
$strict_user = (bool) db_get_value("strict_acl", "tusuario",
"id_user", $config['id_user']);
if (!empty($agent_group)) {
if ($strict_user) {
$permission = tags_check_acl_by_module($id, $config['id_user'], 'RR') === true;
@ -145,28 +134,26 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
$permission = check_acl($config['id_user'], $agent_group, "RR");
}
}
if (!$permission) {
require ($config['homedir'] . "/general/noaccess.php");
exit;
}
$draw_alerts = get_parameter("draw_alerts", 0);
if(isset($config['only_average'])){
$avg_only = $config['only_average'];
}
$show_other = get_parameter('show_other',-1);
if ($show_other != -1) {
$avg_only = $show_other;
}
$period = get_parameter ("period");
$id = get_parameter ("id", 0);
$width = get_parameter ("width", STATWIN_DEFAULT_CHART_WIDTH);
$height = get_parameter ("height", STATWIN_DEFAULT_CHART_HEIGHT);
$id = get_parameter ("id", 0);
$label = get_parameter ("label", "");
$label_graph = base64_decode(get_parameter ("label", ""));
$start_date = get_parameter ("start_date", date("Y/m/d"));
@ -191,7 +178,7 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
}
elseif($config['full_scale_option'] == 2){
if($graph_type == 'boolean'){
$fullscale = 1;
$fullscale = 1;
}else{
$fullscale = 0;
}
@ -203,94 +190,79 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
// To avoid the horizontal overflow
$width -= 20;
$time_compare = false;
if ($time_compare_separated) {
$time_compare = 'separated';
}
else if ($time_compare_overlapped) {
$time_compare = 'overlapped';
}
if ($zoom > 1) {
$height = $height * ($zoom / 2.1);
$width = $width * ($zoom / 1.4);
}
echo "<script type='text/javascript'>window.resizeTo($width + 190, $height + 260);</script>";
// Build date
$date = strtotime("$start_date $start_time");
$now = time();
if ($date > $now)
$date = $now;
$urlImage = ui_get_full_url(false, false, false, false);
$unit = db_get_value('unit', 'tagente_modulo', 'id_agente_modulo', $id);
// log4x doesnt support flash yet
//
if ($config['flash_charts'] == 1)
echo '<div style="margin-left: 65px; padding-top: 10px;">';
else
echo '<div style="margin-left: 20px; padding-top: 10px;">';
$width = '90%';
$height = '450';
switch ($graph_type) {
case 'boolean':
echo grafico_modulo_boolean ($id, $period, $draw_events,
$width, $height, $label_graph, $unit, $draw_alerts,
$avg_only, false, $date, false, $urlImage,
'adapter_' . $graph_type, $time_compare,
$unknown_graph, true, $fullscale);
echo '<br>';
if ($show_events_graph)
echo graphic_module_events($id, $width, $height,
$period, $config['homeurl'], $zoom,
'adapted_' . $graph_type, $date, true);
break;
case 'sparse':
echo grafico_modulo_sparse ($id, $period, $draw_events,
$width, $height, $label_graph, $unit, $draw_alerts,
$avg_only, false, $date, $unit, $baseline, 0, true,
false, $urlImage, 1, false,
'adapter_' . $graph_type, $time_compare,
$unknown_graph, true, 'white',
(($show_percentil)? $config['percentil'] : null),
false, false, $config['type_module_charts'], $fullscale);
echo '<br>';
if ($show_events_graph)
echo graphic_module_events($id, $width, $height,
$period, $config['homeurl'], $zoom,
'adapted_' . $graph_type, $date, true);
break;
case 'string':
echo grafico_modulo_string ($id, $period, $draw_events,
$width, $height, $label_graph, null, $draw_alerts, 1,
false, $date, false, $urlImage,
'adapter_' . $graph_type);
$params =array(
'agent_module_id' => $id,
'period' => $period,
'show_events' => $draw_events,
'title' => $label_graph,
'unit_name' => $unit,
'show_alerts' => $draw_alerts,
'avg_only' => $avg_only,
'date' => $date,
'unit' => $unit,
'baseline' => $baseline,
'homeurl' => $urlImage,
'adapt_key' => 'adapter_' . $graph_type,
'compare' => $time_compare,
'show_unknown' => $unknown_graph,
'percentil' => (($show_percentil)? $config['percentil'] : null),
'type_graph' => $config['type_module_charts'],
'fullscale' => $fullscale
);
echo grafico_modulo_sparse ($params);
echo '<br>';
if ($show_events_graph)
if ($show_events_graph){
$width = '500';
echo graphic_module_events($id, $width, $height,
$period, $config['homeurl'], $zoom,
'adapted_' . $graph_type, $date, true);
break;
case 'log4x':
echo grafico_modulo_log4x ($id, $period, $draw_events,
$width, $height, $label_graph, $unit, $draw_alerts, 1,
$pure, $date);
echo '<br>';
if ($show_events_graph)
echo graphic_module_events($id, $width, $height,
$period, $config['homeurl'], $zoom, '', $date, true);
}
break;
default:
echo fs_error_image ('../images');
break;
}
echo '</div>';
////////////////////////////////////////////////////////////////
// SIDE MENU
////////////////////////////////////////////////////////////////
@ -300,22 +272,21 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
$params['top_text'] = "<div style='color: white; width: 100%; text-align: center; font-weight: bold; vertical-align: top;'>" . html_print_image('images/wrench_blanco.png', true, array('width' => '16px'), false, false, true) . ' ' . __('Graph configuration menu') . ui_print_help_icon ("graphs",true, $config["homeurl"], "images/help_w.png", true) . "</div>";
$params['body_text'] = "<div class='menu_sidebar_outer'>";
$params['body_text'] .=__('Please, make your changes and apply with the <i>Reload</i> button');
// MENU
$params['body_text'] .= '<form method="get" action="stat_win.php">';
$params['body_text'] .= html_print_input_hidden ("id", $id, true);
$params['body_text'] .= html_print_input_hidden ("label", $label, true);
if (!empty($server_id))
$params['body_text'] .= html_print_input_hidden ("server", $server_id, true);
if (isset($_GET["type"])) {
$type = get_parameter_get ("type");
$params['body_text'] .= html_print_input_hidden ("type", $type, true);
}
// FORM TABLE
$table = html_get_predefined_table('transparent', 2);
$table->width = '98%';
$table->id = 'stat_win_form_div';
@ -324,14 +295,14 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
//$table->size[0] = '50%';
$table->styleTable = 'border-spacing: 4px;';
$table->class = 'alternate';
$data = array();
$data[0] = __('Refresh time');
$data[1] = html_print_extended_select_for_time("refresh",
$refresh, '', '', 0, 7, true);
$table->data[] = $data;
$table->rowclass[] = '';
if ($graph_type != "boolean" && $graph_type != "string") {
$data = array();
$data[0] = __('Avg. Only');
@ -341,19 +312,19 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
$table->data[] = $data;
$table->rowclass[] = '';
}
$data = array();
$data[0] = __('Begin date');
$data[1] = html_print_input_text ("start_date", $start_date,'', 10, 20, true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = __('Begin time');
$data[1] = html_print_input_text ("start_time", $start_time,'', 10, 10, true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = __('Zoom factor');
$options = array ();
@ -365,14 +336,14 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
$data[1] = html_print_select ($options, "zoom", $zoom, '', '', 0, true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = __('Time range');
$data[1] = html_print_extended_select_for_time('period',
$period, '', '', 0, 7, true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = __('Show events');
$disabled = false;
@ -389,19 +360,19 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
}
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = __('Show alerts');
$data[1] = html_print_checkbox ("draw_alerts", 1, (bool) $draw_alerts, true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = __('Show event graph');
$data[1] = html_print_checkbox ("show_events_graph", 1, (bool) $show_events_graph, true);
$table->data[] = $data;
$table->rowclass[] = '';
switch ($graph_type) {
case 'boolean':
case 'sparse':
@ -410,19 +381,19 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
$data[1] = html_print_checkbox ("show_percentil", 1, (bool) $show_percentil, true);
$table->data[] = $data;
$table->rowclass[] ='';
$data = array();
$data[0] = __('Time compare (Overlapped)');
$data[1] = html_print_checkbox ("time_compare_overlapped", 1, (bool) $time_compare_overlapped, true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = __('Time compare (Separated)');
$data[1] = html_print_checkbox ("time_compare_separated", 1, (bool) $time_compare_separated, true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = __('Show unknown graph');
$data[1] = html_print_checkbox ("unknown_graph", 1, (bool) $unknown_graph, true);
@ -437,24 +408,24 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
true, false);
$table->data[] = $data;
$table->rowclass[] = '';
$form_table = html_print_table($table, true);
unset($table);
$table = new stdClass();
$table->id = 'stat_win_form';
$table->width = '100%';
$table->cellspacing = 2;
$table->cellpadding = 2;
$table->class = 'databox';
$data = array();
$data[0] = html_print_div(array('id' => 'field_list', 'content' => $form_table,
'style' => 'overflow: auto; height: 220px'), true);
$table->data[] = $data;
$table->rowclass[] = '';
$data = array();
$data[0] = '<div style="width:100%; text-align:right;">' .
html_print_submit_button(__('Reload'), "submit", false,
@ -462,28 +433,28 @@ $alias = db_get_value ("alias","tagente","id_agente",$id_agent);
"</div>";
$table->data[] = $data;
$table->rowclass[] = '';
$params['body_text'] .= html_print_table($table, true);
$params['body_text'] .= '</form>';
$params['body_text'] .= '</div>'; // outer
// ICONS
$params['icon_closed'] = '/images/graphmenu_arrow_hide.png';
$params['icon_open'] = '/images/graphmenu_arrow.png';
// SIZE
$params['width'] = 500;
// POSITION
$params['position'] = 'left';
html_print_side_layer($params);
// Hidden div to forced title
html_print_div(array('id' => 'forced_title_layer',
'class' => 'forced_title_layer', 'hidden' => true));
?>
</body>
</html>
@ -502,38 +473,7 @@ ui_include_time_picker(true);
$('#checkbox-time_compare_overlapped').click(function() {
$('#checkbox-time_compare_separated').removeAttr('checked');
});
<?php
//Resize window when show the overview graph.
if ($config['flash_charts']) {
?>
var show_overview = false;
var height_window;
var width_window;
$(window).ready(function() {
height_window = window.innerHeight;
width_window = window.innerWidth;
});
$("*").filter(function() {
if (typeof(this.id) == "string")
return this.id.match(/menu_overview_graph.*/);
else
return false;
}).click(function() {
if (show_overview) {
window.resizeTo(width_window, height_window);
}
else {
window.resizeTo(width_window, height_window + 150);
}
show_overview = !show_overview;
});
<?php
}
?>
// Add datepicker and timepicker
$("#text-start_date").datepicker({
dateFormat: "<?php echo DATE_FORMAT_JS; ?>"
@ -549,13 +489,13 @@ ui_include_time_picker(true);
currentText: '<?php echo __('Now');?>',
closeText: '<?php echo __('Close');?>'
});
$.datepicker.setDefaults($.datepicker.regional["<?php echo $custom_user_language; ?>"]);
$(window).ready(function() {
$("#field_list").css('height', ($(window).height() - 160) + 'px');
});
$(window).resize(function() {
$("#field_list").css('height', ($(window).height() - 160) + 'px');
});

View File

@ -63,7 +63,7 @@ if ($delete_graph) {
if ($view_graph) {
$sql="SELECT * FROM tgraph_source WHERE id_graph = $id_graph";
$sources = db_get_all_rows_sql($sql);
$sql="SELECT * FROM tgraph WHERE id_graph = $id_graph";
$graph = db_get_row_sql($sql);
@ -71,7 +71,7 @@ if ($view_graph) {
$private = $graph["private"];
$width = $graph["width"];
$height = $graph["height"] + count($sources) * 10;
$zoom = (int) get_parameter ('zoom', 0);
//Increase the height to fix the leyend rise
if ($zoom > 0) {
@ -160,12 +160,12 @@ if ($view_graph) {
html_print_image("images/builder.png", true, array ("title" => __('Graph editor'))) .'</a>')
);
}
$options['view']['text'] = '<a href="index.php?sec=reporting&sec2=operation/reporting/graph_viewer&view_graph=1&id=' . $id_graph . '">' .
html_print_image("images/operation.png", true,
array ("title" => __('View graph'))) .'</a>';
$options['view']['active'] = true;
if ($config["pure"] == 0) {
$options['screen']['text'] = "<a href='$url&pure=1'>"
. html_print_image ("images/full_screen.png", true, array ("title" => __('Full screen mode')))
@ -175,18 +175,42 @@ if ($view_graph) {
$options['screen']['text'] = "<a href='$url&pure=0'>"
. html_print_image ("images/normal_screen.png", true, array ("title" => __('Back to normal mode')))
. "</a>";
// In full screen, the manage options are not available
$options = array('view' => $options['view'], 'screen' => $options['screen']);
}
// Header
ui_print_page_header ($graph['name'],
"images/chart.png", false, "", false, $options);
$graph_return = custom_graphs_print($id_graph, $height, $width, $period, $stacked, true, $unixdate, false, 'white',
array(), '', array(), array(), true, true, true, true, 1, false, false, $percentil, false, false, $fullscale);
ui_print_page_header (
$graph['name'],
"images/chart.png",
false,
"",
false,
$options
);
$width = null;
$height = null;
$params =array(
'period' => $period,
'width' => $width,
'height' => $height,
'date' => $unixdate,
'percentil' => $percentil,
'fullscale' => $fullscale
);
$params_combined = array(
'stacked' => $stacked,
'id_graph' => $id_graph
);
$graph_return = graphic_combined_module(
false,
$params,
$params_combined
);
if ($graph_return){
echo "<table class='databox filters' cellpadding='0' cellspacing='0' width='100%'>";
@ -310,7 +334,6 @@ if ($view_graph) {
$("#stacked").change(function(){
if ($(this).val() == '4') {
console.log($(this).val());
$("#thresholdDiv").show();
$(".stacked").show();
} else {

View File

@ -168,9 +168,23 @@ function main_intel_dcm_agent_view () {
$module = modules_get_agentmodule_id (io_safe_input("Avg. Power"), $id_agent);
$unit = modules_get_unit ($module['id_agente_modulo']);
$data[1] = grafico_modulo_sparse($module['id_agente_modulo'], 7200, $draw_events, 400, 250,
$module['nombre'], null, $draw_alerts, $avg_only, false, $date, $unit);
$params_1 =array(
'agent_module_id' => $module['id_agente_modulo'],
'period' => 7200,
'show_events' => $draw_events,
'width' => 400,
'height' => 250,
'title' => $module['nombre'],
'unit_name' => null,
'show_alerts' => $draw_alerts,
'avg_only' => $avg_only,
'pure' => false,
'date' => $date,
'unit' => $unit
);
$data[1] = grafico_modulo_sparse($params_1);
array_push ($table->data, $data);
@ -190,19 +204,44 @@ function main_intel_dcm_agent_view () {
$module = modules_get_agentmodule_id (io_safe_input("Avg. Inlet Temperature"), $id_agent);
$unit = modules_get_unit ($module['id_agente_modulo']);
$data[0] = grafico_modulo_sparse($module['id_agente_modulo'], 7200, $draw_events, 400, 250,
$module['nombre'], null, $draw_alerts, $avg_only, false, $date, $unit);
$params_2 =array(
'agent_module_id' => $module['id_agente_modulo'],
'period' => 7200,
'show_events' => $draw_events,
'width' => 400,
'height' => 250,
'title' => $module['nombre'],
'unit_name' => null,
'show_alerts' => $draw_alerts,
'avg_only' => $avg_only,
'pure' => false,
'date' => $date,
'unit' => $unit
);
$data[0] = grafico_modulo_sparse($params_2);
$module = modules_get_agentmodule_id (io_safe_input("Calculated Cooling Power"), $id_agent);
$unit = modules_get_unit ($module['id_agente_modulo']);
$data[1] = grafico_modulo_sparse($module['id_agente_modulo'], 7200, $draw_events, 400, 250,
$module['nombre'], null, $draw_alerts, $avg_only, false, $date, $unit);
$params_3 =array(
'agent_module_id' => $module['id_agente_modulo'],
'period' => 7200,
'show_events' => $draw_events,
'width' => 400,
'height' => 250,
'title' => $module['nombre'],
'unit_name' => null,
'show_alerts' => $draw_alerts,
'avg_only' => $avg_only,
'pure' => false,
'date' => $date,
'unit' => $unit
);
$data[1] = grafico_modulo_sparse($params_3);
array_push ($table->data, $data);
echo "<center>";
html_print_table($table);
echo "</center>";