Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | 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
 * The abstract custom fields handler
19
 *
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
23
 */
24
 
25
namespace core_customfield;
26
 
27
use backup_nested_element;
28
use core_customfield\output\field_data;
29
use stdClass;
30
 
31
defined('MOODLE_INTERNAL') || die;
32
 
33
/**
34
 * Base class for custom fields handlers
35
 *
36
 * This handler provides callbacks for field configuration form and also allows to add the fields to the instance editing form
37
 *
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
40
 *
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
44
 *
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)
48
 *
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
52
 */
53
abstract class handler {
54
 
55
    /**
56
     * The component this handler handles
57
     *
58
     * @var string $component
59
     */
60
    private $component;
61
 
62
    /**
63
     * The area within the component
64
     *
65
     * @var string $area
66
     */
67
    private $area;
68
 
69
    /**
70
     * The id of the item within the area and component
71
 
72
     * @var int $itemid
73
     */
74
    private $itemid;
75
 
76
    /**
77
     * @var category_controller[]
78
     */
79
    protected $categories = null;
80
 
81
    /**
82
     * Handler constructor.
83
     *
84
     * @param int $itemid
85
     */
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');
89
        }
90
        $this->component = $matches[1];
91
        $this->area = $matches[2];
92
        $this->itemid = $itemid;
93
    }
94
 
95
    /**
96
     * Returns an instance of the handler
97
     *
98
     * Some areas may choose to use singleton/caching here
99
     *
100
     * @param int $itemid
101
     * @return handler
102
     */
103
    public static function create(int $itemid = 0): handler {
104
        return new static($itemid);
105
    }
106
 
107
    /**
108
     * Returns an instance of handler by component/area/itemid
109
     *
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
114
     */
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);
119
        }
120
        $a = ['component' => s($component), 'area' => s($area)];
121
        throw new \moodle_exception('unknownhandler', 'core_customfield', '', $a);
122
    }
123
 
124
    /**
125
     * Get component
126
     *
127
     * @return string
128
     */
129
    public function get_component(): string {
130
        return $this->component;
131
    }
132
 
133
    /**
134
     * Get area
135
     *
136
     * @return string
137
     */
138
    public function get_area(): string {
139
        return $this->area;
140
    }
141
 
142
    /**
143
     * Context that should be used for new categories created by this handler
144
     *
145
     * @return \context
146
     */
147
    abstract public function get_configuration_context(): \context;
148
 
149
    /**
150
     * URL for configuration of the fields on this handler.
151
     *
152
     * @return \moodle_url
153
     */
154
    abstract public function get_configuration_url(): \moodle_url;
155
 
156
    /**
157
     * Context that should be used for data stored for the given record
158
     *
159
     * @param int $instanceid id of the instance or 0 if the instance is being created
160
     * @return \context
161
     */
162
    abstract public function get_instance_context(int $instanceid = 0): \context;
163
 
164
    /**
165
     * Get itemid
166
     *
167
     * @return int|null
168
     */
169
    public function get_itemid(): int {
170
        return $this->itemid;
171
    }
172
 
173
    /**
174
     * Uses categories
175
     *
176
     * @return bool
177
     */
178
    public function uses_categories(): bool {
179
        return true;
180
    }
181
 
182
    /**
183
     * Generates a name for the new category
184
     *
185
     * @param int $suffix
186
     * @return string
187
     */
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');
193
        }
194
    }
195
 
196
    /**
197
     * Creates a new category and inserts it to the database
198
     *
199
     * @param string $name name of the category, null to generate automatically
200
     * @return int id of the new category
201
     */
1441 ariadna 202
    public function create_category(?string $name = null): int {
1 efrain 203
        global $DB;
204
        $params = ['component' => $this->get_component(), 'area' => $this->get_area(), 'itemid' => $this->get_itemid()];
205
 
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;
211
                }
212
            }
213
        }
214
 
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');
219
    }
220
 
221
    /**
222
     * Validate that the given category belongs to this handler
223
     *
224
     * @param category_controller $category
225
     * @return category_controller
226
     * @throws \moodle_exception
227
     */
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');
232
        }
233
        return $categories[$category->get('id')];
234
    }
235
 
236
    /**
237
     * Validate that the given field belongs to this handler
238
     *
239
     * @param field_controller $field
240
     * @return field_controller
241
     * @throws \moodle_exception
242
     */
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');
246
        }
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');
250
        }
