Proyectos de Subversion Moodle

Rev

Rev 1049 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php
use core_completion\progress;
require_once $CFG->libdir . '/badgeslib.php';

class block_progreso_detalles_renderer extends plugin_renderer_base {

    public function procesar($instance_id) {
        
        global $USER, $CFG, $DB, $PAGE, $OUTPUT;
        
        require_once $CFG->libdir . '/completionlib.php';
        require_once $CFG->dirroot.'/completion/classes/progress.php';
        require_once $CFG->dirroot  . '/course/classes/category.php';
        require_once $CFG->libdir . '/gradelib.php';
        require_once $CFG->dirroot . '/grade/querylib.php';
        
        //require_once $CFG->libdir . '/coursecatlib.php';
        $url_noimage =  $CFG->wwwroot . '/theme/' . $PAGE->theme->name . '/pix/coursenoimage.jpg';
        
        if (!file_exists($CFG->dirroot.'/cesa/progreso_detalles/')) {
            mkdir($CFG->dirroot.'/cesa/progreso_detalles/', 0755, true);
        }
        if (!file_exists($CFG->dirroot.'/cesa/progreso_detalles/'.$USER->id)) {
            mkdir($CFG->dirroot.'/cesa/progreso_detalles/'.$USER->id, 0755, true);
        }
        $oldfiles = glob($CFG->dirroot.'/cesa/progreso_detalles/'.$USER->id.'/*');
        foreach ($oldfiles as $file) {
            if (is_file($file)) {
                unlink($file);
            }
        }
        /** Inicio del seteo de las variables para el area del cuadro de progreso */
        $dedication = 0;
        $completed  = 0;
        $inprogress = 0;
        $grades     = 0;
        $points     = 0;
        $badges     = 0;
        $content    = '';
        /** Inicio de las variables para el area de */
        
        $user       = $DB->get_record('user',array('id'=> $USER->id)); 
        $mycourses  = enrol_get_users_courses($USER->id);
        $max_time   = time();
        $min_time   = strtotime('-1 YEAR');
        $limit      = 3600;

        $data = [
            'user_name'         => $user->firstname . ' ' . $user->lastname  ,
            'user_image'        => $OUTPUT->user_picture($user, array('size' => 100, 'link' => false, 'alttext' => false)),
            'user_email'        => $user->email,
            'graph_dedication'  => '',
            'completed'         => 0,
            'inprogress'        => 0,
            'total_dedication'  => '',
            'courses'           => []
        ];
        

        

        $graph_percentage = [];
        $graph_dedication = [];
        $graph_labels = [];
        
        
        $completed = 0;
        $inprogress = 0;
        $dedication = 0;
        $total_dedication = 0;

        
        foreach($mycourses as $key => $val) {
            $course = get_course($val->id);
            $modules = get_fast_modinfo($val->id)->get_cms();
            $linkurl = '';

            $first_section = 0;
            $sections = $DB->get_records('course_sections', ['course' => $course->id], 'section ASC', 'id,name,section,sequence,visible');

            foreach($sections as $section) 
            {
                                if(!empty($section->section)) {
                                        $first_section = $section->id;
                                        break;
                                }
                        }

            foreach ($modules as $module) 
                        {
                                if (!$module->uservisible || $module->is_stealth() || empty($module->url) || empty($module->section)) {
                                        continue;
                                }
                        
                                if($module->section == $first_section) {
                                        $linkurl =  new moodle_url($module->url, array('forceview' => 1));
                                        
                                        break;
                }
                        }

            if ($course instanceof stdClass) {
                $courseInList = new core_course_list_element($course);
            }
            $image = $url_noimage;
            foreach ($courseInList->get_course_overviewfiles() as $file)
            {
                $isimage = $file->is_valid_image();
                $image = file_encode_url("{$CFG->wwwroot}/pluginfile.php", '/' . $file->get_contextid() . '/' . $file->get_component() . '/' . $file->get_filearea() . $file->get_filepath() . $file->get_filename(), !$isimage);
                if (!$isimage) {
                    $image = $url_noimage;
                }
            }
            
            $lastaccess = null;
            $sql = "select timecreated  from {logstore_standard_log} where courseid  = :courseid and userid  = :userid " .
                "  and eventname  = '\\\\core\\\\event\\\\course_viewed' order by id desc limit 1 ";
            
            $timecreated = $DB->get_field_sql($sql,  array('courseid' => $course->id, 'userid' => $USER->id));
            if($timecreated) {
                
                $lastaccess = date('d/m/Y h:i a', $timecreated);
            }
            
            $category = $DB->get_record('course_categories',array('id'=>$course->category));
            
            
            $completion = new \completion_info($course);
            $percentage = progress::get_course_progress_percentage($course,$USER->id);
            //             echo 'course->fullname = '.$course->fullname."% = [$percentage]<br>";
            if ($completion->is_enabled()) {
                $percentage = progress::get_course_progress_percentage($course);
                $percentage = floatval(!$percentage ? 0 :  $percentage);

            } else {
                $percentage = 0;
            }
            
  
            if($percentage >= 100) {
                $completed++;
            } else {
                $inprogress++;
            }
            
            $resultkrb =  grade_get_course_grades($course->id, $USER->id);
            
            
            $grd = $resultkrb->grades[$USER->id];
            $dedication = $this->get_students_dedication($USER->id, $course->id, $min_time, $max_time, $limit);
            
            $total_dedication = $total_dedication + $dedication;
            
            $graph_percentage[] = number_format($percentage, 2);
            $graph_labels[] = $course->shortname;
            
            
            $data['courses'][] = [
                
                'coursecategory' => $category->name,
                'courseimage' => $image,
                'enddate' => $course->enddate,
                'shortname' => $course->shortname,
                'fullname' => $course->fullname,
                'fullnamedisplay' => get_course_display_name_for_list($course),
                'hasprogress' => $percentage > 0,
                'hidden' => false,
                'id' => $course->id,
                'idnumber' => $course->idnumber,
                'isfavourite' => false,
                'progress' => number_format($percentage, 2),
                'shortname' => $course->shortname,
                'showshortname' => false,
                'startdate' => $course->startdate,
                'summary' => $course->summary,
                'summaryformat' => $course->summaryformat,
                'timeaccess' => $lastaccess,
                // 'viewurl' => $CFG->wwwroot . '/course/view.php?id=' . $course->id,
                'viewurl' => $linkurl,
                'visible' => true,
                'grade' => $grd->str_grade,
                'dedication' => $dedication,
                'percentage' => number_format($percentage, 2),
            ];
        }

        $dedication = 0;        
        for($i = 0, $max = count($data['courses']); $i < $max; $i++) 
        {
            $dedication = ($data['courses'][$i][ 'dedication'] * 100) / $total_dedication;
             
            $data['courses'][$i][ 'dedication']  = $this->format_dedication($data['courses'][$i][ 'dedication']);
            array_push($graph_dedication, number_format($dedication, 2));
        }
        

 
        $serie_dedication = new core\chart_series('Dedicación', $graph_dedication);
        $serie_percentage = new core\chart_series('Progreso', $graph_percentage);

        

        $chart = new core\chart_bar();

       
        
        $chart->set_title('Dedicación/Progreso en %');
        $chart->set_horizontal(true); // Calling set_horizontal() passing true as parameter will display horizontal bar charts.
        $chart->add_series( $serie_dedication );
        $chart->add_series( $serie_percentage);
        $chart->set_labels($graph_labels);

        $data['graph_dedication'] = $OUTPUT->render_chart($chart, true); //true muesta tabla de datos, false no
        
        
        $data['completed']          = $completed;
        $data['inprogress']         = $inprogress;
        $data['total_dedication']   = $this->format_dedication($total_dedication);

        // Inicio de agregado de cuadro curso
        $records = badges_get_user_badges($USER->id,null, null, null, null, true);
        $badges = count($records);
        if(0 != $completed || 0 != $inprogress) {
            $points = (int) ($points / ($completed + $inprogress));
        }
        
        $data['dedication']   = $this->format_dedication($total_dedication);
        $data['grades']   = $badges;
        $data['points']   = $points;
        
        $imgUser = new moodle_url('/user/pix.php/'.$USER->id.'/f1.jpg');
        $data['user_username']   = $USER->username;
        $data['user_profile_picture']   = $imgUser;
        
        $div_cuadro_inf = $OUTPUT->render_from_template('block_progreso_sinopsis/full', $data); //true muesta tabla de datos, false no
        
        $data['div_cuadro_inf']   = $div_cuadro_inf;
        // Fin de agregado de cuadro curso
        
        $content .= html_writer::start_tag('div', array('class' => 'container')); //'d-flex flex-row bd-highlight mb-3'));
        $content .= $this->render_from_template('block_progreso_detalles/full', $data); 
        $content .= html_writer::end_tag('div');    
        $content = str_replace('<!--USER-IMAGE-->', $data['user_image'], $content);
        $content = str_replace('<!--GRAPH-DEDICATION-->', $data['graph_dedication'], $content);
        
        
        return $content;
    }
    
