Rev 1058 | Rev 1060 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
<?php
defined('MOODLE_INTERNAL') || die();
use core_completion\progress;
global $CFG;
require_once $CFG->libdir . '/externallib.php';
require_once $CFG->dirroot . '/course/classes/category.php';
require_once $CFG->dirroot . '/blocks/moodleblock.class.php';
require_once $CFG->dirroot . '/blocks/course_list/block_course_list.php';
class block_cursos_catalogo_ajax_external extends \external_api
{
public static function enrolar_usuario_cursos_catalogo_parameters()
{
return new \external_function_parameters([
'courseid' => new \external_value(PARAM_INT, 'ID del curso', VALUE_DEFAULT, 0),
]);
}
public static function enrolar_usuario_cursos_catalogo($courseid)
{
global $USER, $DB, $CFG;
$userid = $USER->id;
$course = get_course($courseid);
$enrol = false;
if (!$course) {
return json_encode(['success' => false, 'data' => 'No existe el curso']);
}
$enrolmethod = 'self';
$instance = $DB->get_record('enrol', ['courseid' => $course->id, 'enrol' => $enrolmethod, 'status' => 0]);
if (!$instance) {
return json_encode(['success' => false, 'data' => 'El curso no permite auto inscribirse']);
}
try {
$user = $DB->get_record('user', ['id' => $userid]);
$role = $DB->get_record('role', array('archetype' => 'student'));
$context = context_course::instance($course->id);
$context = context_course::instance($course->id);
if (is_enrolled($context, $user)) {
return json_encode(['success' => true]);
} else {
$enrol = enrol_get_plugin($enrolmethod);
if ($enrol === null) {
return false;
}
$instances = enrol_get_instances($course->id, true);
$manualinstance = null;
foreach ($instances as $instance) {
if ($instance->name == $enrolmethod) {
$manualinstance = $instance;
break;
}
}
if ($manualinstance !== null) {
$instanceid = $enrol->add_default_instance($course);
if ($instanceid === null) {
$instanceid = $enrol->add_instance($course);
}
$instance = $DB->get_record('enrol', array('id' => $instanceid));
}
$enrol->enrol_user($instance, $user->id, $role->id);
}
return json_encode(['success' => true]);
} catch (\Exception $e) {
error_log($e->getTraceAsString());
return json_encode(['success' => false, 'data' => $e->getMessage()]);
}
}
public static function enrolar_usuario_cursos_catalogo_returns()
{
return new \external_value(PARAM_RAW, 'The updated JSON output');
}
public static function get_cursos_catalogo_parameters()
{
return new \external_function_parameters([
'category_id' => new \external_value(PARAM_INT, 'Categoría de los Cursos', VALUE_DEFAULT, 0),
'search_text' => new \external_value(PARAM_ALPHANUM, 'Palabra de búsqueda', VALUE_DEFAULT, ''),
'page' => new \external_value(PARAM_INT, 'Número de página', VALUE_DEFAULT, 1),
'perpage' => new \external_value(PARAM_INT, 'Cursos por página', VALUE_DEFAULT, 10),
]);
}
public static function get_cursos_catalogo($category_id, $search_text, $page, $perpage)
{
global $USER, $DB, $CFG, $PAGE;
// Verificar parámetros
$params = self::validate_parameters(
self::get_cursos_catalogo_parameters(),
compact('category_id', 'search_text', 'page', 'perpage')
);
// Validar valores para la paginación
$page = max(1, $params['page']);
$perpage = max(1, $params['perpage']);
$offset = ($page - 1) * $perpage;
$userid = $USER->id;
$url_noimage = $CFG->wwwroot . '/theme/' . $PAGE->theme->name . '/pix/coursenoimage.jpg';
// Obtener todos los cursos según los filtros
$courses_query = "SELECT * FROM {course} WHERE visible = 1";
$conditions = [];
$params_query = [];
if (!empty($search_text)) {
$conditions[] = "fullname LIKE :searchtext";
$params_query['searchtext'] = '%' . $DB->sql_like_escape($search_text) . '%';
}
if ($category_id > 0) {
$conditions[] = "category = :categoryid";
$params_query['categoryid'] = $category_id;
}
if (!empty($conditions)) {
$courses_query .= " AND " . implode(" AND ", $conditions);
}
// Contar todos los cursos que coinciden con los filtros
$total_courses = $DB->count_records_sql(
"SELECT COUNT(*) FROM {course} WHERE visible = 1" . (count($conditions) ? " AND " . implode(" AND ", $conditions) : ""),
$params_query
);
// Agregar límites para la paginación
$courses_query .= " ORDER BY fullname ASC LIMIT :perpage OFFSET :offset";
$params_query['perpage'] = $perpage;
$params_query['offset'] = $offset;
// Obtener los cursos
$courses = $DB->get_records_sql($courses_query, $params_query);
$results = [];
foreach ($courses as $course) {
$results[] = [
'id' => $course->id,
'fullname' => $course->fullname,
'shortname' => $course->shortname,
'category' => $course->category,
'startdate' => $course->startdate,
'enddate' => $course->enddate,
];
}
// Calcular páginas totales
$total_pages = ceil($total_courses / $perpage);
return [
'courses' => $results,
'pagination' => [
'total_courses' => $total_courses,
'total_pages' => $total_pages,
'current_page' => $page,
'per_page' => $perpage,
],
];
}
public static function get_cursos_catalogo_returns()
{
return new \external_single_structure([
'courses' => new \external_multiple_structure(
new \external_single_structure([
'id' => new \external_value(PARAM_INT, 'ID del curso'),
'fullname' => new \external_value(PARAM_TEXT, 'Nombre completo del curso'),
'shortname' => new \external_value(PARAM_TEXT, 'Nombre corto del curso'),
'category' => new \external_value(PARAM_INT, 'Categoría del curso'),
'startdate' => new \external_value(PARAM_INT, 'Fecha de inicio'),
'enddate' => new \external_value(PARAM_INT, 'Fecha de finalización'),
])
),
'pagination' => new \external_single_structure([
'total_courses' => new \external_value(PARAM_INT, 'Total de cursos'),
'total_pages' => new \external_value(PARAM_INT, 'Total de páginas'),
'current_page' => new \external_value(PARAM_INT, 'Página actual'),
'per_page' => new \external_value(PARAM_INT, 'Cursos por página'),
]),
]);
}
}