251
        return $category->get_fields()[$field->get('id')];
252
    }
253
 
254
    /**
255
     * Change name for a field category
256
     *
257
     * @param category_controller $category
258
     * @param string $name
259
     */
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();
265
    }
266
 
267
    /**
268
     * Change sort order of the categories
269
     *
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
272
     */
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();
277
    }
278
 
279
    /**
280
     * Permanently delete category, all fields in it and all associated data
281
     *
282
     * @param category_controller $category
283
     * @return bool
284
     */
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;
290
    }
291
 
292
    /**
293
     * Deletes all data and all fields and categories defined in this handler
294
     */
295
    public function delete_all() {
296
        $categories = $this->get_categories_with_fields();
297
        foreach ($categories as $category) {
298
            api::delete_category($category);
299
        }
300
        $this->clear_configuration_cache();
301
    }
302
 
303
    /**
304
     * Permanently delete a custom field configuration and all associated data
305
     *
306
     * @param field_controller $field
307
     * @return bool
308
     */
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;
314
    }
315
 
316
    /**
317
     * Change fields sort order, move field to another category
318
     *
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
322
     */
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();
327
    }
328
 
329
    /**
330
     * The current user can configure custom fields on this component.
331
     *
332
     * @return bool
333
     */
334
    abstract public function can_configure(): bool;
335
 
336
    /**
337
     * The current user can edit given custom fields on the given instance
338
     *
339
     * Called to filter list of fields displayed on the instance edit form
340
     *
341
     * Capability to edit/create instance is checked separately
342
     *
343
     * @param field_controller $field
344
     * @param int $instanceid id of the instance or 0 if the instance is being created
345
     * @return bool
346
     */
347
    abstract public function can_edit(field_controller $field, int $instanceid = 0): bool;
348
 
349
    /**
350
     * The current user can view the value of the custom field for a given custom field and instance
351
     *
352
     * Called to filter list of fields returned by methods get_instance_data(), get_instances_data(),
353
     * export_instance_data(), export_instance_data_object()
354
     *
355
     * Access to the instance itself is checked by handler before calling these methods
356
     *
357
     * @param field_controller $field
358
     * @param int $instanceid
359
     * @return bool
360
     */
361
    abstract public function can_view(field_controller $field, int $instanceid): bool;
362
 
363
    /**
364
     * Returns the custom field values for an individual instance
365
     *
366
     * The caller must check access to the instance itself before invoking this method
367
     *
368
     * The result is an array of data_controller objects
369
     *
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.
375
     */
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);
379
    }
380
 
381
    /**
382
     * Returns the custom fields values for multiple instances
383
     *
384
     * The caller must check access to the instance itself before invoking this method
385
     *
386
     * The result is an array of data_controller objects
387
     *
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.
393
     */
394
    public function get_instances_data(array $instanceids, bool $returnall = false): array {
395
        $result = api::get_instances_fields_data($this->get_fields(), $instanceids);
396
 
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'));
403
                });
404
            }
405
        }
406
        return $result;
407
    }
408
 
409
    /**
410
     * Returns the custom field values for an individual instance ready to be displayed
411
     *
412
     * The caller must check access to the instance itself before invoking this method
413
     *
414
     * The result is an array of \core_customfield\output\field_data objects
415
     *
416
     * @param int $instanceid
417
     * @param bool $returnall
418
     * @return \core_customfield\output\field_data[]
419
     */
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));
424
    }
425
 
426
    /**
427
     * Returns the custom field values for an individual instance ready to be displayed
428
     *
429
     * The caller must check access to the instance itself before invoking this method
430
     *
431
     * The result is a class where properties are fields short names and the values their export values for this instance
432
     *
433
     * @param int $instanceid
434
     * @param bool $returnall
435
     * @return stdClass
436
     */
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();
441
        }
442
        return $rv;
443
    }
444
 
445
    /**
446
     * Display visible custom fields.
447
     * This is a sample implementation that can be overridden in each handler.
448
     *
449
     * @param data_controller[] $fieldsdata
450
     * @return string
451
     */
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);
459
        }
460
 
461
        return $content;
462
    }
463
 
464
    /**
465
     * Returns array of categories, each of them contains a list of fields definitions.
466
     *
467
     * @return category_controller[]
468
     */
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());
472
        }
