Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 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
namespace core_question\external;
18
 
19
use core\exception\coding_exception;
20
use core_external\external_api;
21
use core_external\external_function_parameters;
22
use core_external\external_single_structure;
23
use core_external\external_multiple_structure;
24
use core_external\external_value;
25
use core_question\local\bank\question_bank_helper;
26
use core\context;
27
 
28
/**
29
 * Return a filtered of the user's shared question banks
30
 *
31
 * For use with core_question/question_banks_datasource as a source for autocomplete suggestions.
32
 *
33
 * @package   core_question
34
 * @copyright 2025 onwards Catalyst IT EU {@link https://catalyst-eu.net}
35
 * @author    Mark Johnson <mark.johnson@catalyst-eu.net>
36
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37
 */
38
class search_shared_banks extends external_api {
39
 
40
    /**
41
     * @var int The maximum number of banks to return.
42
     */
43
    const MAX_RESULTS = 20;
44
 
45
    /**
46
     * Define parameters for external function.
47
     *
48
     * @return external_function_parameters
49
     */
50
    public static function execute_parameters(): external_function_parameters {
51
        return new external_function_parameters(
52
            [
53
                'contextid' => new external_value(PARAM_INT, 'The current context ID for applying text filters to bank names.'),
54
                'search' => new external_value(PARAM_TEXT, 'Search terms by which to filter the shared banks.', default: ''),
55
                'requiredcapabilities' => new external_multiple_structure(
56
                    new external_value(PARAM_TEXT, 'Capability'),
57
                    'Array of abbreviated "moodle/question:" capabilities that the user must have at least one of in the context ' .
58
                        'of each matching question bank. Valid options are "add", "managecategory", "flag", "config", "edit", ' .
59
                        '"view", "use", "move" or "tag". For "edit", "view", "use", "move" and "tag", the -all and -mine ' .
60
                        "suffixed versions of the capabilty will both be checked.",
61
                    VALUE_DEFAULT,
62
                    ['use'],
63
                ),
64
            ]
65
        );
66
    }
67
 
68
    /**
69
     * Expand a list of abbreviated capaibilities into an array of full capability strings.
70
     *
71
     * Each abbreviation must match a capability with the 'moodle/question:' prefix. Capabilities that have an "all" and "mine"
72
     * variant will have both variants included in the returned array.
73
     *
74
     * These abbreviations are copied from {@see question_has_capability_on()}
75
     *
76
     * @param array $abbreviations Abbreviated capabilities. Must match capabilities with the 'moodle/question:' prefix.
77
     * @return array The expanded capabilities
78
     */
79
    protected static function expand_capabilities(array $abbreviations): array {
80
        $capabilitieswithallandmine = ['edit', 'view', 'use', 'move', 'tag'];
81
        $prefix = 'moodle/question:';
82
        $suffixes = ['all', 'mine'];
83
        $capabilities = [];
84
        foreach ($abbreviations as $abbreviation) {
85
            if (in_array($abbreviation, $capabilitieswithallandmine)) {
86
                foreach ($suffixes as $suffix) {
87
                    $capability = $prefix . $abbreviation . $suffix;
88
                    if (is_null(get_capability_info($capability))) {
89
                        throw new coding_exception("Capability {$capability} does not exist.");
90
                    }
91
                    $capabilities[] = $capability;
92
                }
93
            } else {
94
                $capability = $prefix . $abbreviation;
95
                if (is_null(get_capability_info($capability))) {
96
                    throw new coding_exception("Capability {$capability} does not exist.");
97
                }
98
                $capabilities[] = $capability;
99
            }
100
        }
101
        return $capabilities;
102
    }
103
 
104
    /**
105
     * Return ID and formatted name of question banks accessible by the user, in courses other than the one $contextid is in.
106
     *
107
     * @param int $contextid Context ID of the current activity
108
     * @param string $search String to filter results by question bank name
109
     * @param array $requiredcapabilities List of abbreviated capabilities to check, {@see self::expand_capabilities()}
110
     * @return array
111
     */
112
    public static function execute(
113
        int $contextid,
114
        string $search = '',
115
        array $requiredcapabilities = ['use'],
116
    ): array {
117
        [
118
            'contextid' => $contextid,
119
            'search' => $search,
120
            'requiredcapabilities' => $requiredcapabilities,
121
        ] = self::validate_parameters(self::execute_parameters(), [
122
            'contextid' => $contextid,
123
            'search' => $search,
124
            'requiredcapabilities' => $requiredcapabilities,
125
        ]);
126
 
127
        $modulecontext = context::instance_by_id($contextid);
128
        self::validate_context($modulecontext);
129
 
130
        $sharedbanks = question_bank_helper::get_activity_instances_with_shareable_questions(
131
            havingcap: self::expand_capabilities($requiredcapabilities),
132
            filtercontext: $modulecontext,
133
            search: $search,
134
            limit: self::MAX_RESULTS + 1, // Return up to 1 extra result, so we know there are more.
135
        );
136
 
137
        $suggestions = array_map(
138
            fn($sharedbank) => [
139
                'value' => $sharedbank->modid,
140
                'label' => $sharedbank->coursenamebankname,
141
            ],
142
            $sharedbanks,
143
        );
144
 
145
        if (count($suggestions) > self::MAX_RESULTS) {
146
            // If there are too many results, replace the last one with a placeholder.
147
            $suggestions[array_key_last($suggestions)] = [
148
                'value' => 0,
149
                'label' => get_string('otherquestionbankstoomany', 'question', self::MAX_RESULTS),
150
            ];
151
        }
152
 
153
        return [
154
            'sharedbanks' => $suggestions,
155
        ];
156
    }
157
 
158
    /**
159
     * Define return values.
160
     *
161
     * @return external_single_structure
162
     */
163
    public static function execute_returns(): external_single_structure {
164
        return new external_single_structure([
165
            'sharedbanks' => new external_multiple_structure(
166
                new external_single_structure([
167
                    'value' => new external_value(PARAM_INT, 'Course Module ID of the shared bank.'),
168
                    'label' => new external_value(PARAM_TEXT, 'Formatted bank name'),
169
                ]),
170
                'List of shared banks',
171
            ),
172
        ]);
173
    }
174
}