Merge branch 'MDL-81457-main' of https://github.com/andrewnicols/moodle
[moodle.git] / customfield / classes / handler.php
blob022f44ca7f4adc8ca8548502ccbc47783cb273ea
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.
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/>.
17 /**
18 * The abstract custom fields handler
20 * @package core_customfield
21 * @copyright 2018 David Matamoros <davidmc@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 namespace core_customfield;
27 use backup_nested_element;
28 use core_customfield\output\field_data;
29 use stdClass;
31 defined('MOODLE_INTERNAL') || die;
33 /**
34 * Base class for custom fields handlers
36 * This handler provides callbacks for field configuration form and also allows to add the fields to the instance editing form
38 * Every plugin that wants to use custom fields must define a handler class:
39 * <COMPONENT_OR_PLUGIN>\customfield\<AREA>_handler extends \core_customfield\handler
41 * To initiate a class use an appropriate static method:
42 * - <handlerclass>::create - to create an instance of a known handler
43 * - \core_customfield\handler::get_handler - to create an instance of a handler for given component/area/itemid
45 * Also handler is automatically created when the following methods are called:
46 * - \core_customfield\api::get_field($fieldid)
47 * - \core_customfield\api::get_category($categoryid)
49 * @package core_customfield
50 * @copyright 2018 David Matamoros <davidmc@moodle.com>
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 abstract class handler {
55 /**
56 * The component this handler handles
58 * @var string $component
60 private $component;
62 /**
63 * The area within the component
65 * @var string $area
67 private $area;
69 /**
70 * The id of the item within the area and component
72 * @var int $itemid
74 private $itemid;
76 /**
77 * @var category_controller[]
79 protected $categories = null;
81 /**
82 * Handler constructor.
84 * @param int $itemid
86 final protected function __construct(int $itemid = 0) {
87 if (!preg_match('|^(\w+_[\w_]+)\\\\customfield\\\\([\w_]+)_handler$|', static::class, $matches)) {
88 throw new \coding_exception('Handler class name must have format: <PLUGIN>\\customfield\\<AREA>_handler');
90 $this->component = $matches[1];
91 $this->area = $matches[2];
92 $this->itemid = $itemid;
95 /**
96 * Returns an instance of the handler
98 * Some areas may choose to use singleton/caching here
100 * @param int $itemid
101 * @return handler
103 public static function create(int $itemid = 0): handler {
104 return new static($itemid);
108 * Returns an instance of handler by component/area/itemid
110 * @param string $component component name of full frankenstyle plugin name
111 * @param string $area name of the area (each component/plugin may define handlers for multiple areas)
112 * @param int $itemid item id if the area uses them (usually not used)
113 * @return handler
115 public static function get_handler(string $component, string $area, int $itemid = 0): handler {
116 $classname = $component . '\\customfield\\' . $area . '_handler';
117 if (class_exists($classname) && is_subclass_of($classname, self::class)) {
118 return $classname::create($itemid);
120 $a = ['component' => s($component), 'area' => s($area)];
121 throw new \moodle_exception('unknownhandler', 'core_customfield', '', $a);
125 * Get component
127 * @return string
129 public function get_component(): string {
130 return $this->component;
134 * Get area
136 * @return string
138 public function get_area(): string {
139 return $this->area;
143 * Context that should be used for new categories created by this handler
145 * @return \context
147 abstract public function get_configuration_context(): \context;
150 * URL for configuration of the fields on this handler.
152 * @return \moodle_url
154 abstract public function get_configuration_url(): \moodle_url;
157 * Context that should be used for data stored for the given record
159 * @param int $instanceid id of the instance or 0 if the instance is being created
160 * @return \context
162 abstract public function get_instance_context(int $instanceid = 0): \context;
165 * Get itemid
167 * @return int|null
169 public function get_itemid(): int {
170 return $this->itemid;
174 * Uses categories
176 * @return bool
178 public function uses_categories(): bool {
179 return true;
183 * Generates a name for the new category
185 * @param int $suffix
186 * @return string
188 protected function generate_category_name($suffix = 0): string {
189 if ($suffix) {
190 return get_string('otherfieldsn', 'core_customfield', $suffix);
191 } else {
192 return get_string('otherfields', 'core_customfield');
197 * Creates a new category and inserts it to the database
199 * @param string $name name of the category, null to generate automatically
200 * @return int id of the new category
202 public function create_category(string $name = null): int {
203 global $DB;
204 $params = ['component' => $this->get_component(), 'area' => $this->get_area(), 'itemid' => $this->get_itemid()];
206 if (empty($name)) {
207 for ($suffix = 0; $suffix < 100; $suffix++) {
208 $name = $this->generate_category_name($suffix);
209 if (!$DB->record_exists(category::TABLE, $params + ['name' => $name])) {
210 break;
215 $category = category_controller::create(0, (object)['name' => $name], $this);
216 api::save_category($category);
217 $this->clear_configuration_cache();
218 return $category->get('id');
222 * Validate that the given category belongs to this handler
224 * @param category_controller $category
225 * @return category_controller
226 * @throws \moodle_exception
228 protected function validate_category(category_controller $category): category_controller {
229 $categories = $this->get_categories_with_fields();
230 if (!array_key_exists($category->get('id'), $categories)) {
231 throw new \moodle_exception('categorynotfound', 'core_customfield');
233 return $categories[$category->get('id')];
237 * Validate that the given field belongs to this handler
239 * @param field_controller $field
240 * @return field_controller
241 * @throws \moodle_exception
243 protected function validate_field(field_controller $field): field_controller {
244 if (!array_key_exists($field->get('categoryid'), $this->get_categories_with_fields())) {
245 throw new \moodle_exception('fieldnotfound', 'core_customfield');
247 $category = $this->get_categories_with_fields()[$field->get('categoryid')];
248 if (!array_key_exists($field->get('id'), $category->get_fields())) {
249 throw new \moodle_exception('fieldnotfound', 'core_customfield');
251 return $category->get_fields()[$field->get('id')];
255 * Change name for a field category
257 * @param category_controller $category
258 * @param string $name
260 public function rename_category(category_controller $category, string $name) {
261 $this->validate_category($category);
262 $category->set('name', $name);
263 api::save_category($category);
264 $this->clear_configuration_cache();
268 * Change sort order of the categories
270 * @param category_controller $category category that needs to be moved
271 * @param int $beforeid id of the category this category needs to be moved before, 0 to move to the end
273 public function move_category(category_controller $category, int $beforeid = 0) {
274 $category = $this->validate_category($category);
275 api::move_category($category, $beforeid);
276 $this->clear_configuration_cache();
280 * Permanently delete category, all fields in it and all associated data
282 * @param category_controller $category
283 * @return bool
285 public function delete_category(category_controller $category): bool {
286 $category = $this->validate_category($category);
287 $result = api::delete_category($category);
288 $this->clear_configuration_cache();
289 return $result;
293 * Deletes all data and all fields and categories defined in this handler
295 public function delete_all() {
296 $categories = $this->get_categories_with_fields();
297 foreach ($categories as $category) {
298 api::delete_category($category);
300 $this->clear_configuration_cache();
304 * Permanently delete a custom field configuration and all associated data
306 * @param field_controller $field
307 * @return bool
309 public function delete_field_configuration(field_controller $field): bool {
310 $field = $this->validate_field($field);
311 $result = api::delete_field_configuration($field);
312 $this->clear_configuration_cache();
313 return $result;
317 * Change fields sort order, move field to another category
319 * @param field_controller $field field that needs to be moved
320 * @param int $categoryid category that needs to be moved
321 * @param int $beforeid id of the category this category needs to be moved before, 0 to move to the end
323 public function move_field(field_controller $field, int $categoryid, int $beforeid = 0) {
324 $field = $this->validate_field($field);
325 api::move_field($field, $categoryid, $beforeid);
326 $this->clear_configuration_cache();
330 * The current user can configure custom fields on this component.
332 * @return bool
334 abstract public function can_configure(): bool;
337 * The current user can edit given custom fields on the given instance
339 * Called to filter list of fields displayed on the instance edit form
341 * Capability to edit/create instance is checked separately
343 * @param field_controller $field
344 * @param int $instanceid id of the instance or 0 if the instance is being created
345 * @return bool
347 abstract public function can_edit(field_controller $field, int $instanceid = 0): bool;
350 * The current user can view the value of the custom field for a given custom field and instance
352 * Called to filter list of fields returned by methods get_instance_data(), get_instances_data(),
353 * export_instance_data(), export_instance_data_object()
355 * Access to the instance itself is checked by handler before calling these methods
357 * @param field_controller $field
358 * @param int $instanceid
359 * @return bool
361 abstract public function can_view(field_controller $field, int $instanceid): bool;
364 * Returns the custom field values for an individual instance
366 * The caller must check access to the instance itself before invoking this method
368 * The result is an array of data_controller objects
370 * @param int $instanceid
371 * @param bool $returnall return data for all fields (by default only visible fields)
372 * @return data_controller[] array of data_controller objects indexed by fieldid. All fields are present,
373 * some data_controller objects may have 'id', some not
374 * In the last case data_controller::get_value() and export_value() functions will return default values.
376 public function get_instance_data(int $instanceid, bool $returnall = false): array {
377 $fields = $returnall ? $this->get_fields() : $this->get_visible_fields($instanceid);
378 return api::get_instance_fields_data($fields, $instanceid);
382 * Returns the custom fields values for multiple instances
384 * The caller must check access to the instance itself before invoking this method
386 * The result is an array of data_controller objects
388 * @param int[] $instanceids
389 * @param bool $returnall return data for all fields (by default only visible fields)
390 * @return data_controller[][] 2-dimension array, first index is instanceid, second index is fieldid.
391 * All instanceids and all fieldids are present, some data_controller objects may have 'id', some not.
392 * In the last case data_controller::get_value() and export_value() functions will return default values.
394 public function get_instances_data(array $instanceids, bool $returnall = false): array {
395 $result = api::get_instances_fields_data($this->get_fields(), $instanceids);
397 if (!$returnall) {
398 // Filter only by visible fields (list of visible fields may be different for each instance).
399 $handler = $this;
400 foreach ($instanceids as $instanceid) {
401 $result[$instanceid] = array_filter($result[$instanceid], function(data_controller $d) use ($handler) {
402 return $handler->can_view($d->get_field(), $d->get('instanceid'));
406 return $result;
410 * Returns the custom field values for an individual instance ready to be displayed
412 * The caller must check access to the instance itself before invoking this method
414 * The result is an array of \core_customfield\output\field_data objects
416 * @param int $instanceid
417 * @param bool $returnall
418 * @return \core_customfield\output\field_data[]
420 public function export_instance_data(int $instanceid, bool $returnall = false): array {
421 return array_map(function($d) {
422 return new field_data($d);
423 }, $this->get_instance_data($instanceid, $returnall));
427 * Returns the custom field values for an individual instance ready to be displayed
429 * The caller must check access to the instance itself before invoking this method
431 * The result is a class where properties are fields short names and the values their export values for this instance
433 * @param int $instanceid
434 * @param bool $returnall
435 * @return stdClass
437 public function export_instance_data_object(int $instanceid, bool $returnall = false): stdClass {
438 $rv = new stdClass();
439 foreach ($this->export_instance_data($instanceid, $returnall) as $d) {
440 $rv->{$d->get_shortname()} = $d->get_value();
442 return $rv;
446 * Display visible custom fields.
447 * This is a sample implementation that can be overridden in each handler.
449 * @param data_controller[] $fieldsdata
450 * @return string
452 public function display_custom_fields_data(array $fieldsdata): string {
453 global $PAGE;
454 $output = $PAGE->get_renderer('core_customfield');
455 $content = '';
456 foreach ($fieldsdata as $data) {
457 $fd = new field_data($data);
458 $content .= $output->render($fd);
461 return $content;
465 * Returns array of categories, each of them contains a list of fields definitions.
467 * @return category_controller[]
469 public function get_categories_with_fields(): array {
470 if ($this->categories === null) {
471 $this->categories = api::get_categories_with_fields($this->get_component(), $this->get_area(), $this->get_itemid());
473 $handler = $this;
474 array_walk($this->categories, function(category_controller $c) use ($handler) {
475 $c->set_handler($handler);
477 return $this->categories;
481 * Clears a list of categories with corresponding fields definitions.
483 protected function clear_configuration_cache() {
484 $this->categories = null;
488 * Checks if current user can backup a given field
490 * Capability to backup the instance does not need to be checked here
492 * @param field_controller $field
493 * @param int $instanceid
494 * @return bool
496 protected function can_backup(field_controller $field, int $instanceid): bool {
497 return $this->can_view($field, $instanceid) || $this->can_edit($field, $instanceid);
501 * Run the custom field backup callback for each controller.
503 * @param int $instanceid The instance ID.
504 * @param \backup_nested_element $customfieldselement The custom field element to be backed up.
506 public function backup_define_structure(int $instanceid, backup_nested_element $customfieldselement): void {
507 $datacontrollers = $this->get_instance_data($instanceid);
509 foreach ($datacontrollers as $controller) {
510 if ($this->can_backup($controller->get_field(), $instanceid)) {
511 $controller->backup_define_structure($customfieldselement);
517 * Run the custom field restore callback for each controller.
519 * @param \restore_structure_step $step The restore step instance.
520 * @param int $newid The new ID for the custom field data after restore.
521 * @param int $oldid The original ID of the custom field data before backup.
523 public function restore_define_structure(\restore_structure_step $step, int $newid, int $oldid): void {
524 $datacontrollers = $this->get_instance_data($newid);
526 foreach ($datacontrollers as $controller) {
527 $controller->restore_define_structure($step, $newid, $oldid);
532 * Get raw data associated with all fields current user can view or edit
534 * @param int $instanceid
535 * @return array
537 public function get_instance_data_for_backup(int $instanceid): array {
538 $finalfields = [];
539 $data = $this->get_instance_data($instanceid, true);
540 foreach ($data as $d) {
541 if ($d->get('id') && $this->can_backup($d->get_field(), $instanceid)) {
542 $finalfields[] = [
543 'id' => $d->get('id'),
544 'shortname' => $d->get_field()->get('shortname'),
545 'type' => $d->get_field()->get('type'),
546 'value' => $d->get_value(),
547 'valueformat' => $d->get('valueformat'),
548 'valuetrust' => $d->get('valuetrust'),
552 return $finalfields;
556 * Form data definition callback.
558 * This method is called from moodleform::definition_after_data and allows to tweak
559 * mform with some data coming directly from the field plugin data controller.
561 * @param \MoodleQuickForm $mform
562 * @param int $instanceid
564 public function instance_form_definition_after_data(\MoodleQuickForm $mform, int $instanceid = 0) {
565 $editablefields = $this->get_editable_fields($instanceid);
566 $fields = api::get_instance_fields_data($editablefields, $instanceid);
568 foreach ($fields as $formfield) {
569 $formfield->instance_form_definition_after_data($mform);
574 * Prepares the custom fields data related to the instance to pass to mform->set_data()
576 * Example:
577 * $instance = $DB->get_record(...);
578 * // .... prepare editor, filemanager, add tags, etc.
579 * $handler->instance_form_before_set_data($instance);
580 * $form->set_data($instance);
582 * @param stdClass $instance the instance that has custom fields, if 'id' attribute is present the custom
583 * fields for this instance will be added, otherwise the default values will be added.
585 public function instance_form_before_set_data(stdClass $instance) {
586 $instanceid = !empty($instance->id) ? $instance->id : 0;
587 $fields = api::get_instance_fields_data($this->get_editable_fields($instanceid), $instanceid);
589 foreach ($fields as $formfield) {
590 $formfield->instance_form_before_set_data($instance);
595 * Saves the given data for custom fields, must be called after the instance is saved and id is present
597 * Example:
598 * if ($data = $form->get_data()) {
599 * // ... save main instance, set $data->id if instance was created.
600 * $handler->instance_form_save($data);
601 * redirect(...);
604 * @param stdClass $instance data received from a form
605 * @param bool $isnewinstance if this is call is made during instance creation
607 public function instance_form_save(stdClass $instance, bool $isnewinstance = false) {
608 if (empty($instance->id)) {
609 throw new \coding_exception('Caller must ensure that id is already set in data before calling this method');
611 if (!preg_grep('/^customfield_/', array_keys((array)$instance))) {
612 // For performance.
613 return;
615 $editablefields = $this->get_editable_fields($isnewinstance ? 0 : $instance->id);
616 $fields = api::get_instance_fields_data($editablefields, $instance->id);
617 foreach ($fields as $data) {
618 if (!$data->get('id')) {
619 $data->set('contextid', $this->get_instance_context($instance->id)->id);
621 $data->instance_form_save($instance);
626 * Validates the given data for custom fields, used in moodleform validation() function
628 * Example:
629 * public function validation($data, $files) {
630 * $errors = [];
631 * // .... check other fields.
632 * $errors = array_merge($errors, $handler->instance_form_validation($data, $files));
633 * return $errors;
636 * @param array $data
637 * @param array $files
638 * @return array validation errors
640 public function instance_form_validation(array $data, array $files) {
641 $instanceid = empty($data['id']) ? 0 : $data['id'];
642 $editablefields = $this->get_editable_fields($instanceid);
643 $fields = api::get_instance_fields_data($editablefields, $instanceid);
644 $errors = [];
645 foreach ($fields as $formfield) {
646 $errors += $formfield->instance_form_validation($data, $files);
648 return $errors;
652 * Adds custom fields to instance editing form
654 * Example:
655 * public function definition() {
656 * // ... normal instance definition, including hidden 'id' field.
657 * $handler->instance_form_definition($this->_form, $instanceid);
658 * $this->add_action_buttons();
661 * @param \MoodleQuickForm $mform
662 * @param int $instanceid id of the instance, can be null when instance is being created
663 * @param string $headerlangidentifier If specified, a lang string will be used for field category headings
664 * @param string $headerlangcomponent
666 public function instance_form_definition(\MoodleQuickForm $mform, int $instanceid = 0,
667 ?string $headerlangidentifier = null, ?string $headerlangcomponent = null) {
669 $editablefields = $this->get_editable_fields($instanceid);
670 $fieldswithdata = api::get_instance_fields_data($editablefields, $instanceid);
671 $lastcategoryid = null;
672 foreach ($fieldswithdata as $data) {
673 $categoryid = $data->get_field()->get_category()->get('id');
674 if ($categoryid != $lastcategoryid) {
675 $categoryname = $data->get_field()->get_category()->get_formatted_name();
677 // Load category header lang string if specified.
678 if (!empty($headerlangidentifier)) {
679 $categoryname = get_string($headerlangidentifier, $headerlangcomponent, $categoryname);
682 $mform->addElement('header', 'category_' . $categoryid, $categoryname);
683 $lastcategoryid = $categoryid;
685 $data->instance_form_definition($mform);
686 $field = $data->get_field()->to_record();
687 if (strlen((string)$field->description)) {
688 // Add field description.
689 $context = $this->get_configuration_context();
690 $value = file_rewrite_pluginfile_urls($field->description, 'pluginfile.php',
691 $context->id, 'core_customfield', 'description', $field->id);
692 $value = format_text($value, $field->descriptionformat, ['context' => $context]);
693 $mform->addElement('static', 'customfield_' . $field->shortname . '_static', '', $value);
699 * Get field types array
701 * @return array
703 public function get_available_field_types(): array {
704 return api::get_available_field_types();
708 * Options for processing embedded files in the field description.
710 * Handlers may want to extend it to disable files support and/or specify 'noclean'=>true
711 * Context is not necessary here
713 * @return array
715 public function get_description_text_options(): array {
716 global $CFG;
717 require_once($CFG->libdir.'/formslib.php');
718 return [
719 'maxfiles' => EDITOR_UNLIMITED_FILES,
720 'maxbytes' => $CFG->maxbytes,
721 'context' => $this->get_configuration_context()
726 * Save the field configuration with the data from the form
728 * @param field_controller $field
729 * @param stdClass $data data from the form
731 public function save_field_configuration(field_controller $field, stdClass $data) {
732 if ($field->get('id')) {
733 $field = $this->validate_field($field);
734 } else {
735 $this->validate_category($field->get_category());
737 api::save_field_configuration($field, $data);
738 $this->clear_configuration_cache();
742 * Creates or updates custom field data for a instanceid from backup data.
743 * The handlers have to override it if they support backup.
745 * @param \restore_task $task
746 * @param array $data
748 * @return int|void Implementations should conditionally return the ID of the created or updated record.
750 public function restore_instance_data_from_backup(\restore_task $task, array $data) {
751 throw new \coding_exception('Must be implemented in the handler');
755 * Returns list of fields defined for this instance as an array (not groupped by categories)
757 * Fields are sorted in the same order they would appear on the instance edit form
759 * Note that this function returns all fields in all categories regardless of whether the current user
760 * can view or edit data associated with them
762 * @return field_controller[]
764 public function get_fields(): array {
765 $categories = $this->get_categories_with_fields();
766 $fields = [];
767 foreach ($categories as $category) {
768 foreach ($category->get_fields() as $field) {
769 $fields[$field->get('id')] = $field;
772 return $fields;
776 * Get visible fields
778 * @param int $instanceid
779 * @return field_controller[]
781 protected function get_visible_fields(int $instanceid): array {
782 $handler = $this;
783 return array_filter($this->get_fields(),
784 function($field) use($handler, $instanceid) {
785 return $handler->can_view($field, $instanceid);
791 * Get editable fields
793 * @param int $instanceid
794 * @return field_controller[]
796 public function get_editable_fields(int $instanceid): array {
797 $handler = $this;
798 return array_filter($this->get_fields(),
799 function($field) use($handler, $instanceid) {
800 return $handler->can_edit($field, $instanceid);
806 * Allows to add custom controls to the field configuration form that will be saved in configdata
808 * @param \MoodleQuickForm $mform
810 public function config_form_definition(\MoodleQuickForm $mform) {
814 * Deletes all data related to all fields of an instance.
816 * @param int $instanceid
818 public function delete_instance(int $instanceid) {
819 $fielddata = api::get_instance_fields_data($this->get_fields(), $instanceid, false);
820 foreach ($fielddata as $data) {
821 $data->delete();