473
        $handler = $this;
474
        array_walk($this->categories, function(category_controller $c) use ($handler) {
475
            $c->set_handler($handler);
476
        });
477
        return $this->categories;
478
    }
479
 
480
    /**
481
     * Clears a list of categories with corresponding fields definitions.
482
     */
483
    protected function clear_configuration_cache() {
484
        $this->categories = null;
485
    }
486
 
487
    /**
488
     * Checks if current user can backup a given field
489
     *
490
     * Capability to backup the instance does not need to be checked here
491
     *
492
     * @param field_controller $field
493
     * @param int $instanceid
494
     * @return bool
495
     */
496
    protected function can_backup(field_controller $field, int $instanceid): bool {
497
        return $this->can_view($field, $instanceid) || $this->can_edit($field, $instanceid);
498
    }
499
 
500
    /**
501
     * Run the custom field backup callback for each controller.
502
     *
503
     * @param int $instanceid The instance ID.
504
     * @param \backup_nested_element $customfieldselement The custom field element to be backed up.
505
     */
506
    public function backup_define_structure(int $instanceid, backup_nested_element $customfieldselement): void {
507
        $datacontrollers = $this->get_instance_data($instanceid);
508
 
509
        foreach ($datacontrollers as $controller) {
510
            if ($this->can_backup($controller->get_field(), $instanceid)) {
511
                $controller->backup_define_structure($customfieldselement);
512
            }
513
        }
514
    }
515
 
516
    /**
517
     * Run the custom field restore callback for each controller.
518
     *
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.
522
     */
523
    public function restore_define_structure(\restore_structure_step $step, int $newid, int $oldid): void {
524
 
1441 ariadna 525
        // Retrieve the 'instanceid' of the new custom field data.
526
        $instanceid = (new data($newid))->get('instanceid');
527
 
528
        $datacontrollers = $this->get_instance_data($instanceid);
1 efrain 529
        foreach ($datacontrollers as $controller) {
530
            $controller->restore_define_structure($step, $newid, $oldid);
531
        }
532
    }
533
 
534
    /**
535
     * Get raw data associated with all fields current user can view or edit
536
     *
537
     * @param int $instanceid
538
     * @return array
539
     */
540
    public function get_instance_data_for_backup(int $instanceid): array {
541
        $finalfields = [];
542
        $data = $this->get_instance_data($instanceid, true);
543
        foreach ($data as $d) {
544
            if ($d->get('id') && $this->can_backup($d->get_field(), $instanceid)) {
545
                $finalfields[] = [
546
                    'id' => $d->get('id'),
547
                    'shortname' => $d->get_field()->get('shortname'),
548
                    'type' => $d->get_field()->get('type'),
549
                    'value' => $d->get_value(),
550
                    'valueformat' => $d->get('valueformat'),
551
                    'valuetrust' => $d->get('valuetrust'),
552
                ];
553
            }
554
        }
555
        return $finalfields;
556
    }
557
 
558
    /**
559
     * Form data definition callback.
560
     *
561
     * This method is called from moodleform::definition_after_data and allows to tweak
562
     * mform with some data coming directly from the field plugin data controller.
563
     *
564
     * @param \MoodleQuickForm $mform
565
     * @param int $instanceid
566
     */
567
    public function instance_form_definition_after_data(\MoodleQuickForm $mform, int $instanceid = 0) {
568
        $editablefields = $this->get_editable_fields($instanceid);
569
        $fields = api::get_instance_fields_data($editablefields, $instanceid);
570
 
571
        foreach ($fields as $formfield) {
572
            $formfield->instance_form_definition_after_data($mform);
573
        }
574
    }
575
 
576
    /**
577
     * Prepares the custom fields data related to the instance to pass to mform->set_data()
578
     *
579
     * Example:
580
     *   $instance = $DB->get_record(...);
581
     *   // .... prepare editor, filemanager, add tags, etc.
582
     *   $handler->instance_form_before_set_data($instance);
583
     *   $form->set_data($instance);
584
     *
585
     * @param stdClass $instance the instance that has custom fields, if 'id' attribute is present the custom
586
     *    fields for this instance will be added, otherwise the default values will be added.
587
     */
