Proyectos de Subversion Moodle

Rev

Rev 1058 | Rev 1060 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
defined('MOODLE_INTERNAL') || die();
3
 
4
use core_completion\progress;
5
 
6
global $CFG;
7
require_once $CFG->libdir  . '/externallib.php';
8
require_once $CFG->dirroot . '/course/classes/category.php';
9
require_once $CFG->dirroot . '/blocks/moodleblock.class.php';
10
require_once $CFG->dirroot . '/blocks/course_list/block_course_list.php';
11
 
12
 
13
 
14
class block_cursos_catalogo_ajax_external extends \external_api
15
{
1052 ariadna 16
 
1 efrain 17
    public static function enrolar_usuario_cursos_catalogo_parameters()
18
    {
19
        return new \external_function_parameters([
20
            'courseid' => new \external_value(PARAM_INT, 'ID del curso', VALUE_DEFAULT, 0),
21
        ]);
22
    }
1052 ariadna 23
 
1059 ariadna 24
 
25
 
1 efrain 26
    public static function enrolar_usuario_cursos_catalogo($courseid)
27
    {
28
        global $USER, $DB, $CFG;
1052 ariadna 29
 
30
 
1 efrain 31
        $userid = $USER->id;
32
        $course = get_course($courseid);
33
        $enrol = false;
1052 ariadna 34
 
35
        if (!$course) {
1 efrain 36
            return json_encode(['success' => false, 'data' => 'No existe el curso']);
37
        }
1052 ariadna 38
 
39
 
1 efrain 40
        $enrolmethod = 'self';
1052 ariadna 41
 
1 efrain 42
        $instance = $DB->get_record('enrol', ['courseid' => $course->id, 'enrol' => $enrolmethod, 'status' => 0]);
1052 ariadna 43
        if (!$instance) {
1 efrain 44
            return json_encode(['success' => false, 'data' => 'El curso no permite auto inscribirse']);
45
        }
46
 
1052 ariadna 47
        try {
48
            $user = $DB->get_record('user', ['id' => $userid]);
49
            $role = $DB->get_record('role', array('archetype' => 'student'));
50
            $context = context_course::instance($course->id);
51
 
52
            $context = context_course::instance($course->id);
53
            if (is_enrolled($context, $user)) {
54
                return json_encode(['success' => true]);
55
            } else {
56
                $enrol = enrol_get_plugin($enrolmethod);
57
                if ($enrol === null) {
58
                    return false;
1 efrain 59
                }
1052 ariadna 60
                $instances = enrol_get_instances($course->id, true);
61
                $manualinstance = null;
62
                foreach ($instances as $instance) {
63
                    if ($instance->name == $enrolmethod) {
64
                        $manualinstance = $instance;
65
                        break;
66
                    }
1 efrain 67
                }
1052 ariadna 68
                if ($manualinstance !== null) {
69
                    $instanceid = $enrol->add_default_instance($course);
70
                    if ($instanceid === null) {
71
                        $instanceid = $enrol->add_instance($course);
72
                    }
73
                    $instance = $DB->get_record('enrol', array('id' => $instanceid));
74
                }
75
                $enrol->enrol_user($instance, $user->id, $role->id);
1 efrain 76
            }
1052 ariadna 77
 
78
            return json_encode(['success' => true]);
79
        } catch (\Exception $e) {
1 efrain 80
            error_log($e->getTraceAsString());
1052 ariadna 81
 
1 efrain 82
            return json_encode(['success' => false, 'data' => $e->getMessage()]);
83
        }
84
    }
1052 ariadna 85
 
1 efrain 86
    public static function enrolar_usuario_cursos_catalogo_returns()
87
    {
88
        return new \external_value(PARAM_RAW, 'The updated JSON output');
89
    }
1052 ariadna 90
 
1 efrain 91
    public static function get_cursos_catalogo_parameters()
92
    {
93
        return new \external_function_parameters([
94
            'category_id' => new \external_value(PARAM_INT, 'Categoría de los Cursos', VALUE_DEFAULT, 0),
1059 ariadna 95
            'search_text' => new \external_value(PARAM_ALPHANUM, 'Palabra de búsqueda', VALUE_DEFAULT, ''),
96
            'page' => new \external_value(PARAM_INT, 'Número de página', VALUE_DEFAULT, 1),
97
            'perpage' => new \external_value(PARAM_INT, 'Cursos por página', VALUE_DEFAULT, 10),
1 efrain 98
        ]);
99
    }
100
 
1059 ariadna 101
    public static function get_cursos_catalogo($category_id, $search_text, $page, $perpage)
1 efrain 102
    {
1059 ariadna 103
        global $USER, $DB, $CFG, $PAGE;
1 efrain 104
 
1059 ariadna 105
        // Verificar parámetros
106
        $params = self::validate_parameters(
107
            self::get_cursos_catalogo_parameters(),
108
            compact('category_id', 'search_text', 'page', 'perpage')
109
        );
1058 ariadna 110
 
1059 ariadna 111
        // Validar valores para la paginación
112
        $page = max(1, $params['page']);
113
        $perpage = max(1, $params['perpage']);
114
        $offset = ($page - 1) * $perpage;
1 efrain 115
 
116
        $userid = $USER->id;
1059 ariadna 117
        $url_noimage = $CFG->wwwroot . '/theme/' . $PAGE->theme->name . '/pix/coursenoimage.jpg';
1 efrain 118
 
1059 ariadna 119
        // Obtener todos los cursos según los filtros
120
        $courses_query = "SELECT * FROM {course} WHERE visible = 1";
121
        $conditions = [];
122
        $params_query = [];
1052 ariadna 123
 
1059 ariadna 124
        if (!empty($search_text)) {
125
            $conditions[] = "fullname LIKE :searchtext";
126
            $params_query['searchtext'] = '%' . $DB->sql_like_escape($search_text) . '%';
1 efrain 127
        }
1052 ariadna 128
 
1059 ariadna 129
        if ($category_id > 0) {
130
            $conditions[] = "category = :categoryid";
131
            $params_query['categoryid'] = $category_id;
1 efrain 132
        }
133
 
1059 ariadna 134
        if (!empty($conditions)) {
135
            $courses_query .= " AND " . implode(" AND ", $conditions);
1 efrain 136
        }
137
 
1059 ariadna 138
        // Contar todos los cursos que coinciden con los filtros
139
        $total_courses = $DB->count_records_sql(
140
            "SELECT COUNT(*) FROM {course} WHERE visible = 1" . (count($conditions) ? " AND " . implode(" AND ", $conditions) : ""),
141
            $params_query
142
        );
1058 ariadna 143
 
1059 ariadna 144
        // Agregar límites para la paginación
145
        $courses_query .= " ORDER BY fullname ASC LIMIT :perpage OFFSET :offset";
146
        $params_query['perpage'] = $perpage;
147
        $params_query['offset'] = $offset;
1058 ariadna 148
 
1059 ariadna 149
        // Obtener los cursos
150
        $courses = $DB->get_records_sql($courses_query, $params_query);
1052 ariadna 151
 
1059 ariadna 152
        $results = [];
153
        foreach ($courses as $course) {
154
            $results[] = [
155
                'id' => $course->id,
1058 ariadna 156
                'fullname' => $course->fullname,
157
                'shortname' => $course->shortname,
1059 ariadna 158
                'category' => $course->category,
1058 ariadna 159
                'startdate' => $course->startdate,
1059 ariadna 160
                'enddate' => $course->enddate,
161
            ];
1 efrain 162
        }
163
 
1059 ariadna 164
        // Calcular páginas totales
165
        $total_pages = ceil($total_courses / $perpage);
1052 ariadna 166
 
1059 ariadna 167
        return [
168
            'courses' => $results,
169
            'pagination' => [
170
                'total_courses' => $total_courses,
171
                'total_pages' => $total_pages,
172
                'current_page' => $page,
173
                'per_page' => $perpage,
174
            ],
1058 ariadna 175
        ];
1 efrain 176
    }
177
 
178
    public static function get_cursos_catalogo_returns()
179
    {
1059 ariadna 180
        return new \external_single_structure([
181
            'courses' => new \external_multiple_structure(
182
                new \external_single_structure([
183
                    'id' => new \external_value(PARAM_INT, 'ID del curso'),
184
                    'fullname' => new \external_value(PARAM_TEXT, 'Nombre completo del curso'),
185
                    'shortname' => new \external_value(PARAM_TEXT, 'Nombre corto del curso'),
186
                    'category' => new \external_value(PARAM_INT, 'Categoría del curso'),
187
                    'startdate' => new \external_value(PARAM_INT, 'Fecha de inicio'),
188
                    'enddate' => new \external_value(PARAM_INT, 'Fecha de finalización'),
189
                ])
190
            ),
191
            'pagination' => new \external_single_structure([
192
                'total_courses' => new \external_value(PARAM_INT, 'Total de cursos'),
193
                'total_pages' => new \external_value(PARAM_INT, 'Total de páginas'),
194
                'current_page' => new \external_value(PARAM_INT, 'Página actual'),
195
                'per_page' => new \external_value(PARAM_INT, 'Cursos por página'),
196
            ]),
197
        ]);
1 efrain 198
    }
199
}