public function getJSON() { if ($this->oChart == false) { return false; } return $this->oChart->toPrettyString(); }
/** * Generates data for OFC2 line chart in json format * * @return void */ public function get_laba_rugi() { $this->load->plugin('ofc2'); $this->load->model('jurnal_model'); $model_data = $this->jurnal_model->get_laba_rugi_data(); $bulan_data = array("Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agu", "Sep", "Okt", "Nov", "Des"); for ($i = date('n') + 1; $i <= 12; $i++) { $pendapatan_kredit = isset($model_data[$i][date('Y') - 1][4][0]) ? $model_data[$i][date('Y') - 1][4][0] : 0; $pendapatan_debit = isset($model_data[$i][date('Y') - 1][4][1]) ? $model_data[$i][date('Y') - 1][4][1] : 0; $beban_kredit = isset($model_data[$i][date('Y') - 1][5][0]) ? $model_data[$i][date('Y') - 1][5][0] : 0; $beban_debit = isset($model_data[$i][date('Y') - 1][5][1]) ? $model_data[$i][date('Y') - 1][5][1] : 0; $data[] = $pendapatan_kredit - $pendapatan_debit - ($beban_debit - $beban_kredit); $thn = date('y') - 1; $thn = strlen($thn) == 1 ? '0' . $thn : $thn; $x_data[] = $bulan_data[$i - 1] . "'" . $thn; } for ($i = 1; $i <= date('n'); $i++) { $pendapatan_kredit = isset($model_data[$i][date('Y')][4][0]) ? $model_data[$i][date('Y')][4][0] : 0; $pendapatan_debit = isset($model_data[$i][date('Y')][4][1]) ? $model_data[$i][date('Y')][4][1] : 0; $beban_kredit = isset($model_data[$i][date('Y')][5][0]) ? $model_data[$i][date('Y')][5][0] : 0; $beban_debit = isset($model_data[$i][date('Y')][5][1]) ? $model_data[$i][date('Y')][5][1] : 0; $data[] = $pendapatan_kredit - $pendapatan_debit - ($beban_debit - $beban_kredit); $x_data[] = $bulan_data[$i - 1] . "'" . date('y'); } $max = (int) max($data); $maxlen = strlen($max); $up = round($max, -($maxlen - 1)); $min = (int) min($data); $minlen = strlen($min); $down = round($min, -($minlen - 1)); $abs_max = (int) max(abs($max), abs($min)); $len = strlen($abs_max); $round = round($abs_max, -($len - 1)); $step = '1' . substr($round, 1); $up = $max > $up ? $up + $step : $up; $down = $min < $down ? $down - $step : $down; $d = new hollow_dot(); $d->size(4)->halo_size(1)->colour('#668053'); $line = new line(); $line->set_values($data); $line->set_default_dot_style($d); $line->set_width(5); $line->set_colour('#7491a0'); $x_labels = new x_axis_labels(); $x_labels->set_labels($x_data); $x = new x_axis(); $x->set_labels($x_labels); $x->set_grid_colour('#bfb8b3'); $y = new y_axis(); $y->set_grid_colour('#bfb8b3'); $y->set_range($down, $up, $step); $chart = new open_flash_chart(); $chart->add_element($line); $chart->set_x_axis($x); $chart->set_y_axis($y); $chart->set_bg_colour('#FFFFFF'); echo $chart->toPrettyString(); }
function build($options = array()) { if (empty($options)) { return false; } require_once WWW_ROOT . 'php-ofc-library/open-flash-chart.php'; $chart = new open_flash_chart(); if (isset($options['title']['txt'])) { $title = new title($options['title']['txt']); if (isset($options['title']['style'])) { $title->set_style("{" . $options['title']['style'] . "}"); } $chart->set_title($title); } if (isset($options['chart']['bg'])) { $chart->set_bg_colour($options['chart']['bg']); } if (isset($xOptions['color'])) { $x->colour($xOptions['color']); } if (isset($xOptions['grid_colour'])) { $x->grid_colour($xOptions['grid_colour']); } $col = isset($options['color']) ? $options['color'] : null; $outlineCol = isset($options['outline_col']) ? $options['outline_col'] : null; if (isset($options['charts'])) { foreach ($options['charts'] as $chartOpts) { $type = isset($chartOpts['type']) ? $chartOpts['type'] : 'bar_filled'; $diagram = new $type($chartOpts['col'], $chartOpts['outline']); if ($type == 'bar_3d') { $diagram->colour = $col; } $diagram->set_values($chartOpts['values']); if (isset($chartOpts['key'])) { $diagram->key($chartOpts['key'], 12); } $xAxis = $this->xAxis($options); if ($xAxis !== null) { $chart->set_x_axis($xAxis); } $yAxis = $this->yAxis($options); if ($xAxis !== null) { $chart->set_y_axis($yAxis); } if (isset($chartOpts['tooltip'])) { $diagram->set_tooltip($chartOpts['tooltip']); } $chart->add_element($diagram); } } return $chart->toPrettyString(); }
function get_statistic() { $this->load->library('OpenFlashChartLib', NULL, 'OFCL'); $data_1 = array(); $data_2 = array(); // generate 7 data points for ($i = 0; $i <= 7; $i++) { $x = mktime(0, 0, 0, date("m"), date("d") - $i, date('Y')); $param['sms_date'] = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - $i, date("Y"))); $param['user_id'] = $this->session->userdata('id_user'); $y = $this->Kalkun_model->get_sms_used('date', $param); $data_1[] = new scatter_value($x, $y); $data_2[] = $y; } $def = new solid_dot(); $def->size(4)->halo_size(0)->colour('#21759B')->tooltip('#date:d M y#<br>#val# SMS'); $line = new scatter_line('#21759B', 3); $line->set_values($data_1); $line->set_default_dot_style($def); $line->set_key("SMS used in last 7 days", 10); $x = new x_axis(); // grid line and tick every 10 $x->set_range(mktime(0, 0, 0, date("m"), date("d") - 7, date('Y')), mktime(0, 0, 0, date("m"), date("d"), date('Y'))); // show ticks and grid lines for every day: $x->set_steps(86400); $labels = new x_axis_labels(); // tell the labels to render the number as a date: $labels->text('#date:M-d#'); // generate labels for every day $labels->set_steps(86400); // only display every other label (every other day) $labels->visible_steps(1); $labels->rotate(45); // finally attach the label definition to the x axis $x->set_labels($labels); $y = new y_axis(); if (max($data_2) > 0) { $max = max($data_2); } else { $max = 10; } $y->set_range(0, $max, 10); $chart = new open_flash_chart(); //$chart->set_title( $title ); $chart->add_element($line); $chart->set_x_axis($x); $chart->set_y_axis($y); echo $chart->toPrettyString(); }
/** * 工作耗时饼猪状图 *@param $id 传入的项目ID *@examlpe */ public function buglevel($id) { $Public = A('Index', 'Public'); $App = A('App', 'Public'); Vendor('OpenFlash.open-flash-chart'); //main $Report = M('Report_table'); $id = intval($id); $color = array('#99C754', '#54C7C5', '#999999', '#996699', '#009900', '#77C600', '#ff7400', '#FF0000', '#4096ee', '#c79810'); $level = $App->getJson('yanzhongxing', '/Linkage'); $info = $Report->field('level,COUNT(id) as num')->where('pid=' . $id)->group('level')->order('level')->select(); //dump($info); $title = new title(); $title->set_style("font-size:13px; font-weight:bold;"); $pie = new pie(); $pie->set_alpha(0.8); $pie->start_angle(35); $pie->add_animation(new pie_fade()); $pie->add_animation(new pie_bounce(5)); $pie->gradient_fill(); $pie->set_tooltip('数量:#val#条, 占:#percent#'); $pie->set_colours($color); foreach ($info as $k => $t) { $obj = new pie_value(intval($t['num']), ''); $name = $Public->searchArr($level, 'id', $t['level']); $obj->set_label($name . ':' . $t['num'] . '条', $color[$k], 12); $dis_value[] = $obj; } //dump($dis_value); $pie->set_values($dis_value); $chart = new open_flash_chart(); $chart->set_title($title); $chart->add_element($pie); $chart->x_axis = null; $chart->bg_colour = '#FFFFFF'; echo $chart->toPrettyString(); }
public function get_jx_json_bar($info, $type = '') { $year = array_keys($info); $price = array_values($info); $chart = new open_flash_chart(); $chart->set_bg_colour('#FFFFFF'); //flash背景颜色 $x_labels = new x_axis_labels(); $x_labels->set_steps(1); $x_labels->set_size(12); $x_labels->set_colour('#000000'); if (count($year) > 0) { $x_labels->set_vertical(); } $x_labels->set_labels($year); // // 插入数据 $x = new x_axis(); $x->set_colour('#000000'); $x->set_grid_colour('#dadada'); $x->set_offset(true); $x->set_steps(1); // Add the X Axis Labels to the X Axis $x->set_labels($x_labels); $x->set_offset(true); $chart->set_x_axis($x); // $bar = new bar_filled( '#74b1e0', '#9dc7e8' ); // $bar->set_values( $price ); $price_array = array(); foreach ($price as $k => $v) { $price_array[$k] = new bar_value($v); $price_array[$k]->set_colour('#74b1e0'); if ($type == 'percent') { //$y->set_label_text("#val#%"); $price_array[$k]->set_tooltip($year[$k] . '<br>' . '' . number_format($v) . '%'); } else { $price_array[$k]->set_tooltip($year[$k] . '<br>' . '' . number_format($v)); } } $bar = new bar_glass(); $bar->set_values($price_array); $chart->add_element($bar); // // LOOK: // //$x_legend = new x_legend( '1983 to 2008' ); //$x_legend->set_style( '{font-size: 20px; color: #778877}' ); //$chart->set_x_legend( $x_legend ); // // remove this when the Y Axis is smarter // $y = new y_axis(); $max = $this->get_the_right_y(max($price)); $max = $max > 0 ? $max : 1; $y->set_range(0, ($max / 5 + 1) * 5, $max / 5 + 1); // if ($max > 20 && $max <= 100) { // // $y->set_range(0, $max, 10); // }elseif($max >= 10&&$max<=20){ // $y->set_range(0, $max, 5); // } // else { // $y->set_range(0, $max); // } $y->set_colour('#000000'); $y->set_grid_colour('#dadada'); if ($type == 'percent') { $y->set_label_text(" #val#%"); } else { $y->set_label_text(" #val#"); } $chart->add_y_axis($y); $info = $chart->toPrettyString(); return $info; }
function report_chart($data) { // Chart // // This is the MODEL section: // include 'open-flash-chart/php-ofc-library/open-flash-chart.php'; $title = new title("Availability Report "); $pie = new pie(); $pie->set_alpha(0.9); $pie->radius(90); //$pie->start_angle(100); $pie->add_animation(new pie_fade()); $pie->set_tooltip('#label#: #percent#<br>#val# of #total#<br>'); $status_colors = array(ok => '#77CC6D', critical => '#FF0000', warning => '#FFD40F', unknown => '#6D86CC', no_data => '#848484'); $status_name = array(ok => 'Ok', critical => 'Critical', warning => 'Warning', unknown => 'Unknown', no_data => 'No Data'); $col = array(); $d = array(); foreach ($data as $name => $value) { if ($value > 0) { $d[] = new pie_value($value * 1, "{$status_name[$name]}"); array_push($col, $status_colors[$name]); } } $pie->set_values($d); $pie->set_colours($col); $chart = new open_flash_chart(); $chart->set_title($title); $chart->add_element($pie); $chart->x_axis = null; $chart->set_bg_colour('#202020'); $title->set_style("{font-size: 16px; font-family: Times New Roman; font-weight: bold; color: #000; text-align: center;}"); $chart->set_bg_colour('#FFFFFF'); $chart->set_title($title); // This is the VIEW section: // Should print this first. // $heading = "\n <script type='text/javascript' src='open-flash-chart/js/json/json2.js'></script>\n <script type='text/javascript' src='open-flash-chart/js/swfobject.js'></script>\n <script type='text/javascript'>\n swfobject.embedSWF('open-flash-chart/open-flash-chart.swf', 'my_chart', '300', '300', '9.0.0');\n </script>\n\n <script type='text/javascript'>\n\n function open_flash_chart_data() {\n return JSON.stringify(data);\n }\n\n function findSWF(movieName) {\n if (navigator.appName.indexOf('Microsoft')!= -1) {\n return window[movieName];\n } else {\n return document[movieName];\n }\n }\n \n var data = " . $chart->toPrettyString() . "\n\n </script>\n\n\n <script type=\"text/javascript\">\n \n OFC = {};\n \n OFC.jquery = {\n name: 'jQuery',\n version: function(src) { return \$('#'+ src)[0].get_version() },\n rasterize: function (src, dst) { \$('#'+ dst).replaceWith(OFC.jquery.image(src)) },\n image: function(src) { return \"<img src='data:image/png;base64,\" + \$('#'+src)[0].get_img_binary() + \"' />\"},\n popup: function(src) {\n var img_win = window.open('', 'Charts: Export as Image')\n with(img_win.document) {\n write('<html><head><title>Charts: Export as Image<\\/title><\\/head><body>' + OFC.jquery.image(src) + '<\\/body><\\/html>') }\n // stop the 'loading...' message\n img_win.document.close();\n }\n }\n \n // Using_ an object as namespaces is JS Best Practice. I like the Control.XXX style.\n //if (!Control) {var Control = {}}\n //if (typeof(Control == \"undefined\")) {var Control = {}}\n if (typeof(Control == \"undefined\")) {var Control = {OFC: OFC.jquery}}\n \n \n // By default, right-clicking on OFC and choosing \"save image locally\" calls this function.\n // You are free to change the code in OFC and call my wrapper (Control.OFC.your_favorite_save_method)\n // function save_image() { alert(1); Control.OFC.popup('my_chart') }\n function save_image() { alert(\"Your image will be displayed in a new window\"); OFC.jquery.popup('my_chart') }\n </script>\n <div id='my_chart' style='float:left; margin-left:28px;'></div>\n "; return $heading; }
function result_screen($mode = 'reg') { global $month_names; $page_title = "Statistic Center Results"; $page_detail = " "; // ----------------------------------------- if (!checkdate($_POST['to_month'], $_POST['to_day'], $_POST['to_year'])) { die("The 'Date To:' time is incorrect, please check the input and try again"); } if (!checkdate($_POST['from_month'], $_POST['from_day'], $_POST['from_year'])) { die("The 'Date From:' time is incorrect, please check the input and try again"); } // ----------------------------------------- $to_time = mktime(12, 0, 0, $_POST['to_month'], $_POST['to_day'], $_POST['to_year']); $from_time = mktime(12, 0, 0, $_POST['from_month'], $_POST['from_day'], $_POST['from_year']); // $sql_date_to = date("Y-m-d",$to_time); // $sql_date_from = date("Y-m-d",$from_time); $human_to_date = getdate($to_time); $human_from_date = getdate($from_time); // ----------------------------------------- if ($mode == 'reg') { $table = 'Registration Statistics'; $sql_table = 'users'; $sql_field = 'added'; $page_detail = "Showing the number of users registered. (Note: All times based on GMT)"; } else { if ($mode == 'rate') { $table = 'Rating Statistics'; $sql_table = 'ratings'; $sql_field = 'added'; $page_detail = "Showing the number of ratings. (Note: All times based on GMT)"; } else { if ($mode == 'post') { $table = 'Post Statistics'; $sql_table = 'posts'; $sql_field = 'added'; $page_detail = "Showing the number of posts. (Note: All times based on GMT)"; } else { if ($mode == 'msg') { $table = 'PM Sent Statistics'; $sql_table = 'messages'; $sql_field = 'added'; $page_detail = "Showing the number of sent messages. (Note: All times based on GMT)"; } else { if ($mode == 'torr') { $table = 'Torrent Statistics'; $sql_table = 'torrents'; $sql_field = 'added'; $page_detail = "Showing the number of Torrents. (Note: All times based on GMT)"; } else { if ($mode == 'bans') { $table = 'Ban Statistics'; $sql_table = 'bans'; $sql_field = 'added'; $page_detail = "Showing the number of Bans. (Note: All times based on GMT)"; } else { if ($mode == 'comm') { $table = 'Comment Statistics'; $sql_table = 'comments'; $sql_field = 'added'; $page_detail = "Showing the number of torrent Comments. (Note: All times based on GMT)"; } else { if ($mode == 'new') { $table = 'News Statistics'; $sql_table = 'news'; $sql_field = 'added'; $page_detail = "Showing the number of News Items added. (Note: All times based on GMT)"; } else { if ($mode == 'poll') { $table = 'Poll Statistics'; $sql_table = 'polls'; $sql_field = 'added'; $page_detail = "Showing the number of Polls added. (Note: All times based on GMT)"; } else { if ($mode == 'rqst') { $table = 'Request Statistics'; $sql_table = 'requests'; $sql_field = 'added'; $page_detail = "Showing the number of Requests made. (Note: All times based on GMT)"; } } } } } } } } } } switch ($_POST['timescale']) { case 'daily': $sql_date = "%w %U %m %Y"; $php_date = "F jS - Y"; // $sql_scale = "DAY"; break; case 'monthly': $sql_date = "%m %Y"; $php_date = "F Y"; // $sql_scale = "MONTH"; break; default: // weekly $sql_date = "%U %Y"; $php_date = " [F Y]"; // $sql_scale = "WEEK"; break; } $sortby = isset($_POST['sortby']) ? mysql_real_escape_string($_POST['sortby']) : ""; // $sortby = sqlesc($sortby); $sqlq = "SELECT UNIX_TIMESTAMP(MAX({$sql_field})) as result_maxdate,\n\t\t\t\t COUNT(*) as result_count,\n\t\t\t\t DATE_FORMAT({$sql_field},'{$sql_date}') AS result_time\n\t\t\t\t FROM {$sql_table}\n\t\t\t\t WHERE UNIX_TIMESTAMP({$sql_field}) > '{$from_time}'\n\t\t\t\t AND UNIX_TIMESTAMP({$sql_field}) < '{$to_time}'\n\t\t\t\t GROUP BY result_time\n\t\t\t\t ORDER BY {$sql_field} {$sortby}"; $res = @mysql_query($sqlq); $running_total = 0; $max_result = 0; $results = array(); if (mysql_num_rows($res)) { while ($row = mysql_fetch_assoc($res)) { if ($row['result_count'] > $max_result) { $max_result = $row['result_count']; } $running_total += $row['result_count']; $results[] = array('result_maxdate' => $row['result_maxdate'], 'result_count' => $row['result_count'], 'result_time' => $row['result_time']); } include 'chart/php-ofc-library/open-flash-chart.php'; foreach ($results as $pOOp => $data) { $counts[] = (int) $data['result_count']; if ($_POST['timescale'] == 'weekly') { $labes[] = "Week #" . strftime("%W", $data['result_maxdate']) . "\n" . date($php_date, $data['result_maxdate']); } else { $labes[] = date($php_date, $data['result_maxdate']); } } $title = new title($page_title . "\n" . ucfirst($_POST['timescale']) . " " . $table . " " . $human_from_date['mday'] . " " . $month_names[$human_from_date['mon']] . " " . $human_from_date['year'] . " to " . $human_to_date['mday'] . " " . $month_names[$human_to_date['mon']] . " " . $human_to_date['year']); $chart = new open_flash_chart(); $chart->set_title($title); $line_1 = new line_hollow(); $line_1->set_values($counts); $line_1->set_key($table . " | Total: " . $running_total, 12); $line_1->set_halo_size(1); $line_1->set_width(2); $line_1->set_colour('#0099FF'); $line_1->set_dot_size(5); $chart->add_element($line_1); $x_labels = new x_axis_labels(); $x_labels->set_steps(2); $x_labels->set_vertical(); $x_labels->set_colour('#000000'); $x_labels->set_size(12); $x_labels->set_labels($labes); $x = new x_axis(); $x->set_colours('#A2ACBA', '#ECFFAF'); $x->set_steps(2); $x->set_labels($x_labels); $chart->set_x_axis($x); $y = new y_axis(); $y->set_steps(2); $y->set_colour('#A2ACBA'); $y->set_range(0, max($counts) + 5, 50); $chart->add_y_axis($y); $cont = $chart->toPrettyString(); // toFile($_SERVER["DOCUMENT_ROOT"]."/chart/","chart.json",$cont,false); // unset($cont); $html = "<script type=\"text/javascript\" src=\"chart/js/json/json2.js\"></script>"; $html .= "<script type=\"text/javascript\" src=\"chart/js/swfobject.js\"></script>"; $html .= "<script type=\"text/javascript\">\n\n\t\t\t\tfunction open_flash_chart_data()\n\t\t\t\t{\n\t\t\t\treturn JSON.stringify(data);\n\t\t\t\t}\n\n\t\t\t\tfunction findSWF(movieName) {\n\t\t\t\t if (navigator.appName.indexOf(\"Microsoft\")!= -1) {\n\t\t\t\t\treturn window[movieName];\n\t\t\t\t } else {\n\t\t\t\t\treturn document[movieName];\n\t\t\t\t }\n\t\t\t\t}\n\n\t\t\t\tvar data = " . $cont . ";\n\n\t\t\t\t\t swfobject.embedSWF(\"chart/open-flash-chart.swf\", \"my_chart\", \"800\", \"" . (max($counts) * 5 < 200 ? "250" : (max($counts) * 5 > 400 ? "400" : max($counts) * 5)) . "\", \"9.0.0\", \"expressInstall.swf\", {\"loading\":\"Please wait while the stats are loaded!\"} );\n\t\t\t\t\t </script>"; $html .= "<div id=\"my_chart\"></div>"; } else { $html .= "No results found\n"; } print $html . "<br />"; }
function stacked_bar_chart($host_instance_list) { $title = new title('所有instance实际内存使用'); $title->set_style("{color: #567300; font-size: 16px; font-weight:bold;}"); $bar_stack = new bar_stack(); $bar_stack->set_colours(array('#C4D318', '#7D7B6A')); $max = 64; foreach ($host_instance_list as $i => $instance) { $jvmmem = isset($instance['jvmmem']) ? explode('/', $instance['jvmmem']) : array(); if ($jvmmem) { foreach ($jvmmem as &$j) { $j = intval($j); } $max = $max < $jvmmem[1] ? $jvmmem[1] : $max; $jvmmem[1] = $jvmmem[1] - $jvmmem[0]; } $bar_stack->append_stack($jvmmem); $lables[] = $instance['port_num']; $services[$i] = $instance['service_name']; } $bar_stack->set_keys(array(new bar_stack_key('#C4D318', 'used', 13), new bar_stack_key('#7D7B6A', 'total', 13))); $bar_stack->set_on_click('(function(x){var services=' . json_encode($services) . ';alert(services[x]);})'); //js $bar_stack->set_tooltip('#val#M,共#total#M'); $y = new y_axis(); $y->set_range(0, $max + 32, 256); $x = new x_axis(); $x->set_labels_from_array($lables); $tooltip = new tooltip(); $tooltip->set_hover(); $chart = new open_flash_chart(); $chart->set_title($title); $chart->add_element($bar_stack); $chart->set_x_axis($x); $chart->add_y_axis($y); $chart->set_tooltip($tooltip); return $chart->toPrettyString(); }
/** * public static function to generate two pie charts for the mailing reports * It was extracted because there are two graph in mailing for each mailing and general mailing which is the total * * @param array $results data needed for graph values */ public static function mailingPieChart($results) { $data = array(); //First Pie, Pie Chart for HTML/TEXT format $valuesFormat = array(); $pieHtmlValues = new pie_value((int) $results['html_sent'], _JNEWS_GRAPH_LBL_HTML); $pieTextValues = new pie_value((int) $results['text_sent'], _JNEWS_GRAPH_LBL_TEXT); $valuesFormat[] = $pieHtmlValues; $valuesFormat[] = $pieTextValues; if (empty($results['html_sent']) && empty($results['text_sent'])) { $data['pie1'] = 'empty'; } else { $css = '{font-size:15px;font-weight:bold;color:#0B55C4;}'; $title = new title(_JNEWS_GRAPH_TITLE_FORMAT); //Name of the newsletter $title->set_style($css); $pieMailing = new pie(); $pieMailing->set_alpha(0.6); $pieMailing->set_start_angle(35); $pieMailing->add_animation(new pie_fade()); $pieMailing->set_tooltip('#val#<br>#percent# of 100%'); $pieMailing->set_colours(array('#156cbd', '#368d03', '#f7941d', '#ed145a', '#92278f', '#156cbd', '#182972', '#3e5d2b', '#db4b19', '#9d0039', '#440e62')); $pieMailing->set_values($valuesFormat); $chartPie = new open_flash_chart(); $chartPie->set_title($title); $chartPie->add_element($pieMailing); $chartPie->set_bg_colour('#FFFFFF'); $data['pie1'] = $chartPie->toPrettyString(); } //Second chart, Pie chart for the status of mailing process $valuesProcess = array(); //$pieFailedlValues = new pie_value((int)$results['failed'], _JNEWS_MAILING_FAILED); //$pieBounceValues = new pie_value((int)$results['bounces'], _JNEWS_MAILING_BOUNCES); $piePendingValues = new pie_value((int) $results['pending'], _JNEWS_MAILING_PENDING); $pieSentValues = new pie_value((int) $results['sent'], _JNEWS_MAILING_SENT); //$valuesProcess[] = $pieFailedlValues; //$valuesProcess[] = $pieBounceValues; $valuesProcess[] = $piePendingValues; $valuesProcess[] = $pieSentValues; //if(!empty($results['failed']) && !empty($results['pending']) && !empty($results['bounces'])){ if (!empty($results['sent']) || !empty($results['pending'])) { $css = '{font-size:15px;font-weight:bold;color:#0B55C4;}'; $title = new title(_JNEWS_GRAPH_PIE_TITLE_MAIL); //Name of the newsletter $title->set_style($css); $pieMailing = new pie(); $pieMailing->set_alpha(0.6); $pieMailing->set_start_angle(35); $pieMailing->add_animation(new pie_fade()); $pieMailing->set_tooltip('#val#<br>#percent# of 100%'); $pieMailing->set_colours(array('#156cbd', '#368d03', '#f7941d', '#ed145a', '#92278f', '#156cbd', '#182972', '#3e5d2b', '#db4b19', '#9d0039', '#440e62')); $pieMailing->set_values($valuesProcess); $chartPie = new open_flash_chart(); $chartPie->set_title($title); $chartPie->add_element($pieMailing); $chartPie->set_bg_colour('#FFFFFF'); $data['pie2'] = $chartPie->toPrettyString(); } else { $data['pie2'] = 'empty'; } return $data; }
function _render_statistic($x = array(), $yout = array(), $yin = array(), $type = 'bar', $points) { $this->load->helper('date'); $this->load->library('OpenFlashChartLib', NULL, 'OFCL'); $data_1 = array(); $data_2 = array(); $data_3 = array(); switch ($type) { case 'bar': for ($i = 0; $i <= $points; $i++) { $data_1[$i] = $x[$i]; $data_2[$i] = (int) $yout[$i]; // force to integer $data_3[$i] = (int) $yin[$i]; // force to integer } $data_1 = array_reverse($data_1); $data_2 = array_reverse($data_2); $data_3 = array_reverse($data_3); $bar_1 = new bar(); $bar_1->set_values($data_3); $bar_1->set_colour('#639F45'); $bar_1->key(lang('kalkun_incoming_sms'), 10); $bar_1->set_tooltip('#x_label#<br>#val# SMS'); //$bar_1->set_key("SMS used in last 7 days", 10); $bar_2 = new bar(); $bar_2->set_values($data_2); $bar_2->set_colour('#21759B'); $bar_2->key(lang('kalkun_outgoing_sms'), 10); $bar_2->set_tooltip('#x_label#<br>#val# SMS'); $x = new x_axis(); $labels = new x_axis_labels(); $labels->set_labels($data_1); $labels->set_steps(1); $x->set_labels($labels); $y = new y_axis(); $max = max(max($data_2), max($data_3)); if ($max < 10) { $max = 10; } $max = ceil($max / 5) * 5; $range = ceil($max / 5); $range = ceil($range / 10) * 10; $y->set_range(0, $max, $range); $element1 = $bar_1; $element2 = $bar_2; break; case 'line': for ($i = 0; $i <= 7; $i++) { $data_1[$i] = new scatter_value($x[$i], $yin[$i]); $data_2[$i] = new scatter_value($x[$i], $yout[$i]); $data_3[$i] = (int) $yin[$i]; $data_4[$i] = (int) $yout[$i]; } $def = new solid_dot(); $def->size(4)->halo_size(0)->colour('#21759B')->tooltip('#date:d M y#<br>#val# SMS'); $line_1 = new scatter_line('#639F45', 3); $line_1->set_values($data_1); $line_1->set_default_dot_style($def); $line_1->set_key("Incoming SMS", 10); $line_2 = new scatter_line('#21759B', 3); $line_2->set_values($data_2); $line_2->set_default_dot_style($def); $line_2->set_key("Outgoing SMS", 10); $x = new x_axis(); // grid line and tick every 10 $x->set_range(mktime(0, 0, 0, date("m"), date("d") - 7, date('Y')), mktime(0, 0, 0, date("m"), date("d"), date('Y'))); // show ticks and grid lines for every day: $x->set_steps(86400); $labels = new x_axis_labels(); // tell the labels to render the number as a date: $labels->text('#date:M-d#'); // generate labels for every day $labels->set_steps(86400); // only display every other label (every other day) $labels->visible_steps(1); $labels->rotate(45); // finally attach the label definition to the x axis $x->set_labels($labels); $y = new y_axis(); $max = max(max($data_3), max($data_4)); if ($max < 1) { $max = 10; } $y->set_range(0, $max, round($max / 100) * 10); $element1 = $line_1; $element2 = $line_2; break; } $chart = new open_flash_chart(); $chart->add_element($element1); $chart->add_element($element2); $chart->set_x_axis($x); $chart->set_y_axis($y); echo $chart->toPrettyString(); }
public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId) { $sHtml = ''; // Add the extra params into the filter if they make sense for such a filter $bDoSearch = utils::ReadParam('dosearch', false); if ($this->m_oSet == null) { $aQueryParams = array(); if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } if ($this->m_sStyle != 'links') { $oAppContext = new ApplicationContext(); $sClass = $this->m_oFilter->GetClass(); $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($sClass)); $aCallSpec = array($sClass, 'MapContextParam'); if (is_callable($aCallSpec)) { foreach ($oAppContext->GetNames() as $sContextParam) { $sParamCode = call_user_func($aCallSpec, $sContextParam); //Map context parameter to the value/filter code depending on the class if (!is_null($sParamCode)) { $sParamValue = $oAppContext->GetCurrentValue($sContextParam, null); if (!is_null($sParamValue)) { $aExtraParams[$sParamCode] = $sParamValue; } } } } foreach ($aFilterCodes as $sFilterCode) { $externalFilterValue = utils::ReadParam($sFilterCode, '', false, 'raw_data'); $condition = null; if (isset($aExtraParams[$sFilterCode])) { $condition = $aExtraParams[$sFilterCode]; } if ($bDoSearch && $externalFilterValue != "") { // Search takes precedence over context params... unset($aExtraParams[$sFilterCode]); if (!is_array($externalFilterValue)) { $condition = trim($externalFilterValue); } else { if (count($externalFilterValue) == 1) { $condition = trim($externalFilterValue[0]); } else { $condition = $externalFilterValue; } } } if (!is_null($condition)) { $sOpCode = null; // default operator if (is_array($condition)) { // Multiple values, add them as AND X IN (v1, v2, v3...) $sOpCode = 'IN'; } $this->AddCondition($sFilterCode, $condition, $sOpCode); } } if ($bDoSearch) { // Keep the table_id identifying this table if we're performing a search $sTableId = utils::ReadParam('_table_id_', null, false, 'raw_data'); if ($sTableId != null) { $aExtraParams['table_id'] = $sTableId; } } } $aOrderBy = array(); if (isset($aExtraParams['order_by'])) { // Convert the string describing the order_by parameter into an array // The syntax is +attCode1,-attCode2 // attCode1 => ascending, attCode2 => descending $aTemp = explode(',', $aExtraParams['order_by']); foreach ($aTemp as $sTemp) { $aMatches = array(); if (preg_match('/^([+-])?(.+)$/', $sTemp, $aMatches)) { $bAscending = true; if ($aMatches[1] == '-') { $bAscending = false; } $aOrderBy[$aMatches[2]] = $bAscending; } } } $this->m_oSet = new CMDBObjectSet($this->m_oFilter, $aOrderBy, $aQueryParams); } switch ($this->m_sStyle) { case 'count': if (isset($aExtraParams['group_by'])) { if (isset($aExtraParams['group_by_label'])) { $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']); $sGroupByLabel = $aExtraParams['group_by_label']; } else { // Backward compatibility: group_by is simply a field id $sAlias = $this->m_oFilter->GetClassAlias(); $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias); $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']); } $aGroupBy = array(); $aGroupBy['grouped_by_1'] = $oGroupByExp; $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true); $aRes = CMDBSource::QueryToArray($sSql); $aGroupBy = array(); $aLabels = array(); $aValues = array(); $iTotalCount = 0; foreach ($aRes as $iRow => $aRow) { $sValue = $aRow['grouped_by_1']; $aValues[$iRow] = $sValue; $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue); $aLabels[$iRow] = $sHtmlValue; $aGroupBy[$iRow] = (int) $aRow['_itop_count_']; $iTotalCount += $aRow['_itop_count_']; } $aData = array(); $oAppContext = new ApplicationContext(); $sParams = $oAppContext->GetForLink(); foreach ($aGroupBy as $iRow => $iCount) { // Build the search for this subset $oSubsetSearch = $this->m_oFilter->DeepClone(); $oCondition = new BinaryExpression($oGroupByExp, '=', new ScalarExpression($aValues[$iRow])); $oSubsetSearch->AddConditionExpression($oCondition); $sFilter = urlencode($oSubsetSearch->serialize()); $aData[] = array('group' => $aLabels[$iRow], 'value' => "<a href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/UI.php?operation=search&dosearch=1&{$sParams}&filter={$sFilter}\">{$iCount}</a>"); // TO DO: add the context information } $aAttribs = array('group' => array('label' => $sGroupByLabel, 'description' => ''), 'value' => array('label' => Dict::S('UI:GroupBy:Count'), 'description' => Dict::S('UI:GroupBy:Count+'))); $sFormat = isset($aExtraParams['format']) ? $aExtraParams['format'] : 'UI:Pagination:HeaderNoSelection'; $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iTotalCount)); $sHtml .= $oPage->GetTable($aAttribs, $aData); } else { // Simply count the number of elements in the set $iCount = $this->m_oSet->Count(); $sFormat = 'UI:CountOfObjects'; if (isset($aExtraParams['format'])) { $sFormat = $aExtraParams['format']; } $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iCount)); } break; case 'join': $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array(); if (!isset($aExtraParams['group_by'])) { $sHtml .= $oPage->GetP(Dict::S('UI:Error:MandatoryTemplateParameter_group_by')); } else { $aGroupByFields = array(); $aGroupBy = explode(',', $aExtraParams['group_by']); foreach ($aGroupBy as $sGroupBy) { $aMatches = array(); if (preg_match('/^(.+)\\.(.+)$/', $sGroupBy, $aMatches) > 0) { $aGroupByFields[] = array('alias' => $aMatches[1], 'att_code' => $aMatches[2]); } } if (count($aGroupByFields) == 0) { $sHtml .= $oPage->GetP(Dict::Format('UI:Error:InvalidGroupByFields', $aExtraParams['group_by'])); } else { $aResults = array(); $aCriteria = array(); while ($aObjects = $this->m_oSet->FetchAssoc()) { $aKeys = array(); foreach ($aGroupByFields as $aField) { $sAlias = $aField['alias']; if (is_null($aObjects[$sAlias])) { $aKeys[$sAlias . '.' . $aField['att_code']] = ''; } else { $aKeys[$sAlias . '.' . $aField['att_code']] = $aObjects[$sAlias]->Get($aField['att_code']); } } $sCategory = implode($aKeys, ' '); $aResults[$sCategory][] = $aObjects; $aCriteria[$sCategory] = $aKeys; } $sHtml .= "<table>\n"; // Construct a new (parametric) query that will return the content of this block $oBlockFilter = $this->m_oFilter->DeepClone(); $aExpressions = array(); $index = 0; foreach ($aGroupByFields as $aField) { $aExpressions[] = '`' . $aField['alias'] . '`.`' . $aField['att_code'] . '` = :param' . $index++; } $sExpression = implode(' AND ', $aExpressions); $oExpression = Expression::FromOQL($sExpression); $oBlockFilter->AddConditionExpression($oExpression); $aExtraParams['menu'] = false; foreach ($aResults as $sCategory => $aObjects) { $sHtml .= "<tr><td><h1>{$sCategory}</h1></td></tr>\n"; if (count($aDisplayAliases) == 1) { $aSimpleArray = array(); foreach ($aObjects as $aRow) { $oObj = $aRow[$aDisplayAliases[0]]; if (!is_null($oObj)) { $aSimpleArray[] = $oObj; } } $oSet = CMDBObjectSet::FromArray($this->m_oFilter->GetClass(), $aSimpleArray); $sHtml .= "<tr><td>" . cmdbAbstractObject::GetDisplaySet($oPage, $oSet, $aExtraParams) . "</td></tr>\n"; } else { $index = 0; $aArgs = array(); foreach ($aGroupByFields as $aField) { $aArgs['param' . $index] = $aCriteria[$sCategory][$aField['alias'] . '.' . $aField['att_code']]; $index++; } $oSet = new CMDBObjectSet($oBlockFilter, array(), $aArgs); $sHtml .= "<tr><td>" . cmdbAbstractObject::GetDisplayExtendedSet($oPage, $oSet, $aExtraParams) . "</td></tr>\n"; } } $sHtml .= "</table>\n"; } } break; case 'list': $aClasses = $this->m_oSet->GetSelectedClasses(); $aAuthorizedClasses = array(); if (count($aClasses) > 1) { // Check the classes that can be read (i.e authorized) by this user... foreach ($aClasses as $sAlias => $sClassName) { if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $this->m_oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS)) { $aAuthorizedClasses[$sAlias] = $sClassName; } } if (count($aAuthorizedClasses) > 0) { if ($this->m_oSet->Count() > 0) { $sHtml .= cmdbAbstractObject::GetDisplayExtendedSet($oPage, $this->m_oSet, $aExtraParams); } else { // Empty set $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay')); } } else { // Not authorized $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay')); } } else { // The list is made of only 1 class of objects, actions on the list are possible if ($this->m_oSet->Count() > 0 && UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) { $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams); } else { $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay')); $sClass = $this->m_oFilter->GetClass(); $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true; if ($bDisplayMenu) { if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES) { $sLinkTarget = ''; $oAppContext = new ApplicationContext(); $sParams = $oAppContext->GetForLink(); // 1:n links, populate the target object as a default value when creating a new linked object if (isset($aExtraParams['target_attr'])) { $sLinkTarget = ' target="_blank" '; $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id']; } $sDefault = ''; if (!empty($aExtraParams['default'])) { foreach ($aExtraParams['default'] as $sKey => $sValue) { $sDefault .= "&default[{$sKey}]={$sValue}"; } } $sHtml .= $oPage->GetP("<a{$sLinkTarget} href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/UI.php?operation=new&class={$sClass}&{$sParams}{$sDefault}\">" . Dict::Format('UI:ClickToCreateNew', Metamodel::GetName($sClass)) . "</a>\n"); } } } } break; case 'links': //$bDashboardMode = isset($aExtraParams['dashboard']) ? ($aExtraParams['dashboard'] == 'true') : false; //$bSelectMode = isset($aExtraParams['select']) ? ($aExtraParams['select'] == 'true') : false; if ($this->m_oSet->Count() > 0 && UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) { //$sLinkage = isset($aExtraParams['linkage']) ? $aExtraParams['linkage'] : ''; $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams); } else { $sClass = $this->m_oFilter->GetClass(); $oAttDef = MetaModel::GetAttributeDef($sClass, $this->m_aParams['target_attr']); $sTargetClass = $oAttDef->GetTargetClass(); $sHtml .= $oPage->GetP(Dict::Format('UI:NoObject_Class_ToDisplay', MetaModel::GetName($sTargetClass))); $bDisplayMenu = isset($this->m_aParams['menu']) ? $this->m_aParams['menu'] == true : true; if ($bDisplayMenu) { if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES) { $oAppContext = new ApplicationContext(); $sParams = $oAppContext->GetForLink(); $sDefaults = ''; if (isset($this->m_aParams['default'])) { foreach ($this->m_aParams['default'] as $sName => $sValue) { $sDefaults .= '&' . urlencode($sName) . '=' . urlencode($sValue); } } $sHtml .= $oPage->GetP("<a href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/UI.php?operation=modify_links&class={$sClass}&sParams&link_attr=" . $aExtraParams['link_attr'] . "&id=" . $aExtraParams['object_id'] . "&target_class={$sTargetClass}&addObjects=true{$sDefaults}\">" . Dict::Format('UI:ClickToCreateNew', Metamodel::GetName($sClass)) . "</a>\n"); } } } break; case 'details': while ($oObj = $this->m_oSet->Fetch()) { $sHtml .= $oObj->GetDetails($oPage); // Still used ??? } break; case 'actions': $sClass = $this->m_oFilter->GetClass(); $oAppContext = new ApplicationContext(); $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false; if ($bContextFilter) { $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass())); foreach ($oAppContext->GetNames() as $sFilterCode) { $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null); if (!is_null($sContextParamValue) && !empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode)) { $this->AddCondition($sFilterCode, $sContextParamValue); } } $aQueryParams = array(); if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams); } $iCount = $this->m_oSet->Count(); $sHyperlink = utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?operation=search&' . $oAppContext->GetForLink() . '&filter=' . urlencode($this->m_oFilter->serialize()); $sHtml .= '<p><a class="actions" href="' . $sHyperlink . '">'; // Note: border set to 0 due to various browser interpretations (IE9 adding a 2px border) $sHtml .= MetaModel::GetClassIcon($sClass, true, 'float;left;margin-right:10px;border:0;'); $sHtml .= MetaModel::GetName($sClass) . ': ' . $iCount . '</a></p>'; $sParams = $oAppContext->GetForLink(); $sHtml .= '<p>'; if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY)) { $sHtml .= "<a href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/UI.php?operation=new&class={$sClass}&{$sParams}\">" . Dict::Format('UI:ClickToCreateNew', MetaModel::GetName($sClass)) . "</a><br/>\n"; } $sHtml .= "<a href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/UI.php?operation=search_form&do_search=0&class={$sClass}&{$sParams}\">" . Dict::Format('UI:SearchFor_Class', MetaModel::GetName($sClass)) . "</a>\n"; $sHtml .= '</p>'; break; case 'summary': $sClass = $this->m_oFilter->GetClass(); $oAppContext = new ApplicationContext(); $sTitle = isset($aExtraParams['title[block]']) ? $aExtraParams['title[block]'] : ''; $sLabel = isset($aExtraParams['label[block]']) ? $aExtraParams['label[block]'] : ''; $sStateAttrCode = isset($aExtraParams['status[block]']) ? $aExtraParams['status[block]'] : 'status'; $sStatesList = isset($aExtraParams['status_codes[block]']) ? $aExtraParams['status_codes[block]'] : ''; $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false; if ($bContextFilter) { $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass())); foreach ($oAppContext->GetNames() as $sFilterCode) { $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null); if (!is_null($sContextParamValue) && !empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode)) { $this->AddCondition($sFilterCode, $sContextParamValue); } } $aQueryParams = array(); if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams); } // Summary details $aCounts = array(); $aStateLabels = array(); if (!empty($sStateAttrCode) && !empty($sStatesList)) { $aStates = explode(',', $sStatesList); $oAttDef = MetaModel::GetAttributeDef($sClass, $sStateAttrCode); foreach ($aStates as $sStateValue) { $oFilter = $this->m_oFilter->DeepClone(); $oFilter->AddCondition($sStateAttrCode, $sStateValue, '='); $oSet = new DBObjectSet($oFilter); $aCounts[$sStateValue] = $oSet->Count(); $aStateLabels[$sStateValue] = htmlentities($oAttDef->GetValueLabel($sStateValue), ENT_QUOTES, 'UTF-8'); if ($aCounts[$sStateValue] == 0) { $aCounts[$sStateValue] = '-'; } else { $sHyperlink = utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?operation=search&' . $oAppContext->GetForLink() . '&filter=' . urlencode($oFilter->serialize()); $aCounts[$sStateValue] = "<a href=\"{$sHyperlink}\">{$aCounts[$sStateValue]}</a>"; } } } $sHtml .= '<div class="summary-details"><table><tr><th>' . implode('</th><th>', $aStateLabels) . '</th></tr>'; $sHtml .= '<tr><td>' . implode('</td><td>', $aCounts) . '</td></tr></table></div>'; // Title & summary $iCount = $this->m_oSet->Count(); $sHyperlink = utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?operation=search&' . $oAppContext->GetForLink() . '&filter=' . urlencode($this->m_oFilter->serialize()); $sHtml .= '<h1>' . Dict::S(str_replace('_', ':', $sTitle)) . '</h1>'; $sHtml .= '<a class="summary" href="' . $sHyperlink . '">' . Dict::Format(str_replace('_', ':', $sLabel), $iCount) . '</a>'; $sHtml .= '<div style="clear:both;"></div>'; break; case 'csv': $bAdvancedMode = utils::ReadParam('advanced', false); $sCsvFile = strtolower($this->m_oFilter->GetClass()) . '.csv'; $sDownloadLink = utils::GetAbsoluteUrlAppRoot() . 'webservices/export.php?expression=' . urlencode($this->m_oFilter->ToOQL(true)) . '&format=csv&filename=' . urlencode($sCsvFile); $sLinkToToggle = utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?operation=search&' . $oAppContext->GetForLink() . '&filter=' . urlencode($this->m_oFilter->serialize()) . '&format=csv'; if ($bAdvancedMode) { $sDownloadLink .= '&fields_advanced=1'; $sChecked = 'CHECKED'; } else { $sLinkToToggle = $sLinkToToggle . '&advanced=1'; $sChecked = ''; } $sAjaxLink = $sDownloadLink . '&charset=UTF-8'; // Includes &fields_advanced=1 if in advanced mode /* $sCSVData = cmdbAbstractObject::GetSetAsCSV($this->m_oSet, array('fields_advanced' => $bAdvancedMode)); $sCharset = MetaModel::GetConfig()->Get('csv_file_default_charset'); if ($sCharset == 'UTF-8') { $bLostChars = false; } else { $sConverted = @iconv('UTF-8', $sCharset, $sCSVData); $sRestored = @iconv($sCharset, 'UTF-8', $sConverted); $bLostChars = ($sRestored != $sCSVData); } if ($bLostChars) { $sCharsetNotice = " <span id=\"csv_charset_issue\">"; $sCharsetNotice .= '<img src="../images/error.png" style="vertical-align:middle"/>'; $sCharsetNotice .= "</span>"; $sTip = "<p>".htmlentities(Dict::S('UI:CSVExport:LostChars'), ENT_QUOTES, 'UTF-8')."</p>"; $sTip .= "<p>".htmlentities(Dict::Format('UI:CSVExport:LostChars+', $sCharset), ENT_QUOTES, 'UTF-8')."</p>"; $oPage->add_ready_script("$('#csv_charset_issue').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );"); } else { $sCharsetNotice = ''; } */ $sCharsetNotice = false; $sHtml .= "<div>"; $sHtml .= '<table style="width:100%" class="transparent">'; $sHtml .= '<tr>'; $sHtml .= '<td><a href="' . $sDownloadLink . '">' . Dict::Format('UI:Download-CSV', $sCsvFile) . '</a>' . $sCharsetNotice . '</td>'; $sHtml .= '<td style="text-align:right"><input type="checkbox" ' . $sChecked . ' onClick="window.location.href=\'' . $sLinkToToggle . '\'"> ' . Dict::S('UI:CSVExport:AdvancedMode') . '</td>'; $sHtml .= '</tr>'; $sHtml .= '</table>'; if ($bAdvancedMode) { $sHtml .= "<p>"; $sHtml .= htmlentities(Dict::S('UI:CSVExport:AdvancedMode+'), ENT_QUOTES, 'UTF-8'); $sHtml .= "</p>"; } $sHtml .= "</div>"; $sHtml .= "<div id=\"csv_content_loading\"><div style=\"width: 250px; height: 20px; background: url(../setup/orange-progress.gif); border: 1px #999 solid; margin-left:auto; margin-right: auto; text-align: center;\">" . Dict::S('UI:Loading') . "</div></div><textarea id=\"csv_content\" style=\"display:none;\">\n"; //$sHtml .= htmlentities($sCSVData, ENT_QUOTES, 'UTF-8'); $sHtml .= "</textarea>\n"; $oPage->add_ready_script("\$.post('{$sAjaxLink}', {}, function(data) { \$('#csv_content').html(data); \$('#csv_content_loading').hide(); \$('#csv_content').show();} );"); break; case 'modify': if (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_MODIFY, $this->m_oSet) == UR_ALLOWED_YES) { while ($oObj = $this->m_oSet->Fetch()) { $sHtml .= $oObj->GetModifyForm($oPage); } } break; case 'search': $sStyle = isset($aExtraParams['open']) && $aExtraParams['open'] == 'true' ? 'SearchDrawer' : 'SearchDrawer DrawerClosed'; $sHtml .= "<div id=\"ds_{$sId}\" class=\"{$sStyle}\">\n"; $oPage->add_ready_script(<<<EOF \t\$("#dh_{$sId}").click( function() { \t\t\$("#ds_{$sId}").slideToggle('normal', function() { \$("#ds_{$sId}").parent().resize(); FixSearchFormsDisposition(); } ); \t\t\$("#dh_{$sId}").toggleClass('open'); \t}); EOF ); $aExtraParams['currentId'] = $sId; $sHtml .= cmdbAbstractObject::GetSearchForm($oPage, $this->m_oSet, $aExtraParams); $sHtml .= "</div>\n"; $sHtml .= "<div class=\"HRDrawer\"></div>\n"; $sHtml .= "<div id=\"dh_{$sId}\" class=\"DrawerHandle\">" . Dict::S('UI:SearchToggle') . "</div>\n"; break; case 'open_flash_chart': static $iChartCounter = 0; $oAppContext = new ApplicationContext(); $sContext = $oAppContext->GetForLink(); if (!empty($sContext)) { $sContext = '&' . $sContext; } $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie'; $sTitle = isset($aExtraParams['chart_title']) ? $aExtraParams['chart_title'] : ''; $sGroupBy = isset($aExtraParams['group_by']) ? $aExtraParams['group_by'] : ''; $sGroupByExpr = isset($aExtraParams['group_by_expr']) ? '¶ms[group_by_expr]=' . $aExtraParams['group_by_expr'] : ''; $sFilter = $this->m_oFilter->serialize(); $sHtml .= "<div id=\"my_chart_{$sId}{$iChartCounter}\">If the chart does not display, <a href=\"http://get.adobe.com/flash/\" target=\"_blank\">install Flash</a></div>\n"; $oPage->add_script("function ofc_resize(left, width, top, height) { /* do nothing special */ }"); if (isset($aExtraParams['group_by_label'])) { $sUrl = urlencode(utils::GetAbsoluteUrlAppRoot() . "pages/ajax.render.php?operation=open_flash_chart¶ms[group_by]={$sGroupBy}{$sGroupByExpr}¶ms[group_by_label]={$aExtraParams['group_by_label']}¶ms[chart_type]={$sChartType}¶ms[chart_title]={$sTitle}¶ms[currentId]={$sId}&id={$sId}&filter=" . urlencode($sFilter)); } else { $sUrl = urlencode(utils::GetAbsoluteUrlAppRoot() . "pages/ajax.render.php?operation=open_flash_chart¶ms[group_by]={$sGroupBy}{$sGroupByExpr}¶ms[chart_type]={$sChartType}¶ms[chart_title]={$sTitle}¶ms[currentId]={$sId}&id={$sId}&filter=" . urlencode($sFilter)); } $oPage->add_ready_script("swfobject.embedSWF(\"../images/open-flash-chart.swf\", \"my_chart_{$sId}{$iChartCounter}\", \"100%\", \"300\",\"9.0.0\", \"expressInstall.swf\",\n\t\t\t\t{\"data-file\":\"" . $sUrl . "\"}, {wmode: 'transparent'} );\n"); $iChartCounter++; if (isset($aExtraParams['group_by'])) { if (isset($aExtraParams['group_by_label'])) { $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']); $sGroupByLabel = $aExtraParams['group_by_label']; } else { // Backward compatibility: group_by is simply a field id $sAlias = $this->m_oFilter->GetClassAlias(); $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias); $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']); } $aGroupBy = array(); $aGroupBy['grouped_by_1'] = $oGroupByExp; $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true); $aRes = CMDBSource::QueryToArray($sSql); $aGroupBy = array(); $aLabels = array(); $aValues = array(); $iTotalCount = 0; foreach ($aRes as $iRow => $aRow) { $sValue = $aRow['grouped_by_1']; $aValues[$iRow] = $sValue; $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue); $aLabels[$iRow] = $sHtmlValue; $aGroupBy[$iRow] = (int) $aRow['_itop_count_']; $iTotalCount += $aRow['_itop_count_']; } $aData = array(); $idx = 0; $aURLs = array(); foreach ($aGroupBy as $iRow => $iCount) { // Build the search for this subset $oSubsetSearch = $this->m_oFilter->DeepClone(); $oCondition = new BinaryExpression($oGroupByExp, '=', new ScalarExpression($aValues[$iRow])); $oSubsetSearch->AddConditionExpression($oCondition); $aURLs[$idx] = $oSubsetSearch->serialize(); $idx++; } $sURLList = ''; foreach ($aURLs as $index => $sURL) { $sURLList .= "\taURLs[{$index}] = '" . utils::GetAbsoluteUrlAppRoot() . "pages/UI.php?operation=search&format=html{$sContext}&filter=" . urlencode($sURL) . "';\n"; } $oPage->add_script(<<<EOF function ofc_drill_down_{$sId}(index) { \tvar aURLs = new Array(); {$sURLList} \twindow.location.href=aURLs[index]; } EOF ); } break; case 'open_flash_chart_ajax': require_once APPROOT . '/pages/php-ofc-library/open-flash-chart.php'; $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie'; $sId = utils::ReadParam('id', ''); $oChart = new open_flash_chart(); switch ($sChartType) { case 'bars': $oChartElement = new bar_glass(); if (isset($aExtraParams['group_by'])) { if (isset($aExtraParams['group_by_label'])) { $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']); $sGroupByLabel = $aExtraParams['group_by_label']; } else { // Backward compatibility: group_by is simply a field id $sAlias = $this->m_oFilter->GetClassAlias(); $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias); $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']); } $aGroupBy = array(); $aGroupBy['grouped_by_1'] = $oGroupByExp; $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true); $aRes = CMDBSource::QueryToArray($sSql); $aGroupBy = array(); $aLabels = array(); $iTotalCount = 0; foreach ($aRes as $iRow => $aRow) { $sValue = $aRow['grouped_by_1']; $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue); $aLabels[$iRow] = strip_tags($sHtmlValue); $aGroupBy[$iRow] = (int) $aRow['_itop_count_']; $iTotalCount += $aRow['_itop_count_']; } $aData = array(); $aChartLabels = array(); $maxValue = 0; foreach ($aGroupBy as $iRow => $iCount) { $oBarValue = new bar_value($iCount); $oBarValue->on_click("ofc_drill_down_{$sId}"); $aData[] = $oBarValue; if ($iCount > $maxValue) { $maxValue = $iCount; } $aChartLabels[] = html_entity_decode($aLabels[$iRow], ENT_QUOTES, 'UTF-8'); } $oYAxis = new y_axis(); $aMagicValues = array(1, 2, 5, 10); $iMultiplier = 1; $index = 0; $iTop = $aMagicValues[$index % count($aMagicValues)] * $iMultiplier; while ($maxValue > $iTop) { $index++; $iTop = $aMagicValues[$index % count($aMagicValues)] * $iMultiplier; if ($index % count($aMagicValues) == 0) { $iMultiplier = $iMultiplier * 10; } } //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n"; $oYAxis->set_range(0, $iTop, $iMultiplier); $oChart->set_y_axis($oYAxis); $oChartElement->set_values($aData); $oXAxis = new x_axis(); $oXLabels = new x_axis_labels(); // set them vertical $oXLabels->set_vertical(); // set the label text $oXLabels->set_labels($aChartLabels); // Add the X Axis Labels to the X Axis $oXAxis->set_labels($oXLabels); $oChart->set_x_axis($oXAxis); } break; case 'pie': default: $oChartElement = new pie(); $oChartElement->set_start_angle(35); $oChartElement->set_animate(true); $oChartElement->set_tooltip('#label# - #val# (#percent#)'); $oChartElement->set_colours(array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664')); if (isset($aExtraParams['group_by'])) { if (isset($aExtraParams['group_by_label'])) { $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']); $sGroupByLabel = $aExtraParams['group_by_label']; } else { // Backward compatibility: group_by is simply a field id $sAlias = $this->m_oFilter->GetClassAlias(); $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias); $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']); } $aGroupBy = array(); $aGroupBy['grouped_by_1'] = $oGroupByExp; $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true); $aRes = CMDBSource::QueryToArray($sSql); $aGroupBy = array(); $aLabels = array(); $iTotalCount = 0; foreach ($aRes as $iRow => $aRow) { $sValue = $aRow['grouped_by_1']; $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue); $aLabels[$iRow] = strip_tags($sHtmlValue); $aGroupBy[$iRow] = (int) $aRow['_itop_count_']; $iTotalCount += $aRow['_itop_count_']; } $aData = array(); foreach ($aGroupBy as $iRow => $iCount) { $sFlashLabel = html_entity_decode($aLabels[$iRow], ENT_QUOTES, 'UTF-8'); $PieValue = new pie_value($iCount, $sFlashLabel); //@@ BUG: not passed via ajax !!! $PieValue->on_click("ofc_drill_down_{$sId}"); $aData[] = $PieValue; } $oChartElement->set_values($aData); $oChart->x_axis = null; } } if (isset($aExtraParams['chart_title'])) { // The title has been given in an url, and urlencoded... // and urlencode transforms utf-8 into something similar to ISO-8859-1 // Example: é (C3A9 becomes %E9) // As a consequence, json_encode (called within open-flash-chart.php) // was returning 'null' and the graph was not displayed at all // To make sure that the graph is displayed AND to get a correct title // (at least for european characters) let's transform back into utf-8 ! $sTitle = iconv("ISO-8859-1", "UTF-8//IGNORE", $aExtraParams['chart_title']); // If the title is a dictionnary entry, fetch it $sTitle = Dict::S($sTitle); $oTitle = new title($sTitle); $oChart->set_title($oTitle); $oTitle->set_style("{font-size: 16px; font-family: Tahoma; font-weight: bold; text-align: center;}"); } $oChart->set_bg_colour('#FFFFFF'); $oChart->add_element($oChartElement); $sHtml = $oChart->toPrettyString(); break; default: // Unsupported style, do nothing. $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle); } return $sHtml; }
public function RenderNoData($oPage, $bEditMode = false, $aExtraParams = array()) { $sTitle = $this->aProperties['title']; $aDisplayValues = $this->MakeSimulatedData(); require_once APPROOT . '/pages/php-ofc-library/open-flash-chart.php'; $oChart = new open_flash_chart(); $aGroupBy = array(); $aLabels = array(); foreach ($aDisplayValues as $iRow => $aDisplayData) { $aLabels[$iRow] = $aDisplayData['label']; $aGroupBy[$iRow] = (int) $aDisplayData['count']; } $oChartElement = new bar_glass(); $aData = array(); $aChartLabels = array(); $maxValue = 0; foreach ($aGroupBy as $iRow => $iCount) { $oBarValue = new bar_value($iCount); $aData[] = $oBarValue; if ($iCount > $maxValue) { $maxValue = $iCount; } $aChartLabels[] = html_entity_decode($aLabels[$iRow], ENT_QUOTES, 'UTF-8'); } $oYAxis = new y_axis(); $aMagicValues = array(1, 2, 5, 10); $iMultiplier = 1; $index = 0; $iTop = $aMagicValues[$index % count($aMagicValues)] * $iMultiplier; while ($maxValue > $iTop) { $index++; $iTop = $aMagicValues[$index % count($aMagicValues)] * $iMultiplier; if ($index % count($aMagicValues) == 0) { $iMultiplier = $iMultiplier * 10; } } //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n"; $oYAxis->set_range(0, $iTop, $iMultiplier); $oChart->set_y_axis($oYAxis); $oChartElement->set_values($aData); $oXAxis = new x_axis(); $oXLabels = new x_axis_labels(); // set them vertical $oXLabels->set_vertical(); // set the label text $oXLabels->set_labels($aChartLabels); // Add the X Axis Labels to the X Axis $oXAxis->set_labels($oXLabels); $oChart->set_x_axis($oXAxis); if (!empty($sTitle)) { // The title has been given in an url, and urlencoded... // and urlencode transforms utf-8 into something similar to ISO-8859-1 // Example: é (C3A9 becomes %E9) // As a consequence, json_encode (called within open-flash-chart.php) // was returning 'null' and the graph was not displayed at all // To make sure that the graph is displayed AND to get a correct title // (at least for european characters) let's transform back into utf-8 ! $sTitle = iconv("ISO-8859-1", "UTF-8//IGNORE", $sTitle); // If the title is a dictionnary entry, fetch it $sTitle = $this->oModelReflection->DictString($sTitle); $oTitle = new title($sTitle); $oChart->set_title($oTitle); $oTitle->set_style("{font-size: 16px; font-family: Tahoma; font-weight: bold; text-align: center;}"); } $oChart->set_bg_colour('#FFFFFF'); $oChart->add_element($oChartElement); $sData = $oChart->toPrettyString(); $sData = json_encode($sData); $oPage->add_script(<<<EOF function ofc_get_data_dashlet_{$this->sId}() { \treturn {$sData}; } EOF ); $oPage->add('<div class="dashlet-content">'); $oPage->add("<div id=\"dashlet_chart_{$this->sId}\">If the chart does not display, <a href=\"http://get.adobe.com/flash/\" target=\"_blank\">install Flash</a></div>\n"); $oPage->add('</div>'); // $oPage->add_script("function ofc_resize(left, width, top, height) { /* do nothing special */ }"); $oPage->add_ready_script(<<<EOF swfobject.embedSWF(\t"../images/open-flash-chart.swf", \t"dashlet_chart_{$this->sId}", \t"100%", "300","9.0.0", \t"expressInstall.swf", \t{"get-data":"ofc_get_data_dashlet_{$this->sId}", "id":"dashlet_chart_{$this->sId}"}, \t{'wmode': 'transparent'} ); EOF ); }
function netio() { function bit_to_kb($n) { return round($n / 1000, 2); } function bit_to_mb($n) { return round($n / 1000000, 2); } function get_data() { $recv_l = trim(shell_exec("cat /sys/class/net/eth0/statistics/rx_bytes")) / 8; sleep(1); $recv_n = trim(shell_exec("cat /sys/class/net/eth0/statistics/rx_bytes")) / 8; return $recv_n - $recv_l; } if (array_key_exists('netio', $_SESSION) && array_key_exists('recv_l', $_SESSION)) { if (count($_SESSION['netio']) == 10) { array_shift($_SESSION['netio']); $_SESSION['netio'][] = get_data(); } else { $_SESSION['netio'][] = get_data(); $_SESSION['recv_l'] = end($_SESSION['netio']); } } else { $_SESSION['netio'] = array(0, 0, 0, 0, 0, 0, 0, 0, 0); $_SESSION['netio'][] = get_data(); $_SESSION['recv_l'] = end($_SESSION['netio']); } $data = $_SESSION['netio']; /* $data = array(); for($i=0;$i<40;$i++){ $data[] = rand(1000000,10000000); } */ foreach (range(1, 10) as $i) { settype($i, 'string'); $second[] = $i; } if (max($data) <= 1000) { $data = array_map("bit_to_kb", $data); $y_axis_max = 1; $y_axis_key_text = " KB/s"; } elseif (max($data) <= 10000) { $data = array_map("bit_to_kb", $data); $y_axis_max = 10; $y_axis_key_text = " KB/s"; } elseif (max($data) <= 100000) { $data = array_map("bit_to_kb", $data); $y_axis_max = 100; $y_axis_key_text = " KB/s"; } elseif (max($data) <= 1000000) { $data = array_map("bit_to_kb", $data); $y_axis_max = 1000; $y_axis_key_text = " KB/s"; } elseif (max($data) <= 10000000) { $data = array_map("bit_to_mb", $data); $y_axis_max = 10; $y_axis_key_text = " MB/s"; } else { $data = array_map("bit_to_mb", $data); $y_axis_max = 100; $y_axis_key_text = " MB/s"; } $y_axis_step = $y_axis_max / 5; $chart = new open_flash_chart(); $title = new title("实时流量显示"); $title->set_style("{font-size: 12px; color: #A2ACBA; text-align: center;}"); $chart->set_title($title); #点是指曲线图上的顶点 # $d = new dot(); # $d->colour('#9C0E57')->size(3); $area = new area(); #width是指曲线的宽度 # $area->set_width(3); # $area->set_default_dot_style($d); $area->set_colour('#5B56B6'); #value即曲线顶的值 $area->set_values($data); #左上角的文字 $area->set_key($y_axis_key_text, 10); $area->set_fill_colour('#CCCAAA'); #设透明度 $area->set_fill_alpha(0.3); #area设置结束,使用add_element方法把area加进来 $chart->add_element($area); $chart->set_bg_colour('#FFFFFF'); #设置label $x_labels = new x_axis_labels(); $x_labels->set_steps(1); $x_labels->set_colour('#A2ACBA'); $x_labels->set_labels($second); #设置X轴 $x_axis = new x_axis(); $x_axis->set_colour('#A2ACBA'); $x_axis->set_grid_colour('#D7E4A3'); $x_axis->set_offset(false); $x_axis->set_steps(1); $x_axis->set_labels($x_labels); $chart->set_x_axis($x_axis); #设置X轴的文件说明,即x_legend $legend_text = "当前网络流量 " . end($data) . $y_axis_key_text; $x_legend = new x_legend($legend_text); $x_legend->set_style('{font-size: 12px; color: #778877}'); $chart->set_x_legend($x_legend); #设置轴 $y_axis = new y_axis(); $y_axis->set_range(0, $y_axis_max, $y_axis_step); $y_axis->labels = null; $y_axis->set_offset(false); $chart->add_y_axis($y_axis); header("Cache-Control: cache, must-revalidate"); header("Pragma: public"); echo $chart->toPrettyString(); }
function render_service_reports() { $content = "<h1>Service Reports</h1>"; // Start Filter for service type $allServiceTypes = ServiceType::get_service_types(); # $allServiceTypes = array('all' => 'all'); #$allServiceTypes = array_merge($allServiceTypes, ServiceType::get_service_types()); $allServiceTypes['all'] = 'all'; $service_type = $_GET['service_type']; $service_filter = $_GET['service_type']; if ($service_type == '' || !isset($service_type) || !is_numeric($service_type)) { $service_type = 'all'; $service_filter = ''; } $filter = "\r\n\t\t<FORM>\r\n\t\t<DIV style=\" \">\r\n\t\t<SELECT name'=service_type_report'\r\n\t\t\tonChange=\"window.location='services.php?&action=serviceReports&service_type='+this.options[this.selectedIndex].value;\">"; foreach ($allServiceTypes as $id => $name) { if ($service_type == $id) { $selected = "SELECTED"; } else { $selected = ''; } $filter .= "<OPTION value='{$id}' {$selected}>{$name}\n"; } $filter .= "\r\n\t\t</SELECT>\r\n\t\t</DIV>\r\n\t\t</FORM>\r\n\t"; // End filter $max_date = strtotime("2009-01-01"); $start_date = date("Y-m") . "-01"; // Get all months since start $workdate = strtotime($start_date); $now = strtotime("Now"); $form = new Form(auto, 3); $headings = array("Period", "In production", "Out of Production"); $data = array(); $x_ax_data = array(); $y_ax_data = array(); $handlers = array(); while ($workdate > $max_date) { $sql_enddate = date("Y-m-d", $workdate); $month_period = date("m-Y", $workdate); // This is for the chart $month_label = date("M\nY", $workdate); $graph_date = strtotime("-1 month", $workdate); $month_label = date("M\nY", $graph_date); $sql_startdate = date("Y-m-d", $workdate); array_push($x_ax_data, $month_label); array_push($y_ax_data, count(Service::get_inprod_services_at_date($sql_startdate, $service_filter))); // Add one month $workdate = strtotime("-1 month", $workdate); $sql_startdate = date("Y-m-d", $workdate); $out_of_prod = count(Service::get_outprod_services_diff_date($sql_startdate, $sql_enddate, $service_filter)); $in_prod = count(Service::get_inprod_services_diff_date($sql_startdate, $sql_enddate, $service_filter)); array_push($data, "{$sql_startdate} {$sql_enddate}"); array_push($data, $in_prod); array_push($data, $out_of_prod); array_push($handlers, "handleEvent('services.php?action=detailedServiceReports&start_date={$sql_startdate}&end_date={$sql_enddate}&service_type={$service_type}')"); } $form->setTableWidth("224px"); $form->setData($data); $form->setEventHandler($handlers); $form->setHeadings($headings); $form->setSortable(true); $content .= "<div style=\"float: left; clear: both; margin-right:28px\">" . $form->showForm() . "</div>"; // Chart // // This is the MODEL section: // include 'open-flash-chart/php-ofc-library/open-flash-chart.php'; // create an X Axis object // $y_ax_data = array_reverse($y_ax_data); $x_ax_data = array_reverse($x_ax_data); $x = new x_axis(); $x->set_steps(3); $x->set_labels_from_array($x_ax_data); $max = max($y_ax_data); $y = new y_axis(); $y->set_range(0, $max); // Bar $bar = new bar(); $bar->set_values($y_ax_data); // Bar // ------- LINE 2 ----- $line_2_default_dot = new dot(); $line_2_default_dot->size(3)->halo_size(1)->colour('#3D5C56'); $line_2 = new line(); $line_2->set_default_dot_style($line_2_default_dot); $line_2->set_values($y_ax_data); $line_2->set_width(3); $line_2->set_colour('#3D5C56'); $chart = new open_flash_chart(); $title = new title("In Production Services over Time"); $title->set_style("{font-size: 10px; font-family: Times New Roman; font-weight: bold; color: #000; text-align: center;}"); $chart->set_bg_colour('#FFFFFF'); $chart->set_title($title); $chart->add_element($bar); //$chart->add_element( $line1 ); $chart->add_element($line_2); $chart->set_x_axis($x); $chart->set_y_axis($y); // // This is the VIEW section: // Should print this first. // $heading = "\r\n\t<script type='text/javascript' src='open-flash-chart/js/json/json2.js'></script>\r\n\t<script type='text/javascript' src='open-flash-chart/js/swfobject.js'></script>\r\n\t<script type='text/javascript'>\r\n\tswfobject.embedSWF('open-flash-chart/open-flash-chart.swf', 'my_chart', '660', '350', '9.0.0');\r\n\t</script>\r\n\r\n\t<script type='text/javascript'>\r\n\r\n\tfunction open_flash_chart_data() {\r\n\t\treturn JSON.stringify(data);\r\n\t}\r\n\r\n\tfunction findSWF(movieName) {\r\n \t\tif (navigator.appName.indexOf('Microsoft')!= -1) {\r\n \t\t\treturn window[movieName];\r\n \t\t} else {\r\n \t\t\treturn document[movieName];\r\n \t\t}\r\n\t}\r\n \r\n\tvar data = " . $chart->toPrettyString() . "\r\n\r\n\t</script>\r\n\r\n\r\n\t<script type=\"text/javascript\">\r\n \r\n\tOFC = {};\r\n \r\n\tOFC.jquery = {\r\n \tname: 'jQuery',\r\n \tversion: function(src) { return \$('#'+ src)[0].get_version() },\r\n \trasterize: function (src, dst) { \$('#'+ dst).replaceWith(OFC.jquery.image(src)) },\r\n \timage: function(src) { return \"<img src='data:image/png;base64,\" + \$('#'+src)[0].get_img_binary() + \"' />\"},\r\n \tpopup: function(src) {\r\n var img_win = window.open('', 'Charts: Export as Image')\r\n with(img_win.document) {\r\n write('<html><head><title>Charts: Export as Image<\\/title><\\/head><body>' + OFC.jquery.image(src) + '<\\/body><\\/html>') }\r\n\t\t// stop the 'loading...' message\r\n\t\timg_win.document.close();\r\n \t}\r\n\t}\r\n \r\n\t// Using_ an object as namespaces is JS Best Practice. I like the Control.XXX style.\r\n\t//if (!Control) {var Control = {}}\r\n\t//if (typeof(Control == \"undefined\")) {var Control = {}}\r\n\tif (typeof(Control == \"undefined\")) {var Control = {OFC: OFC.jquery}}\r\n \r\n \r\n\t// By default, right-clicking on OFC and choosing \"save image locally\" calls this function.\r\n\t// You are free to change the code in OFC and call my wrapper (Control.OFC.your_favorite_save_method)\r\n\t// function save_image() { alert(1); Control.OFC.popup('my_chart') }\r\n\tfunction save_image() { alert(\"Your image will be displayed in a new window\"); OFC.jquery.popup('my_chart') }\r\n\t</script>\r\n\t<div id='my_chart' style='float:left; margin-left:28px;'></div>\r\n\t"; print " {$content}\n \r\n\t\t<div style=''<b>Select Service Type:</b>{$filter} <br></div>\n\r\n\t\t{$heading} "; }
$chart->add_element($line); // title properties $title = new title("Total Portfolio Performance"); $title->set_style("{font-size: 25px; font-family: Calibri; font-weight: bold; color: #121212; text-align: center;}"); $chart->set_title($title); // y axis properties $y = new y_axis(); $y_min = 0.0; $y_max = 0.0; $y_min = floor(0.995 * $amt_min); $y_max = ceil(1.005 * $amt_max); $y->set_grid_colour('#EFEFEF'); $y->set_range($y_min, $y_max, round(($y_max - $y_min) / 5.0)); $chart->set_y_axis($y); // y legend properties $y_legend = new y_legend('Amount ($)'); $y_legend->set_style('{font-size:15px; font-family:Calibri; color:#121212}'); $chart->set_y_legend($y_legend); // x axis properties $x = new x_axis(); $x->set_labels_from_array($x_labels); $x->grid_colour('#EFEFEF'); $chart->set_x_axis($x); // background properties $chart->set_bg_colour('#FFFFFF'); // menu $m = new ofc_menu("#E0E0FF", "#707070"); $m->values(array(new ofc_menu_item('Toggle view', 'toggle'))); //$chart->set_menu($m); $chart_data = $chart->toPrettyString(); echo $chart_data;
function get_daily_entries($form, $colors = false, $type = "DATE") { global $wpdb, $frmdb; if (!$colors) { $colors = array('#EF8C08', '#21759B', '#1C9E05'); } $type = strtoupper($type); //Chart for Entries Submitted $values = array(); $labels = array(); if ($type == 'HOUR') { $start_timestamp = strtotime('-48 hours'); } else { if ($type == 'MONTH') { $start_timestamp = strtotime('-1 year'); } else { if ($type == 'YEAR') { $start_timestamp = strtotime('-10 years'); } else { $start_timestamp = strtotime('-1 month'); } } } $end_timestamp = time(); if ($type == 'HOUR') { $query = "SELECT en.created_at as endate,COUNT(*) as encount FROM {$frmdb->entries} en WHERE en.created_at >= '" . date("Y-n-j H", $start_timestamp) . ":00:00' AND en.form_id={$form->id} GROUP BY endate"; } else { $query = "SELECT DATE(en.created_at) as endate,COUNT(*) as encount FROM {$frmdb->entries} en WHERE en.created_at >= '" . date("Y-n-j", $start_timestamp) . " 00:00:00' AND en.form_id={$form->id} GROUP BY {$type}(en.created_at)"; } $entries_array = $wpdb->get_results($query); $temp_array = $counts_array = $dates_array = array(); // Refactor Array for use later on foreach ($entries_array as $e) { $e_key = $e->endate; if ($type == 'HOUR') { $e_key = date('Y-m-d H', strtotime($e->endate)) . ':00:00'; } else { if ($type == 'MONTH') { $e_key = date('Y-m', strtotime($e->endate)) . '-01'; } else { if ($type == 'YEAR') { $e_key = date('Y', strtotime($e->endate)) . '-01-01'; } } } $temp_array[$e_key] = $e->encount; } // Get the dates array if ($type == 'HOUR') { for ($e = $start_timestamp; $e <= $end_timestamp; $e += 60 * 60) { if (!in_array(date('Y-m-d H', $e) . ':00:00', $dates_array)) { $dates_array[] = date('Y-m-d H', $e) . ':00:00'; } } $date_format = get_option('time_format'); } else { if ($type == 'MONTH') { for ($e = $start_timestamp; $e <= $end_timestamp; $e += 60 * 60 * 24 * 25) { if (!in_array(date('Y-m', $e) . '-01', $dates_array)) { $dates_array[] = date('Y-m', $e) . '-01'; } } $date_format = 'F Y'; } else { if ($type == 'YEAR') { for ($e = $start_timestamp; $e <= $end_timestamp; $e += 60 * 60 * 24 * 364) { if (!in_array(date('Y', $e) . '-01-01', $dates_array)) { $dates_array[] = date('Y', $e) . '-01-01'; } } $date_format = 'Y'; } else { for ($e = $start_timestamp; $e <= $end_timestamp; $e += 60 * 60 * 24) { $dates_array[] = date("Y-m-d", $e); } $date_format = get_option('date_format'); } } } // Make sure counts array is in order and includes zero click days foreach ($dates_array as $date_str) { if (isset($temp_array[$date_str])) { $counts_array[$date_str] = $temp_array[$date_str]; } else { $counts_array[$date_str] = 0; } } foreach ($counts_array as $date => $count) { $labels[] = date_i18n($date_format, strtotime($date)); $values[] = (int) $count; } if ($type == 'MONTH') { $title = __('Monthly Entries', 'formidable'); } else { if ($type == 'YEAR') { $title = __('Yearly Entries', 'formidable'); } else { if ($type == 'HOUR') { $title = __('Hourly Entries', 'formidable'); } else { $title = __('Daily Entries', 'formidable'); } } } $title = new title($title); $line_1_default_dot = new dot(); $line_1_default_dot->colour($colors[0]); $line_1_default_dot->tooltip('#x_label#<br>#val# Entries'); $line_1 = new line(); $line_1->set_default_dot_style($line_1_default_dot); $line_1->set_values($values); $line_1->set_colour($colors[1]); $chart = new open_flash_chart(); $chart->set_title($title); $chart->set_bg_colour('#FFFFFF'); $x = new x_axis(); $x_labels = new x_axis_labels(); $x_labels->rotate(340); $x_labels->set_labels($labels); if (count($labels) > 15) { $x_labels->visible_steps(2); } $x->set_labels($x_labels); $chart->set_x_axis($x); $y = new y_axis(); if (!empty($values)) { $max = max($values) + 1; $step = ceil($max / 10); $y->set_range(0, $max, $step); } $chart->add_element($line_1); $chart->set_y_axis($y); return $chart->toPrettyString(); }
protected function RenderChart($oPage, $sId, $aValues, $sDrillDown = '', $aRows = array()) { // 1- Compute Open Flash Chart data // $aValueKeys = array(); $index = 0; if (count($aValues) > 0 && $sDrillDown != '') { $oFilter = DBObjectSearch::FromOQL($sDrillDown); $sClass = $oFilter->GetClass(); $sOQLClause = str_replace('SELECT ' . $sClass, '', $sDrillDown); $aSQLColNames = array_keys(current($aRows)); // Read the list of columns from the current (i.e. first) element of the array $oAppContext = new ApplicationContext(); $sURL = utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?operation=search_oql&search_form=0&oql_class=' . $sClass . '&format=html&' . $oAppContext->GetForLink() . '&oql_clause='; } $aURLs = array(); foreach ($aValues as $key => $value) { // Make sure that values are integers (so that max() will work....) // and build an array of STRING with the keys (numeric keys are transformed into string by PHP :-( $aValues[$key] = (int) $value; $aValueKeys[] = (string) $key; // Build the custom query for the 'drill down' on each element if ($sDrillDown != '') { $sFilter = $sOQLClause; foreach ($aSQLColNames as $sColName) { $sFilter = str_replace(':' . $sColName, "'" . addslashes($aRows[$key][$sColName]) . "'", $sFilter); $aURLs[$index] = $sURL . urlencode($sFilter); } } $index++; } $oChart = new open_flash_chart(); if ($this->m_sType == 'bars') { $oChartElement = new bar_glass(); if (count($aValues) > 0) { $maxValue = max($aValues); } else { $maxValue = 1; } $oYAxis = new y_axis(); $aMagicValues = array(1, 2, 5, 10); $iMultiplier = 1; $index = 0; $iTop = $aMagicValues[$index % count($aMagicValues)] * $iMultiplier; while ($maxValue > $iTop) { $index++; $iTop = $aMagicValues[$index % count($aMagicValues)] * $iMultiplier; if ($index % count($aMagicValues) == 0) { $iMultiplier = $iMultiplier * 10; } } //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n"; $oYAxis->set_range(0, $iTop, $iMultiplier); $oChart->set_y_axis($oYAxis); $aBarValues = array(); foreach ($aValues as $iValue) { $oBarValue = new bar_value($iValue); $oBarValue->on_click("ofc_drilldown_{$sId}"); $aBarValues[] = $oBarValue; } $oChartElement->set_values($aBarValues); //$oChartElement->set_values(array_values($aValues)); $oXAxis = new x_axis(); $oXLabels = new x_axis_labels(); // set them vertical $oXLabels->set_vertical(); // set the label text $oXLabels->set_labels($aValueKeys); // Add the X Axis Labels to the X Axis $oXAxis->set_labels($oXLabels); $oChart->set_x_axis($oXAxis); } else { $oChartElement = new pie(); $oChartElement->set_start_angle(35); $oChartElement->set_animate(true); $oChartElement->set_tooltip('#label# - #val# (#percent#)'); $oChartElement->set_colours(array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664')); $aData = array(); foreach ($aValues as $sValue => $iValue) { $oPieValue = new pie_value($iValue, $sValue); //@@ BUG: not passed via ajax !!! $oPieValue->on_click("ofc_drilldown_{$sId}"); $aData[] = $oPieValue; } $oChartElement->set_values($aData); $oChart->x_axis = null; } // Title given in HTML //$oTitle = new title($this->m_sTitle); //$oChart->set_title($oTitle); $oChart->set_bg_colour('#FFFFFF'); $oChart->add_element($oChartElement); $sData = $oChart->toPrettyString(); $sData = json_encode($sData); // 2- Declare the Javascript function that will render the chart data\ // $oPage->add_script(<<<EOF function ofc_get_data_{$sId}() { \treturn {$sData}; } EOF ); if (count($aURLs) > 0) { $sURLList = ''; foreach ($aURLs as $index => $sURL) { $sURLList .= "\taURLs[{$index}] = '" . addslashes($sURL) . "';\n"; } $oPage->add_script(<<<EOF function ofc_drilldown_{$sId}(index) { \tvar aURLs = new Array(); {$sURLList} \tvar sURL = aURLs[index]; \t \twindow.location.href = sURL; // Navigate ! } EOF ); } // 3- Insert the Open Flash chart // $oPage->add("<div id=\"{$sId}\"><div>\n"); $oPage->add_ready_script(<<<EOF swfobject.embedSWF(\t"../images/open-flash-chart.swf", \t"{$sId}", \t"100%", "300","9.0.0", \t"expressInstall.swf", \t{"get-data":"ofc_get_data_{$sId}", "id":"{$sId}"}, \t{'wmode': 'transparent'} ); EOF ); }
function admin_graphs($id = null) { App::import('Vendor', 'Newsletter.php-ofc-library', array('file' => 'php-ofc-library/open-flash-chart.php')); //Configure::write('debug', 0); //$this->layout = null; // generate some random data srand((double) microtime() * 1000000); $title = new title(__d("newsletter", "Views per time", true)); $chart = new open_flash_chart(); $chart->set_title($title); $newsletter = $this->Newsletter->read(null, $id); // Views $dates = array(); $values = array(); //// init sender class //// App::import('Lib', 'Newsletter.ClassCollection'); $senderOpt = NewsletterConfig::load('sender'); if (!is_array($senderOpt)) { $senderOpt = array('name' => $senderOpt); } $sender = ClassCollection::getObject('NewsletterSender', $senderOpt['name']); //// query //// $opt = array('type' => 'graph', 'query' => array('fields' => array('count(*) as nb', 'DATE(NewsletterEvent.date) as date'), 'conditions' => array('NewsletterSended.newsletter_id' => $id, 'or' => array('NewsletterEvent.action' => 'view', array('NewsletterEvent.action IS NULL', 'NewsletterEvent.url' => null))), 'group' => 'DATE(NewsletterEvent.date)', 'order' => 'DATE(NewsletterEvent.date)', 'model' => 'NewsletterEvent')); $data = $this->_get_stats(array('viewByDays' => $opt), $newsletter, $sender); //debug($data); $dates = $data['viewByDays']; $min_value = 99999999; $max_value = 0; foreach ($dates as $d => $val) { if ($val < $min_value) { $min_value = $val; } if ($val > $max_value) { $max_value = $val; } } if ($max_value == $min_value) { $max_value++; $min_value--; } $min_value = 0; //debug($dates); $min_date = key($dates); end($dates); $max_date = key($dates); for ($cur_date = $min_date; $cur_date <= $max_date; $cur_date = $cur_date + 86400) { $x = strtotime('00:00:00', $cur_date); if (isset($dates[$cur_date])) { $values[] = new scatter_value($x, $dates[$cur_date]); } else { $values[] = new scatter_value($x, 0); } } if ($max_date == $min_date) { $max_date += 86400; } //debug($values); //pr($views); $line_dot = new line(); $line_dot->set_values($values); $line_dot->set_text("Views"); $chart->add_element($line_dot); $y = new y_axis(); $y->set_range($min_value, $max_value, ($max_value - $min_value) / 10); $x = new x_axis(); // grid line and tick every 10 $x->set_range(mktime(0, 0, 0, date("m", $min_date), date("d", $min_date), date("Y", $min_date)), mktime(0, 0, 0, date("m", $max_date), date("d", $max_date), date("Y", $max_date))); // show ticks and grid lines for every day: $x->set_steps(86400); $labels = new x_axis_labels(); // tell the labels to render the number as a date: $labels->text('#date:d-m-Y#'); // generate labels for every day $labels->set_steps(86400); // only display every other label (every other day) $labels->visible_steps(ceil(($max_date - $min_date) / 86400 / 20)); $labels->rotate(90); $x->set_labels($labels); $chart->set_x_axis($x); $chart->set_y_axis($y); $chart->set_bg_colour("#FFFFFF"); //print_r($views); //$this->set("allviews",$views[0][0]['count(*)']); $line_dot = new line(); $line_dot->set_values(array(2, 1)); $line_dot->set_text("Unique views"); $line_dot->colour("#0000000"); //$chart->add_element($line_dot); // echo $chart->toPrettyString(); exit; //$this->render(false); }
function generateStats($params) { global $reportCacheLocation; // Computer Statistics Generation $dbTrackHandler = connectDb(); $resultBag = generateStatsBag($params, $dbTrackHandler); // ---------------------------------------------------- // Generate charts $animation_1 = isset($params['animation_1']) ? $params['animation_1'] : 'pop'; $delay_1 = isset($params['delay_1']) ? $params['delay_1'] : 0.5; $cascade_1 = isset($params['cascade_1']) ? $params['cascade_1'] : 1; $title = new title("Genie Report: " . $params['reportName'] . " - Generated on " . date('Y/m/d h:i:s A')); $title->set_style("{font-size: 12px; color: #000000; text-align: center;}"); $bar_stack = new bar_stack(); if ($params['reportType'] == 'computerStats') { foreach ($resultBag as $elm) { $tmpTotal = $elm[AVAIBILITY_TYPE_OFFLINE] + $elm[AVAIBILITY_TYPE_AVAILABLE] + $elm[AVAIBILITY_TYPE_BUSY]; if ($tmpTotal == 0) { $tmpTotal = 1; } // Only Chuck Norris can divide by Zero. $bar_stack->append_stack(array($elm[AVAIBILITY_TYPE_OFFLINE] / $tmpTotal * 100, $elm[AVAIBILITY_TYPE_AVAILABLE] / $tmpTotal * 100, $elm[AVAIBILITY_TYPE_BUSY] / $tmpTotal * 100)); } $bar_stack->set_colours(array('#FF0000', '#00FF00', '#A25B00')); $bar_stack->set_keys(array(new bar_stack_key('#FF0000', 'OFFLINE', 13), new bar_stack_key('#00FF00', 'FREE', 13), new bar_stack_key('#A25B00', 'BUSY', 13))); } else { $allProgNames = array(); foreach ($resultBag as $elm) { $progNames = array_keys($elm); foreach ($progNames as $progName) { if (validProgram($progName)) { if (!array_key_exists($progName, $allProgNames)) { $allProgNames[$progName] = "#" . dechex(rand(0, 10000000)); } } } } $progsArray = array(); foreach ($resultBag as $elm) { $tmpTotal = 0; $progNames = array_keys($elm); foreach ($elm as $programName => $programWeight) { if (validProgram($programName)) { $tmpTotal += $programWeight; } } //echo "<h1>$tmpTotal</h1>"; if ($tmpTotal == 0) { $tmpTotal = 1; } // Only Chuck Norris can divide by Zero. $progs = array(); foreach ($elm as $programName => $programWeight) { if (validProgram($programName)) { $percentVal = $programWeight / $tmpTotal * 100; $progs[] = new bar_stack_value($percentVal, $allProgNames[$programName]); $progsArray[$percentVal * 1000000] = $programName; } } $bar_stack->append_stack($progs); } $legends = array(); //$strAllProgNames = array_keys($allProgNames); foreach ($allProgNames as $programName => $programColor) { $legends[] = new bar_stack_key($programColor, $programName, 13); } $bar_stack->set_keys($legends); ksort($progsArray); echo "<pre>"; while (list($key, $value) = each($progsArray)) { $kw = $key / 1000000; echo "{$kw}: {$value}<br />\n"; } echo "</pre>"; } //$bar_stack->set_tooltip( 'In #x_label# you get #total# days holiday a year.<br>Number of days: #val#' ); $bar_stack->set_on_show(new bar_on_show($animation_1, $cascade_1, $delay_1)); $y = new y_axis(); $y->set_range(0, 100, 10); //$y->set_range( 0, $tmpMax, $tmpMax/10 ); $x_labels = new x_axis_labels(); $x_labels->rotate(45); $x_labels->set_labels(array_keys($resultBag)); $x = new x_axis(); $x->set_labels($x_labels); $tooltip = new tooltip(); $tooltip->set_hover(); $chart = new open_flash_chart(); $chart->set_title($title); $chart->add_element($bar_stack); $chart->set_x_axis($x); $chart->add_y_axis($y); $chart->set_tooltip($tooltip); // ---------------------------------------------------- $cacheid = time(); $filename = $cacheid . '.cache.json'; $myFile = "{$reportCacheLocation}/reports-cache/" . $filename; $fh = fopen($myFile, 'w') or die("can't open file"); fwrite($fh, $chart->toPrettyString()); fclose($fh); return $cacheid; }
// Absisses $x2 = new x_axis(); //$x->set_labels( $x_labels ); $x2->set_stroke(2); $x2->set_tick_height(2); $x2->set_colour("#d000d0"); $x2->set_labels($labels2); // Tooltip du graphe ! $chart2->set_tooltip($t); $title2 = new title("Evolution par joueur"); $chart2->set_title($title2); $chart2->set_y_axis($y2); $chart2->set_x_axis($x2); $fp = fopen($fichierImage, "w"); // ouverture du fichier en écriture fputs($fp, $chart2->toPrettyString()); // on écrit les données fclose($fp); } echo "<div id=\"my_chart2\"> </div>"; ferme_base($db_link); } ?> <script type="text/javascript" src="js/swfobject.js"></script> <script type="text/javascript"> swfobject.embedSWF(
function report_chart($data) { $title = new title("Availability Report "); $pie = new pie(); $pie->set_alpha(0.9); $pie->radius(90); //$pie->start_angle(100); $pie->add_animation(new pie_fade()); $pie->set_tooltip('#label#: #percent#<br>#val# of #total#<br>'); $status_colors = array(free => '#77CC6D', assigned => '#FF0000', reserved => '#6D86CC', free2 => '#77CC6D', assigned2 => '#FF0000', reserved2 => '#6D86CC'); $status_name = array(free => 'FREE', assigned => 'ASSIGNED', reserved => 'RESERVED', free2 => 'FREE', assigned2 => 'ASSIGNED', reserved2 => 'RESERVED'); $col = array(); $d = array(); foreach ($data as $name => $value) { if ($value > 0) { $d[] = new pie_value($value * 1, "{$status_name[$name]}"); array_push($col, $status_colors[$name]); } } $pie->set_values($d); $pie->set_colours($col); $chart = new open_flash_chart(); $chart->set_title($title); $chart->add_element($pie); $chart->x_axis = null; $chart->set_bg_colour('#202020'); $title->set_style("{font-size: 16px; font-family: Times New Roman; font-weight: bold; color: #000; text-align: center;}"); $chart->set_bg_colour('#FFFFFF'); $chart->set_title($title); // This is the VIEW section: // Should print this first. // $heading = "\n <script type='text/javascript'>\n \n var data = " . $chart->toPrettyString() . "\n\n </script>\n\n\n <script type=\"text/javascript\">\n \n OFC = {};\n \n OFC.jquery = {\n name: 'jQuery',\n version: function(src) { return \$('#'+ src)[0].get_version() },\n rasterize: function (src, dst) { \$('#'+ dst).replaceWith(OFC.jquery.image(src)) },\n image: function(src) { return \"<img src='data:image/png;base64,\" + \$('#'+src)[0].get_img_binary() + \"' />\"},\n popup: function(src) {\n var img_win = window.open('', 'Charts: Export as Image')\n with(img_win.document) {\n write('<html><head><title>Charts: Export as Image<\\/title><\\/head><body>' + OFC.jquery.image(src) + '<\\/body><\\/html>') }\n // stop the 'loading...' message\n img_win.document.close();\n }\n }\n \n // Using_ an object as namespaces is JS Best Practice. I like the Control.XXX style.\n //if (!Control) {var Control = {}}\n //if (typeof(Control == \"undefined\")) {var Control = {}}\n if (typeof(Control == \"undefined\")) {var Control = {OFC: OFC.jquery}}\n \n \n // By default, right-clicking on OFC and choosing \"save image locally\" calls this function.\n // You are free to change the code in OFC and call my wrapper (Control.OFC.your_favorite_save_method)\n // function save_image() { alert(1); Control.OFC.popup('my_chart') }\n function save_image() { alert(\"Your image will be displayed in a new window\"); OFC.jquery.popup('my_chart') }\n </script>\n <div id='my_chart' style='float:left; margin-left:28px;'></div>\n "; return $heading; }
function gsitedata() { $this->autoRender = false; $solid = $this->Session->read('sol'); $host_id = $this->Session->read('host_id'); $tinterval = 3600; $host_srch = ""; if (!empty($host_id) && $host_id != 0) { $host_srch = " AND source_id = " . $host_id; } $this->DnsMessage->recursive = -1; $site_count = $this->DnsMessage->query('SELECT hostname, COUNT(*) FROM dns_messages WHERE sol_id = ' . $solid . $host_srch . ' GROUP BY hostname ORDER BY COUNT(*) DESC LIMIT 50'); //sort($site_count); $data = array(); $x = array(); $max_resp = 0; foreach ($site_count as $site) { $data[] = array((int) $site[0]['COUNT(*)'], 0); if ($max_resp < (int) $site[0]['COUNT(*)']) { $max_resp = (int) $site[0]['COUNT(*)']; } if (empty($site[0]['hostname'])) { $x[] = (string) $site['dns_messages']['hostname']; } else { $x[] = (string) $site[0]['hostname']; } } // joson data format $title = new title(__("Host Popularity", true)); $title->set_style("{font-size: 14px; color: #990000; text-align: center; font-weight:bold;}"); $bar = new bar_stack(); $bar->set_colours(array('#e77919', '#577261')); $bar->set_on_show(new bar_on_show('grow-up', 0, 0.5)); $bar->set_values($data); $bar->set_tooltip('Host: #x_label#<br>Response #val#<br>'); $tooltip = new tooltip(); $tooltip->set_hover(); $tooltip->set_shadow(false); $tooltip->set_stroke(5); $tooltip->set_colour("#6E604F"); $tooltip->set_background_colour("#BDB396"); $data_labels = new x_axis_labels(); $data_labels->rotate(90); $data_labels->set_labels($x); $x_axis = new x_axis(); $x_axis->set_labels($data_labels); $y = new y_axis(); $y->set_range(0, $max_resp * 1.1, (int) ($max_resp / 10)); $chart = new open_flash_chart(); $chart->set_bg_colour('#F9F9F9'); $chart->set_title($title); $chart->add_element($bar); $chart->set_x_axis($x_axis); $chart->set_y_axis($y); $chart->set_tooltip($tooltip); // menu' $m = new ofc_menu("#f0E0ff", "#878787"); $m->values(array(new ofc_menu_item(__('DNS Response', true), 'go_gpage'))); $chart->set_menu($m); header("Content-Type: text/plain"); echo $chart->toPrettyString(); die; }
$chart = new open_flash_chart(); $chart->set_title(new title('Area Chart')); // // Make our area chart: // $area = new area(); // set the circle line width: $area->set_width(2); $area->set_default_dot_style(new hollow_dot()); $area->set_colour('#838A96'); $area->set_fill_colour('#E01B49'); $area->set_fill_alpha(0.4); $area->set_values($data); // add the area object to the chart: $chart->add_element($area); $y_axis = new y_axis(); $y_axis->set_range(-2, 2, 2); $y_axis->labels = null; $y_axis->set_offset(false); $x_axis = new x_axis(); $x_axis->labels = $data; $x_axis->set_steps(2); $x_labels = new x_axis_labels(); $x_labels->set_steps(4); $x_labels->set_vertical(); // Add the X Axis Labels to the X Axis $x_axis->set_labels($x_labels); $chart->add_y_axis($y_axis); $chart->x_axis = $x_axis; echo $chart->toPrettyString();
function get_linear_graph($dates, $vals, $keys = array()) { include 'php-ofc-library/open-flash-chart.php'; $max_y = 0; $arr_filled = array(); for ($i = 0; $i < count($dates); $i++) { $year[] = $dates[$i]; for ($m = 0; $m < count($vals); $m++) { $price[$m][] = (int) $vals[$m][$i]; if ($max_y < (int) $vals[$m][$i]) { $max_y = (int) $vals[$m][$i]; } if (@$arr_filled[$m] != $vals[$m][$i] and @$arr_filled[$m] == 0) { @($arr_filled[$m] = (int) $vals[$m][$i]); } } } while ($max_y % 10 != 0) { $max_y++; } $chart = new open_flash_chart(); //$title = new title( 'UK Petrol price (pence) per Litre' ); $d = new anchor(); if (count($dates) > 60) { $d->size(2); } else { $d->size(3); } $d->halo_size(1); $d->colour('#3D5C56'); $d->rotation(0); $d->sides(4); for ($i = 0; $i < count($price); $i++) { if ($arr_filled[$i] == 0) { continue; } if ($i == 0) { $color = '#5E0722'; } elseif ($i == 1) { $color = '#00FF00'; } else { $color = '#FF0000'; } $area = new area(); $area->set_colour($color); $area->set_default_dot_style($d); $area->set_values($price[$i]); if (isset($keys[$i])) { $area->set_key($keys[$i], 12); } // mb_convert_encoding($keys[$i], "UTF-8", "Windows-1251") $area->set_width(2); $chart->add_element($area); } $x_labels = new x_axis_labels(); if (count($dates) > 40) { $x_labels->set_steps(7); } else { $x_labels->set_steps(1); } $x_labels->set_vertical(); $x_labels->set_colour('#000000'); $x_labels->set_labels($year); $x_labels->rotate(-55); $x_labels->set_size(12); $x = new x_axis(); $x->set_colour('#000000'); $x->set_grid_colour('#DDDDDD'); //$x->set_offset( false ); $x->set_steps(1); // Add the X Axis Labels to the X Axis $x->set_labels($x_labels); $chart->set_x_axis($x); $y = new y_axis(); $y->set_range(0, $max_y); $y->set_colour('#000000'); $y->set_grid_colour('#DDDDDD'); $chart->add_y_axis($y); $chart->set_bg_colour("#FFFFFF"); ?> <script type="text/javascript" src="script/json/json2.js"></script> <script type="text/javascript" src="script/swfobject.js"></script> <script type="text/javascript"> swfobject.embedSWF("open-flash-chart.swf", "my_chart", "600", "350", "9.0.0"); </script> <script type="text/javascript"> function ofc_ready() { } function open_flash_chart_data() { return JSON.stringify(data); } function findSWF(movieName) { if (navigator.appName.indexOf("Microsoft")!= -1) { return window[movieName]; } else { return document[movieName]; } } var data = <?php echo $chart->toPrettyString(); ?> ; </script> <?php }