588
    public function instance_form_before_set_data(stdClass $instance) {
589
        $instanceid = !empty($instance->id) ? $instance->id : 0;
590
        $fields = api::get_instance_fields_data($this->get_editable_fields($instanceid), $instanceid);
591
 
592
        foreach ($fields as $formfield) {
593
            $formfield->instance_form_before_set_data($instance);
594
        }
595
    }
596
 
597
    /**
598
     * Saves the given data for custom fields, must be called after the instance is saved and id is present
599
     *
600
     * Example:
601
     *   if ($data = $form->get_data()) {
602
     *     // ... save main instance, set $data->id if instance was created.
603
     *     $handler->instance_form_save($data);
604
     *     redirect(...);
605
     *   }
606
     *
607
     * @param stdClass $instance data received from a form
608
     * @param bool $isnewinstance if this is call is made during instance creation
609
     */
610
    public function instance_form_save(stdClass $instance, bool $isnewinstance = false) {
611
        if (empty($instance->id)) {
612
            throw new \coding_exception('Caller must ensure that id is already set in data before calling this method');
613
        }
614
        if (!preg_grep('/^customfield_/', array_keys((array)$instance))) {
615
            // For performance.
616
            return;
617
        }
618
        $editablefields = $this->get_editable_fields($isnewinstance ? 0 : $instance->id);
619
        $fields = api::get_instance_fields_data($editablefields, $instance->id);
620
        foreach ($fields as $data) {
621
            if (!$data->get('id')) {
622
                $data->set('contextid', $this->get_instance_context($instance->id)->id);
623
            }
624
            $data->instance_form_save($instance);
625
        }
626
    }
627
 
628
    /**
629
     * Validates the given data for custom fields, used in moodleform validation() function
630
     *
631
     * Example:
632
     *   public function validation($data, $files) {
633
     *     $errors = [];
634
     *     // .... check other fields.
635
     *     $errors = array_merge($errors, $handler->instance_form_validation($data, $files));
636
     *     return $errors;
637
     *   }
638
     *
639
     * @param array $data
640
     * @param array $files
641
     * @return array validation errors
642
     */
643
    public function instance_form_validation(array $data, array $files) {
644
        $instanceid = empty($data['id']) ? 0 : $data['id'];
645
        $editablefields = $this->get_editable_fields($instanceid);
646
        $fields = api::get_instance_fields_data($editablefields, $instanceid);
647
        $errors = [];
648
        foreach ($fields as $formfield) {
649
            $errors += $formfield->instance_form_validation($data, $files);
650
        }
651
        return $errors;
652
    }
653
 
654
    /**
655
     * Adds custom fields to instance editing form
656
     *
657
     * Example:
658
     *   public function definition() {
659
     *     // ... normal instance definition, including hidden 'id' field.
660
     *     $handler->instance_form_definition($this->_form, $instanceid);
661
     *     $this->add_action_buttons();
662
     *   }
663
     *
664
     * @param \MoodleQuickForm $mform
665
     * @param int $instanceid id of the instance, can be null when instance is being created
666
     * @param string $headerlangidentifier If specified, a lang string will be used for field category headings
667
     * @param string $headerlangcomponent
668
     */
669
    public function instance_form_definition(\MoodleQuickForm $mform, int $instanceid = 0,
670
            ?string $headerlangidentifier = null, ?string $headerlangcomponent = null) {
671
 
672
        $editablefields = $this->get_editable_fields($instanceid);
673
        $fieldswithdata = api::get_instance_fields_data($editablefields, $instanceid);
674
        $lastcategoryid = null;
675
        foreach ($fieldswithdata as $data) {
676
            $categoryid = $data->get_field()->get_category()->get('id');
677
            if ($categoryid != $lastcategoryid) {
678
                $categoryname = $data->get_field()->get_category()->get_formatted_name();
679
 
680
                // Load category header lang string if specified.
681
                if (!empty($headerlangidentifier)) {
682
                    $categoryname = get_string($headerlangidentifier, $headerlangcomponent, $categoryname);
683
                }
684
 
685
                $mform->addElement('header', 'category_' . $categoryid, $categoryname);
686
                $lastcategoryid = $categoryid;
687
            }
688
            $data->instance_form_definition($mform);
689
            $field = $data->get_field()->to_record();
690
            if (strlen((string)$field->description)) {
691
                // Add field description.
692
                $context = $this->get_configuration_context();
693
                $value = file_rewrite_pluginfile_urls($field->description, 'pluginfile.php',
694
                    $context->id, 'core_customfield', 'description', $field->id);
695
                $value = format_text($value, $field->descriptionformat, ['context' => $context]);
696
                $mform->addElement('static', 'customfield_' . $field->shortname . '_static', '', $value);
697
            }
698
        }
699
    }
