Modificación Bloque Moodle 2.8.3

Modificación Bloque Moodle 2.8.3

de Josep Vargas -
Número de respuestas: 0

Buenas tardes a tod@s;

Estoy intentando modificar el bloque "Course Overview" de Moodle 2.8.3 a partir del código modificado de otro bloque. La idea es que Course Overview, muestre también la categoría del curso dónde está alojado este, como lo hace el otro bloque. 


He intentado copiar el código del curso que sí realiza esta acción, pero sin éxito ya que no funciona correctamente.


Otra solución, sería añadir el bloque que sí muestra las categorías, en vez del "Coure Overview" pero... No funciona del todo correcto, por el JS. Seguramente sea un problema de compatibilidad, no lo tengo claro.


<?php

//Este no lo muestra como el otro código, ya que lo muestra debajo.  
define('BLOCKS_COURSE_OVERVIEW_SHOWCATEGORIES_NONE', '0');
define('BLOCKS_COURSE_OVERVIEW_SHOWCATEGORIES_ONLY_PARENT_NAME', '1');
define('BLOCKS_COURSE_OVERVIEW_SHOWCATEGORIES_FULL_PATH', '2');

/**
 * Display overview for courses
 *
 * @param array $courses courses for which overview needs to be shown
 * @return array html overview
 */
function block_course_overview_get_overviews($courses) {
    $htmlarray = array();
    if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
        // Split courses list into batches with no more than MAX_MODINFO_CACHE_SIZE courses in one batch.
        // Otherwise we exceed the cache limit in get_fast_modinfo() and rebuild it too often.
        if (defined('MAX_MODINFO_CACHE_SIZE') && MAX_MODINFO_CACHE_SIZE > 0 && count($courses) > MAX_MODINFO_CACHE_SIZE) {
            $batches = array_chunk($courses, MAX_MODINFO_CACHE_SIZE, true);
        } else {
            $batches = array($courses);
        }
        foreach ($batches as $courses) {
            foreach ($modules as $fname) {
                $fname($courses, $htmlarray);
            }
        }
    }
    return $htmlarray;
}

/**
 * Sets user preference for maximum courses to be displayed in course_overview block
 *
 * @param int $number maximum courses which should be visible
 */
function block_course_overview_update_mynumber($number) {
    set_user_preference('course_overview_number_of_courses', $number);
}

/**
 * Sets user course sorting preference in course_overview block
 *
 * @param array $sortorder list of course ids
 */
function block_course_overview_update_myorder($sortorder) {
    $value = implode(',', $sortorder);
    if (core_text::strlen($value) > 1333) {
        // The value won't fit into the user preference. Remove courses in the end of the list (mostly likely user won't even notice).
        $value = preg_replace('/,[\d]*$/', '', core_text::substr($value, 0, 1334));
    }
    set_user_preference('course_overview_course_sortorder', $value);
}

/**
 * Gets user course sorting preference in course_overview block
 *
 * @return array list of course ids
 */
function block_course_overview_get_myorder() {
    if ($value = get_user_preferences('course_overview_course_sortorder')) {
        return explode(',', $value);
    }
    // If preference was not found, look in the old location and convert if found.
    $order = array();
    if ($value = get_user_preferences('course_overview_course_order')) {
        $order = unserialize($value);
        block_course_overview_update_myorder($order);
        unset_user_preference('course_overview_course_order');
    }
    return $order;
}

/**
 * Returns shortname of activities in course
 *
 * @param int $courseid id of course for which activity shortname is needed
 * @return string|bool list of child shortname
 */
