Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Mylearning widget class contains the courses user enrolled and not completed.
19
 *
20
 * @package    block_dash
21
 * @copyright  2022 bdecent gmbh <https://bdecent.de>
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
namespace block_dash\local\widget\mylearning;
26
 
27
use block_dash\local\widget\abstract_widget;
28
use block_dash\local\widget\mylearning\mylearning_layout;
29
use context_module;
30
use context_course;
31
use html_writer;
32
use cm_info;
33
use moodle_url;
34
 
35
/**
36
 * Mylearning widget class contains the courses user enrolled and not completed.
37
 */
38
class mylearning_widget extends abstract_widget {
39
 
40
    /**
41
     * Get the name of widget.
42
     *
43
     * @return void
44
     */
45
    public function get_name() {
46
        return get_string('widget:mylearning', 'block_dash');
47
    }
48
 
49
    /**
50
     * Check the widget support uses the query method to build the widget.
51
     *
52
     * @return bool
53
     */
54
    public function supports_query() {
55
        return false;
56
    }
57
 
58
    /**
59
     * Layout class widget will use to render the widget content.
60
     *
61
     * @return \abstract_layout
62
     */
63
    public function layout() {
64
        return new mylearning_layout($this);
65
    }
66
 
67
    /**
68
     * Pre defined preferences that widget uses.
69
     *
70
     * @return array
71
     */
72
    public function widget_preferences() {
73
        $preferences = [
74
            'datasource' => 'mylearning',
75
            'layout' => 'mylearning',
76
        ];
77
        return $preferences;
78
    }
79
 
80
    /**
81
     * Build widget data and send to layout thene the layout will render the widget.
82
     *
83
     * @return void
84
     */
85
    public function build_widget() {
86
        global $USER, $CFG, $DB;
87
        $userid = $USER->id;
88
        require_once($CFG->dirroot.'/lib/enrollib.php');
89
        require_once($CFG->dirroot.'/course/renderer.php');
90
 
91
        $completed = $DB->get_records_sql(
92
            'SELECT * FROM {course_completions} cc
93
            WHERE cc.userid = :userid AND cc.timecompleted > 0',
94
            ['userid' => $userid]
95
        );
96
        $completedcourses = array_column($completed, 'course');
97
        $basefields = [
98
            'id', 'category', 'sortorder', 'format',
99
            'shortname', 'fullname', 'idnumber', 'summary',
100
            'startdate', 'visible',
101
            'groupmode', 'groupmodeforce', 'cacherev',
102
        ];
103
        $courses = enrol_get_my_courses($basefields, null, 0, [], false, 0, $completedcourses);
104
        array_walk($courses, function($course) {
105
            $courseelement = (class_exists('\core_course_list_element'))
106
            ? new \core_course_list_element($course) : new \course_in_list($course);
107
            $summary = (new \coursecat_helper($course))->get_course_formatted_summary($courseelement);
108
 
109
            $category = (class_exists('\core_course_category'))
110
            ? \core_course_category::get($course->category) : \coursecat::get($course->category);
111
            $course->courseimage = $this->courseimage($course);
112
            $course->category = (isset($category->name) ? format_string($category->name) : '');
113
            $course->badges = $this->badges($course);
114
            $course->coursecontent = $this->coursecontent($course);
115
            $course->contacts = $this->contacts($course);
116
            $course->customfields = $this->customfields($course);
117
            $course->courseurl = new \moodle_url('/course/view.php', ['id' => $course->id]);
118
            $course->summary = shorten_text($summary, 200);
119
            $course->fullname = $courseelement->get_formatted_fullname();
120
        });
121
        $this->data = (!empty($courses)) ? ['courses' => array_values($courses)] : [];
122
 
123
        return $this->data;
124
    }
125
 
126
    /**
127
     * After records are relieved from database each field has a chance to transform the data.
128
     * Example: Convert unix timestamp into a human readable date format
129
     *
130
     * @param \stdClass $course
131
     * @return mixed
132
     * @throws \moodle_exception
133
     */
134
    public function courseimage($course) {
135
        global $DB, $CFG;
136
 
137
        require_once("$CFG->dirroot/course/lib.php");
138
 
139
        if ($course = $DB->get_record('course', ['id' => $course->id])) {
140
            if (block_dash_is_totara()) {
141
                $image = course_get_image($course->id)->out();
142
            } else {
143
                $image = \core_course\external\course_summary_exporter::get_course_image($course);
144
            }
145
 
146
            if ($image == '') {
147
                $courseimage = get_config('local_dash', 'courseimage');
148
                if ($courseimage != '') {
149
                    $image = moodle_url::make_pluginfile_url(
150
                        \context_system::instance()->id,
151
                        'local_dash',
152
                        'courseimage',
153
                        null,
154
                        null,
155
                        $courseimage
156
                    );
157
                }
158
            }
159
            return $image;
160
        }
161
 
162
        return false;
163
    }
164
 
165
    /**
166
     * Generate the Course contents like sections and activities.
167
     *
168
     * @param stdclass $record
169
     * @return array
170
     */
171
    public function coursecontent($record) {
172
        global $CFG;
173
        require_once($CFG->dirroot.'/course/externallib.php');
174
        $options = ['name' => 'excludecontents', 'value' => true];
175
        $contents = self::get_course_contents($record->id, [$options]);
176
        return $contents;
177
    }
178
 
179
    /**
180
     * List of badges available in the course.
181
     *
182
     * @param \stdclass $record
183
     * @return void
184
     */
185
    public function badges($record) {
186
        global $USER, $CFG;
187
        require_once($CFG->dirroot.'/lib/badgeslib.php');
188
        $badges = badges_get_badges(BADGE_TYPE_COURSE, $record->id);
189
        $userbadges = badges_get_user_badges($USER->id, $record->id);
190
        $userbadges = array_column($userbadges, 'id');
191
        $coursecontext = \context_course::instance($record->id);
192
        $images = array_map(function($badge) use ($coursecontext, $userbadges) {
193
            $collected = (in_array($badge->id, $userbadges)) ? 'collected' : '';
194
            return html_writer::tag('li', print_badge_image($badge, $coursecontext, 'f1'), ['class' => $collected]);
195
        }, $badges);
196
        $heading = html_writer::tag('h5', get_string('badgestitle', 'block_dash'));
197
        $content = html_writer::tag('ul', implode('', $images));
198
 
199
        if ($images) {
200
            return html_writer::tag('div', $heading.$content, ['class' => 'badge-block']);
201
        }
202
    }
203
 
204
    /**
205
     * Contacts staff users list with profile pic.
206
     *
207
     * @param stdclass $record
208
     * @return array
209
     */
210
    public function contacts($record) {
211
        global $DB;
212
        $courserecord = get_course($record->id);
213
        $course = (class_exists('\core_course_list_element'))
214
            ? new \core_course_list_element($courserecord) : new \course_in_list($courserecord);
215
        $contacts = $course->get_course_contacts();
216
        $data = array_map(function($user) {
217
            global $PAGE;
218
            // Set the user picture data.
219
            $user = \core_user::get_user($user['user']->id);
220
            $userpicture = new \user_picture($user);
221
            $userpicture->size = 0; // Size f2.
222
 
223
            $profileurl = new \moodle_url('/user/profile.php', ['id' => $user->id]);
224
            $link = html_writer::empty_tag('img', [
225
                'src' => $userpicture->get_url($PAGE)->out(false),
226
                'alt' => fullname($user),
227
                'role' => "presentation",
228
            ]);
229
            $link .= html_writer::tag('span', fullname($user));
230
 
231
            $html = html_writer::start_tag('li', ['class' => 'contact-user']);
232
            $html .= html_writer::link($profileurl, $link);
233
            $html .= html_writer::end_tag('li');
234
 
235
            return $html;
236
        }, $contacts);
237
 
238
        if ($data) {
239
            $heading = html_writer::tag('h5', get_string('coursestafftitle', 'block_dash'));
240
            $content = html_writer::tag('ul', implode('', $data));
241
 
242
            return html_writer::tag('div', $heading.$content, ['class' => 'course-staff-block']);
243
        }
244
    }
245
 
246
    /**
247
     * Get course custom fields with data.
248
     *
249
     * @param stdclass $record
250
     * @return void
251
     */
252
    public function customfields($record) {
253
        global $CFG;
254
        $courserecord = get_course($record->id);
255
        $output = [];
256
        if (class_exists('\core_course_list_element')) {
257
            $course = new \core_course_list_element($courserecord);
258
            if ($course->has_custom_fields()) {
259
                foreach ($course->get_custom_fields() as $field) {
260
                    $output[] = [
261
                        'fieldname' => format_string($field->get_field()->get('name')),
262
                        'value' => ($field->export_value()) ? $field->export_value() : '-',
263
                    ];
264
                }
265
                return $output;
266
            }
267
        } else {
268
            $fields = get_course_custom_fields($record->id);
269
            if ($fields) {
270
                foreach ($fields as $field) {
271
                    $type = $field->datatype;
272
                    if (file_exists($CFG->dirroot.'/totara/customfield/field/'.$type.'/field.class.php')) {
273
                        require_once($CFG->dirroot.'/totara/customfield/field/'.$type.'/field.class.php');
274
                        $classname = 'customfield_'.$type;
275
                        $output[] = [
276
                            'fieldname' => format_string($field->fullname),
277
                            'value' => $classname::display_item_data($field->data),
278
                        ];
279
                    }
280
                }
281
                return $output;
282
            }
283
        }
284
    }
285
 
286
    /**
287
     * Get current course module progress. count of completion enable modules and count of completed modules.
288
     *
289
     * @param stdclass $course
290
     * @param int $userid
291
     * @return array Modules progress
292
     */
293
    protected function activity_progress($course, $userid) {
294
        $completion = new \completion_info($course);
295
        // First, let's make sure completion is enabled.
296
        if (!$completion->is_enabled()) {
297
            return null;
298
        }
299
        $result = [];
300
 
301
        // Get the number of modules that support completion.
302
        $modules = $completion->get_activities();
303
        $completionactivities = $completion->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
304
 
305
        $count = count($completionactivities);
306
        if (!$count) {
307
            return null;
308
        }
309
        // Get the number of modules that have been completed.
310
        $completed = 0;
311
        foreach ($completionactivities as $activity) {
312
            $cmid = $activity->moduleinstance;
313
 
314
            if (isset($modules[$cmid])) {
315
                $data = $completion->get_data($modules[$cmid], true, $userid);
316
                $completed += $data->completionstate == COMPLETION_INCOMPLETE ? 0 : 1;
317
            }
318
        }
319
        $percent = ($completed / $count) * 100;
320
 
321
        return ['count' => $count, 'completed' => $completed, 'percent' => $percent] + $result;
322
    }
323
 
324
    /**
325
     * Get course contents. Modified version of course/externallib class method get_course_contents.
326
     *
327
     * @param int $courseid course id
328
     * @return array
329
     * @since Moodle 2.9 Options available
330
     * @since Moodle 2.2
331
     */
332
    public static function get_course_contents($courseid) {
333
        global $CFG, $DB, $USER, $PAGE;
334
        // Include library files.
335
        require_once($CFG->dirroot . "/course/lib.php");
336
        require_once($CFG->libdir . '/completionlib.php');
337
        require_once($CFG->libdir . '/externallib.php');
338
 
339
        $filters = [];
340
        // Retrieve the course.
341
        $course = $DB->get_record('course', ['id' => $courseid], '*', MUST_EXIST);
342
 
343
        if ($course->id != SITEID) {
344
            // Check course format exist.
345
            if (file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
346
                require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
347
            }
348
        }
349
 
350
        // Now security checks.
351
        $context = context_course::instance($course->id);
352
        // TODO: course content view capability check.
353
        $canupdatecourse = true;
354
 
355
        // Create return value.
356
        $coursecontents = [];
357
 
358
        if ($canupdatecourse || $course->visible
359
                || has_capability('moodle/course:viewhiddencourses', $context)) {
360
 
361
            $modinfo = get_fast_modinfo($course);
362
            $sections = $modinfo->get_section_info_all();
363
            $courseformat = course_get_format($course);
364
            $coursenumsections = $courseformat->get_last_section_number();
365
            $stealthmodules = [];   // Array to keep all the modules available but not visible in a course section/topic.
366
 
367
            $completioninfo = new \completion_info($course);
368
 
369
            $modinfosections = $modinfo->get_sections();
370
            foreach ($sections as $key => $section) {
371
                // This becomes true when we are filtering and we found the value to filter with.
372
                $sectionfound = false;
373
                $sectionvalues = [];
374
                $sectionvalues['id'] = $section->id;
375
                $sectionvalues['name'] = get_section_name($course, $section);
376
                $sectionvalues['visible'] = $section->visible;
377
 
378
                $options = (object) ['noclean' => true];
379
                list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
380
                        external_format_text($section->summary, $section->summaryformat,
381
                                $context->id, 'course', 'section', $section->id, $options);
382
                $sectionvalues['section'] = $section->section;
383
                $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
384
                $sectionvalues['uservisible'] = $section->uservisible;
385
                if (!empty($section->availableinfo)) {
386
                    $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course);
387
                }
388
 
389
                $sectioncontents = [];
390
 
391
                // For each module of the section.
392
                $sectionactivitycompleted = $sectionactivitycount = 0;
393
                if (!empty($modinfosections[$section->section])) {
394
 
395
                    foreach ($modinfosections[$section->section] as $cmid) {
396
                        $cm = $modinfo->cms[$cmid];
397
                        $cminfo = cm_info::create($cm);
398
                        // Stop here if the module is not visible to the user on the course main page:
399
                        // The user can't access the module and the user can't view the module on the course page.
400
                        if (!$cm->uservisible) {
401
                            continue;
402
                        }
403
 
404
                        // This becomes true when we are filtering and we found the value to filter with.
405
                        $modfound = false;
406
                        $module = [];
407
                        $modcontext = context_module::instance($cm->id);
408
 
409
                        $module['id'] = $cm->id;
410
                        $module['name'] = external_format_string($cm->name, $modcontext->id);
411
                        $module['instance'] = $cm->instance;
412
                        $module['contextid'] = $modcontext->id;
413
                        $module['modname'] = (string) $cm->modname;
414
                        $module['modplural'] = (string) $cm->modplural;
415
                        $module['modicon'] = $cm->get_icon_url()->out(false);
416
                        $module['indent'] = $cm->indent;
417
                        $module['onclick'] = $cm->onclick;
418
                        $module['afterlink'] = $cm->afterlink;
419
                        $module['customdata'] = json_encode($cm->customdata);
420
                        $module['completion'] = $cm->completion;
421
                        $module['noviewlink'] = plugin_supports('mod', $cm->modname, FEATURE_NO_VIEW_LINK, false);
422
 
423
                        // Check module completion.
424
                        $completion = $completioninfo->is_enabled($cm);
425
                        if ($completion != COMPLETION_DISABLED) {
426
                            if (class_exists('\core_completion\cm_completion_details')) {
427
                                $cmcompletion = \core_completion\cm_completion_details::get_instance($cm, $USER->id);
428
                                $exporter = new \core_completion\external\completion_info_exporter($course, $cm, $USER->id);
429
                                $renderer = $PAGE->get_renderer('core');
430
                                $modulecompletiondata = (array)$exporter->export($renderer);
431
                                $module['completiondata'] = $modulecompletiondata;
432
                            } else {
433
                                $data = $completioninfo->get_data($cm);
434
                                $module['completiondata']['state'] = $data->completionstate;
435
                            }
436
                            $sectionactivitycompleted += $module['completiondata']['state'] ? 1 : 0;
437
                            $sectionactivitycount += 1;
438
                        }
439
 
440
                        if (!empty($cm->showdescription) || $module['noviewlink']) {
441
                            // We want to use the external format. However from reading get_formatted_content(), $cm->content
442
                            // Format is always FORMAT_HTML.
443
                            $options = ['noclean' => true];
444
                            list($module['description'], $descriptionformat) = external_format_text($cm->content,
445
                                FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
446
                        }
447
                        // Url of the module.
448
                        $url = $cm->url;
449
                        if ($url) {
450
                            $module['url'] = $url->out(false);
451
                        } else {
452
                            $module['url'] = (new \moodle_url('/mod/'.$cm->modname.'/view.php', ['id' => $cm->id]))->out(false);
453
                        }
454
                        $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
455
                                            context_module::instance($cm->id));
456
                        // User that can view hidden module should know about the visibility.
457
                        $module['visible'] = $cm->visible;
458
                        $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
459
                        $module['uservisible'] = $cm->uservisible;
460
                        if (!empty($cm->availableinfo)) {
461
                            $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
462
                        }
463
                        // Availability date (also send to user who can see hidden module).
464
                        if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
465
                            $module['availability'] = $cm->availability;
466
                        }
467
 
468
                        // Assign result to $sectioncontents, there is an exception,
469
                        // Stealth activities in non-visible sections for students go to a special section.
470
                        if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
471
                            $stealthmodules[] = $module;
472
                        } else {
473
                            $sectioncontents[] = $module;
474
                        }
475
                    }
476
                }
477
                $sectionvalues['activitycompleted'] = $sectionactivitycompleted;
478
                $sectionvalues['activitycount'] = $sectionactivitycount;
479
                if ($sectionactivitycount > 0 && ($sectionactivitycount - $sectionactivitycompleted) == 0) {
480
                    $sectionvalues['completed'] = 1;
481
                }
482
                $sectionvalues['modules'] = $sectioncontents;
483
                $sectionvalues['hidemodules'] = count($sectioncontents) > 0 ? false : true;
484
                // Assign result to $coursecontents.
485
                $coursecontents[$key] = $sectionvalues;
486
                // Break the loop if we are filtering.
487
                if ($sectionfound) {
488
                    break;
489
                }
490
            }