    public static function format_dedication($totalsecs) {
        $totalsecs = abs($totalsecs);
        
        $str = new stdClass();
        $str->hour = get_string('hour');
        $str->hours = get_string('hours');
        $str->min = get_string('min');
        $str->mins = get_string('mins');
        $str->sec = get_string('sec');
        $str->secs = get_string('secs');
        
        $hours = floor($totalsecs / HOURSECS);
        $remainder = $totalsecs - ($hours * HOURSECS);
        $mins = floor($remainder / MINSECS);
        $secs = round($remainder - ($mins * MINSECS), 2);
        
        $ss = ($secs == 1) ? $str->sec : $str->secs;
        $sm = ($mins == 1) ? $str->min : $str->mins;
        $sh = ($hours == 1) ? $str->hour : $str->hours;
        
        $ohours = '';
        $omins = '';
        $osecs = '';
        
        if ($hours) {
            //             $ohours = $hours . ' ' . $sh;
                        $ohours = $hours . ' ' . 'h';
                    }
                    if ($mins) {
            //             $omins = $mins . ' ' . $sm;
                        $omins = $mins . ' ' . 'm';
                    }
                    if ($secs) {
            //             $osecs = $secs . ' ' . $ss;
                        $osecs = $secs . ' ' . 's';
                    }
        
        if ($hours) {
            return trim($ohours . ' ' . $omins);
        }
        if ($mins) {
            return trim($omins . ' ' . $osecs);
        }
        if ($secs) {
            return $osecs;
        }
        return get_string('none');
    }
    
