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.'">';
         }
         */
     }
 }
	/**
 	 * 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;
 	}
    /**
     * 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;
    }
 /**
  * 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;
 }
 /**
  * This method return a graph containing informations about students evaluation, it's used inside get_block method for showing it inside dashboard interface
  * @return string  img html
  */
 public function get_students_attendance_graph()
 {
     $students = $this->students;
     $attendance = new Attendance();
     // get data
     $attendances_faults_avg = array();
     if (is_array($students) && count($students) > 0) {
         foreach ($students as $student) {
             $student_id = $student['user_id'];
             //$student_info = api_get_user_info($student_id);
             // get average of faults in attendances by student
             $results_faults_avg = $attendance->get_faults_average_inside_courses($student_id);
             if (!empty($results_faults_avg)) {
                 $attendances_faults_avg[$student['lastname']] = $results_faults_avg['porcent'];
             } else {
                 $attendances_faults_avg[$student['lastname']] = 0;
             }
         }
     }
     arsort($attendances_faults_avg);
     $usernames = array_keys($attendances_faults_avg);
     $faults = array();
     foreach ($usernames as $username) {
         $faults[] = $attendances_faults_avg[$username];
     }
     $graph = '';
     $img_file = '';
     if (is_array($usernames) && count($usernames) > 0) {
         // Defining data
         $data_set = new pData();
         $data_set->AddPoint($faults, "Promedio");
         $data_set->AddPoint($usernames, "Usuario");
         $data_set->AddAllSeries();
         $data_set->SetAbsciseLabelSerie("Usuario");
         // prepare cache for saving image
         $graph_id = $this->user_id . 'StudentEvaluationGraph';
         // the graph id
         $cache = new pCache(api_get_path(SYS_ARCHIVE_PATH));
         $data = $data_set->GetData();
         // return $this->DataDescription
         if ($cache->IsInCache($graph_id, $data_set->GetData())) {
             //if (0) {
             //if we already created the img
             $img_file = $cache->GetHash($graph_id, $data_set->GetData());
             // image file with hash
         } else {
             if (count($usernames) < 5) {
                 $height = 200;
             } else {
                 $height = count($usernames) * 40;
             }
             // Initialise the graph
             $test = new MyHorBar(400, $height + 30);
             $test->setFontProperties(api_get_path(LIBRARY_PATH) . 'pchart/fonts/tahoma.ttf', 8);
             $test->setGraphArea(100, 30, 370, $height);
             $test->drawFilledRoundedRectangle(7, 7, 393, $height, 5, 240, 240, 240);
             $test->drawRoundedRectangle(5, 5, 395, $height, 5, 230, 230, 230);
             $test->drawGraphArea(255, 255, 255, TRUE);
             //X axis
             $test->setFixedScale(0, 100, 10);
             //var_dump($data_set->GetDataDescription());
             $test->drawHorScale($data_set->GetData(), $data_set->GetDataDescription(), SCALE_ADDALL, 150, 150, 150, TRUE, 0, 0, TRUE);
             $test->setColorPalette(0, 255, 0, 0);
             $test->drawHorGrid(10, 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->drawHorBarGraph($data_set->GetData(), $data_set->GetDataDescription(), TRUE, 50);
             $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;
 }
/**
 * This function draw the graphic to be displayed on the user view as an image
 *
 * @param array $sql_result
 * @param string $start_date
 * @param string $end_date
 * @param string $type
 * @author Jorge Frisancho Jibaja
 * @version OCT-22- 2010
 * @return string
 */
function grapher($sql_result, $start_date, $end_date, $type = "") {
    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';

    if (empty($start_date)) { $start_date =""; }
    if (empty($end_date)) { $end_date =""; }
    if ($type == ""){ $type = 'day'; }
    $main_year  = $main_month_year = $main_day = array();
    // get last 8 days/months
    $last_days      = 5;
    $last_months    = 3;
    for ($i = $last_days; $i >= 0; $i--) {
        $main_day[date ('d-m-Y', mktime () - $i * 3600 * 24)] = 0;
    }
    for ($i = $last_months; $i >= 0; $i--) {
        $main_month_year[date ('m-Y', mktime () - $i * 30 * 3600 * 24)] = 0;
    }

    $i = 0;
    if (is_array($sql_result) && count($sql_result) > 0) {
        foreach ($sql_result as $key => $data) {
            //creating the main array
            $main_month_year[date('m-Y', $data['login'])] += float_format(($data['logout'] - $data['login']) / 60, 0);
            $main_day[date('d-m-Y', $data['login'])] += float_format(($data['logout'] - $data['login']) / 60, 0);
            if ($i > 500) {
                break;
            }
            $i++;
        }

        switch ($type) {
            case 'day':
                $main_date = $main_day;
                break;
            case 'month':
                $main_date = $main_month_year;
                break;
            case 'year':
                $main_date = $main_year;
                break;
        }

        // the nice graphics :D
        $labels = array_keys($main_date);
        if (count($main_date) == 1) {
            $labels = $labels[0];
            $main_date = $main_date[$labels];
        }

        $data_set = new pData();
        $data_set->AddPoint($main_date, 'Q');
        if (count($main_date)!= 1) {
            $data_set->AddPoint($labels, 'Date');
        }
        $data_set->AddAllSeries();
        $data_set->RemoveSerie('Date');
        $data_set->SetAbsciseLabelSerie('Date');
        $data_set->SetYAxisName(get_lang('Minutes', ''));
        $graph_id = api_get_user_id().'AccessDetails'.api_get_course_id().$start_date.$end_date.$type;
        $data_set->AddAllSeries();

        $cache = new pCache();
        // the graph id
        $data = $data_set->GetData();

        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 {
            // if the image does not exist in the archive/ folder
            // Initialise the graph
            $test = new pChart(760, 230);

            //which schema of color will be used
            $quant_resources = count($data[0]) - 1;
            // Adding the color schemma
            $test->loadColorPalette(api_get_path(LIBRARY_PATH).'pchart/palette/default.txt');

            $test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf', 8);
            $test->setGraphArea(70, 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($data_set->GetData(), $data_set->GetDataDescription(), SCALE_START0, 150, 150, 150, TRUE, 0, 0);
            $test->drawGrid(4, TRUE, 230, 230, 230, 50);
            $test->setLineStyle(2);
            // Draw the 0 line
            $test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf', 6);
            $test->drawTreshold(0, 143, 55, 72, TRUE, TRUE);

            if (count($main_date) == 1) {
                //Draw a graph
                echo '<strong>'.$labels.'</strong><br/>';
                $test->drawBarGraph($data_set->GetData(), $data_set->GetDataDescription(), TRUE);
            } else {
                //Draw the line graph
                $test->drawLineGraph($data_set->GetData(), $data_set->GetDataDescription());
                $test->drawPlotGraph($data_set->GetData(), $data_set->GetDataDescription(), 3, 2, 255, 255, 255);
            }

            // Finish the graph
            $test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf', 8);
            $test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf', 10);
            $test->drawTitle(60, 22, get_lang('AccessDetails'), 50, 50, 50, 585);

            //------------------
            //echo 'not in cache';
            $cache->WriteToCache($graph_id, $data_set->GetData(), $test);
            ob_start();
            $test->Stroke();
            ob_end_clean();
            $img_file = $cache->GetHash($graph_id, $data_set->GetData());
        }
        $foo_img = '<img src="'.api_get_path(WEB_ARCHIVE_PATH).$img_file.'">';
        return $foo_img;
    } else {
        $foo_img = api_convert_encoding('<div id="messages" class="warning-message">'.get_lang('GraphicNotAvailable').'</div>','UTF-8');
        return $foo_img;
    }

}