function age() { if ($this->Session->read('Policy') <= 2) { $this->redirect(array('controller' => 'users', 'action' => 'login')); return; } $sqlage = "SELECT YEAR( CURRENT_DATE( ) ) - YEAR( users.birthday ) AS age, COUNT( * ) AS count\r\n FROM users\r\n GROUP BY (\r\n YEAR( CURRENT_DATE( ) ) - YEAR( users.birthday )\r\n )"; $data = $this->query($sqlage); $chart = new PieChart(); $dataSet = new XYDataSet(); while ($row = mysql_fetch_array($data)) { $dataSet->addPoint(new Point("Age :" . $row[0] . "(" . $row[1] . ")", $row[1])); } $chart->setDataSet($dataSet); $chart->setTitle("Report age"); $chart->render("../webroot/img/age.png"); }
/** * @author Ibnu Daqiqil Id * @param string $title Judul Chart * @param array $data Data array dengan dua dimensi (key,value) * @param integer $x Lebar chart * @param integer $y Tinggi Chart * @param string $type tipe output chart (bar_vertikal,bar_horizontal,pie) * @param boolean $render Apakah di render ke file? */ function create_bar_chart($title, $data, $x = 500, $y = 300, $type = "bar_vertikal", $render_file = FALSE) { if ("bar_horizontal" == $type) { $chart = new HorizontalBarChart($x, $y); } else { if ("bar_vertikal" == $type) { $chart = new VerticalBarChart($x, $y); } else { $chart = new PieChart($x, $y); } } $dataSet = new XYDataSet(); foreach ($data as $value) { $dataSet->addPoint(new Point($value['key'], $value['value'])); } $chart->setDataSet($dataSet); $chart->setTitle($title); if (!$render_file) { return $chart->render(); } else { return $chart->render($render_file); } }
* */ /** * Pie chart demonstration * */ include "../libchart/classes/libchart.php"; $chart = new PieChart(); $chart->getPlot()->getPalette()->setPieColor(array(new Color(255, 0, 0), new Color(255, 255, 255))); $dataSet = new XYDataSet(); $dataSet->addPoint(new Point("Amanita abrupta", 80)); $dataSet->addPoint(new Point("Amanita arocheae", 75)); $dataSet->addPoint(new Point("Clitocybe dealbata", 50)); $dataSet->addPoint(new Point("Cortinarius rubellus", 70)); $dataSet->addPoint(new Point("Gyromitra esculenta", 37)); $dataSet->addPoint(new Point("Lepiota castanea", 37)); $chart->setDataSet($dataSet); $chart->setTitle("Deadly mushrooms"); $chart->render("generated/pie_chart_color.png"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Libchart pie chart color demonstration</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" /> </head> <body> <img alt="Pie chart color test" src="generated/pie_chart_color.png" style="border: 1px solid gray;"/> </body> </html>
* * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ********************************************************************************************************* * Description: * this extension creates a pie chart of the comparison of hotspots per unique users * * Authors: Liran Tal <*****@*****.**> * ********************************************************************************************************* */ include 'checklogin.php'; include 'opendb.php'; include 'libchart/libchart.php'; header("Content-type: image/png"); $chart = new PieChart(620, 320); // getting total downloads of days in a month $sql = "select " . $configValues['CONFIG_DB_TBL_DALOHOTSPOTS'] . ".name, count(distinct(UserName)), count(radacctid), " . " avg(AcctSessionTime), sum(AcctSessionTime) FROM " . $configValues['CONFIG_DB_TBL_RADACCT'] . " JOIN " . $configValues['CONFIG_DB_TBL_DALOHOTSPOTS'] . " ON (" . $configValues['CONFIG_DB_TBL_RADACCT'] . ".calledstationid LIKE " . $configValues['CONFIG_DB_TBL_DALOHOTSPOTS'] . ".mac) GROUP BY " . $configValues['CONFIG_DB_TBL_DALOHOTSPOTS'] . ".name;"; $res = $dbSocket->query($sql); while ($row = $res->fetchRow()) { $chart->addPoint(new Point("{$row['0']} ({$row['1']} users)", "{$row['1']}")); } $chart->setTitle("Distribution of Unique users per Hotspot"); $chart->render(); include 'closedb.php'; ?>
/** * Función encargada de generar la gráfica con el porcentaje * de alumnos que pasan y no pasan los test. Se muestra * en el panel del profesor. * */ public function generarGraficaAlumnosTest() { $alumnos_tabla = TableRegistry::get("Alumnos"); $alumnos = $alumnos_tabla->find('all'); $alumnos_registrados = false; $alumnos_pasan_test = 0; $alumnos_no_pasan_test = 0; foreach ($alumnos as $alumno) { $alumnos_registrados = true; $intentos_tabla = TableRegistry::get("Intentos"); $intentos_pasan_test = $intentos_tabla->find('all')->where(['tarea_id' => $_SESSION["lti_idTarea"], 'alumno_id' => $alumno->id, 'resultado' => 1]); if ($intentos_pasan_test->isEmpty()) { $alumnos_no_pasan_test++; } else { $alumnos_pasan_test++; } } if ($alumnos_registrados) { // hay alumnos $chart = new \PieChart(800, 350); $dataSet = new \XYDataSet(); $dataSet->addPoint(new \Point("Alumnos que pasan los test", $alumnos_pasan_test)); $dataSet->addPoint(new \Point("Alumnos que no pasan los test", $alumnos_no_pasan_test)); $chart->setDataSet($dataSet); $chart->setTitle("Porcentaje de alumnos que pasan y no pasan los test"); $chart->render("img/" . $_SESSION["lti_idTarea"] . "-prof-test.png"); } }
* * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ********************************************************************************************************* * Description: * this extension creates a pie chart of the comparison of hotspots per unique users * * Authors: Liran Tal <*****@*****.**> * ********************************************************************************************************* */ include 'checklogin.php'; include 'opendb.php'; include 'libchart/libchart.php'; header("Content-type: image/png"); $chart = new PieChart(620, 320); // getting total downloads of days in a month $sql = "SELECT " . $configValues['CONFIG_DB_TBL_DALOHOTSPOTS'] . ".name, count(distinct(UserName)), count(radacctid), " . " avg(AcctSessionTime), sum(AcctSessionTime) FROM " . $configValues['CONFIG_DB_TBL_RADACCT'] . " JOIN " . $configValues['CONFIG_DB_TBL_DALOHOTSPOTS'] . " ON (" . $configValues['CONFIG_DB_TBL_RADACCT'] . ".calledstationid LIKE " . $configValues['CONFIG_DB_TBL_DALOHOTSPOTS'] . ".mac) GROUP BY " . $configValues['CONFIG_DB_TBL_DALOHOTSPOTS'] . ".name;"; $res = $dbSocket->query($sql); while ($row = $res->fetchRow()) { $chart->addPoint(new Point("{$row['0']} ({$row['3']} seconds)", "{$row['3']}")); } $chart->setTitle("Distribution of Time usage per Hotspot"); $chart->render(); include 'closedb.php'; ?>
require_once "{$root}/Function/Db.php"; require_once "{$root}/Function/Debug.php"; require_once "{$root}/Function/DataTime.php"; $Stati = GetRows("tab_stato_mch", "", "stato_mch", $db, 1); /* echo "<pre>"; print_r($Stati); echo "</pre>"; */ //Padding::Padding ($top, $right, $bottom, $left) define("ChartPath", "tmp/chart.png"); define("ChartWidth", 1000); define("ChartHeight", 400); $chart = new PieChart(ChartWidth, ChartHeight); $chart->getPlot()->setGraphPadding(new Padding("5", "5", "5", "5")); $chart->setTitle("Statistiche Magazzino RollOut"); $dataSet = new XYDataSet(); foreach ($Stati as $key => $field) { $stat = GetRows("tab_macchine", "id_stato = '" . $field['id_stato_call'] . "'", "", $db, 1, "count(id_macchina) as count"); /* echo "[Debug]: count stato: ".$stat[0]['count']." <br />"; */ $dataSet->addPoint(new Point($field['stato_call'] . " ( " . $stat[0]['count'] . " )", $stat[0]['count'])); } $chart->setDataSet($dataSet); $chart->render(ChartPath); ?> <img src="<?php echo ChartPath;
function show_page($mode_) { if (isset($_GET['from'])) { $t0 = strtotime($_GET['from']); } else { $t0 = strtotime($mode_->get_default_from()); } if (isset($_GET['to'])) { $t1 = strtotime($_GET['to']); } else { $t1 = time(); } $t0 = $mode_->transform_date($t0); $t1 = $mode_->transform_date($t1); if ($t0 > $t1) { popup_error(_('Error: "from" date is after "to" date, the dates will be reversed')); $buf = $t0; $t0 = $t1; $t1 = $buf; } if ($t1 > time()) { popup_error(_('Error: "to" field is in the future, the current time will be used')); $t1 = $mode_->transform_date(time()); } if ($t0 > time()) { popup_error(_('Error: "from" field is in the future, the current time will be used')); $t0 = $mode_->transform_date(time()); } $t2 = strtotime($mode_->get_next(), $t1); /* General system */ if (!is_writable(TMP_DIR)) { popup_error(sprintf(_("%s is not writable"), TMP_DIR)); page_header(); echo '<h1>' . _('Reporting') . '</h1>'; page_footer(); die; } list($session_number, $result, $res_server, $end_status, $end_status_by_server) = get_session_history($t0, $t2, $mode_); $info2 = get_server_history($t0, $t2, $mode_); $chart = new LineChart(); $chart->getPlot()->setLogoFileName(''); $dataSet = new XYDataSet(); $step = max(round(count($result) / MAX_STEPS), 1); $step_i = 0; foreach ($result as $day => $num) { $text = ''; if ($step_i % $step == 0) { $text = $mode_->get_pretty_date($day); } $step_i++; $dataSet->addPoint(new Point($text, $num)); } $chart->setDataSet($dataSet); $chart->setTitle(_('Number of launched sessions')); $tmpfile = tempnam(TMP_DIR, REPORT_PREFIX); $file_id = substr($tmpfile, strlen(TMP_DIR . '/' . REPORT_PREFIX)); $chart->render($tmpfile); // Foreach server $servers = array(); foreach ($res_server as $server_id => $value) { $servers[$server_id] = array(); $server = $_SESSION['service']->server_info($server_id); if ($server) { $servers[$server_id]['name'] = $server->getDisplayName(); } else { $servers[$server_id]['name'] = $server_id; } } if ($session_number > 0) { $dataSet = new XYDataSet(); foreach ($res_server as $server_id => $c) { if ($server_id === "") { $server_id = _("unknown"); } $tot = 0; foreach ($c as $k => $v) { $tot += $v; } $value = $tot * 100 / $session_number; $dataSet->addPoint(new Point(str_replace(array('%SERVER%', '%TOTAL%'), array($servers[$server_id]['name'], (int) $tot), ngettext(_('%SERVER% (%TOTAL% session)'), _('%SERVER% (%TOTAL% sessions)'), $value)), $value)); } $chart = new PieChart(); $chart->getPlot()->setLogoFileName(''); $chart->setTitle(_('Session repartition')); $chart->setDataSet($dataSet); $tmpfile = tempnam(TMP_DIR, REPORT_PREFIX); $file_id2 = substr($tmpfile, strlen(TMP_DIR . '/' . REPORT_PREFIX)); $chart->render($tmpfile); if (count($end_status) > 0) { $dataSet = new XYDataSet(); foreach ($end_status as $status_session => $number_status) { $dataSet->addPoint(new Point(str_replace(array('%STATUS%', '%TOTAL%'), array(Session::textEndStatus($status_session), (int) $number_status), ngettext(_('%STATUS% (%TOTAL% session)'), _('%STATUS% (%TOTAL% sessions)'), $number_status)), $number_status)); } $chart = new PieChart(); $chart->getPlot()->setLogoFileName(''); $chart->setTitle(_('Session end status')); $chart->setDataSet($dataSet); $tmpfile = tempnam(TMP_DIR, REPORT_PREFIX); $file_id3 = substr($tmpfile, strlen(TMP_DIR . '/' . REPORT_PREFIX)); $chart->render($tmpfile); } } // Foreach server foreach ($res_server as $server_id => $value) { $chart = new LineChart(); $chart->getPlot()->setLogoFileName(''); $dataSet = new XYDataSet(); $step = max(round(count($value) / MAX_STEPS), 1); $step_i = 0; foreach ($value as $day => $num) { $text = $step_i % $step == 0 ? substr($day, -2) : ''; $step_i++; $dataSet->addPoint(new Point($text, $num)); } $chart->setDataSet($dataSet); $chart->setTitle(_('Number of launched sessions')); $tmpfile = tempnam(TMP_DIR, REPORT_PREFIX); $servers[$server_id]['session_file'] = substr($tmpfile, strlen(TMP_DIR . '/' . REPORT_PREFIX)); $chart->render($tmpfile); $dataSet = new XYDataSet(); $end_status2 = array(); if (array_key_exists($server_id, $end_status_by_server)) { $end_status2 = $end_status_by_server[$server_id]; } if (count($end_status2) > 0) { foreach ($end_status2 as $status_session => $number_status) { $dataSet->addPoint(new Point(str_replace(array('%STATUS%', '%TOTAL%'), array(Session::textEndStatus($status_session), (int) $number_status), ngettext(_('%STATUS% (%TOTAL% session)'), _('%STATUS% (%TOTAL% sessions)'), $number_status)), $number_status)); } $chart = new PieChart(); $chart->getPlot()->setLogoFileName(''); $chart->setTitle(_('Session end status')); $chart->setDataSet($dataSet); $tmpfile = tempnam(TMP_DIR, REPORT_PREFIX); $servers[$server_id]['session_end_status'] = substr($tmpfile, strlen(TMP_DIR . '/' . REPORT_PREFIX)); $chart->render($tmpfile); } if (!isset($info2[$server_id])) { continue; } $dataSet_cpu = new XYDataSet(); $step = max(round(count($info2[$server_id]['cpu']) / MAX_STEPS), 1); $step_i = 0; foreach ($info2[$server_id]['cpu'] as $day => $num) { $text = $step_i % $step == 0 ? substr($day, -2) : ''; $step_i++; $b = get_avg_value($num); $dataSet_cpu->addPoint(new Point($text, $b)); } $chart = new LineChart(); $chart->getPlot()->setLogoFileName(''); $chart->setDataSet($dataSet_cpu); $chart->setTitle(_('CPU usage')); $tmpfile = tempnam(TMP_DIR, REPORT_PREFIX); $servers[$server_id]['cpu_file'] = substr($tmpfile, strlen(TMP_DIR . '/' . REPORT_PREFIX)); $chart->render($tmpfile); $dataSet_ram = new XYDataSet(); $step = max(round(count($info2[$server_id]['ram']) / MAX_STEPS), 1); $step_i = 0; foreach ($info2[$server_id]['ram'] as $day => $num) { $text = $step_i % $step == 0 ? substr($day, -2) : ''; $step_i++; $b = get_avg_value($num); $dataSet_ram->addPoint(new Point($text, $b)); } $chart = new LineChart(); $chart->getPlot()->setLogoFileName(''); $chart->setDataSet($dataSet_ram); $chart->setTitle(_('RAM usage')); $tmpfile = tempnam(TMP_DIR, REPORT_PREFIX); $servers[$server_id]['ram_file'] = substr($tmpfile, strlen(TMP_DIR . '/' . REPORT_PREFIX)); $chart->render($tmpfile); } page_header(array('js_files' => array('media/script/lib/calendarpopup/CalendarPopup.js'))); echo '<h1>' . _('Reporting') . '</h1>'; echo '<div id="calendar_day_from" style="position: absolute; visibility: hidden; background: white;"></div>'; echo '<div id="calendar_day_to" style="position: absolute; visibility: hidden; background: white;"></div>'; echo '<script type="text/javascript" charset="utf-8">'; echo ' document.write(getCalendarStyles());'; echo ' var calendar_day_from = new CalendarPopup("calendar_day_from");'; echo ' calendar_day_from.setReturnFunction(\'func_day_from\');'; echo ' function func_day_from(y,m,d) {'; echo ' if (m < 10)'; echo ' m = \'0\'+m;'; echo ' if (d < 10)'; echo ' d = \'0\'+d;'; echo ' $(\'from\').value = y+\'-\'+m+\'-\'+d;'; echo ' $(\'anchor_day_from\').innerHTML = $(\'from\').value;'; echo ' }'; echo ' var calendar_day_to = new CalendarPopup("calendar_day_to");'; echo ' calendar_day_to.setReturnFunction(\'func_day_to\');'; echo ' function func_day_to(y,m,d) {'; echo ' if (m < 10)'; echo ' m = \'0\'+m;'; echo ' if (d < 10)'; echo ' d = \'0\'+d;'; echo ' $(\'to\').value = y+\'-\'+m+\'-\'+d;'; echo ' $(\'anchor_day_to\').innerHTML = $(\'to\').value;'; echo ' }'; echo ' Event.observe(window, \'load\', function() {'; echo ' func_day_from(' . date('Y', $t0) . ', ' . date('m', $t0) . ', ' . date('d', $t0) . ');'; echo ' func_day_to(' . date('Y', $t1) . ', ' . date('m', $t1) . ', ' . date('d', $t1) . ');'; echo ' });'; echo ' function generateReport() {'; echo ' $(\'from\').value+= \' \'+$(\'hour_from\').value+\':00\';'; echo ' $(\'to\').value+= \' \'+$(\'hour_to\').value+\':00\';'; echo ' return true;'; echo ' }'; echo '</script>'; echo '<form onsubmit="return generateReport();">'; echo '<input id="from" name="from" value="" type="hidden" />'; echo '<input id="to" name="to" value="" type="hidden" />'; echo '<strong>' . _('From') . '</strong> '; echo '<a href="#" id="anchor_day_from" onclick="calendar_day_from.select($(\'from\'), \'anchor_day_from\'); return false;" >' . date('Y-m-d', $t0) . '</a> '; echo '<select id="hour_from">'; for ($i = 0; $i < 24; $i++) { echo '<option value="' . $i . '"'; if ((int) date('H', $t0) == $i) { echo ' selected="selected"'; } echo '>' . $i . ':00</option>'; } echo '</select> '; echo '<strong>' . _('to') . '</strong> '; echo '<a href="#" id="anchor_day_to" onclick="calendar_day_to.select($(\'to\'), \'anchor_day_to\'); return false;" >' . date('Y-m-d', $t1) . '</a> '; echo '<select id="hour_to">'; for ($i = 0; $i < 24; $i++) { echo '<option value="' . $i . '"'; if ((int) date('H', $t1) == $i) { echo ' selected="selected"'; } echo '>' . $i . ':00</option>'; } echo '</select> '; echo '<strong>' . _('step') . '</strong>'; echo '<select name="mode">'; echo '<option value="minute"'; if ($mode_->get_value() == 'minute') { echo ' selected="selected"'; } echo '>' . ReportMode_minute::get_name() . '</option>'; echo '<option value="hour"'; if ($mode_->get_value() == 'hour') { echo ' selected="selected"'; } echo '>' . ReportMode_hour::get_name() . '</option>'; echo '<option value="day"'; if ($mode_->get_value() == 'day') { echo ' selected="selected"'; } echo '>' . ReportMode_day::get_name() . '</option>'; echo '</select> '; echo '<input type="submit" value="' . _('Refresh') . '" />'; echo '</form>'; echo '<div>'; echo '<table><tr><td>'; echo '<img src="?img=1&file=' . $file_id . '" />'; echo '</td><td><i>'; if ($mode_->get_value() == 'day') { echo _('Abscissa: day of the month'); } else { if ($mode_->get_value() == 'hour') { echo _('Abscissa: hour of the day'); } else { if ($mode_->get_value() == 'minute') { echo _('Abscissa: minute of the hour'); } } } echo '<br/>'; echo _('Ordinate: number of sessions'); echo '</i></td></tr>'; echo '<tr><td>'; echo '<img src="?img=nb_sessions&mode=' . $mode_->get_value() . '&from=' . date('Y-m-d H:i:s', $t0) . '&to=' . date('Y-m-d H:i:s', $t1) . '" />'; echo '</td><td><i>'; if ($mode_->get_value() == 'day') { echo _('Abscissa: day of the month'); } else { if ($mode_->get_value() == 'hour') { echo _('Abscissa: hour of the day'); } else { if ($mode_->get_value() == 'minute') { echo _('Abscissa: minute of the hour'); } } } echo '<br/>'; echo _('Ordinate: number of sessions'); echo '</i></td></tr>'; echo '</table>'; if ($session_number > 0) { if (isset($file_id2)) { echo '<img src="?img=1&file=' . $file_id2 . '" />'; } echo ' '; if (isset($file_id3)) { echo '<img src="?img=1&file=' . $file_id3 . '" />'; } } echo '<form action="session-reporting.php">'; echo '<input type="hidden" name="search_by[]" value="time" />'; echo '<input type="hidden" name="from" value="' . $t0 . '" />'; echo '<input type="hidden" name="to" value="' . $t1 . '" />'; echo '<input type="submit" value="' . _('See archived sessions in this time range') . '" />'; echo '</form>'; foreach ($servers as $server_id => $value) { echo '<hr/>'; echo '<h2>' . _('Server') . ' ' . $value['name'] . '</h2>'; echo '<table>'; if (isset($value['session_file'])) { echo '<tr><td>'; echo '<img src="?img=1&file=' . $value['session_file'] . '" />'; echo '</td><td><i>'; if ($mode_->get_value() == 'day') { echo _('Abscissa: day of the month'); } else { if ($mode_->get_value() == 'hour') { echo _('Abscissa: hour of the day'); } else { if ($mode_->get_value() == 'minute') { echo _('Abscissa: minute of the hour'); } } } echo '<br/>'; echo _('Ordinate: number of sessions'); echo '</i></td></tr>'; } if (isset($value['session_end_status'])) { echo '<tr><td>'; echo '<img src="?img=1&file=' . $value['session_end_status'] . '" />'; echo '</td><td></td></tr>'; } if (isset($value['cpu_file'])) { echo '<tr><td>'; echo '<img src="?img=1&file=' . $value['cpu_file'] . '" />'; echo '</td><td><i>'; if ($mode_->get_value() == 'day') { echo _('Abscissa: day of the month'); } else { if ($mode_->get_value() == 'hour') { echo _('Abscissa: hour of the day'); } else { if ($mode_->get_value() == 'minute') { echo _('Abscissa: minute of the hour'); } } } echo '<br/>'; echo _('Ordinate: CPU usage in percent'); echo '</i></td></tr>'; } if (isset($value['ram_file'])) { echo '<tr><td>'; echo '<img src="?img=1&file=' . $value['ram_file'] . '" />'; echo '</td><td><i>'; if ($mode_->get_value() == 'day') { echo _('Abscissa: day of the month'); } else { if ($mode_->get_value() == 'hour') { echo _('Abscissa: hour of the day'); } else { if ($mode_->get_value() == 'minute') { echo _('Abscissa: minute of the hour'); } } } echo '<br/>'; echo _('Ordinate: RAM usage in percent'); echo '</i></td></tr>'; } echo '</table>'; } echo '</div>'; page_footer(); die; }
/* Libchart - PHP chart library * Copyright (C) 2005-2011 Jean-Marc Trémeaux (jm.tremeaux at gmail.com) * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /** * Direct PNG output demonstration (image not saved to disk) * */ include "../libchart/classes/libchart.php"; header("Content-type: image/png"); $chart = new PieChart(500, 300); $dataSet = new XYDataSet(); $dataSet->addPoint(new Point("Bleu d'Auvergne", 50)); $dataSet->addPoint(new Point("Tomme de Savoie", 75)); $dataSet->addPoint(new Point("Crottin de Chavignol", 30)); $chart->setDataSet($dataSet); $chart->setTitle("Preferred Cheese"); $chart->render();
* * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ********************************************************************************************************* * Description: * this extension creates a pie chart of the comparison of hotspots per unique users * * Authors: Liran Tal <*****@*****.**> * ********************************************************************************************************* */ include 'checklogin.php'; include 'opendb.php'; include 'libchart/libchart.php'; header("Content-type: image/png"); $chart = new PieChart(620, 320); // getting total downloads of days in a month $sql = "SELECT " . $configValues['CONFIG_DB_TBL_DALOHOTSPOTS'] . ".name, count(distinct(UserName)), count(radacctid), avg(AcctSessionTime), sum(AcctSessionTime) FROM " . $configValues['CONFIG_DB_TBL_RADACCT'] . " JOIN " . $configValues['CONFIG_DB_TBL_DALOHOTSPOTS'] . " ON (" . $configValues['CONFIG_DB_TBL_RADACCT'] . ".calledstationid LIKE " . $configValues['CONFIG_DB_TBL_DALOHOTSPOTS'] . ".mac) GROUP BY " . $configValues['CONFIG_DB_TBL_DALOHOTSPOTS'] . ".name;"; $res = $dbSocket->query($sql); while ($row = $res->fetchRow()) { $chart->addPoint(new Point("{$row['0']} ({$row['2']} users)", "{$row['2']}")); } $chart->setTitle("Distribution of Hits (Logins) per Hotspot"); $chart->render(); include 'closedb.php'; ?>
echo $year; ?> </h3></div> <div class="box-body"> <?php //Initialisation graphique $chartF = new PieChart(400, 280); $dataSetF = new XYDataSet(); $row = getStatFrequence($year, $epn); //debug($row); $dataSetF->addPoint(new Point("1 à 2 fois par semaine", $row['f1'])); $dataSetF->addPoint(new Point("2 à 3 fois par semaine", $row['f2'])); $dataSetF->addPoint(new Point("+3 fois par semaine", $row['f3'])); $chartF->setDataSet($dataSetF); $chartF->getPlot()->getPalette()->setPieColor(array(new Color(255, 133, 4), new Color(234, 42, 83), new Color(44, 173, 135))); $chartF->setTitle("Frequence des visites (" . $year . ") "); $chartF->render("img/chart/" . $year . "/resa_frequenceSemaine_" . $namepn . ".png"); ?> <img src="img/chart/<?php echo $year; ?> /resa_frequenceSemaine_<?php echo $namepn; ?> .png" > </div><!-- /.box-body--> </div><!-- /.box --> <!-- Classement des réservations : les adhérents par classe d'âge--> <div class="box box-primary"> <div class="box-header"><i class="fa fa-bar-chart-o"></i><h3 class="box-title">Les réservations par classe d'âge, année <?php
* ********************************************************************************************************* * Description: * this extension creates a pie chart of online users * * Authors: Liran Tal <*****@*****.**> * ********************************************************************************************************* */ include 'checklogin.php'; include 'opendb.php'; include 'libchart/libchart.php'; header("Content-type: image/png"); $chart = new PieChart(620, 320); // getting total users $sql = "SELECT DISTINCT(UserName) FROM " . $configValues['CONFIG_DB_TBL_RADCHECK']; $res = $dbSocket->query($sql); $totalUsers = $res->numRows(); $chart->addPoint(new Point("{$totalUsers} usuarios totales", "{$totalUsers}")); // get total users online $sql = "SELECT DISTINCT(UserName) FROM " . $configValues['CONFIG_DB_TBL_RADACCT'] . " WHERE (AcctStopTime is NULL OR AcctStopTime = '0000-00-00 00:00:00')"; $res = $dbSocket->query($sql); $totalUsersOnline = $res->numRows(); $chart->addPoint(new Point("{$totalUsersOnline} usuarios en linea", "{$totalUsersOnline}")); $chart->setTitle("Usuarios en linea"); $chart->render(); include 'closedb.php'; ?>
function cargar_informe($informe, $en_ventana = 1, $formato = "htm", $estilo = "Informes", $embebido = 0) { global $ConexionPDO, $ArchivoCORE, $TablasCore, $Nombre_Aplicacion, $PCO_ValorBusquedaBD, $PCO_CampoBusquedaBD; // Carga variables de sesion por si son comparadas en alguna condicion. De todas formas pueden ser cargadas por el usuario en el diseno del informe global $PCOSESS_LoginUsuario, $Nombre_usuario, $Descripcion_usuario, $Nivel_usuario, $Correo_usuario, $LlaveDePasoUsuario, $PCO_FechaOperacion; // Carga variables de definicion de tablas global $ListaCamposSinID_informe, $ListaCamposSinID_informe_campos, $ListaCamposSinID_informe_tablas, $ListaCamposSinID_informe_condiciones, $ListaCamposSinID_informe_boton; global $MULTILANG_TotalRegistros, $MULTILANG_ContacteAdmin, $MULTILANG_ObjetoNoExiste, $MULTILANG_ErrorTiempoEjecucion, $MULTILANG_Informes, $MULTILANG_IrEscritorio, $MULTILANG_ErrorDatos, $MULTILANG_InfErrTamano, $MULTILANG_MonCommSQL; global $IdiomaPredeterminado; global $PCO_InformesDataTable; global $ModoDepuracion; // Busca datos del informe $consulta_informe = ejecutar_sql("SELECT id," . $ListaCamposSinID_informe . " FROM " . $TablasCore . "informe WHERE id=? ", "{$informe}"); $registro_informe = $consulta_informe->fetch(); $Identificador_informe = $registro_informe["id"]; //Si no encuentra informe presenta error if ($registro_informe["id"] == "") { mensaje($MULTILANG_ErrorTiempoEjecucion, $MULTILANG_ObjetoNoExiste . " " . $MULTILANG_ContacteAdmin . "<br>(" . $MULTILANG_Informes . " {$informe})", '', 'fa fa-times fa-5x icon-red texto-blink', 'alert alert-danger alert-dismissible'); } //Identifica si el informe requiere un formulario de filtrado previo if ($registro_informe["formulario_filtrado"] != "") { //Determina si solicita el informe desde el formulario de filtrado apropiado, sino redirecciona a este global $PCO_FormularioActivo; if ($registro_informe["formulario_filtrado"] != $PCO_FormularioActivo) { echo '<form name="precarga_form_filtro" action="' . $ArchivoCORE . '" method="POST"> <input type="Hidden" name="PCO_Accion" value="cargar_objeto"> <input type="Hidden" name="PCO_InformeFiltro" value="' . $registro_informe["id"] . '"> <input type="Hidden" name="objeto" value="frm:' . $registro_informe["formulario_filtrado"] . ':1"> <input type="Hidden" name="Presentar_FullScreen" value="' . @$Presentar_FullScreen . '"> <input type="Hidden" name="Precarga_EstilosBS" value="' . @$Precarga_EstilosBS . '"> <script type="" language="JavaScript"> document.precarga_form_filtro.submit(); </script>'; die; } } //Si hay variables de filtro definidas busca su valor en el contexto global if ($registro_informe["variables_filtro"] != "") { $arreglo_variables_filtro = @explode(",", $registro_informe["variables_filtro"]); //Busca y convierte cada variable recibida en global foreach ($arreglo_variables_filtro as $nombre_variable_filtro) { //if (isset($$nombre_variable_filtro)) // {Deprecated} global ${$nombre_variable_filtro}; } } // Inicia CONSTRUCCION DE CONSULTA DINAMICA $numero_columnas = 0; //Busca los CAMPOS definidos para el informe $consulta = "SELECT "; $consulta_campos = ejecutar_sql("SELECT id," . $ListaCamposSinID_informe_campos . " FROM " . $TablasCore . "informe_campos WHERE informe=? ORDER BY peso", "{$informe}"); $PCO_ColumnasOcultas[] = "ArregloDeCamposOcultos"; while ($registro_campos = $consulta_campos->fetch()) { //Si tiene alias definido lo agrega $posfijo_campo = ""; if ($registro_campos["valor_alias"] != "") { $posfijo_campo = " as " . $registro_campos["valor_alias"]; } //Agrega el campo a la consulta $consulta .= $registro_campos["valor_campo"] . $posfijo_campo . ","; //Crea un arreglo con los campos marcados como ocultos para filtrarlos luego if ($registro_campos["visible"] == 0) { $PCO_ColumnasOcultas[] = $registro_campos["valor_campo"] . $posfijo_campo; //Lleva el campo oculto despues del punto $PCO_PartesCampo = explode(".", $registro_campos["valor_campo"] . $posfijo_campo); $PCO_ColumnasOcultas[] = $PCO_PartesCampo[1]; //Lleva el campo oculto si es un alias $PCO_PartesCampo = explode(" as ", $registro_campos["valor_campo"] . $posfijo_campo); $PCO_ColumnasOcultas[] = $PCO_PartesCampo[1]; } } // Elimina la ultima coma en el listado de campos $consulta = substr($consulta, 0, strlen($consulta) - 1); //Busca las TABLAS definidas para el informe $consulta .= " FROM "; $consulta_tablas = ejecutar_sql("SELECT id," . $ListaCamposSinID_informe_tablas . " FROM " . $TablasCore . "informe_tablas WHERE informe=? ", "{$informe}"); while ($registro_tablas = $consulta_tablas->fetch()) { //Si tiene alias definido lo agrega $posfijo_tabla = ""; if ($registro_tablas["valor_alias"] != "") { $posfijo_tabla = " as " . $registro_tablas["valor_alias"]; } //Agrega tabla a la consulta $consulta .= $registro_tablas["valor_tabla"] . $posfijo_tabla . ","; } // Elimina la ultima coma en el listado de tablas $consulta = substr($consulta, 0, strlen($consulta) - 1); // Busca las CONDICIONES para el informe $consulta .= " WHERE "; $consulta_condiciones = ejecutar_sql("SELECT id," . $ListaCamposSinID_informe_condiciones . " FROM " . $TablasCore . "informe_condiciones WHERE informe=? ORDER BY peso", "{$informe}"); $hay_condiciones = 0; while ($registro_condiciones = $consulta_condiciones->fetch()) { //Agrega condicion a la consulta $valor_izquierdo = $registro_condiciones["valor_izq"]; $valor_derecho = $registro_condiciones["valor_der"]; // CONVIERTE VARIABLES DE SESION PHP A VALORES PARA EL QUERY Cuando el primer simbolos es un PESOS ($), es decir, solo se ingreso una variable //LADO IZQUIERDO DE LA CONDICION //Si el valor Izquierdo a comparar inicia por signo pesos y es una variable PHP la usa como tal if (@$valor_izquierdo[0] == "\$") { //Quita el signo pesos inicial para buscar la variable $variable_a_buscar = substr($valor_izquierdo, 1, strlen($valor_izquierdo)); // Si la variable esta definida toma su valor encerrado entre comillas para el query y evitar conflictos de variables con espacios y demas. if (@isset($variable_a_buscar)) { $valor_izquierdo = "'" . ${$variable_a_buscar} . "'"; } } //Evalua casos donde se tienen variables PHP escapadas por llaves. Ej "%{$Variable}%" si fuera para un LIKE, por ejemplo. if (strpos($valor_izquierdo, "{") !== FALSE && strrpos($valor_izquierdo, "}") !== FALSE) { //Determina las posiciones de las llaves en la cadena $PosLlaveIzquierda = strpos($valor_izquierdo, "{"); $PosLlaveDerecha = strrpos($valor_izquierdo, "}"); //Toma solo el pedazo entre llaves para intentar ubicar el valor de la variable por su nombre $NombreVariable = substr($valor_izquierdo, $PosLlaveIzquierda + 2, $PosLlaveDerecha - $PosLlaveIzquierda - 2); //Si la variable no esta definida la busca en el entorno global global ${$NombreVariable}; if (@isset($NombreVariable)) { $ValorVariable = ${$NombreVariable}; //Reemplaza el valor encontrado en la cadena de valor original $valor_izquierdo = str_replace('{$' . $NombreVariable . '}', $ValorVariable, $valor_izquierdo); } } //LADO DERECHO DE LA CONDICION //Si el valor Derecho a comparar inicia por signo pesos y es una variable PHP la usa como tal if (@$valor_derecho[0] == "\$") { //Quita el signo pesos inicial para buscar la variable $variable_a_buscar = substr($valor_derecho, 1, strlen($valor_derecho)); // Si la variable esta definida toma su valor encerrado entre comillas para el query y evitar conflictos de variables con espacios y demas. if (@isset($variable_a_buscar)) { $valor_derecho = "'" . ${$variable_a_buscar} . "'"; } } //Evalua casos donde se tienen variables PHP escapadas por llaves. Ej "%{$Variable}%" si fuera para un LIKE, por ejemplo. if (strpos($valor_derecho, "{") !== FALSE && strrpos($valor_derecho, "}") !== FALSE) { //Determina las posiciones de las llaves en la cadena $PosLlaveIzquierda = strpos($valor_derecho, "{"); $PosLlaveDerecha = strrpos($valor_derecho, "}"); //Toma solo el pedazo entre llaves para intentar ubicar el valor de la variable por su nombre $NombreVariable = substr($valor_derecho, $PosLlaveIzquierda + 2, $PosLlaveDerecha - $PosLlaveIzquierda - 2); //Si la variable no esta definida la busca en el entorno global global ${$NombreVariable}; if (@isset($NombreVariable)) { $ValorVariable = ${$NombreVariable}; //Reemplaza el valor encontrado en la cadena de valor original $valor_derecho = str_replace('{$' . $NombreVariable . '}', $ValorVariable, $valor_derecho); } } $consulta .= " " . $valor_izquierdo . " " . $registro_condiciones["operador"] . " " . $valor_derecho . " "; $hay_condiciones = 1; } if (!$hay_condiciones) { $consulta .= " 1 "; } if (@$registro_informe["agrupamiento"] != "") { $campoagrupa = $registro_informe["agrupamiento"]; $consulta .= " GROUP BY {$campoagrupa}"; } if (@$registro_informe["ordenamiento"] != "") { $campoorden = $registro_informe["ordenamiento"]; $consulta .= " ORDER BY {$campoorden}"; } // Si el informe tiene formato_final = T (tabla de datos) if ($registro_informe["formato_final"] == "T") { $SalidaFinalInforme = ''; $SalidaFinalInformePDF = ''; if ($en_ventana) { //Cuando es embebido (=1) no imprime el boton de retorno pues se asume dentro de un formulario if (!$embebido) { echo '<div align=center><button type="Button" onclick="document.core_ver_menu.submit()" class="btn btn-warning"><i class="fa fa-home fa-fw"></i> ' . $MULTILANG_IrEscritorio . '</button></div><br>'; } //Carga la ventana con el informe abrir_ventana($Nombre_Aplicacion . ' - ' . $registro_informe["titulo"], 'panel panel-info', $registro_informe["ancho"]); } // Si se ha definido un tamano fijo entonces crea el marco if ($registro_informe["ancho"] != "" && $registro_informe["alto"] != "") { echo '<DIV style="DISPLAY: block; OVERFLOW: auto; POSITION: relative; WIDTH: ' . $registro_informe["ancho"] . '; HEIGHT: ' . $registro_informe["alto"] . '">'; } //Genera enlace al PDF cuando se detecta el modulo y ademas el informe lo tiene activado if (@file_exists("mod/pdf") && $registro_informe["genera_pdf"] == 'S') { echo '<div align=right><a href="tmp/Inf_' . $Identificador_informe . '-' . $PCOSESS_LoginUsuario . '.pdf" target="_BLANK"><i class="fa fa-file-pdf-o"></i> PDF </a></div>'; } // Crea encabezado por tipo de formato: 1=html 2=Excel if ($formato == "htm") { echo ' <html> <body leftmargin="0" topmargin="0" rightmargin="0" bottommargin="0" marginwidth="0" marginheight="0" style="font-size: 12px; font-family: Arial, Verdana, Tahoma;">'; } if ($formato == "xls") { $fecha = date("d-m-Y"); $tituloinforme = trim($registro_informe["titulo"]); $tituloinforme = "Informe"; $nombrearchivo = $tituloinforme . "_" . $fecha; header('Content-type: application/vnd.ms-excel'); header("Content-Disposition: attachment; filename={$nombrearchivo}.xls"); header("Pragma: no-cache"); header("Expires: 0"); } if ($formato == "htm") { //Si el informe va a soportar datatable entonces lo agrega a las tablas que deben ser convertidas en el pageonload if ($registro_informe["soporte_datatable"] == "S") { @($PCO_InformesDataTable .= "TablaInforme_" . $registro_informe["id"] . "|"); } $SalidaFinalInforme .= '<table class="table table-condensed table-hover table-striped table-unbordered ' . $estilo . '" id="TablaInforme_' . $registro_informe["id"] . '"><thead><tr>'; $SalidaFinalInformePDF .= '<table class="' . $estilo . '"><thead><tr>'; } if ($formato == "xls") { $SalidaFinalInforme .= '<table class="font-size: 11px; font-family: Verdana, Tahoma, Arial;"><thead><tr>'; $SalidaFinalInformePDF .= '<table class="font-size: 11px; font-family: Verdana, Tahoma, Arial;"><thead><tr>'; } // Busca si el informe tiene acciones (botones), los cuenta y prepara dentro de un arreglo para repetir en cada registro $consulta_botones = ejecutar_sql("SELECT id," . $ListaCamposSinID_informe_boton . " FROM " . $TablasCore . "informe_boton WHERE informe=? AND visible=1 ORDER BY peso", "{$informe}"); $total_botones = 0; while ($registro_botones = $consulta_botones->fetch()) { //Construye una cadena generica con todos los botones para ser reemplazada luego con valores if ($registro_botones["tipo_accion"] == "interna_eliminar") { $valores = explode(".", $registro_botones["accion_usuario"]); $tabla_vinculada = @$valores[0]; $campo_vinculado = @$valores[1]; //Si solo se indico el campo, sin la tabla, intenta usar solo el campo if ($campo_vinculado == "" && $tabla_vinculada != "") { $campo_vinculado = $valores[0]; $tabla_vinculada = ""; } $comando_javascript = "\r\n\t\t\t\t\t\t\t\t\t\tdocument.FRMBASEINFORME.PCO_Accion.value='eliminar_registro_informe';\r\n\t\t\t\t\t\t\t\t\t\tdocument.FRMBASEINFORME.tabla.value='" . @$tabla_vinculada . "';\r\n\t\t\t\t\t\t\t\t\t\tdocument.FRMBASEINFORME.campo.value='" . @$campo_vinculado . "';\r\n\t\t\t\t\t\t\t\t\t\tdocument.FRMBASEINFORME.valor.value='DELFRMVALVALOR';\r\n\t\t\t\t\t\t\t\t\t\tdocument.FRMBASEINFORME.submit()"; } if ($registro_botones["tipo_accion"] == "interna_cargar") { $comando_javascript = "\r\n document.FRMBASEINFORME.PCO_Accion.value='cargar_objeto';\r\n\t\t\t\t\t\t\t\t\t\tdocument.FRMBASEINFORME.objeto.value='frm:" . $registro_botones["accion_usuario"] . ":DETFRMVALBASE';\r\n\t\t\t\t\t\t\t\t\t\tdocument.FRMBASEINFORME.submit()"; } if ($registro_botones["tipo_accion"] == "externa_formulario") { $comando_javascript = "\r\n\t\t\t\t\t\t\t\t\t\tdocument.FRMBASEINFORME.PCO_Tabla.value='" . @$tabla_vinculada . "';\r\n\t\t\t\t\t\t\t\t\t\tdocument.FRMBASEINFORME.PCO_Campo.value='" . @$campo_vinculado . "';\r\n\t\t\t\t\t\t\t\t\t\tdocument.FRMBASEINFORME.PCO_Valor.value='DELFRMVALVALOR';\r\n document.FRMBASEINFORME.PCO_Accion.value='" . $registro_botones["accion_usuario"] . "';\r\n\t\t\t\t\t\t\t\t\t\tdocument.FRMBASEINFORME.submit()"; } if ($registro_botones["tipo_accion"] == "externa_javascript") { $comando_javascript = $registro_botones["accion_usuario"]; } //Verifica si el registro de botones presenta algun texto de confirmacion y lo antepone al script $cadena_confirmacion_accion_pre = ""; $cadena_confirmacion_accion_pos = ""; if ($registro_botones["confirmacion_texto"] != "") { $cadena_confirmacion_accion_pre = " if (confirm('" . $registro_botones["confirmacion_texto"] . "')) {"; $cadena_confirmacion_accion_pos = " } else {} "; } //Genera la cadena del enlace $cadena_javascript = 'onclick="' . $cadena_confirmacion_accion_pre . ' ' . @$comando_javascript . ' ' . $cadena_confirmacion_accion_pos . ' "'; @($cadena_generica_botones .= '<input type="Button" class="' . $registro_botones["estilo"] . '" value="' . $registro_botones["titulo"] . '" ' . $cadena_javascript . ' > '); $total_botones++; } // Imprime encabezados de columna $resultado_columnas = @ejecutar_sql($consulta); $ConteoColumnas = $resultado_columnas->rowCount(); //Si se tienen registros para mirar las columnas las agrega if ($ConteoColumnas > 0) { $numero_columnas = 0; foreach ($resultado_columnas->fetch(PDO::FETCH_ASSOC) as $key => $val) { //Imprime el encabezado siempre y cuando no se trate de un campo que se desea ocultar if (!in_array($key, $PCO_ColumnasOcultas)) { $SalidaFinalInforme .= '<th>' . $key . '</th>'; $SalidaFinalInformePDF .= '<th>' . $key . '</th>'; } else { //Agrega la columna al indice de columnas ocultas para no mostrarla luego $PCO_NumerosColumnasOcultas[] = $numero_columnas; } $numero_columnas++; } } //Si el informe tiene botones entonces agrega columna adicional if ($total_botones > 0) { $SalidaFinalInforme .= '<th></th>'; $SalidaFinalInformePDF .= '<th></th>'; } $SalidaFinalInforme .= '</tr></thead><tbody>'; $SalidaFinalInformePDF .= '</tr></thead><tbody>'; // Imprime registros del resultado $numero_filas = 0; $consulta_ejecucion = ejecutar_sql($consulta); while ($registro_informe = $consulta_ejecucion->fetch()) { $SalidaFinalInforme .= '<tr>'; $SalidaFinalInformePDF .= '<tr>'; for ($i = 0; $i < $numero_columnas; $i++) { //Muestra la columna solo si no se trata de una de las ocultas if (!in_array($i, $PCO_NumerosColumnasOcultas)) { $SalidaFinalInforme .= '<td>' . $registro_informe[$i] . '</td>'; $SalidaFinalInformePDF .= '<td>' . $registro_informe[$i] . '</td>'; } } //Si el informe tiene botones los agrega if ($total_botones > 0) { //Transforma la cadena generica con los datos especificos del registro, toma por ahora el primer campo $cadena_botones_registro = str_replace("DELFRMVALVALOR", $registro_informe[0], $cadena_generica_botones); $cadena_botones_registro = str_replace("DETFRMVALBASE", $registro_informe[0], $cadena_botones_registro); //Muestra los botones preparados para el registro $SalidaFinalInforme .= '<th>' . $cadena_botones_registro . '</th>'; $SalidaFinalInformePDF .= '<th>' . $cadena_botones_registro . '</th>'; } $SalidaFinalInforme .= '</tr>'; $SalidaFinalInformePDF .= '</tr>'; $numero_filas++; } $SalidaFinalInforme .= '</tbody>'; $SalidaFinalInformePDF .= '</tbody>'; if ($formato == "htm") { //Cuando es embebido (=1) no agrega los totales de registro if (!$embebido) { $SalidaFinalInforme .= '<tfoot> <tr><td colspan=' . $numero_columnas . '> <b>' . $MULTILANG_TotalRegistros . ': </b>' . $numero_filas . ' </td></tr>'; $SalidaFinalInformePDF .= '<tfoot> <tr><td colspan=' . $numero_columnas . '> <b>' . $MULTILANG_TotalRegistros . ': </b>' . $numero_filas . ' </td></tr>'; } echo '</tfoot>'; } $SalidaFinalInforme .= '</table>'; $SalidaFinalInformePDF .= '</table>'; if ($formato == "htm") { echo '</body></html>'; } //Imprime el HTML generado para el informe echo $SalidaFinalInforme; //Genera el PDF cuando se encuentra el modulo y el informe lo tiene activado if (@file_exists("mod/pdf") && $registro_informe["genera_pdf"] == 'S') { require_once 'mod/pdf/html2pdf/html2pdf.class.php'; try { //Define parametros para generar el PDF $IdiomaPDF = $IdiomaPredeterminado; // Acepta solo ca|cs|da|de|en|es|fr|it|nl|pt|tr $OrientacionPDF = 'P'; // P|ortrait L|andscape $TamanoPaginaPDF = 'A4'; // A4|A5|LETTER|LEGAL|100×200...| $MargenPaginaMM = '10'; // Como Entero o arreglo (Izq,Der,Arr,Aba) ej: 10 o array(1, 25, 25, 5) $ModoVistaPDF = 'fullpage'; // fullpage|fullwidth|real|default $FuentePredeterminadaPDF = 'Arial'; // Arial|Courier|Courier-Bold|Courier-BoldOblique|Courier-Oblique|Helvetica|Helvetica-Bold|Helvetica-BoldOblique|Helvetica-Oblique|Symbol|Times-Roman|Times-Bold|Times-BoldItalic|Times-Italic|ZapfDingbats $ContrasenaLecturaPDF = ''; // Si se asigna un valor pedira contrasena para poderlo leer $JavaScriptPDF = ''; // Ej. print(true); // Inicia la generacion del PDF $html2pdf = new HTML2PDF($OrientacionPDF, $TamanoPaginaPDF, $IdiomaPDF, true, 'UTF-8', $MargenPaginaMM); if ($ContrasenaLecturaPDF != "") { $html2pdf->pdf->SetProtection(array('print'), $ContrasenaLecturaPDF); } if ($JavaScriptPDF != "") { $html2pdf->pdf->IncludeJS($JavaScriptPDF); } $html2pdf->pdf->SetDisplayMode($ModoVistaPDF); $html2pdf->setDefaultFont($FuentePredeterminadaPDF); $html2pdf->WriteHTML($SalidaFinalInformePDF); $html2pdf->Output('tmp/Inf_' . $Identificador_informe . '-' . $PCOSESS_LoginUsuario . '.pdf', 'F'); // Antes: $html2pdf->Output('tmp/exemple.pdf'); enviaba salida al navegador directamente } catch (HTML2PDF_exception $e) { echo $e; exit; } } // Si se ha definido un tamano fijo entonces cierra el marco if ($registro_informe["ancho"] != "" && $registro_informe["alto"] != "") { echo '</DIV>'; } } // Fin si informe es T (tabla) //Verifica si es un informe grafico sin dimensiones if ($registro_informe["formato_final"] == "G" && ($registro_informe["ancho"] == "" || $registro_informe["alto"] == "")) { echo '<form name="cancelarXTamano" action="' . $ArchivoCORE . '" method="POST"> <input type="Hidden" name="PCO_Accion" value="Ver_menu"> <input type="Hidden" name="PCO_ErrorTitulo" value="' . $MULTILANG_ErrorDatos . '"> <input type="Hidden" name="PCO_ErrorDescripcion" value="' . $MULTILANG_InfErrTamano . '"> </form> <script type="" language="JavaScript"> document.cancelarXTamano.submit(); </script>'; } // Si el informe tiene formato_final = G (grafico) if ($registro_informe["formato_final"] == "G" && $registro_informe["ancho"] != "" && $registro_informe["alto"] != "") { //Consulta el formato de grafico y datos de series para ponerlo en los campos //Dado por: Tipo|Nombre1!NombreN|Etiqueta1!EtiquetaN|Valor1!ValorN| $formato_base = explode("|", $registro_informe["formato_grafico"]); $tipo_grafico = $formato_base[0]; $lista_nombre_series = explode("!", $formato_base[1]); $lista_etiqueta_series = explode("!", $formato_base[2]); $lista_valor_series = explode("!", $formato_base[3]); //Elimina los nombres de tabla en caso de tener punto y usa los alias si los tiene for ($i = 0; $i < 5; $i++) { //Elimina nombres de tabla encontrando el punto y seleccionando siguiente palabra if (strpos($lista_etiqueta_series[$i], ".")) { $tmp = explode(".", $lista_etiqueta_series[$i]); $lista_etiqueta_series[$i] = $tmp[1]; } if (strpos($lista_valor_series[$i], ".")) { $tmp = explode(".", $lista_valor_series[$i]); $lista_valor_series[$i] = $tmp[1]; } // Prefiere los alias sobre los nombres de campo cuando encuentra un AS if (strpos($lista_etiqueta_series[$i], " AS ")) { $tmp = explode(" AS ", $lista_etiqueta_series[$i]); $lista_etiqueta_series[$i] = $tmp[1]; } if (strpos($lista_valor_series[$i], " AS ")) { $tmp = explode(" AS ", $lista_valor_series[$i]); $lista_valor_series[$i] = $tmp[1]; } } $nombre_serie_1 = $lista_nombre_series[0]; $nombre_serie_2 = $lista_nombre_series[1]; $nombre_serie_3 = $lista_nombre_series[2]; $nombre_serie_4 = $lista_nombre_series[3]; $nombre_serie_5 = $lista_nombre_series[4]; $campo_etiqueta_serie_1 = $lista_etiqueta_series[0]; $campo_etiqueta_serie_2 = $lista_etiqueta_series[1]; $campo_etiqueta_serie_3 = $lista_etiqueta_series[2]; $campo_etiqueta_serie_4 = $lista_etiqueta_series[3]; $campo_etiqueta_serie_5 = $lista_etiqueta_series[4]; $campo_valor_serie_1 = $lista_valor_series[0]; $campo_valor_serie_2 = $lista_valor_series[1]; $campo_valor_serie_3 = $lista_valor_series[2]; $campo_valor_serie_4 = $lista_valor_series[3]; $campo_valor_serie_5 = $lista_valor_series[4]; // Libreria para graficos include "inc/libchart/classes/libchart.php"; //Crea las series para el grafico, dependiendo si es torta (una serie) o cualquier otro (multiples series) if ($tipo_grafico == "torta") { $dataSet = new XYDataSet(); // GENERA DATOS DEL GRAFICO $consulta_ejecucion = ejecutar_sql($consulta); while ($registro = $consulta_ejecucion->fetch()) { if ($nombre_serie_1 != "") { $dataSet->addPoint(new Point($registro[$campo_etiqueta_serie_1], $registro[$campo_valor_serie_1])); } } } else { $dataSet = new XYSeriesDataSet(); if ($nombre_serie_1 != "") { $serie1 = new XYDataSet(); $dataSet->addSerie($nombre_serie_1, $serie1); } if ($nombre_serie_2 != "") { $serie2 = new XYDataSet(); $dataSet->addSerie($nombre_serie_2, $serie2); } if ($nombre_serie_3 != "") { $serie3 = new XYDataSet(); $dataSet->addSerie($nombre_serie_3, $serie3); } if ($nombre_serie_4 != "") { $serie4 = new XYDataSet(); $dataSet->addSerie($nombre_serie_4, $serie4); } if ($nombre_serie_5 != "") { $serie5 = new XYDataSet(); $dataSet->addSerie($nombre_serie_5, $serie5); } // GENERA DATOS DEL GRAFICO $consulta_ejecucion = ejecutar_sql($consulta); while ($registro = $consulta_ejecucion->fetch()) { if ($nombre_serie_1 != "") { $serie1->addPoint(new Point($registro[$campo_etiqueta_serie_1], $registro[$campo_valor_serie_1])); } if ($nombre_serie_2 != "") { $serie2->addPoint(new Point($registro[$campo_etiqueta_serie_2], $registro[$campo_valor_serie_2])); } if ($nombre_serie_3 != "") { $serie3->addPoint(new Point($registro[$campo_etiqueta_serie_3], $registro[$campo_valor_serie_3])); } if ($nombre_serie_4 != "") { $serie4->addPoint(new Point($registro[$campo_etiqueta_serie_4], $registro[$campo_valor_serie_4])); } if ($nombre_serie_5 != "") { $serie5->addPoint(new Point($registro[$campo_etiqueta_serie_5], $registro[$campo_valor_serie_5])); } } } // CREA OBJETO SEGUN TIPO DE GRAFICO if ($tipo_grafico == "linea" || $tipo_grafico == "linea_multiples") { $chart = new LineChart($registro_informe["ancho"], $registro_informe["alto"]); } if ($tipo_grafico == "barrah" || $tipo_grafico == "barrah_multiples") { $chart = new HorizontalBarChart($registro_informe["ancho"], $registro_informe["alto"]); } if ($tipo_grafico == "barrav" || $tipo_grafico == "barrav_multiples") { $chart = new VerticalBarChart($registro_informe["ancho"], $registro_informe["alto"]); } if ($tipo_grafico == "torta") { $chart = new PieChart($registro_informe["ancho"], $registro_informe["alto"]); } // PRESENTA EL GRAFICO EN PANTALLA $chart->setDataSet($dataSet); //$chart->getPlot()->setGraphCaptionRatio(0.75); $chart->setTitle($registro_informe["titulo"]); $chart->render("tmp/Inf_" . $registro_informe["id"] . "-" . $PCOSESS_LoginUsuario . ".png"); echo '<img alt="Grafico" src="tmp/Inf_' . $Identificador_informe . '-' . $PCOSESS_LoginUsuario . '.png" style="border: 1px solid gray;">'; } // Fin si informe es G (grafico) if ($en_ventana) { cerrar_ventana(); } //Si el usuario es admin le muestra el query generador. if (@$PCOSESS_LoginUsuario == "admin" && $ModoDepuracion) { mensaje($MULTILANG_MonCommSQL, $consulta, '', 'fa fa-fw fa-2x fa-database', 'alert alert-info alert-dismissible '); } }
case "4": $chart = new PieChart(ChartWidth, ChartHeight); $chart->getPlot()->setGraphPadding(new Padding("5", "5", "50", "30")); $chart->setTitle("Chiamate per categoria"); $Stats = GetRows("view_call WHERE data_att <= '" . date('Y-m-d') . "' AND id_stato_call = '1'" . " group by categoria", "", "categoria", $db, 1, 'count(id_chiamata) as c_day,concat(categoria, " ", prz) as cat'); $dataSet = new XYDataSet(); foreach ($Stats as $key => $field) { $dataSet->addPoint(new Point("Categoria " . $field['cat'] . " € (" . $field['c_day'] . " chiamate)", $field['c_day'])); } $chart->setDataSet($dataSet); $chart->render(ChartPath); echo '<img src="' . ChartPath . '" alt="chart" />'; break; case "5": $chart = new PieChart(ChartWidth, ChartHeight); $chart->getPlot()->setGraphPadding(new Padding("5", "5", "50", "30")); $chart->setTitle("Chiamate per Provincia"); $Stats = GetRows("view_call WHERE data_att >= '2010-03-01' and data_att <= '2010-03-31" . "' AND id_stato_call = '1' AND id_tecnico = '2' and id_attivita != '45' GROUP BY Targa", "", "Targa", $db, 0, "count(id_chiamata) as tot_prov, Targa"); $dataSet = new XYDataSet(); foreach ($Stats as $key => $field) { $dataSet->addPoint(new Point("Provincia: " . $field['Targa'] . " (" . $field['tot_prov'] . ")", $field['tot_prov'])); } $chart->setDataSet($dataSet); $chart->render(ChartPath); echo '<img src="' . ChartPath . '" alt="chart" />'; break; } ?> </div>
if (count($v) / 2 > 8) { $chart = new PieChart(450, 300); } else { $chart = new PieChart(400, 250); } if (isset($_GET['order'])) { $chart->order = true; } else { $chart->order = false; } $tot = 0; for ($i = 1; $i < count($v); $i += 2) { $tot += $v[$i + 1]; } for ($i = 1; $i < count($v); $i += 2) { $color = null; if ($cor != null) { $r = hexdec(substr($cor[($i - 1) / 2], 0, 2)); $g = hexdec(substr($cor[($i - 1) / 2], 2, 2)); $b = hexdec(substr($cor[($i - 1) / 2], 4, 2)); $color = array($r, $g, $b); } if ($v[$i + 1] > $tot / 100) { $chart->addPoint(new Point($v[$i], $v[$i + 1], $color)); } else { $chart->addPoint(new Point($v[$i], $tot / 100, $color)); } } $chart->setTitle($v[0]); $chart->setLogo($locr . "/images/poweredbyboca.png"); $chart->render();
<h1>Time Analysis : Encrypted Text Searching</h1> <table align="center" cellpadding="10" cellspacing="10" border="1"> <tr> <th>Modules</th> <th>Time (in seconds)</th> </tr> <tr> <td>Untrusted Cloud Search</td> <td>' . $totalTimeUntrustedCloud . '</td> </tr> <tr> <td>Trusted Cloud Search</td> <td>' . $totalTimeTrustedCloud . '</td> </tr> <tr> <th>Total Time</th> <th>' . $totalTime . '</th> </tr> </table> '; $chart = new PieChart(500, 250); $dataSet = new XYDataSet(); $dataSet->addPoint(new Point("Trusted Cloud", $totalTimeTrustedCloud)); $dataSet->addPoint(new Point("Untrusted Cloud", $totalTimeUntrustedCloud)); $chart->setDataSet($dataSet); $chart->setTitle("Graphical Analysis"); $chart->render("generated/textSearch.png"); echo ' <br /><br /> <center><img src="generated/textSearch.png" height="442" width="542" /></center> ';
public function printShockpotGeoData() { $db_query = "SELECT source_ip, COUNT(source_ip) AS count\n FROM connections\n GROUP BY source_ip\n ORDER BY COUNT(source_ip) DESC\n LIMIT 10 "; $rows = R::getAll($db_query); if (count($rows)) { //We create a new vertical bar chart, a new pie chart and initialize the dataset $verticalChart = new VerticalBarChart(600, 300); $pieChart = new PieChart(600, 300); $dataSet = new XYDataSet(); //We create a "intensity" pie chart as well along with a dataset $intensityPieChart = new PieChart(600, 300); $intensityDataSet = new XYDataSet(); //We create a new Google Map and initialize its columns, //where the decoded geolocation data will be entered in the format //of Lat(number), Lon(number) and IP(string) $gMapTop10 = new QMapGoogleGraph(); $gMapTop10->addColumns(array(array('number', 'Lat'), array('number', 'Lon'), array('string', 'IP'))); //We create a new Intensity Map and initialize its columns, //where the decoded geolocation data will be entered in the format //of Country(2 letter string), #Probes(number) $intensityMap = new QIntensitymapGoogleGraph(); $intensityMap->addDrawProperties(array("title" => 'IntensityMap')); $intensityMap->addColumns(array(array('string', '', 'Country'), array('number', '#Probes', 'a'))); //We create a temporary table in the database where we will store the IPs along with their #probes //and the corresponding country code, otherwise the Intensity Map won't work, because we need to //GROUP BY country code and SUM the #Probers per country $temp_table = 'CREATE TEMPORARY TABLE temp_ip (ip TEXT, counter INTEGER, country TEXT)'; R::exec($temp_table); //We create a dummy counter to use for the markers' tooltip inside Google Map like: IP 3/10 //We use the same counter for the IP <table> as well $counter = 1; //We create a skeleton for the table echo '<p>The following table displays the top 10 IP addresses connected to the system (ordered by volume of connections).</p>'; echo '<table><thead>'; echo '<tr class="dark">'; echo '<th>ID</th>'; echo '<th>IP Address</th>'; echo '<th>Probes</th>'; echo '<th>City</th>'; echo '<th>Region</th>'; echo '<th>Country Name</th>'; echo '<th>Code</th>'; echo '<th>Latitude</th>'; echo '<th>Longitude</th>'; echo '<th>Hostname</th>'; echo '<th colspan="9">IP Lookup</th>'; echo '</tr></thead><tbody>'; //We need to add data on the correct Map columns. The columns are always 0 or 1 or 2 for every repetition //so we can hardcode it into our code, but we need a way to automatically increase the row index. So we //create a dummy index variable to be increased after every repetition (as many db results we have) $col = 0; //For every row returned from the database... foreach ($rows as $row) { //We create a new GeoDataObject which geolocates the IP address $geodata = new GeoDataObject($this, $row['source_ip']); //We prepare the label for our vertical bar chart and add the point $label = $row['source_ip'] . " - " . $geodata->countryCode; $dataSet->addPoint(new Point($label, $row['count'])); //We next prepare the marker's tooltip inside Google Map $tooltip = "<strong>TOP {$counter}/10:</strong> " . $row['source_ip'] . "<br />" . "<strong>Probes:</strong> " . $row['count'] . "<br />" . "<strong>City:</strong> " . $geodata->city . "<br />" . "<strong>Region:</strong> " . $geodata->region . "<br />" . "<strong>Country:</strong> " . $geodata->countryName . "<br />" . "<strong>Latitude:</strong> " . $geodata->latitude . "<br />" . "<strong>Longitude:</strong> " . $geodata->longitude . "<br />"; //And add the marker to the map $gMapTop10->setValues(array(array($col, 0, (double) $geodata->latitude), array($col, 1, (double) $geodata->longitude), array($col, 2, $tooltip))); //We prepare the data that will be inserted in our temporary table $ip = $row['source_ip']; $ip_count = $row['count']; $country_code = $geodata->countryCode; $country_query = "INSERT INTO temp_ip VALUES('{$ip}', '{$ip_count}', '{$country_code}')"; R::exec($country_query); //For every row returned from the database we create a new table row with the data as columns echo '<tr class="light">'; echo '<td>' . $counter . '</td>'; echo '<td>' . $row['source_ip'] . '</td>'; echo '<td>' . $row['count'] . '</td>'; echo '<td>' . $geodata->city . '</td>'; echo '<td>' . $geodata->region . '</td>'; echo '<td>' . $geodata->countryName . '</td>'; echo '<td>' . $geodata->countryCode . '</td>'; echo '<td>' . $geodata->latitude . '</td>'; echo '<td>' . $geodata->longitude . '</td>'; echo '<td>' . get_host($row['source_ip']) . '</td>'; echo '<td class="icon"><a href="http://www.dshield.org/ipinfo.html?ip=' . $row['source_ip'] . '" target="_blank"><img class="icon" src="images/dshield.ico"/></a></td>'; echo '<td class="icon"><a href="http://www.ipvoid.com/scan/' . $row['source_ip'] . '" target="_blank"><img class="icon" src="images/ipvoid.ico"/></a></td>'; echo '<td class="icon"><a href="http://www.robtex.com/ip/' . $row['source_ip'] . '.html" target="_blank"><img class="icon" src="images/robtex.ico"/></a></td>'; echo '<td class="icon"><a href="http://www.fortiguard.com/ip_rep/index.php?data=' . $row['source_ip'] . '&lookup=Lookup" target="_blank"><img class="icon" src="images/fortiguard.ico"/></a></td>'; echo '<td class="icon"><a href="http://labs.alienvault.com/labs/index.php/projects/open-source-ip-reputation-portal/information-about-ip/?ip=' . $row['source_ip'] . '" target="_blank"><img class="icon" src="images/alienvault.ico"/></a></td>'; echo '<td class="icon"><a href="http://www.reputationauthority.org/lookup.php?ip=' . $row['source_ip'] . '" target="_blank"><img class="icon" src="images/watchguard.ico"/></a></td>'; echo '<td class="icon"><a href="http://www.mcafee.com/threat-intelligence/ip/default.aspx?ip=' . $row['source_ip'] . '" target="_blank"><img class="icon" src="images/mcafee.ico"/></a></td>'; echo '<td class="icon"><a href="http://www.ip-adress.com/ip_tracer/' . $row['source_ip'] . '" target="_blank"><img class="icon" src="images/ip_tracer.png"/></a></td>'; echo '<td class="icon"><a href="https://www.virustotal.com/en/ip-address/' . $row['source_ip'] . '/information/" target="_blank"><img class="icon" src="images/virustotal.ico"/></a></td>'; echo '</tr>'; //Lastly, we increase the index used by maps to indicate the next row, //and the dummy counter that indicates the next IP index (out of 10) $col++; $counter++; } //Close tbody and table element, it's ready. echo '</tbody></table>'; echo '<hr /><br />'; //While still inside the if(count($rows)) clause (otherwise the dataSet will be empty), //we set the bar chart's dataset, render the graph and display it (we're inside html code!) $verticalChart->setDataSet($dataSet); $verticalChart->setTitle(NUMBER_OF_CONNECTIONS_PER_UNIQUE_IP_CC); //For this particular graph we need to set the corrent padding $verticalChart->getPlot()->setGraphPadding(new Padding(5, 50, 100, 50)); //top, right, bottom, left | defaults: 5, 30, 50, 50 $verticalChart->render("generated-graphs/connections_per_ip_geo.png"); echo '<p>The following vertical bar chart visualizes the top 10 IPs ordered by the number of connections to the system.' . '<br/>Notice the two-letter country code to after each IP get a quick view of the locations where the attacks are coming from.</p>'; echo '<img src="generated-graphs/connections_per_ip_geo.png">'; //We set the pie chart's dataset, render the graph and display it (we're inside html code!) $pieChart->setDataSet($dataSet); $pieChart->setTitle(NUMBER_OF_CONNECTIONS_PER_UNIQUE_IP_CC); $pieChart->render("generated-graphs/connections_per_ip_geo_pie.png"); echo '<p>The following pie chart visualizes the top 10 IPs ordered by the number of connections to the system.' . '<br/>Notice the two-letter country code to after each IP get a quick view of the locations where the attacks are coming from.</p>'; echo '<img src="generated-graphs/connections_per_ip_geo_pie.png">'; echo '<hr /><br />'; //Charts are ready, so is Google Map, let's render it below echo '<p>The following zoomable world map marks the geographic locations of the top 10 IPs according to their latitude and longitude values. ' . 'Click on them to get the full information available from the database.<p>'; //echo '<div align=center>'; echo $gMapTop10->render(); //echo '</div>'; echo '<br/><hr /><br />'; //Lastly, we prepare the data for the Intesity Map $db_query_map = "SELECT country, SUM(counter) AS sum\n FROM temp_ip\n GROUP BY country\n ORDER BY SUM(counter) DESC "; //LIMIT 10 "; $rows = R::getAll($db_query_map); if (count($rows)) { $col = 0; //Dummy row index //For every row returned from the database add the values to Intensity Map's table and intensityPieChart foreach ($rows as $row) { $countryProbes = $row['country'] . " - " . $row['sum']; $intensityDataSet->addPoint(new Point($countryProbes, $row['sum'])); $intensityMap->setValues(array(array($col, 0, (string) $row['country']), array($col, 1, (int) $row['sum']))); $col++; } } //Intensity Map is ready, render it echo '<p>The following Intensity Map shows the volume of attacks per country by summarising probes originating from the same nation, using the same IP or not.</p>'; echo $intensityMap->render(); echo '<br/>'; //We set the "intensity" pie chart's dataset, render the graph and display it (we're inside html code!) $intensityPieChart->setDataSet($intensityDataSet); $intensityPieChart->setTitle(NUMBER_OF_CONNECTIONS_PER_COUNTRY); $intensityPieChart->render("generated-graphs/connections_per_country_pie.png"); echo '<p>The following pie chart visualizes the volume of attacks per country by summarising probes originating from the same nation, using the same IP or not.</p>'; echo '<img src="generated-graphs/connections_per_country_pie.png">'; if (GEO_METHOD == 'LOCAL') { echo '<hr /><small><a href="http://www.maxmind.com">http://www.maxmind.com</a></small><br />'; } else { if (GEO_METHOD == 'GEOPLUGIN') { echo '<hr /><small><a href="http://www.geoplugin.com/geolocation/" target="_new">IP Geolocation</a> by <a href="http://www.geoplugin.com/" target="_new">geoPlugin</a></small><br />'; } else { //TODO } } } //END IF }
public function createNumberOfConnectionsPerIP() { $db_query = "SELECT source_ip, COUNT(source_ip) AS count\n FROM connections\n GROUP BY source_ip\n ORDER BY COUNT(source_ip) DESC\n LIMIT 10 "; $rows = R::getAll($db_query); if (count($rows)) { //We create a new vertical bar chart,a new pie chart and initialize the dataset $chart = new VerticalBarChart(600, 300); $pie_chart = new PieChart(600, 300); $dataSet = new XYDataSet(); //For every row returned from the database we add a new point to the dataset foreach ($rows as $row) { $dataSet->addPoint(new Point($row['source_ip'], $row['count'])); } //We set the bar chart's dataset and render the graph $chart->setDataSet($dataSet); $chart->setTitle(NUMBER_OF_CONNECTIONS_PER_UNIQUE_IP); //For this particular graph we need to set the corrent padding $chart->getPlot()->setGraphPadding(new Padding(5, 40, 75, 50)); //top, right, bottom, left | defaults: 5, 30, 50, 50 $chart->render("generated-graphs/connections_per_ip.png"); //We set the pie chart's dataset and render the graph $pie_chart->setDataSet($dataSet); $pie_chart->setTitle(NUMBER_OF_CONNECTIONS_PER_UNIQUE_IP); $pie_chart->render("generated-graphs/connections_per_ip_pie.png"); } }
//type of chart, pie, vertical bar, horizontal, etc. $type = isset($_GET['type']) ? $_GET['type'] : '1'; $chartType = isset($_GET['chart']) ? $_GET['chart'] : '1'; $user = isset($_GET['user']) ? $_GET['user'] : $_SESSION['USER_LOGGED']; $chartsObj = new chartsClass(); //$chart = new PieChart(450,300); switch ($type) { case '1': $chart = new VerticalBarChart(430, 280); break; case '2': $chart = new HorizontalBarChart(430, 200); break; case '3': $chart = new LineChart(430, 280); break; case '4': $chart = new PieChart(430, 200); break; } switch ($chartType) { case '1': $dataSet = $chartsObj->getDatasetCasesByStatus(); break; default: $dataSet = $chartsObj->getDatasetCasesByProcess(); break; } $chart->setDataSet($dataSet); $chart->setTitle("Cases list"); $chart->render();
$gethari3 = gethari("3"); $gethari4 = gethari("4"); $gethari5 = gethari("5"); $gethari6 = gethari("6"); $gethari0 = gethari("0"); $chart4 = new PieChart(400); $dataSet4 = new XYDataSet(); $dataSet4->addPoint(new Point("Senin ({$gethari1})", $gethari1)); $dataSet4->addPoint(new Point("Selasa ({$gethari2})", $gethari2)); $dataSet4->addPoint(new Point("Rabu ({$gethari3})", $gethari3)); $dataSet4->addPoint(new Point("Kamis ({$gethari4})", $gethari4)); $dataSet4->addPoint(new Point("Jumat ({$gethari5})", $gethari5)); $dataSet4->addPoint(new Point("Sabtu ({$gethari6})", $gethari6)); $dataSet4->addPoint(new Point("Minggu ({$gethari0})", $gethari0)); $chart4->setDataSet($dataSet4); $chart4->setTitle("Berdasarkan Hari"); $chart4->render("hari.png"); /********************************************************/ $chart5 = new VerticalBarChart(900, 300); $serie1 = new XYDataSet(); $query5 = "SELECT dateflag,count(distinct(ip)) AS kunjungan FROM statistiksitus WHERE dateflag BETWEEN '{$_POST['DariTanggal']}' AND '{$_POST['SampaiTanggal']}'group by dateflag asc"; $hasil5 = mysql_query($query5); while ($data5 = mysql_fetch_assoc($hasil5)) { $kunjungan = $data5['kunjungan']; $date = $data5['dateflag']; $bulan = substr($date, 5, 2); $tgl = substr($date, 8, 2); $dateflag = $tgl . '-' . $bulan; $serie1->addPoint(new Point("{$dateflag}", $kunjungan)); } $serie2 = new XYDataSet();
<div id="search-result"> <?php require_once "{$root}/Function/libchart/classes/libchart.php"; $Stati = $d->GetRows("*", "tab_stato_call", "", "", "stato_call"); //Padding::Padding ($top, $right, $bottom, $left) define("ChartPath", "tmp/chart.png"); define("ChartWidth", 1000); define("ChartHeight", 400); $chart = new PieChart(ChartWidth, ChartHeight); $chart->getPlot()->setGraphPadding(new Padding("5", "5", "5", "5")); $chart->setTitle("Stato rollout filiali Unicredit - Sicilia"); $dataSet = new XYDataSet(); foreach ($Stati as $key => $field) { $stat = $d->GetRows("count(id_filiale) as count", "tab_filiali", "id_stato = '" . $field['id_stato_call'] . "'"); /* echo "[Debug]: count stato: ".$stat[0]['count']." <br />"; */ $dataSet->addPoint(new Point($field['stato_call'] . " ( " . $stat[0]['count'] . " )", $stat[0]['count'])); } $chart->setDataSet($dataSet); $chart->render(ChartPath); ?> <img src="<?php echo ChartPath; ?> " alt="chart" /> </div>
$chart->render("generated/kelamin.png"); $chart2 = new PieChart(); $dataSet2 = new XYDataSet(); $totala = $koneksi_db->sql_query("SELECT * FROM hrd_karyawan where status='3'"); $jumlaha = $koneksi_db->sql_numrows($totala); $totala2 = $koneksi_db->sql_query("SELECT * FROM hrd_karyawan where status='4'"); $jumlaha2 = $koneksi_db->sql_numrows($totala2); $totala3 = $koneksi_db->sql_query("SELECT * FROM hrd_karyawan where status='5'"); $jumlaha3 = $koneksi_db->sql_numrows($totala3); $totala4 = $koneksi_db->sql_query("SELECT * FROM hrd_karyawan where status='6'"); $dataSet2->addPoint(new Point("Tetap ({$jumlaha})", $jumlaha)); $dataSet2->addPoint(new Point("Honorer ({$jumlaha2})", $jumlaha2)); $dataSet2->addPoint(new Point("Kontrak ({$jumlaha3})", $jumlaha3)); $dataSet2->addPoint(new Point("Magang ({$jumlaha4})", $jumlaha4)); $chart2->setDataSet($dataSet2); $chart2->setTitle("Status Karyawan"); $chart2->render("generated/status.png"); /////////////////////////// if (!defined('AURACMS_CONTENT')) { Header("Location: ../index.php"); exit; } global $koneksi_db; $style_include[] = ' <style type="text/css"> /*<![CDATA[*/ .box{ padding: 20px; display: none; margin-top: 20px; }
public function pieChartHamSpam($emails = '', $timespan, $title, $output) { $ham = $spam = 0; $range = $this->getRangeInSeconds($timespan); $chart = new PieChart(SIZE_X, SIZE_Y); $query = $this->db->query("SELECT COUNT(*) AS SPAM FROM " . TABLE_META . " WHERE {$emails} AND arrived > {$range}"); if ($query->num_rows > 0) { $spam = $query->row['SPAM']; } $query = $this->db->query("SELECT COUNT(*) AS HAM FROM " . TABLE_META . " WHERE {$emails} AND arrived > {$range}"); if ($query->num_rows > 0) { $ham = $query->row['HAM']; } if ($ham > $spam) { $chart->getPlot()->getPalette()->setPieColor(array(new Color(26, 192, 144), new Color(208, 48, 128))); } else { $chart->getPlot()->getPalette()->setPieColor(array(new Color(208, 48, 128), new Color(26, 192, 144))); } $dataSet = new XYDataSet(); $dataSet->addPoint(new Point("HAM ({$ham})", $ham)); $dataSet->addPoint(new Point("SPAM ({$spam})", $spam)); $chart->setDataSet($dataSet); $chart->setTitle($title); $this->sendOutput($chart, $output); }
* GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /** * Pie chart demonstration * */ include "../../../COCONUT/libchart/libchart/classes/libchart.php"; $chart = new PieChart(); $ro = new database1(); $dataSet = new XYDataSet(); $dataSet->addPoint(new Point("OPD (" . number_format($ro->getPxRevenueDaily_opd($fromMonth, $fromDay, $fromYear), 2) . ")", $ro->getPxRevenueDaily_opd($fromMonth, $fromDay, $fromYear))); $dataSet->addPoint(new Point("IPD (" . number_format($ro->getPxRevenueDaily_ipd($fromMonth, $fromDay, $fromYear), 2) . ")", $ro->getPxRevenueDaily_ipd($fromMonth, $fromDay, $fromYear))); $chart->setDataSet($dataSet); $chart->setTitle("Collection Report For {$fromMonth} {$fromDay}, {$fromYear} "); $chart->render("../../../COCONUT/graphicalReport/chartList/dailyRevenue.png"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" /> </head> <body> <img alt="Pie chart" src="/COCONUT/graphicalReport/chartList/dailyRevenue.png" style="border: 1px solid gray;"/> </body> </html>
if (count($rows)) { //We create a new vertical bar chart,a new pie chart and initialize the dataset $chart = new VerticalBarChart(600, 300); $pie_chart = new PieChart(600, 300); $dataSet = new XYDataSet(); //For every row returned from the database we add a new point to the dataset foreach ($rows as $row) { $dataSet->addPoint(new Point($row['dest_port'] . " / " . $row['proto'], $row['COUNT(dest_port)'])); } //We set the bar chart's dataset and render the graph $chart->setDataSet($dataSet); $chart->setTitle("Number of connections by destination port"); $chart->render("generated-graphs/connections_by_dest_port.png"); //We set the pie chart's dataset and render the graph $pie_chart->setDataSet($dataSet); $pie_chart->setTitle("Number of connections by destination port"); $pie_chart->render("generated-graphs/connections_by_dest_port_pie.png"); } //----------------------------------------------------------------------------------------------------------------- //MOST CONNECTIONS PER DAY //----------------------------------------------------------------------------------------------------------------- $db_query = "SELECT COUNT(*), date_time\n FROM connections\n GROUP BY DAYOFYEAR(date_time)\n ORDER BY COUNT(*) DESC\n LIMIT 20 "; $rows = R::getAll($db_query); if (count($rows)) { //We create a new horizontal bar chart and initialize the dataset $chart = new HorizontalBarChart(600, 300); $dataSet = new XYDataSet(); //For every row returned from the database we add a new point to the dataset foreach ($rows as $row) { $dataSet->addPoint(new Point(date('d-m-Y', strtotime($row['date_time'])), $row['COUNT(*)'])); }
* You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /** * Pie chart demonstration * */ include "../../../COCONUT/libchart/libchart/classes/libchart.php"; $chart = new PieChart(); $ro = new database1(); $dataSet = new XYDataSet(); $dataSet->addPoint(new Point("IPD FEMALE (" . $ro->getGenderDaily($fromMonth, $fromDay, $fromYear, "female", "IPD") . ")", $ro->getGenderDaily($fromMonth, $fromDay, $fromYear, "female", "IPD"))); $dataSet->addPoint(new Point("IPD MALE (" . $ro->getGenderDaily($fromMonth, $fromDay, $fromYear, "male", "IPD") . ")", $ro->getGenderDaily($fromMonth, $fromDay, $fromYear, "male", "IPD"))); $dataSet->addPoint(new Point("OPD FEMALE (" . $ro->getGenderDaily($fromMonth, $fromDay, $fromYear, "female", "OPD") . ")", $ro->getGenderDaily($fromMonth, $fromDay, $fromYear, "female", "OPD"))); $dataSet->addPoint(new Point("OPD MALE (" . $ro->getGenderDaily($fromMonth, $fromDay, $fromYear, "male", "OPD") . ")", $ro->getGenderDaily($fromMonth, $fromDay, $fromYear, "male", "OPD"))); $chart->setDataSet($dataSet); $chart->setTitle("Gender Census {$fromMonth} {$fromDay}, {$fromYear} "); $chart->render("../../../COCONUT/graphicalReport/chartList/genderCensus.png"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" /> </head> <body> <img alt="Pie chart" src="/COCONUT/graphicalReport/chartList/genderCensus.png" style="border: 1px solid gray;"/> </body> </html>
$dataSet->addPoint(new Point("Opera (50)", 50)); $dataSet->addPoint(new Point("Safari (37)", 37)); $dataSet->addPoint(new Point("Dillo (37)", 37)); $dataSet->addPoint(new Point("Other (72)", 70)); $chart->setDataSet($dataSet); $chart->setTitle("User agents for www.example.com"); $chart->render("generated/demo3.png"); $chart2 = new PieChart(); $dataSet2 = new XYDataSet(); $dataSet2->addPoint(new Point("Mozilla (10)", 10)); $dataSet2->addPoint(new Point("Konqror (75)", 75)); $dataSet2->addPoint(new Point("Opa (50)", 50)); $dataSet2->addPoint(new Point("Saf (37)", 37)); $dataSet2->addPoint(new Point("Dilo (37)", 37)); $dataSet2->addPoint(new Point("Oter (72)", 70)); $chart2->setDataSet($dataSet2); $chart2->setTitle("User agents for www.example.com"); $chart2->render("generated/demo4.png"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Libchart pie chart demonstration</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" /> </head> <body> <img alt="Pie chart" src="generated/demo3.png" style="border: 1px solid gray;"/> <img alt="Pie chart" src="generated/demo4.png" style="border: 1px solid gray;"/> </body> </html>
// assume year has always 4 digits // e.g. 2005 $curTimestamp = substr($curTimestamp, 0, 4); // $curTimestamp is oldest year, if $oldestYear is not set if (strlen($oldestYear) === 0) { $oldestYear = $curTimestamp; } if (!isset($matches[$curTimestamp]['year'])) { $matches[$curTimestamp]['year'] = $curTimestamp; } if (strcmp($curTimestamp, $oldTimestamp) === 0) { // if we are still in the same month: 1 more match in the month $matches[$curTimestamp]['matches']++; } else { // otherwise initialise with 1 (at least one match at that month) $matches[$curTimestamp]['matches'] = '1'; } // done with this month $oldTimestamp = $curTimestamp; } $chart = new PieChart(450, 250); $dataSet = new XYDataSet(); $chart->getPlot()->setGraphPadding(new Padding(0, 15, 15, 50)); // add a data point for each month foreach ($matches as $matchesPerYear) { $dataSet->addPoint(new Point($matchesPerYear['year'], $matchesPerYear['matches'])); } $chart->setDataSet($dataSet); $chart->setTitle('Official GU Matches [ ' . $oldestYear . ' - ' . date('Y') . ' ]'); // FIXME: Where should the graph be saved? $chart->render(dirname(__FILE__) . '/img/yearPie.png');
/** * Display a nice graph from data * * @param type Type of data. * @param sort Field */ function renderGraph($machines, $type, $sort, $filter) { $id = "{$type} {$sort}"; $chart = new PieChart(770, 340); $dataSet = new XYDataSet(); $div = 1; $mod = 0; $suffix = ""; switch ($id) { case "BootGeneral TotalMem": $div = 1024; $mod = 64; $suffix = " MB"; break; case "BootGeneral Freq": $div = 1; $mod = 200; $suffix = " Mhz"; break; case "BootDisk Capacity": $div = 1000; $mod = 20; $suffix = " GB"; break; case "Memory Size": $div = 1024; $mod = 0; $suffix = " MB"; break; } $data = array(); foreach ($machines as $machine) { foreach ($machine[1] as $inv) { // filter data in ranges if ($div != 1) { $inv /= $div; $inv = round($inv); } if ($mod) { $inv /= $mod; $inv = round($inv); $inv *= $mod; if ($inv != 0) { $inv = $d - $mod + 1 . "-" . $inv; } } if ($suffix != "") { $inv = $inv . $suffix; } $data[$inv] += 1; } } // For each data count the occurence foreach ($data as $key => $value) { $dataSet->addPoint(new Point("{$key} ({$value})", $value)); } $chart->setDataSet($dataSet); $chart->setTitle(ucfirst($sort)); header("Content-type: image/png"); @$chart->render(); exit; }
<?php include "header.php"; include "/libchart/libchart/classes/libchart.php"; require_once "dbconnect/dbconnect.php"; opendb(); //Menentukan batas, cek halaman dan posisi data $count = arraydb(querydb("\n\t\t\tselect * from (\n\n\t\t\t(select count(*) as nlaptop from alat natural join peminjaman \n\n\t\t\twhere lower(kategori)='laptop') a\n\n\t\t\tjoin\n\n\t\t\t(select count(*) as nsound from alat natural join peminjaman \n\n\t\t\twhere lower(kategori)='sound') as b\n\n\t\t\tjoin\n\n\t\t\t(select count(*) as nproyektor from alat natural join peminjaman \n\n\t\t\twhere lower(kategori)='proyektor') as c\n\n\t\t\tjoin\n\n\t\t\t(select count(*) as nlain from alat natural join peminjaman) as d\n\t\t\t)\t\t\t\t\t\t\n\t\t\t")); $chart = new PieChart(); $nlain = $count['nlain'] - $count['nlaptop'] - $count['nproyektor'] - $count['nsound']; $dataSet = new XYDataSet(); $dataSet->addPoint(new Point("Sound (" . $count['nsound'] . ")", $count['nsound'])); $dataSet->addPoint(new Point("Proyektor (" . $count['nproyektor'] . ")", $count['nproyektor'])); $dataSet->addPoint(new Point("Laptop (" . $count['nlaptop'] . ")", $count['nlaptop'])); $dataSet->addPoint(new Point("Misc (" . $nlain . ")", $nlain)); $chart->setDataSet($dataSet); $chart->setTitle("Statistik Umum Peminjaman Barang"); $chart->render("generated/Peminjaman.png"); ?> <center><img alt="Pie chart" src="generated/Peminjaman.png" style="border: 1px solid gray;"/></center> <script> $('li:disabled').prop('disabled',true); </script> <?php include "footer.php";