491
            // Now that we have iterated over all the sections and activities, check the visibility.
492
            // We didn't this before to be able to retrieve stealth activities.
493
            foreach ($coursecontents as $sectionnumber => $sectioncontents) {
494
                $section = $sections[$sectionnumber];
495
                // Show the section if the user is permitted to access it OR
496
                // if it's not available but there is some available info text which explains the reason & should display OR
497
                // the course is configured to show hidden sections name.
498
                $showsection = $section->uservisible ||
499
                    ($section->visible && !$section->available && !empty($section->availableinfo)) ||
500
                    (!$section->visible && empty($courseformat->get_course()->hiddensections));
501
 
502
                if (!$showsection) {
503
                    unset($coursecontents[$sectionnumber]);
504
                    continue;
505
                }
506
                // Remove section and modules information if the section is not visible for the user.
507
                if (!$section->uservisible) {
508
                    $coursecontents[$sectionnumber]['modules'] = [];
509
                    // Remove summary information if the section is completely hidden only,
510
                    // Even if the section is not user visible, the summary is always displayed among the availability information.
511
                    if (!$section->visible) {
512
                        $coursecontents[$sectionnumber]['summary'] = '';
513
                    }
514
                }
515
            }
516
 
517
            // Include stealth modules in special section (without any info).
518
            if (!empty($stealthmodules)) {
519
                $coursecontents[] = [
520
                    'id' => -1,
521
                    'name' => '',
522
                    'summary' => '',
523
                    'summaryformat' => FORMAT_MOODLE,
524
                    'modules' => $stealthmodules,
525
                ];
526
            }
527
        }
528
        return $coursecontents;
529
    }
530
}