function block_course_overview_get_child_shortnames($courseid) {
    global $DB;
    $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
    $sql = "SELECT c.id, c.shortname, $ctxselect
            FROM {enrol} e
            JOIN {course} c ON (c.id = e.customint1)
            JOIN {context} ctx ON (ctx.instanceid = e.customint1)
            WHERE e.courseid = :courseid AND e.enrol = :method AND ctx.contextlevel = :contextlevel ORDER BY e.sortorder";
    $params = array('method' => 'meta', 'courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);

    if ($results = $DB->get_records_sql($sql, $params)) {
        $shortnames = array();
        // Preload the context we will need it to format the category name shortly.
        foreach ($results as $res) {
            context_helper::preload_from_record($res);
            $context = context_course::instance($res->id);
            $shortnames[] = format_string($res->shortname, true, $context);
        }
        $total = count($shortnames);
        $suffix = '';
        if ($total > 10) {
            $shortnames = array_slice($shortnames, 0, 10);
            $diff = $total - count($shortnames);
            if ($diff > 1) {
                $suffix = get_string('shortnamesufixprural', 'block_course_overview', $diff);
            } else {
                $suffix = get_string('shortnamesufixsingular', 'block_course_overview', $diff);
            }
        }
        $shortnames = get_string('shortnameprefix', 'block_course_overview', implode('; ', $shortnames));
        $shortnames .= $suffix;
    }

    return isset($shortnames) ? $shortnames : false;
}

/**
 * Returns maximum number of courses which will be displayed in course_overview block
 *
 * @param bool $showallcourses if set true all courses will be visible.
 * @return int maximum number of courses
 */
function block_course_overview_get_max_user_courses($showallcourses = false) {
    // Get block configuration
    $config = get_config('block_course_overview');
    $limit = $config->defaultmaxcourses;

    // If max course is not set then try get user preference
    if (empty($config->forcedefaultmaxcourses)) {
        if ($showallcourses) {
            $limit = 0;
        } else {
            $limit = get_user_preferences('course_overview_number_of_courses', $limit);
        }
    }
    return $limit;
}

/**
 * Return sorted list of user courses
 *
 * @param bool $showallcourses if set true all courses will be visible.
 * @return array list of sorted courses and count of courses.
 */
function block_course_overview_get_sorted_courses($showallcourses = false) {
    global $USER;

    $limit = block_course_overview_get_max_user_courses($showallcourses);

    $courses = enrol_get_my_courses();
    $site = get_site();

    if (array_key_exists($site->id,$courses)) {
        unset($courses[$site->id]);
    }

    foreach ($courses as $c) {
        if (isset($USER->lastcourseaccess[$c->id])) {
            $courses[$c->id]->lastaccess = $USER->lastcourseaccess[$c->id];
        } else {
            $courses[$c->id]->lastaccess = 0;
        }
    }

    // Get remote courses.
    $remotecourses = array();
    if (is_enabled_auth('mnet')) {
        $remotecourses = get_my_remotecourses();
    }
    // Remote courses will have -ve remoteid as key, so it can be differentiated from normal courses
    foreach ($remotecourses as $id => $val) {
        $remoteid = $val->remoteid * -1;
        $val->id = $remoteid;
        $courses[$remoteid] = $val;
    }

    $order = block_course_overview_get_myorder();

    $sortedcourses = array();
    $counter = 0;
    // Get courses in sort order into list.
    foreach ($order as $key => $cid) {
        if (($counter >= $limit) && ($limit != 0)) {
            break;
        }

        // Make sure user is still enroled.
        if (isset($courses[$cid])) {
            $sortedcourses[$cid] = $courses[$cid];
            $counter++;
        }
    }
    // Append unsorted courses if limit allows
    foreach ($courses as $c) {
        if (($limit != 0) && ($counter >= $limit)) {
            break;
        }
        if (!in_array($c->id, $order)) {
            $sortedcourses[$c->id] = $c;
            $counter++;
        }
    }

    // From list extract site courses for overview
    $sitecourses = array();
    foreach ($sortedcourses as $key => $course) {
        if ($course->id > 0) {
            $sitecourses[$key] = $course;
        }
    }
    return array($sortedcourses, $sitecourses, count($courses));
}



Código BLOCK que SÍ muestra las categorías. (La cuestión es ¿qué debo añadir de este código al código de "Course Overview" para que me muestre también las categorías de igual forma?)

<?php

require_once(dirname(dirname(dirname(__FILE__))).'/config.php');
require_once($CFG->dirroot . '/course/lib.php');
require_once($CFG->libdir . '/coursecatlib.php');

$overview = optional_param('overview', false, PARAM_BOOL);

if ($overview) {
    header('Content-type: text/plain');

    $strmymoodle = get_string('myhome');

    if (!empty($USER->id)) {
        $userid = $USER->id;  // Owner of the page
        $context = context_user::instance($USER->id);
        $PAGE->set_blocks_editing_capability('moodle/my:manageblocks');
        $header = "$SITE->shortname: $strmymoodle";

        $PAGE->set_context($context);
        $courses = enrol_get_my_courses();
        $site = get_site();
        if (array_key_exists($site->id, $courses)) {
            unset($courses[$site->id]);
        }
        foreach ($courses as $c) {
            if (isset($USER->lastcourseaccess[$c->id])) {
                $courses[$c->id]->lastaccess = $USER->lastcourseaccess[$c->id];
            } else {
                $courses[$c->id]->lastaccess = 0;
            }
        }
        if (empty($courses)) {
            echo $OUTPUT->box(get_string('nocourses','my'), 'center');
        } else {
            print_mycourses_overview($courses, true);
        }
    }
}


function print_mycourses_overview($courses, $full=false) {
    global $CFG, $USER, $DB, $OUTPUT, $PAGE;

    $visible_courses = array();
    foreach ($courses as $id => $course) {
        if ($course->visible) {
            $visible_courses[$id] = $course;
        }
    }

    $htmlarray = array();
    if ($full) {
        if ($modules = $DB->get_records('modules')) {
            foreach ($modules as $mod) {
                if (file_exists($CFG->dirroot .'/mod/'.$mod->name.'/lib.php')) {
                    include_once($CFG->dirroot .'/mod/'.$mod->name.'/lib.php');
                    $fname = $mod->name.'_print_overview';
                    if (function_exists($fname)) {
                        $fname($visible_courses,$htmlarray);
                    }
                }
            }
        }
    }

    $cat_names = coursecat::make_categories_list();
    $cat_courses = array();
    foreach ($courses as $course) {
        $parent = $course->category;
        if ($aux = coursecat::get($parent, MUST_EXIST, true)->get_parents()) {
            $parent = $aux[0];
        }
        $cat_courses[$parent][$course->id] = $course;
    }

    foreach ($cat_courses as $category => $courses) {
        echo html_writer::start_tag('div', array('class' => 'categorybox'));
        echo $OUTPUT->heading($cat_names[$category], 3);
        foreach ($courses as $course) {
            $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
            $attributes = array('title' => s($fullname));
            if (empty($course->visible)) {
                $attributes['class'] = 'dimmed';
            }
            $show_overview = '';
            if ($course->visible){
                if ($full) {
                    if(array_key_exists($course->id, $htmlarray)) {
                        if (count($htmlarray[$course->id]) > 0) {
                            foreach (array_keys($htmlarray[$course->id]) as $mod) {
                                $modname = get_string('modulenameplural', $mod);
                                $show_overview .= html_writer::start_tag('a', array('title' => $modname,
                                        'id' => 'overview-'. $course->id .'-'.$mod.'-link',
                                        'class' => 'overview-link',
                                        'href' => '#'));
                                $show_overview .= html_writer::empty_tag('img', array('title' => $modname,
                                        'class' => 'icon',
                                        'src' =>  $OUTPUT->pix_url('icon', $mod)));
                                $show_overview .= html_writer::end_tag('a');
                            }
                        }
                    }
                }else{
                    $show_overview = '<img class="overview-loading"'
                    . ' src="'. $OUTPUT->pix_url('i/ajaxloader').'"'
                    . ' style="display: none" alt="" />';
                }
            }
            echo $OUTPUT->box_start('coursebox');
            echo $OUTPUT->heading(html_writer::link(
                    new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes).$show_overview, 3);
            if (array_key_exists($course->id,$htmlarray)) {
                foreach ($htmlarray[$course->id] as $modname => $html) {
                    echo html_writer::start_tag('div', array('id' => 'overview-'. $course->id .'-'.$modname,
                            'class' => 'course-overview'));
                    echo $html;
                    echo html_writer::end_tag('div');
                }
            }
            echo $OUTPUT->box_end();
        }
        echo html_writer::end_tag('div');
    }
}

¡Muchas gracias de antemano!
Promedio de valoraciones: -