### Dispatching a Hook Source: https://moodledev.io/docs/5.2/apis/core/hooks Example of how to dispatch a hook within the Moodle installation process. ```APIDOC ## POST /mod/activity/db/install.php ### Description Dispatches the `installation_finished` hook after the `mod_activity` plugin installation process is complete. ### Method N/A (This is a function definition) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) N/A #### Response Example None ```php dispatch($hook); } ``` ``` -------------------------------- ### Parameter Value Examples Source: https://moodledev.io/docs/5.2/apis/subsystems/routing/parameters Demonstrates how to provide examples for API parameters, specifically for theme names. ```APIDOC ## Parameter Schema with Examples ### Description This section illustrates how to define examples for API parameters within the schema definition. This is particularly useful for complex or enumerated parameters to guide users on valid input formats. ### Method N/A (Schema Definition) ### Endpoint N/A (Schema Definition) ### Parameters #### Path Parameters - **themename** (ALPHANUMEXT) - Required - The name of the theme. - **examples**: - **name**: 'The Boost theme' **value**: 'boost' ### Request Example (Illustrative - actual request depends on the endpoint using this parameter) ``` // Example of how a parameter with examples might be defined in code: new path_parameter( name: 'themename', type: param::ALPHANUMEXT, examples: [ new \core\router\schema\example( name: 'The Boost theme', value: 'boost', ), ], ) ``` ### Response N/A (Schema Definition) ``` -------------------------------- ### Define Route Parameter with Examples in PHP Source: https://moodledev.io/docs/5.2/apis/subsystems/routing/parameters Demonstrates how to define a path parameter for a route, including specifying its type and providing usage examples. The `examples` property takes an array of `\core\router\schema\example` objects, each with a name and value. ```PHP new path_parameter( name: 'themename', type: param::ALPHANUMEXT, examples: [ new \core\router\schema\example( name: 'The Boost theme', value: 'boost', ), ], ) ``` -------------------------------- ### Example Component Callback Implementation Source: https://moodledev.io/docs/5.2/apis/subsystems/files An example implementation of the `[component_name]_pluginfile()` callback for an activity module plugin. ```APIDOC ## Example Component Callback Implementation ### Description This example demonstrates how to implement the `mod_myplugin_pluginfile()` callback for an activity module plugin, including context checks, capability verification, and file retrieval using the Files API. ### File: `mod/myplugin/lib.php` ```php /** * Serve the files from the myplugin file areas. * * @param stdClass $course The course object. * @param stdClass $cm The course module object. * @param stdClass $context The context. * @param string $filearea The name of the file area. * @param array $args Extra arguments (itemid, path). * @param bool $forcedownload Whether or not force download. * @param array $options Additional options affecting the file serving. * @return bool false if the file not found, just send the file otherwise and do not return anything */ function mod_myplugin_pluginfile( $course, $cm, $context, string $filearea, array $args, bool $forcedownload, array $options = [] ): bool { global $DB; // Check the contextlevel is as expected - if your plugin is a block, this becomes CONTEXT_BLOCK, etc. if ($context->contextlevel != CONTEXT_MODULE) { return false; } // Make sure the filearea is one of those used by the plugin. if ($filearea !== 'expectedfilearea' && $filearea !== 'anotherexpectedfilearea') { return false; } // Make sure the user is logged in and has access to the module (plugins that are not course modules should leave out the 'cm' part). require_login($course, true, $cm); // Check the relevant capabilities - these may vary depending on the filearea being accessed. if (!has_capability('mod/myplugin:view', $context)) { return false; } // The args is an array containing [itemid, path]. // Fetch the itemid from the path. $itemid = array_shift($args); // The itemid can be used to check access to a record, and ensure that the // record belongs to the specifeid context. For example: if ($filearea === 'expectedfilearea') { $post = $DB->get_record('myplugin_posts', ['id' => $itemid]); if ($post->myplugin !== $context->instanceid) { // This post does not belong to the requested context. return false; } // You may want to perform additional checks here, for example: // - ensure that if the record relates to a grouped activity, that this // user has access to it // - check whether the record is hidden // - check whether the user is allowed to see the record for some other // reason. // If, for any reason, the user does not hve access, you can return // false here. } // For a plugin which does not specify the itemid, you may want to use the following to keep your code consistent: // $itemid = null; // Extract the filename / filepath from the $args array. $filename = array_pop($args); // The last item in the $args array. if (empty($args)) { // $args is empty => the path is '/'. $filepath = '/'; } else { // $args contains the remaining elements of the filepath. $filepath = '/' . implode('/', $args) . '/'; } // Retrieve the file from the Files API. $fs = get_file_storage(); // You would typically use $fs->get_file_by_hash() or $fs->get_file() here. // For example: // $file = $fs->get_file($context->id, 'mod_myplugin', $filearea, $itemid, $filepath . $filename); // If the file is found and accessible, send it. // send_file_to_user(...); // If the file is not found, return false. return false; // Placeholder: replace with actual file serving logic } ``` ``` -------------------------------- ### Repository Plugin Initialization Source: https://moodledev.io/docs/5.2/apis/plugintypes/repository The plugin_init method is triggered once upon the installation of the repository plugin to perform setup tasks. ```APIDOC ## plugin_init ### Description This static method is called automatically by Moodle when the administrator installs the repository plugin. It is typically used to create default instances or perform initial database setup. ### Method Static Method ### Parameters None ### Example ```php public static function plugin_init() { repository::static_function( 'flickrpublic', 'create', 'flickrpublic', 0, context_system::instance(), ['name' => 'default instance', 'email_address' => null], 1 ); } ``` ``` -------------------------------- ### Full Implementation of Mapped Course Parameter Source: https://moodledev.io/docs/5.2/apis/subsystems/routing/parameters A comprehensive example showing the constructor configuration for a mapped parameter, including documentation, examples, and the logic for resolving course data from various input formats like numeric IDs, idnumbers, or shortnames. ```php namespace core\router\parameters; use core\exception\not_found_exception; use core\param; use core\router\schema\example; use core\router\schema\parameters\mapped_property_parameter; use core\router\schema\referenced_object; use Psr\Http\Message\ServerRequestInterface; class path_course extends \core\router\schema\parameters\path_parameter implements referenced_object, mapped_property_parameter { public function __construct( string $name = 'course', ...$extra, ) { $extra['name'] = $name; $extra['type'] = param::RAW; $extra['description'] = <<get_record('course', ['id' => $value]); } else if (str_starts_with($value, 'idnumber:')) { $data = $DB->get_record('course', ['idnumber' => substr($value, 9)]); } return $data; } } ``` -------------------------------- ### Moodle Profiling Path Configuration Example Source: https://moodledev.io/docs/5.2/guides/profiling Example of how to configure specific paths within Moodle to be profiled. This allows developers to target particular sections of their Moodle site for performance analysis. The wildcard '*' can be used to include multiple files matching a pattern. ```text mod/*/view.php ``` -------------------------------- ### Exporter Implementation Example Source: https://moodledev.io/docs/5.2/apis/subsystems/output This example demonstrates how to implement an exporter for an 'externable' output class, defining properties and related data for webservice export. ```APIDOC ## Exporter Implementation Example ### Description This code defines an exporter class for the `myname` output, specifying how its data should be structured for webservice clients. It includes properties like `activityname`, `activityurl`, and `hidden`. ### Method N/A (Class definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ```php namespace mod_MYPLUGIN\external; use core_external\exporter; use mod_MYPLUGIN\output\myname; class myname_exporter extends exporter { /** * Constructor with parameter type hints. * * @param action_link $data The action link data to export. * @param array $related Related data for the exporter. */ public function __construct( myname $data, array $related = [], ) { parent::__construct($data, $related); } #[\]Override protected static function define_properties(): array { return []; } #[\]Override protected static function define_related() { // Most exporter need to define the context as related data to parse texts. return [ 'context' => 'context', ]; } #[\]Override protected static function define_other_properties() { return [ 'activityname' => [ 'type' => PARAM_TEXT, 'null' => NULL_NOT_ALLOWED, 'description' => 'The name of the activity.', ], 'activityurl' => [ 'type' => PARAM_URL, 'null' => NULL_ALLOWED, 'description' => 'The URL of the activity.', ], 'hidden' => [ 'type' => PARAM_BOOL, 'null' => NULL_NOT_ALLOWED, 'description' => 'Whether the activity is hidden.', ], ]; } #[\]Override protected function get_other_values(\renderer_base $output) { /** @var \cm_info $cm */ $cm = $this->data->cm; return [ 'activityname' => \core_external\util::format_string($cm->name, $cm->context, true), 'activityurl' => $cm->url, 'hidden' => empty($cm->visible), ]; } } ``` ``` -------------------------------- ### Define Plugin Installation Function Source: https://moodledev.io/docs/5.2/guides/upgrade Shows the structure for defining an installation function within a plugin's install.php file. The function name must follow the frankenstyle naming convention. ```php config->title)) { $this->title = format_string($this->config->title, true, ['context' => $this->context]); } else { $this->title = get_string('newhtmlblock', 'block_html'); } } ``` ``` -------------------------------- ### Example Usage of Moodle Tabs Component Source: https://moodledev.io/docs/5.2/guides/templates An example demonstrating how to use the Moodle tabs component in an HTML file. It shows how to include the tabs partial and define content for specific tab names and panel content using blocks. ```html
User Profile
{{> core/tabs }} {{$ tablist }} {{< core/tab_header_item }} {{$ tabname }}Name{{/ tabname }} {{/ core/tab_header_item }} {{< core/tab_header_item }} {{$ tabname }}Email{{/ tabname }} {{/ core/tab_header_item }} {{/ tablist }} {{$ tabcontent }} {{< core/tab_content_item }} {{$ tabpanelcontent }}Your name is {{ name }}.{{/ tabpanelcontent }} {{/ core/tab_content_item }} {{< core/tab_content_item }} {{$ tabpanelcontent }}Your email address is {{ email }}.{{/ tabpanelcontent }} {{/ core/tab_content_item }} {{/ tabcontent }} {{/ core/tabs }} ``` -------------------------------- ### Webservice Execution Example Source: https://moodledev.io/docs/5.2/apis/subsystems/output This example shows how to implement a webservice function that uses an 'externable' output and its associated exporter to return structured data. ```APIDOC ## Webservice Execution Example ### Description This code defines a webservice function `get_my_name` that retrieves course module information and returns it using a defined exporter, ensuring structured data output for clients. ### Method N/A (Class definition) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **structure** (external_single_structure) - Defines the structure of the returned data, typically derived from the 'externable' class. ### Response Example N/A (Structure defined by `myname::get_read_structure()`) ```php namespace mod_MYPLUGIN\external; use core_external\external_api; use core_external\external_function_parameters; use core_external\external_single_structure; use core_external\external_value; use core\output\renderer_helper; use mod_MYPLUGIN\output\myname; use stdClass; class get_my_name extends external_api { public static function execute_parameters(): external_function_parameters { return new external_function_parameters([ 'cmid' => new external_value(PARAM_INT, 'Course module id', VALUE_REQUIRED), ]); } public static function execute(int $cmid): stdClass { [ 'cmid' => $cmid, ] = external_api::validate_parameters(self::execute_parameters(), [ 'cmid' => $cmid, ]); [$course, $cm] = get_course_and_cm_from_cmid($cmid); $context = \core\context\module::instance($cm->id); self::validate_context($context); // Check any capability required to view the activity. $page = \core\di::get(renderer_helper::class)->get_core_renderer(); $output = new myname($cm); $exporter = $output->get_exporter($context); return $exporter->export($renderer); } /** * Webservice returns. * * @return external_single_structure */ public static function execute_returns(): external_single_structure { return myname::get_read_structure(); } } ``` ``` -------------------------------- ### Moodle Course Format Plugin Language File Example Source: https://moodledev.io/docs/5.2/apis/plugintypes/format An example of a language file (`plugintype_pluginname.php`) for a Moodle course format plugin. It includes standard Moodle licensing and header information, followed by an array of string identifiers and their English translations, such as 'pluginname', 'addsections', and 'currentsection'. ```php . /** * Languages configuration for the format_pluginname plugin. * * @package format_pluginname * @copyright Year, You Name * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $string['addsections'] = 'Add section'; $string['currentsection'] = 'This section'; $string['deletesection'] = 'Delete section'; $string['editsection'] = 'Edit section'; $string['editsectionname'] = 'Edit section name'; $string['hidefromothers'] = 'Hide section'; $string['newsectionname'] = 'New name for section {$a}'; $string['pluginname'] = 'pluginname format'; $string['privacy:metadata'] = 'The Sample format plugin does not store any personal data.'; $string['sectionname'] = 'Section'; $string['showfromothers'] = 'Show section'; ``` -------------------------------- ### Example: Set Preference and Retrieve All - PHP Source: https://moodledev.io/docs/5.2/apis/core/preference Shows how to set a preference and then retrieve all currently set preferences using 'get_user_preferences()' without any arguments. ```PHP set_user_preference('foo_showavatars', 'no'); // returns [ // foo_nameformat => "long", // foo_showavatars => "no", // ]; get_user_preferences(); ``` -------------------------------- ### Example: Get Users Able to Submit Assignment (PHP) Source: https://moodledev.io/docs/5.2/apis/subsystems/enrol An example demonstrating the use of get_enrolled_users to retrieve users who have the 'mod/assign:submit' capability within a given context, likely for an assignment module. ```php $submissioncandidates = get_enrolled_users($modcontext, 'mod/assign:submit'); ``` -------------------------------- ### Example: Set and Retrieve Preference - PHP Source: https://moodledev.io/docs/5.2/apis/core/preference Demonstrates the basic usage of setting a preference using 'set_user_preference' and then retrieving its value with 'get_user_preferences'. ```PHP set_user_preference('foo_nameformat', 'long'); // Returns the string - "long" get_user_preferences('foo_nameformat'); ``` -------------------------------- ### Create a simplified Moodle router for testing Source: https://moodledev.io/docs/5.2/apis/subsystems/routing/testing Demonstrates how to extend the \route_testcase class and initialize a simplified router instance using get_router(). ```php final class my_test extends \route_testcase { public function test_example(): void { $router = $this->get_router(); } } ``` -------------------------------- ### Initialize Moodle Admin Page Source: https://moodledev.io/docs/5.2/apis/subsystems/output Demonstrates the standard setup for a Moodle admin tool page, including configuration loading, permission checks via admin_externalpage_setup, and global page property configuration. ```php require_once(__DIR__ . '/../../../config.php'); require_once($CFG->libdir.'/adminlib.php'); admin_externalpage_setup('tooldemo'); $title = get_string('pluginname', 'tool_demo'); $url = new moodle_url("/admin/tool/demo/index.php"); $PAGE->set_url($url); $PAGE->set_title($title); $PAGE->set_heading($title); ``` -------------------------------- ### Schedule Task at Random Time Source: https://moodledev.io/docs/5.2/apis/commonfiles/db-tasks.php Example of using the 'R' value to assign a fixed random time to a task upon installation. ```php $tasks = [ [ 'classname' => 'mod_example\task\do_something', // Every month. 'month' => '*', // Every day. 'day' => '*', // A fixed random hour and minute. 'hour' => 'R', 'month' => 'R', ], ]; ``` -------------------------------- ### Get Day of Week for First Day of Month in Moodle Source: https://moodledev.io/docs/5.2/apis/subsystems/time This example shows how to determine the day of the week for the first day of the current month using Moodle's `clock` service. It formats the current date to extract the year and month, then sets the day to 1 and formats the result to get the day of the week. ```php $now = \core\di::get(\core\clock::class)->now(); $year = $now->format('Y'); $month = $now->format('m'); $firstdayofmonth = $now->setDate($year, $month, 1); $dayofweek = $firstdayofmonth->format('N'); echo $dayofweek; ``` -------------------------------- ### PHP Method to Get Template Name (Moodle) Source: https://moodledev.io/docs/5.2/apis/subsystems/output An example implementation of the `get_template_name` method required when using the `named_templatable` interface in Moodle plugins. This method explicitly returns the name of the Mustache template to be used for rendering. ```PHP /** * Gets the name of the mustache template used to render the data. * * @return string */ public function get_template_name( enderer_base $renderer): string { return 'tool_demo/index_page'; } ``` -------------------------------- ### Instance Management - Course and User Repositories Source: https://moodledev.io/docs/5.2/apis/plugintypes/repository Configure repository plugins to support system-wide, course-specific, or user-specific instances. This can be done via language files, implementing `get_instance_option_names()`, or using `db/install.php`. ```APIDOC ## Course and User Repository Instances ### Description This section details how to enable and manage repository instances at different scopes: system-wide, course-specific, and user-specific. A system-wide instance is created when a repository is enabled. Course and user instances can be supported by setting specific configuration options. ### Enabling Course and User Instances There are three primary methods to enable course and user instances: 1. **Language Files**: Define the strings `'$string['enablecourseinstances']'` and `'$string['enableuserinstances']'` in your plugin's language file. Refer to the filesystem repository for an example. 2. **`get_instance_option_names()` Method**: The plugin must provide a static method `get_instance_option_names()` that returns an array of instance option names. If no instance attributes are needed, this method should not be defined or should return an empty array. The form fields for these options must *not* be defined in the `type_config_form()` function. 3. **`db/install.php`**: Some core repositories use this file to create initial repository instances by constructing a `repository_type` object. Options can be defined in the array passed to the constructor. The Wikipedia repository is an example. ### Example using `get_instance_option_names()` ```php public static function get_instance_option_names() { // Returns an array of option names for instance configuration. // For example, if 'rootpath' is an instance-specific option. return ['rootpath']; } ``` ``` -------------------------------- ### Moodle Developer Apache Configuration (Directory) Source: https://moodledev.io/docs/5.2/guides/restructure This Apache configuration snippet sets up directory-specific settings for Moodle installations, including options for symbolic links and access control. It is intended for developer setups supporting multiple Moodle versions. ```apache ####################### # UPDATE ME ####################### # Do not allow directory listing. # Allow following symbolic links. Options -Indexes +FollowSymLinks # Do not allow .htaccess files to override settings. AllowOverride None # Allow access to all users. Require all granted # Repeat the same for any public folder too. ####################### ``` -------------------------------- ### MoodleDev State Event Triggering Examples Source: https://moodledev.io/docs/5.2/guides/javascript/reactive Illustrates how different state mutations trigger specific state events. It shows the sequence of events from `transaction:start` to `transaction:end`, including specific element updates and generic state updates. ```javascript // Mutation: state.activity.name = ‘New name’; // Triggers: transaction:start activity.name:updated activity:updated state:updated transaction:end ``` ```javascript // Mutation: students[2].attempts = 2; // Triggers: transaction:start students.attempts:updated students[2].attempts:updated students[2]:updated students:updated state:updated transaction:end ``` ```javascript // Mutation: students[2].attempts = 2; delete students[1]; // Triggers: transaction:start students.attempts:updated students[2].attempts:updated students[2]:updated students:updated state:updated students[1]:deleted students:deleted state:updated transaction:end ``` -------------------------------- ### Create a Basic Moodle JavaScript Module Source: https://moodledev.io/docs/5.2/guides/javascript Demonstrates the standard practice of exporting an 'init' function as the entry point for a Moodle JavaScript module. ```javascript export const init = () => { window.console.log('Hello, world!'); }; ``` -------------------------------- ### Setup Toggle for In-place Editable Element (PHP) Source: https://moodledev.io/docs/5.2/apis/subsystems/output/inplace This code example shows how to configure an in-place editable element to use a toggle switch. It initializes the inplace_editable class and sets the toggle type with an array of possible values (e.g., 0 and 1). ```php $tmpl = new \core\output\inplace_editable( 'core_tag', 'tagflag', $tag->id, $editable, $displayvalue, $value, $hint, ); $tmpl->set_type_toggle([0, 1]); ``` -------------------------------- ### Marking an Entire Section as Advanced (PHP) Source: https://moodledev.io/docs/5.2/apis/subsystems/form/advanced/advanced-elements This example illustrates how to mark an entire section of a Moodle form as advanced by specifying the name of the header element that starts the section. All form elements following this header, until the next header, will be treated as advanced and hidden by default. ```php $mform->addElement("header", "miscellaneoussettingshdr", get_string('miscellaneoussettings', 'form')); $mform->setAdvanced('miscellaneoussettingshdr'); ``` -------------------------------- ### Get Assignment Settings - PHP Source: https://moodledev.io/docs/5.2/apis/plugintypes/assign/feedback The get_settings function is used to build the settings page for an assignment, allowing plugins to add their specific settings to the form. Settings should be prefixed with the plugin name to avoid conflicts. This function is typically called during the assignment setup process. ```PHP public function get_settings(MoodleQuickForm $mform) { $mform->addElement( 'assignfeedback_file_fileextensions', get_string('allowedfileextensions', 'assignfeedback_file') ); $mform->setType('assignfeedback_file_fileextensions', PARAM_FILE); } ``` -------------------------------- ### Initialize a Dropzone Component Source: https://moodledev.io/docs/5.2/guides/javascript Demonstrates creating a file dropzone using core/dropzone. It includes setting accepted file types, defining a callback for file handling, and initializing the UI component. ```javascript import Dropzone from 'core/dropzone'; const dropZoneContainer = document.querySelector('#dropZoneId'); const dropZone = new Dropzone( dropZoneContainer, 'image/*', function(files) { window.console.log(files); } ); dropZone.setLabel('Drop images here'); dropZone.init(); ``` -------------------------------- ### Example: Set Multiple Preferences - PHP Source: https://moodledev.io/docs/5.2/apis/core/preference Illustrates using 'set_user_preferences' to add or update multiple preferences from an associative array, and then retrieving all preferences to show the changes. ```PHP $preferences = [ 'foo_displaynum' => '100', 'foo_nameformat' => 'short', ]; set_user_preferences($preferences); // returns [ // foo_nameformat => "short", // foo_showavatars => "no", // foo_displaynum => "100", // ]; get_user_preferences(); ``` -------------------------------- ### Define Post-Installation Hook (PHP) Source: https://moodledev.io/docs/5.2/apis/commonfiles The db/install.php file defines a post-installation hook that is executed immediately after the plugin's database schema is created. This file is only used during the initial installation of the plugin and not during upgrades. -------------------------------- ### Initialize Moodle AMD Module with Parameters Source: https://moodledev.io/docs/5.2/guides/javascript/modules Shows how to pass arguments from PHP to a JavaScript module's init function and how to consume those parameters in the module. ```php $PAGE->requires->js_call_amd('plugintype_pluginname/somefile', 'init', [ $first, $last, ]); ``` ```javascript export const init = (first, last) { window.console.log(`The first name was '${first}' and the last name was '${last}'`); }; ``` -------------------------------- ### Cache Operations (Set, Get, Delete) Source: https://moodledev.io/docs/5.2/apis/subsystems/muc Demonstrates basic cache operations: setting a value, getting a value, and deleting a value. ```APIDOC ## Cache Operations (Set, Get, Delete) ### Description Performs basic operations on a cache object: setting a key-value pair, retrieving a value by key, and deleting a key-value pair. ### Method N/A (Object Methods) ### Endpoint N/A (Object Methods) ### Parameters #### Request Body (for set) - **key** (string|int) - Required - The cache key. - **value** (mixed) - Required - The data to store (must be serializable). #### Request Body (for get) - **key** (string|int) - Required - The cache key to retrieve. #### Request Body (for delete) - **key** (string|int) - Required - The cache key to delete. ### Request Example ```php // Set a value $result = $cache->set('key', 'value'); // Get a value $data = $cache->get('key'); // Delete a value $result = $cache->delete('key'); ``` ### Response #### Success Response (200) - **set result** (bool) - True if successful, false otherwise. - **get result** (mixed|bool) - The cached data or false if not found. - **delete result** (bool) - True if successful, false otherwise. #### Response Example ```php // For set/delete: true or false // For get: 'value' or false ``` ``` -------------------------------- ### Enrolment Plugin Welcome Email Configuration and Sending (PHP) Source: https://moodledev.io/docs/5.2/apis/plugintypes/enrol Example of an enrolment plugin class demonstrating how to add a 'send welcome message' option to the instance form and how to conditionally send a welcome email after a user is enrolled. ```php class enrol_pluginname_plugin extends enrol_plugin { // () public function edit_instance_form($instance, MoodleQuickForm $mform, $context) { $mform->addElement( 'select', 'customint4', get_string('sendcoursewelcomemessage', 'enrol_pluginname'), enrol_send_welcome_email_options() ); } /** * Enrol a user using a given enrolment instance. * * @param stdClass $instance the plugin instance * @param int $userid the user id * @param int $roleid the role id * @param int $timestart enrolment start timestamp * @param int $timeend enrolment end timestamp * @param int $status default to ENROL_USER_ACTIVE for new enrolments * @param bool $recovergrades restore grade history */ public function enrol_user( stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null ) { parent::enrol_user( $instance, $userid, $roleid, $timestart, $timeend, $status, $recovergrades ); // Send welcome message. if ($instance->customint4 != ENROL_DO_NOT_SEND_EMAIL) { $this->email_welcome_message($instance, core_user::get_user($userid)); } } } ``` -------------------------------- ### Component Initialization Source: https://moodledev.io/docs/5.2/guides/javascript/reactive Methods for instantiating reactive components via AMD modules and PHP integration. ```APIDOC ## POST /component/init ### Description Instantiates a new component by binding it to a DOM element and a reactive instance. ### Method POST ### Parameters #### Request Body - **domElementId** (string) - Required - The ID of the DOM element to bind the component to. - **reactiveInstance** (object) - Optional - The reactive instance to manage the component state. ### Request Example { "domElementId": "my-component-id", "reactiveInstance": "reactiveInstance" } ### Response #### Success Response (200) - **instance** (object) - The initialized component instance. ``` -------------------------------- ### Fetching Moodle Context Instances Source: https://moodledev.io/docs/5.2/apis/subsystems/access Provides examples of how to fetch Moodle context instances using different methods, including by object ID for system, user, course category, course, module, and block contexts, as well as fetching by context ID. ```php $systemcontext = context_system::instance(); $usercontext = context_user::instance($user->id); $categorycontext = context_coursecat::instance($category->id); $coursecontext = context_course::instance($course->id); $contextmodule = context_module::instance($cm->id); $contextblock = context_block::instance($this->instance->id); $context = context::instance_by_id($contextid); ``` -------------------------------- ### Custom Inplace Editable Class Example Source: https://moodledev.io/docs/5.2/apis/subsystems/output/inplace Example of creating a custom class that extends `core\output\inplace_editable` for more complex or reusable inplace editing scenarios. ```APIDOC ## Custom Inplace Editable Class ### Description This example demonstrates how to create a custom class, `inplace_edit_text`, that extends Moodle's `core\output\inplace_editable`. This allows for encapsulated logic for specific types of inplace editing, including a static `update` method for handling data persistence. ### Method Class Definition (PHP) ### Endpoint N/A ### Parameters - **$record** (object) - The database record to initialize the element with. - **$itemid** (int) - The ID of the item to update. - **$newvalue** (mixed) - The new value to save. ### Code Example ```php class inplace_edit_text extends \core\output\inplace_editable { /** * Constructor. * * @param object $record */ public function __construct($record) { parent::__construct( component: 'tool_mytest', // The item type as managed your plugin. itemtype: 'mytesttext', // An ID that relates to this instance of this item type. itemid: $record->id, // Whether this user can makes changes. // Perhaps based upon a capability check. editable: has_capability( 'capname', // Replace with actual capability \context_system::instance(), ), // The display value of this item. displayvalue: format_string($record->name), // The machine-readable value. value: $record->name, // Hints and labels. edithint: get_string('edithint', 'tool_mytest'), editlabel: get_string('editlabel', 'tool_mytest'), ); // Example of setting additional properties, like a select type // $this->set_type_select($answeroptionstemp); } /** * Updates the value in database and returns itself. * * Called from inplace_editable callback * * @param int $itemid * @param mixed $newvalue * @return \self */ public static function update($itemid, $newvalue) { // Clean the new value. $newvalue = clean_param($newvalue, PARAM_INT); // Adjust PARAM type as needed // {{ Do some mighty things here}} // Example: Fetch record and update global $DB; $record = $DB->get_record('xxx', ['id' => 'xxx']); // Replace 'xxx' with actual table and field // $DB->update_record('your_table', ['id' => $itemid, 'your_field' => $newvalue]); // Fetch the updated record to return $updated_record = $DB->get_record('xxx', ['id' => $itemid]); // Replace 'xxx' // Finally return itself. return new self($updated_record); } } ``` ``` -------------------------------- ### Callback Function Example Source: https://moodledev.io/docs/5.2/apis/subsystems/output/inplace Example of a PHP callback function within a plugin that handles the inplace_editable request, including validation and database updates. ```APIDOC ## Callback Function for Inplace Editing ### Description This PHP function demonstrates how to handle an `inplace_editable` request within a Moodle plugin. It validates the item type, checks user capabilities, cleans the input, updates the database, and returns a new `inplace_editable` object. ### Method Callback Function (within plugin) ### Endpoint N/A (Handled by Moodle's core callback system) ### Parameters - **$itemtype** (string) - The type of item being edited. - **$itemid** (int) - The ID of the item being edited. - **$newvalue** (string) - The new value submitted by the user. ### Code Example ```php function tool_mytest_inplace_editable($itemtype, $itemid, $newvalue) { global $DB; if ($itemtype === 'mytestname') { $record = $DB->get_record('tool_mytest_mytable', ['id' => $itemid], '*', MUST_EXIST); // Must call validate_context for either system, or course or course module context. // This will both check access and set current context. \external_api::validate_context(context_system::instance()); // Check permission of the user to update this item. require_capability('tool/mytest:update', context_system::instance()); // Clean input and update the record. $newvalue = clean_param($newvalue, PARAM_NOTAGS); $DB->update_record('tool_mytest_mytable', ['id' => $itemid, 'name' => $newvalue]); // Prepare the element for the output: $record->name = $newvalue; return new \core\output\inplace_editable( 'tool_mytest', 'mytestname', $record->id, true, format_string($record->name), $record->name, get_string('editmytestnamefield', 'tool_mytest'), get_string('newvaluestring', 'tool_mytest', format_string($record->name)) ); } } ``` ``` -------------------------------- ### Initialize and Enable a Moodle Editor Source: https://moodledev.io/docs/5.2/apis/subsystems/editor Demonstrates how to retrieve the preferred editor instance and attach it to an existing HTML textarea element using its ID. ```php $editor = editors_get_preferred_editor(FORMAT_HTML); $editor->use_editor('mytextareaid'); ``` -------------------------------- ### Import Map Example Source: https://moodledev.io/docs/5.2/guides/javascript/react/importmap An example of a JSON import map embedded in a page as a script tag, which instructs the browser on how to resolve bare module specifiers. ```APIDOC ## Import Map Example ### Description This script tag demonstrates the structure of an import map, which defines mappings between bare module specifiers (like 'react') and their corresponding URLs. ### Method N/A (Embedded script) ### Endpoint N/A (Embedded script) ### Parameters N/A ### Request Example ```html ``` ### Response N/A (This is a client-side script) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Dependency Injection for Overview Class Source: https://moodledev.io/docs/5.2/apis/plugintypes/mod/courseoverview Demonstrates how to define a custom overview class using dependency injection to access Moodle's database and clock services. ```APIDOC ## Dependency Injection for Overview Class ### Description This section shows how to implement a custom `overview` class that utilizes dependency injection. The constructor accepts essential objects like `cm_info`, `moodle_database`, and `core_clock` to initialize the class and access Moodle's core functionalities. ### Method Not applicable (Class definition) ### Endpoint Not applicable (Class definition) ### Parameters #### Constructor Parameters - **cm** (cm_info) - Required - The activity course module information. - **db** (moodle_database) - Required - The database access object. - **clock** (core_clock) - Required - The clock interface for timestamps. ### Request Example ```php namespace mod_PLUGINNAME\courseformat; use core_course\activityoverviewbase; class overview extends activityoverviewbase { public function __construct( /** @var cm_info $cm the activity course module. */ cm_info $cm, /** @var \moodle_database $db the database acces. */ protected readonly \moodle_database $db, /** @var \core\clock $clock the clock interface */ protected readonly \core\clock $clock ) { parent::__construct($cm); } // The rest of your code goes here. All methods must access the // $this->db property to interact with the database instead of // using the global $DB. // Also, to handle timestamps, use $this->clock->time() instead. } ``` ### Response Not applicable (Class definition) ### Response Example Not applicable (Class definition) ``` -------------------------------- ### MoodleDev State Data Example Source: https://moodledev.io/docs/5.2/guides/javascript/reactive An example of the expected state data structure used in MoodleDev components. This structure includes activity details and a list of students with their attempts. ```json { "activity": {"name": "Something", "id": 42}, "students": [ {"id": 1, "username": "Jane Doe", "attempts": 3}, {"id": 2, "username": "John Doe", "attempts": 1} ] } ``` -------------------------------- ### Cache Bulk Operations (Set Many, Get Many, Delete Many) Source: https://moodledev.io/docs/5.2/apis/subsystems/muc Demonstrates bulk operations for setting, getting, and deleting multiple cache entries simultaneously. ```APIDOC ## Cache Bulk Operations ### Description Performs bulk operations on a cache object: setting multiple key-value pairs, retrieving multiple values by keys, and deleting multiple keys. ### Method N/A (Object Methods) ### Endpoint N/A (Object Methods) ### Parameters #### Request Body (for set_many) - **key-value pairs** (array) - Required - An associative array of keys and their corresponding values. #### Request Body (for get_many) - **keys** (array) - Required - An array of cache keys to retrieve. #### Request Body (for delete_many) - **keys** (array) - Required - An array of cache keys to delete. ### Request Example ```php // Set multiple values $result = $cache->set_many([ 'key1' => 'data1', 'key3' => 'data3' ]); // Get multiple values $result = $cache->get_many(['key1', 'key2', 'key3']); // Delete multiple values $result = $cache->delete_many(['key1', 'key3']); ``` ### Response #### Success Response (200) - **set_many result** (int) - The number of pairs successfully set. - **get_many result** (array) - An associative array of requested keys and their corresponding values (or false if not found). - **delete_many result** (int) - The number of records successfully deleted. #### Response Example ```php // For set_many/delete_many: integer count // For get_many: array('key1' => 'data1', 'key2' => false, 'key3' => 'data3') ``` ```