public static function create_cohorts($cohorts) {
        global $CFG, $DB;
        require_once("$CFG->dirroot/cohort/lib.php");

        $params = self::validate_parameters(self::create_cohorts_parameters(), array('cohorts' => $cohorts));

        $availablethemes = cohort_get_list_of_themes();

        $transaction = $DB->start_delegated_transaction();

        $syscontext = context_system::instance();
        $cohortids = array();

        foreach ($params['cohorts'] as $cohort) {
            $cohort = (object)$cohort;

            // Category type (context id).
            $categorytype = $cohort->categorytype;
            if (!in_array($categorytype['type'], array('idnumber', 'id', 'system'))) {
                throw new invalid_parameter_exception('category type must be id, idnumber or system:' . $categorytype['type']);
            }
            if ($categorytype['type'] === 'system') {
                $cohort->contextid = $syscontext->id;
            } else if ($catid = $DB->get_field('course_categories', 'id', array($categorytype['type'] => $categorytype['value']))) {
                $catcontext = context_coursecat::instance($catid);
                $cohort->contextid = $catcontext->id;
            } else {
                throw new invalid_parameter_exception('category not exists: category '
                    .$categorytype['type'].' = '.$categorytype['value']);
            }
            // Make sure that the idnumber doesn't already exist.
            if ($DB->record_exists('cohort', array('idnumber' => $cohort->idnumber))) {
                throw new invalid_parameter_exception('record already exists: idnumber='.$cohort->idnumber);
            }
            $context = context::instance_by_id($cohort->contextid, MUST_EXIST);
            if ($context->contextlevel != CONTEXT_COURSECAT and $context->contextlevel != CONTEXT_SYSTEM) {
                throw new invalid_parameter_exception('Invalid context');
            }
            self::validate_context($context);
            require_capability('moodle/cohort:manage', $context);

            // Make sure theme is valid.
            if (isset($cohort->theme)) {
                if (!empty($CFG->allowcohortthemes)) {
                    if (empty($availablethemes[$cohort->theme])) {
                        throw new moodle_exception('errorinvalidparam', 'webservice', '', 'theme');
                    }
                }
            }

            // Validate format.
            $cohort->descriptionformat = external_validate_format($cohort->descriptionformat);
            $cohort->id = cohort_add_cohort($cohort);

            list($cohort->description, $cohort->descriptionformat) =
                external_format_text($cohort->description, $cohort->descriptionformat,
                        $context->id, 'cohort', 'description', $cohort->id);
            $cohortids[] = (array)$cohort;
        }
        $transaction->allow_commit();

        return $cohortids;
    }