2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
20 * @package core_cohort
22 * @copyright MediaTouch 2000 srl
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') ||
die();
28 require_once("$CFG->libdir/externallib.php");
30 class core_cohort_external
extends external_api
{
33 * Returns description of method parameters
35 * @return external_function_parameters
38 public static function create_cohorts_parameters() {
39 return new external_function_parameters(
41 'cohorts' => new external_multiple_structure(
42 new external_single_structure(
44 'categorytype' => new external_single_structure(
46 'type' => new external_value(PARAM_TEXT
, 'the name of the field: id (numeric value
47 of course category id) or idnumber (alphanumeric value of idnumber course category)
48 or system (value ignored)'),
49 'value' => new external_value(PARAM_RAW
, 'the value of the categorytype')
52 'name' => new external_value(PARAM_RAW
, 'cohort name'),
53 'idnumber' => new external_value(PARAM_RAW
, 'cohort idnumber'),
54 'description' => new external_value(PARAM_RAW
, 'cohort description', VALUE_OPTIONAL
),
55 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
56 'visible' => new external_value(PARAM_BOOL
, 'cohort visible', VALUE_OPTIONAL
, true),
65 * Create one or more cohorts
67 * @param array $cohorts An array of cohorts to create.
68 * @return array An array of arrays
71 public static function create_cohorts($cohorts) {
73 require_once("$CFG->dirroot/cohort/lib.php");
75 $params = self
::validate_parameters(self
::create_cohorts_parameters(), array('cohorts' => $cohorts));
77 $transaction = $DB->start_delegated_transaction();
79 $syscontext = context_system
::instance();
82 foreach ($params['cohorts'] as $cohort) {
83 $cohort = (object)$cohort;
85 // Category type (context id).
86 $categorytype = $cohort->categorytype
;
87 if (!in_array($categorytype['type'], array('idnumber', 'id', 'system'))) {
88 throw new invalid_parameter_exception('category type must be id, idnumber or system:' . $categorytype['type']);
90 if ($categorytype['type'] === 'system') {
91 $cohort->contextid
= $syscontext->id
;
92 } else if ($catid = $DB->get_field('course_categories', 'id', array($categorytype['type'] => $categorytype['value']))) {
93 $catcontext = context_coursecat
::instance($catid);
94 $cohort->contextid
= $catcontext->id
;
96 throw new invalid_parameter_exception('category not exists: category '
97 .$categorytype['type'].' = '.$categorytype['value']);
99 // Make sure that the idnumber doesn't already exist.
100 if ($DB->record_exists('cohort', array('idnumber' => $cohort->idnumber
))) {
101 throw new invalid_parameter_exception('record already exists: idnumber='.$cohort->idnumber
);
103 $context = context
::instance_by_id($cohort->contextid
, MUST_EXIST
);
104 if ($context->contextlevel
!= CONTEXT_COURSECAT
and $context->contextlevel
!= CONTEXT_SYSTEM
) {
105 throw new invalid_parameter_exception('Invalid context');
107 self
::validate_context($context);
108 require_capability('moodle/cohort:manage', $context);
111 $cohort->descriptionformat
= external_validate_format($cohort->descriptionformat
);
112 $cohort->id
= cohort_add_cohort($cohort);
114 list($cohort->description
, $cohort->descriptionformat
) =
115 external_format_text($cohort->description
, $cohort->descriptionformat
,
116 $context->id
, 'cohort', 'description', $cohort->id
);
117 $cohortids[] = (array)$cohort;
119 $transaction->allow_commit();
125 * Returns description of method result value
127 * @return external_description
130 public static function create_cohorts_returns() {
131 return new external_multiple_structure(
132 new external_single_structure(
134 'id' => new external_value(PARAM_INT
, 'cohort id'),
135 'name' => new external_value(PARAM_RAW
, 'cohort name'),
136 'idnumber' => new external_value(PARAM_RAW
, 'cohort idnumber'),
137 'description' => new external_value(PARAM_RAW
, 'cohort description'),
138 'descriptionformat' => new external_format_value('description'),
139 'visible' => new external_value(PARAM_BOOL
, 'cohort visible'),
146 * Returns description of method parameters
148 * @return external_function_parameters
151 public static function delete_cohorts_parameters() {
152 return new external_function_parameters(
154 'cohortids' => new external_multiple_structure(new external_value(PARAM_INT
, 'cohort ID')),
162 * @param array $cohortids
166 public static function delete_cohorts($cohortids) {
168 require_once("$CFG->dirroot/cohort/lib.php");
170 $params = self
::validate_parameters(self
::delete_cohorts_parameters(), array('cohortids' => $cohortids));
172 $transaction = $DB->start_delegated_transaction();
174 foreach ($params['cohortids'] as $cohortid) {
176 $cohortid = validate_param($cohortid, PARAM_INT
);
177 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST
);
179 // Now security checks.
180 $context = context
::instance_by_id($cohort->contextid
, MUST_EXIST
);
181 if ($context->contextlevel
!= CONTEXT_COURSECAT
and $context->contextlevel
!= CONTEXT_SYSTEM
) {
182 throw new invalid_parameter_exception('Invalid context');
184 self
::validate_context($context);
185 require_capability('moodle/cohort:manage', $context);
186 cohort_delete_cohort($cohort);
188 $transaction->allow_commit();
194 * Returns description of method result value
199 public static function delete_cohorts_returns() {
204 * Returns description of method parameters
206 * @return external_function_parameters
209 public static function get_cohorts_parameters() {
210 return new external_function_parameters(
212 'cohortids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Cohort ID')
213 , 'List of cohort id. A cohort id is an integer.', VALUE_DEFAULT
, array()),
219 * Get cohorts definition specified by ids
221 * @param array $cohortids array of cohort ids
222 * @return array of cohort objects (id, courseid, name)
225 public static function get_cohorts($cohortids = array()) {
228 $params = self
::validate_parameters(self
::get_cohorts_parameters(), array('cohortids' => $cohortids));
230 if (empty($cohortids)) {
231 $cohorts = $DB->get_records('cohort');
233 $cohorts = $DB->get_records_list('cohort', 'id', $params['cohortids']);
236 $cohortsinfo = array();
237 foreach ($cohorts as $cohort) {
238 // Now security checks.
239 $context = context
::instance_by_id($cohort->contextid
, MUST_EXIST
);
240 if ($context->contextlevel
!= CONTEXT_COURSECAT
and $context->contextlevel
!= CONTEXT_SYSTEM
) {
241 throw new invalid_parameter_exception('Invalid context');
243 self
::validate_context($context);
244 if (!has_any_capability(array('moodle/cohort:manage', 'moodle/cohort:view'), $context)) {
245 throw new required_capability_exception($context, 'moodle/cohort:view', 'nopermissions', '');
248 list($cohort->description
, $cohort->descriptionformat
) =
249 external_format_text($cohort->description
, $cohort->descriptionformat
,
250 $context->id
, 'cohort', 'description', $cohort->id
);
252 $cohortsinfo[] = (array) $cohort;
259 * Returns description of method result value
261 * @return external_description
264 public static function get_cohorts_returns() {
265 return new external_multiple_structure(
266 new external_single_structure(
268 'id' => new external_value(PARAM_INT
, 'ID of the cohort'),
269 'name' => new external_value(PARAM_RAW
, 'cohort name'),
270 'idnumber' => new external_value(PARAM_RAW
, 'cohort idnumber'),
271 'description' => new external_value(PARAM_RAW
, 'cohort description'),
272 'descriptionformat' => new external_format_value('description'),
273 'visible' => new external_value(PARAM_BOOL
, 'cohort visible'),
280 * Returns the description of external function parameters.
282 * @return external_function_parameters
284 public static function search_cohorts_parameters() {
285 $query = new external_value(
289 $includes = new external_value(
291 'What other contexts to fetch the frameworks from. (all, parents, self)',
295 $limitfrom = new external_value(
297 'limitfrom we are fetching the records from',
301 $limitnum = new external_value(
303 'Number of records to fetch',
307 return new external_function_parameters(array(
309 'context' => self
::get_context_parameters(),
310 'includes' => $includes,
311 'limitfrom' => $limitfrom,
312 'limitnum' => $limitnum
319 * @param string $query
320 * @param array $context
321 * @param string $includes
322 * @param int $limitfrom
323 * @param int $limitnum
326 public static function search_cohorts($query, $context, $includes = 'parents', $limitfrom = 0, $limitnum = 25) {
328 require_once($CFG->dirroot
. '/cohort/lib.php');
330 $params = self
::validate_parameters(self
::search_cohorts_parameters(), array(
332 'context' => $context,
333 'includes' => $includes,
334 'limitfrom' => $limitfrom,
335 'limitnum' => $limitnum,
337 $query = $params['query'];
338 $includes = $params['includes'];
339 $context = self
::get_context_from_params($params['context']);
340 $limitfrom = $params['limitfrom'];
341 $limitnum = $params['limitnum'];
343 self
::validate_context($context);
345 $manager = has_capability('moodle/cohort:manage', $context);
347 require_capability('moodle/cohort:view', $context);
350 // TODO Make this more efficient.
351 if ($includes == 'self') {
352 $results = cohort_get_cohorts($context->id
, $limitfrom, $limitnum, $query);
353 $results = $results['cohorts'];
354 } else if ($includes == 'parents') {
355 $results = cohort_get_cohorts($context->id
, $limitfrom, $limitnum, $query);
356 $results = $results['cohorts'];
357 if (!$context instanceof context_system
) {
358 $results = array_merge($results, cohort_get_available_cohorts($context, COHORT_ALL
, $limitfrom, $limitnum, $query));
360 } else if ($includes == 'all') {
361 $results = cohort_get_all_cohorts($limitfrom, $limitnum, $query);
362 $results = $results['cohorts'];
364 throw new coding_exception('Invalid parameter value for \'includes\'.');
368 foreach ($results as $key => $cohort) {
369 $cohortcontext = context
::instance_by_id($cohort->contextid
);
370 if (!isset($cohort->description
)) {
371 $cohort->description
= '';
373 if (!isset($cohort->descriptionformat
)) {
374 $cohort->descriptionformat
= FORMAT_PLAIN
;
377 list($cohort->description
, $cohort->descriptionformat
) =
378 external_format_text($cohort->description
, $cohort->descriptionformat
,
379 $cohortcontext->id
, 'cohort', 'description', $cohort->id
);
381 $cohorts[$key] = $cohort;
384 return array('cohorts' => $cohorts);
388 * Returns description of external function result value.
390 * @return external_description
392 public static function search_cohorts_returns() {
393 return new external_single_structure(array(
394 'cohorts' => new external_multiple_structure(
395 new external_single_structure(array(
396 'id' => new external_value(PARAM_INT
, 'ID of the cohort'),
397 'name' => new external_value(PARAM_RAW
, 'cohort name'),
398 'idnumber' => new external_value(PARAM_RAW
, 'cohort idnumber'),
399 'description' => new external_value(PARAM_RAW
, 'cohort description'),
400 'descriptionformat' => new external_format_value('description'),
401 'visible' => new external_value(PARAM_BOOL
, 'cohort visible'),
410 * Returns description of method parameters
412 * @return external_function_parameters
415 public static function update_cohorts_parameters() {
416 return new external_function_parameters(
418 'cohorts' => new external_multiple_structure(
419 new external_single_structure(
421 'id' => new external_value(PARAM_INT
, 'ID of the cohort'),
422 'categorytype' => new external_single_structure(
424 'type' => new external_value(PARAM_TEXT
, 'the name of the field: id (numeric value
425 of course category id) or idnumber (alphanumeric value of idnumber course category)
426 or system (value ignored)'),
427 'value' => new external_value(PARAM_RAW
, 'the value of the categorytype')
430 'name' => new external_value(PARAM_RAW
, 'cohort name'),
431 'idnumber' => new external_value(PARAM_RAW
, 'cohort idnumber'),
432 'description' => new external_value(PARAM_RAW
, 'cohort description', VALUE_OPTIONAL
),
433 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
434 'visible' => new external_value(PARAM_BOOL
, 'cohort visible', VALUE_OPTIONAL
),
445 * @param array $cohorts
449 public static function update_cohorts($cohorts) {
451 require_once("$CFG->dirroot/cohort/lib.php");
453 $params = self
::validate_parameters(self
::update_cohorts_parameters(), array('cohorts' => $cohorts));
455 $transaction = $DB->start_delegated_transaction();
456 $syscontext = context_system
::instance();
458 foreach ($params['cohorts'] as $cohort) {
459 $cohort = (object) $cohort;
461 if (trim($cohort->name
) == '') {
462 throw new invalid_parameter_exception('Invalid cohort name');
465 $oldcohort = $DB->get_record('cohort', array('id' => $cohort->id
), '*', MUST_EXIST
);
466 $oldcontext = context
::instance_by_id($oldcohort->contextid
, MUST_EXIST
);
467 require_capability('moodle/cohort:manage', $oldcontext);
469 // Category type (context id).
470 $categorytype = $cohort->categorytype
;
471 if (!in_array($categorytype['type'], array('idnumber', 'id', 'system'))) {
472 throw new invalid_parameter_exception('category type must be id, idnumber or system:' . $categorytype['type']);
474 if ($categorytype['type'] === 'system') {
475 $cohort->contextid
= $syscontext->id
;
476 } else if ($catid = $DB->get_field('course_categories', 'id', array($categorytype['type'] => $categorytype['value']))) {
477 $cohort->contextid
= $DB->get_field('context', 'id', array('instanceid' => $catid,
478 'contextlevel' => CONTEXT_COURSECAT
));
480 throw new invalid_parameter_exception('category not exists: category='.$categorytype['value']);
483 if ($cohort->contextid
!= $oldcohort->contextid
) {
484 $context = context
::instance_by_id($cohort->contextid
, MUST_EXIST
);
485 if ($context->contextlevel
!= CONTEXT_COURSECAT
and $context->contextlevel
!= CONTEXT_SYSTEM
) {
486 throw new invalid_parameter_exception('Invalid context');
489 self
::validate_context($context);
490 require_capability('moodle/cohort:manage', $context);
493 if (!empty($cohort->description
)) {
494 $cohort->descriptionformat
= external_validate_format($cohort->descriptionformat
);
497 cohort_update_cohort($cohort);
500 $transaction->allow_commit();
506 * Returns description of method result value
511 public static function update_cohorts_returns() {
516 * Returns description of method parameters
518 * @return external_function_parameters
521 public static function add_cohort_members_parameters() {
522 return new external_function_parameters (
524 'members' => new external_multiple_structure (
525 new external_single_structure (
527 'cohorttype' => new external_single_structure (
529 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the field: id
530 (numeric value of cohortid) or idnumber (alphanumeric value of idnumber) '),
531 'value' => new external_value(PARAM_RAW
, 'The value of the cohort')
534 'usertype' => new external_single_structure (
536 'type' => new external_value(PARAM_ALPHANUMEXT
, 'The name of the field: id
537 (numeric value of id) or username (alphanumeric value of username) '),
538 'value' => new external_value(PARAM_RAW
, 'The value of the cohort')
551 * @param array $members of arrays with keys userid, cohortid
554 public static function add_cohort_members($members) {
556 require_once($CFG->dirroot
."/cohort/lib.php");
558 $params = self
::validate_parameters(self
::add_cohort_members_parameters(), array('members' => $members));
560 $transaction = $DB->start_delegated_transaction();
562 foreach ($params['members'] as $member) {
563 // Cohort parameters.
564 $cohorttype = $member['cohorttype'];
565 $cohortparam = array($cohorttype['type'] => $cohorttype['value']);
567 $usertype = $member['usertype'];
568 $userparam = array($usertype['type'] => $usertype['value']);
571 if ($cohorttype['type'] != 'id' && $cohorttype['type'] != 'idnumber') {
573 $warning['warningcode'] = '1';
574 $warning['message'] = 'invalid parameter: cohortype='.$cohorttype['type'];
575 $warnings[] = $warning;
578 if ($usertype['type'] != 'id' && $usertype['type'] != 'username') {
580 $warning['warningcode'] = '1';
581 $warning['message'] = 'invalid parameter: usertype='.$usertype['type'];
582 $warnings[] = $warning;
585 // Extract parameters.
586 if (!$cohortid = $DB->get_field('cohort', 'id', $cohortparam)) {
588 $warning['warningcode'] = '2';
589 $warning['message'] = 'cohort '.$cohorttype['type'].'='.$cohorttype['value'].' not exists';
590 $warnings[] = $warning;
593 if (!$userid = $DB->get_field('user', 'id', array_merge($userparam, array('deleted' => 0,
594 'mnethostid' => $CFG->mnet_localhost_id
)))) {
596 $warning['warningcode'] = '2';
597 $warning['message'] = 'user '.$usertype['type'].'='.$usertype['value'].' not exists';
598 $warnings[] = $warning;
601 if ($DB->record_exists('cohort_members', array('cohortid' => $cohortid, 'userid' => $userid))) {
603 $warning['warningcode'] = '3';
604 $warning['message'] = 'record already exists: cohort('.$cohorttype['type'].'='.$cohorttype['value'].' '.
605 $usertype['type'].'='.$usertype['value'].')';
606 $warnings[] = $warning;
609 $cohort = $DB->get_record('cohort', array('id'=>$cohortid), '*', MUST_EXIST
);
610 $context = context
::instance_by_id($cohort->contextid
, MUST_EXIST
);
611 if ($context->contextlevel
!= CONTEXT_COURSECAT
and $context->contextlevel
!= CONTEXT_SYSTEM
) {
613 $warning['warningcode'] = '1';
614 $warning['message'] = 'Invalid context: '.$context->contextlevel
;
615 $warnings[] = $warning;
618 self
::validate_context($context);
619 } catch (Exception
$e) {
620 throw new moodle_exception('Error', 'cohort', '', $e->getMessage());
622 if (!has_any_capability(array('moodle/cohort:manage', 'moodle/cohort:assign'), $context)) {
623 throw new required_capability_exception($context, 'moodle/cohort:assign', 'nopermissions', '');
625 cohort_add_member($cohortid, $userid);
627 $transaction->allow_commit();
630 $result['warnings'] = $warnings;
635 * Returns description of method result value
640 public static function add_cohort_members_returns() {
641 return new external_single_structure(
643 'warnings' => new external_warnings()
649 * Returns description of method parameters
651 * @return external_function_parameters
654 public static function delete_cohort_members_parameters() {
655 return new external_function_parameters(
657 'members' => new external_multiple_structure(
658 new external_single_structure(
660 'cohortid' => new external_value(PARAM_INT
, 'cohort record id'),
661 'userid' => new external_value(PARAM_INT
, 'user id'),
670 * Delete cohort members
672 * @param array $members of arrays with keys userid, cohortid
675 public static function delete_cohort_members($members) {
677 require_once("$CFG->dirroot/cohort/lib.php");
679 // Validate parameters.
680 $params = self
::validate_parameters(self
::delete_cohort_members_parameters(), array('members' => $members));
682 $transaction = $DB->start_delegated_transaction();
684 foreach ($params['members'] as $member) {
685 $cohortid = $member['cohortid'];
686 $userid = $member['userid'];
688 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST
);
689 $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id
),
692 // Now security checks.
693 $context = context
::instance_by_id($cohort->contextid
, MUST_EXIST
);
694 if ($context->contextlevel
!= CONTEXT_COURSECAT
and $context->contextlevel
!= CONTEXT_SYSTEM
) {
695 throw new invalid_parameter_exception('Invalid context');
697 self
::validate_context($context);
698 if (!has_any_capability(array('moodle/cohort:manage', 'moodle/cohort:assign'), $context)) {
699 throw new required_capability_exception($context, 'moodle/cohort:assign', 'nopermissions', '');
702 cohort_remove_member($cohort->id
, $user->id
);
704 $transaction->allow_commit();
708 * Returns description of method result value
713 public static function delete_cohort_members_returns() {
718 * Returns description of method parameters
720 * @return external_function_parameters
723 public static function get_cohort_members_parameters() {
724 return new external_function_parameters(
726 'cohortids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Cohort ID')),
732 * Return all members for a cohort
734 * @param array $cohortids array of cohort ids
735 * @return array with cohort id keys containing arrays of user ids
738 public static function get_cohort_members($cohortids) {
740 $params = self
::validate_parameters(self
::get_cohort_members_parameters(), array('cohortids' => $cohortids));
744 foreach ($params['cohortids'] as $cohortid) {
746 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST
);
747 // Now security checks.
748 $context = context
::instance_by_id($cohort->contextid
, MUST_EXIST
);
749 if ($context->contextlevel
!= CONTEXT_COURSECAT
and $context->contextlevel
!= CONTEXT_SYSTEM
) {
750 throw new invalid_parameter_exception('Invalid context');
752 self
::validate_context($context);
753 if (!has_any_capability(array('moodle/cohort:manage', 'moodle/cohort:view'), $context)) {
754 throw new required_capability_exception($context, 'moodle/cohort:view', 'nopermissions', '');
757 $cohortmembers = $DB->get_records_sql("SELECT u.id FROM {user} u, {cohort_members} cm
758 WHERE u.id = cm.userid AND cm.cohortid = ?
759 ORDER BY lastname ASC, firstname ASC", array($cohort->id
));
760 $members[] = array('cohortid' => $cohortid, 'userids' => array_keys($cohortmembers));
766 * Returns description of method result value
768 * @return external_description
771 public static function get_cohort_members_returns() {
772 return new external_multiple_structure(
773 new external_single_structure(
775 'cohortid' => new external_value(PARAM_INT
, 'cohort record id'),
776 'userids' => new external_multiple_structure(new external_value(PARAM_INT
, 'user id')),