    public function get_events_select($selectwhere, array $params)
    {
        $logstores  = ['logstore_standard', 'logstore_legacy'];
        $return     = [];
        
        static $allreaders = null;
        
        if (is_null($allreaders)) {
            $allreaders = get_log_manager()->get_readers();
        }
        
        $processedreaders = 0;
        
        foreach ($logstores as $name) {
            if (isset($allreaders[$name])) {
                $reader = $allreaders[$name];
                $events = $reader->get_events_select($selectwhere, $params, 'timecreated ASC', 0, 0);
                foreach ($events as $event) {
                    // Note: see \core\event\base to view base class of event.
                    $obj = new stdClass();
                    $obj->time = $event->timecreated;
                    $obj->ip = $event->get_logextra()['ip'];
                    $return[] = $obj;
                }
                if (!empty($events)) {
                    $processedreaders++;
                }
            }
        }
        
        // Sort mixed array by time ascending again only when more of a reader has added events to return array.
        if ($processedreaders > 1) {
            usort($return, function($a, $b) {
                return $a->time > $b->time;
            });
        }
        
        return $return;
    }
    
    public function get_students_dedication($user_id, $course_id, $min_time, $max_time, $limit)
    {
        
        $where = 'courseid = :courseid AND userid = :userid AND timecreated >= :mintime AND timecreated <= :maxtime';
        $params = array(
            'courseid'  => $course_id,
            'userid'    => $user_id,
            'mintime'   => $min_time,
            'maxtime'   => $max_time
        );
        
        
        $logs = $this->get_events_select($where, $params);
        if ($logs) {
            $previouslog = array_shift($logs);
            $previouslogtime = $previouslog->time;
            $sessionstart = $previouslog->time;
            $dedication = 0;
            
            foreach ($logs as $log) {
                if (($log->time - $previouslogtime) > $limit) {
                    $dedication += $previouslogtime - $sessionstart;
                    $sessionstart = $log->time;
                }
                $previouslogtime = $log->time;
            }
            $dedication += $previouslogtime - $sessionstart;
        } else {
            $dedication = 0;
        }
        return $dedication;
        
    }

    

}