700
 
701
    /**
702
     * Get field types array
703
     *
704
     * @return array
705
     */
706
    public function get_available_field_types(): array {
707
        return api::get_available_field_types();
708
    }
709
 
710
    /**
711
     * Options for processing embedded files in the field description.
712
     *
713
     * Handlers may want to extend it to disable files support and/or specify 'noclean'=>true
714
     * Context is not necessary here
715
     *
716
     * @return array
717
     */
718
    public function get_description_text_options(): array {
719
        global $CFG;
720
        require_once($CFG->libdir.'/formslib.php');
721
        return [
722
            'maxfiles' => EDITOR_UNLIMITED_FILES,
723
            'maxbytes' => $CFG->maxbytes,
724
            'context' => $this->get_configuration_context()
725
        ];
726
    }
727
 
728
    /**
729
     * Save the field configuration with the data from the form
730
     *
731
     * @param field_controller $field
732
     * @param stdClass $data data from the form
733
     */
734
    public function save_field_configuration(field_controller $field, stdClass $data) {
735
        if ($field->get('id')) {
736
            $field = $this->validate_field($field);
737
        } else {
738
            $this->validate_category($field->get_category());
739
        }
740
        api::save_field_configuration($field, $data);
741
        $this->clear_configuration_cache();
742
    }
743
 
744
    /**
745
     * Creates or updates custom field data for a instanceid from backup data.
746
     * The handlers have to override it if they support backup.
747
     *
748
     * @param \restore_task $task
749
     * @param array $data
750
     *
751
     * @return int|void Implementations should conditionally return the ID of the created or updated record.
752
     */
753
    public function restore_instance_data_from_backup(\restore_task $task, array $data) {
754
        throw new \coding_exception('Must be implemented in the handler');
755
    }
756
 
757
    /**
758
     * Returns list of fields defined for this instance as an array (not groupped by categories)
759
     *
760
     * Fields are sorted in the same order they would appear on the instance edit form
761
     *
762
     * Note that this function returns all fields in all categories regardless of whether the current user
763
     * can view or edit data associated with them
764
     *
765
     * @return field_controller[]
766
     */
767
    public function get_fields(): array {
768
        $categories = $this->get_categories_with_fields();
769
        $fields = [];
770
        foreach ($categories as $category) {
771
            foreach ($category->get_fields() as $field) {
772
                $fields[$field->get('id')] = $field;
773
            }
774
        }
775
        return $fields;
776
    }
777
 
778
    /**
779
     * Get visible fields
780
     *
781
     * @param int $instanceid
782
     * @return field_controller[]
783
     */
784
    protected function get_visible_fields(int $instanceid): array {
785
        $handler = $this;
786
        return array_filter($this->get_fields(),
787
            function($field) use($handler, $instanceid) {
788
                return $handler->can_view($field, $instanceid);
789
            }
790
        );
791
    }
792
 
793
    /**
794
     * Get editable fields
795
     *
796
     * @param int $instanceid
797
     * @return field_controller[]
798
     */
799
    public function get_editable_fields(int $instanceid): array {
800
        $handler = $this;
801
        return array_filter($this->get_fields(),
802
            function($field) use($handler, $instanceid) {
803
                return $handler->can_edit($field, $instanceid);
804
            }
805
        );
806
    }
807
 
808
    /**
809
     * Allows to add custom controls to the field configuration form that will be saved in configdata
810
     *
811
     * @param \MoodleQuickForm $mform
812
     */
813
    public function config_form_definition(\MoodleQuickForm $mform) {
814
    }
815
 
816
    /**
817
     * Deletes all data related to all fields of an instance.
818
     *
819
     * @param int $instanceid
820
     */
821
    public function delete_instance(int $instanceid) {
822
        $fielddata = api::get_instance_fields_data($this->get_fields(), $instanceid, false);
823
        foreach ($fielddata as $data) {
824
            $data->delete();
825
        }
826
    }
827
}