troodle-expcontent/lib.php
Kumi 321c470a23
feat: add event observer for course viewing
Introduces an event observer to inject JavaScript into courses containing the exp360 activity when the course is viewed.

The newly created `db/events.php` initializes event observers, while updates to `lib.php` define the event observer callback and the observer list. Enhancements to `global.js` include modal handling logic for improved UI interaction.

This aids in dynamically loading required scripts, enhancing user experience in courses with exp360 activities.
2024-07-05 12:02:11 +02:00

99 lines
2.2 KiB
PHP

<?php
defined('MOODLE_INTERNAL') || die();
function exp360_add_instance($exp360)
{
global $DB;
$exp360->timemodified = time();
$exp360->timecreated = time();
// Process standard intro fields.
$exp360->introformat = FORMAT_HTML;
$exp360->intro = '';
return $DB->insert_record('exp360', $exp360);
}
function exp360_update_instance($exp360)
{
global $DB;
$exp360->timemodified = time();
$exp360->id = $exp360->instance;
// Process standard intro fields.
$exp360->introformat = FORMAT_HTML;
$exp360->intro = '';
return $DB->update_record('exp360', $exp360);
}
function exp360_delete_instance($id)
{
global $DB;
if (!$exp360 = $DB->get_record('exp360', array('id' => $id))) {
return false;
}
$DB->delete_records('exp360', array('id' => $exp360->id));
return true;
}
function mod_exp360_cm_info_dynamic(cm_info $cm)
{
global $PAGE, $DB;
if ($cm->modname !== 'exp360') {
return;
}
$script = "<script src='https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js'></script><script data-activity-id='$cm->id' src='/mod/exp360/script.js'></script>";
$cm->set_no_view_link();
$cm->set_content($script);
}
/**
* Event observer for mod_exp360.
*/
function mod_exp360_event_observer($event)
{
global $PAGE, $DB;
// Get the course ID from the event.
$courseid = $event->courseid;
// Check if the course contains any instances of the exp360 activity.
$sql = "SELECT COUNT(*)
FROM {course_modules} cm
JOIN {modules} m ON cm.module = m.id
JOIN {exp360} e ON cm.instance = e.id
WHERE cm.course = :courseid
AND m.name = 'exp360'";
$params = ['courseid' => $courseid];
$count = $DB->count_records_sql($sql, $params);
// If the course contains at least one instance of exp360, inject the JavaScript.
if ($count > 0) {
$PAGE->requires->js('/mod/exp360/global.js');
}
}
/**
* Returns the list of event observers.
*
* @return array
*/
function mod_exp360_get_event_observers()
{
return [
[
'eventname' => '\core\event\course_viewed',
'callback' => 'mod_exp360_event_observer',
],
];
}