function drawChart($title, $DataSet, $names, $colors, $legend = false) { // Initialise the graph $Chart = new pChart(1300, 750); $Chart->setFontProperties("Fonts/tahoma.ttf", 8); $Chart->setGraphArea(50, 25, 1200, 725); $Chart->drawGraphArea(255, 255, 255, TRUE); $Chart->drawXYScale($DataSet->GetData(), $DataSet->GetDataDescription(), "ally", "allx", 150, 150, 150, TRUE, 45); $Chart->setLineStyle(4); // Draw the 0 line $Chart->setFontProperties("Fonts/tahoma.ttf", 6); $Chart->drawTreshold(0, 143, 55, 72, TRUE, TRUE); foreach ($colors as $idx => $color) { $Chart->setColorPalette($idx, $color[0], $color[1], $color[2]); } $i = 0; foreach ($names as $name) { $Chart->drawXYGraph($DataSet->GetData(), $DataSet->GetDataDescription(), $name . "y", $name . "x", $i); $i++; } if ($legend) { $Chart->drawLegend(465, 40, $DataSet->GetDataDescription(), 255, 255, 255); } // Finish the graph $Chart->setFontProperties("Fonts/tahoma.ttf", 10); // $Chart->drawTitle(60,22,$title,50,50,50,530); $Chart->Stroke(); }
// Standard inclusions include "pChart/pData.class"; include "pChart/pChart.class"; // Dataset definition $DataSet = new pData(); $DataSet->AddPoint(array(1, 4, 3, 2, 3, 3, 2, 1, 0, 7, 4, 3, 2, 3, 3, 5, 1, 0, 7), "Serie1"); $DataSet->AddPoint(array(1, 4, 2, 6, 2, 3, 0, 1, 5, 1, 2, 4, 5, 2, 1, 0, 6, 4, 2), "Serie2"); $DataSet->AddAllSeries(); $DataSet->SetAbsciseLabelSerie(); $DataSet->SetSerieName("January", "Serie1"); $DataSet->SetSerieName("February", "Serie2"); // Initialise the graph $Test = new pChart(700, 230); $Test->setFontProperties("Fonts/tahoma.ttf", 8); $Test->setGraphArea(50, 30, 585, 200); $Test->drawFilledRoundedRectangle(7, 7, 693, 223, 5, 240, 240, 240); $Test->drawRoundedRectangle(5, 5, 695, 225, 5, 230, 230, 230); $Test->drawGraphArea(255, 255, 255, TRUE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2); $Test->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line $Test->setFontProperties("Fonts/tahoma.ttf", 6); $Test->drawTreshold(0, 143, 55, 72, TRUE, TRUE); // Draw the cubic curve graph $Test->drawFilledCubicCurve($DataSet->GetData(), $DataSet->GetDataDescription(), 0.1, 50); // Finish the graph $Test->setFontProperties("Fonts/tahoma.ttf", 8); $Test->drawLegend(600, 30, $DataSet->GetDataDescription(), 255, 255, 255); $Test->setFontProperties("Fonts/tahoma.ttf", 10); $Test->drawTitle(50, 22, "Example 7", 50, 50, 50, 585); $Test->Render("example7.png");
/** * Рисует график по переданным данным * * @param array $points * @return string путь к файлу графика */ private function draw(array $points) { $errLevel = error_reporting(); error_reporting(0); $newsList = $this->dataProvider->getNewsList(); $classLoader = new CPChart(); $DataSet = new pData(); foreach ($points as $news_id => $set) { $DataSet->AddPoint($set, "news" . $news_id); $DataSet->SetSerieName($newsList[$news_id], "news" . $news_id); } $DataSet->AddAllSeries(); $DataSet->AddPoint(array_values($this->dataProvider->getDates()), "dates"); $DataSet->SetAbsciseLabelSerie('dates'); // Initialise the graph $chart = new pChart(700, 250); $chart->setFontProperties($classLoader->Cpath("Fonts/tahoma.ttf"), 7); $chart->setGraphArea(60, 30, 570, 200); $chart->drawFilledRoundedRectangle(7, 7, 693, 253, 5, 240, 240, 240); $chart->drawRoundedRectangle(5, 5, 695, 255, 5, 230, 230, 230); $chart->drawGraphArea(255, 255, 255, true); $data = $DataSet->GetData(); if (!empty($data)) { $chart->drawScale($data, $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, true, 45, 2, true, 3); $chart->drawGrid(4, true, 230, 230, 230, 50); $chart->drawCubicCurve($DataSet->GetData(), $DataSet->GetDataDescription()); // Finish the graph $chart->setFontProperties($classLoader->Cpath("Fonts/tahoma.ttf"), 8); $chart->drawLegend(590, 20, $DataSet->GetDataDescription(), 255, 255, 255); } // Restore reporting level error_reporting($errLevel); return $this->render($chart, $points); }
public function _showGraph_pChart($buscarBarra) { // Dataset definition $DataSet = new pData(); if ($buscarBarra == "semana") { $semana = array("1era Semana", "2da Semana", "3era Semana", "4ta Semana"); $cantidadSemanal = array(2, 4, 5, 6); $DataSet->AddPoint($semana, "Serie1"); $DataSet->AddPoint($cantidadSemanal, "Serie2"); // Initialise the graph define("WIDTH", 500); define("HEIGHT", 500); $Test = new pChart(WIDTH, HEIGHT); $Test->setFontProperties("../font/arial.ttf", 7); $Test->setGraphArea(40, 30, WIDTH - 30, HEIGHT - 30); $Test->drawFilledRoundedRectangle(7, 7, WIDTH - 7, HEIGHT - 7, 5, 240, 240, 240); $Test->drawRoundedRectangle(5, 5, WIDTH - 5, HEIGHT - 5, 5, 230, 230, 230); } elseif ($buscarBarra == "mes") { $mensual = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Setiembre", "Octubre"); $cantidadMensual = array(4, 6, 11, 23, 9, 2, 30, 20, 12, 45); $DataSet->AddPoint($mensual, "Serie1"); $DataSet->AddPoint($cantidadMensual, "Serie2"); // Initialise the graph define("WIDTH", 700); define("HEIGHT", 500); $Test = new pChart(WIDTH, HEIGHT); $Test->setFontProperties("../font/arial.ttf", 7); $Test->setGraphArea(40, 30, WIDTH - 30, HEIGHT - 30); $Test->drawFilledRoundedRectangle(7, 7, WIDTH - 7, HEIGHT - 7, 5, 240, 240, 240); $Test->drawRoundedRectangle(5, 5, WIDTH - 5, HEIGHT - 5, 5, 230, 230, 230); $Test->setColorPalette(0, 224, 100, 46); } $DataSet->AddAllSeries(); $DataSet->RemoveSerie("Serie1"); $DataSet->SetAbsciseLabelSerie("Serie1"); $DataSet->SetSerieName("Productos Comprados", "Serie2"); // Initialise the graph $Test->drawGraphArea(255, 255, 255, TRUE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_START0, 150, 150, 150, TRUE, 0, 2, TRUE); $Test->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line $Test->setFontProperties("../font/arial.ttf", 6); $Test->drawTreshold(0, 143, 55, 72, TRUE, TRUE); // Draw the bar graph $Test->drawStackedBarGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 70); // Set labels $Test->setFontProperties("../font/arial.ttf", 7); $Test->writeValues($DataSet->GetData(), $DataSet->GetDataDescription(), "Serie2"); // Finish the graph $Test->setFontProperties("../font/arial.ttf", 8); $Test->drawLegend(WIDTH / 5, 25, $DataSet->GetDataDescription(), 255, 255, 255); $Test->setFontProperties("../font/arial.ttf", 10); $Test->drawTitle(WIDTH - 200, 22, "Estadistica de Barra de Grafico", 50, 50, 50, 185); $Test->Render("../img/imagenBarra_pChart.png"); }
function drawChart($title, $DataSet, $type, $colors, $legend = false) { // Initialise the graph $Chart = new pChart(1300, 700); $Chart->setFontProperties("Fonts/tahoma.ttf", 8); $Chart->setGraphArea(50, 50, 1200, 600); $Chart->drawGraphArea(255, 255, 255, TRUE); $Chart->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 0, TRUE); // Draw the 0 line $Chart->setFontProperties("Fonts/tahoma.ttf", 6); $Chart->drawTreshold(0, 143, 55, 72, TRUE, TRUE); foreach ($colors as $idx => $color) { $Chart->setColorPalette($idx, $color[0], $color[1], $color[2]); } if ($type == "bar") { $Chart->drawBarGraph($DataSet->GetData(), $DataSet->GetDataDescription()); } else { if ($type == "line") { $Chart->drawLineGraph($DataSet->GetData(), $DataSet->GetDataDescription()); } } if ($legend) { $Chart->drawLegend(465, 40, $DataSet->GetDataDescription(), 255, 255, 255); } // Finish the graph $Chart->setFontProperties("Fonts/tahoma.ttf", 10); $Chart->drawTitle(60, 22, $title, 50, 50, 50, 530); $Chart->Stroke(); }
/** * Генерация графика * @param DataSet $DataSet * @param String $GraphTitle * @param String $safeToFile */ function createGraphToFile($DataSet, $GraphTitle, $safeToFile, $scaleFormat) { // Rotrate $rotate = 30; // Initialise the graph $GraphImage = new pChart(594, 344); $GraphImage->setDateFormat($scaleFormat); // $GraphImage->loadColorPalette(DIR_FONT.'/tones-3.txt'); $GraphImage->setFontProperties(DIR_FONT . "/segoepr.ttf", 8); $GraphImage->setGraphArea(80, 50, 580, 300); $GraphImage->drawFilledRectangle(3, 3, 590, 340, 240, 240, 240); $GraphImage->drawRectangle(0, 0, 593, 343, 230, 230, 230); $GraphImage->drawGraphArea(255, 255, 255, TRUE); $GraphImage->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_START0, 150, 150, 150, TRUE, $rotate, 0, FALSE); $GraphImage->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line $GraphImage->setFontProperties(DIR_FONT . "/segoepr.ttf", 6); $GraphImage->drawTreshold(0, 143, 55, 72, TRUE, TRUE); // Просто пунктирная линия // Draw the cubic curve graph $GraphImage->drawCubicCurve($DataSet->GetData(), $DataSet->GetDataDescription()); // Draw the line graph //$GraphImage->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription()); $GraphImage->drawPlotGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 3, 2, 255, 255, 255); // Finish the graph $GraphImage->setFontProperties(DIR_FONT . "/segoepr.ttf", 12); $GraphImage->drawTitle(60, 32, $GraphTitle, 50, 50, 50, 600); //$GraphImage->Render(DIR_CACHE . './' . $safeToFile . '.png'); $GraphImage->Stroke(); }
function generateGraph($year, $month, $quarter, $biAnn, $dev, $patna, $duration, $from, $to) { $myarr = graphTests($year, $month, $quarter, $biAnn, $dev, $patna, $duration, $from, $to); $myarr1 = graphErrs($year, $month, $quarter, $biAnn, $dev, $patna, $duration, $from, $to); $myarr2 = graphLbls($year, $month, $quarter, $biAnn, $dev, $patna, $duration, $from, $to); // Standard inclusions include "pChart/pChart/pData.class"; include "pChart/pChart/pChart.class"; // Dataset definition $DataSet = new pData(); $DataSet->AddPoint($myarr, "Serie1"); $DataSet->AddPoint($myarr1, "Serie2"); $DataSet->AddPoint($myarr2, "Serie3"); $DataSet->AddSerie("Serie1"); $DataSet->AddSerie("Serie2"); $DataSet->SetAbsciseLabelSerie("Serie3"); $DataSet->SetSerieName("Test Resulting trends", "Serie1"); $DataSet->SetSerieName("Errors in tests", "Serie2"); $DataSet->SetYAxisName("Tests"); // $DataSet->SetYAxisFormat("time"); $DataSet->SetXAxisName("months"); // Initialise the graph $Test = new pChart(750, 330); $Test->setFontProperties("Fonts/tahoma.ttf", 8); $Test->setGraphArea(85, 30, 650, 200); $Test->drawFilledRoundedRectangle(7, 7, 693, 223, 5, 240, 240, 240); $Test->drawRoundedRectangle(5, 5, 695, 225, 5, 230, 230, 230); $Test->drawGraphArea(255, 255, 255, TRUE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2); $Test->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line $Test->setFontProperties("Fonts/tahoma.ttf", 6); $Test->drawTreshold(0, 143, 55, 72, TRUE, TRUE); // Draw the line graph $Test->drawLineGraph($DataSet->GetData(), $DataSet->GetDataDescription()); $Test->drawPlotGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 3, 2, 255, 255, 255); // Finish the graph $Test->setFontProperties("Fonts/tahoma.ttf", 8); $Test->drawLegend(90, 35, $DataSet->GetDataDescription(), 255, 255, 255); $Test->setFontProperties("Fonts/tahoma.ttf", 10); $Test->drawTitle(60, 22, "Test Summary", 50, 50, 50, 585); $Test->Render("mpdf.png"); }
$DataSet->AddPoint(array(9, 9, 9, 10, 10, 11, 12, 14, 16, 17, 18, 18, 19, 19, 18, 15, 12, 10, 9), "Serie1"); $DataSet->AddPoint(array(10, 11, 11, 12, 12, 13, 14, 15, 17, 19, 22, 24, 23, 23, 22, 20, 18, 16, 14), "Serie2"); $DataSet->AddPoint(array(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22), "Serie3"); $DataSet->AddAllSeries(); $DataSet->RemoveSerie("Serie3"); $DataSet->SetAbsciseLabelSerie("Serie3"); $DataSet->SetSerieName("January", "Serie1"); $DataSet->SetSerieName("February", "Serie2"); $DataSet->SetYAxisName("Temperature"); $DataSet->SetYAxisUnit("°C"); $DataSet->SetXAxisUnit("h"); // Initialise the graph $Test = new pChart(700, 230); $Test->drawGraphAreaGradient(132, 173, 131, 50, TARGET_BACKGROUND); $Test->setFontProperties("../Fonts/tahoma.ttf", 8); $Test->setGraphArea(120, 20, 675, 190); $Test->drawGraphArea(213, 217, 221, FALSE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_ADDALL, 213, 217, 221, TRUE, 0, 2, TRUE); $Test->drawGraphAreaGradient(163, 203, 167, 50); $Test->drawGrid(4, TRUE, 230, 230, 230, 20); // Draw the bar chart $Test->drawStackedBarGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 70); // Draw the title $Title = " Average Temperatures during\r\n the first months of 2008 "; $Test->drawTextBox(0, 0, 50, 230, $Title, 90, 255, 255, 255, ALIGN_BOTTOM_CENTER, TRUE, 0, 0, 0, 30); // Draw the legend $Test->setFontProperties("../Fonts/tahoma.ttf", 8); $Test->drawLegend(610, 10, $DataSet->GetDataDescription(), 236, 238, 240, 52, 58, 82); // Render the picture $Test->addBorder(2); $Test->Render("example23.png");
function makeGraph($values, $labels) { $values[] = '0'; $labels[] = ''; // Standard inclusions include_once "charts/pChart.class"; include_once "charts/pData.class"; // Dataset definition $DataSet = new pData(); $DataSet->AddPoint($values, "Serie2"); $DataSet->AddPoint($labels, "Xlabel"); $DataSet->AddSerie("Serie2"); $DataSet->SetAbsciseLabelSerie('Xlabel'); $DataSet->SetSerieName("No Of Births", "Serie2"); // Initialise the graph $Test = new pChart(700, 230); $Test->setFontProperties("Fonts/tahoma.ttf", 8); $Test->setGraphArea(50, 30, 585, 200); $Test->drawFilledRoundedRectangle(7, 7, 693, 223, 5, 240, 240, 240); $Test->drawRoundedRectangle(5, 5, 695, 225, 5, 230, 230, 230); $Test->drawGraphArea(255, 255, 255, TRUE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2, TRUE); $Test->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line $Test->setFontProperties("Fonts/tahoma.ttf", 6); $Test->drawTreshold(0, 143, 55, 72, TRUE, TRUE); // Draw the bar graph $Test->drawOverlayBarGraph($DataSet->GetData(), $DataSet->GetDataDescription()); // Finish the graph $Test->setFontProperties("Fonts/tahoma.ttf", 8); $Test->drawLegend(600, 30, $DataSet->GetDataDescription(), 255, 255, 255); $Test->setFontProperties("Fonts/tahoma.ttf", 10); $Test->drawTitle(50, 22, "Change in name popularity", 50, 50, 50, 585); ob_start(); $Test->Stroke(); $img = ob_get_clean(); $img = base64_encode($img); return $img; }
public function make($working_path) { // This will import the file http://my.domain.com/myData.csv using each column as a serie if (!$this->plot->valid()) { $file = $this->plot->name(); $error = $this->plot->error(); $this->log($working_path, "Plot file {$file} is invalid: {$error}"); return 1; } $data = new pData(); $columns = array(); $all_columns = array(); $x_column = $this->plot->property('x_column') - 1; if ($x_column === NULL) { $x_column = 0; } $data_file = $this->plot->data_property('name'); $deliminator = $this->plot->data_property('deliminator'); $has_header = $this->plot->data_property('header') == 'yes'; foreach ($this->plot->columns() as $column => $name) { if ($column != $x_column + 1) { $columns[] = $column - 1; } $all_columns[] = $column - 1; } $data->ImportFromCSV($working_path . $data_file, $deliminator, $all_columns, $has_header); foreach ($columns as $column) { $name = $this->plot->column($column + 1); $data->AddSerie('Serie' . $column); $data->SetSerieName($name, "Serie" . $column); } $max_col = -1; $max_val = NULL; foreach ($data->GetData() as $record) { foreach ($columns as $column) { $point = $record['Serie' . $column]; if ($max_val === NULL || $point > $max_val) { $max_val = $point; $max_col = $column; } } } $x_label = $this->plot->axis_property('x', 'label'); if ($x_label) { $data->SetXAxisName($x_label); } else { $data->SetXAxisName($this->plot->column($x_column + 1)); } $x_unit = $this->plot->axis_property('x', 'unit'); if ($x_unit) { $data->SetXAxisUnit($x_unit); } $y_label = $this->plot->axis_property('y', 'label'); reset($columns); if ($y_label) { $data->SetYAxisName($y_label); } else { $data->SetYAxisName($this->plot->column(current($columns) + 1)); } $y_unit = $this->plot->axis_property('y', 'unit'); if ($y_unit) { $data->SetyAxisUnit($y_unit); } $width = $this->plot->property('width'); if (!$width) { $width = 640; } $height = $this->plot->property('height'); if (!$height) { $height = 480; } $plot = new pChart($width, $height); $font_name = $this->plot->property('font-name'); if (!$font_name) { $font_name = 'tahoma.ttf'; } $font_name = 'lib/plugins/projects/pchart/fonts/' . $font_name; $font_size = $this->plot->property('font_size'); if (!$font_size) { $font_size = 12; } $plot->setFontProperties($font_name, $font_size); $h = $font_size + 10; $left_margin = 0; foreach ($data->GetData() as $record) { $position = imageftbbox($font_size, 0, $font_name, $record['Serie' . $max_col]); $text_width = $position[2] - $position[0]; if ($text_width > $left_margin) { $left_margin = $text_width; } } $left_margin += 2 * $h; $plot->setGraphArea($left_margin, 2 * $h, $width - $h, $height - 2 * $h); $background = $this->plot->property('background'); if (!$background) { $background = array('R' => 255, 'G' => 255, 'B' => 255); } else { $background = html_color_to_RGB($background); } $plot->drawGraphArea($background['R'], $background['G'], $background['B']); // pick the largest scale $plot->drawXYScale($data->GetData(), $data->GetDataDescription(), 'Serie' . $max_col, 'Serie' . $x_column, 0, 0, 0, TRUE, 0, 0); $line_no = 0; $colors = array(); foreach ($columns as $column) { $name = $this->plot->column($column + 1); $style = $this->plot->line_style($name, 'style'); $line_color = $this->plot->line_style($name, 'color'); if (!$line_color) { $colors[$name] = array('R' => 0, 'G' => 0, 'B' => 0); } else { $colors[$name] = html_color_to_RGB($line_color); } $plot->setColorPalette($line_no, $colors[$name]['R'], $colors[$name]['G'], $colors[$name]['B']); if (!$style || $style == 'line' || $style == 'both') { $line_width = $this->plot->line_style($name, 'width'); if (!$line_width) { $line_width = 1; } $dot_size = $this->plot->line_style($name, 'dot-size'); if (!$dot_size) { $dot_size = 0; } $plot->setLineStyle($line_width, $dot_size); $plot->drawXYGraph($data->GetData(), $data->GetDataDescription(), 'Serie' . $column, 'Serie' . $x_column, $line_no); } if ($style == 'point' || $style == 'both') { $radius = $this->plot->line_style($name, 'radius'); if (!$radius) { $radius = 5; } $plot->drawXYPlotGraph($data->GetData(), $data->GetDataDescription(), 'Serie' . $column, 'Serie' . $x_column, $line_no, $radius, $radius - 2); } $line_no++; } $title = $this->plot->property('title'); foreach ($columns as $column) { $data->removeSerie('Serie' . $column); } $in_legend = array(); $description = $data->GetDataDescription(); $description['Description'] = array(); $palette_id = 0; foreach ($columns as $column) { $name = $this->plot->column($column + 1); if (in_array($name, $in_legend)) { continue; } $in_legend[] = $name; $description['Description']['Serie' . $column] = $name; $plot->setColorPalette($palette_id, $colors[$name]['R'], $colors[$name]['G'], $colors[$name]['B']); ++$palette_id; } $legend_box_size = $plot->getLegendBoxSize($description); $legend_position = $this->plot->property('legend-position'); if (!$legend_position) { $legend_position = 'top-left'; } switch ($legend_position) { case 'top-left': $legend_left = 0; $legend_top = 0; break; case 'top': $legend_left = ($width - $h - $left_margin - $legend_box_size[0]) / 2; $legend_top = 0; break; case 'top-right': $legend_left = $width - $left_margin - $h - $legend_box_size[0]; $legend_top = 0; break; case 'left': $legend_left = 0; $legend_top = ($height - 4 * $h - $legend_box_size[1]) / 2; break; case 'center': $legend_left = ($width - $h - $left_margin - $legend_box_size[0]) / 2; $legend_top = ($height - 4 * $h - $legend_box_size[1]) / 2; break; case 'right': $legend_left = $width - $left_margin - $h - $legend_box_size[0]; $legend_top = ($height - 4 * $h - $legend_box_size[1]) / 2; break; case 'bottom-left': $legend_left = 0; $legend_top = $height - 4 * $h - $legend_box_size[1]; break; case 'bottom': $legend_left = ($width - $h - $left_margin - $legend_box_size[0]) / 2; $legend_top = $height - 4 * $h - $legend_box_size[1]; break; case 'bottom-right': $legend_left = $width - $left_margin - $h - $legend_box_size[0]; $legend_top = $height - 4 * $h - $legend_box_size[1]; break; } $plot->drawLegend($left_margin + $legend_left, 2 * $h + $legend_top, $description, 255, 255, 255, 100, 100, 100, 0, 0, 0, true); $plot->drawTitle($h, 0, $title, 0, 0, 0, $width - $h, $h * 2, 100); $plot->Render($this->path($working_path)); $file_name = $this->plot->name(); $plot_name = $this->name(); $this->log($working_path, "Successfully plotted {$file_name} as {$plot_name}\ntitle: {$title}\n"); return 0; }
function line($valores, $titulo, $label = array()) { $nombre = tempnam('/tmp', 'g') . '.png'; $DataSet = new pData(); $ind = 1; $DataSet->AddPoint($valores, 'Serie' . $ind); $DataSet->AddAllSeries(); $DataSet->SetAbsciseLabelSerie(); $DataSet->SetSerieName($titulo, 'Serie' . $ind); if (count($label) > 0) { $ID = 0; foreach ($label as $val) { $DataSet->Data[$ID]["Name"] = $val; $ID++; } } $Test = new pChart(300, 200); $Test->setFontProperties(APPPATH . 'libraries/pChart/Fonts/tahoma.ttf', 8); $Test->setGraphArea(70, 30, 280, 170); $Test->drawFilledRoundedRectangle(7, 7, 293, 193, 5, 240, 240, 240); $Test->drawRoundedRectangle(5, 5, 295, 195, 5, 230, 230, 230); $Test->drawGraphArea(255, 255, 255, TRUE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, true, 0, 0); $Test->drawGrid(4, TRUE, 200, 200, 200, 50); $Test->setFontProperties(APPPATH . 'libraries/pChart/Fonts/tahoma.ttf', 6); $Test->drawTreshold(0, 143, 55, 72, TRUE, TRUE); $Test->drawCubicCurve($DataSet->GetData(), $DataSet->GetDataDescription()); $Test->setFontProperties(APPPATH . 'libraries/pChart/Fonts/tahoma.ttf', 8); $Test->drawLegend(200, 9, $DataSet->GetDataDescription(), 255, 255, 255); $Test->setFontProperties(APPPATH . 'libraries/pChart/Fonts/tahoma.ttf', 10); //$Test->drawTitle(10,22,$titulo,50,50,50,300); $Test->Render($nombre); return $nombre; }
/** * Draw bar style chart * @return unknown */ protected function drawBar() { // prepare font & series $this->_prepareSerie(); $this->_prepareFont(); // init chart params $outer_w = $this->w - 5; // Outer frame witdh $outer_h = $this->h - 5; // Outer frame heigth $inner_w = $this->w - 7; // Inner frame witdh $inner_h = $this->h - 7; // Inner frame heigth $chart_w = $this->w - 150; // Chart frame witdh $chart_h = $this->h - 40; // Chart frame heigth $title_w = $this->w - 200; // Title width $title_h = 45; // Title height $legend_w = $chart_w + 30; // Legend width $legend_h = 40; // Legend height // chart styles $grid = isset($this->p['grid']) ? $this->p['grid'] : false; // fill chart $this->chart->drawBackground(255, 255, 255); $this->chart->setFontProperties($this->font, 7); // set font and size $this->chart->drawRoundedRectangle(5, 5, $outer_w, $outer_h, 10, 230, 230, 230); // drawRoundedRectangle($X1,$Y1,$X2,$Y2,$Radius,$R,$G,$B) $this->chart->drawFilledRoundedRectangle(7, 7, $inner_w, $inner_h, 10, 240, 240, 240); // drawRoundedRectangle($X1,$Y1,$X2,$Y2,$Radius,$R,$G,$B) $this->chart->setGraphArea(90, 40, $chart_w, $chart_h); // setGraphArea($X1,$Y1,$X2,$Y2) $this->chart->drawGraphArea(255, 255, 255, TRUE); // drawGraphArea($R,$G,$B) $this->chart->drawScale($this->data->GetData(), $this->data->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2, $this->margin, $this->skip); // drawScale($Data,$DataDescription,$ScaleMode,$R,$G,$B,$DrawTicks=TRUE,$Angle=0,$Decimals=1,$WithMargin=FALSE,$SkipLabels=1,$RightScale=FALSE) $this->data->RemoveSerie('DEFAULT_SCALE'); // clear scale serie for setScale method // draw grid if ($grid) { $this->chart->drawGrid(3, TRUE, 230, 230, 230, 50); // drawGrid($LineWidth,$Mosaic=TRUE,$R=220,$G=220,$B=220,$Alpha=255) } // draw the cubic curve graph $this->chart->drawBarGraph($this->data->GetData(), $this->data->GetDataDescription(), TRUE); // add Title $this->chart->setFontProperties($this->font, 10); $this->chart->drawTitle(40, 0, $this->title, 50, 50, 50, $title_w, $title_h); // drawTitle($XPos,$YPos,$Value,$R,$G,$B,$XPos2=-1,$YPos2=-1,$Shadow=FALSE) // add Legend $this->chart->setFontProperties($this->font, 8); $this->chart->drawLegend($legend_w, $legend_h, $this->data->GetDataDescription(), 255, 255, 255); // drawLegend($description,$R,$G,$B) }
function index() { $this->load->model('charge_model'); $revenue = $this->charge_model->GetRevenueByDay($this->user->Get('client_id')); $data = array(); if ($this->config->item('show_dashboard_chart') !== 'no' and !empty($revenue) and count($revenue) > 1) { $series = array(); foreach ($revenue as $day) { $series[] = $day['revenue']; $series2[] = date("M j", strtotime($day['day'])); } include APPPATH . 'libraries/pchart/pData.class'; include APPPATH . 'libraries/pchart/pChart.class'; // Dataset definition $DataSet = new pData(); $DataSet->AddPoint($series, "Revenue"); $DataSet->AddPoint($series2, "Serie2"); $DataSet->AddAllSeries(); $DataSet->SetAbsciseLabelSerie("Serie2"); $DataSet->RemoveSerie("Serie2"); $DataSet->SetXAxisName('Date'); $DataSet->SetYAxisName('Revenue'); //$DataSet->SetXAxisFormat('date'); // Initialise the graph $Test = new pChart(1000, 260); $Test->setFontProperties(APPPATH . 'libraries/pchart/Arial.ttf', 10); $Test->setGraphArea(90, 30, 960, 200); $Test->drawGraphArea(252, 252, 252); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2); $Test->drawGrid(4, TRUE, 230, 230, 230, 255); // Draw the line graph $Test->drawLineGraph($DataSet->GetData(), $DataSet->GetDataDescription()); $Test->drawPlotGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 3, 2, 255, 255, 255); // Finish the graph $Test->setFontProperties(APPPATH . 'libraries/pchart/Arial.ttf', 8); $Test->drawLegend(45, 35, $DataSet->GetDataDescription(), 255, 255, 255); $Test->setFontProperties(APPPATH . 'libraries/pchart/Arial.ttf', 10); //$Test->drawTitle(60,22,"Last 30 Days",50,50,50,585); $Test->Render(BASEPATH . '../writeable/rev_chart_' . $this->user->Get('client_id') . '.png'); } else { $data['no_chart'] = 'true'; } // get log $this->load->model('log_model'); $log = $this->log_model->GetClientLog($this->user->Get('client_id')); $data['log'] = $log; $this->load->view(branded_view('cp/dashboard'), $data); }
function writeBarData($data, $graph) { if ($data != "") { echo "Plottong " . $graph . "\n"; $dataset1 = array(); $dataset2 = array(); $counter = 0; $toggle = true; $data = array_reverse($data, TRUE); ksort($data); foreach ($data as $key => $value) { if ($counter % 5 != 0) { $key = " "; } array_push($dataset1, $key); array_push($dataset2, $value); $counter++; } // Dataset definition $DataSet = new pData(); $DataSet->AddPoint($dataset2, "Serie1"); $DataSet->AddPoint($dataset1, "XLabel"); $DataSet->AddAllSeries(); $DataSet->SetAbsciseLabelSerie("XLabel"); $DataSet->RemoveSerie("XLabel"); $DataSet->SetSerieName("Membership", "Serie1"); // Initialise the graph $Test = new pChart(700, 230); $Test->setFontProperties("Fonts/tahoma.ttf", 8); $Test->setGraphArea(50, 30, 680, 200); $Test->drawFilledRoundedRectangle(7, 7, 693, 223, 5, 240, 240, 240); $Test->drawRoundedRectangle(5, 5, 695, 225, 5, 230, 230, 230); $Test->drawGraphArea(255, 255, 255, TRUE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), 'SCALE_NORMAL', 150, 150, 150, TRUE, 0, 2, TRUE); $Test->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line $Test->setFontProperties("Fonts/tahoma.ttf", 6); $Test->drawTreshold(0, 143, 55, 72, TRUE, TRUE); // Draw the bar graph $Test->drawBarGraph($DataSet->GetData(), $DataSet->GetDataDescription(), TRUE); // Finish the graph $Test->setFontProperties("Fonts/tahoma.ttf", 8); $Test->drawLegend(596, 150, $DataSet->GetDataDescription(), 255, 255, 255); $Test->setFontProperties("Fonts/tahoma.ttf", 10); $Test->drawTitle(50, 22, "Membership by Month", 50, 50, 50, 585); $Test->Render("{$graph}-bar.png"); } }
function generate_image($site_name, $visits) { $font = APP_PATH . "libs/pchart/Fonts/tahoma.ttf"; //$font = APP_PATH."includes/pchart/Fonts/DejaVuSans.ttf"; global $lang; // Dataset definition $DataSet = new pData(); $names = array(); $points = array(); foreach ($visits as $date => $visit) { $points[] = $visit; $text = $lang['days'][date('N', strtotime($date))]; $names[] = $text; } $DataSet->AddPoint($points, "Lankytojai"); $DataSet->AddPoint($names, "days"); $DataSet->AddAllSeries(); $DataSet->RemoveSerie("days"); $DataSet->SetAbsciseLabelSerie('days'); // Initialise the graph $Test = new pChart(700, 230); $Test->setFontProperties($font, 8); $Test->setGraphArea(50, 30, 680, 200); $Test->drawFilledRoundedRectangle(7, 7, 693, 223, 5, 240, 240, 240); $Test->drawRoundedRectangle(5, 5, 695, 225, 5, 230, 230, 230); $Test->drawGraphArea(255, 255, 255, TRUE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2, TRUE); $Test->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line $Test->setFontProperties($font, 6); $Test->drawTreshold(0, 143, 55, 72, TRUE, TRUE); // Draw the bar graph $Test->drawBarGraph($DataSet->GetData(), $DataSet->GetDataDescription(), TRUE, 80); // Finish the graph $Test->setFontProperties($font, 8); // $Test->drawLegend(100,20,$DataSet->GetDataDescription(),255,255,255); $Test->drawLegend(610, 10, $DataSet->GetDataDescription(), 236, 238, 240, 52, 58, 82); $Test->setFontProperties($font, 10); $Test->drawTitle(50, 22, $site_name, 50, 50, 50, 585); $path = IMAGE_PATH . "{$site_name}.png"; if (file_exists($path)) { unlink($path); } $Test->Render($path); return $path; }
/** * Generates statistics * * @param int $surveyid The survey id * @param mixed $allfields * @param mixed $q2show * @param mixed $usegraph * @param string $outputType Optional - Can be xls, html or pdf - Defaults to pdf * @param string $pdfOutput Sets the target for the PDF output: DD=File download , F=Save file to local disk * @param string $statlangcode Lamguage for statistics * @param mixed $browse Show browse buttons * @return buffer */ function generate_statistics($surveyid, $allfields, $q2show='all', $usegraph=0, $outputType='pdf', $pdfOutput='I',$statlangcode=null, $browse = true) { //$allfields =""; global $connect, $dbprefix, $clang, $rooturl, $rootdir, $homedir, $homeurl, $tempdir, $tempurl, $scriptname, $imagedir, $chartfontfile, $chartfontsize, $admintheme, $pdfdefaultfont, $pdffontsize; $fieldmap=createFieldMap($surveyid, "full"); if (is_null($statlangcode)) { $statlang=$clang; } else { $statlang = new limesurvey_lang($statlangcode); } /* * this variable is used in the function shortencode() which cuts off a question/answer title * after $maxchars and shows the rest as tooltip (in html mode) */ $maxchars = 13; //we collect all the html-output within this variable $statisticsoutput =''; /** * $outputType: html || pdf || */ /** * get/set Survey Details */ //no survey ID? -> come and get one if (!isset($surveyid)) {$surveyid=returnglobal('sid');} //Get an array of codes of all available languages in this survey $surveylanguagecodes = GetAdditionalLanguagesFromSurveyID($surveyid); $surveylanguagecodes[] = GetBaseLanguageFromSurveyID($surveyid); // Set language for questions and answers to base language of this survey $language=$statlangcode; if ($usegraph==1) { //for creating graphs we need some more scripts which are included here require_once(dirname(__FILE__).'/../classes/pchart/pchart/pChart.class'); require_once(dirname(__FILE__).'/../classes/pchart/pchart/pData.class'); require_once(dirname(__FILE__).'/../classes/pchart/pchart/pCache.class'); $MyCache = new pCache($tempdir.'/'); //pick the best font file if font setting is 'auto' if ($chartfontfile=='auto') { $chartfontfile='vera.ttf'; if ( $language=='ar') { $chartfontfile='KacstOffice.ttf'; } elseif ($language=='fa' ) { $chartfontfile='KacstFarsi.ttf'; } } } if($q2show=='all' ) { $summarySql=" SELECT gid, parent_qid, qid, type " ." FROM {$dbprefix}questions WHERE parent_qid=0" ." AND sid=$surveyid "; $summaryRs = db_execute_assoc($summarySql); foreach($summaryRs as $field) { $myField = $surveyid."X".$field['gid']."X".$field['qid']; // Multiple choice get special treatment if ($field['type'] == "M") {$myField = "M$myField";} if ($field['type'] == "P") {$myField = "P$myField";} //numerical input will get special treatment (arihtmetic mean, standard derivation, ...) if ($field['type'] == "N") {$myField = "N$myField";} if ($field['type'] == "|") {$myField = "|$myField";} if ($field['type'] == "Q") {$myField = "Q$myField";} // textfields get special treatment if ($field['type'] == "S" || $field['type'] == "T" || $field['type'] == "U"){$myField = "T$myField";} //statistics for Date questions are not implemented yet. if ($field['type'] == "D") {$myField = "D$myField";} if ($field['type'] == "F" || $field['type'] == "H") { //Get answers. We always use the answer code because the label might be too long elsewise $query = "SELECT code, answer FROM ".db_table_name("answers")." WHERE qid='".$field['qid']."' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer"; $result = db_execute_num($query) or safe_die ("Couldn't get answers!<br />$query<br />".$connect->ErrorMsg()); $counter2=0; //check all the answers while ($row=$result->FetchRow()) { $myField = "$myField{$row[0]}"; } //$myField = "{$surveyid}X{$flt[1]}X{$flt[0]}{$row[0]}[]"; } if($q2show=='all') $summary[]=$myField; //$allfields[]=$myField; } } else { // This gets all the 'to be shown questions' from the POST and puts these into an array if (!is_array($q2show)) $summary=returnglobal('summary'); else $summary = $q2show; //print_r($_POST); //if $summary isn't an array we create one if (isset($summary) && !is_array($summary)) { $summary = explode("+", $summary); } } /* Some variable depend on output type, actually : only line feed */ switch($outputType) { case 'xls': $linefeed = "\n"; break; case 'pdf': $linefeed = "\n"; break; case 'html': $linefeed = "<br />\n"; break; default: break; } /** * pdf Config */ if($outputType=='pdf') { require_once('classes/tcpdf/config/lang/eng.php'); global $l; $l['w_page'] = $statlang->gT("Page",'unescaped'); require_once('classes/tcpdf/mypdf.php'); // create new PDF document $pdf = new MyPDF(); $pdf->SetFont($pdfdefaultfont,'',$pdffontsize); $surveyInfo = getSurveyInfo($surveyid,$language); // set document information $pdf->SetCreator(PDF_CREATOR); $pdf->SetAuthor('LimeSurvey'); $pdf->SetTitle('Statistic survey '.$surveyid); $pdf->SetSubject($surveyInfo['surveyls_title']); $pdf->SetKeywords('LimeSurvey, Statistics, Survey '.$surveyid.''); $pdf->SetDisplayMode('fullpage', 'two'); // set header and footer fonts $pdf->setHeaderFont(Array($pdfdefaultfont, '', PDF_FONT_SIZE_MAIN)); $pdf->setFooterFont(Array($pdfdefaultfont, '', PDF_FONT_SIZE_DATA)); // set default header data // the path looks awkward - did not find a better solution to set the image path? $pdf->SetHeaderData("statistics.png", 10, $statlang->gT("Quick statistics",'unescaped') , $statlang->gT("Survey")." ".$surveyid." '".FlattenText($surveyInfo['surveyls_title'],true,'UTF-8')."'"); // set default monospaced font $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); //set margins $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); //set auto page breaks $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); //set image scale factor $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); //set some language-dependent strings $pdf->setLanguageArray($l); } if($outputType=='xls') { /** * Initiate the Spreadsheet_Excel_Writer */ include_once(dirname(__FILE__)."/classes/pear/Spreadsheet/Excel/Writer.php"); if($pdfOutput=='F') $workbook = new Spreadsheet_Excel_Writer($tempdir.'/statistic-survey'.$surveyid.'.xls'); else $workbook = new Spreadsheet_Excel_Writer(); $workbook->setVersion(8); // Inform the module that our data will arrive as UTF-8. // Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...) if (!empty($tempdir)) { $workbook->setTempDir($tempdir); } if ($pdfOutput!='F') $workbook->send('statistic-survey'.$surveyid.'.xls'); // Creating the first worksheet $sheet =& $workbook->addWorksheet(utf8_decode('results-survey'.$surveyid)); $sheet->setInputEncoding('utf-8'); $sheet->setColumn(0,20,20); $separator="~|"; } /** * Start generating */ // creates array of post variable names for (reset($_POST); $key=key($_POST); next($_POST)) { $postvars[]=$key;} $aQuestionMap=array(); foreach ($fieldmap as $field) { if(isset($field['qid']) && $field['qid']!='') $aQuestionMap[]=$field['sid'].'X'.$field['gid'].'X'.$field['qid']; } /* * Iterate through postvars to create "nice" data for SQL later. * * Remember there might be some filters applied which have to be put into an SQL statement */ if(isset($postvars)) foreach ($postvars as $pv) { //Only do this if there is actually a value for the $pv if (in_array($pv, $allfields) || in_array(substr($pv,1),$aQuestionMap) || in_array($pv,$aQuestionMap) || (($pv[0]=='D' || $pv[0]=='N' || $pv[0]=='K') && in_array(substr($pv,1,strlen($pv)-2),$aQuestionMap))) { $firstletter=substr($pv,0,1); /* * these question types WON'T be handled here: * M = Multiple choice * T - Long Free Text * Q - Multiple Short Text * D - Date * N - Numerical Input * | - File Upload * K - Multiple Numerical Input */ if ($pv != "sid" && $pv != "display" && $firstletter != "M" && $firstletter != "P" && $firstletter != "T" && $firstletter != "Q" && $firstletter != "D" && $firstletter != "N" && $firstletter != "K" && $firstletter != "|" && $pv != "summary" && substr($pv, 0, 2) != "id" && substr($pv, 0, 9) != "datestamp") //pull out just the fieldnames { //put together some SQL here $thisquestion = db_quote_id($pv)." IN ("; foreach ($_POST[$pv] as $condition) { $thisquestion .= "'$condition', "; } $thisquestion = substr($thisquestion, 0, -2) . ")"; //we collect all the to be selected data in this array $selects[]=$thisquestion; } //M - Multiple choice //P - Multiple choice with comments elseif ($firstletter == "M" || $firstletter == "P") { $mselects=array(); //create a list out of the $pv array list($lsid, $lgid, $lqid) = explode("X", $pv); $aquery="SELECT title FROM ".db_table_name("questions")." WHERE parent_qid=$lqid AND language='{$language}' and scale_id=0 ORDER BY question_order"; $aresult=db_execute_num($aquery) or safe_die ("Couldn't get subquestions<br />$aquery<br />".$connect->ErrorMsg()); // go through every possible answer while ($arow=$aresult->FetchRow()) { // only add condition if answer has been chosen if (in_array($arow[0], $_POST[$pv])) { $mselects[]=db_quote_id(substr($pv, 1, strlen($pv)).$arow[0])." = 'Y'"; } } if ($mselects) { $thismulti=implode(" OR ", $mselects); $selects[]="($thismulti)"; $mselects = ""; } } //N - Numerical Input //K - Multiple Numerical Input elseif ($firstletter == "N" || $firstletter == "K") { //value greater than if (substr($pv, strlen($pv)-1, 1) == "G" && $_POST[$pv] != "") { $selects[]=db_quote_id(substr($pv, 1, -1))." > ".sanitize_int($_POST[$pv]); } //value less than if (substr($pv, strlen($pv)-1, 1) == "L" && $_POST[$pv] != "") { $selects[]=db_quote_id(substr($pv, 1, -1))." < ".sanitize_int($_POST[$pv]); } } //| - File Upload Question Type else if ($firstletter == "|") { // no. of files greater than if (substr($pv, strlen($pv)-1, 1) == "G" && $_POST[$pv] != "") $selects[]=db_quote_id(substr($pv, 1, -1)."_filecount")." > ".sanitize_int($_POST[$pv]); // no. of files less than if (substr($pv, strlen($pv)-1, 1) == "L" && $_POST[$pv] != "") $selects[]=db_quote_id(substr($pv, 1, -1)."_filecount")." < ".sanitize_int($_POST[$pv]); } //"id" is a built in field, the unique database id key of each response row elseif (substr($pv, 0, 2) == "id") { if (substr($pv, strlen($pv)-1, 1) == "G" && $_POST[$pv] != "") { $selects[]=db_quote_id(substr($pv, 0, -1))." > '".$_POST[$pv]."'"; } if (substr($pv, strlen($pv)-1, 1) == "L" && $_POST[$pv] != "") { $selects[]=db_quote_id(substr($pv, 0, -1))." < '".$_POST[$pv]."'"; } } //T - Long Free Text //Q - Multiple Short Text elseif (($firstletter == "T" || $firstletter == "Q" ) && $_POST[$pv] != "") { $selectSubs = array(); //We intepret and * and % as wildcard matches, and use ' OR ' and , as the seperators $pvParts = explode(",",str_replace('*','%', str_replace(' OR ',',',$_POST[$pv]))); if(is_array($pvParts) AND count($pvParts)){ foreach($pvParts AS $pvPart){ $selectSubs[]=db_quote_id(substr($pv, 1, strlen($pv)))." LIKE '".trim($pvPart)."'"; } if(count($selectSubs)){ $selects[] = ' ('.implode(' OR ',$selectSubs).') '; } } } //D - Date elseif ($firstletter == "D" && $_POST[$pv] != "") { //Date equals if (substr($pv, -1, 1) == "=") { $selects[]=db_quote_id(substr($pv, 1, strlen($pv)-2))." = '".$_POST[$pv]."'"; } else { //date less than if (substr($pv, -1, 1) == "<") { $selects[]= db_quote_id(substr($pv, 1, strlen($pv)-2)) . " >= '".$_POST[$pv]."'"; } //date greater than if (substr($pv, -1, 1) == ">") { $selects[]= db_quote_id(substr($pv, 1, strlen($pv)-2)) . " <= '".$_POST[$pv]."'"; } } } //check for datestamp of given answer elseif (substr($pv, 0, 9) == "datestamp") { //timestamp equals $formatdata=getDateFormatData($_SESSION['dateformat']); if (substr($pv, -1, 1) == "E" && !empty($_POST[$pv])) { $datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'].' H:i'); $_POST[$pv]=$datetimeobj->convert("Y-m-d"); $selects[] = db_quote_id('datestamp')." >= '".$_POST[$pv]." 00:00:00' and ".db_quote_id('datestamp')." <= '".$_POST[$pv]." 23:59:59'"; } else { //timestamp less than if (substr($pv, -1, 1) == "L" && !empty($_POST[$pv])) { $datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'].' H:i'); $_POST[$pv]=$datetimeobj->convert("Y-m-d H:i:s"); $selects[]= db_quote_id('datestamp')." < '".$_POST[$pv]."'"; } //timestamp greater than if (substr($pv, -1, 1) == "G" && !empty($_POST[$pv])) { $datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'].' H:i'); $_POST[$pv]=$datetimeobj->convert("Y-m-d H:i:s"); $selects[]= db_quote_id('datestamp')." > '".$_POST[$pv]."'"; } } } } else { $statisticsoutput .= "<!-- $pv DOES NOT EXIST IN ARRAY -->"; } } //end foreach -> loop through filter options to create SQL //count number of answers $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid"); //if incompleted answers should be filtert submitdate has to be not null if (incompleteAnsFilterstate() == "inc") {$query .= " WHERE submitdate is null";} elseif (incompleteAnsFilterstate() == "filter") {$query .= " WHERE submitdate is not null";} $result = db_execute_num($query) or safe_die ("Couldn't get total<br />$query<br />".$connect->ErrorMsg()); //$total = total number of answers while ($row=$result->FetchRow()) {$total=$row[0];} //are there any filters that have to be taken care of? if (isset($selects) && $selects) { //filter incomplete answers? if (incompleteAnsFilterstate() == "filter" || incompleteAnsFilterstate() == "inc") {$query .= " AND ";} else {$query .= " WHERE ";} //add filter criteria to SQL $query .= implode(" AND ", $selects); } //$_POST['sql'] is a post field that is sent from the statistics script to the export script in order // to export just those results filtered by this statistics script. It can also be passed to the statistics // script to filter from external scripts. elseif (!empty($_POST['sql']) && !isset($_POST['id='])) { $newsql=substr($_POST['sql'], strpos($_POST['sql'], "WHERE")+5, strlen($_POST['sql'])); //for debugging only //$query = $_POST['sql']; //filter incomplete answers? if (incompleteAnsFilterstate() == "inc") {$query .= " AND ".$newsql;} elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND ".$newsql;} else {$query .= " WHERE ".$newsql;} } //get me some data Scotty $result=db_execute_num($query) or safe_die("Couldn't get results<br />$query<br />".$connect->ErrorMsg()); //put all results into $results while ($row=$result->FetchRow()) {$results=$row[0];} if ($total) { $percent=sprintf("%01.2f", ($results/$total)*100); } switch($outputType) { case "xls": $xlsRow = 0; $sheet->write($xlsRow,0,$statlang->gT("Number of records in this query:")); $sheet->write($xlsRow,1,$results); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Total records in survey:")); $sheet->write($xlsRow,1,$total); if($total) { ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Percentage of total:")); $sheet->write($xlsRow,1,$percent."%"); } break; case 'pdf': // add summary to pdf $array = array(); //$array[] = array($statlang->gT("Results"),""); $array[] = array($statlang->gT("Number of records in this query:"), $results); $array[] = array($statlang->gT("Total records in survey:"), $total); if($total) $array[] = array($statlang->gT("Percentage of total:"), $percent."%"); $pdf->addPage('P','A4'); $pdf->Bookmark($pdf->delete_html($statlang->gT("Results")), 0, 0); $pdf->titleintopdf($statlang->gT("Results"),$statlang->gT("Survey")." ".$surveyid); $pdf->tableintopdf($array); $pdf->addPage('P','A4'); break; case 'html': $statisticsoutput .= "<br />\n<table class='statisticssummary' >\n" ."\t<thead><tr><th colspan='2'>".$statlang->gT("Results")."</th></tr></thead>\n" ."\t<tr><th >".$statlang->gT("Number of records in this query:").'</th>' ."<td>$results</td></tr>\n" ."\t<tr><th>".$statlang->gT("Total records in survey:").'</th>' ."<td>$total</td></tr>\n"; //only calculate percentage if $total is set if ($total) { $percent=sprintf("%01.2f", ($results/$total)*100); $statisticsoutput .= "\t<tr><th align='right'>".$statlang->gT("Percentage of total:").'</th>' ."<td>$percent%</td></tr>\n"; } $statisticsoutput .="</table>\n"; break; default: break; } //put everything from $selects array into a string connected by AND if (isset ($selects) && $selects) {$sql=implode(" AND ", $selects);} elseif (!empty($newsql)) {$sql = $newsql;} if (!isset($sql) || !$sql) {$sql="NULL";} //only continue if we have something to output if ($results > 0) { if($outputType=='html' && $browse === true) { //add a buttons to browse results $statisticsoutput .= "<form action='$scriptname?action=browse' method='post' target='_blank'>\n" ."\t\t<p>" ."\t\t\t<input type='submit' value='".$statlang->gT("Browse")."' />\n" ."\t\t\t<input type='hidden' name='sid' value='$surveyid' />\n" ."\t\t\t<input type='hidden' name='sql' value=\"$sql\" />\n" ."\t\t\t<input type='hidden' name='subaction' value='all' />\n" ."\t\t</p>" ."\t\t</form>\n"; } } //end if (results > 0) //Show Summary results if (isset($summary) && $summary) { //let's run through the survey $runthrough=$summary; //START Chop up fieldname and find matching questions //GET LIST OF LEGIT QIDs FOR TESTING LATER $lq = "SELECT DISTINCT qid FROM ".db_table_name("questions")." WHERE sid=$surveyid and parent_qid=0"; $lr = db_execute_assoc($lq); //loop through the IDs while ($lw = $lr->FetchRow()) { //this creates an array of question id's' $legitqids[] = $lw['qid']; } //loop through all selected questions foreach ($runthrough as $rt) { $firstletter = substr($rt, 0, 1); // 1. Get answers for question ############################################################## //M - Multiple choice, therefore multiple fields if ($firstletter == "M" || $firstletter == "P") { //get SGQ data list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3); //select details for this question $nquery = "SELECT title, type, question, parent_qid, other FROM ".db_table_name("questions")." WHERE language='{$language}' AND parent_qid=0 AND qid='$qqid'"; $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg()); //loop through question data while ($nrow=$nresult->FetchRow()) { $qtitle=$nrow[0]; $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]); $qlid=$nrow[3]; $qother=$nrow[4]; } //1. Get list of answers $query="SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qqid' AND language='{$language}' and scale_id=0 ORDER BY question_order"; $result=db_execute_num($query) or safe_die("Couldn't get list of subquestions for multitype<br />$query<br />".$connect->ErrorMsg()); //loop through multiple answers while ($row=$result->FetchRow()) { $mfield=substr($rt, 1, strlen($rt))."$row[0]"; //create an array containing answer code, answer and fieldname(??) $alist[]=array("$row[0]", FlattenText($row[1]), $mfield); } //check "other" field. is it set? if ($qother == "Y") { $mfield=substr($rt, 1, strlen($rt))."other"; //create an array containing answer code, answer and fieldname(??) $alist[]=array($statlang->gT("Other"), $statlang->gT("Other"), $mfield); } } //S - Short Free Text //T - Long Free Text elseif ($firstletter == "T" || $firstletter == "S") //Short and long text { //search for key $fld = substr($rt, 1, strlen($rt)); $fielddata=$fieldmap[$fld]; //get SGQA IDs $qsid=$fielddata['sid']; $qgid=$fielddata['gid']; $qqid=$fielddata['qid']; list($qanswer, $qlid)=!empty($fielddata['aid']) ? explode("_", $fielddata['aid']) : array("", ""); //get SGQ data //list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3); //get question data $nquery = "SELECT title, type, question, other, parent_qid FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'"; $nresult = db_execute_num($nquery) or safe_die("Couldn't get text question<br />$nquery<br />".$connect->ErrorMsg()); //loop through question data while ($nrow=$nresult->FetchRow()) { $qtitle=FlattenText($nrow[0]); $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]); $nlid=$nrow[4]; } $mfield=substr($rt, 1, strlen($rt)); //Text questions either have an answer, or they don't. There's no other way of quantising the results. // So, instead of building an array of predefined answers like we do with lists & other types, // we instead create two "types" of possible answer - either there is a response.. or there isn't. // This question type then can provide a % of the question answered in the summary. $alist[]=array("Answers", $statlang->gT("Answer"), $mfield); $alist[]=array("NoAnswer", $statlang->gT("No answer"), $mfield); } //Multiple short text elseif ($firstletter == "Q") { //get SGQ data list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3); //separating another ID $tmpqid=substr($qqid, 0, strlen($qqid)-1); //check if we have legid QIDs. if not create them by substringing while (!in_array ($tmpqid,$legitqids)) $tmpqid=substr($tmpqid, 0, strlen($tmpqid)-1); //length of QID $qidlength=strlen($tmpqid); //we somehow get the answer code (see SQL later) from the $qqid $qaid=substr($qqid, $qidlength, strlen($qqid)-$qidlength); //get some question data $nquery = "SELECT title, type, question, other FROM ".db_table_name("questions")." WHERE qid='".substr($qqid, 0, $qidlength)."' AND parent_qid=0 AND language='{$language}'"; $nresult = db_execute_num($nquery) or safe_die("Couldn't get text question<br />$nquery<br />".$connect->ErrorMsg()); //more substrings $count = substr($qqid, strlen($qqid)-1); //loop through question data while ($nrow=$nresult->FetchRow()) { $qtitle=FlattenText($nrow[0]).'-'.$count; $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]); } //get answers $qquery = "SELECT title as code, question as answer FROM ".db_table_name("questions")." WHERE parent_qid='".substr($qqid, 0, $qidlength)."' AND title='$qaid' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details (Array 5p Q)<br />$qquery<br />".$connect->ErrorMsg()); //loop through answer data while ($qrow=$qresult->FetchRow()) { //store each answer here $atext=FlattenText($qrow[1]); } //add this to the question title $qtitle .= " [$atext]"; //even more substrings... $mfield=substr($rt, 1, strlen($rt)); //Text questions either have an answer, or they don't. There's no other way of quantising the results. // So, instead of building an array of predefined answers like we do with lists & other types, // we instead create two "types" of possible answer - either there is a response.. or there isn't. // This question type then can provide a % of the question answered in the summary. $alist[]=array("Answers", $statlang->gT("Answer"), $mfield); $alist[]=array("NoAnswer", $statlang->gT("No answer"), $mfield); } //RANKING OPTION THEREFORE CONFUSING elseif ($firstletter == "R") { //getting the needed IDs somehow $lengthofnumeral=substr($rt, strpos($rt, "-")+1, 1); list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strpos($rt, "-")-($lengthofnumeral+1)), 3); //get question data $nquery = "SELECT title, type, question FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'"; $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg()); //loop through question data while ($nrow=$nresult->FetchRow()) { $qtitle=FlattenText($nrow[0]). " [".substr($rt, strpos($rt, "-")-($lengthofnumeral), $lengthofnumeral)."]"; $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]). "[".$statlang->gT("Ranking")." ".substr($rt, strpos($rt, "-")-($lengthofnumeral), $lengthofnumeral)."]"; } //get answers $query="SELECT code, answer FROM ".db_table_name("answers")." WHERE qid='$qqid' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer"; $result=db_execute_num($query) or safe_die("Couldn't get list of answers for multitype<br />$query<br />".$connect->ErrorMsg()); //loop through answers while ($row=$result->FetchRow()) { //create an array containing answer code, answer and fieldname(??) $mfield=substr($rt, 1, strpos($rt, "-")-1); $alist[]=array("$row[0]", FlattenText($row[1]), $mfield); } } else if ($firstletter == "|") // File UPload { //get SGQ data list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3); //select details for this question $nquery = "SELECT title, type, question, parent_qid, other FROM ".db_table_name("questions")." WHERE language='{$language}' AND parent_qid=0 AND qid='$qqid'"; $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg()); //loop through question data while ($nrow=$nresult->FetchRow()) { $qtitle=$nrow[0]; $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]); $qlid=$nrow[3]; $qother=$nrow[4]; } /* 4) Average size of file per respondent 5) Average no. of files 5) Summary/count of file types (ie: 37 jpg, 65 gif, 12 png) 6) Total size of all files (useful if you're about to download them all) 7) You could also add things like smallest file size, largest file size, median file size 8) no. of files corresponding to each extension 9) max file size 10) min file size */ // 1) Total number of files uploaded // 2) Number of respondents who uploaded at least one file (with the inverse being the number of respondents who didn’t upload any) $fieldname=substr($rt, 1, strlen($rt)); $query = "SELECT SUM(".db_quote_id($fieldname.'_filecount').") as sum, AVG(".db_quote_id($fieldname.'_filecount').") as avg FROM ".db_table_name("survey_$surveyid"); $result=db_execute_assoc($query) or safe_die("Couldn't fetch the records<br />$query<br />".$connect->ErrorMsg()); $showem = array(); while ($row = $result->FetchRow()) { $showem[]=array($statlang->gT("Total number of files"), $row['sum']); $showem[]=array($statlang->gT("Average no. of files per respondent"), $row['avg']); } $query = "SELECT ". $fieldname ." as json FROM ".db_table_name("survey_$surveyid"); $result=db_execute_assoc($query) or safe_die("Couldn't fetch the records<br />$query<br />".$connect->ErrorMsg()); $responsecount = 0; $filecount = 0; $size = 0; while ($row = $result->FetchRow()) { $json = $row['json']; $phparray = json_decode($json); foreach ($phparray as $metadata) { $size += (int) $metadata->size; $filecount++; } $responsecount++; } $showem[] = array($statlang->gT("Total size of files"), $size." KB"); $showem[] = array($statlang->gT("Average file size"), $size/$filecount . " KB"); $showem[] = array($statlang->gT("Average size per respondent"), $size/$responsecount . " KB"); /* $query="SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qqid' AND language='{$language}' ORDER BY question_order"; $result=db_execute_num($query) or safe_die("Couldn't get list of subquestions for multitype<br />$query<br />".$connect->ErrorMsg()); //loop through multiple answers while ($row=$result->FetchRow()) { $mfield=substr($rt, 1, strlen($rt))."$row[0]"; //create an array containing answer code, answer and fieldname(??) $alist[]=array("$row[0]", FlattenText($row[1]), $mfield); } */ //outputting switch($outputType) { case 'xls': $headXLS = array(); $tableXLS = array(); $footXLS = array(); $xlsTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8')); $xlsDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8'); ++$xlsRow; ++$xlsRow; ++$xlsRow; $sheet->setCellValueByColumnAndRow(0,$xlsRow,$xlsTitle); ++$xlsRow; $sheet->setCellValueByColumnAndRow(0,$xlsRow,$xlsDesc); $headXLS[] = array($statlang->gT("Calculation"),$statlang->gT("Result")); ++$xlsRow; $sheet->setCellValueByColumnAndRow(0, $xlsRow,$statlang->gT("Calculation")); $sheet->setCellValueByColumnAndRow(1, $xlsRow,$statlang->gT("Result")); break; case 'pdf': $headPDF = array(); $tablePDF = array(); $footPDF = array(); $pdfTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8')); $titleDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8'); $headPDF[] = array($statlang->gT("Calculation"),$statlang->gT("Result")); break; case 'html': $statisticsoutput .= "\n<table class='statisticstable' >\n" ."\t<thead><tr><th colspan='2' align='center'><strong>".sprintf($statlang->gT("Field summary for %s"),$qtitle).":</strong>" ."</th></tr>\n" ."\t<tr><th colspan='2' align='center'><strong>$qquestion</strong></th></tr>\n" ."\t<tr>\n\t\t<th width='50%' align='center' ><strong>" .$statlang->gT("Calculation")."</strong></th>\n" ."\t\t<th width='50%' align='center' ><strong>" .$statlang->gT("Result")."</strong></th>\n" ."\t</tr></thead>\n"; foreach ($showem as $res) $statisticsoutput .= "<tr><td>".$res[0]."</td><td>".$res[1]."</td></tr>"; break; default: break; } } //N = numerical input //K = multiple numerical input elseif ($firstletter == "N" || $firstletter == "K") //NUMERICAL TYPE { //Zero handling if (!isset($excludezeros)) //If this hasn't been set, set it to on as default: { $excludezeros=1; } //check last character, greater/less/equals don't need special treatment if (substr($rt, -1) == "G" || substr($rt, -1) == "L" || substr($rt, -1) == "=") { //DO NOTHING } else { //create SGQ identifier list($qsid, $qgid, $qqid) = explode("X", $rt, 3); //multiple numerical input if($firstletter == "K") { // This is a multiple numerical question so we need to strip of the answer id to find the question title $tmpqid=substr($qqid, 0, strlen($qqid)-1); //did we get a valid ID? while (!in_array ($tmpqid,$legitqids)) $tmpqid=substr($tmpqid, 0, strlen($tmpqid)-1); //check lenght of ID $qidlength=strlen($tmpqid); //get answer ID from qid $qaid=substr($qqid, $qidlength, strlen($qqid)-$qidlength); //get question details from DB $nquery = "SELECT title, type, question, qid, parent_qid FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='".substr($qqid, 0, $qidlength)."' AND language='{$language}'"; $nresult = db_execute_num($nquery) or safe_die("Couldn't get text question<br />$nquery<br />".$connect->ErrorMsg()); } //probably question type "N" = numerical input else { //we can use the qqid without any editing $nquery = "SELECT title, type, question, qid, parent_qid FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'"; $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg()); } //loop through results while ($nrow=$nresult->FetchRow()) { $qtitle=FlattenText($nrow[0]); //clean up title $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]); $qiqid=$nrow[3]; $qlid=$nrow[4]; } //Get answer texts for multiple numerical if(substr($rt, 0, 1) == "K") { //get answer data $atext=$connect->GetOne("SELECT question FROM ".db_table_name("questions")." WHERE parent_qid='{$qiqid}' AND scale_id=0 AND title='{$qaid}' AND language='{$language}'"); //put single items in brackets at output $qtitle .= " [$atext]"; } //outputting switch($outputType) { case 'xls': $headXLS = array(); $tableXLS = array(); $footXLS = array(); $xlsTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8')); $xlsDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8'); ++$xlsRow; ++$xlsRow; ++$xlsRow; $sheet->write($xlsRow, 0,$xlsTitle); ++$xlsRow; $sheet->write($xlsRow, 0,$xlsDesc); $headXLS[] = array($statlang->gT("Calculation"),$statlang->gT("Result")); ++$xlsRow; $sheet->write($xlsRow, 0,$statlang->gT("Calculation")); $sheet->write($xlsRow, 1,$statlang->gT("Result")); break; case 'pdf': $headPDF = array(); $tablePDF = array(); $footPDF = array(); $pdfTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8')); $titleDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8'); $headPDF[] = array($statlang->gT("Calculation"),$statlang->gT("Result")); break; case 'html': $statisticsoutput .= "\n<table class='statisticstable' >\n" ."\t<thead><tr><th colspan='2' align='center'><strong>".sprintf($statlang->gT("Field summary for %s"),$qtitle).":</strong>" ."</th></tr>\n" ."\t<tr><th colspan='2' align='center'><strong>$qquestion</strong></th></tr>\n" ."\t<tr>\n\t\t<th width='50%' align='center' ><strong>" .$statlang->gT("Calculation")."</strong></th>\n" ."\t\t<th width='50%' align='center' ><strong>" .$statlang->gT("Result")."</strong></th>\n" ."\t</tr></thead>\n"; break; default: break; } //this field is queried using mathematical functions $fieldname=substr($rt, 1, strlen($rt)); //special treatment for MS SQL databases if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative') { //standard deviation $query = "SELECT STDEVP(".db_quote_id($fieldname)."*1) as stdev"; } //other databases (MySQL, Postgres) else { //standard deviation $query = "SELECT STDDEV(".db_quote_id($fieldname).") as stdev"; } //sum $query .= ", SUM(".db_quote_id($fieldname)."*1) as sum"; //average $query .= ", AVG(".db_quote_id($fieldname)."*1) as average"; //min $query .= ", MIN(".db_quote_id($fieldname)."*1) as minimum"; //max $query .= ", MAX(".db_quote_id($fieldname)."*1) as maximum"; //Only select responses where there is an actual number response, ignore nulls and empties (if these are included, they are treated as zeroes, and distort the deviation/mean calculations) //special treatment for MS SQL databases if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative') { //no NULL/empty values please $query .= " FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT NULL"; if(!$excludezeros) { //NO ZERO VALUES $query .= " AND (".db_quote_id($fieldname)." <> 0)"; } } //other databases (MySQL, Postgres) else { //no NULL/empty values please $query .= " FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT NULL"; if(!$excludezeros) { //NO ZERO VALUES $query .= " AND (".db_quote_id($fieldname)." != 0)"; } } //filter incomplete answers if set if (incompleteAnsFilterstate() == "inc") {$query .= " AND submitdate is null";} elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND submitdate is not null";} //$sql was set somewhere before if ($sql != "NULL") {$query .= " AND $sql";} //execute query $result=db_execute_assoc($query) or safe_die("Couldn't do maths testing<br />$query<br />".$connect->ErrorMsg()); //get calculated data while ($row=$result->FetchRow()) { //put translation of mean and calculated data into $showem array $showem[]=array($statlang->gT("Sum"), $row['sum']); $showem[]=array($statlang->gT("Standard deviation"), round($row['stdev'],2)); $showem[]=array($statlang->gT("Average"), round($row['average'],2)); $showem[]=array($statlang->gT("Minimum"), $row['minimum']); //Display the maximum and minimum figures after the quartiles for neatness $maximum=$row['maximum']; $minimum=$row['minimum']; } //CALCULATE QUARTILES //get data $query ="SELECT ".db_quote_id($fieldname)." FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT null"; //NO ZEROES if(!$excludezeros) { $query .= " AND ".db_quote_id($fieldname)." != 0"; } //filtering enabled? if (incompleteAnsFilterstate() == "inc") {$query .= " AND submitdate is null";} elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND submitdate is not null";} //if $sql values have been passed to the statistics script from another script, incorporate them if ($sql != "NULL") {$query .= " AND $sql";} //execute query $result=$connect->Execute($query) or safe_die("Disaster during median calculation<br />$query<br />".$connect->ErrorMsg()); $querystarter="SELECT ".db_quote_id($fieldname)." FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT null"; //No Zeroes if(!$excludezeros) { $querystart .= " AND ".db_quote_id($fieldname)." != 0"; } //filtering enabled? if (incompleteAnsFilterstate() == "inc") {$querystarter .= " AND submitdate is null";} elseif (incompleteAnsFilterstate() == "filter") {$querystarter .= " AND submitdate is not null";} //if $sql values have been passed to the statistics script from another script, incorporate them if ($sql != "NULL") {$querystarter .= " AND $sql";} //we just count the number of records returned $medcount=$result->RecordCount(); //put the total number of records at the beginning of this array array_unshift($showem, array($statlang->gT("Count"), $medcount)); //no more comment from Mazi regarding the calculation // Calculating only makes sense with more than one result if ($medcount>1) { //1ST QUARTILE (Q1) $q1=(1/4)*($medcount+1); $q1b=(int)((1/4)*($medcount+1)); $q1c=$q1b-1; $q1diff=$q1-$q1b; $total=0; // fix if there are too few values to evaluate. if ($q1c<0) {$q1c=0;} if ($q1 != $q1b) { //ODD NUMBER $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 "; $result=db_select_limit_assoc($query, 2, $q1c) or safe_die("1st Quartile query failed<br />".$connect->ErrorMsg()); while ($row=$result->FetchRow()) { if ($total == 0) {$total=$total-$row[$fieldname];} else {$total=$total+$row[$fieldname];} $lastnumber=$row[$fieldname]; } $q1total=$lastnumber-((1-$q1diff)*$total); if ($q1total < $minimum) {$q1total=$minimum;} $showem[]=array($statlang->gT("1st quartile (Q1)"), $q1total); } else { //EVEN NUMBER $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 "; $result=db_select_limit_assoc($query,1, $q1c) or safe_die ("1st Quartile query failed<br />".$connect->ErrorMsg()); while ($row=$result->FetchRow()) { $showem[]=array($statlang->gT("1st quartile (Q1)"), $row[$fieldname]); } } $total=0; //MEDIAN (Q2) $median=(1/2)*($medcount+1); $medianb=(int)((1/2)*($medcount+1)); $medianc=$medianb-1; $mediandiff=$median-$medianb; if ($median != $medianb) { //remainder $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 "; $result=db_select_limit_assoc($query,2, $medianc) or safe_die("What a complete mess with the remainder<br />$query<br />".$connect->ErrorMsg()); while ( $row=$result->FetchRow()) {$total=$total+$row[$fieldname]; } $showem[]=array($statlang->gT("2nd quartile (Median)"), $total/2); } else { //EVEN NUMBER $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 "; $result=db_select_limit_assoc($query,1, $medianc-1) or safe_die("What a complete mess<br />$query<br />".$connect->ErrorMsg()); while ($row=$result->FetchRow()) { $showem[]=array($statlang->gT("Median value"), $row[$fieldname]); } } $total=0; //3RD QUARTILE (Q3) $q3=(3/4)*($medcount+1); $q3b=(int)((3/4)*($medcount+1)); $q3c=$q3b-1; $q3diff=$q3-$q3b; if ($q3 != $q3b) { $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 "; $result = db_select_limit_assoc($query,2,$q3c) or safe_die("3rd Quartile query failed<br />".$connect->ErrorMsg()); while ($row=$result->FetchRow()) { if ($total == 0) {$total=$total-$row[$fieldname];} else {$total=$total+$row[$fieldname];} $lastnumber=$row[$fieldname]; } $q3total=$lastnumber-((1-$q3diff)*$total); if ($q3total < $maximum) {$q1total=$maximum;} $showem[]=array($statlang->gT("3rd quartile (Q3)"), $q3total); } else { $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1"; $result = db_select_limit_assoc($query,1, $q3c) or safe_die("3rd Quartile even query failed<br />".$connect->ErrorMsg()); while ($row=$result->FetchRow()) { $showem[]=array($statlang->gT("3rd quartile (Q3)"), $row[$fieldname]); } } $total=0; $showem[]=array($statlang->gT("Maximum"), $maximum); //output results foreach ($showem as $shw) { switch($outputType) { case 'xls': ++$xlsRow; $sheet->write($xlsRow, 0,html_entity_decode($shw[0],ENT_QUOTES,'UTF-8')); $sheet->write($xlsRow, 1,html_entity_decode($shw[1],ENT_QUOTES,'UTF-8')); $tableXLS[] = array($shw[0],$shw[1]); break; case 'pdf': $tablePDF[] = array(html_entity_decode($shw[0],ENT_QUOTES,'UTF-8'),html_entity_decode($shw[1],ENT_QUOTES,'UTF-8')); break; case 'html': $statisticsoutput .= "\t<tr>\n" ."\t\t<td align='center' >$shw[0]</td>\n" ."\t\t<td align='center' >$shw[1]</td>\n" ."\t</tr>\n"; break; default: break; } } switch($outputType) { case 'xls': ++$xlsRow; $sheet->write($xlsRow, 0,$statlang->gT("Null values are ignored in calculations")); ++$xlsRow; $sheet->write($xlsRow, 0,sprintf($statlang->gT("Q1 and Q3 calculated using %s"), $statlang->gT("minitab method"))); $footXLS[] = array($statlang->gT("Null values are ignored in calculations")); $footXLS[] = array(sprintf($statlang->gT("Q1 and Q3 calculated using %s"), $statlang->gT("minitab method"))); break; case 'pdf': $footPDF[] = array($statlang->gT("Null values are ignored in calculations")); $footPDF[] = array(sprintf($statlang->gT("Q1 and Q3 calculated using %s"), "<a href='http://mathforum.org/library/drmath/view/60969.html' target='_blank'>".$statlang->gT("minitab method")."</a>")); $pdf->addPage('P','A4'); $pdf->Bookmark($pdf->delete_html($qquestion), 1, 0); $pdf->titleintopdf($pdfTitle,$titleDesc); $pdf->headTable($headPDF, $tablePDF); $pdf->tablehead($footPDF); break; case 'html': //footer of question type "N" $statisticsoutput .= "\t<tr>\n" ."\t\t<td colspan='4' align='center' bgcolor='#EEEEEE'>\n" ."\t\t\t<font size='1'>".$statlang->gT("Null values are ignored in calculations")."<br />\n" ."\t\t\t".sprintf($statlang->gT("Q1 and Q3 calculated using %s"), "<a href='http://mathforum.org/library/drmath/view/60969.html' target='_blank'>".$statlang->gT("minitab method")."</a>") ."</font>\n" ."\t\t</td>\n" ."\t</tr>\n</table>\n"; break; default: break; } //clean up unset($showem); } //end if (enough results?) //not enough (<1) results for calculation else { switch($outputType) { case 'xls': $tableXLS = array(); $tableXLS[] = array($statlang->gT("Not enough values for calculation")); ++$xlsRow; $sheet->write($xlsRow, 0, $statlang->gT("Not enough values for calculation")); break; case 'pdf': $tablePDF = array(); $tablePDF[] = array($statlang->gT("Not enough values for calculation")); $pdf->addPage('P','A4'); $pdf->Bookmark($pdf->delete_html($qquestion), 1, 0); $pdf->titleintopdf($pdfTitle,$titleDesc); $pdf->equalTable($tablePDF); break; case 'html': //output $statisticsoutput .= "\t<tr>\n" ."\t\t<td align='center' colspan='4'>".$statlang->gT("Not enough values for calculation")."</td>\n" ."\t</tr>\n</table><br />\n"; break; default: break; } unset($showem); } } //end else -> check last character, greater/less/equals don't need special treatment } //end else-if -> multiple numerical types //is there some "id", "datestamp" or "D" within the type? elseif (substr($rt, 0, 2) == "id" || substr($rt, 0, 9) == "datestamp" || ($firstletter == "D")) { /* * DON'T show anything for date questions * because there aren't any statistics implemented yet! * * See bug report #2539 and * feature request #2620 */ } // NICE SIMPLE SINGLE OPTION ANSWERS else { //search for key $fielddata=$fieldmap[$rt]; //print_r($fielddata); //get SGQA IDs $qsid=$fielddata['sid']; $qgid=$fielddata['gid']; $qqid=$fielddata['qid']; $qanswer=$fielddata['aid']; //question type $qtype=$fielddata['type']; //question string $qastring=$fielddata['question']; //question ID $rqid=$qqid; //get question data $nquery = "SELECT title, type, question, qid, parent_qid, other FROM ".db_table_name("questions")." WHERE qid='{$rqid}' AND parent_qid=0 and language='{$language}'"; $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg()); //loop though question data while ($nrow=$nresult->FetchRow()) { $qtitle=FlattenText($nrow[0]); $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]); $qiqid=$nrow[3]; $qparentqid=$nrow[4]; $qother=$nrow[5]; } //check question types switch($qtype) { //Array of 5 point choices (several items to rank!) case "A": //get data $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details (Array 5p Q)<br />$qquery<br />".$connect->ErrorMsg()); //loop through results while ($qrow=$qresult->FetchRow()) { //5-point array for ($i=1; $i<=5; $i++) { //add data $alist[]=array("$i", "$i"); } //add counter $atext=FlattenText($qrow[1]); } //list IDs and answer codes in brackets $qquestion .= $linefeed."[".$atext."]"; $qtitle .= "($qanswer)"; break; //Array of 10 point choices //same as above just with 10 items case "B": $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details (Array 10p Q)<br />$qquery<br />".$connect->ErrorMsg()); while ($qrow=$qresult->FetchRow()) { for ($i=1; $i<=10; $i++) { $alist[]=array("$i", "$i"); } $atext=FlattenText($qrow[1]); } $qquestion .= $linefeed."[".$atext."]"; $qtitle .= "($qanswer)"; break; //Array of Yes/No/$statlang->gT("Uncertain") case "C": $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details<br />$qquery<br />".$connect->ErrorMsg()); //loop thorugh results while ($qrow=$qresult->FetchRow()) { //add results $alist[]=array("Y", $statlang->gT("Yes")); $alist[]=array("N", $statlang->gT("No")); $alist[]=array("U", $statlang->gT("Uncertain")); $atext=FlattenText($qrow[1]); } //output $qquestion .= $linefeed."[".$atext."]"; $qtitle .= "($qanswer)"; break; //Array of Yes/No/$statlang->gT("Uncertain") //same as above case "E": $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details<br />$qquery<br />".$connect->ErrorMsg()); while ($qrow=$qresult->FetchRow()) { $alist[]=array("I", $statlang->gT("Increase")); $alist[]=array("S", $statlang->gT("Same")); $alist[]=array("D", $statlang->gT("Decrease")); $atext=FlattenText($qrow[1]); } $qquestion .= $linefeed."[".$atext."]"; $qtitle .= "($qanswer)"; break; case ";": //Array (Multi Flexi) (Text) list($qacode, $licode)=explode("_", $qanswer); $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qacode' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or die ("Couldn't get answer details<br />$qquery<br />".$connect->ErrorMsg()); while ($qrow=$qresult->FetchRow()) { $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid='{$qiqid}' AND scale_id=0 AND code = '{$licode}' AND language='{$language}'ORDER BY sortorder, code"; $fresult = db_execute_assoc($fquery); while ($frow=$fresult->FetchRow()) { $alist[]=array($frow['code'], $frow['answer']); $ltext=$frow['answer']; } $atext=FlattenText($qrow[1]); } $qquestion .= $linefeed."[".$atext."] [".$ltext."]"; $qtitle .= "($qanswer)"; break; case ":": //Array (Multiple Flexi) (Numbers) $qidattributes=getQuestionAttributes($qiqid); if (trim($qidattributes['multiflexible_max'])!='') { $maxvalue=$qidattributes['multiflexible_max']; } else { $maxvalue=10; } if (trim($qidattributes['multiflexible_min'])!='') { $minvalue=$qidattributes['multiflexible_min']; } else { $minvalue=1; } if (trim($qidattributes['multiflexible_step'])!='') { $stepvalue=$qidattributes['multiflexible_step']; } else { $stepvalue=1; } if ($qidattributes['multiflexible_checkbox']!=0) { $minvalue=0; $maxvalue=1; $stepvalue=1; } for($i=$minvalue; $i<=$maxvalue; $i+=$stepvalue) { $alist[]=array($i, $i); } $qquestion .= $linefeed."[".$fielddata['subquestion1']."] [".$fielddata['subquestion2']."]"; list($myans, $mylabel)=explode("_", $qanswer); $qtitle .= "[$myans][$mylabel]"; break; case "F": //Array of Flexible case "H": //Array of Flexible by Column $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details<br />$qquery<br />".$connect->ErrorMsg()); //loop through answers while ($qrow=$qresult->FetchRow()) { //this question type uses its own labels $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid='{$qiqid}' AND scale_id=0 AND language='{$language}'ORDER BY sortorder, code"; $fresult = db_execute_assoc($fquery); //add code and title to results for outputting them later while ($frow=$fresult->FetchRow()) { $alist[]=array($frow['code'], FlattenText($frow['answer'])); } //counter $atext=FlattenText($qrow[1]); } //output $qquestion .= $linefeed."[".$atext."]"; $qtitle .= "($qanswer)"; break; case "G": //Gender $alist[]=array("F", $statlang->gT("Female")); $alist[]=array("M", $statlang->gT("Male")); break; case "Y": //Yes\No $alist[]=array("Y", $statlang->gT("Yes")); $alist[]=array("N", $statlang->gT("No")); break; case "I": //Language // Using previously defined $surveylanguagecodes array of language codes foreach ($surveylanguagecodes as $availlang) { $alist[]=array($availlang, getLanguageNameFromCode($availlang,false)); } break; case "5": //5 Point (just 1 item to rank!) for ($i=1; $i<=5; $i++) { $alist[]=array("$i", "$i"); } break; case "1": //array (dual scale) $sSubquestionQuery = "SELECT question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order"; $sSubquestion=FlattenText($connect->GetOne($sSubquestionQuery)); //get question attributes $qidattributes=getQuestionAttributes($qqid); //check last character -> label 1 if (substr($rt,-1,1) == 0) { //get label 1 $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid='{$qqid}' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, code"; //header available? if (trim($qidattributes['dualscale_headerA'])!='') { //output $labelheader= "[".$qidattributes['dualscale_headerA']."]"; } //no header else { $labelheader =''; } //output $labelno = sprintf($clang->gT('Label %s'),'1'); } //label 2 else { //get label 2 $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid='{$qqid}' AND scale_id=1 AND language='{$language}' ORDER BY sortorder, code"; //header available? if (trim($qidattributes['dualscale_headerB'])!='') { //output $labelheader= "[".$qidattributes['dualscale_headerB']."]"; } //no header else { $labelheader =''; } //output $labelno = sprintf($clang->gT('Label %s'),'2'); } //get data $fresult = db_execute_assoc($fquery); //put label code and label title into array while ($frow=$fresult->FetchRow()) { $alist[]=array($frow['code'], FlattenText($frow['answer'])); } //adapt title and question $qtitle = $qtitle." [".$sSubquestion."][".$labelno."]"; $qquestion = $qastring .$labelheader; break; default: //default handling //get answer code and title $qquery = "SELECT code, answer FROM ".db_table_name("answers")." WHERE qid='$qqid' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer"; $qresult = db_execute_num($qquery) or safe_die ("Couldn't get answers list<br />$qquery<br />".$connect->ErrorMsg()); //put answer code and title into array while ($qrow=$qresult->FetchRow()) { $alist[]=array("$qrow[0]", FlattenText($qrow[1])); } //handling for "other" field for list radio or list drowpdown if ((($qtype == "L" || $qtype == "!") && $qother == "Y")) { //add "other" $alist[]=array($statlang->gT("Other"),$statlang->gT("Other"),$fielddata['fieldname'].'other'); } if ( $qtype == "O") { //add "comment" $alist[]=array($statlang->gT("Comments"),$statlang->gT("Comments"),$fielddata['fieldname'].'comment'); } } //end switch question type //moved because it's better to have "no answer" at the end of the list instead of the beginning //put data into array $alist[]=array("", $statlang->gT("No answer")); } //end else -> single option answers //foreach ($alist as $al) {$statisticsoutput .= "$al[0] - $al[1]<br />";} //debugging line //foreach ($fvalues as $fv) {$statisticsoutput .= "$fv | ";} //debugging line //2. Collect and Display results ####################################################################### if (isset($alist) && $alist) //Make sure there really is an answerlist, and if so: { // this will count the answers considered completed $TotalCompleted = 0; switch($outputType) { case 'xls': $xlsTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8')); $xlsDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8'); ++$xlsRow; ++$xlsRow; ++$xlsRow; $sheet->write($xlsRow, 0,$xlsTitle); ++$xlsRow; $sheet->write($xlsRow, 0,$xlsDesc); $tableXLS = array(); $footXLS = array(); break; case 'pdf': $sPDFQuestion=FlattenText($qquestion,true); $pdfTitle = $pdf->delete_html(sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8'))); $titleDesc = $sPDFQuestion; $pdf->addPage('P','A4'); $pdf->Bookmark($sPDFQuestion, 1, 0); $pdf->titleintopdf($pdfTitle,$sPDFQuestion); $tablePDF = array(); $footPDF = array(); break; case 'html': //output $statisticsoutput .= "<table class='statisticstable'>\n" ."\t<thead><tr><th colspan='4' align='center'><strong>" //headline .sprintf($statlang->gT("Field summary for %s"),$qtitle)."</strong>" ."</th></tr>\n" ."\t<tr><th colspan='4' align='center'><strong>" //question title .$qquestion."</strong></th></tr>\n" ."\t<tr>\n\t\t<th width='50%' align='center' >"; break; default: break; } echo ''; //loop thorugh the array which contains all answer data foreach ($alist as $al) { //picks out alist that come from the multiple list above if (isset($al[2]) && $al[2]) { //handling for "other" option if ($al[0] == $statlang->gT("Other")) { if($qtype=='!' || $qtype=='L') { // It is better for single choice question types to filter on the number of '-oth-' entries, than to // just count the number of 'other' values - that way with failing Javascript the statistics don't get messed up $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id(substr($al[2],0,strlen($al[2])-5))."='-oth-'"; } else { //get data $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE "; $query .= ($connect->databaseType == "mysql")? db_quote_id($al[2])." != ''" : "NOT (".db_quote_id($al[2])." LIKE '')"; } } /* * text questions: * * U = huge free text * T = long free text * S = short free text * Q = multiple short text */ elseif ($qtype == "U" || $qtype == "T" || $qtype == "S" || $qtype == "Q" || $qtype == ";") { //free text answers if($al[0]=="Answers") { $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE "; $query .= ($connect->databaseType == "mysql")? db_quote_id($al[2])." != ''" : "NOT (".db_quote_id($al[2])." LIKE '')"; } //"no answer" handling elseif($al[0]=="NoAnswer") { $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ( "; $query .= ($connect->databaseType == "mysql")? db_quote_id($al[2])." = '')" : " (".db_quote_id($al[2])." LIKE ''))"; } } elseif ($qtype == "O") { $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ( "; $query .= ($connect->databaseType == "mysql")? db_quote_id($al[2])." <> '')" : " (".db_quote_id($al[2])." NOT LIKE ''))"; // all other question types } else { $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($al[2])." ="; //ranking question? if (substr($rt, 0, 1) == "R") { $query .= " '$al[0]'"; } else { $query .= " 'Y'"; } } } //end if -> alist set else { if ($al[0] != "") { //get more data if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative') { // mssql cannot compare text blobs so we have to cast here $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE cast(".db_quote_id($rt)." as varchar)= '$al[0]'"; } else $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($rt)." = '$al[0]'"; } else { // This is for the 'NoAnswer' case // We need to take into account several possibilities // * NoAnswer cause the participant clicked the NoAnswer radio // ==> in this case value is '' or ' ' // * NoAnswer in text field // ==> value is '' // * NoAnswer due to conditions, or a page not displayed // ==> value is NULL if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative') { // mssql cannot compare text blobs so we have to cast here //$query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE (".db_quote_id($rt)." IS NULL " $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ( " // . "OR cast(".db_quote_id($rt)." as varchar) = '' " . "cast(".db_quote_id($rt)." as varchar) = '' " . "OR cast(".db_quote_id($rt)." as varchar) = ' ' )"; } else // $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE (".db_quote_id($rt)." IS NULL " $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ( " // . "OR ".db_quote_id($rt)." = '' " . " ".db_quote_id($rt)." = '' " . "OR ".db_quote_id($rt)." = ' ') "; } } //check filter option if (incompleteAnsFilterstate() == "inc") {$query .= " AND submitdate is null";} elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND submitdate is not null";} //check for any "sql" that has been passed from another script if ($sql != "NULL") {$query .= " AND $sql";} //get data $result=db_execute_num($query) or safe_die ("Couldn't do count of values<br />$query<br />".$connect->ErrorMsg()); // $statisticsoutput .= "\n<!-- ($sql): $query -->\n\n"; // this just extracts the data, after we present while ($row=$result->FetchRow()) { //increase counter $TotalCompleted += $row[0]; //"no answer" handling if ($al[0] === "") {$fname=$statlang->gT("No answer");} //"other" handling //"Answers" means that we show an option to list answer to "other" text field elseif ($al[0] === $statlang->gT("Other") || $al[0] === "Answers" || ($qtype === "O" && $al[0] === $statlang->gT("Comments")) || $qtype === "P") { if ($qtype == "P" ) $ColumnName_RM = $al[2]."comment"; else $ColumnName_RM = $al[2]; if ($qtype=='O') { $TotalCompleted -=$row[0]; } $fname="$al[1]"; if ($browse===true) $fname .= " <input type='button' value='".$statlang->gT("Browse")."' onclick=\"window.open('admin.php?action=listcolumn&sid=$surveyid&column=$ColumnName_RM&sql=".urlencode($sql)."', 'results', 'width=460, height=500, left=50, top=50, resizable=yes, scrollbars=yes, menubar=no, status=no, location=no, toolbar=no')\" />"; } /* * text questions: * * U = huge free text * T = long free text * S = short free text * Q = multiple short text */ elseif ($qtype == "S" || $qtype == "U" || $qtype == "T" || $qtype == "Q") { $headPDF = array(); $headPDF[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage")); //show free text answers if ($al[0] == "Answers") { $fname= "$al[1]"; if ($browse===true) $fname .= " <input type='submit' value='" . $statlang->gT("Browse")."' onclick=\"window.open('admin.php?action=listcolumn&sid=$surveyid&column=$al[2]&sql=" . urlencode($sql)."', 'results', 'width=460, height=500, left=50, top=50, resizable=yes, scrollbars=yes, menubar=no, status=no, location=no, toolbar=no')\" />"; } elseif ($al[0] == "NoAnswer") { $fname= "$al[1]"; } $statisticsoutput .= "</th>\n" ."\t\t<th width='25%' align='center' >" ."<strong>".$statlang->gT("Count")."</strong></th>\n" ."\t\t<th width='25%' align='center' >" ."<strong>".$statlang->gT("Percentage")."</strong></th>\n" ."\t</tr></thead>\n"; } //check if aggregated results should be shown elseif (isset($showaggregateddata) && $showaggregateddata == 1) { if(!isset($showheadline) || $showheadline != false) { if($qtype == "5" || $qtype == "A") { switch($outputType) { case 'xls': $headXLS = array(); $headXLS[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage"),$statlang->gT("Sum")); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Answer")); $sheet->write($xlsRow,1,$statlang->gT("Count")); $sheet->write($xlsRow,2,$statlang->gT("Percentage")); $sheet->write($xlsRow,3,$statlang->gT("Sum")); break; case 'pdf': $headPDF = array(); $headPDF[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage"),$statlang->gT("Sum")); break; case 'html': //four columns $statisticsoutput .= "<strong>".$statlang->gT("Answer")."</strong></th>\n" ."\t\t<th width='15%' align='center' >" ."<strong>".$statlang->gT("Count")."</strong></th>\n" ."\t\t<th width='20%' align='center' >" ."<strong>".$statlang->gT("Percentage")."</strong></th>\n" ."\t\t<th width='15%' align='center' >" ."<strong>".$statlang->gT("Sum")."</strong></th>\n" ."\t</tr></thead>\n"; break; default: break; } $showheadline = false; } else { switch($outputType) { case 'xls': $headXLS = array(); $headXLS[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage")); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Answer")); $sheet->write($xlsRow,1,$statlang->gT("Count")); $sheet->write($xlsRow,2,$statlang->gT("Percentage")); break; case 'pdf': $headPDF = array(); $headPDF[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage")); break; case 'html': //three columns $statisticsoutput .= "<strong>".$statlang->gT("Answer")."</strong></td>\n" ."\t\t<th width='25%' align='center' >" ."<strong>".$statlang->gT("Count")."</strong></th>\n" ."\t\t<th width='25%' align='center' >" ."<strong>".$statlang->gT("Percentage")."</strong></th>\n" ."\t</tr></thead>\n"; break; default: break; } $showheadline = false; } } //text for answer column is always needed $fname="$al[1] ($al[0])"; //these question types get special treatment by $showaggregateddata if($qtype == "5" || $qtype == "A") { //put non-edited data in here because $row will be edited later $grawdata[]=$row[0]; $showaggregated_indice=count($grawdata) - 1; $showaggregated_indice_table[$showaggregated_indice]="aggregated"; $showaggregated_indice=-1; //keep in mind that we already added data (will be checked later) $justadded = true; //we need a counter because we want to sum up certain values //reset counter if 5 items have passed if(!isset($testcounter) || $testcounter >= 4) { $testcounter = 0; } else { $testcounter++; } //beside the known percentage value a new aggregated value should be shown //therefore this item is marked in a certain way if($testcounter == 0 ) //add 300 to original value { //HACK: add three times the total number of results to the value //This way we get a 300 + X percentage which can be checked later $row[0] += (3*$results); } //the third value should be shown twice later -> mark it if($testcounter == 2) //add 400 to original value { //HACK: add four times the total number of results to the value //This way there should be a 400 + X percentage which can be checked later $row[0] += (4*$results); } //the last value aggregates the data of item 4 + item 5 later if($testcounter == 4 ) //add 200 to original value { //HACK: add two times the total number of results to the value //This way there should be a 200 + X percentage which can be checked later $row[0] += (2*$results); } } //end if -> question type = "5"/"A" } //end if -> show aggregated data //handling what's left else { if(!isset($showheadline) || $showheadline != false) { switch($outputType) { case 'xls': $headXLS = array(); $headXLS[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage")); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Answer")); $sheet->write($xlsRow,1,$statlang->gT("Count")); $sheet->write($xlsRow,2,$statlang->gT("Percentage")); break; case 'pdf': $headPDF = array(); $headPDF[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage")); break; case 'html': //three columns $statisticsoutput .= "<strong>".$statlang->gT("Answer")."</strong></th>\n" ."\t\t<th width='25%' align='center' >" ."<strong>".$statlang->gT("Count")."</strong></th>\n" ."\t\t<th width='25%' align='center' >" ."<strong>".$statlang->gT("Percentage")."</strong></th>\n" ."\t</tr></thead>\n"; break; default: break; } $showheadline = false; } //answer text $fname="$al[1] ($al[0])"; } //are there some results to play with? if ($results > 0) { //calculate percentage $gdata[] = ($row[0]/$results)*100; } //no results else { //no data! $gdata[] = "N/A"; } //only add this if we don't handle question type "5"/"A" if(!isset($justadded)) { //put absolute data into array $grawdata[]=$row[0]; } else { //unset to handle "no answer" data correctly unset($justadded); } //put question title and code into array $label[]=$fname; //put only the code into the array $justcode[]=$al[0]; //edit labels and put them into antoher array $lbl[] = wordwrap(FlattenText("$al[1] ($row[0])"), 25, "\n"); // NMO 2009-03-24 $lblrtl[] = utf8_strrev(wordwrap(FlattenText("$al[1] )$row[0]("), 25, "\n")); // NMO 2009-03-24 } //end while -> loop through results } //end foreach -> loop through answer data //no filtering of incomplete answers and NO multiple option questions //if ((incompleteAnsFilterstate() != "filter") and ($qtype != "M") and ($qtype != "P")) //error_log("TIBO ".print_r($showaggregated_indice_table,true)); if (($qtype != "M") and ($qtype != "P")) { //is the checkbox "Don't consider NON completed responses (only works when Filter incomplete answers is Disable)" checked? //if (isset($_POST["noncompleted"]) and ($_POST["noncompleted"] == "on") && (isset($showaggregateddata) && $showaggregateddata == 0)) // TIBO: TODO WE MUST SKIP THE FOLLOWING SECTION FOR TYPE A and 5 when // showaggreagated data is set and set to 1 if (isset($_POST["noncompleted"]) and ($_POST["noncompleted"] == "on") ) { //counter $i=0; while (isset($gdata[$i])) { if (isset($showaggregated_indice_table[$i]) && $showaggregated_indice_table[$i]=="aggregated") { // do nothing, we don't rewrite aggregated results // or at least I don't know how !!! (lemeur) } else { //we want to have some "real" data here if ($gdata[$i] != "N/A") { //calculate percentage $gdata[$i] = ($grawdata[$i]/$TotalCompleted)*100; } } //increase counter $i++; } //end while (data available) } //end if -> noncompleted checked //noncompleted is NOT checked else { //calculate total number of incompleted records $TotalIncomplete = $results - $TotalCompleted; //output if ((incompleteAnsFilterstate() != "filter")) { $fname=$statlang->gT("Not completed or Not displayed"); } else { $fname=$statlang->gT("Not displayed"); } //we need some data if ($results > 0) { //calculate percentage $gdata[] = ($TotalIncomplete/$results)*100; } //no data :( else { $gdata[] = "N/A"; } //put data of incompleted records into array $grawdata[]=$TotalIncomplete; //put question title ("Not completed") into array $label[]= $fname; //put the code ("Not completed") into the array $justcode[]=$fname; //edit labels and put them into antoher array if ((incompleteAnsFilterstate() != "filter")) { $lbl[] = wordwrap(FlattenText($statlang->gT("Not completed or Not displayed")." ($TotalIncomplete)"), 20, "\n"); // NMO 2009-03-24 } else { $lbl[] = wordwrap(FlattenText($statlang->gT("Not displayed")." ($TotalIncomplete)"), 20, "\n"); // NMO 2009-03-24 } } //end else -> noncompleted NOT checked } //end if -> no filtering of incomplete answers and no multiple option questions //counter $i=0; //we need to know which item we are editing $itemcounter = 1; //array to store items 1 - 5 of question types "5" and "A" $stddevarray = array(); //loop through all available answers while (isset($gdata[$i])) { //repeat header (answer, count, ...) for each new question unset($showheadline); /* * there are 3 colums: * * 1 (50%) = answer (title and code in brackets) * 2 (25%) = count (absolute) * 3 (25%) = percentage */ $statisticsoutput .= "\t<tr>\n\t\t<td align='center' >" . $label[$i] ."\n" ."\t\t</td>\n" //output absolute number of records ."\t\t<td align='center' >" . $grawdata[$i] . "\n</td>"; //no data if ($gdata[$i] == "N/A") { switch($outputType) { case 'xls': $label[$i]=FlattenText($label[$i]); $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $gdata[$i]). "%"); ++$xlsRow; $sheet->write($xlsRow,0,$label[$i]); $sheet->write($xlsRow,1,$grawdata[$i]); $sheet->write($xlsRow,2,sprintf("%01.2f", $gdata[$i]). "%"); break; case 'pdf': $tablePDF[] = array(FlattenText($label[$i]),$grawdata[$i],sprintf("%01.2f", $gdata[$i]). "%", ""); break; case 'html': //output when having no data $statisticsoutput .= "\t\t<td align='center' >"; //percentage = 0 $statisticsoutput .= sprintf("%01.2f", $gdata[$i]) . "%"; $gdata[$i] = 0; //check if we have to adjust ouput due to $showaggregateddata setting if(isset($showaggregateddata) && $showaggregateddata == 1 && ($qtype == "5" || $qtype == "A")) { $statisticsoutput .= "\t\t</td>"; } elseif ($qtype == "S" || $qtype == "U" || $qtype == "T" || $qtype == "Q") { $statisticsoutput .= "</td>\n\t</tr>\n"; } break; default: break; } } //data available else { //check if data should be aggregated if(isset($showaggregateddata) && $showaggregateddata == 1 && ($qtype == "5" || $qtype == "A")) { //mark that we have done soemthing special here $aggregated = true; //just calculate everything once. the data is there in the array if($itemcounter == 1) { //there are always 5 answers for($x = 0; $x < 5; $x++) { //put 5 items into array for further calculations array_push($stddevarray, $grawdata[$x]); } } //"no answer" & items 2 / 4 - nothing special to do here, just adjust output if($gdata[$i] <= 100) { if($itemcounter == 2 && $label[$i+4] == $statlang->gT("No answer")) { //prevent division by zero if(($results - $grawdata[$i+4]) > 0) { //re-calculate percentage $percentage = ($grawdata[$i] / ($results - $grawdata[$i+4])) * 100; } else { $percentage = 0; } } elseif($itemcounter == 4 && $label[$i+2] == $statlang->gT("No answer")) { //prevent division by zero if(($results - $grawdata[$i+2]) > 0) { //re-calculate percentage $percentage = ($grawdata[$i] / ($results - $grawdata[$i+2])) * 100; } else { $percentage = 0; } } else { $percentage = $gdata[$i]; } switch($outputType) { case 'xls': $label[$i]=FlattenText($label[$i]); $tableXLS[]= array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%"); ++$xlsRow; $sheet->write($xlsRow,0,$label[$i]); $sheet->write($xlsRow,1,$grawdata[$i]); $sheet->write($xlsRow,2,sprintf("%01.2f", $percentage)."%"); break; case 'pdf': $label[$i]=FlattenText($label[$i]); $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%", ""); break; case 'html': //output $statisticsoutput .= "\t\t<td align='center'>"; //output percentage $statisticsoutput .= sprintf("%01.2f", $percentage) . "%"; //adjust output $statisticsoutput .= "\t\t</td>"; break; default: break; } } //item 3 - just show results twice //old: if($gdata[$i] >= 400) //trying to fix bug #2583: if($gdata[$i] >= 400 && $i != 0) { //remove "400" which was added before $gdata[$i] -= 400; if($itemcounter == 3 && $label[$i+3] == $statlang->gT("No answer")) { //prevent division by zero if(($results - $grawdata[$i+3]) > 0) { //re-calculate percentage $percentage = ($grawdata[$i] / ($results - $grawdata[$i+3])) * 100; } else { $percentage = 0; } } else { //get the original percentage $percentage = $gdata[$i]; } switch($outputType) { case 'xls': $label[$i]=FlattenText($label[$i]); $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $percentage)."%"); ++$xlsRow; $sheet->write($xlsRow,0,$label[$i]); $sheet->write($xlsRow,1,$grawdata[$i]); $sheet->write($xlsRow,2,sprintf("%01.2f", $percentage)."%"); $sheet->write($xlsRow,3,sprintf("%01.2f", $percentage)."%"); break; case 'pdf': $label[$i]=FlattenText($label[$i]); $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $percentage)."%"); break; case 'html': //output percentage $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>"; //output again (no real aggregation here) $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $percentage)."%"; $statisticsoutput .= "</td>\t\t"; break; default: break; } } //FIRST value -> add percentage of item 1 + item 2 //old: if($gdata[$i] >= 300 && $gdata[$i] < 400) //trying to fix bug #2583: if(($gdata[$i] >= 300 && $gdata[$i] < 400) || ($i == 0 && $gdata[$i] <= 400)) { //remove "300" which was added before $gdata[$i] -= 300; if($itemcounter == 1 && $label[$i+5] == $statlang->gT("No answer")) { //prevent division by zero if(($results - $grawdata[$i+5]) > 0) { //re-calculate percentage $percentage = ($grawdata[$i] / ($results - $grawdata[$i+5])) * 100; $percentage2 = ($grawdata[$i + 1] / ($results - $grawdata[$i+5])) * 100; } else { $percentage = 0; $percentage2 = 0; } } else { $percentage = $gdata[$i]; $percentage2 = $gdata[$i+1]; } //percentage of item 1 + item 2 $aggregatedgdata = $percentage + $percentage2; switch($outputType) { case 'xls': $label[$i]=FlattenText($label[$i]); $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $aggregatedgdata)."%"); ++$xlsRow; $sheet->write($xlsRow,0,$label[$i]); $sheet->write($xlsRow,1,$grawdata[$i]); $sheet->write($xlsRow,2,sprintf("%01.2f", $percentage)."%"); $sheet->write($xlsRow,3,sprintf("%01.2f", $aggregatedgdata)."%"); break; case 'pdf': $label[$i]=FlattenText($label[$i]); $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $aggregatedgdata)."%"); break; case 'html': //output percentage $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>"; //output aggregated data $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $aggregatedgdata)."%"; $statisticsoutput .= "</td>\t\t"; break; default: break; } } //LAST value -> add item 4 + item 5 if($gdata[$i] > 100 && $gdata[$i] < 300) { //remove "200" which was added before $gdata[$i] -= 200; if($itemcounter == 5 && $label[$i+1] == $statlang->gT("No answer")) { //prevent division by zero if(($results - $grawdata[$i+1]) > 0) { //re-calculate percentage $percentage = ($grawdata[$i] / ($results - $grawdata[$i+1])) * 100; $percentage2 = ($grawdata[$i - 1] / ($results - $grawdata[$i+1])) * 100; } else { $percentage = 0; $percentage2 = 0; } } else { $percentage = $gdata[$i]; $percentage2 = $gdata[$i-1]; } //item 4 + item 5 $aggregatedgdata = $percentage + $percentage2; switch($outputType) { case 'xls': $label[$i]=FlattenText($label[$i]); $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $aggregatedgdata)."%"); ++$xlsRow; $sheet->write($xlsRow,0,$label[$i]); $sheet->write($xlsRow,1,$grawdata[$i]); $sheet->write($xlsRow,2,sprintf("%01.2f", $percentage)."%"); $sheet->write($xlsRow,3,sprintf("%01.2f", $aggregatedgdata)."%"); break; case 'pdf': $label[$i]=FlattenText($label[$i]); $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $aggregatedgdata)."%"); break; case 'html': //output percentage $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>"; //output aggregated data $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $aggregatedgdata)."%"; $statisticsoutput .= "</td>\t\t"; break; default: break; } // create new row "sum" //calculate sum of items 1-5 $sumitems = $grawdata[$i] + $grawdata[$i-1] + $grawdata[$i-2] + $grawdata[$i-3] + $grawdata[$i-4]; //special treatment for zero values if($sumitems > 0) { $sumpercentage = "100.00"; } else { $sumpercentage = "0"; } //special treatment for zero values if($TotalCompleted > 0) { $casepercentage = "100.00"; } else { $casepercentage = "0"; } switch($outputType) { case 'xls': $footXLS[] = array($statlang->gT("Sum")." (".$statlang->gT("Answers").")",$sumitems,$sumpercentage."%",$sumpercentage."%"); $footXLS[] = array($statlang->gT("Number of cases"),$TotalCompleted,$casepercentage."%",""); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Sum")." (".$statlang->gT("Answers").")"); $sheet->write($xlsRow,1,$sumitems); $sheet->write($xlsRow,2,$sumpercentage."%"); $sheet->write($xlsRow,3,$sumpercentage."%"); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Number of cases")); $sheet->write($xlsRow,1,$TotalCompleted); $sheet->write($xlsRow,2,$casepercentage."%"); break; case 'pdf': $footPDF[] = array($statlang->gT("Sum")." (".$statlang->gT("Answers").")",$sumitems,$sumpercentage."%",$sumpercentage."%"); $footPDF[] = array($statlang->gT("Number of cases"),$TotalCompleted,$casepercentage."%",""); break; case 'html': $statisticsoutput .= "\t\t \n\t</tr>\n"; $statisticsoutput .= "<tr><td align='center'><strong>".$statlang->gT("Sum")." (".$statlang->gT("Answers").")</strong></td>"; $statisticsoutput .= "<td align='center' ><strong>".$sumitems."</strong></td>"; $statisticsoutput .= "<td align='center' ><strong>$sumpercentage%</strong></td>"; $statisticsoutput .= "<td align='center' ><strong>$sumpercentage%</strong></td>"; $statisticsoutput .= "\t\t \n\t</tr>\n"; $statisticsoutput .= "<tr><td align='center'>".$statlang->gT("Number of cases")."</td>"; //German: "Fallzahl" $statisticsoutput .= "<td align='center' >".$TotalCompleted."</td>"; $statisticsoutput .= "<td align='center' >$casepercentage%</td>"; //there has to be a whitespace within the table cell to display correctly $statisticsoutput .= "<td align='center' > </td></tr>"; break; default: break; } } } //end if -> show aggregated data //don't show aggregated data else { switch($outputType) { case 'xls': $label[$i]=FlattenText($label[$i]); $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $gdata[$i])."%", ""); ++$xlsRow; $sheet->write($xlsRow,0,$label[$i]); $sheet->write($xlsRow,1,$grawdata[$i]); $sheet->write($xlsRow,2,sprintf("%01.2f", $gdata[$i])."%"); //$sheet->write($xlsRow,3,$sumpercentage."%"); break; case 'pdf': $label[$i]=FlattenText($label[$i]); $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $gdata[$i])."%", ""); break; case 'html': //output percentage $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $gdata[$i]) . "%"; $statisticsoutput .= "\t\t"; //end output per line. there has to be a whitespace within the table cell to display correctly $statisticsoutput .= "\t\t </td>\n\t</tr>\n"; break; default: break; } } } //end else -> $gdata[$i] != "N/A" //increase counter $i++; $itemcounter++; } //end while //only show additional values when this setting is enabled if(isset($showaggregateddata) && $showaggregateddata == 1 ) { //it's only useful to calculate standard deviation and arithmetic means for question types //5 = 5 Point Scale //A = Array (5 Point Choice) if($qtype == "5" || $qtype == "A") { $stddev = 0; $am = 0; //calculate arithmetic mean if(isset($sumitems) && $sumitems > 0) { //calculate and round results //there are always 5 items for($x = 0; $x < 5; $x++) { //create product of item * value $am += (($x+1) * $stddevarray[$x]); } //prevent division by zero if(isset($stddevarray) && array_sum($stddevarray) > 0) { $am = round($am / array_sum($stddevarray),2); } else { $am = 0; } //calculate standard deviation -> loop through all data /* * four steps to calculate the standard deviation * 1 = calculate difference between item and arithmetic mean and multiply with the number of elements * 2 = create sqaure value of difference * 3 = sum up square values * 4 = multiply result with 1 / (number of items) * 5 = get root */ for($j = 0; $j < 5; $j++) { //1 = calculate difference between item and arithmetic mean $diff = (($j+1) - $am); //2 = create square value of difference $squarevalue = square($diff); //3 = sum up square values and multiply them with the occurence //prevent divison by zero if($squarevalue != 0 && $stddevarray[$j] != 0) { $stddev += $squarevalue * $stddevarray[$j]; } } //4 = multiply result with 1 / (number of items (=5)) //There are two different formulas to calculate standard derivation //$stddev = $stddev / array_sum($stddevarray); //formula source: http://de.wikipedia.org/wiki/Standardabweichung //prevent division by zero if((array_sum($stddevarray)-1) != 0 && $stddev != 0) { $stddev = $stddev / (array_sum($stddevarray)-1); //formula source: http://de.wikipedia.org/wiki/Empirische_Varianz } else { $stddev = 0; } //5 = get root $stddev = sqrt($stddev); $stddev = round($stddev,2); } switch($outputType) { case 'xls': $tableXLS[] = array($statlang->gT("Arithmetic mean"),$am,'',''); $tableXLS[] = array($statlang->gT("Standard deviation"),$stddev,'',''); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Arithmetic mean")); $sheet->write($xlsRow,1,$am); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Standard deviation")); $sheet->write($xlsRow,1,$stddev); break; case 'pdf': $tablePDF[] = array($statlang->gT("Arithmetic mean"),$am,'',''); $tablePDF[] = array($statlang->gT("Standard deviation"),$stddev,'',''); break; case 'html': //calculate standard deviation $statisticsoutput .= "<tr><td align='center'>".$statlang->gT("Arithmetic mean")."</td>"; //German: "Fallzahl" $statisticsoutput .= "<td> </td><td align='center'> $am</td><td> </td></tr>"; $statisticsoutput .= "<tr><td align='center'>".$statlang->gT("Standard deviation")."</td>"; //German: "Fallzahl" $statisticsoutput .= "<td> </td><td align='center'>$stddev</td><td> </td></tr>"; break; default: break; } } } if($outputType=='pdf') //XXX TODO PDF { //$tablePDF = array(); $tablePDF = array_merge_recursive($tablePDF, $footPDF); $pdf->headTable($headPDF,$tablePDF); //$pdf->tableintopdf($tablePDF); // if(isset($footPDF)) // foreach($footPDF as $foot) // { // $footA = array($foot); // $pdf->tablehead($footA); // } } //-------------------------- PCHART OUTPUT ---------------------------- //PCHART has to be enabled and we need some data if ($usegraph==1 && array_sum($gdata)>0) { $graph = ""; $p1 = ""; // $statisticsoutput .= "<pre>"; // $statisticsoutput .= "GDATA:\n"; // print_r($gdata); // $statisticsoutput .= "GRAWDATA\n"; // print_r($grawdata); // $statisticsoutput .= "LABEL\n"; // print_r($label); // $statisticsoutput .= "JUSTCODE\n"; // print_r($justcode); // $statisticsoutput .= "LBL\n"; // print_r($lbl); // $statisticsoutput .= "</pre>"; //First, lets delete any earlier graphs from the tmp directory //$gdata and $lbl are arrays built at the end of the last section //that contain the values, and labels for the data we are about //to send to pchart. $i = 0; foreach ($gdata as $data) { if ($data != 0){$i++;} } $totallines=$i; if ($totallines>15) { $gheight=320+(6.7*($totallines-15)); $fontsize=7; $legendtop=0.01; $setcentrey=0.5/(($gheight/320)); } else { $gheight=320; $fontsize=8; $legendtop=0.07; $setcentrey=0.5; } // Create bar chart for Multiple choice if ($qtype == "M" || $qtype == "P") { //new bar chart using data from array $grawdata which contains percentage $DataSet = new pData; $counter=0; $maxyvalue=0; foreach ($grawdata as $datapoint) { $DataSet->AddPoint(array($datapoint),"Serie$counter"); $DataSet->AddSerie("Serie$counter"); $counter++; if ($datapoint>$maxyvalue) $maxyvalue=$datapoint; } if ($maxyvalue<10) {++$maxyvalue;} $counter=0; foreach ($lbl as $label) { $DataSet->SetSerieName($label,"Serie$counter"); $counter++; } if ($MyCache->IsInCache("graph".$surveyid,$DataSet->GetData())) { $cachefilename=basename($MyCache->GetFileFromCache("graph".$surveyid,$DataSet->GetData())); } else { $graph = new pChart(1,1); $graph->setFontProperties($rootdir."/fonts/".$chartfontfile, $chartfontsize); $legendsize=$graph->getLegendBoxSize($DataSet->GetDataDescription()); if ($legendsize[1]<320) $gheight=420; else $gheight=$legendsize[1]+100; $graph = new pChart(690+$legendsize[0],$gheight); $graph->loadColorPalette($homedir.'/styles/'.$admintheme.'/limesurvey.pal'); $graph->setFontProperties($rootdir."/fonts/".$chartfontfile,$chartfontsize); $graph->setGraphArea(50,30,500,$gheight-60); $graph->drawFilledRoundedRectangle(7,7,523+$legendsize[0],$gheight-7,5,254,255,254); $graph->drawRoundedRectangle(5,5,525+$legendsize[0],$gheight-5,5,230,230,230); $graph->drawGraphArea(255,255,255,TRUE); $graph->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,150,150,150,TRUE,90,0,TRUE,5,false); $graph->drawGrid(4,TRUE,230,230,230,50); // Draw the 0 line $graph->setFontProperties($rootdir."/fonts/".$chartfontfile,$chartfontsize); $graph->drawTreshold(0,143,55,72,TRUE,TRUE); // Draw the bar graph $graph->drawBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),FALSE); //$Test->setLabel($DataSet->GetData(),$DataSet->GetDataDescription(),"Serie4","1","Important point!"); // Finish the graph $graph->setFontProperties($rootdir."/fonts/".$chartfontfile, $chartfontsize); $graph->drawLegend(510,30,$DataSet->GetDataDescription(),255,255,255); $MyCache->WriteToCache("graph".$surveyid,$DataSet->GetData(),$graph); $cachefilename=basename($MyCache->GetFileFromCache("graph".$surveyid,$DataSet->GetData())); unset($graph); } } //end if (bar chart) //Pie Chart else { // this block is to remove the items with value == 0 $i = 0; while (isset ($gdata[$i])) { if ($gdata[$i] == 0) { array_splice ($gdata, $i, 1); array_splice ($lbl, $i, 1); } else {$i++;} } $lblout=array(); if ($language=='ar') { $lblout=$lbl; //reset text order to original include_once($rootdir.'/classes/core/Arabic.php'); $Arabic = new Arabic('ArGlyphs'); foreach($lblout as $kkey => $kval){ if (preg_match("^[A-Za-z]^", $kval)) { //auto detect if english //eng //no reversing } else{ $kval = $Arabic->utf8Glyphs($kval,50,false); $lblout[$kkey] = $kval; } } } elseif (getLanguageRTL($language)) { $lblout=$lblrtl; } else { $lblout=$lbl; } //create new 3D pie chart if ($usegraph==1) { $DataSet = new pData; $DataSet->AddPoint($gdata,"Serie1"); $DataSet->AddPoint($lblout,"Serie2"); $DataSet->AddAllSeries(); $DataSet->SetAbsciseLabelSerie("Serie2"); if ($MyCache->IsInCache("graph".$surveyid,$DataSet->GetData())) { $cachefilename=basename($MyCache->GetFileFromCache("graph".$surveyid,$DataSet->GetData())); } else { $gheight=ceil($gheight); $graph = new pChart(690,$gheight); $graph->loadColorPalette($homedir.'/styles/'.$admintheme.'/limesurvey.pal'); $graph->drawFilledRoundedRectangle(7,7,687,$gheight-3,5,254,255,254); $graph->drawRoundedRectangle(5,5,689,$gheight-1,5,230,230,230); // Draw the pie chart $graph->setFontProperties($rootdir."/fonts/".$chartfontfile, $chartfontsize); $graph->drawPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),225,round($gheight/2),170,PIE_PERCENTAGE,TRUE,50,20,5); $graph->setFontProperties($rootdir."/fonts/".$chartfontfile,$chartfontsize); $graph->drawPieLegend(430,12,$DataSet->GetData(),$DataSet->GetDataDescription(),250,250,250); $MyCache->WriteToCache("graph".$surveyid,$DataSet->GetData(),$graph); $cachefilename=basename($MyCache->GetFileFromCache("graph".$surveyid,$DataSet->GetData())); unset($graph); } //print_r($DataSet->GetData()); echo "<br/><br/>"; } } //end else -> pie charts //introduce new counter if (!isset($ci)) {$ci=0;} //increase counter, start value -> 1 $ci++; switch($outputType) { case 'xls': /** * No Image for Excel... */ break; case 'pdf': $pdf->AddPage('P','A4'); $pdf->titleintopdf($pdfTitle,$titleDesc); $pdf->Image($tempdir."/".$cachefilename, 0, 70, 180, 0, '', $homeurl."/admin.php?sid=$surveyid", 'B', true, 150,'C',false,false,0,true); break; case 'html': $statisticsoutput .= "<tr><td colspan='4' style=\"text-align:center\"><img src=\"$tempurl/".$cachefilename."\" border='1' /></td></tr>"; break; default: break; } } //close table/output if($outputType=='html') $statisticsoutput .= "</table><br /> \n"; } //end if -> collect and display results //delete data unset($gdata); unset($grawdata); unset($label); unset($lbl); unset($lblrtl); unset($lblout); unset($justcode); unset ($alist); } // end foreach -> loop through all questions //output if($outputType=='html') $statisticsoutput .= "<br /> \n"; } //end if -> show summary results switch($outputType) { case 'xls': //$workbook-> $workbook->close(); if($pdfOutput=='F') { return $sFileName; } else { return; } break; case 'pdf': $pdf->lastPage(); if($pdfOutput=='F') { // This is only used by lsrc to send an E-Mail attachment, so it gives back the filename to send and delete afterwards $pdf->Output($tempdir."/".$statlang->gT('Survey').'_'.$surveyid."_".$surveyInfo['surveyls_title'].'.pdf', $pdfOutput); return $tempdir."/".$statlang->gT('Survey').'_'.$surveyid."_".$surveyInfo['surveyls_title'].'.pdf'; } else return $pdf->Output($statlang->gT('Survey').'_'.$surveyid."_".$surveyInfo['surveyls_title'].'.pdf', $pdfOutput); break; case 'html': return $statisticsoutput; break; default: return $statisticsoutput; break; } }
function display_graph_by_resource() { require_once api_get_path(LIBRARY_PATH) . 'pchart/pData.class.php'; require_once api_get_path(LIBRARY_PATH) . 'pchart/pChart.class.php'; require_once api_get_path(LIBRARY_PATH) . 'pchart/pCache.class.php'; $header_name = $this->datagen->get_header_names(); $total_users = $this->datagen->get_total_users_count(); $img_file = ''; if ($this->datagen->get_total_items_count() > 0 && $total_users > 0) { //Removing first name array_shift($header_name); //Removing last name array_shift($header_name); $displayscore = ScoreDisplay::instance(); $customdisplays = $displayscore->get_custom_score_display_settings(); if (is_array($customdisplays) && count($customdisplays)) { $user_results = $this->datagen->get_data_to_graph2(); $pre_result = $new_result = array(); $DataSet = new pData(); //filling the Dataset foreach ($user_results as $result) { //print_r($result); for ($i = 0; $i < count($header_name); $i++) { $pre_result[$i + 3][] = $result[$i + 1]; } } $i = 0; $show_draw = false; $resource_list = array(); $pre_result2 = array(); foreach ($pre_result as $key => $res_array) { rsort($res_array); $pre_result2[] = $res_array; } //@todo when a display custom does not exist the order of the color does not match //filling all the answer that are not responded with 0 rsort($customdisplays); if ($total_users > 0) { foreach ($pre_result2 as $key => $res_array) { $key_list = array(); foreach ($res_array as $user_result) { $resource_list[$key][$user_result[1]] += 1; $key_list[] = $user_result[1]; } foreach ($customdisplays as $display) { if (!in_array($display['display'], $key_list)) { $resource_list[$key][$display['display']] = 0; } } $i++; } } //fixing $resource_list $max = 0; $new_list = array(); foreach ($resource_list as $key => $value) { $new_value = array(); foreach ($customdisplays as $item) { if ($value[$item['display']] > $max) { $max = $value[$item['display']]; } $new_value[$item['display']] = strip_tags($value[$item['display']]); } $new_list[] = $new_value; } $resource_list = $new_list; $i = 1; $j = 0; foreach ($resource_list as $key => $resource) { $new_resource_list = $new_resource_list_name = array(); $DataSet = new pData(); // Reverse array, otherwise we get highest values first $resource = array_reverse($resource, true); foreach ($resource as $name => $cant) { $DataSet->AddPoint($cant, "Serie" . $j); $DataSet->SetSerieName(strip_tags($name), "Serie" . $j); $j++; } //print_r($pre_result); print_r($header_name); // Dataset definition $DataSet->AddAllSeries(); $DataSet->SetAbsciseLabelSerie(''); $DataSet->SetXAxisName(get_lang('GradebookSkillsRanking')); $DataSet->SetYAxisName(get_lang('Students')); $show_draw = true; // Cache definition $Cache = new pCache(); // the graph id $gradebook_id = intval($_GET['selectcat']); $graph_id = api_get_user_id() . 'ByResource' . $gradebook_id . api_get_course_id() . api_get_session_id(); if ($show_draw) { //if ($Cache->IsInCache($graph_id, $DataSet->GetData())) { if (0) { //if we already created the img we get the img file id //echo 'in cache'; $img_file = $Cache->GetHash($graph_id, $DataSet->GetData()); } else { // if the image does not exist in the archive/ folder // Initialise the graph $chart_size_w = 480; $chart_size_h = 250; $Test = new pChart($chart_size_w, $chart_size_h); // Adding the color schemma $Test->loadColorPalette(api_get_path(LIBRARY_PATH) . "pchart/palette/pastel.txt"); // set font of the axes $Test->setFontProperties(api_get_path(LIBRARY_PATH) . "pchart/fonts/tahoma.ttf", 8); $area_graph_w = $chart_size_w - 130; $Test->setGraphArea(50, 30, $area_graph_w, $chart_size_h - 50); $Test->drawFilledRoundedRectangle(5, 5, $chart_size_w - 1, $chart_size_h - 20, 5, 240, 240, 240); //$Test->drawRoundedRectangle(5,5,790,330,5,230,230,230); //background color area & stripe or not $Test->drawGraphArea(255, 255, 255, TRUE); //Setting max height by default see #3296 if (!empty($max)) { $Test->setFixedScale(0, $max); } $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_ADDALLSTART0, 150, 150, 150, TRUE, 0, 0, FALSE); //background grid $Test->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line //$Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",6); //$Test->drawTreshold(0,143,55,72,TRUE,TRUE); // Draw the bar graph $Test->drawBarGraph($DataSet->GetData(), $DataSet->GetDataDescription(), TRUE); //Set legend properties: width, height and text color and font $Test->setFontProperties(api_get_path(LIBRARY_PATH) . "pchart/fonts/tahoma.ttf", 9); $Test->drawLegend($area_graph_w + 10, 50, $DataSet->GetDataDescription(), 255, 255, 255); //Set title properties $Test->setFontProperties(api_get_path(LIBRARY_PATH) . "pchart/fonts/tahoma.ttf", 10); $Test->drawTitle(50, 22, strip_tags($header_name[$i - 1]), 50, 50, 80, $chart_size_w - 50); //------------------ //echo 'not in cache'; $Cache->WriteToCache($graph_id, $DataSet->GetData(), $Test); //ob_start(); //$Test->Stroke(); //ob_end_clean(); $img_file = $Cache->GetHash($graph_id, $DataSet->GetData()); } echo '<img src="' . api_get_path(WEB_ARCHIVE_PATH) . $img_file . '" >'; if ($i % 2 == 0 && $i != 0) { echo '<br />'; } $i++; } } //end foreach } else { echo get_lang('ToViewGraphScoreRuleMustBeEnabled'); } // Pie charts /* $show_draw = false; $resource_list = array(); //print_r($pre_result_pie); if ($total_users>0) { foreach($pre_result_pie as $key=>$res_array) { //$resource_list foreach($res_array as $user_result) { $total+= $user_result / ($total_users*100); } echo $total; //echo $total = $res / ($total_users*100); echo '<br>'; //$DataSet->AddPoint($total,"Serie".$i); //$DataSet->SetSerieName($header_name[$i-1],"Serie".$i); } } //here-------------- foreach($resource_list as $key=>$resource) { $new_resource_list = $new_resource_list_name = array(); foreach($resource as $name=>$cant) { $new_resource_list[]=$cant; $new_resource_list_name[]=$name; } //Pie chart $DataSet = new pData; $DataSet->AddPoint($new_resource_list,"Serie1"); $DataSet->AddPoint($new_resource_list_name,"Serie2"); $DataSet->AddAllSeries(); $DataSet->SetAbsciseLabelSerie("Serie2"); $Test = new pChart(400,300); $Test->loadColorPalette(api_get_path(LIBRARY_PATH)."pchart/palette/soft_tones.txt"); // background //$Test->drawFilledRoundedRectangle(7,7,293,193,5,240,240,240); // border color $Test->drawRoundedRectangle(5,5,295,195,5,230,230,230); // This will draw a shadow under the pie chart //$Test->drawFilledCircle(122,102,70,200,200,200); //Draw the pie chart $Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",8); $Test->drawBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),TRUE); $tmp_path = api_get_path(SYS_ARCHIVE_PATH); $Test->drawBasicPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),120,100,70,PIE_PERCENTAGE,255,255,218); $Test->drawPieLegend(230,15,$DataSet->GetData(),$DataSet->GetDataDescription(),250,250,250); $user_id = api_get_user_id(); $img_file_generated_name = $key.uniqid('').'gradebook.png'; $Test->Render($tmp_path.$img_file_generated_name); chmod($tmp_path.$img_file_generated_name, api_get_permissions_for_new_files()); if ($i % 2 == 0 && $i!= 0) { echo '<br>'; } echo '<img src="'.api_get_path(WEB_ARCHIVE_PATH).$img_file_generated_name.'">'; } */ } }
<?php /* Naked: Naked and easy! */ // Standard inclusions include "pChart/pData.class"; include "pChart/pChart.class"; // Dataset definition $DataSet = new pData(); $DataSet->AddPoint(array(1, 4, 3, 2, 3, 3, 2, 1, 0, 7, 4, 3, 2, 3, 3, 5, 1, 0, 7)); $DataSet->AddSerie(); $DataSet->SetSerieName("Sample data", "Serie1"); // Initialise the graph $Test = new pChart(700, 230); $Test->setFontProperties("Fonts/tahoma.ttf", 10); $Test->setGraphArea(40, 30, 680, 200); $Test->drawGraphArea(252, 252, 252, TRUE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2); $Test->drawGrid(4, TRUE, 230, 230, 230, 70); // Draw the line graph $Test->drawLineGraph($DataSet->GetData(), $DataSet->GetDataDescription()); $Test->drawPlotGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 3, 2, 255, 255, 255); // Finish the graph $Test->setFontProperties("Fonts/tahoma.ttf", 8); $Test->drawLegend(45, 35, $DataSet->GetDataDescription(), 255, 255, 255); $Test->setFontProperties("Fonts/tahoma.ttf", 10); $Test->drawTitle(60, 22, "My pretty graph", 50, 50, 50, 585); $Test->Render("Naked.png");
/** * This method return a graph containing information about evaluations * inside courses in sessions, it's used inside get_block method for * showing it inside dashboard interface * @return string img html */ public function get_evaluations_courses_in_sessions_graph() { $graphs = array(); if (!empty($this->sessions)) { $session_ids = array_keys($this->sessions); foreach ($session_ids as $session_id) { $courses_code = array_keys(Tracking::get_courses_list_from_session($session_id)); $courses_graph = array(); foreach ($courses_code as $course_code) { $cats = Category::load(null, null, $course_code, null, null, $session_id); if (isset($cats) && isset($cats[0])) { $alleval = $cats[0]->get_evaluations(null, true, $course_code); $alllinks = $cats[0]->get_links(null, true); $users = get_all_users($alleval, $alllinks); $datagen = new FlatViewDataGenerator ($users, $alleval, $alllinks); $evaluation_sumary = $datagen->get_evaluation_sumary_results(); if (!empty($evaluation_sumary)) { $items = array_keys($evaluation_sumary); $max = $min = $avg = array(); foreach ($evaluation_sumary as $evaluation) { $max[] = $evaluation['max']; $min[] = $evaluation['min']; $avg[] = $evaluation['avg']; } // Dataset definition $data_set = new pData; $data_set->AddPoint($max, "Max"); $data_set->AddPoint($avg, "Avg"); $data_set->AddPoint($min, "Min"); $data_set->AddPoint($items, "Items"); $data_set->SetXAxisName(get_lang('EvaluationName')); $data_set->SetYAxisName(get_lang('Percentage')); $data_set->AddAllSeries(); $data_set->RemoveSerie("Items"); $data_set->SetAbsciseLabelSerie("Items"); $graph_id = $this->user_id.'StudentEvaluationGraph'; $cache = new pCache(); // the graph id $data = $data_set->GetData(); if ($cache->IsInCache($graph_id, $data)) { //if we already created the img $img_file = $cache->GetHash($graph_id, $data); } else { // Initialise the graph $angle = -30; $test = new pChart($this->bg_width, $this->bg_height); $test->setFontProperties(api_get_path(LIBRARY_PATH) . 'pchart/fonts/tahoma.ttf', 8); $test->fixHeightByRotation( $data_set->GetData(), $data_set->GetDataDescription(), $angle ); $test->setGraphArea(50, 30, $this->bg_width - 75, $this->bg_height - 75); $test->drawFilledRoundedRectangle( 7, 7, $this->bg_width - 20, $test->YSize - 20, 5, 240, 240, 240 ); $test->drawRoundedRectangle( 5, 5, $this->bg_width - 18, $test->YSize - 18, 5, 230, 230, 230 ); $test->drawGraphArea(255,255,255,TRUE); $test->setFixedScale(0,100,5); $test->drawScale( $data_set->GetData(), $data_set->GetDataDescription(), SCALE_ADDALL, 150, 150, 150, TRUE, $angle, 2, TRUE ); $test->setColorPalette(0,105,221,34); $test->setColorPalette(1,255,135,30); $test->setColorPalette(2,255,0,0); $test->drawGrid(4,TRUE,230,230,230,50); // Draw the 0 line $test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf',6); $test->drawTreshold(0,143,55,72,TRUE,TRUE); // Draw the bar graph $test->drawOverlayBarGraph($data_set->GetData(),$data_set->GetDataDescription(), 100); // Finish the graph $test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf',8); $test->drawLegend($this->bg_width-80,20,$data_set->GetDataDescription(),255,255,255); $test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf',10); $test->setColorPalette(0,50,50,50); $test->setColorPalette(1,50,50,50); $test->setColorPalette(2,50,50,50); $test->writeValues($data_set->GetData(),$data_set->GetDataDescription(),array("Min", "Max", "Avg")); $cache->WriteToCache($graph_id, $data_set->GetData(), $test); ob_start(); $test->Stroke(); ob_end_clean(); $img_file = $cache->GetHash($graph_id, $data_set->GetData()); } if (!empty($img_file)) { $courses_graph[$course_code] = '<img src="'.api_get_path(WEB_ARCHIVE_PATH).$img_file.'">'; } } } } if (!empty($courses_graph)) { $graphs[$session_id] = $courses_graph; } } } return $graphs; }
/** * * Generate a chart for a question * @param int $iQuestionID ID of the question * @param int $iSurveyID ID of the survey * @param mixed $type Type of the chart to be created - null produces bar chart, any other value produces pie chart * @param array $lbl An array containing the labels for the chart items * @param mixed $gdata An array containing the percentages for the chart items * @param mixed $grawdata An array containing the raw count for the chart items * @param mixed $cache An object containing [Hashkey] and [CacheFolder] * @param string $sQuestionType The question type * @return Name */ function createChart($iQuestionID, $iSurveyID, $type = null, $lbl, $gdata, $grawdata, $cache, $oLanguage, $sQuestionType) { /* This is a lazy solution to bug #6389. A better solution would be to find out how the "T" gets passed to this function from the statistics.js file in the first place! */ if (substr($iSurveyID, 0, 1) == "T") { $iSurveyID = substr($iSurveyID, 1); } static $bErrorGenerate = false; if ($bErrorGenerate) { return false; } $rootdir = Yii::app()->getConfig("rootdir"); $homedir = Yii::app()->getConfig("homedir"); $homeurl = Yii::app()->getConfig("homeurl"); $admintheme = Yii::app()->getConfig("admintheme"); $scriptname = Yii::app()->getConfig("scriptname"); $chartfontfile = Yii::app()->getConfig("chartfontfile"); $chartfontsize = Yii::app()->getConfig("chartfontsize"); $alternatechartfontfile = Yii::app()->getConfig("alternatechartfontfile"); $language = $oLanguage->langcode; $cachefilename = ""; /* Set the fonts for the chart */ if ($chartfontfile == 'auto') { // Tested with ar,be,el,fa,hu,he,is,lt,mt,sr, and en (english) // Not working for hi, si, zh, th, ko, ja : see $config['alternatechartfontfile'] to add some specific language font $chartfontfile = 'DejaVuSans.ttf'; if (array_key_exists($language, $alternatechartfontfile)) { $neededfontfile = $alternatechartfontfile[$language]; if (is_file($rootdir . "/fonts/" . $neededfontfile)) { $chartfontfile = $neededfontfile; } else { Yii::app()->setFlashMessage(sprintf(gT('The fonts file %s was not found in <limesurvey root folder>/fonts directory. Please, see the txt file for your language in fonts directory to generate the charts.'), $neededfontfile), 'error'); $bErrorGenerate = true; // Don't do a graph again. return false; } } } if (count($lbl) > 72) { $DataSet = array(1 => array(1 => 1)); if ($cache->IsInCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet) && Yii::app()->getConfig('debug') < 2) { $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet)); } else { $graph = new pChart(690, 200); $graph->loadColorPalette($homedir . DIRECTORY_SEPARATOR . 'styles' . DIRECTORY_SEPARATOR . $admintheme . DIRECTORY_SEPARATOR . 'limesurvey.pal'); $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize); $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize); $graph->drawTitle(0, 0, gT('Sorry, but this question has too many answer options to be shown properly in a graph.', 'unescaped'), 30, 30, 30, 690, 200); $cache->WriteToCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet, $graph); $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet)); unset($graph); } return $cachefilename; } if (array_sum($gdata) == 0) { $DataSet = array(1 => array(1 => 1)); if ($cache->IsInCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet) && Yii::app()->getConfig('debug') < 2) { $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet)); } else { $graph = new pChart(690, 200); $graph->loadColorPalette($homedir . DIRECTORY_SEPARATOR . 'styles' . DIRECTORY_SEPARATOR . $admintheme . DIRECTORY_SEPARATOR . 'limesurvey.pal'); $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize); $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize); $graph->drawTitle(0, 0, gT('Sorry, but this question has no responses yet so a graph cannot be shown.', 'unescaped'), 30, 30, 30, 690, 200); $cache->WriteToCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet, $graph); $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet)); unset($graph); } return $cachefilename; } if (array_sum($gdata) > 0) { $graph = ""; $p1 = ""; $i = 0; foreach ($gdata as $data) { if ($data != 0) { $i++; } } /* Totatllines is the number of entries to show in the key and we need to reduce the font and increase the size of the chart if there are lots of them (ie more than 15) */ $totallines = $i; if ($totallines > 15) { $gheight = 320 + 6.7 * ($totallines - 15); $fontsize = 7; $legendtop = 0.01; $setcentrey = 0.5 / ($gheight / 320); } else { $gheight = 320; $fontsize = 8; $legendtop = 0.07000000000000001; $setcentrey = 0.5; } if (!$type) { $DataSet = new pData(); $counter = 0; $maxyvalue = 0; foreach ($grawdata as $datapoint) { $DataSet->AddPoint(array($datapoint), "Serie{$counter}"); $DataSet->AddSerie("Serie{$counter}"); $counter++; if ($datapoint > $maxyvalue) { $maxyvalue = $datapoint; } } if ($maxyvalue < 10) { ++$maxyvalue; } if ($language == 'ar') { if (!class_exists('I18N_Arabic_Glyphs', false)) { $Arabic = new I18N_Arabic('Glyphs'); } else { $Arabic = new I18N_Arabic_Glyphs(); } foreach ($lbl as $kkey => $kval) { if (preg_match("^[A-Za-z]^", $kkey)) { //auto detect if english $lblout[] = $kkey . ' (' . $kval . ')'; } else { $lblout[] = $Arabic->utf8Glyphs($kkey . ' )' . $kval . '('); } } } elseif (getLanguageRTL($language)) { foreach ($lbl as $kkey => $kval) { $lblout[] = UTF8Strrev($kkey . ' )' . $kval . '('); } } else { foreach ($lbl as $kkey => $kval) { $lblout[] = $kkey . ' (' . $kval . ')'; } } $counter = 0; foreach ($lblout as $sLabelName) { $DataSet->SetSerieName(html_entity_decode($sLabelName, null, 'UTF-8'), "Serie{$counter}"); $counter++; } if ($cache->IsInCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData()) && Yii::app()->getConfig('debug') < 2) { $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData())); } else { $graph = new pChart(1, 1); $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize); $legendsize = $graph->getLegendBoxSize($DataSet->GetDataDescription()); if ($legendsize[1] < 320) { $gheight = 420; } else { $gheight = $legendsize[1] + 100; } $graph = new pChart(690 + $legendsize[0], $gheight); $graph->drawFilledRectangle(0, 0, 690 + $legendsize[0], $gheight, 254, 254, 254, false); $graph->loadColorPalette($homedir . DIRECTORY_SEPARATOR . 'styles' . DIRECTORY_SEPARATOR . $admintheme . DIRECTORY_SEPARATOR . 'limesurvey.pal'); $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize); $graph->setGraphArea(50, 30, 500, $gheight - 60); $graph->drawFilledRoundedRectangle(7, 7, 523 + $legendsize[0], $gheight - 7, 5, 254, 255, 254); $graph->drawRoundedRectangle(5, 5, 525 + $legendsize[0], $gheight - 5, 5, 230, 230, 230); $graph->drawGraphArea(254, 254, 254, TRUE); $graph->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_START0, 150, 150, 150, TRUE, 90, 0, TRUE, 5, false); $graph->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize); $graph->drawTreshold(0, 143, 55, 72, TRUE, TRUE); // Draw the bar graph $graph->drawBarGraph($DataSet->GetData(), $DataSet->GetDataDescription(), FALSE); //$Test->setLabel($DataSet->GetData(),$DataSet->GetDataDescription(),"Serie4","1","Important point!"); // Finish the graph $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize); $graph->drawLegend(510, 30, $DataSet->GetDataDescription(), 250, 250, 250); $cache->WriteToCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData(), $graph); $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData())); unset($graph); } } else { // this block is to remove the items with value == 0 // and an inelegant way to remove comments from List with Comments questions $i = 0; $j = 0; $labelTmp = array(); while (isset($gdata[$i])) { $aHelperArray = array_keys($lbl); if ($gdata[$i] == 0 || $sQuestionType == "O" && substr($aHelperArray[$i], 0, strlen($oLanguage->gT("Comments"))) == $oLanguage->gT("Comments")) { array_splice($gdata, $i, 1); } else { $i++; $labelTmp = $labelTmp + array_slice($lbl, $j, 1, true); // Preserve numeric keys for the labels! } $j++; } $lbl = $labelTmp; if ($language == 'ar') { if (!class_exists('I18N_Arabic_Glyphs', false)) { $Arabic = new I18N_Arabic('Glyphs'); } else { $Arabic = new I18N_Arabic_Glyphs(); } foreach ($lbl as $kkey => $kval) { if (preg_match("^[A-Za-z]^", $kkey)) { //auto detect if english $lblout[] = $kkey . ' (' . $kval . ')'; } else { $lblout[] = $Arabic->utf8Glyphs($kkey . ' )' . $kval . '('); } } } elseif (getLanguageRTL($language)) { foreach ($lbl as $kkey => $kval) { $lblout[] = UTF8Strrev(html_entity_decode($kkey, null, 'UTF-8') . ' )' . $kval . '('); } } else { foreach ($lbl as $kkey => $kval) { $lblout[] = html_entity_decode($kkey, null, 'UTF-8') . ' (' . $kval . ')'; } } //create new 3D pie chart $DataSet = new pData(); $DataSet->AddPoint($gdata, "Serie1"); $DataSet->AddPoint($lblout, "Serie2"); $DataSet->AddAllSeries(); $DataSet->SetAbsciseLabelSerie("Serie2"); if ($cache->IsInCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData()) && Yii::app()->getConfig('debug') < 2) { $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData())); } else { $gheight = ceil($gheight); $graph = new pChart(690, $gheight); $graph->drawFilledRectangle(0, 0, 690, $gheight, 254, 254, 254, false); $graph->loadColorPalette($homedir . '/styles/' . $admintheme . '/limesurvey.pal'); $graph->drawFilledRoundedRectangle(7, 7, 687, $gheight - 3, 5, 254, 255, 254); $graph->drawRoundedRectangle(5, 5, 689, $gheight - 1, 5, 230, 230, 230); // Draw the pie chart $graph->setFontProperties($rootdir . "/fonts/" . $chartfontfile, $chartfontsize); $graph->drawPieGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 225, round($gheight / 2), 170, PIE_PERCENTAGE, TRUE, 50, 20, 5); $graph->setFontProperties($rootdir . "/fonts/" . $chartfontfile, $chartfontsize); $graph->drawPieLegend(430, 12, $DataSet->GetData(), $DataSet->GetDataDescription(), 250, 250, 250); $cache->WriteToCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData(), $graph); $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData())); unset($graph); } } //end else -> pie charts } return $cachefilename; }
public function pchartAction() { // $this->_helper->layout->disableLayout(); $this->_helper->layout->setLayout("layout_admin"); include "pData.class"; include "pChart.class"; $this->view->showArray = $this->testdemoAction(); $showdate = array(); $showreport = array(); foreach ($this->view->showArray as $show) { array_push($showdate, substr($show['date'], strlen($show['date']) - 4, 4)); array_push($showreport, $show['count']); } // Dataset definition $DataSet = new pData(); $DataSet->AddPoint(array_slice($showreport, 0, 26), "Serie1"); $DataSet->AddPoint(array_slice($showdate, 0, 26), "Serie2"); $DataSet->AddSerie("Serie1"); $DataSet->SetAbsciseLabelSerie("Serie2"); $DataSet->SetSerieName("Reports", "Serie1"); $DataSet->SetYAxisName('Report Count'); $DataSet->SetXAxisName('Date'); // Initialise the graph $Test = new pChart(900, 250); $Test->setFontProperties("xihei.ttf", 8); $Test->setGraphArea(50, 30, 780, 200); $Test->drawFilledRoundedRectangle(7, 7, 793, 248, 5, 255, 255, 255); $Test->drawRoundedRectangle(5, 5, 795, 249, 5, 230, 230, 230); $Test->drawGraphArea(255, 255, 255, TRUE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2, TRUE); $Test->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line $Test->setFontProperties("xihei.ttf", 6); $Test->drawTreshold(0, 143, 55, 72, TRUE, TRUE); // Draw the bar graph $Test->drawBarGraph($DataSet->GetData(), $DataSet->GetDataDescription(), TRUE); // Finish the graph $Test->setFontProperties("xihei.ttf", 8); $Test->drawLegend(596, 50, $DataSet->GetDataDescription(), 255, 255, 255); $Test->setFontProperties("xihei.ttf", 10); $Test->drawTitle(200, 22, "Reports by Day in Jue.", 50, 50, 50, 585); $Test->Render("Naked1.png"); //===================================================================================== // Dataset definition $DataSet2 = new pData(); $DataSet2->AddPoint(array(38, 22, 606), "Serie1"); $DataSet2->AddPoint(array("Male", "Female", "Unkown"), "Serie2"); $DataSet2->AddAllSeries(); $DataSet2->SetAbsciseLabelSerie("Serie2"); // Initialise the graph $Test2 = new pChart(300, 200); $Test2->loadColorPalette("softtones.txt"); $Test2->drawFilledRoundedRectangle(7, 7, 293, 193, 5, 255, 255, 255); $Test2->drawRoundedRectangle(5, 5, 295, 195, 5, 230, 230, 230); // This will draw a shadow under the pie chart $Test2->drawFilledCircle(122, 102, 70, 200, 200, 200); // Draw the pie chart $Test2->setFontProperties("tahoma.ttf", 8); $Test2->drawBasicPieGraph($DataSet2->GetData(), $DataSet2->GetDataDescription(), 120, 100, 70, PIE_PERCENTAGE, 255, 255, 218); $Test2->drawPieLegend(230, 15, $DataSet2->GetData(), $DataSet2->GetDataDescription(), 250, 250, 250); $Test2->Render("Naked2.png"); //===================================================================================== // select province $db = Zend_Registry::get('db'); $selectprovince = $db->select(); $selectprovince->from('consumer', array("province", "count(*) as count"))->where("pest is null")->group("consumer.province")->order("count desc"); $provinceArray = $db->fetchAll($selectprovince); $this->view->showprovince = ''; $this->view->showprovincecount = ''; $showprovince = array(); $showprovincecount = array(); foreach ($provinceArray as $province) { if ($province['province'] == null || $province['province'] == '') { array_push($showprovince, 'Unkown'); } else { array_push($showprovince, $province['province']); } array_push($showprovincecount, $province['count']); } // Dataset definition $DataSet3 = new pData(); $DataSet3->AddPoint(array_slice($showprovincecount, 0, 20), "Serie1"); $DataSet3->AddPoint(array_slice($showprovince, 0, 20), "Serie2"); $DataSet3->AddSerie("Serie1"); $DataSet3->SetAbsciseLabelSerie("Serie2"); $DataSet3->SetSerieName("Spark Count", "Serie1"); $DataSet3->SetYAxisName('Spark Count'); $DataSet3->SetXAxisName('Province'); Zend_Debug::dump($DataSet3->GetDataDescription()); // Initialise the graph $Test3 = new pChart(900, 250); $Test3->setFontProperties("xihei.ttf", 8); $Test3->setGraphArea(50, 30, 780, 200); $Test3->drawFilledRoundedRectangle(7, 7, 793, 248, 5, 255, 255, 255); $Test3->drawRoundedRectangle(5, 5, 795, 249, 5, 230, 230, 230); $Test3->drawGraphArea(255, 255, 255, TRUE); $Test3->drawScale($DataSet3->GetData(), $DataSet3->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2, TRUE); $Test3->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line $Test3->setFontProperties("xihei.ttf", 6); $Test3->drawTreshold(0, 143, 55, 72, TRUE, TRUE); // Draw the bar graph $Test3->drawBarGraph($DataSet3->GetData(), $DataSet3->GetDataDescription(), TRUE); // Finish the graph $Test3->setFontProperties("xihei.ttf", 8); $Test3->drawLegend(596, 50, $DataSet3->GetDataDescription(), 255, 255, 255); $Test3->setFontProperties("xihei.ttf", 10); $Test3->drawTitle(200, 22, "Reports by Day in Jue.", 50, 50, 50, 585); $Test3->Render("Naked3.png"); }
} // Standard inclusions include 'pChart/pData.class'; include 'pChart/pChart.class'; // Dataset definition $DataSet = new pData(); $DataSet->AddPoint($data, 'S1'); $DataSet->AddPoint(array_keys($data), 'S2'); $DataSet->AddSerie('S1'); $DataSet->SetAbsciseLabelSerie('S2'); // Initialise the graph $Test = new pChart(700, 230); if ($is_null) { $Test->setFixedScale(0, 1, 1); } $Test->setFontProperties('Fonts/tahoma.ttf', 8); $Test->setGraphArea(50, 30, 665, 200); $Test->drawFilledRoundedRectangle(7, 7, 693, 223, 5, 240, 240, 240); $Test->drawRoundedRectangle(5, 5, 695, 225, 5, 230, 230, 230); $Test->drawGraphArea(255, 255, 255, true); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, true, 0, 2); $Test->drawGrid(4, true, 230, 230, 230, 50); // Draw the cubic curve graph $Test->drawCubicCurve($DataSet->GetData(), $DataSet->GetDataDescription()); // Finish the graph $Test->setFontProperties('Fonts/tahoma.ttf', 10); $Test->drawTitle(50, 22, 'Пользователи PRO', 50, 50, 50, 585); $Test->Stroke(); ?>
/** * Creates the object and prepares it for rendering. * Does all the calculation like borders, margins, paddings .... * * @return void */ private function preGraphCreation() { // Initialize the graph $this->objChart = new pChart($this->intWidth, $this->intHeight); //set the color palette to be used foreach ($this->arrDefaultColorPalette as $intKey => $strCurrentColor) { $arrCurColor = hex2rgb($strCurrentColor); $this->objChart->setColorPalette($intKey, $arrCurColor[0], $arrCurColor[1], $arrCurColor[2]); } //calculate all needed params, draw that funky shit //the outer bounding and pane - rounded and with sharp corners $arrBackgroundColor = hex2rgb($this->strBackgroundColor); if ($this->bitRoundedCorners) { $this->objChart->drawFilledRoundedRectangle(2, 2, $this->intWidth - 3, $this->intHeight - 3, 5, $arrBackgroundColor[0], $arrBackgroundColor[1], $arrBackgroundColor[2]); $arrOuterBack = hex2rgb($this->strOuterFrameColor); $this->objChart->drawRoundedRectangle(0, 0, $this->intWidth - 1, $this->intHeight - 1, 5, $arrOuterBack[0], $arrOuterBack[1], $arrOuterBack[2]); } else { $this->objChart->drawFilledRectangle(0, 0, $this->intWidth, $this->intHeight, $arrBackgroundColor[0], $arrBackgroundColor[1], $arrBackgroundColor[2]); } //the graph area - x and or y-axis label present? if ($this->bitRenderLegend) { $intRightMargin = 10; } else { $intRightMargin = 20; } $intTopMargin = 15; $intBottomMargin = 30; $intLeftMargin = 40; $intLegendWidth = 0; if ($this->bitRenderLegend) { $intLegendWidth = 120; } $intWidth = $this->intWidth - $intRightMargin - $intLegendWidth; $intHeight = $this->intHeight - $intBottomMargin; $intLeftStart = $intLeftMargin; $intTopStart = $intTopMargin; if ($this->strYAxisTitle != "") { $intLeftStart += 15; //$intWidth -= 15; //TODO: why not needed? } if ($this->strXAxisTitle != "") { $intHeight -= 15; } if ($this->strGraphTitle != "") { //$intHeight -= 12; //TODO: why not needed??? $intTopStart += 12; } if ($this->intCurrentGraphMode != $this->GRAPH_TYPE_PIE) { $this->objChart->setGraphArea($intLeftStart, $intTopStart, $intWidth, $intHeight); $arrPaneBackground = hex2rgb($this->strGraphBackgroundColor); $this->objChart->drawGraphArea($arrPaneBackground[0], $arrPaneBackground[1], $arrPaneBackground[2], true); } $arrFontColors = hex2rgb($this->strFontColor); $this->objChart->setFontProperties(class_resourceloader::getInstance()->getCorePathForModule("module_system", true) . "/module_system/system" . $this->strFont, 8); //set up the axis-titles if ($this->intCurrentGraphMode == $this->GRAPH_TYPE_BAR || $this->intCurrentGraphMode == $this->GRAPH_TYPE_STACKEDBAR || $this->intCurrentGraphMode == $this->GRAPH_TYPE_LINE) { if ($this->strXAxisTitle != "") { $this->objDataset->SetXAxisName($this->strXAxisTitle); } if ($this->strYAxisTitle != "") { $this->objDataset->SetYAxisName($this->strYAxisTitle); } } //the x- and y axis, in- / exclusive margins if ($this->bitAdditionalDatasetAdded && $this->bitScaleFromAdditionalDataset) { $this->objChart->drawScale($this->objAdditionalDataset->GetData(), $this->objAdditionalDataset->GetDataDescription(), SCALE_START0, $arrFontColors[0], $arrFontColors[1], $arrFontColors[2], TRUE, $this->intXAxisAngle, 1, true); } else { if ($this->intCurrentGraphMode == $this->GRAPH_TYPE_BAR) { $this->objChart->drawScale($this->objDataset->GetData(), $this->objDataset->GetDataDescription(), SCALE_START0, $arrFontColors[0], $arrFontColors[1], $arrFontColors[2], TRUE, $this->intXAxisAngle, 1, true); } else { if ($this->intCurrentGraphMode == $this->GRAPH_TYPE_STACKEDBAR) { $this->objChart->drawScale($this->objDataset->GetData(), $this->objDataset->GetDataDescription(), SCALE_ADDALLSTART0, $arrFontColors[0], $arrFontColors[1], $arrFontColors[2], TRUE, $this->intXAxisAngle, 1, true); } else { if ($this->intCurrentGraphMode == $this->GRAPH_TYPE_LINE) { $this->objChart->drawScale($this->objDataset->GetData(), $this->objDataset->GetDataDescription(), SCALE_NORMAL, $arrFontColors[0], $arrFontColors[1], $arrFontColors[2], TRUE, $this->intXAxisAngle, 1, false); } } } } //the background grid if ($this->intCurrentGraphMode != $this->GRAPH_TYPE_PIE) { $arrGridColor = hex2rgb($this->strGridColor); $this->objChart->drawGrid(4, true, $arrGridColor[0], $arrGridColor[1], $arrGridColor[2], 50); } if ($this->intCurrentGraphMode == $this->GRAPH_TYPE_LINE) { // Draw the line graph $this->objChart->drawLineGraph($this->objDataset->GetData(), $this->objDataset->GetDataDescription()); //dots in line $this->objChart->drawPlotGraph($this->objDataset->GetData(), $this->objDataset->GetDataDescription(), 3, 2, 255, 255, 255); } else { if ($this->intCurrentGraphMode == $this->GRAPH_TYPE_BAR) { //the zero-line $this->objChart->setFontProperties(class_resourceloader::getInstance()->getCorePathForModule("module_system", true) . "/module_system/system" . $this->strFont, 6); $this->objChart->drawBarGraph($this->objDataset->GetData(), $this->objDataset->GetDataDescription(), TRUE); $this->objChart->drawTreshold(0, 143, 55, 72, TRUE, TRUE); //if given, render the line-plots on top if ($this->bitAdditionalDatasetAdded) { //the line itself $this->objChart->drawLineGraph($this->objAdditionalDataset->GetData(), $this->objAdditionalDataset->GetDataDescription()); //the dots $this->objChart->drawPlotGraph($this->objAdditionalDataset->GetData(), $this->objAdditionalDataset->GetDataDescription(), 3, 2, 255, 255, 255); } } else { if ($this->intCurrentGraphMode == $this->GRAPH_TYPE_STACKEDBAR) { //the zero-line $this->objChart->setFontProperties(class_resourceloader::getInstance()->getCorePathForModule("module_system", true) . "/module_system/system" . $this->strFont, 6); $this->objChart->drawTreshold(0, 143, 55, 72, TRUE, TRUE); $this->objChart->drawStackedBarGraph($this->objDataset->GetData(), $this->objDataset->GetDataDescription(), 75); } else { if ($this->intCurrentGraphMode == $this->GRAPH_TYPE_PIE) { $this->objChart->drawPieGraph($this->objDataset->GetData(), $this->objDataset->GetDataDescription(), ceil($this->intWidth / 2) - 20, ceil($this->intHeight / 2), ceil($intHeight / 2) + 20, PIE_PERCENTAGE, TRUE, 50, 20, 5); } } } } //render values? if (count($this->arrValueSeriesToRender) > 0) { $this->objChart->writeValues($this->objDataset->GetData(), $this->objDataset->GetDataDescription(), $this->arrValueSeriesToRender); } // Finish the graph $this->objChart->setFontProperties(class_resourceloader::getInstance()->getCorePathForModule("module_system", true) . "/module_system/system" . $this->strFont, 7); //set up the legend if ($this->bitRenderLegend) { if ($this->intCurrentGraphMode == $this->GRAPH_TYPE_PIE) { $this->objChart->drawPieLegend($this->intWidth - $intLegendWidth - $intRightMargin + 10 - $this->intLegendAdditionalMargin, $intTopStart, $this->objDataset->GetData(), $this->objDataset->GetDataDescription(), 255, 255, 255); } else { $arrLegend = $this->objDataset->GetDataDescription(); //merge legends if ($this->bitAdditionalDatasetAdded) { $arrAdditionalLegend = $this->objAdditionalDataset->GetDataDescription(); foreach ($arrAdditionalLegend["Description"] as $strKey => $strName) { $arrLegend["Description"][$strKey] = $strName; } } $this->objChart->drawLegend($this->intWidth - $intLegendWidth - $intRightMargin + 10 - $this->intLegendAdditionalMargin, $intTopStart, $arrLegend, 255, 255, 255); } } //draw the title if ($this->strGraphTitle != "") { $this->objChart->setFontProperties(class_resourceloader::getInstance()->getCorePathForModule("module_system", true) . "/module_system/system" . $this->strFont, 10); $this->objChart->drawTitle(0, $intTopMargin, $this->strGraphTitle, $arrFontColors[0], $arrFontColors[1], $arrFontColors[2], $this->intWidth, 10); } }
/** * Generates a big graph with the number of best results * @param array */ static function generate_exercise_result_graph($attempts) { require_once api_get_path(LIBRARY_PATH).'pchart/pData.class.php'; require_once api_get_path(LIBRARY_PATH).'pchart/pChart.class.php'; require_once api_get_path(LIBRARY_PATH).'pchart/pCache.class.php'; $exercise_title = strip_tags($attempts['title']); $attempts = $attempts['data']; $my_exercise_result_array = $exercise_result = array(); if (empty($attempts)) { return null; } foreach ($attempts as $attempt) { if (api_get_user_id() == $attempt['exe_user_id']) { if ($attempt['exe_weighting'] != 0 ) { $my_exercise_result_array[]= $attempt['exe_result']/$attempt['exe_weighting']; } } else { if ($attempt['exe_weighting'] != 0 ) { $exercise_result[]= $attempt['exe_result']/$attempt['exe_weighting']; } } } //Getting best result rsort($my_exercise_result_array); $my_exercise_result = 0; if (isset($my_exercise_result_array[0])) { $my_exercise_result = $my_exercise_result_array[0] *100; } $max = 100; $pieces = 5 ; $part = round($max / $pieces); $x_axis = array(); $final_array = array(); $my_final_array = array(); for ($i=1; $i <=$pieces; $i++) { $sum = 1; if ($i == 1) { $sum = 0; } $min = ($i-1)*$part + $sum; $max = ($i)*$part; $x_axis[]= $min." - ".$max; $count = 0; foreach($exercise_result as $result) { $percentage = $result*100; //echo $percentage.' - '.$min.' - '.$max."<br />"; if ($percentage >= $min && $percentage <= $max) { //echo ' is > '; $count++; } } //echo '<br />'; $final_array[]= $count; if ($my_exercise_result >= $min && $my_exercise_result <= $max) { $my_final_array[] = 1; } else { $my_final_array[] = 0; } } //Fix to remove the data of the user with my data for($i = 0; $i<=count($my_final_array); $i++) { if (!empty($my_final_array[$i])) { $my_final_array[$i] = $final_array[$i] + 1; //Add my result $final_array[$i] = 0; } } $cache = new pCache(); // Dataset definition $data_set = new pData(); $data_set->AddPoint($final_array,"Serie1"); $data_set->AddPoint($my_final_array,"Serie2"); $data_set->AddPoint($x_axis,"Serie3"); $data_set->AddAllSeries(); $data_set->SetAbsciseLabelSerie('Serie3'); $data_set->SetSerieName(get_lang('Score'),"Serie1"); $data_set->SetSerieName(get_lang('MyResults'),"Serie2"); $data_set->SetXAxisName(get_lang("Score")); // Initialise the graph $main_width = 500; $main_height = 250; $main_graph = new pChart($main_width,$main_height); $main_graph->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf',8); $main_graph->setGraphArea(50,30, $main_width -20,$main_height -50); $main_graph->drawFilledRoundedRectangle(10,10, $main_width- 10,$main_height -10,5,240,240,240); $main_graph->drawRoundedRectangle(7,7,$main_width - 7,$main_height - 7,5,230,230,230); $main_graph->drawGraphArea(255,255,255,TRUE); //SCALE_NORMAL, SCALE_START0, SCALE_ADDALLSTART0 $main_graph->drawScale($data_set->GetData(),$data_set->GetDataDescription(),SCALE_ADDALLSTART0, 150,150,150,TRUE,0,1,TRUE); $main_graph->drawGrid(4,TRUE,230,230,230,50); // Draw the 0 line $main_graph->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf',6); // $main_graph->drawTreshold(0,143,55,72,TRUE,TRUE); // Draw the bar graph $data_set->RemoveSerie("Serie3"); //$main_graph->drawBarGraph($data_set->GetData(),$data_set->GetDataDescription(),TRUE); //$main_graph->drawStackedBarGraph($data_set->GetData(),$data_set->GetDataDescription(),TRUE); $main_graph->drawOverlayBarGraph($data_set->GetData(),$data_set->GetDataDescription(), 100); // Finish the graph $main_graph->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf',8); $main_graph->drawLegend($main_width - 120,$main_height -100,$data_set->GetDataDescription(),255,255,255); $main_graph->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf',8); $main_graph->drawTitle(180,22,$exercise_title,50,50,50); $graph_id = 'exercise_result_graph'.Security::remove_XSS($_GET['course']).'-'.intval($_GET['session_id']).'-'.api_get_user_id(); if ($cache->IsInCache($graph_id, $data_set->GetData())) { //if (0) { //if we already created the img //echo 'in cache'; $img_file = $cache->GetHash($graph_id,$data_set->GetData()); } else { $cache->WriteToCache($graph_id, $data_set->GetData(), $main_graph); ob_start(); $main_graph->Stroke(); ob_end_clean(); $img_file = $cache->GetHash($graph_id, $data_set->GetData()); } $html = '<img src="'.api_get_path(WEB_ARCHIVE_PATH).$img_file.'">'; return $html; }
// $DataSet->SetAbsciseLabelSerie("Serie4"); // $DataSet->SetSerieName("Max Average","Serie1"); // $DataSet->SetSerieName("Min Average","Serie2"); $DataSet->SetSerieName("Temperature", "Serie3"); $DataSet->SetYAxisName("Kg"); $DataSet->SetXAxisName("week"); // Initialise the graph $Test = new pChart(600, 230); $Test->reportWarnings("GD"); $Test->setFixedScale(-12, 13, 5); // $Test->setFontProperties("Fonts/tahoma.ttf", 8); $Test->setGraphArea(65, 20, 570, 185); $Test->drawFilledRoundedRectangle(7, 7, 693, 223, 5, 243, 249, 249); $Test->drawRoundedRectangle(5, 5, 695, 225, 5, 230, 230, 230); $Test->drawGraphArea(243, 249, 249, TRUE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2, TRUE, 3); $Test->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line // $Test->setFontProperties("Fonts/tahoma.ttf",6); // $Test->drawTreshold(0,143,55,72,TRUE,TRUE); // Draw the area // $DataSet->RemoveSerie("Serie4"); // $Test->drawArea($DataSet->GetData(),"Serie1","Serie2",239,238,227,50); // $DataSet->RemoveSerie("Serie3"); // $Test->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription()); // Draw the line graph // $Test->setLineStyle(1,0); // $DataSet->RemoveAllSeries(); // $DataSet->AddSerie("Serie3"); $Test->drawLineGraph($DataSet->GetData(), $DataSet->GetDataDescription());
public function componentLineGraph() { $DataSet = new pData(); $maxvals = array(); foreach ($this->datasets as $ds_id => $dataset) { $DataSet->AddPoint($dataset['values'], "Serie" . $ds_id, array_keys($dataset['values'])); $maxvals[] = max($dataset['values']); if (isset($dataset['burndown'])) { $amount = count($dataset['values']) > 1 ? $dataset['burndown']['maxEstimation'] / (count($dataset['values']) - 1) : 0; for ($i = 0; $i < count($dataset['values']); $i++) { $burndownValues[] = $dataset['burndown']['maxEstimation'] - $i * $amount; } $DataSet->AddPoint($burndownValues, "Burndown" . $ds_id, $dataset['burndown']['maxEstimation']); } } $DataSet->AddAllSeries(); if (isset($this->labels)) { $DataSet->AddPoint($this->labels, "Labels"); $DataSet->SetAbsciseLabelSerie("Labels"); } else { $DataSet->SetAbsciseLabelSerie(); } foreach ($this->datasets as $ds_id => $dataset) { $DataSet->SetSerieName($dataset['label'], "Serie" . $ds_id); if (isset($dataset['burndown'])) { $DataSet->SetSerieName($dataset['burndown']['label'], "Burndown" . $ds_id); } } if (isset($this->values_title)) { $DataSet->SetYAxisName($this->values_title); } if (isset($this->labels_title)) { $DataSet->SetXAxisName($this->labels_title); } // Initialise the graph $Test = new pChart($this->width, $this->height); $Test->setFixedScale(0, ceil(max($maxvals) / 5) * 5); $Test->setFontProperties(THEBUGGENIE_MODULES_PATH . 'pchart' . DS . 'fonts' . DS . 'DroidSans.ttf', 8); if (isset($this->labels_title)) { $Test->setGraphArea(50, 30, $this->width - 30, $this->height - 45); } else { $Test->setGraphArea(50, 30, $this->width - 30, $this->height - 30); } $Test->drawFilledRoundedRectangle(2, 2, $this->width - 3, $this->height - 3, 5, 240, 240, 240); $Test->drawRoundedRectangle(0, 0, $this->width - 1, $this->height - 1, 5, 230, 230, 230); $Test->drawGraphArea(255, 255, 255, TRUE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2); $Test->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line $Test->setFontProperties(THEBUGGENIE_MODULES_PATH . 'pchart' . DS . 'fonts' . DS . 'DroidSans.ttf', 6); $Test->drawTreshold(0, 143, 55, 72, TRUE, TRUE); // Draw the cubic curve graph if (isset($this->style) && $this->style == 'curved') { $Test->drawCubicCurve($DataSet->GetData(), $DataSet->GetDataDescription()); } elseif (isset($this->style) && $this->style == 'filled_line') { $Test->drawFilledLineGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 50, true); } elseif (isset($this->style) && $this->style == 'stacked_bar') { $Test->drawStackedBarGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 50, true); } elseif (isset($this->style) && $this->style == 'single_bar') { $Test->drawBarGraph($DataSet->GetData(), $DataSet->GetDataDescription(), TRUE); } else { $Test->drawLineGraph($DataSet->GetData(), $DataSet->GetDataDescription()); } if (isset($this->include_plotter) && $this->include_plotter) { $Test->drawPlotGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 3, 2, 255, 255, 255); } // Finish the graph $Test->setFontProperties(THEBUGGENIE_MODULES_PATH . 'pchart' . DS . 'fonts' . DS . 'DroidSans.ttf', 8); //$Test->drawLegend(600, 30, $DataSet->GetDataDescription(), 255, 255, 255); $Test->drawLegend(55, 35, $DataSet->GetDataDescription(), 255, 255, 255); $Test->setFontProperties(THEBUGGENIE_MODULES_PATH . 'pchart' . DS . 'fonts' . DS . 'DroidSansBold.ttf', 10); $Test->drawTitle(50, 22, $this->title, 50, 50, 50, $this->width - 30); $Test->Stroke(); //("example2.png"); }
/** * Render graph * *@return nothing **/ function render($p_stack = FALSE) { // declare the graph $Test = new pChart(800, 250); $Test->tmpFolder = $this->tmpPath; $fileId = time() . '_' . rand(1, 1000); $fontFile = "tahoma.ttf"; // prepare the map echo '<SCRIPT TYPE="text/javascript" SRC="' . $this->pChartPath . 'overlib.js"></SCRIPT> <SCRIPT TYPE="text/javascript" SRC="' . $this->pChartPath . 'pMap.js"></SCRIPT>'; $MapID = "map_" . $fileId . ".map"; $Test->setImageMap(TRUE, $MapID); $Map = new pChart(800, 250); $Map->tmpFolder = $this->tmpPath; $imgName = "img_" . $fileId . ".png"; $img = $this->tmpPath . $imgName; $imgLink = GLPI_ROOT . "/plugins/fusioninventory/front/send.php?file=" . urlencode("tmp/" . $imgName); $mapLink = GLPI_ROOT . "/plugins/fusioninventory/front/send.php?file=" . urlencode("tmp/" . $MapID); echo '<DIV ID="overDiv" STYLE="position:absolute; visibility:hidden; z-index:1000;"></DIV>'; echo "<IMG ID='fusioninventory_graph_{$fileId}' SRC='{$imgLink}' WIDTH=800 HEIGHT=250 BORDER=0 OnMouseMove='fusioninventory_graph(event);' OnMouseOut='nd();'>"; echo '<SCRIPT> function fusioninventory_graph(event) { LoadImageMap("fusioninventory_graph_' . $fileId . '","' . $mapLink . '"); getMousePosition(event); } </SCRIPT>'; // configure the graph $Test->setFontProperties($this->fontsPath . $fontFile, 8); $Test->setGraphArea(80, 30, 580, 185); // graph size : keep place for titles on X and Y axes $Test->drawFilledRoundedRectangle(7, 7, 793, 243, 5, 240, 240, 240); // background rectangle $Test->drawRoundedRectangle(5, 5, 795, 245, 5, 230, 230, 230); // 3D effect $Test->drawGraphArea(255, 255, 255, TRUE); $Test->setFixedScale(0, $this->getMaxY($this->maxValue), $this->divisionsY); // to see values from 0 $Test->drawScale($this->pData->GetData(), $this->pData->GetDataDescription(), SCALE_ADDALL, 150, 150, 150, TRUE, 0, 2, TRUE); $Test->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the 0 line $Test->setFontProperties($this->fontsPath . $fontFile, 6); // Draw the bar graph if ($p_stack) { $Test->drawStackedBarGraph($this->pData->GetData(), $this->pData->GetDataDescription(), 100); } else { $Test->drawBarGraph($this->pData->GetData(), $this->pData->GetDataDescription(), FALSE, 100); } // Finish the graph $Test->setFontProperties($this->fontsPath . $fontFile, 8); $Test->drawLegend(590, 30, $this->pData->GetDataDescription(), 255, 255, 255); // take care of legend text size $Test->setFontProperties($this->fontsPath . $fontFile, 10); $Test->drawTitle(50, 22, $this->title . ' (/ ' . $this->timeUnitName . ')', 50, 50, 50, 585); $Test->Render($img); }
$DataSet->AddSerie("Serie" . $j); } $DataSet->SetAbsciseLabelSerie("Serie" . $allmonth_i); $z = 0; foreach ($seriesname as $currentseriesname) { $z++; $DataSet->SetSerieName($currentseriesname, "Serie" . $z); } // $DataSet->SetSerieName("Expenses","Serie2"); $DataSet->SetYAxisName("Amount({$defcurrencycode})"); $Test = new pChart(800, 330); $Test->setFontProperties("../system/class/pchart/Fonts/tahoma.ttf", 8); $Test->setGraphArea(65, 30, 650, 300); $Test->drawFilledRoundedRectangle(7, 7, 793, 325, 5, 254, 254, 254); $Test->drawRoundedRectangle(5, 5, 794, 325, 5, 254, 10, 10); $Test->drawGraphArea(254, 254, 254, TRUE); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2, TRUE); $Test->drawGrid(4, TRUE, 230, 230, 230, 50); // Draw the title $Test->setFontProperties("../system/class/pchart/Fonts/pf_arma_five.ttf", 10); $Title = "Chart Generator From Balance Sheet({$defaultorganization_name})"; $Test->drawTextBox(65, 12, 650, 25, $Title, 0, 0, 0, 1, ALIGN_CENTER, FALSE, 254, 254, 254, 30); // Draw the line graph $Test->drawLineGraph($DataSet->GetData(), $DataSet->GetDataDescription()); $Test->drawPlotGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 3, 2, 254, 254, 254); // Draw the legend $Test->setFontProperties("../system/class/pchart/Fonts/tahoma.ttf", 8); $Test->drawLegend(655, 20, $DataSet->GetDataDescription(), 254, 254, 254); // Render the chart $random = rand(); $photofile = "chartcache/balancesheetchartgenerated{$random}.png";
/** * This method return a content html, it's used inside get_block method for showing it inside dashboard interface * @return string content html */ public function get_teachers_information_graph() { $teachers = $this->teachers; $graph = ''; $user_ids = array_keys($teachers); $a_last_week = get_last_week(); if (is_array($user_ids) && count($user_ids) > 0) { $data_set = new pData(); foreach ($user_ids as $user_id) { $teacher_info = api_get_user_info($user_id); $username = $teacher_info['username']; $time_by_days = array(); foreach ($a_last_week as $day) { // day is received as y-m-d 12:00:00 $start_date = api_get_utc_datetime($day); $end_date = api_get_utc_datetime($day + (3600 * 24 - 1)); $time_on_platform_by_day = Tracking::get_time_spent_on_the_platform($user_id, 'custom', $start_date, $end_date); $hours = floor($time_on_platform_by_day / 3600); $min = floor(($time_on_platform_by_day - $hours * 3600) / 60); $time_by_days[] = $min; } $data_set->AddPoint($time_by_days, $username); $data_set->AddSerie($username); } $last_week = date('Y-m-d', $a_last_week[0]) . ' ' . get_lang('To') . ' ' . date('Y-m-d', $a_last_week[6]); $days_on_week = array(); foreach ($a_last_week as $weekday) { $days_on_week[] = date('d/m', $weekday); } $data_set->AddPoint($days_on_week, "Days"); $data_set->SetXAxisName($last_week); $data_set->SetYAxisName(get_lang('Minutes')); $data_set->SetAbsciseLabelSerie("Days"); $graph_id = $this->user_id . 'TeacherConnectionsGraph'; $cache = new pCache(); // the graph id $data = $data_set->GetData(); if ($cache->IsInCache($graph_id, $data_set->GetData())) { //if we already created the img $img_file = $cache->GetHash($graph_id, $data_set->GetData()); } else { // Initializing the graph $bg_width = 440; $bg_height = 350; $test = new pChart($bg_width + 10, $bg_height + 20); $test->setFontProperties(api_get_path(LIBRARY_PATH) . 'pchart/fonts/tahoma.ttf', 8); $test->setGraphArea(65, 30, $bg_width - 70, $bg_height - 50); $test->drawFilledRoundedRectangle(7, 7, $bg_width, $bg_height, 5, 240, 240, 240); $test->drawRoundedRectangle(5, 5, $bg_width + 2, $bg_height + 2, 5, 230, 230, 230); $test->drawGraphArea(255, 255, 255, TRUE); $test->drawScale($data_set->GetData(), $data_set->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 0, 2, TRUE); $test->drawGrid(4, TRUE, 230, 230, 230, 50); // Drawing lines //$test->drawLineGraph($data_set->GetData(),$data_set->GetDataDescription()); $test->drawFilledCubicCurve($data_set->GetData(), $data_set->GetDataDescription(), 0.1, 30); //$test->drawPlotGraph($data_set->GetData(),$data_set->GetDataDescription(),3,2,255,255,255); // Drawing Legend $test->setFontProperties(api_get_path(LIBRARY_PATH) . 'pchart/fonts/tahoma.ttf', 8); $test->drawLegend($bg_width - 80, 20, $data_set->GetDataDescription(), 204, 204, 255); $test->writeValues($data_set->GetData(), $data_set->GetDataDescription(), array("Days")); $cache->WriteToCache($graph_id, $data_set->GetData(), $test); ob_start(); $test->Stroke(); ob_end_clean(); $img_file = $cache->GetHash($graph_id, $data_set->GetData()); } if (!empty($img_file)) { $graph = '<img src="' . api_get_path(WEB_ARCHIVE_PATH) . $img_file . '">'; } } else { $graph = '<p>' . api_convert_encoding(get_lang('GraphicNotAvailable'), 'UTF-8') . '</p>'; } return $graph; }
<?php /* SmallGraph: Let's go fast, draw small! */ // Standard inclusions include "src/pData.php"; include "src/pChart.php"; // Dataset definition $DataSet = new pData(); $DataSet->AddPoint(array(1, 4, -3, 2, -3, 3, 2, 1, 0, 7, 4, -3, 2, -3, 3, 5, 1, 0, 7), "Serie1"); $DataSet->AddAllSeries(); $DataSet->SetAbsciseLabelSerie(); $DataSet->SetSerieName("January", "Serie1"); // Initialise the graph $Test = new pChart(100, 30); $Test->setFontProperties("Fonts/tahoma.ttf", 8); $Test->drawFilledRoundedRectangle(2, 2, 98, 28, 2, 230, 230, 230); $Test->setGraphArea(5, 5, 95, 25); $Test->drawGraphArea(255, 255, 255); $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 220, 220, 220, FALSE); // Draw the line graph $Test->drawLineGraph($DataSet->GetData(), $DataSet->GetDataDescription()); // Finish the graph $Test->Render("SmallGraph.png");